{"text":"\/* libscratch - Multipurpose objective C++ library.\r\n Copyright (C) 2012 - 2013 Angelo Geels\r\n\r\n This program is free software: you can redistribute it and\/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see . *\/\r\n\r\n#include \/\/ for printf\r\n#include \/\/ for std::cin.get\r\n\r\n#include \r\n\r\nstatic INDEX _ctTests = 0;\r\nstatic INDEX _ctFailed = 0;\r\n\r\n#define TEST(expr) { \\\r\n BOOL bSuccess = (expr); \\\r\n _ctTests++; \\\r\n ASSERT(bSuccess); \\\r\n printf(\" Test #%d: (%s) \", _ctTests, #expr); \\\r\n if(!bSuccess) { \\\r\n _ctFailed++; \\\r\n printf(\"FAILED!\\n\"); \\\r\n } else { \\\r\n printf(\"OK\\n\"); \\\r\n } \\\r\n}\r\n\r\n\/\/\/ String testing\r\nvoid TestString()\r\n{\r\n printf(\"Testing strings\\n\");\r\n\r\n CString strTest;\r\n strTest += \"Lib\";\r\n strTest += \"Scratch\";\r\n strTest = strTest.ToLower();\r\n TEST(strTest == \"libscratch\");\r\n\r\n strTest += \" is great\";\r\n CStackArray astrParse = strTest.Split(\" \");\r\n TEST(astrParse[2] == \"great\");\r\n TEST(astrParse[2][1] == 'r');\r\n\r\n CString strTest2 = strTest.Replace(\"great\", \"cool\");\r\n TEST(strTest2 == \"libscratch is cool\");\r\n}\r\n\r\n\/\/\/ Stack array testing\r\nvoid TestStackArray()\r\n{\r\n printf(\"Testing stack arrays\\n\");\r\n\r\n CStackArray aiNumbers;\r\n TEST(aiNumbers.Count() == 0);\r\n\r\n aiNumbers.Push() = 5;\r\n aiNumbers.Push() = 10;\r\n aiNumbers.Push() = 15;\r\n TEST(aiNumbers.Count() == 3);\r\n TEST(aiNumbers[0] == 5);\r\n TEST(aiNumbers[1] == 10);\r\n TEST(aiNumbers[2] + aiNumbers[0] == 20);\r\n\r\n TEST(aiNumbers.Pop() == 15);\r\n TEST(aiNumbers.Count() == 2);\r\n}\r\n\r\n\/\/\/ Dictionary testing\r\nvoid TestDictionary()\r\n{\r\n printf(\"Testing dictionary\\n\");\r\n\r\n CDictionary diTest;\r\n TEST(!diTest.HasKey(\"Test\"));\r\n\r\n diTest[\"Test\"] = 100;\r\n diTest[\"Test2\"] = 200;\r\n TEST(diTest.HasKey(\"Test\"));\r\n TEST(diTest[\"Test\"] == 100);\r\n\r\n diTest.RemoveByKey(\"Test\");\r\n TEST(diTest.Count() == 1);\r\n TEST(!diTest.HasKey(\"Test\"));\r\n}\r\n\r\n\/\/\/ Test file stream\r\nvoid TestFilestream()\r\n{\r\n printf(\"Testing file streams\\n\");\r\n\r\n \/\/ this test will create a Test.bin file, containing an integer 5 and the text \"Hello!\"\r\n CFileStream fsTest;\r\n fsTest.Open(\"Test.bin\", \"w\");\r\n fsTest << INDEX(5);\r\n fsTest << \"Hello!\";\r\n fsTest.Close();\r\n\r\n \/\/ as a follow-up, we will read the same file from a seperate file stream\r\n CFileStream fsTestRead;\r\n fsTestRead.Open(\"Test.bin\", \"r\");\r\n\r\n INDEX iTest = 0;\r\n fsTestRead >> iTest;\r\n TEST(iTest == 5);\r\n\r\n CString strTest;\r\n fsTestRead >> strTest;\r\n TEST(strTest == \"Hello!\");\r\n\r\n \/\/ note that closing the stream is optional (destructor does it for us), however we need to have it closed for the unlink below\r\n fsTestRead.Close();\r\n\r\n \/\/ remove the test file from the system\r\n unlink(\"Test.bin\");\r\n}\r\n\r\nint main()\r\n{\r\n \/\/ perform tests\r\n TestString();\r\n TestStackArray();\r\n TestDictionary();\r\n TestFilestream();\r\n\r\n \/\/ report test results\r\n printf(\"\\n\\nResults: %d out of %d went OK.\\n\\n\", _ctTests - _ctFailed, _ctTests);\r\n\r\n \/\/ check if all went OK\r\n if(_ctFailed == 0) {\r\n \/\/ it did! no failures. :)\r\n printf(\"All OK!\\n\");\r\n } else {\r\n \/\/ oops, there's a bug somewhere. please report!\r\n printf(\"Some problems seem to have popped up. Please report a bug.\\n\");\r\n }\r\n\r\n std::cin.get();\r\n return 0;\r\n}\r\nAdded vector tests\/* libscratch - Multipurpose objective C++ library.\r\n Copyright (C) 2012 - 2013 Angelo Geels\r\n\r\n This program is free software: you can redistribute it and\/or modify\r\n it under the terms of the GNU General Public License as published by\r\n the Free Software Foundation, either version 3 of the License, or\r\n (at your option) any later version.\r\n\r\n This program is distributed in the hope that it will be useful,\r\n but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\r\n GNU General Public License for more details.\r\n\r\n You should have received a copy of the GNU General Public License\r\n along with this program. If not, see . *\/\r\n\r\n#include \/\/ for printf\r\n#include \/\/ for std::cin.get\r\n\r\n#include \r\n\r\nstatic INDEX _ctTests = 0;\r\nstatic INDEX _ctFailed = 0;\r\n\r\n#define TEST(expr) { \\\r\n BOOL bSuccess = (expr); \\\r\n _ctTests++; \\\r\n ASSERT(bSuccess); \\\r\n printf(\" Test #%d: (%s) \", _ctTests, #expr); \\\r\n if(!bSuccess) { \\\r\n _ctFailed++; \\\r\n printf(\"FAILED!\\n\"); \\\r\n } else { \\\r\n printf(\"OK\\n\"); \\\r\n } \\\r\n}\r\n\r\n\/\/\/ String testing\r\nvoid TestString()\r\n{\r\n printf(\"Testing strings\\n\");\r\n\r\n CString strTest;\r\n strTest += \"Lib\";\r\n strTest += \"Scratch\";\r\n strTest = strTest.ToLower();\r\n TEST(strTest == \"libscratch\");\r\n\r\n strTest += \" is great\";\r\n CStackArray astrParse = strTest.Split(\" \");\r\n TEST(astrParse[2] == \"great\");\r\n TEST(astrParse[2][1] == 'r');\r\n\r\n CString strTest2 = strTest.Replace(\"great\", \"cool\");\r\n TEST(strTest2 == \"libscratch is cool\");\r\n}\r\n\r\n\/\/\/ Stack array testing\r\nvoid TestStackArray()\r\n{\r\n printf(\"Testing stack arrays\\n\");\r\n\r\n CStackArray aiNumbers;\r\n TEST(aiNumbers.Count() == 0);\r\n\r\n aiNumbers.Push() = 5;\r\n aiNumbers.Push() = 10;\r\n aiNumbers.Push() = 15;\r\n TEST(aiNumbers.Count() == 3);\r\n TEST(aiNumbers[0] == 5);\r\n TEST(aiNumbers[1] == 10);\r\n TEST(aiNumbers[2] + aiNumbers[0] == 20);\r\n\r\n TEST(aiNumbers.Pop() == 15);\r\n TEST(aiNumbers.Count() == 2);\r\n}\r\n\r\n\/\/\/ Dictionary testing\r\nvoid TestDictionary()\r\n{\r\n printf(\"Testing dictionary\\n\");\r\n\r\n CDictionary diTest;\r\n TEST(!diTest.HasKey(\"Test\"));\r\n\r\n diTest[\"Test\"] = 100;\r\n diTest[\"Test2\"] = 200;\r\n TEST(diTest.HasKey(\"Test\"));\r\n TEST(diTest[\"Test\"] == 100);\r\n\r\n diTest.RemoveByKey(\"Test\");\r\n TEST(diTest.Count() == 1);\r\n TEST(!diTest.HasKey(\"Test\"));\r\n}\r\n\r\n\/\/\/ Test file stream\r\nvoid TestFilestream()\r\n{\r\n printf(\"Testing file streams\\n\");\r\n\r\n \/\/ this test will create a Test.bin file, containing an integer 5 and the text \"Hello!\"\r\n CFileStream fsTest;\r\n fsTest.Open(\"Test.bin\", \"w\");\r\n fsTest << INDEX(5);\r\n fsTest << \"Hello!\";\r\n fsTest.Close();\r\n\r\n \/\/ as a follow-up, we will read the same file from a seperate file stream\r\n CFileStream fsTestRead;\r\n fsTestRead.Open(\"Test.bin\", \"r\");\r\n\r\n INDEX iTest = 0;\r\n fsTestRead >> iTest;\r\n TEST(iTest == 5);\r\n\r\n CString strTest;\r\n fsTestRead >> strTest;\r\n TEST(strTest == \"Hello!\");\r\n\r\n \/\/ note that closing the stream is optional (destructor does it for us), however we need to have it closed for the unlink below\r\n fsTestRead.Close();\r\n\r\n \/\/ remove the test file from the system\r\n unlink(\"Test.bin\");\r\n}\r\n\r\n\/\/\/ Vector tests\r\nvoid TestVectors()\r\n{\r\n printf(\"Testing vectors\\n\");\r\n\r\n Vector3f vTest(1, 0, 0);\r\n TEST(vTest.Length() == 1.0f);\r\n\r\n vTest *= 5.0f;\r\n TEST(vTest.Length() == 5.0f);\r\n\r\n vTest.x = 3;\r\n vTest.y = 4;\r\n TEST(vTest.Length() == 5.0f);\r\n\r\n vTest.Normalize();\r\n TEST(vTest.Length() == 1.0f);\r\n}\r\n\r\nint main()\r\n{\r\n \/\/ perform tests\r\n TestString();\r\n TestStackArray();\r\n TestDictionary();\r\n TestFilestream();\r\n TestVectors();\r\n\r\n \/\/ report test results\r\n printf(\"\\n\\nResults: %d out of %d went OK.\\n\\n\", _ctTests - _ctFailed, _ctTests);\r\n\r\n \/\/ check if all went OK\r\n if(_ctFailed == 0) {\r\n \/\/ it did! no failures. :)\r\n printf(\"All OK!\\n\");\r\n } else {\r\n \/\/ oops, there's a bug somewhere. please report!\r\n printf(\"Some problems seem to have popped up. Please report a bug.\\n\");\r\n }\r\n\r\n std::cin.get();\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_BASEFUNCTIONSET_FEM_HH\n#define DUNE_GDT_BASEFUNCTIONSET_FEM_HH\n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace BaseFunctionSet {\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate \nclass FemWrapper;\n\n\ntemplate \nclass FemWrapperTraits\n{\npublic:\n typedef FemWrapper derived_type;\n typedef typename Dune::Fem::BaseFunctionSetInterface::BaseFunctionSetType BackendType;\n typedef EntityImp EntityType;\n};\n\n\ntemplate \nclass FemWrapper\n : public BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>\n{\n typedef FemWrapper\n ThisType;\n typedef BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;\n\npublic:\n typedef FemWrapperTraits\n Traits;\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::EntityType EntityType;\n\n typedef DomainFieldImp DomainFieldType;\n static const unsigned int dimDomain = domainDim;\n typedef Dune::FieldVector DomainType;\n typedef RangeFieldImp RangeFieldType;\n static const unsigned int dimRange = rangeDim;\n static const unsigned int dimRangeCols = 1;\n typedef Dune::FieldVector RangeType;\n typedef Dune::FieldMatrix JacobianRangeType;\n\n template \n FemWrapper(const Dune::Fem::DiscreteFunctionSpaceInterface& femSpace, const EntityType& ent)\n : BaseType(ent)\n , order_(femSpace.order())\n , backend_(new BackendType(femSpace.baseFunctionSet(this->entity())))\n {\n }\n\n FemWrapper(ThisType&& source)\n : BaseType(source.entity())\n , order_(std::move(source.order_))\n , backend_(std::move(source.backend_))\n {\n }\n\n FemWrapper(const ThisType& \/*other*\/) = delete;\n\n ThisType& operator=(const ThisType& \/*other*\/) = delete;\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n virtual size_t size() const DS_OVERRIDE\n {\n return backend_->size();\n }\n\n virtual size_t order() const DS_OVERRIDE\n {\n return order_;\n }\n\n virtual void evaluate(const DomainType& xx, std::vector& ret) const DS_OVERRIDE\n {\n assert(ret.size() >= backend_->size());\n backend_->evaluateAll(xx, ret);\n }\n\n using BaseType::evaluate;\n\n virtual void jacobian(const DomainType& xx, std::vector& ret) const DS_OVERRIDE\n {\n assert(ret.size() >= backend_->size());\n backend_->jacobianAll(xx, this->entity().geometry().jacobianInverseTransposed(xx), ret);\n }\n\n using BaseType::jacobian;\n\nprivate:\n const size_t order_;\n std::unique_ptr backend_;\n}; \/\/ class FemWrapper\n\n\n} \/\/ namespace BaseFunctionSet\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_BASEFUNCTIONSET_FEM_HH\n[basefunctionset.fem] add proper guards\/\/ This file is part of the dune-gdt project:\n\/\/ http:\/\/users.dune-project.org\/projects\/dune-gdt\n\/\/ Copyright holders: Felix Albrecht\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#ifndef DUNE_GDT_BASEFUNCTIONSET_FEM_HH\n#define DUNE_GDT_BASEFUNCTIONSET_FEM_HH\n\n#include \n\n#include \n#include \n#include \n\n#ifdef HAVE_DUNE_FEM\n#include \n#include \n#endif \/\/ HAVE_DUNE_FEM\n\n#include \n\n#include \"interface.hh\"\n\nnamespace Dune {\nnamespace GDT {\nnamespace BaseFunctionSet {\n\n#ifdef HAVE_DUNE_FEM\n\n\n\/\/ forward, to be used in the traits and to allow for specialization\ntemplate \nclass FemWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"Untested for these dimensions!\");\n};\n\n\ntemplate \nclass FemWrapperTraits\n{\npublic:\n typedef FemWrapper derived_type;\n typedef typename Dune::Fem::BaseFunctionSetInterface::BaseFunctionSetType BackendType;\n typedef EntityImp EntityType;\n};\n\n\ntemplate \nclass FemWrapper\n : public BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1>\n{\n typedef FemWrapper\n ThisType;\n typedef BaseFunctionSetInterface,\n DomainFieldImp, domainDim, RangeFieldImp, rangeDim, 1> BaseType;\n\npublic:\n typedef FemWrapperTraits\n Traits;\n typedef typename Traits::BackendType BackendType;\n typedef typename Traits::EntityType EntityType;\n\n typedef DomainFieldImp DomainFieldType;\n static const unsigned int dimDomain = domainDim;\n typedef Dune::FieldVector DomainType;\n typedef RangeFieldImp RangeFieldType;\n static const unsigned int dimRange = rangeDim;\n static const unsigned int dimRangeCols = 1;\n typedef Dune::FieldVector RangeType;\n typedef Dune::FieldMatrix JacobianRangeType;\n\n template \n FemWrapper(const Dune::Fem::DiscreteFunctionSpaceInterface& femSpace, const EntityType& ent)\n : BaseType(ent)\n , order_(femSpace.order())\n , backend_(new BackendType(femSpace.baseFunctionSet(this->entity())))\n {\n }\n\n FemWrapper(ThisType&& source)\n : BaseType(source.entity())\n , order_(std::move(source.order_))\n , backend_(std::move(source.backend_))\n {\n }\n\n FemWrapper(const ThisType& \/*other*\/) = delete;\n\n ThisType& operator=(const ThisType& \/*other*\/) = delete;\n\n const BackendType& backend() const\n {\n return *backend_;\n }\n\n virtual size_t size() const DS_OVERRIDE\n {\n return backend_->size();\n }\n\n virtual size_t order() const DS_OVERRIDE\n {\n return order_;\n }\n\n virtual void evaluate(const DomainType& xx, std::vector& ret) const DS_OVERRIDE\n {\n assert(ret.size() >= backend_->size());\n backend_->evaluateAll(xx, ret);\n }\n\n using BaseType::evaluate;\n\n virtual void jacobian(const DomainType& xx, std::vector& ret) const DS_OVERRIDE\n {\n assert(ret.size() >= backend_->size());\n backend_->jacobianAll(xx, this->entity().geometry().jacobianInverseTransposed(xx), ret);\n }\n\n using BaseType::jacobian;\n\nprivate:\n const size_t order_;\n std::unique_ptr backend_;\n}; \/\/ class FemWrapper\n\n\n#else \/\/ HAVE_DUNE_FEM\n\n\ntemplate \nclass FemWrapper\n{\n static_assert(Dune::AlwaysFalse::value, \"You are missing dune-fem!\");\n};\n\n\n#endif \/\/ HAVE_DUNE_FEM\n\n} \/\/ namespace BaseFunctionSet\n} \/\/ namespace GDT\n} \/\/ namespace Dune\n\n#endif \/\/ DUNE_GDT_BASEFUNCTIONSET_FEM_HH\n<|endoftext|>"} {"text":"#ifndef DUNE_HELPER_TOOLS_GRID_INTERSECTION_HH\n#define DUNE_FEMTOOLS_GRID_INTERSECTION_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n\/\/ dune-common includes\n#include \n#include \n\n\/\/ dune-stuff\n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Grid {\n\n\/**\n \\brief prints some basic information about a Dune::Intersection, namely the number of its corners and the\n coordinates of those corners.\n \\tparam IntersectionType\n Dune::Intersection compatible\n \\param[in] intersection\n Dune::Intersection, whose information should be printed\n \\param[out] stream\n std::ostream, into which the information is printed\n **\/\ntemplate< class IntersectionType >\nvoid printIntersection( const IntersectionType& intersection, std::ostream& stream = std::cout )\n{\n typedef typename IntersectionType::Geometry\n GeometryType;\n\n typedef typename GeometryType::GlobalCoordinate\n GlobalPointType;\n\n const GeometryType& geometry = intersection.geometry();\n\n const int numCorners = geometry.corners();\n\n std::string prefix = \"Dune::Intersection (\" + Dune::Stuff::Common::toString( numCorners ) + \" corner\";\n if( numCorners != 1 )\n {\n prefix += \"s\";\n }\n prefix += \"): \";\n const unsigned int missing = 32 - prefix.size();\n if( missing > 0 )\n {\n for( unsigned int i = 0; i < missing; ++i )\n {\n prefix += \" \";\n }\n }\n const std::string whitespace = Dune::Stuff::Common::whitespaceify( prefix );\n\n stream << prefix << \"[ (\";\n for( int i = 0; i < numCorners; ++i )\n {\n const GlobalPointType corner = geometry.corner( i );\n for( unsigned int j = 0; j < corner.size(); ++ j )\n {\n stream << corner[j];\n if( j < corner.size() - 1 )\n {\n stream << \", \" ;\n }\n }\n stream << \")\";\n if( i < geometry.corners() - 1 )\n {\n stream << \",\" << std::endl << whitespace << \" (\";\n }\n else{\n stream << \" ]\" << std::endl;\n }\n }\n\n} \/\/ end function print\n\ntemplate< class IntersectionType, class FieldType, int size >\nbool intersectionContains( const IntersectionType& \/*intersection*\/, const Dune::FieldVector< FieldType, size >& \/*globalPoint*\/ )\n{\n dune_static_assert( size < 3, \"Dune::FemTools::Grid::Intersection::contains() not implemented for more than 2 dimension!\" );\n return false;\n}\n\ntemplate< class IntersectionType, class FieldType >\nbool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 1 >& globalPoint )\n{\n typedef Dune::FieldVector< FieldType, 1 >\n GlobalPointType;\n\n typedef typename IntersectionType::Geometry\n GeometryType;\n\n const GeometryType& geometry = intersection.geometry();\n\n \/\/ get the only corner\n const GlobalPointType corner = geometry.corner( 0 );\n \/\/ check if the point is the corner\n if( corner == globalPoint )\n {\n return true;\n }\n\n return false;\n} \/\/ end function contains\n\ntemplate< class IntersectionType, class FieldType >\nbool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 2 > & globalPoint )\n{\n typedef Dune::FieldVector< FieldType, 2 >\n GlobalPointType;\n\n typedef typename IntersectionType::Geometry\n GeometryType;\n\n const GeometryType& geometry = intersection.geometry();\n\n \/\/ get the two corners\n const GlobalPointType firstCorner = geometry.corner( 0 );\n const GlobalPointType secondCorner = geometry.corner( 1 );\n\n \/\/ check, that point is on the line between the two points\n const FieldType x1 = ( globalPoint[0] - firstCorner[0] ) \/ ( secondCorner[0] - firstCorner[0] );\n const FieldType x2 = ( globalPoint[1] - firstCorner[1] ) \/ ( secondCorner[1] - firstCorner[1] );\n if( !( x1 > x2 ) && !( x1 < x2 ) && !( x1 < 0.0 ) && !( x1 > 1.0 ) )\n {\n return true;\n }\n\n return false;\n} \/\/ end function contains\n\n} \/\/ end namespace Grid\n} \/\/ end of namespace Stuff\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_FEMTOOLS_GRID_INTERSECTION_HH\n\/** Copyright (c) 2012, Felix Albrecht\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n[grid] fix headerguard snafu#ifndef DUNE_STUFF_GRID_INTERSECTION_HH\n#define DUNE_STUFF_GRID_INTERSECTION_HH\n\n#ifdef HAVE_CMAKE_CONFIG\n #include \"cmake_config.h\"\n#else\n #include \"config.h\"\n#endif \/\/ ifdef HAVE_CMAKE_CONFIG\n\n\/\/ dune-common includes\n#include \n#include \n\n\/\/ dune-stuff\n#include \n\nnamespace Dune {\nnamespace Stuff {\nnamespace Grid {\n\n\/**\n \\brief prints some basic information about a Dune::Intersection, namely the number of its corners and the\n coordinates of those corners.\n \\tparam IntersectionType\n Dune::Intersection compatible\n \\param[in] intersection\n Dune::Intersection, whose information should be printed\n \\param[out] stream\n std::ostream, into which the information is printed\n **\/\ntemplate< class IntersectionType >\nvoid printIntersection( const IntersectionType& intersection, std::ostream& stream = std::cout )\n{\n typedef typename IntersectionType::Geometry\n GeometryType;\n\n typedef typename GeometryType::GlobalCoordinate\n GlobalPointType;\n\n const GeometryType& geometry = intersection.geometry();\n\n const int numCorners = geometry.corners();\n\n std::string prefix = \"Dune::Intersection (\" + Dune::Stuff::Common::toString( numCorners ) + \" corner\";\n if( numCorners != 1 )\n {\n prefix += \"s\";\n }\n prefix += \"): \";\n const unsigned int missing = 32 - prefix.size();\n if( missing > 0 )\n {\n for( unsigned int i = 0; i < missing; ++i )\n {\n prefix += \" \";\n }\n }\n const std::string whitespace = Dune::Stuff::Common::whitespaceify( prefix );\n\n stream << prefix << \"[ (\";\n for( int i = 0; i < numCorners; ++i )\n {\n const GlobalPointType corner = geometry.corner( i );\n for( unsigned int j = 0; j < corner.size(); ++ j )\n {\n stream << corner[j];\n if( j < corner.size() - 1 )\n {\n stream << \", \" ;\n }\n }\n stream << \")\";\n if( i < geometry.corners() - 1 )\n {\n stream << \",\" << std::endl << whitespace << \" (\";\n }\n else{\n stream << \" ]\" << std::endl;\n }\n }\n\n} \/\/ end function print\n\ntemplate< class IntersectionType, class FieldType, int size >\nbool intersectionContains( const IntersectionType& \/*intersection*\/, const Dune::FieldVector< FieldType, size >& \/*globalPoint*\/ )\n{\n dune_static_assert( size < 3, \"Dune::FemTools::Grid::Intersection::contains() not implemented for more than 2 dimension!\" );\n return false;\n}\n\ntemplate< class IntersectionType, class FieldType >\nbool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 1 >& globalPoint )\n{\n typedef Dune::FieldVector< FieldType, 1 >\n GlobalPointType;\n\n typedef typename IntersectionType::Geometry\n GeometryType;\n\n const GeometryType& geometry = intersection.geometry();\n\n \/\/ get the only corner\n const GlobalPointType corner = geometry.corner( 0 );\n \/\/ check if the point is the corner\n if( corner == globalPoint )\n {\n return true;\n }\n\n return false;\n} \/\/ end function contains\n\ntemplate< class IntersectionType, class FieldType >\nbool intersectionContains( const IntersectionType& intersection, const Dune::FieldVector< FieldType, 2 > & globalPoint )\n{\n typedef Dune::FieldVector< FieldType, 2 >\n GlobalPointType;\n\n typedef typename IntersectionType::Geometry\n GeometryType;\n\n const GeometryType& geometry = intersection.geometry();\n\n \/\/ get the two corners\n const GlobalPointType firstCorner = geometry.corner( 0 );\n const GlobalPointType secondCorner = geometry.corner( 1 );\n\n \/\/ check, that point is on the line between the two points\n const FieldType x1 = ( globalPoint[0] - firstCorner[0] ) \/ ( secondCorner[0] - firstCorner[0] );\n const FieldType x2 = ( globalPoint[1] - firstCorner[1] ) \/ ( secondCorner[1] - firstCorner[1] );\n if( !( x1 > x2 ) && !( x1 < x2 ) && !( x1 < 0.0 ) && !( x1 > 1.0 ) )\n {\n return true;\n }\n\n return false;\n} \/\/ end function contains\n\n} \/\/ end namespace Grid\n} \/\/ end of namespace Stuff\n} \/\/ end namespace Dune\n\n#endif \/\/ DUNE_STUFF_GRID_INTERSECTION_HH\n\/** Copyright (c) 2012, Felix Albrecht\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * 1. Redistributions of source code must retain the above copyright notice, this\n * list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\n * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\n * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * The views and conclusions contained in the software and documentation are those\n * of the authors and should not be interpreted as representing official policies,\n * either expressed or implied, of the FreeBSD Project.\n **\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012,2017-2018 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n#ifndef __BASE_COMPILER_HH__\n#define __BASE_COMPILER_HH__\n\n#include \n\n\/\/ http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Function-Attributes.html\n\n#if defined(__GNUC__) \/\/ clang or gcc\n# define M5_ATTR_NORETURN __attribute__((noreturn))\n# define M5_DUMMY_RETURN\n# define M5_VAR_USED __attribute__((unused))\n# define M5_ATTR_PACKED __attribute__ ((__packed__))\n# define M5_NO_INLINE __attribute__ ((__noinline__))\n# define M5_DEPRECATED __attribute__((deprecated))\n# define M5_DEPRECATED_MSG(MSG) __attribute__((deprecated(MSG)))\n# define M5_UNREACHABLE __builtin_unreachable()\n# define M5_PUBLIC __attribute__ ((visibility (\"default\")))\n# define M5_LOCAL __attribute__ ((visibility (\"hidden\")))\n#endif\n\n#if defined(__clang__)\n# define M5_CLASS_VAR_USED M5_VAR_USED\n#else\n# define M5_CLASS_VAR_USED\n#endif\n\n\/\/ This can be removed once all compilers support C++17\n#if defined __has_cpp_attribute\n \/\/ Note: We must separate this if statement because GCC < 5.0 doesn't\n \/\/ support the function-like syntax in #if statements.\n #if __has_cpp_attribute(fallthrough)\n #define M5_FALLTHROUGH [[fallthrough]]\n #else\n #define M5_FALLTHROUGH\n #endif\n\n #if __has_cpp_attribute(nodiscard)\n #define M5_NODISCARD [[nodiscard]]\n #else\n #define M5_NODISCARD\n #endif\n#else\n \/\/ Unsupported (and no warning) on GCC < 7.\n #define M5_FALLTHROUGH\n\n #define M5_NODISCARD\n#endif\n\n\/\/ std::make_unique redefined for C++11 compilers\nnamespace m5\n{\n\n#if __cplusplus == 201402L \/\/ C++14\n\nusing std::make_unique;\n\n#else \/\/ C++11\n\n\/** Defining custom version of make_unique: m5::make_unique<>() *\/\ntemplate\nstd::unique_ptr\nmake_unique( Args&&... constructor_args )\n{\n return std::unique_ptr(\n new T( std::forward(constructor_args)... )\n );\n}\n\n#endif \/\/ __cplusplus == 201402L\n\n} \/\/namespace m5\n\n#endif \/\/ __BASE_COMPILER_HH__\nbase: Replace cppversion == version with >= version\/*\n * Copyright (c) 2012,2017-2018 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2006 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n#ifndef __BASE_COMPILER_HH__\n#define __BASE_COMPILER_HH__\n\n#include \n\n\/\/ http:\/\/gcc.gnu.org\/onlinedocs\/gcc\/Function-Attributes.html\n\n#if defined(__GNUC__) \/\/ clang or gcc\n# define M5_ATTR_NORETURN __attribute__((noreturn))\n# define M5_DUMMY_RETURN\n# define M5_VAR_USED __attribute__((unused))\n# define M5_ATTR_PACKED __attribute__ ((__packed__))\n# define M5_NO_INLINE __attribute__ ((__noinline__))\n# define M5_DEPRECATED __attribute__((deprecated))\n# define M5_DEPRECATED_MSG(MSG) __attribute__((deprecated(MSG)))\n# define M5_UNREACHABLE __builtin_unreachable()\n# define M5_PUBLIC __attribute__ ((visibility (\"default\")))\n# define M5_LOCAL __attribute__ ((visibility (\"hidden\")))\n#endif\n\n#if defined(__clang__)\n# define M5_CLASS_VAR_USED M5_VAR_USED\n#else\n# define M5_CLASS_VAR_USED\n#endif\n\n\/\/ This can be removed once all compilers support C++17\n#if defined __has_cpp_attribute\n \/\/ Note: We must separate this if statement because GCC < 5.0 doesn't\n \/\/ support the function-like syntax in #if statements.\n #if __has_cpp_attribute(fallthrough)\n #define M5_FALLTHROUGH [[fallthrough]]\n #else\n #define M5_FALLTHROUGH\n #endif\n\n #if __has_cpp_attribute(nodiscard)\n #define M5_NODISCARD [[nodiscard]]\n #else\n #define M5_NODISCARD\n #endif\n#else\n \/\/ Unsupported (and no warning) on GCC < 7.\n #define M5_FALLTHROUGH\n\n #define M5_NODISCARD\n#endif\n\n\/\/ std::make_unique redefined for C++11 compilers\nnamespace m5\n{\n\n#if __cplusplus >= 201402L \/\/ C++14\n\nusing std::make_unique;\n\n#else \/\/ C++11\n\n\/** Defining custom version of make_unique: m5::make_unique<>() *\/\ntemplate\nstd::unique_ptr\nmake_unique( Args&&... constructor_args )\n{\n return std::unique_ptr(\n new T( std::forward(constructor_args)... )\n );\n}\n\n#endif \/\/ __cplusplus >= 201402L\n\n} \/\/namespace m5\n\n#endif \/\/ __BASE_COMPILER_HH__\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nstatic const int CONTINUE_EXECUTION=-1;\n\nconst std::function G_TRANSLATION_FUN = nullptr;\n\nstatic void SetupBitcoinUtilArgs(ArgsManager &argsman)\n{\n SetupHelpOptions(argsman);\n\n argsman.AddArg(\"-version\", \"Print version and exit\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n\n SetupChainParamsBaseOptions(argsman);\n}\n\n\/\/ This function returns either one of EXIT_ codes when it's expected to stop the process or\n\/\/ CONTINUE_EXECUTION when it's expected to continue further.\nstatic int AppInitUtil(int argc, char* argv[])\n{\n SetupBitcoinUtilArgs(gArgs);\n std::string error;\n if (!gArgs.ParseParameters(argc, argv, error)) {\n tfm::format(std::cerr, \"Error parsing command line arguments: %s\\n\", error);\n return EXIT_FAILURE;\n }\n\n \/\/ Check for chain settings (Params() calls are only valid after this clause)\n try {\n SelectParams(gArgs.GetChainName());\n } catch (const std::exception& e) {\n tfm::format(std::cerr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n\n if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet(\"-version\")) {\n \/\/ First part of help message is specific to this utility\n std::string strUsage = PACKAGE_NAME \" bitcoin-util utility version \" + FormatFullVersion() + \"\\n\";\n if (!gArgs.IsArgSet(\"-version\")) {\n strUsage += \"\\n\"\n \"Usage: bitcoin-util [options] [commands] Do stuff\\n\";\n strUsage += \"\\n\" + gArgs.GetHelpMessage();\n }\n\n tfm::format(std::cout, \"%s\", strUsage);\n\n if (argc < 2) {\n tfm::format(std::cerr, \"Error: too few parameters\\n\");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n }\n return CONTINUE_EXECUTION;\n}\n\nstatic void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic& found)\n{\n arith_uint256 target;\n bool neg, over;\n target.SetCompact(nBits, &neg, &over);\n if (target == 0 || neg || over) return;\n CBlockHeader header = header_orig; \/\/ working copy\n header.nNonce = offset;\n\n uint32_t finish = std::numeric_limits::max() - step;\n finish = finish - (finish % step) + offset;\n\n while (!found && header.nNonce < finish) {\n const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;\n do {\n if (UintToArith256(header.GetHash()) <= target) {\n if (!found.exchange(true)) {\n header_orig.nNonce = header.nNonce;\n }\n return;\n }\n header.nNonce += step;\n } while(header.nNonce != next);\n }\n}\n\nstatic int Grind(int argc, char* argv[], std::string& strPrint)\n{\n if (argc != 1) {\n strPrint = \"Must specify block header to grind\";\n return 1;\n }\n\n CBlockHeader header;\n if (!DecodeHexBlockHeader(header, argv[0])) {\n strPrint = \"Could not decode block header\";\n return 1;\n }\n\n uint32_t nBits = header.nBits;\n std::atomic found{false};\n\n std::vector threads;\n int n_tasks = std::max(1u, std::thread::hardware_concurrency());\n for (int i = 0; i < n_tasks; ++i) {\n threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );\n }\n for (auto& t : threads) {\n t.join();\n }\n if (!found) {\n strPrint = \"Could not satisfy difficulty target\";\n return 1;\n }\n\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << header;\n strPrint = HexStr(ss);\n return 0;\n}\n\nstatic int CommandLineUtil(int argc, char* argv[])\n{\n if (argc <= 1) return 1;\n\n std::string strPrint;\n int nRet = 0;\n\n try {\n while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {\n --argc;\n ++argv;\n }\n\n char* command = argv[1];\n if (strcmp(command, \"grind\") == 0) {\n nRet = Grind(argc-2, argv+2, strPrint);\n } else {\n strPrint = strprintf(\"Unknown command %s\", command);\n nRet = 1;\n }\n }\n catch (const std::exception& e) {\n strPrint = std::string(\"error: \") + e.what();\n nRet = EXIT_FAILURE;\n }\n catch (...) {\n PrintExceptionContinue(nullptr, \"CommandLineUtil()\");\n throw;\n }\n\n if (strPrint != \"\") {\n tfm::format(nRet == 0 ? std::cout : std::cerr, \"%s\\n\", strPrint);\n }\n return nRet;\n}\n\nint main(int argc, char* argv[])\n{\n SetupEnvironment();\n\n try {\n int ret = AppInitUtil(argc, argv);\n if (ret != CONTINUE_EXECUTION)\n return ret;\n }\n catch (const std::exception& e) {\n PrintExceptionContinue(&e, \"AppInitUtil()\");\n return EXIT_FAILURE;\n } catch (...) {\n PrintExceptionContinue(nullptr, \"AppInitUtil()\");\n return EXIT_FAILURE;\n }\n\n int ret = EXIT_FAILURE;\n try {\n ret = CommandLineUtil(argc, argv);\n }\n catch (const std::exception& e) {\n PrintExceptionContinue(&e, \"CommandLineUtil()\");\n } catch (...) {\n PrintExceptionContinue(nullptr, \"CommandLineUtil()\");\n }\n return ret;\n}\nadd std::atomic include to bitcoin-util.cpp\/\/ Copyright (c) 2009-2020 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\nstatic const int CONTINUE_EXECUTION=-1;\n\nconst std::function G_TRANSLATION_FUN = nullptr;\n\nstatic void SetupBitcoinUtilArgs(ArgsManager &argsman)\n{\n SetupHelpOptions(argsman);\n\n argsman.AddArg(\"-version\", \"Print version and exit\", ArgsManager::ALLOW_ANY, OptionsCategory::OPTIONS);\n\n SetupChainParamsBaseOptions(argsman);\n}\n\n\/\/ This function returns either one of EXIT_ codes when it's expected to stop the process or\n\/\/ CONTINUE_EXECUTION when it's expected to continue further.\nstatic int AppInitUtil(int argc, char* argv[])\n{\n SetupBitcoinUtilArgs(gArgs);\n std::string error;\n if (!gArgs.ParseParameters(argc, argv, error)) {\n tfm::format(std::cerr, \"Error parsing command line arguments: %s\\n\", error);\n return EXIT_FAILURE;\n }\n\n \/\/ Check for chain settings (Params() calls are only valid after this clause)\n try {\n SelectParams(gArgs.GetChainName());\n } catch (const std::exception& e) {\n tfm::format(std::cerr, \"Error: %s\\n\", e.what());\n return EXIT_FAILURE;\n }\n\n if (argc < 2 || HelpRequested(gArgs) || gArgs.IsArgSet(\"-version\")) {\n \/\/ First part of help message is specific to this utility\n std::string strUsage = PACKAGE_NAME \" bitcoin-util utility version \" + FormatFullVersion() + \"\\n\";\n if (!gArgs.IsArgSet(\"-version\")) {\n strUsage += \"\\n\"\n \"Usage: bitcoin-util [options] [commands] Do stuff\\n\";\n strUsage += \"\\n\" + gArgs.GetHelpMessage();\n }\n\n tfm::format(std::cout, \"%s\", strUsage);\n\n if (argc < 2) {\n tfm::format(std::cerr, \"Error: too few parameters\\n\");\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n }\n return CONTINUE_EXECUTION;\n}\n\nstatic void grind_task(uint32_t nBits, CBlockHeader& header_orig, uint32_t offset, uint32_t step, std::atomic& found)\n{\n arith_uint256 target;\n bool neg, over;\n target.SetCompact(nBits, &neg, &over);\n if (target == 0 || neg || over) return;\n CBlockHeader header = header_orig; \/\/ working copy\n header.nNonce = offset;\n\n uint32_t finish = std::numeric_limits::max() - step;\n finish = finish - (finish % step) + offset;\n\n while (!found && header.nNonce < finish) {\n const uint32_t next = (finish - header.nNonce < 5000*step) ? finish : header.nNonce + 5000*step;\n do {\n if (UintToArith256(header.GetHash()) <= target) {\n if (!found.exchange(true)) {\n header_orig.nNonce = header.nNonce;\n }\n return;\n }\n header.nNonce += step;\n } while(header.nNonce != next);\n }\n}\n\nstatic int Grind(int argc, char* argv[], std::string& strPrint)\n{\n if (argc != 1) {\n strPrint = \"Must specify block header to grind\";\n return 1;\n }\n\n CBlockHeader header;\n if (!DecodeHexBlockHeader(header, argv[0])) {\n strPrint = \"Could not decode block header\";\n return 1;\n }\n\n uint32_t nBits = header.nBits;\n std::atomic found{false};\n\n std::vector threads;\n int n_tasks = std::max(1u, std::thread::hardware_concurrency());\n for (int i = 0; i < n_tasks; ++i) {\n threads.emplace_back( grind_task, nBits, std::ref(header), i, n_tasks, std::ref(found) );\n }\n for (auto& t : threads) {\n t.join();\n }\n if (!found) {\n strPrint = \"Could not satisfy difficulty target\";\n return 1;\n }\n\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << header;\n strPrint = HexStr(ss);\n return 0;\n}\n\nstatic int CommandLineUtil(int argc, char* argv[])\n{\n if (argc <= 1) return 1;\n\n std::string strPrint;\n int nRet = 0;\n\n try {\n while (argc > 1 && IsSwitchChar(argv[1][0]) && (argv[1][1] != 0)) {\n --argc;\n ++argv;\n }\n\n char* command = argv[1];\n if (strcmp(command, \"grind\") == 0) {\n nRet = Grind(argc-2, argv+2, strPrint);\n } else {\n strPrint = strprintf(\"Unknown command %s\", command);\n nRet = 1;\n }\n }\n catch (const std::exception& e) {\n strPrint = std::string(\"error: \") + e.what();\n nRet = EXIT_FAILURE;\n }\n catch (...) {\n PrintExceptionContinue(nullptr, \"CommandLineUtil()\");\n throw;\n }\n\n if (strPrint != \"\") {\n tfm::format(nRet == 0 ? std::cout : std::cerr, \"%s\\n\", strPrint);\n }\n return nRet;\n}\n\nint main(int argc, char* argv[])\n{\n SetupEnvironment();\n\n try {\n int ret = AppInitUtil(argc, argv);\n if (ret != CONTINUE_EXECUTION)\n return ret;\n }\n catch (const std::exception& e) {\n PrintExceptionContinue(&e, \"AppInitUtil()\");\n return EXIT_FAILURE;\n } catch (...) {\n PrintExceptionContinue(nullptr, \"AppInitUtil()\");\n return EXIT_FAILURE;\n }\n\n int ret = EXIT_FAILURE;\n try {\n ret = CommandLineUtil(argc, argv);\n }\n catch (const std::exception& e) {\n PrintExceptionContinue(&e, \"CommandLineUtil()\");\n } catch (...) {\n PrintExceptionContinue(nullptr, \"CommandLineUtil()\");\n }\n return ret;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 National ICT Australia Limited (NICTA)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"bonmin_model.hpp\"\n#include \"bonmin_minlp.hpp\"\n\n#include \"common.hpp\"\n\nusing namespace MadOpt;\n\nnamespace MadOpt {\n\nstruct BonminModelImpl {\n BonminModelImpl(BonminModel* model){\n Bapp = new Bonmin::BonminSetup();\n Bapp->initializeOptionsAndJournalist();\n bonmin_callback = new BonminUserClass(model);\n }\n\n ~BonminModelImpl(){\n delete Bapp;\n }\n\n Bonmin::BonminSetup* Bapp;\n Ipopt::SmartPtr bonmin_callback;\n};\n}\n\nBonminModel::BonminModel(): Model(){\n impl = new BonminModelImpl(this);\n}\n\nBonminModel::~BonminModel(){\n delete impl;\n}\n\nvoid BonminModel::solve(){\n if (timelimit >= 0)\n setNumericOption(\"bonmin.time_limit\", timelimit);\n\n if (not show_solver){\n setIntegerOption(\"print_level\", 0);\n setIntegerOption(\"bonmin.bb_log_level\", 0);\n setIntegerOption(\"bonmin.nlp_log_level\", 0);\n setStringOption(\"sb\", \"yes\");\n }\n\n try {\n impl->Bapp->initialize(GetRawPtr(impl->bonmin_callback));\n Bonmin::Bab bb;\n bb(impl->Bapp);\n\n }\n catch(Bonmin::TNLPSolver::UnsolvedError &E) {\n solution.setStatus(Solution::SolverStatus::UNSOLVED_ERROR);\n }\n\n \/\/ impl->Bapp->initialize(GetRawPtr(impl->bonmin_callback));\n \/\/ Bonmin::Bab bb;\n \/\/ bb(impl->Bapp);\n\n model_changed = false;\n}\n\nvoid BonminModel::setStringOption(std::string key, std::string value){\n impl->Bapp->options()->SetStringValue(key, value);\n}\n\nvoid BonminModel::setNumericOption(std::string key, double value){\n impl->Bapp->options()->SetNumericValue(key, value);\n}\n\nvoid BonminModel::setIntegerOption(std::string key, int value){\n impl->Bapp->options()->SetIntegerValue(key, value);\n}\nSolved #12\/*\n * Copyright 2014 National ICT Australia Limited (NICTA)\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"bonmin_model.hpp\"\n#include \"bonmin_minlp.hpp\"\n\n#include \"common.hpp\"\n\nusing namespace MadOpt;\n\nnamespace MadOpt {\n\nstruct BonminModelImpl {\n BonminModelImpl(BonminModel* model){\n Bapp = new Bonmin::BonminSetup();\n Bapp->initializeOptionsAndJournalist();\n bonmin_callback = new BonminUserClass(model);\n }\n\n ~BonminModelImpl(){\n delete Bapp;\n }\n\n Bonmin::BonminSetup* Bapp;\n Ipopt::SmartPtr bonmin_callback;\n};\n}\n\nBonminModel::BonminModel(): Model(){\n impl = new BonminModelImpl(this);\n}\n\nBonminModel::~BonminModel(){\n delete impl;\n}\n\nvoid BonminModel::solve(){\n if (timelimit >= 0)\n setNumericOption(\"bonmin.time_limit\", timelimit);\n\n if (not show_solver){\n setIntegerOption(\"print_level\", 0);\n setIntegerOption(\"bonmin.bb_log_level\", 0);\n setIntegerOption(\"bonmin.nlp_log_level\", 0);\n setStringOption(\"sb\", \"yes\");\n }\n\n try {\n impl->Bapp->initialize(GetRawPtr(impl->bonmin_callback));\n Bonmin::Bab bb;\n bb(impl->Bapp);\n }\n catch(Bonmin::TNLPSolver::UnsolvedError *E) {\n solution.setStatus(Solution::SolverStatus::UNSOLVED_ERROR);\n delete E;\n }\n catch(Bonmin::TNLPSolver::UnsolvedError &E) {\n solution.setStatus(Solution::SolverStatus::UNSOLVED_ERROR);\n }\n \/\/ Other possible exceptions we may want to catch here:\n \/\/ OsiTMINLPInterface::SimpleError &E\n \/\/ CoinError &E\n\n model_changed = false;\n}\n\nvoid BonminModel::setStringOption(std::string key, std::string value){\n impl->Bapp->options()->SetStringValue(key, value);\n}\n\nvoid BonminModel::setNumericOption(std::string key, double value){\n impl->Bapp->options()->SetNumericValue(key, value);\n}\n\nvoid BonminModel::setIntegerOption(std::string key, int value){\n impl->Bapp->options()->SetIntegerValue(key, value);\n}\n<|endoftext|>"} {"text":"\/******\nootree: An easy to use and highly configurable C++ template tree class, \nusing STL container style interfaces.\n\nCopyright (c) 2010 Erik Erlandson\n\nAuthor: Erik Erlandson \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n******\/\n\n#include \nusing namespace std;\n\n\/\/ use the mtree header and namespace\n#include \"ootree.h\"\nusing namespace ootree;\n\nint main(int argc, char** argv) {\n return 0;\n}\nAdded 1st example -- hello world\/******\nootree: An easy to use and highly configurable C++ template tree class, \nusing STL container style interfaces.\n\nCopyright (c) 2010 Erik Erlandson\n\nAuthor: Erik Erlandson \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n******\/\n\n#include \nusing namespace std;\n\n\/\/ use the mtree header and namespace\n#include \"ootree.h\"\nusing namespace ootree;\n\nint main(int argc, char** argv) {\n \/\/ declare a tree of strings \n tree t;\n typedef tree::bf_iterator bf_iterator;\n\n \/\/ insert a string at root (ply 0)\n t.insert(\"Hello\");\n\n \/\/ insert strings at ply 1\n t.root().insert(\" \");\n t.root().insert(\"world\");\n\n \/\/ insert strings at ply 2\n t.root()[0].insert(\"!\");\n t.root()[1].insert(\"\\n\");\n\n \/\/ output data in breadth first order to print a traditional message\n for (bf_iterator j(t.bf_begin()); j != t.bf_end(); ++j)\n cout << j->data();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014 Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Alexandru Dutu\n *\/\n\n\/**\n * @file\n * Definitions of page table\n *\/\n#include \n#include \n#include \n\n#include \"base\/bitfield.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/trace.hh\"\n#include \"config\/the_isa.hh\"\n#include \"debug\/MMU.hh\"\n#include \"mem\/multi_level_page_table.hh\"\n#include \"sim\/faults.hh\"\n#include \"sim\/sim_object.hh\"\n\nusing namespace std;\nusing namespace TheISA;\n\ntemplate \nMultiLevelPageTable::MultiLevelPageTable(const std::string &__name,\n uint64_t _pid, System *_sys)\n : PageTableBase(__name, _pid), system(_sys),\n logLevelSize(PageTableLayout),\n numLevels(logLevelSize.size())\n{\n}\n\ntemplate \nMultiLevelPageTable::~MultiLevelPageTable()\n{\n}\n\ntemplate \nvoid\nMultiLevelPageTable::initState(ThreadContext* tc)\n{\n basePtr = pTableISAOps.getBasePtr(tc);\n if (basePtr == 0) basePtr++;\n DPRINTF(MMU, \"basePtr: %d\\n\", basePtr);\n\n system->pagePtr = basePtr;\n\n \/* setting first level of the page table *\/\n uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +\n logLevelSize[numLevels-1];\n assert(log_req_size >= PageShift);\n uint64_t npages = 1 << (log_req_size - PageShift);\n\n Addr paddr = system->allocPhysPages(npages);\n\n PortProxy &p = system->physProxy;\n p.memsetBlob(paddr, 0, npages << PageShift);\n}\n\n\ntemplate \nbool\nMultiLevelPageTable::walk(Addr vaddr, bool allocate, Addr &PTE_addr)\n{\n std::vector offsets = pTableISAOps.getOffsets(vaddr);\n\n Addr level_base = basePtr;\n for (int i = numLevels - 1; i > 0; i--) {\n\n Addr entry_addr = (level_base<physProxy;\n PageTableEntry entry = p.read(entry_addr);\n\n Addr next_entry_pnum = pTableISAOps.getPnum(entry);\n if (next_entry_pnum == 0) {\n\n if (!allocate) return false;\n\n uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +\n logLevelSize[i-1];\n assert(log_req_size >= PageShift);\n uint64_t npages = 1 << (log_req_size - PageShift);\n\n DPRINTF(MMU, \"Allocating %d pages needed for entry in level %d\\n\",\n npages, i - 1);\n\n \/* allocate new entry *\/\n Addr next_entry_paddr = system->allocPhysPages(npages);\n p.memsetBlob(next_entry_paddr, 0, npages << PageShift);\n\n next_entry_pnum = next_entry_paddr >> PageShift;\n pTableISAOps.setPnum(entry, next_entry_pnum);\n pTableISAOps.setPTEFields(entry);\n p.write(entry_addr, entry);\n\n }\n DPRINTF(MMU, \"Level %d base: %d offset: %d entry: %d\\n\",\n i, level_base, offsets[i], next_entry_pnum);\n level_base = next_entry_pnum;\n\n }\n PTE_addr = (level_base<\nvoid\nMultiLevelPageTable::map(Addr vaddr, Addr paddr,\n int64_t size, bool clobber)\n{\n \/\/ starting address must be page aligned\n assert(pageOffset(vaddr) == 0);\n\n DPRINTF(MMU, \"Allocating Page: %#x-%#x\\n\", vaddr, vaddr + size);\n\n PortProxy &p = system->physProxy;\n\n for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) {\n Addr PTE_addr;\n if (walk(vaddr, true, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n Addr entry_paddr = pTableISAOps.getPnum(PTE);\n if (!clobber && entry_paddr == 0) {\n pTableISAOps.setPnum(PTE, paddr >> PageShift);\n pTableISAOps.setPTEFields(PTE);\n p.write(PTE_addr, PTE);\n DPRINTF(MMU, \"New mapping: %#x-%#x\\n\", vaddr, paddr);\n } else {\n fatal(\"addr 0x%x already mapped to %x\", vaddr, entry_paddr);\n }\n\n eraseCacheEntry(vaddr);\n updateCache(vaddr, TlbEntry(pid, vaddr, paddr));\n }\n\n }\n}\n\ntemplate \nvoid\nMultiLevelPageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr)\n{\n assert(pageOffset(vaddr) == 0);\n assert(pageOffset(new_vaddr) == 0);\n\n DPRINTF(MMU, \"moving pages from vaddr %08p to %08p, size = %d\\n\", vaddr,\n new_vaddr, size);\n\n PortProxy &p = system->physProxy;\n\n for (; size > 0;\n size -= pageSize, vaddr += pageSize, new_vaddr += pageSize)\n {\n Addr PTE_addr;\n if (walk(vaddr, false, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n Addr paddr = pTableISAOps.getPnum(PTE);\n\n if (paddr == 0) {\n fatal(\"Page fault while remapping\");\n } else {\n \/* unmapping vaddr *\/\n pTableISAOps.setPnum(PTE, 0);\n p.write(PTE_addr, PTE);\n\n \/* maping new_vaddr *\/\n Addr new_PTE_addr;\n walk(new_vaddr, true, new_PTE_addr);\n PageTableEntry new_PTE = p.read(new_PTE_addr);\n\n pTableISAOps.setPnum(new_PTE, paddr>>PageShift);\n pTableISAOps.setPTEFields(new_PTE);\n p.write(new_PTE_addr, new_PTE);\n DPRINTF(MMU, \"Remapping: %#x-%#x\\n\", vaddr, new_PTE_addr);\n }\n\n eraseCacheEntry(vaddr);\n updateCache(new_vaddr, TlbEntry(pid, new_vaddr, paddr));\n } else {\n fatal(\"Page fault while remapping\");\n }\n }\n}\n\ntemplate \nvoid\nMultiLevelPageTable::unmap(Addr vaddr, int64_t size)\n{\n assert(pageOffset(vaddr) == 0);\n\n DPRINTF(MMU, \"Unmapping page: %#x-%#x\\n\", vaddr, vaddr+ size);\n\n PortProxy &p = system->physProxy;\n\n for (; size > 0; size -= pageSize, vaddr += pageSize) {\n Addr PTE_addr;\n if (walk(vaddr, false, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n Addr paddr = pTableISAOps.getPnum(PTE);\n if (paddr == 0) {\n fatal(\"PageTable::allocate: address 0x%x not mapped\", vaddr);\n } else {\n pTableISAOps.setPnum(PTE, 0);\n p.write(PTE_addr, PTE);\n DPRINTF(MMU, \"Unmapping: %#x\\n\", vaddr);\n }\n eraseCacheEntry(vaddr);\n } else {\n fatal(\"Page fault while unmapping\");\n }\n }\n\n}\n\ntemplate \nbool\nMultiLevelPageTable::isUnmapped(Addr vaddr, int64_t size)\n{\n \/\/ starting address must be page aligned\n assert(pageOffset(vaddr) == 0);\n PortProxy &p = system->physProxy;\n\n for (; size > 0; size -= pageSize, vaddr += pageSize) {\n Addr PTE_addr;\n if (walk(vaddr, false, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n if (pTableISAOps.getPnum(PTE) != 0)\n return false;\n }\n }\n\n return true;\n}\n\ntemplate \nbool\nMultiLevelPageTable::lookup(Addr vaddr, TlbEntry &entry)\n{\n Addr page_addr = pageAlign(vaddr);\n\n if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) {\n entry = pTableCache[0].entry;\n return true;\n }\n if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) {\n entry = pTableCache[1].entry;\n return true;\n }\n if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) {\n entry = pTableCache[2].entry;\n return true;\n }\n\n DPRINTF(MMU, \"lookup page_addr: %#x\\n\", page_addr);\n Addr PTE_addr;\n if (walk(page_addr, false, PTE_addr)) {\n PortProxy &p = system->physProxy;\n PageTableEntry PTE = p.read(PTE_addr);\n Addr pnum = pTableISAOps.getPnum(PTE);\n if (pnum == 0)\n return false;\n\n entry = TlbEntry(pid, vaddr, pnum << PageShift);\n updateCache(page_addr, entry);\n } else {\n return false;\n }\n return true;\n}\n\ntemplate \nvoid\nMultiLevelPageTable::serialize(std::ostream &os)\n{\n \/** Since, the page table is stored in system memory\n * which is serialized separately, we will serialize\n * just the base pointer\n *\/\n paramOut(os, \"ptable.pointer\", basePtr);\n}\n\ntemplate \nvoid\nMultiLevelPageTable::unserialize(Checkpoint *cp,\n const std::string §ion)\n{\n paramIn(cp, section, \"ptable.pointer\", basePtr);\n}\nmem: Multi Level Page Table bug fix\/*\n * Copyright (c) 2014 Advanced Micro Devices, Inc.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Alexandru Dutu\n *\/\n\n\/**\n * @file\n * Definitions of page table\n *\/\n#include \n#include \n#include \n\n#include \"base\/bitfield.hh\"\n#include \"base\/intmath.hh\"\n#include \"base\/trace.hh\"\n#include \"config\/the_isa.hh\"\n#include \"debug\/MMU.hh\"\n#include \"mem\/multi_level_page_table.hh\"\n#include \"sim\/faults.hh\"\n#include \"sim\/sim_object.hh\"\n\nusing namespace std;\nusing namespace TheISA;\n\ntemplate \nMultiLevelPageTable::MultiLevelPageTable(const std::string &__name,\n uint64_t _pid, System *_sys)\n : PageTableBase(__name, _pid), system(_sys),\n logLevelSize(PageTableLayout),\n numLevels(logLevelSize.size())\n{\n}\n\ntemplate \nMultiLevelPageTable::~MultiLevelPageTable()\n{\n}\n\ntemplate \nvoid\nMultiLevelPageTable::initState(ThreadContext* tc)\n{\n basePtr = pTableISAOps.getBasePtr(tc);\n if (basePtr == 0) basePtr++;\n DPRINTF(MMU, \"basePtr: %d\\n\", basePtr);\n\n system->pagePtr = basePtr;\n\n \/* setting first level of the page table *\/\n uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +\n logLevelSize[numLevels-1];\n assert(log_req_size >= PageShift);\n uint64_t npages = 1 << (log_req_size - PageShift);\n\n Addr paddr = system->allocPhysPages(npages);\n\n PortProxy &p = system->physProxy;\n p.memsetBlob(paddr, 0, npages << PageShift);\n}\n\n\ntemplate \nbool\nMultiLevelPageTable::walk(Addr vaddr, bool allocate, Addr &PTE_addr)\n{\n std::vector offsets = pTableISAOps.getOffsets(vaddr);\n\n Addr level_base = basePtr;\n for (int i = numLevels - 1; i > 0; i--) {\n\n Addr entry_addr = (level_base<physProxy;\n PageTableEntry entry = p.read(entry_addr);\n\n Addr next_entry_pnum = pTableISAOps.getPnum(entry);\n if (next_entry_pnum == 0) {\n\n if (!allocate) return false;\n\n uint64_t log_req_size = floorLog2(sizeof(PageTableEntry)) +\n logLevelSize[i-1];\n assert(log_req_size >= PageShift);\n uint64_t npages = 1 << (log_req_size - PageShift);\n\n DPRINTF(MMU, \"Allocating %d pages needed for entry in level %d\\n\",\n npages, i - 1);\n\n \/* allocate new entry *\/\n Addr next_entry_paddr = system->allocPhysPages(npages);\n p.memsetBlob(next_entry_paddr, 0, npages << PageShift);\n\n next_entry_pnum = next_entry_paddr >> PageShift;\n pTableISAOps.setPnum(entry, next_entry_pnum);\n pTableISAOps.setPTEFields(entry);\n p.write(entry_addr, entry);\n\n }\n DPRINTF(MMU, \"Level %d base: %d offset: %d entry: %d\\n\",\n i, level_base, offsets[i], next_entry_pnum);\n level_base = next_entry_pnum;\n\n }\n PTE_addr = (level_base<\nvoid\nMultiLevelPageTable::map(Addr vaddr, Addr paddr,\n int64_t size, bool clobber)\n{\n \/\/ starting address must be page aligned\n assert(pageOffset(vaddr) == 0);\n\n DPRINTF(MMU, \"Allocating Page: %#x-%#x\\n\", vaddr, vaddr + size);\n\n PortProxy &p = system->physProxy;\n\n for (; size > 0; size -= pageSize, vaddr += pageSize, paddr += pageSize) {\n Addr PTE_addr;\n if (walk(vaddr, true, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n Addr entry_paddr = pTableISAOps.getPnum(PTE);\n if (!clobber && entry_paddr != 0) {\n fatal(\"addr 0x%x already mapped to %x\", vaddr, entry_paddr);\n }\n pTableISAOps.setPnum(PTE, paddr >> PageShift);\n pTableISAOps.setPTEFields(PTE);\n p.write(PTE_addr, PTE);\n DPRINTF(MMU, \"New mapping: %#x-%#x\\n\", vaddr, paddr);\n\n eraseCacheEntry(vaddr);\n updateCache(vaddr, TlbEntry(pid, vaddr, paddr));\n }\n\n }\n}\n\ntemplate \nvoid\nMultiLevelPageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr)\n{\n assert(pageOffset(vaddr) == 0);\n assert(pageOffset(new_vaddr) == 0);\n\n DPRINTF(MMU, \"moving pages from vaddr %08p to %08p, size = %d\\n\", vaddr,\n new_vaddr, size);\n\n PortProxy &p = system->physProxy;\n\n for (; size > 0;\n size -= pageSize, vaddr += pageSize, new_vaddr += pageSize)\n {\n Addr PTE_addr;\n if (walk(vaddr, false, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n Addr paddr = pTableISAOps.getPnum(PTE);\n\n if (paddr == 0) {\n fatal(\"Page fault while remapping\");\n } else {\n \/* unmapping vaddr *\/\n pTableISAOps.setPnum(PTE, 0);\n p.write(PTE_addr, PTE);\n\n \/* maping new_vaddr *\/\n Addr new_PTE_addr;\n walk(new_vaddr, true, new_PTE_addr);\n PageTableEntry new_PTE = p.read(new_PTE_addr);\n\n pTableISAOps.setPnum(new_PTE, paddr>>PageShift);\n pTableISAOps.setPTEFields(new_PTE);\n p.write(new_PTE_addr, new_PTE);\n DPRINTF(MMU, \"Remapping: %#x-%#x\\n\", vaddr, new_PTE_addr);\n }\n\n eraseCacheEntry(vaddr);\n updateCache(new_vaddr, TlbEntry(pid, new_vaddr, paddr));\n } else {\n fatal(\"Page fault while remapping\");\n }\n }\n}\n\ntemplate \nvoid\nMultiLevelPageTable::unmap(Addr vaddr, int64_t size)\n{\n assert(pageOffset(vaddr) == 0);\n\n DPRINTF(MMU, \"Unmapping page: %#x-%#x\\n\", vaddr, vaddr+ size);\n\n PortProxy &p = system->physProxy;\n\n for (; size > 0; size -= pageSize, vaddr += pageSize) {\n Addr PTE_addr;\n if (walk(vaddr, false, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n Addr paddr = pTableISAOps.getPnum(PTE);\n if (paddr == 0) {\n fatal(\"PageTable::allocate: address 0x%x not mapped\", vaddr);\n } else {\n pTableISAOps.setPnum(PTE, 0);\n p.write(PTE_addr, PTE);\n DPRINTF(MMU, \"Unmapping: %#x\\n\", vaddr);\n }\n eraseCacheEntry(vaddr);\n } else {\n fatal(\"Page fault while unmapping\");\n }\n }\n\n}\n\ntemplate \nbool\nMultiLevelPageTable::isUnmapped(Addr vaddr, int64_t size)\n{\n \/\/ starting address must be page aligned\n assert(pageOffset(vaddr) == 0);\n PortProxy &p = system->physProxy;\n\n for (; size > 0; size -= pageSize, vaddr += pageSize) {\n Addr PTE_addr;\n if (walk(vaddr, false, PTE_addr)) {\n PageTableEntry PTE = p.read(PTE_addr);\n if (pTableISAOps.getPnum(PTE) != 0)\n return false;\n }\n }\n\n return true;\n}\n\ntemplate \nbool\nMultiLevelPageTable::lookup(Addr vaddr, TlbEntry &entry)\n{\n Addr page_addr = pageAlign(vaddr);\n\n if (pTableCache[0].valid && pTableCache[0].vaddr == page_addr) {\n entry = pTableCache[0].entry;\n return true;\n }\n if (pTableCache[1].valid && pTableCache[1].vaddr == page_addr) {\n entry = pTableCache[1].entry;\n return true;\n }\n if (pTableCache[2].valid && pTableCache[2].vaddr == page_addr) {\n entry = pTableCache[2].entry;\n return true;\n }\n\n DPRINTF(MMU, \"lookup page_addr: %#x\\n\", page_addr);\n Addr PTE_addr;\n if (walk(page_addr, false, PTE_addr)) {\n PortProxy &p = system->physProxy;\n PageTableEntry PTE = p.read(PTE_addr);\n Addr pnum = pTableISAOps.getPnum(PTE);\n if (pnum == 0)\n return false;\n\n entry = TlbEntry(pid, vaddr, pnum << PageShift);\n updateCache(page_addr, entry);\n } else {\n return false;\n }\n return true;\n}\n\ntemplate \nvoid\nMultiLevelPageTable::serialize(std::ostream &os)\n{\n \/** Since, the page table is stored in system memory\n * which is serialized separately, we will serialize\n * just the base pointer\n *\/\n paramOut(os, \"ptable.pointer\", basePtr);\n}\n\ntemplate \nvoid\nMultiLevelPageTable::unserialize(Checkpoint *cp,\n const std::string §ion)\n{\n paramIn(cp, section, \"ptable.pointer\", basePtr);\n}\n<|endoftext|>"} {"text":"\/\/ UiaDll.cpp : Defines the exported functions for the DLL application.\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"Locator.h\"\r\n#include \"DynamicAssemblyResolver.h\"\r\n#include \"StringHelper.h\"\r\n\r\nIUIAutomation* getGlobalIUIAutomation() ;\r\n\r\nusing namespace RAutomation::UIA;\r\nusing namespace RAutomation::UIA::Controls;\r\nusing namespace RAutomation::UIA::Extensions;\r\n\r\nusing namespace System::Diagnostics;\r\n\r\nextern \"C\" {\r\n\t__declspec(dllexport) void initialize(char* privateAssemblyDirectory) {\r\n\t\tDynamicAssemblyResolver::PrivatePath = gcnew String(privateAssemblyDirectory);\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool ElementExists(const FindInformation& findInformation) {\r\n return Element::Exists(Locator::FindFor(findInformation));\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int NativeWindowHandle(const FindInformation& findInformation) { \r\n return Element::NativeWindowHandle(Locator::FindFor(findInformation));\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int HandleFromPoint(int xCoord, int yCoord) {\r\n\t\tauto element = AutomationElement::FromPoint(Point((double)xCoord, (double)yCoord));\r\n\t\treturn Element::NativeWindowHandle(element);\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int BoundingRectangle(const FindInformation& findInformation, long *rectangle) {\r\n\t\ttry {\r\n\t\t\tauto boundary = Element::BoundingRectangle(Locator::FindFor(findInformation));\r\n\r\n\t\t\trectangle[0] = (long)boundary.Left;\r\n\t\t\trectangle[1] = (long)boundary.Top;\r\n\t\t\trectangle[2] = (long)boundary.Right;\r\n\t\t\trectangle[3] = (long)boundary.Bottom;\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\tcatch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"BoundingRectangle: {0}\", e->Message);\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int ControlType(const FindInformation& findInformation) {\r\n\t\ttry {\r\n return Element::ControlType(Locator::FindFor(findInformation))->Id;\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"ControlType: {0}\", e->Message);\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int ProcessId(const FindInformation& findInformation) {\r\n\t\ttry {\r\n return Element::ProcessId(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"ProcessId: {0}\", e->Message);\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void Name(const FindInformation& findInformation, char* name, const int nameLength) {\r\n\t\ttry {\r\n auto currentName = Element::Name(Locator::FindFor(findInformation));\r\n\t StringHelper::CopyToUnmanagedString(currentName, name, nameLength);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"Name: {0}\", e->Message);\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void ClassName(const FindInformation& findInformation, char* className, const int classNameLength) {\r\n\t\ttry {\r\n auto currentClassName = Element::ClassName(Locator::FindFor(findInformation));\r\n\t\t\tStringHelper::CopyToUnmanagedString(currentClassName, className, classNameLength);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"ClassName: {0}\", e->Message);\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsEnabled(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsEnabled(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"IsEnabled: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsFocused(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsFocused(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"IsFocused: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool SetControlFocus(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\tLocator::FindFor(findInformation)->SetFocus();\r\n\t\t\treturn true;\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"IsFocused: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int GetClassNames(const FindInformation& findInformation, const char* classNames[]) {\r\n\t\tauto allChildren = Locator::FindFor(findInformation)->FindAll(System::Windows::Automation::TreeScope::Subtree, Condition::TrueCondition);\r\n\r\n\t\tif( NULL != classNames ) {\r\n\t\t\tStringHelper::CopyClassNames(allChildren, classNames);\r\n\t\t}\r\n\r\n\t\treturn allChildren->Count;\r\n\t}\r\n\r\n\t__declspec ( dllexport ) IUIAutomationElement *RA_ElementFromHandle(HWND hwnd) {\r\n\t\tIUIAutomationElement *pElement ;\r\n\r\n\t\tHRESULT hr = getGlobalIUIAutomation()->ElementFromHandle(hwnd, &pElement) ;\r\n\t\tif (SUCCEEDED(hr))\r\n\t\t\treturn pElement ;\r\n\t\telse {\r\n\t\t\tprintf(\"RA_ElementFromHandle: Cannot find element from handle 0x%x. HRESULT was 0x%x\\r\\n\", hwnd, hr) ;\r\n\t\t\treturn NULL ;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int RA_CurrentIsOffscreen(IUIAutomationElement *pElement, int *visible) {\r\n\t\tBOOL offscreen;\r\n\r\n\t\tHRESULT hr = pElement->get_CurrentIsOffscreen(&offscreen) ;\r\n\t\tif (SUCCEEDED(hr)) {\r\n\t\t\tif(offscreen){\r\n\t\t\t\t*visible = 1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t*visible = 0;\r\n\t\t\t}\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tprintf(\"RA_CurrentIsOffscreen: get_CurrentIsOffscreen failed 0x%x\\r\\n\", hr) ;\r\n\t\t\treturn 0 ;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsSet(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsToggled(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tDebug::WriteLine(\"IsSet: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsSelected(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsSelected(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tDebug::WriteLine(\"IsSelected: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool RA_Click(const FindInformation& findInformation, char* errorInfo, const int errorInfoSize) {\r\n\t\ttry {\r\n\t\t\treturn Clicker::Click(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tif( errorInfo ) {\r\n\t\t\t\tStringHelper::CopyToUnmanagedString(e->ToString(), errorInfo, errorInfoSize);\r\n\t\t\t}\r\n\r\n return false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_ExpandItemByValue(const FindInformation& findInformation, const char* whichItem) {\r\n\t\ttry {\r\n\t\t\tauto expander = gcnew Expander(Locator::FindFor(findInformation));\r\n expander->Expand(gcnew String(whichItem));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_ExpandItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {\r\n\t\ttry {\r\n\t\t\tauto expander = gcnew Expander(Locator::FindFor(findInformation));\r\n\t\t\texpander->Expand(whichItemIndex);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_CollapseItemByValue(const FindInformation& findInformation, const char* whichItem) {\r\n\t\ttry {\r\n\t\t\tauto collapser = gcnew Collapser(Locator::FindFor(findInformation));\r\n\t\t\tcollapser->Collapse(gcnew String(whichItem));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_CollapseItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {\r\n\t\ttry {\r\n\t\t\tauto collapser = gcnew Collapser(Locator::FindFor(findInformation));\r\n\t\t\tcollapser->Collapse(whichItemIndex);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n}\r\nRevert \"get rid of RA_ClickMouse \/ RA_MoveMouse\"\/\/ UiaDll.cpp : Defines the exported functions for the DLL application.\r\n\/\/\r\n\r\n#include \"stdafx.h\"\r\n#include \"Locator.h\"\r\n#include \"DynamicAssemblyResolver.h\"\r\n#include \"StringHelper.h\"\r\n\r\nIUIAutomation* getGlobalIUIAutomation() ;\r\n\r\nusing namespace RAutomation::UIA;\r\nusing namespace RAutomation::UIA::Controls;\r\nusing namespace RAutomation::UIA::Extensions;\r\n\r\nusing namespace System::Diagnostics;\r\n\r\nextern \"C\" {\r\n\t__declspec(dllexport) void initialize(char* privateAssemblyDirectory) {\r\n\t\tDynamicAssemblyResolver::PrivatePath = gcnew String(privateAssemblyDirectory);\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool ElementExists(const FindInformation& findInformation) {\r\n return Element::Exists(Locator::FindFor(findInformation));\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int NativeWindowHandle(const FindInformation& findInformation) { \r\n return Element::NativeWindowHandle(Locator::FindFor(findInformation));\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int HandleFromPoint(int xCoord, int yCoord) {\r\n\t\tauto element = AutomationElement::FromPoint(Point((double)xCoord, (double)yCoord));\r\n\t\treturn Element::NativeWindowHandle(element);\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int BoundingRectangle(const FindInformation& findInformation, long *rectangle) {\r\n\t\ttry {\r\n\t\t\tauto boundary = Element::BoundingRectangle(Locator::FindFor(findInformation));\r\n\r\n\t\t\trectangle[0] = (long)boundary.Left;\r\n\t\t\trectangle[1] = (long)boundary.Top;\r\n\t\t\trectangle[2] = (long)boundary.Right;\r\n\t\t\trectangle[3] = (long)boundary.Bottom;\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\tcatch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"BoundingRectangle: {0}\", e->Message);\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int ControlType(const FindInformation& findInformation) {\r\n\t\ttry {\r\n return Element::ControlType(Locator::FindFor(findInformation))->Id;\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"ControlType: {0}\", e->Message);\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int ProcessId(const FindInformation& findInformation) {\r\n\t\ttry {\r\n return Element::ProcessId(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"ProcessId: {0}\", e->Message);\r\n\t\t\treturn 0;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void Name(const FindInformation& findInformation, char* name, const int nameLength) {\r\n\t\ttry {\r\n auto currentName = Element::Name(Locator::FindFor(findInformation));\r\n\t StringHelper::CopyToUnmanagedString(currentName, name, nameLength);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"Name: {0}\", e->Message);\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void ClassName(const FindInformation& findInformation, char* className, const int classNameLength) {\r\n\t\ttry {\r\n auto currentClassName = Element::ClassName(Locator::FindFor(findInformation));\r\n\t\t\tStringHelper::CopyToUnmanagedString(currentClassName, className, classNameLength);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"ClassName: {0}\", e->Message);\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsEnabled(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsEnabled(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"IsEnabled: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsFocused(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsFocused(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"IsFocused: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool SetControlFocus(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\tLocator::FindFor(findInformation)->SetFocus();\r\n\t\t\treturn true;\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(\"IsFocused: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int GetClassNames(const FindInformation& findInformation, const char* classNames[]) {\r\n\t\tauto allChildren = Locator::FindFor(findInformation)->FindAll(System::Windows::Automation::TreeScope::Subtree, Condition::TrueCondition);\r\n\r\n\t\tif( NULL != classNames ) {\r\n\t\t\tStringHelper::CopyClassNames(allChildren, classNames);\r\n\t\t}\r\n\r\n\t\treturn allChildren->Count;\r\n\t}\r\n\r\n\t__declspec ( dllexport ) IUIAutomationElement *RA_ElementFromHandle(HWND hwnd) {\r\n\t\tIUIAutomationElement *pElement ;\r\n\r\n\t\tHRESULT hr = getGlobalIUIAutomation()->ElementFromHandle(hwnd, &pElement) ;\r\n\t\tif (SUCCEEDED(hr))\r\n\t\t\treturn pElement ;\r\n\t\telse {\r\n\t\t\tprintf(\"RA_ElementFromHandle: Cannot find element from handle 0x%x. HRESULT was 0x%x\\r\\n\", hwnd, hr) ;\r\n\t\t\treturn NULL ;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) long RA_ClickMouse() {\r\n\t\tmouse_event(MOUSEEVENTF_LEFTDOWN, 0, 0, 0, 0);\r\n\t\tmouse_event(MOUSEEVENTF_LEFTUP, 0, 0, 0, 0);\r\n\t\treturn 0;\r\n\t}\r\n\r\n\t__declspec ( dllexport ) long RA_MoveMouse(int x, int y) {\r\n\t\treturn SetCursorPos(x,y);\r\n\t}\r\n\r\n\t__declspec ( dllexport ) int RA_CurrentIsOffscreen(IUIAutomationElement *pElement, int *visible) {\r\n\t\tBOOL offscreen;\r\n\r\n\t\tHRESULT hr = pElement->get_CurrentIsOffscreen(&offscreen) ;\r\n\t\tif (SUCCEEDED(hr)) {\r\n\t\t\tif(offscreen){\r\n\t\t\t\t*visible = 1;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\t*visible = 0;\r\n\t\t\t}\r\n\t\t\treturn 1;\r\n\t\t}\r\n\t\telse {\r\n\t\t\tprintf(\"RA_CurrentIsOffscreen: get_CurrentIsOffscreen failed 0x%x\\r\\n\", hr) ;\r\n\t\t\treturn 0 ;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsSet(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsToggled(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tDebug::WriteLine(\"IsSet: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool IsSelected(const FindInformation& findInformation) {\r\n\t\ttry {\r\n\t\t\treturn Element::IsSelected(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tDebug::WriteLine(\"IsSelected: {0}\", e->Message);\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) bool RA_Click(const FindInformation& findInformation, char* errorInfo, const int errorInfoSize) {\r\n\t\ttry {\r\n\t\t\treturn Clicker::Click(Locator::FindFor(findInformation));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tif( errorInfo ) {\r\n\t\t\t\tStringHelper::CopyToUnmanagedString(e->ToString(), errorInfo, errorInfoSize);\r\n\t\t\t}\r\n\r\n return false;\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_ExpandItemByValue(const FindInformation& findInformation, const char* whichItem) {\r\n\t\ttry {\r\n\t\t\tauto expander = gcnew Expander(Locator::FindFor(findInformation));\r\n expander->Expand(gcnew String(whichItem));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_ExpandItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {\r\n\t\ttry {\r\n\t\t\tauto expander = gcnew Expander(Locator::FindFor(findInformation));\r\n\t\t\texpander->Expand(whichItemIndex);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_CollapseItemByValue(const FindInformation& findInformation, const char* whichItem) {\r\n\t\ttry {\r\n\t\t\tauto collapser = gcnew Collapser(Locator::FindFor(findInformation));\r\n\t\t\tcollapser->Collapse(gcnew String(whichItem));\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n\r\n\t__declspec ( dllexport ) void RA_CollapseItemByIndex(const FindInformation& findInformation, const int whichItemIndex) {\r\n\t\ttry {\r\n\t\t\tauto collapser = gcnew Collapser(Locator::FindFor(findInformation));\r\n\t\t\tcollapser->Collapse(whichItemIndex);\r\n\t\t} catch(Exception^ e) {\r\n\t\t\tConsole::WriteLine(e->ToString());\r\n\t\t}\r\n\t}\r\n}\r\n<|endoftext|>"} {"text":"#include \"calc.h\"\n#include \n#include \n#include \n#include \n\nint sign(const int i) {\n\treturn (int(0) < i) - (i < int(0));\n}\n\nvoid throw_overflow_if(const bool condition) {\n\tif (condition) throw std::invalid_argument { \"overflow\" };\n}\n\n\/\/ Calculates the result of two numbers a and b and basic math operator.\nint calc(const int a, const int b, const char operator_symbol) {\n\tusing int_limits = std::numeric_limits;\n\tconst int int_max { int_limits::max() }, int_min { int_limits::min() };\n\n\tswitch (operator_symbol) {\n\t\tcase '*': {\n\t\t\tint result { a * b };\n\t\t\tthrow_overflow_if((sign(a) * sign(b) != sign(result)) || (a != 0 && result \/ a != b));\n\t\t\treturn result;\n\t\t}\n\t\tcase '\/':\n\t\t\tif (b == 0) throw std::domain_error{\"division by zero\"};\n\t\t\treturn a \/ b;\n\t\tcase '+':\n\t\t\tthrow_overflow_if((a >= 0) && (int_max - a < b));\n\t\t\tthrow_overflow_if((a < 0) && (b < int_min - a));\n\t\t\treturn a + b;\n\t\tcase '-': {\n\t\t\tthrow_overflow_if((a >= 0) && (int_max - a < -b));\n\t\t\tthrow_overflow_if((a < 0) && (-b < int_min - a));\n\t\t\treturn a - b;\n\t\t}\n\t\tcase '%':\n\t\t\tif (b == 0) throw std::domain_error{\"division by zero\"};\n\t\t\treturn a % b;\n\t}\n\n\tauto reason = std::string(\"invalid operator: \");\n\treason.push_back(operator_symbol);\n\tthrow std::invalid_argument{reason};\n}\n\nint calc(std::istream &input) {\n\tint a {0}, b {0};\n\tchar operator_symbol { };\n\tinput >> a >> operator_symbol >> b;\n\tif (input.fail())\n\t\t\tthrow std::invalid_argument{ \"malformed input term\"};\n\treturn calc(a, b, operator_symbol);\n}\nrecognize malformed input terms#include \"calc.h\"\n#include \n#include \n#include \n#include \n\nint sign(const int i) {\n\treturn (int(0) < i) - (i < int(0));\n}\n\nvoid throw_overflow_if(const bool condition) {\n\tif (condition) throw std::invalid_argument { \"overflow\" };\n}\n\n\/\/ Calculates the result of two numbers a and b and basic math operator.\nint calc(const int a, const int b, const char operator_symbol) {\n\tusing int_limits = std::numeric_limits;\n\tconst int int_max { int_limits::max() }, int_min { int_limits::min() };\n\n\tswitch (operator_symbol) {\n\t\tcase '*': {\n\t\t\tint result { a * b };\n\t\t\tthrow_overflow_if((sign(a) * sign(b) != sign(result)) || (a != 0 && result \/ a != b));\n\t\t\treturn result;\n\t\t}\n\t\tcase '\/':\n\t\t\tif (b == 0) throw std::domain_error{\"division by zero\"};\n\t\t\treturn a \/ b;\n\t\tcase '+':\n\t\t\tthrow_overflow_if((a >= 0) && (int_max - a < b));\n\t\t\tthrow_overflow_if((a < 0) && (b < int_min - a));\n\t\t\treturn a + b;\n\t\tcase '-': {\n\t\t\tthrow_overflow_if((a >= 0) && (int_max - a < -b));\n\t\t\tthrow_overflow_if((a < 0) && (-b < int_min - a));\n\t\t\treturn a - b;\n\t\t}\n\t\tcase '%':\n\t\t\tif (b == 0) throw std::domain_error{\"division by zero\"};\n\t\t\treturn a % b;\n\t}\n\n\tauto reason = std::string(\"invalid operator: \");\n\treason.push_back(operator_symbol);\n\tthrow std::invalid_argument{reason};\n}\n\nint calc(std::istream &input) {\n\tint a {0}, b {0};\n\tchar operator_symbol { };\n\tstd::string term {};\n\tstd::getline(input, term);\n\tstd::istringstream term_input { term };\n\tterm_input >> a >> operator_symbol >> b;\n\tif (term_input.fail() || !term_input.eof())\n\t\t\tthrow std::invalid_argument{ \"malformed input term\"};\n\treturn calc(a, b, operator_symbol);\n}\n<|endoftext|>"} {"text":"\/************************************************************\n\n cvcontourtree.cpp -\n\n $Author: lsxi $\n\n Copyright (C) 2007 Masakazu Yonekura\n\n************************************************************\/\n#include \"cvcontour.h\"\n\/*\n * Document-class: OpenCV::CvContourTree\n *\n * Contour tree. CvContour#create_tree\n *\n * C structure is here.\n * typedef struct CvContourTree {\n * CV_SEQUENCE_FIELDS()\n * CvPoint p1;\n * CvPoint p2;\n * } CvContourTree;\n * \n *\/\n__NAMESPACE_BEGIN_OPENCV\n__NAMESPACE_BEGIN_CVCONTOURTREE\n\nVALUE rb_klass;\n\nVALUE\nrb_class()\n{\n return rb_klass;\n}\n\nvoid\ndefine_ruby_class()\n{\n if (rb_klass)\n return;\n \/* \n * opencv = rb_define_module(\"OpenCV\");\n * cvseq = rb_define_class_under(opencv, \"CvSeq\");\n *\n * note: this comment is used by rdoc.\n *\/\n VALUE opencv = rb_module_opencv();\n VALUE cvseq = cCvSeq::rb_class();\n \n rb_klass = rb_define_class_under(opencv, \"CvContourTree\", cvseq);\n rb_define_method(rb_klass, \"p1\", RUBY_METHOD_FUNC(rb_p1), 0);\n rb_define_method(rb_klass, \"p2\", RUBY_METHOD_FUNC(rb_p2), 0);\n rb_define_method(rb_klass, \"contour\", RUBY_METHOD_FUNC(rb_contour), 1);\n}\n\nVALUE\nrb_p1(VALUE self)\n{\n return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p1, self);\n}\n\nVALUE\nrb_p2(VALUE self)\n{\n return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p2, self);\n}\n\n\/*\n * call-seq:\n * contour([criteria = 0]<\/i>) -> cvcontour\n *\n * Restores the contour from its binary tree representation.\n * The parameter criteria determines the accuracy and\/or the number of tree levels\n * used for reconstruction, so it is possible to build approximated contour.\n *\/\nVALUE\nrb_contour(VALUE self, VALUE criteria)\n{\n VALUE storage = cCvMemStorage::new_object();\n CvSeq *contour = NULL;\n try {\n contour = cvContourFromContourTree(CVCONTOURTREE(self), CVMEMSTORAGE(storage),\n\t\t\t\t VALUE_TO_CVTERMCRITERIA(criteria));\n }\n catch (cv::Exception& e) {\n raise_cverror(e);\n }\n return cCvSeq::new_sequence(cCvContour::rb_class(), contour, cCvPoint::rb_class(), storage);\n}\n\n__NAMESPACE_END_CVCONTOURTREE\n__NAMESPACE_END_OPENCV\nadd documents of CvContourTree\/************************************************************\n\n cvcontourtree.cpp -\n\n $Author: lsxi $\n\n Copyright (C) 2007 Masakazu Yonekura\n\n************************************************************\/\n#include \"cvcontour.h\"\n\/*\n * Document-class: OpenCV::CvContourTree\n *\n * Contour tree\n * @see CvContour#create_tree\n *\/\n__NAMESPACE_BEGIN_OPENCV\n__NAMESPACE_BEGIN_CVCONTOURTREE\n\nVALUE rb_klass;\n\nVALUE\nrb_class()\n{\n return rb_klass;\n}\n\nvoid\ndefine_ruby_class()\n{\n if (rb_klass)\n return;\n \/* \n * opencv = rb_define_module(\"OpenCV\");\n * cvseq = rb_define_class_under(opencv, \"CvSeq\");\n *\n * note: this comment is used by rdoc.\n *\/\n VALUE opencv = rb_module_opencv();\n VALUE cvseq = cCvSeq::rb_class();\n \n rb_klass = rb_define_class_under(opencv, \"CvContourTree\", cvseq);\n rb_define_method(rb_klass, \"p1\", RUBY_METHOD_FUNC(rb_p1), 0);\n rb_define_method(rb_klass, \"p2\", RUBY_METHOD_FUNC(rb_p2), 0);\n rb_define_method(rb_klass, \"contour\", RUBY_METHOD_FUNC(rb_contour), 1);\n}\n\n\/*\n * Returns the first point of the binary tree root segment\n * @overload p1\n * @return [CvPoint] First point of the binary tree root segment\n *\/\nVALUE\nrb_p1(VALUE self)\n{\n return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p1, self);\n}\n\n\/*\n * Returns the last point of the binary tree root segment\n * @overload p2\n * @return [CvPoint] Last point of the binary tree root segment\n *\/\nVALUE\nrb_p2(VALUE self)\n{\n return REFER_OBJECT(cCvPoint::rb_class(), &CVCONTOURTREE(self)->p2, self);\n}\n\n\/*\n * Restores the contour from its binary tree representation.\n *\n * The parameter +criteria+ determines the accuracy and\/or the number of tree levels\n * used for reconstruction, so it is possible to build approximated contour.\n * @overload contour(criteria = 0)\n * @param criteria [Integer] Criteria, where to stop reconstruction\n * @return [CvContour] Contour tree\n * @opencv_func cvContourFromContourTree\n *\/\nVALUE\nrb_contour(VALUE self, VALUE criteria)\n{\n VALUE storage = cCvMemStorage::new_object();\n CvSeq *contour = NULL;\n try {\n contour = cvContourFromContourTree(CVCONTOURTREE(self), CVMEMSTORAGE(storage),\n\t\t\t\t VALUE_TO_CVTERMCRITERIA(criteria));\n }\n catch (cv::Exception& e) {\n raise_cverror(e);\n }\n return cCvSeq::new_sequence(cCvContour::rb_class(), contour, cCvPoint::rb_class(), storage);\n}\n\n__NAMESPACE_END_CVCONTOURTREE\n__NAMESPACE_END_OPENCV\n<|endoftext|>"} {"text":"\n#include \"view.hpp\"\n#include \"view\/shade.hpp\"\n\nnamespace View {\n\n\tvoid printErrors(const char *prefix = \"OpenGL error(s): \") {\n\t\tGLenum err;\n\t\tbool once = false;\n\t\tstd::ostringstream oss;\n\t\t\n\t\twhile(!(err = glGetError())) {\n\t\t\tonce = true;\n\t\t\tswitch(err) {\n\t\t\tcase GL_INVALID_ENUM:\n\t\t\t\toss << \"invalid enum; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_INVALID_VALUE:\n\t\t\t\toss << \"invalid value; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_INVALID_OPERATION:\n\t\t\t\toss << \"invalid operation; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_STACK_OVERFLOW:\n\t\t\t\toss << \"stack overflow; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_STACK_UNDERFLOW:\n\t\t\t\toss << \"stack underflow; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_OUT_OF_MEMORY:\n\t\t\t\toss << \"out of memory; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_INVALID_FRAMEBUFFER_OPERATION:\n\t\t\t\toss << \"invalid framebuffer operation; \";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t \n\t\tif(once) {\n\t\t\tstd::cout << prefix << oss.str() << std::endl;\n\t\t}\n\t}\n\n\tvoid view::setUniforms(void) {\n\t\tint w, h;\n\t\tglfwGetFramebufferSize(win, &w, &h);\n\t\tfloat mag = float(1\/tan(fov*M_PI\/180));\n\t\tfloat projection[]{\n\t\t\t\tmag*h\/w, 0, 0, 0, 0, mag, 0, 0,\n\t\t\t\t0, 0, (far+near)\/(far-near), -1,\n\t\t\t\t0, 0, 2*far*near\/(far-near), 0\n\t\t};\n\t\tglUniformMatrix4fv(projID, 1, GL_TRUE, projection);\n\n\t\t\/* TODO - static not intended, just persistence;\n \t\t * all of the data here should be passed or shared *\/\n\t\tstatic float theta = 0;\n\t\ttheta += M_PI\/180;\n\t\tfloat c = cos(theta), s = sin(theta);\n\t\tfloat modelData[]{\n\t\t\t\tc, 0,-s, 0,\n\t\t\t\t0, 1, 0, 0,\n\t\t\t\ts, 0, c, c,\n\t\t\t\t0, 0, 0, 1\n\t\t}, viewData[]{\n\t\t\t\t1, 0, 0, 0,\n\t\t\t\t0, 1, 0, 0,\n\t\t\t\t0, 0, 1, 0,\n\t\t\t\t0, 0, 2, 1\n\t\t};\n\n\t\tglUniformMatrix4fv(modelID, 1, GL_TRUE, modelData);\n\t\tglUniformMatrix4fv(viewID, 1, GL_FALSE, viewData);\n\t}\n\t\n\tvoid view::redraw(void) {\n\t\tsetUniforms();\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\t\tglEnableVertexAttribArray(0);\n\t\tglEnableVertexAttribArray(1);\n\n\t\tstatic long int offset = 3*sizeof(float),\n\t\t\t\tstride = 2*offset;\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vbuf);\n\t\tglVertexAttribPointer(0, 3, GL_FLOAT,\n\t\t\t\tGL_FALSE, stride, nullptr);\n\t\tglVertexAttribPointer(1, 3, GL_FLOAT,\n\t\t\t\tGL_FALSE, stride, (void*) offset);\n\n\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);\n\t\tglDrawElements(GL_TRIANGLES, nTriangles*3,\n\t\t\t\tGL_UNSIGNED_INT, nullptr);\n\n\t\tglDisableVertexAttribArray(1);\n\t\tglDisableVertexAttribArray(0);\n\n\t\tglfwSwapBuffers(win);\n\n\t\tstatic int nFrames = -1;\n\t\tnFrames++;\n\t\tstatic double t0 = glfwGetTime();\n\t\tdouble t1 = glfwGetTime(), dt = t1-t0;\n\t\tif(dt >= 1) {\n\t\t\tstd::cout << (nFrames\/dt) << \"FPS\" << std::endl;\n\t\t\tt0 = t1;\n\t\t\tnFrames = -1;\n\t\t}\n\t}\n\n\tvoid view::run(std::function update,\n\t\t\tstd::function quit) {\n\t\tif(valid && win) {\n\t\t\tglfwMakeContextCurrent(win);\n\t\t\twhile(true) {\n\t\t\t\tglfwPollEvents();\n\t\t\t\tif(glfwWindowShouldClose(win)) {\n\t\t\t\t\tquit();\n\t\t\t\t} else if(update()) {\n\t\t\t\t\tredraw();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tview::view(void) {\n\t\tusing Header = Model::Ply::Header;\n\t\tusing Element = Model::Ply::Element;\n\n\t\tstatic constexpr const char \n\t\t\t*vpath = \"resources\/shade.vert\",\n\t\t\t*fpath = \"resources\/shade.frag\",\n\t\t\t*mpath = \"resources\/bunny.ply\";\n\n\t\tHeader model(mpath);\n\t\tif(!glfwInit()) {\n\t\t\tstd::cout << \"Could not initialize GLFW.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\t\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\t\twin = glfwCreateWindow(512, 512, \"View\", NULL, NULL);\n\n\t\tif(!win) {\n\t\t\tstd::cout << \"Could not create window.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tglfwMakeContextCurrent(win);\n\t\tif(gl3wInit()) {\n\t\t\tstd::cout << \"Could not initialize gl3w.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tglfwSetWindowSizeCallback(win, \n\t\t\t[](GLFWwindow*, int w, int h){\n\t\t\t\tglViewport(0, 0, w, h);\n\t\t\t}\n\t\t);\n\t\t\n\t\tglEnable(GL_DEPTH_TEST);\n\t\tglEnable(GL_CULL_FACE);\n\n\t\tglGenVertexArrays(1, &vaID);\n\t\tglBindVertexArray(vaID);\n\n\t\tif(model.status) {\n\t\t\tstd::cout << model.statusContext << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tauto start = begin(model.elements), \n\t\t\t\t stop = end(model.elements);\n\t\tauto getVertices = [](Element const& el) -> bool {\n\t\t\treturn el.name == \"vertex\" && !el.has_list\n\t\t\t\t&& el.properties.size() == 6;\n\t\t};\n\t\tauto getIndices = [](Element const& el) -> bool {\n\t\t\tint sz = el.properties.size();\n\t\t\treturn el.name == \"face\"\n\t\t\t\t&& (el.has_list ? sz==1 : sz==3);\n\t\t};\n\t\tauto vertices = std::find_if(start, stop, getVertices),\n\t\t\t\t indices = std::find_if(start, stop, getIndices);\n\t\tif(vertices == stop || indices == stop) {\n\t\t\tvalid = false;\n\t\t\tstd::cout << \"The model is valid, but does not match \"\n\t\t\t\t\"the anticipated structure.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tglGenBuffers(1, &vbuf);\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vbuf);\n\t\tglBufferData(GL_ARRAY_BUFFER, vertices->data.size(),\n\t\t\t\t(void*)(&vertices->data[0]), GL_STATIC_DRAW);\n\n\t\tglGenBuffers(1, &ibuf);\n\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);\n\t\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->data.size(),\n\t\t\t\t(void*)(&indices->data[0]), GL_STATIC_DRAW);\n\t\tnTriangles = indices -> instances;\n\t\t\n\t\tprogID = glCreateProgram();\n\t\tif(!link(vpath, fpath, progID)) {\n\t\t\tstd::cout << \"Could not compile\/link shader(s).\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tmodelID = glGetUniformLocation(progID, \"model\");\n\t\tviewID = glGetUniformLocation(progID, \"view\");\n\t\tprojID = glGetUniformLocation(progID, \"proj\");\n\t\tglUseProgram(progID);\n\t\tvalid = true;\n\t}\n\tview::~view(void) {\n\t\tif(progID) {\n\t\t\tglDeleteProgram(progID);\n\t\t}\n\t\tglfwDestroyWindow(win);\n\t}\n}\nAdded TODO to view\n#include \"view.hpp\"\n#include \"view\/shade.hpp\"\n\nnamespace View {\n\n\tvoid printErrors(const char *prefix = \"OpenGL error(s): \") {\n\t\tGLenum err;\n\t\tbool once = false;\n\t\tstd::ostringstream oss;\n\t\t\n\t\twhile(!(err = glGetError())) {\n\t\t\tonce = true;\n\t\t\tswitch(err) {\n\t\t\tcase GL_INVALID_ENUM:\n\t\t\t\toss << \"invalid enum; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_INVALID_VALUE:\n\t\t\t\toss << \"invalid value; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_INVALID_OPERATION:\n\t\t\t\toss << \"invalid operation; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_STACK_OVERFLOW:\n\t\t\t\toss << \"stack overflow; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_STACK_UNDERFLOW:\n\t\t\t\toss << \"stack underflow; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_OUT_OF_MEMORY:\n\t\t\t\toss << \"out of memory; \";\n\t\t\t\tbreak;\n\t\t\tcase GL_INVALID_FRAMEBUFFER_OPERATION:\n\t\t\t\toss << \"invalid framebuffer operation; \";\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\t \n\t\tif(once) {\n\t\t\tstd::cout << prefix << oss.str() << std::endl;\n\t\t}\n\t}\n\n\tvoid view::setUniforms(void) {\n\t\tint w, h;\n\t\tglfwGetFramebufferSize(win, &w, &h);\n\t\tfloat mag = float(1\/tan(fov*M_PI\/180));\n\t\tfloat projection[]{\n\t\t\t\tmag*h\/w, 0, 0, 0, 0, mag, 0, 0,\n\t\t\t\t0, 0, (far+near)\/(far-near), -1,\n\t\t\t\t0, 0, 2*far*near\/(far-near), 0\n\t\t};\n\t\tglUniformMatrix4fv(projID, 1, GL_TRUE, projection);\n\n\t\t\/* TODO - static not intended, just persistence;\n \t\t * all of the data here should be passed or shared *\/\n\t\tstatic float theta = 0;\n\t\ttheta += M_PI\/180;\n\t\tfloat c = cos(theta), s = sin(theta);\n\t\tfloat modelData[]{\n\t\t\t\tc, 0,-s, 0,\n\t\t\t\t0, 1, 0, 0,\n\t\t\t\ts, 0, c, c,\n\t\t\t\t0, 0, 0, 1\n\t\t}, viewData[]{\n\t\t\t\t1, 0, 0, 0,\n\t\t\t\t0, 1, 0, 0,\n\t\t\t\t0, 0, 1, 0,\n\t\t\t\t0, 0, 2, 1\n\t\t};\n\n\t\tglUniformMatrix4fv(modelID, 1, GL_TRUE, modelData);\n\t\tglUniformMatrix4fv(viewID, 1, GL_FALSE, viewData);\n\t}\n\t\n\tvoid view::redraw(void) {\n\t\tsetUniforms();\n\t\tglClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n\t\tglEnableVertexAttribArray(0);\n\t\tglEnableVertexAttribArray(1);\n\n\t\tstatic long int offset = 3*sizeof(float),\n\t\t\t\tstride = 2*offset;\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vbuf);\n\t\tglVertexAttribPointer(0, 3, GL_FLOAT,\n\t\t\t\tGL_FALSE, stride, nullptr);\n\t\tglVertexAttribPointer(1, 3, GL_FLOAT,\n\t\t\t\tGL_FALSE, stride, (void*) offset);\n\n\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);\n\t\tglDrawElements(GL_TRIANGLES, nTriangles*3,\n\t\t\t\tGL_UNSIGNED_INT, nullptr);\n\n\t\tglDisableVertexAttribArray(1);\n\t\tglDisableVertexAttribArray(0);\n\n\t\tglfwSwapBuffers(win);\n\n\t\tstatic int nFrames = -1;\n\t\tnFrames++;\n\t\tstatic double t0 = glfwGetTime();\n\t\tdouble t1 = glfwGetTime(), dt = t1-t0;\n\t\tif(dt >= 1) {\n\t\t\tstd::cout << (nFrames\/dt) << \"FPS\" << std::endl;\n\t\t\tt0 = t1;\n\t\t\tnFrames = -1;\n\t\t}\n\t}\n\n\tvoid view::run(std::function update,\n\t\t\tstd::function quit) {\n\t\tif(valid && win) {\n\t\t\tglfwMakeContextCurrent(win);\n\t\t\twhile(true) {\n\t\t\t\tglfwPollEvents();\n\t\t\t\tif(glfwWindowShouldClose(win)) {\n\t\t\t\t\tquit();\n\t\t\t\t} else if(update()) {\n\t\t\t\t\tredraw();\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tview::view(void) {\n\t\tusing Header = Model::Ply::Header;\n\t\tusing Element = Model::Ply::Element;\n\n\t\t\/\/ TODO - safe model and shader loading at runtime\n\t\tstatic constexpr const char \n\t\t\t*vpath = \"resources\/shade.vert\",\n\t\t\t*fpath = \"resources\/shade.frag\",\n\t\t\t*mpath = \"resources\/bunny.ply\";\n\n\t\tHeader model(mpath);\n\t\tif(!glfwInit()) {\n\t\t\tstd::cout << \"Could not initialize GLFW.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);\n\t\tglfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);\n\t\tglfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);\n\t\twin = glfwCreateWindow(512, 512, \"View\", NULL, NULL);\n\n\t\tif(!win) {\n\t\t\tstd::cout << \"Could not create window.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tglfwMakeContextCurrent(win);\n\t\tif(gl3wInit()) {\n\t\t\tstd::cout << \"Could not initialize gl3w.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tglfwSetWindowSizeCallback(win, \n\t\t\t[](GLFWwindow*, int w, int h){\n\t\t\t\tglViewport(0, 0, w, h);\n\t\t\t}\n\t\t);\n\t\t\n\t\tglEnable(GL_DEPTH_TEST);\n\t\tglEnable(GL_CULL_FACE);\n\n\t\tglGenVertexArrays(1, &vaID);\n\t\tglBindVertexArray(vaID);\n\n\t\tif(model.status) {\n\t\t\tstd::cout << model.statusContext << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tauto start = begin(model.elements), \n\t\t\t\t stop = end(model.elements);\n\t\tauto getVertices = [](Element const& el) -> bool {\n\t\t\treturn el.name == \"vertex\" && !el.has_list\n\t\t\t\t&& el.properties.size() == 6;\n\t\t};\n\t\tauto getIndices = [](Element const& el) -> bool {\n\t\t\tint sz = el.properties.size();\n\t\t\treturn el.name == \"face\"\n\t\t\t\t&& (el.has_list ? sz==1 : sz==3);\n\t\t};\n\t\tauto vertices = std::find_if(start, stop, getVertices),\n\t\t\t\t indices = std::find_if(start, stop, getIndices);\n\t\tif(vertices == stop || indices == stop) {\n\t\t\tvalid = false;\n\t\t\tstd::cout << \"The model is valid, but does not match \"\n\t\t\t\t\"the anticipated structure.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\tglGenBuffers(1, &vbuf);\n\t\tglBindBuffer(GL_ARRAY_BUFFER, vbuf);\n\t\tglBufferData(GL_ARRAY_BUFFER, vertices->data.size(),\n\t\t\t\t(void*)(&vertices->data[0]), GL_STATIC_DRAW);\n\n\t\tglGenBuffers(1, &ibuf);\n\t\tglBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibuf);\n\t\tglBufferData(GL_ELEMENT_ARRAY_BUFFER, indices->data.size(),\n\t\t\t\t(void*)(&indices->data[0]), GL_STATIC_DRAW);\n\t\tnTriangles = indices -> instances;\n\t\t\n\t\tprogID = glCreateProgram();\n\t\tif(!link(vpath, fpath, progID)) {\n\t\t\tstd::cout << \"Could not compile\/link shader(s).\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\tmodelID = glGetUniformLocation(progID, \"model\");\n\t\tviewID = glGetUniformLocation(progID, \"view\");\n\t\tprojID = glGetUniformLocation(progID, \"proj\");\n\t\tglUseProgram(progID);\n\t\tvalid = true;\n\t}\n\tview::~view(void) {\n\t\tif(progID) {\n\t\t\tglDeleteProgram(progID);\n\t\t}\n\t\tglfwDestroyWindow(win);\n\t}\n}\n<|endoftext|>"} {"text":"Adapt loplugin:derefnullptr to old Clang versions<|endoftext|>"} {"text":"\/\/ Copyright (C) 2017, 2018 Rob Caelers \n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"loopp\/net\/TLSStream.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"loopp\/net\/NetworkErrors.hpp\"\n\n#include \"lwip\/sockets.h\"\n#include \"lwip\/sys.h\"\n\nextern \"C\"\n{\n#include \"esp_heap_caps.h\"\n#include \"mbedtls\/esp_debug.h\"\n}\n\n#include \"esp_log.h\"\n\nstatic const char tag[] = \"NET\";\n\nusing namespace loopp;\nusing namespace loopp::net;\n\nTLSStream::TLSStream(std::shared_ptr loop) : Stream(loop), loop(loop)\n{\n mbedtls_net_init(&server_fd);\n mbedtls_ssl_init(&ssl);\n mbedtls_ssl_config_init(&config);\n\n mbedtls_x509_crt_init(&client_crt);\n mbedtls_x509_crt_init(&ca_crt);\n mbedtls_pk_init(&client_key);\n\n#ifdef CONFIG_MBEDTLS_DEBUG\n mbedtls_esp_enable_debug_log(&config, 4);\n#endif\n\n init_entropy();\n}\n\nTLSStream::~TLSStream()\n{\n if (server_fd.fd != -1)\n {\n ::close(server_fd.fd);\n loop->unnotify(server_fd.fd);\n }\n\n mbedtls_net_free(&server_fd);\n mbedtls_x509_crt_free(&client_crt);\n mbedtls_x509_crt_free(&ca_crt);\n mbedtls_pk_free(&client_key);\n mbedtls_ssl_config_free(&config);\n mbedtls_ctr_drbg_free(&ctr_drbg);\n mbedtls_entropy_free(&entropy);\n}\n\nvoid\nTLSStream::set_client_certificate(const char *cert, const char *key)\n{\n parse_cert(&client_crt, cert);\n parse_key(&client_key, key);\n}\n\nvoid\nTLSStream::set_ca_certificate(const char *cert)\n{\n parse_cert(&ca_crt, cert);\n}\n\nvoid\nTLSStream::init_entropy()\n{\n mbedtls_entropy_init(&entropy);\n mbedtls_ctr_drbg_init(&ctr_drbg);\n\n int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);\n throw_if_failure(\"mbedtls_ctr_drbg_seed\", ret);\n}\n\nvoid\nTLSStream::parse_cert(mbedtls_x509_crt *crt, const char *cert_str)\n{\n mbedtls_x509_crt_init(crt);\n int ret = mbedtls_x509_crt_parse(crt, (const unsigned char *)cert_str, strlen(cert_str) + 1);\n throw_if_failure(\"mbedtls_x509_crt_parse\", ret);\n}\n\nvoid\nTLSStream::parse_key(mbedtls_pk_context *key, const char *key_str)\n{\n mbedtls_pk_init(key);\n int ret = mbedtls_pk_parse_key(key, (const unsigned char *)key_str, strlen(key_str) + 1, (const unsigned char *)\"\", 0);\n throw_if_failure(\"mbedtls_x509_crt_parse\", ret);\n}\n\nint\nTLSStream::socket_read(uint8_t *buffer, std::size_t count)\n{\n int ret = mbedtls_ssl_read(&ssl, buffer, count);\n\n if (ret == MBEDTLS_ERR_SSL_WANT_READ)\n {\n ret = -EAGAIN;\n }\n\n return ret;\n}\n\nint\nTLSStream::socket_write(uint8_t *buffer, std::size_t count)\n{\n int ret = mbedtls_ssl_write(&ssl, buffer, count);\n\n if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)\n {\n ret = -EAGAIN;\n }\n\n return ret;\n}\n\nvoid\nTLSStream::socket_close()\n{\n int ret = 0;\n do\n {\n ret = mbedtls_ssl_close_notify(&ssl);\n }\n while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);\n}\n\nvoid\nTLSStream::socket_on_connected(std::string host, connect_slot_t slot)\n{\n ESP_LOGD(tag, \"Connected. Starting handshake\");\n\n server_fd.fd = get_socket();\n\n try\n {\n int ret = mbedtls_ssl_set_hostname(&ssl, host.c_str());\n throw_if_failure(\"mbedtls_ssl_set_hostname\", ret);\n\n ret = mbedtls_ssl_config_defaults(&config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,\n MBEDTLS_SSL_PRESET_DEFAULT);\n throw_if_failure(\"mbedtls_ssl_config_defaults\", ret);\n\n mbedtls_ssl_conf_verify(&config, verify_certificate, NULL);\n mbedtls_ssl_conf_rng(&config, mbedtls_ctr_drbg_random, &ctr_drbg);\n mbedtls_ssl_conf_authmode(&config, have_ca_cert ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_OPTIONAL);\n if (have_ca_cert)\n {\n mbedtls_ssl_conf_ca_chain(&config, &ca_crt, NULL);\n }\n if (have_ca_cert)\n {\n ret = mbedtls_ssl_conf_own_cert(&config, &client_crt, &client_key);\n throw_if_failure(\"mbedtls_ssl_conf_own_cert\", ret);\n }\n mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);\n\n ret = mbedtls_ssl_setup(&ssl, &config);\n throw_if_failure(\"mbedtls_ssl_setup\", ret);\n\n on_handshake(slot);\n }\n catch (const std::system_error &ex)\n {\n slot.call(ex.code());\n }\n}\n\nvoid\nTLSStream::on_handshake(connect_slot_t slot)\n{\n try\n {\n auto self = shared_from_this();\n\n int ret = mbedtls_ssl_handshake(&ssl);\n ESP_LOGD(tag, \"Handshake ret = %x\", -ret);\n switch (ret)\n {\n case 0:\n ESP_LOGD(tag, \"TLS Handshake complete\");\n break;\n\n case MBEDTLS_ERR_SSL_WANT_READ:\n loop->notify_read(server_fd.fd, [this, self, slot](std::error_code ec) {\n if (!ec)\n {\n on_handshake(slot);\n }\n else\n {\n slot.call(ec);\n }\n });\n break;\n\n case MBEDTLS_ERR_SSL_WANT_WRITE:\n loop->notify_write(server_fd.fd, [this, self, slot](std::error_code ec) {\n if (!ec)\n {\n on_handshake(slot);\n }\n else\n {\n slot.call(ec);\n }\n });\n break;\n\n default:\n ESP_LOGE(tag, \"TLS Handshake failed: %x\", -ret);\n throw_if_failure(\"mbedtls_ssl_handshake\", ret);\n }\n\n if (ret == 0)\n {\n ret = mbedtls_ssl_get_verify_result(&ssl);\n if (ret != 0)\n {\n char buf[512];\n mbedtls_x509_crt_verify_info(buf, sizeof(buf), \"\", ret);\n ESP_LOGE(tag, \"TLS Verify failed: %s\", buf);\n }\n\n if (mbedtls_ssl_get_peer_cert(&ssl) != NULL)\n {\n char buf[512];\n mbedtls_x509_crt_info((char *)buf, sizeof(buf) - 1, \"\", mbedtls_ssl_get_peer_cert(&ssl));\n ESP_LOGD(tag, \"Peer certificate information: %s\", buf);\n }\n\n connected_property.set(true);\n slot.call(std::error_code());\n }\n }\n catch (const std::system_error &ex)\n {\n slot.call(ex.code());\n }\n}\n\nvoid\nTLSStream::log_failure(std::string msg, int error_code)\n{\n if (error_code != 0)\n {\n char error_msg[512];\n mbedtls_strerror(error_code, error_msg, sizeof(error_msg));\n ESP_LOGE(tag, \"Error: %s %s %d\", msg.c_str(), error_msg, error_code);\n }\n}\n\nvoid\nTLSStream::throw_if_failure(std::string msg, int error_code)\n{\n if (error_code != 0)\n {\n char error_msg[512];\n mbedtls_strerror(error_code, error_msg, sizeof(error_msg));\n ESP_LOGE(tag, \"Error: %s %s %d\", msg.c_str(), error_msg, error_code);\n\n \/\/ TODO: convert errors.\n std::error_code ec(NetworkErrc::TLSProtocolError);\n throw std::system_error(ec, msg);\n }\n}\n\nint\nTLSStream::verify_certificate(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)\n{\n char buf[1024];\n ((void)data);\n\n ESP_LOGD(tag, \"Verify requested for (depth %d):\", depth);\n mbedtls_x509_crt_info(buf, sizeof(buf) - 1, \"\", crt);\n ESP_LOGD(tag, \"%s\", buf);\n\n return 0;\n}\nFix use of certificate\/\/ Copyright (C) 2017, 2018 Rob Caelers \n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in\n\/\/ all copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/ THE SOFTWARE.\n\n#include \"loopp\/net\/TLSStream.hpp\"\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"loopp\/net\/NetworkErrors.hpp\"\n\n#include \"lwip\/sockets.h\"\n#include \"lwip\/sys.h\"\n\nextern \"C\"\n{\n#include \"esp_heap_caps.h\"\n#include \"mbedtls\/esp_debug.h\"\n}\n\n#include \"esp_log.h\"\n\nstatic const char tag[] = \"NET\";\n\nusing namespace loopp;\nusing namespace loopp::net;\n\nTLSStream::TLSStream(std::shared_ptr loop) : Stream(loop), loop(loop)\n{\n mbedtls_net_init(&server_fd);\n mbedtls_ssl_init(&ssl);\n mbedtls_ssl_config_init(&config);\n\n mbedtls_x509_crt_init(&client_crt);\n mbedtls_x509_crt_init(&ca_crt);\n mbedtls_pk_init(&client_key);\n\n#ifdef CONFIG_MBEDTLS_DEBUG\n mbedtls_esp_enable_debug_log(&config, 4);\n#endif\n\n init_entropy();\n}\n\nTLSStream::~TLSStream()\n{\n if (server_fd.fd != -1)\n {\n ::close(server_fd.fd);\n loop->unnotify(server_fd.fd);\n }\n\n mbedtls_net_free(&server_fd);\n mbedtls_x509_crt_free(&client_crt);\n mbedtls_x509_crt_free(&ca_crt);\n mbedtls_pk_free(&client_key);\n mbedtls_ssl_config_free(&config);\n mbedtls_ctr_drbg_free(&ctr_drbg);\n mbedtls_entropy_free(&entropy);\n}\n\nvoid\nTLSStream::set_client_certificate(const char *cert, const char *key)\n{\n assert(cert != nullptr && key != nullptr);\n parse_cert(&client_crt, cert);\n parse_key(&client_key, key);\n have_client_cert = true;\n}\n\nvoid\nTLSStream::set_ca_certificate(const char *cert)\n{\n assert(cert != nullptr);\n parse_cert(&ca_crt, cert);\n have_ca_cert = true;\n}\n\nvoid\nTLSStream::init_entropy()\n{\n mbedtls_entropy_init(&entropy);\n mbedtls_ctr_drbg_init(&ctr_drbg);\n\n int ret = mbedtls_ctr_drbg_seed(&ctr_drbg, mbedtls_entropy_func, &entropy, NULL, 0);\n throw_if_failure(\"mbedtls_ctr_drbg_seed\", ret);\n}\n\nvoid\nTLSStream::parse_cert(mbedtls_x509_crt *crt, const char *cert_str)\n{\n mbedtls_x509_crt_init(crt);\n int ret = mbedtls_x509_crt_parse(crt, (const unsigned char *)cert_str, strlen(cert_str) + 1);\n throw_if_failure(\"mbedtls_x509_crt_parse\", ret);\n}\n\nvoid\nTLSStream::parse_key(mbedtls_pk_context *key, const char *key_str)\n{\n mbedtls_pk_init(key);\n int ret = mbedtls_pk_parse_key(key, (const unsigned char *)key_str, strlen(key_str) + 1, (const unsigned char *)\"\", 0);\n throw_if_failure(\"mbedtls_x509_crt_parse\", ret);\n}\n\nint\nTLSStream::socket_read(uint8_t *buffer, std::size_t count)\n{\n int ret = mbedtls_ssl_read(&ssl, buffer, count);\n\n if (ret == MBEDTLS_ERR_SSL_WANT_READ)\n {\n ret = -EAGAIN;\n }\n\n return ret;\n}\n\nint\nTLSStream::socket_write(uint8_t *buffer, std::size_t count)\n{\n int ret = mbedtls_ssl_write(&ssl, buffer, count);\n\n if (ret == MBEDTLS_ERR_SSL_WANT_WRITE)\n {\n ret = -EAGAIN;\n }\n\n return ret;\n}\n\nvoid\nTLSStream::socket_close()\n{\n int ret = 0;\n do\n {\n ret = mbedtls_ssl_close_notify(&ssl);\n }\n while (ret == MBEDTLS_ERR_SSL_WANT_WRITE);\n}\n\nvoid\nTLSStream::socket_on_connected(std::string host, connect_slot_t slot)\n{\n ESP_LOGD(tag, \"Connected. Starting handshake\");\n\n server_fd.fd = get_socket();\n\n try\n {\n int ret = mbedtls_ssl_set_hostname(&ssl, host.c_str());\n throw_if_failure(\"mbedtls_ssl_set_hostname\", ret);\n\n ret = mbedtls_ssl_config_defaults(&config, MBEDTLS_SSL_IS_CLIENT, MBEDTLS_SSL_TRANSPORT_STREAM,\n MBEDTLS_SSL_PRESET_DEFAULT);\n throw_if_failure(\"mbedtls_ssl_config_defaults\", ret);\n\n mbedtls_ssl_conf_verify(&config, verify_certificate, NULL);\n mbedtls_ssl_conf_rng(&config, mbedtls_ctr_drbg_random, &ctr_drbg);\n mbedtls_ssl_conf_authmode(&config, have_ca_cert ? MBEDTLS_SSL_VERIFY_REQUIRED : MBEDTLS_SSL_VERIFY_OPTIONAL);\n if (have_ca_cert)\n {\n ESP_LOGD(tag, \"Using CA cert\");\n mbedtls_ssl_conf_ca_chain(&config, &ca_crt, NULL);\n }\n if (have_client_cert)\n {\n ESP_LOGD(tag, \"Using Client cert\");\n ret = mbedtls_ssl_conf_own_cert(&config, &client_crt, &client_key);\n throw_if_failure(\"mbedtls_ssl_conf_own_cert\", ret);\n }\n mbedtls_ssl_set_bio(&ssl, &server_fd, mbedtls_net_send, mbedtls_net_recv, NULL);\n\n ret = mbedtls_ssl_setup(&ssl, &config);\n throw_if_failure(\"mbedtls_ssl_setup\", ret);\n\n on_handshake(slot);\n }\n catch (const std::system_error &ex)\n {\n slot.call(ex.code());\n }\n}\n\nvoid\nTLSStream::on_handshake(connect_slot_t slot)\n{\n try\n {\n auto self = shared_from_this();\n\n int ret = mbedtls_ssl_handshake(&ssl);\n ESP_LOGD(tag, \"Handshake ret = %x\", -ret);\n switch (ret)\n {\n case 0:\n ESP_LOGD(tag, \"TLS Handshake complete\");\n break;\n\n case MBEDTLS_ERR_SSL_WANT_READ:\n loop->notify_read(server_fd.fd, [this, self, slot](std::error_code ec) {\n if (!ec)\n {\n on_handshake(slot);\n }\n else\n {\n slot.call(ec);\n }\n });\n break;\n\n case MBEDTLS_ERR_SSL_WANT_WRITE:\n loop->notify_write(server_fd.fd, [this, self, slot](std::error_code ec) {\n if (!ec)\n {\n on_handshake(slot);\n }\n else\n {\n slot.call(ec);\n }\n });\n break;\n\n default:\n ESP_LOGE(tag, \"TLS Handshake failed: %x\", -ret);\n throw_if_failure(\"mbedtls_ssl_handshake\", ret);\n }\n\n if (ret == 0)\n {\n ret = mbedtls_ssl_get_verify_result(&ssl);\n if (ret != 0)\n {\n char buf[512];\n mbedtls_x509_crt_verify_info(buf, sizeof(buf), \"\", ret);\n ESP_LOGE(tag, \"TLS Verify failed: %s\", buf);\n }\n\n if (mbedtls_ssl_get_peer_cert(&ssl) != NULL)\n {\n char buf[512];\n mbedtls_x509_crt_info((char *)buf, sizeof(buf) - 1, \"\", mbedtls_ssl_get_peer_cert(&ssl));\n ESP_LOGD(tag, \"Peer certificate information: %s\", buf);\n }\n\n connected_property.set(true);\n slot.call(std::error_code());\n }\n }\n catch (const std::system_error &ex)\n {\n slot.call(ex.code());\n }\n}\n\nvoid\nTLSStream::log_failure(std::string msg, int error_code)\n{\n if (error_code != 0)\n {\n char error_msg[512];\n mbedtls_strerror(error_code, error_msg, sizeof(error_msg));\n ESP_LOGE(tag, \"Error: %s %s %d\", msg.c_str(), error_msg, error_code);\n }\n}\n\nvoid\nTLSStream::throw_if_failure(std::string msg, int error_code)\n{\n if (error_code != 0)\n {\n char error_msg[512];\n mbedtls_strerror(error_code, error_msg, sizeof(error_msg));\n ESP_LOGE(tag, \"Error: %s %s %d\", msg.c_str(), error_msg, error_code);\n\n \/\/ TODO: convert errors.\n std::error_code ec(NetworkErrc::TLSProtocolError);\n throw std::system_error(ec, msg);\n }\n}\n\nint\nTLSStream::verify_certificate(void *data, mbedtls_x509_crt *crt, int depth, uint32_t *flags)\n{\n char buf[1024];\n ((void)data);\n\n ESP_LOGD(tag, \"Verify requested for (depth %d):\", depth);\n mbedtls_x509_crt_info(buf, sizeof(buf) - 1, \"\", crt);\n ESP_LOGD(tag, \"%s\", buf);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ from http:\/\/stackoverflow.com\/a\/9096509\/1781435\n#define stringify(x) #x\n#define expand_and_stringify(x) stringify(x)\n\n\/\/ Path from site-packages to packages that contain NuPIC Python regions\nstatic std::vector packages { \"nupic.regions\", \"nupic.regions.extra\" };\n\nnamespace nupic\n{\n\n \/\/ Allows the user to add custom regions to the package list\n void RegionImplFactory::registerRegionPackage(const char * path)\n {\n packages.push_back(path);\n }\n\n class DynamicPythonLibrary\n {\n typedef void (*initPythonFunc)();\n typedef void (*finalizePythonFunc)();\n typedef void * (*createSpecFunc)(const char *, void **);\n typedef int (*destroySpecFunc)(const char *);\n typedef void * (*createPyNodeFunc)(const char *, void *, void *, void **);\n typedef void * (*deserializePyNodeFunc)(const char *, void *, void *, void *);\n public:\n DynamicPythonLibrary() :\n initPython_(nullptr),\n finalizePython_(nullptr),\n createSpec_(nullptr),\n destroySpec_(nullptr),\n createPyNode_(nullptr)\n {\n \/\/ To find the pynode plugin we need the nupic\n \/\/ installation directory.\n#if defined(NTA_OS_WINDOWS)\n std::string command = \"python -c \\\"import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \\\"\\\"..\/..\\\"\\\")))\\\"\";\n#else\n std::string command = \"python -c 'import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \\\"..\/..\\\")))'\";\n#endif\n rootDir_ = OS::executeCommand(command);\n if (!Path::exists(rootDir_))\n NTA_THROW << \"Unable to find NuPIC library in '\" << rootDir_ << \"'\";\n \n \n#if defined(NTA_OS_WINDOWS)\n const char * filename = \"cpp_region.dll\";\n#else\n const char * filename = \"libcpp_region.so\";\n#endif\n\n std::string libName = Path::join(rootDir_, \"nupic\", filename);\n\n if (!Path::exists(libName))\n NTA_THROW << \"Unable to find library '\" << libName << \"'\";\n\n std::string errorString;\n DynamicLibrary * p = \n DynamicLibrary::load(libName, \n \/\/ export as LOCAL because we don't want\n \/\/ the symbols to be globally visible; \n \/\/ But the python module that we load\n \/\/ has to be able to access symbols from\n \/\/ libpython.so; Since libpython.so is linked\n \/\/ to the pynode shared library, it appears\n \/\/ we have to make the pynode shared library\n \/\/ symbols global. TODO: investigate\n DynamicLibrary::GLOBAL| \n \/\/ Evaluate them NOW instead of LAZY to catch \n \/\/ errors up front, even though this takes\n \/\/ a little longer to load the library. \n \/\/ However -- the current dependency chain\n \/\/ PyNode->Region->RegionImplFactory apparently\n \/\/ creates never-used dependencies on YAML\n \/\/ so until this is resolved use LAZY\n DynamicLibrary::LAZY,\n errorString);\n NTA_CHECK(p) << \"Unable to load the pynode library: \" << errorString;\n\n pynodeLibrary_ = boost::shared_ptr(p);\n\n initPython_ = (initPythonFunc)pynodeLibrary_->getSymbol(\"NTA_initPython\");\n NTA_CHECK(initPython_) << \"Unable to find NTA_initPython symbol in \" << filename;\n\n finalizePython_ = (finalizePythonFunc)pynodeLibrary_->getSymbol(\"NTA_finalizePython\");\n NTA_CHECK(finalizePython_) << \"Unable to find NTA_finalizePython symbol in \" << filename;\n\n createPyNode_ = (createPyNodeFunc)pynodeLibrary_->getSymbol(\"NTA_createPyNode\");\n NTA_CHECK(createPyNode_) << \"Unable to find NTA_createPyNode symbol in \" << filename;\n\n deserializePyNode_ = (deserializePyNodeFunc)pynodeLibrary_->getSymbol(\"NTA_deserializePyNode\");\n NTA_CHECK(createPyNode_) << \"Unable to find NTA_createPyNode symbol in \" << filename;\n\n createSpec_ = (createSpecFunc)pynodeLibrary_->getSymbol(\"NTA_createSpec\");\n NTA_CHECK(createSpec_) << \"Unable to find NTA_createSpec symbol in \" << filename;\n\n destroySpec_ = (destroySpecFunc)pynodeLibrary_->getSymbol(\"NTA_destroySpec\");\n NTA_CHECK(destroySpec_) << \"Unable to find NTA_destroySpec symbol in \" << filename;\n\n (*initPython_)();\n }\n\n ~DynamicPythonLibrary()\n {\n \/\/NTA_DEBUG << \"In DynamicPythonLibrary Destructor\";\n if (finalizePython_)\n finalizePython_();\n } \n\n void * createSpec(std::string nodeType, void ** exception)\n {\n \/\/NTA_DEBUG << \"RegionImplFactory::createSpec(\" << nodeType << \")\";\n return (*createSpec_)(nodeType.c_str(), exception);\n }\n\n int destroySpec(std::string nodeType)\n {\n NTA_INFO << \"destroySpec(\" << nodeType << \")\";\n return (*destroySpec_)(nodeType.c_str());\n }\n\n void * createPyNode(const std::string& nodeType, \n ValueMap * nodeParams,\n Region * region,\n void ** exception)\n {\n \/\/NTA_DEBUG << \"RegionImplFactory::createPyNode(\" << nodeType << \")\";\n return (*createPyNode_)(nodeType.c_str(),\n reinterpret_cast(nodeParams),\n reinterpret_cast(region),\n exception);\n\n }\n\n void * deserializePyNode(const std::string& nodeType, \n BundleIO* bundle,\n Region * region, \n void ** exception)\n {\n \/\/NTA_DEBUG << \"RegionImplFactory::deserializePyNode(\" << nodeType << \")\";\n return (*deserializePyNode_)(nodeType.c_str(), \n reinterpret_cast(bundle),\n reinterpret_cast(region), \n exception);\n }\n\n const std::string& getRootDir() const\n {\n return rootDir_;\n }\n\n private:\n std::string rootDir_;\n boost::shared_ptr pynodeLibrary_;\n initPythonFunc initPython_;\n finalizePythonFunc finalizePython_;\n createSpecFunc createSpec_;\n destroySpecFunc destroySpec_;\n createPyNodeFunc createPyNode_;\n deserializePyNodeFunc deserializePyNode_;\n };\n\nRegionImplFactory & RegionImplFactory::getInstance()\n{\n static RegionImplFactory instance;\n\n return instance;\n}\n\n\/\/ This function creates either a NuPIC 2 or NuPIC 1 Python node \nstatic RegionImpl * createPyNode(DynamicPythonLibrary * pyLib, \n const std::string & nodeType,\n ValueMap * nodeParams,\n Region * region)\n{\n for (auto package : packages)\n {\n \n \/\/ Construct the full module path to the requested node\n std::string fullNodeType = std::string(package);\n if (!fullNodeType.empty()) \/\/ Not in current directory\n fullNodeType += std::string(\".\");\n fullNodeType += std::string(nodeType.c_str() + 3);\n\n void * exception = nullptr;\n void * node = pyLib->createPyNode(fullNodeType, nodeParams, region, &exception);\n if (node)\n return static_cast(node);\n }\n\n NTA_THROW << \"Unable to create region \" << region->getName() << \" of type \" << nodeType;\n return nullptr;\n}\n\n\/\/ This function deserializes either a NuPIC 2 or NuPIC 1 Python node \nstatic RegionImpl * deserializePyNode(DynamicPythonLibrary * pyLib, \n const std::string & nodeType,\n BundleIO & bundle,\n Region * region)\n{\n \/\/ We need to find the module so that we know if it is NuPIC 1 or NuPIC 2\n for (auto package : packages)\n {\n \n \/\/ Construct the full module path to the requested node\n std::string fullNodeType = std::string(package);\n if (!fullNodeType.empty()) \/\/ Not in current directory\n fullNodeType += std::string(\".\");\n fullNodeType += std::string(nodeType.c_str() + 3);\n\n void *exception = nullptr;\n void * node = pyLib->deserializePyNode(fullNodeType, &bundle, region, &exception);\n if (node)\n return static_cast(node);\n }\n NTA_THROW << \"Unable to deserialize region \" << region->getName() << \" of type \" << nodeType;\n return nullptr;\n\n\n\n}\n\nRegionImpl* RegionImplFactory::createRegionImpl(const std::string nodeType, \n const std::string nodeParams,\n Region* region)\n{\n\n RegionImpl *mn = nullptr;\n Spec *ns = getSpec(nodeType);\n ValueMap vm = YAMLUtils::toValueMap(\n nodeParams.c_str(), \n ns->parameters, \n nodeType, \n region->getName());\n \n if (nodeType == \"TestNode\")\n {\n mn = new TestNode(vm, region);\n } else if (nodeType == \"VectorFileEffector\")\n {\n mn = new VectorFileEffector(vm, region);\n } else if (nodeType == \"VectorFileSensor\")\n {\n mn = new VectorFileSensor(vm, region);\n } else if ((nodeType.find(std::string(\"py.\")) == 0))\n {\n if (!pyLib_)\n pyLib_ = boost::shared_ptr(new DynamicPythonLibrary());\n \n mn = createPyNode(pyLib_.get(), nodeType, &vm, region);\n } else\n {\n NTA_THROW << \"Unsupported node type '\" << nodeType << \"'\";\n }\n return mn;\n\n}\n\nRegionImpl* RegionImplFactory::deserializeRegionImpl(const std::string nodeType, \n BundleIO& bundle,\n Region* region)\n{\n\n RegionImpl *mn = nullptr;\n\n if (nodeType == \"TestNode\")\n {\n mn = new TestNode(bundle, region);\n } else if (nodeType == \"VectorFileEffector\")\n {\n mn = new VectorFileEffector(bundle, region);\n } else if (nodeType == \"VectorFileSensor\")\n {\n mn = new VectorFileSensor(bundle, region);\n } else if (StringUtils::startsWith(nodeType, \"py.\"))\n {\n if (!pyLib_)\n pyLib_ = boost::shared_ptr(new DynamicPythonLibrary());\n \n mn = deserializePyNode(pyLib_.get(), nodeType, bundle, region);\n } else\n {\n NTA_THROW << \"Unsupported node type '\" << nodeType << \"'\";\n }\n return mn;\n\n}\n\n\/\/ This function returns the node spec of a NuPIC 2 or NuPIC 1 Python node \nstatic Spec * getPySpec(DynamicPythonLibrary * pyLib,\n const std::string & nodeType)\n{\n for (auto package : packages)\n {\n \n\n \/\/ Construct the full module path to the requested node\n std::string fullNodeType = std::string(package);\n if (!fullNodeType.empty()) \/\/ Not in current directory\n fullNodeType += std::string(\".\");\n fullNodeType += std::string(nodeType.c_str() + 3);\n std::cout << fullNodeType << std::endl;\n\n void * exception = nullptr;\n void * ns = pyLib->createSpec(fullNodeType, &exception);\n if (ns) {\n return (Spec *)ns;\n }\n }\n\n NTA_THROW << \"Matching Python module for \" << nodeType << \" not found.\";\n}\n\nSpec * RegionImplFactory::getSpec(const std::string nodeType)\n{\n std::map::iterator it;\n \/\/ return from cache if we already have it\n it = nodespecCache_.find(nodeType);\n if (it != nodespecCache_.end())\n return it->second;\n\n \/\/ grab the nodespec and cache it\n \/\/ one entry per supported node type\n Spec * ns = nullptr;\n if (nodeType == \"TestNode\")\n {\n ns = TestNode::createSpec();\n } \n else if (nodeType == \"VectorFileEffector\")\n {\n ns = VectorFileEffector::createSpec();\n }\n else if (nodeType == \"VectorFileSensor\")\n {\n ns = VectorFileSensor::createSpec();\n }\n else if (nodeType.find(std::string(\"py.\")) == 0)\n {\n if (!pyLib_)\n pyLib_ = boost::shared_ptr(new DynamicPythonLibrary());\n\n ns = getPySpec(pyLib_.get(), nodeType);\n } \n else \n {\n NTA_THROW << \"getSpec() -- Unsupported node type '\" << nodeType << \"'\";\n }\n\n if (!ns)\n NTA_THROW << \"Unable to get node spec for: \" << nodeType;\n\n nodespecCache_[nodeType] = ns;\n return ns;\n}\n \nvoid RegionImplFactory::cleanup()\n{\n std::map::iterator ns;\n \/\/ destroy all nodespecs\n for (ns = nodespecCache_.begin(); ns != nodespecCache_.end(); ns++)\n {\n assert(ns->second != nullptr);\n \/\/ PyNode node specs are destroyed by the C++ PyNode\n if (ns->first.substr(0, 3) == \"py.\")\n {\n pyLib_->destroySpec(ns->first);\n }\n else\n {\n delete ns->second;\n }\n\n ns->second = nullptr;\n }\n\n nodespecCache_.clear();\n\n \/\/ Never release the Python dynamic library!\n \/\/ This is due to cleanup issues of Python itself\n \/\/ See: http:\/\/docs.python.org\/c-api\/init.html#Py_Finalize\n \/\/pyLib_.reset();\n}\n\n}\n\nremoved print statement\/* ---------------------------------------------------------------------\n * Numenta Platform for Intelligent Computing (NuPIC)\n * Copyright (C) 2013, Numenta, Inc. Unless you have an agreement\n * with Numenta, Inc., for a separate license for this software code, the\n * following terms and conditions apply:\n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License version 3 as\n * published by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n * See the GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see http:\/\/www.gnu.org\/licenses.\n *\n * http:\/\/numenta.org\/licenses\/\n * ---------------------------------------------------------------------\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ from http:\/\/stackoverflow.com\/a\/9096509\/1781435\n#define stringify(x) #x\n#define expand_and_stringify(x) stringify(x)\n\n\/\/ Path from site-packages to packages that contain NuPIC Python regions\nstatic std::vector packages { \"nupic.regions\", \"nupic.regions.extra\" };\n\nnamespace nupic\n{\n\n \/\/ Allows the user to add custom regions to the package list\n void RegionImplFactory::registerRegionPackage(const char * path)\n {\n packages.push_back(path);\n }\n\n class DynamicPythonLibrary\n {\n typedef void (*initPythonFunc)();\n typedef void (*finalizePythonFunc)();\n typedef void * (*createSpecFunc)(const char *, void **);\n typedef int (*destroySpecFunc)(const char *);\n typedef void * (*createPyNodeFunc)(const char *, void *, void *, void **);\n typedef void * (*deserializePyNodeFunc)(const char *, void *, void *, void *);\n public:\n DynamicPythonLibrary() :\n initPython_(nullptr),\n finalizePython_(nullptr),\n createSpec_(nullptr),\n destroySpec_(nullptr),\n createPyNode_(nullptr)\n {\n \/\/ To find the pynode plugin we need the nupic\n \/\/ installation directory.\n#if defined(NTA_OS_WINDOWS)\n std::string command = \"python -c \\\"import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \\\"\\\"..\/..\\\"\\\")))\\\"\";\n#else\n std::string command = \"python -c 'import sys;import os;import nupic;sys.stdout.write(os.path.abspath(os.path.join(nupic.__file__, \\\"..\/..\\\")))'\";\n#endif\n rootDir_ = OS::executeCommand(command);\n if (!Path::exists(rootDir_))\n NTA_THROW << \"Unable to find NuPIC library in '\" << rootDir_ << \"'\";\n \n \n#if defined(NTA_OS_WINDOWS)\n const char * filename = \"cpp_region.dll\";\n#else\n const char * filename = \"libcpp_region.so\";\n#endif\n\n std::string libName = Path::join(rootDir_, \"nupic\", filename);\n\n if (!Path::exists(libName))\n NTA_THROW << \"Unable to find library '\" << libName << \"'\";\n\n std::string errorString;\n DynamicLibrary * p = \n DynamicLibrary::load(libName, \n \/\/ export as LOCAL because we don't want\n \/\/ the symbols to be globally visible; \n \/\/ But the python module that we load\n \/\/ has to be able to access symbols from\n \/\/ libpython.so; Since libpython.so is linked\n \/\/ to the pynode shared library, it appears\n \/\/ we have to make the pynode shared library\n \/\/ symbols global. TODO: investigate\n DynamicLibrary::GLOBAL| \n \/\/ Evaluate them NOW instead of LAZY to catch \n \/\/ errors up front, even though this takes\n \/\/ a little longer to load the library. \n \/\/ However -- the current dependency chain\n \/\/ PyNode->Region->RegionImplFactory apparently\n \/\/ creates never-used dependencies on YAML\n \/\/ so until this is resolved use LAZY\n DynamicLibrary::LAZY,\n errorString);\n NTA_CHECK(p) << \"Unable to load the pynode library: \" << errorString;\n\n pynodeLibrary_ = boost::shared_ptr(p);\n\n initPython_ = (initPythonFunc)pynodeLibrary_->getSymbol(\"NTA_initPython\");\n NTA_CHECK(initPython_) << \"Unable to find NTA_initPython symbol in \" << filename;\n\n finalizePython_ = (finalizePythonFunc)pynodeLibrary_->getSymbol(\"NTA_finalizePython\");\n NTA_CHECK(finalizePython_) << \"Unable to find NTA_finalizePython symbol in \" << filename;\n\n createPyNode_ = (createPyNodeFunc)pynodeLibrary_->getSymbol(\"NTA_createPyNode\");\n NTA_CHECK(createPyNode_) << \"Unable to find NTA_createPyNode symbol in \" << filename;\n\n deserializePyNode_ = (deserializePyNodeFunc)pynodeLibrary_->getSymbol(\"NTA_deserializePyNode\");\n NTA_CHECK(createPyNode_) << \"Unable to find NTA_createPyNode symbol in \" << filename;\n\n createSpec_ = (createSpecFunc)pynodeLibrary_->getSymbol(\"NTA_createSpec\");\n NTA_CHECK(createSpec_) << \"Unable to find NTA_createSpec symbol in \" << filename;\n\n destroySpec_ = (destroySpecFunc)pynodeLibrary_->getSymbol(\"NTA_destroySpec\");\n NTA_CHECK(destroySpec_) << \"Unable to find NTA_destroySpec symbol in \" << filename;\n\n (*initPython_)();\n }\n\n ~DynamicPythonLibrary()\n {\n \/\/NTA_DEBUG << \"In DynamicPythonLibrary Destructor\";\n if (finalizePython_)\n finalizePython_();\n } \n\n void * createSpec(std::string nodeType, void ** exception)\n {\n \/\/NTA_DEBUG << \"RegionImplFactory::createSpec(\" << nodeType << \")\";\n return (*createSpec_)(nodeType.c_str(), exception);\n }\n\n int destroySpec(std::string nodeType)\n {\n NTA_INFO << \"destroySpec(\" << nodeType << \")\";\n return (*destroySpec_)(nodeType.c_str());\n }\n\n void * createPyNode(const std::string& nodeType, \n ValueMap * nodeParams,\n Region * region,\n void ** exception)\n {\n \/\/NTA_DEBUG << \"RegionImplFactory::createPyNode(\" << nodeType << \")\";\n return (*createPyNode_)(nodeType.c_str(),\n reinterpret_cast(nodeParams),\n reinterpret_cast(region),\n exception);\n\n }\n\n void * deserializePyNode(const std::string& nodeType, \n BundleIO* bundle,\n Region * region, \n void ** exception)\n {\n \/\/NTA_DEBUG << \"RegionImplFactory::deserializePyNode(\" << nodeType << \")\";\n return (*deserializePyNode_)(nodeType.c_str(), \n reinterpret_cast(bundle),\n reinterpret_cast(region), \n exception);\n }\n\n const std::string& getRootDir() const\n {\n return rootDir_;\n }\n\n private:\n std::string rootDir_;\n boost::shared_ptr pynodeLibrary_;\n initPythonFunc initPython_;\n finalizePythonFunc finalizePython_;\n createSpecFunc createSpec_;\n destroySpecFunc destroySpec_;\n createPyNodeFunc createPyNode_;\n deserializePyNodeFunc deserializePyNode_;\n };\n\nRegionImplFactory & RegionImplFactory::getInstance()\n{\n static RegionImplFactory instance;\n\n return instance;\n}\n\n\/\/ This function creates either a NuPIC 2 or NuPIC 1 Python node \nstatic RegionImpl * createPyNode(DynamicPythonLibrary * pyLib, \n const std::string & nodeType,\n ValueMap * nodeParams,\n Region * region)\n{\n for (auto package : packages)\n {\n \n \/\/ Construct the full module path to the requested node\n std::string fullNodeType = std::string(package);\n if (!fullNodeType.empty()) \/\/ Not in current directory\n fullNodeType += std::string(\".\");\n fullNodeType += std::string(nodeType.c_str() + 3);\n\n void * exception = nullptr;\n void * node = pyLib->createPyNode(fullNodeType, nodeParams, region, &exception);\n if (node)\n return static_cast(node);\n }\n\n NTA_THROW << \"Unable to create region \" << region->getName() << \" of type \" << nodeType;\n return nullptr;\n}\n\n\/\/ This function deserializes either a NuPIC 2 or NuPIC 1 Python node \nstatic RegionImpl * deserializePyNode(DynamicPythonLibrary * pyLib, \n const std::string & nodeType,\n BundleIO & bundle,\n Region * region)\n{\n \/\/ We need to find the module so that we know if it is NuPIC 1 or NuPIC 2\n for (auto package : packages)\n {\n \n \/\/ Construct the full module path to the requested node\n std::string fullNodeType = std::string(package);\n if (!fullNodeType.empty()) \/\/ Not in current directory\n fullNodeType += std::string(\".\");\n fullNodeType += std::string(nodeType.c_str() + 3);\n\n void *exception = nullptr;\n void * node = pyLib->deserializePyNode(fullNodeType, &bundle, region, &exception);\n if (node)\n return static_cast(node);\n }\n NTA_THROW << \"Unable to deserialize region \" << region->getName() << \" of type \" << nodeType;\n return nullptr;\n\n\n\n}\n\nRegionImpl* RegionImplFactory::createRegionImpl(const std::string nodeType, \n const std::string nodeParams,\n Region* region)\n{\n\n RegionImpl *mn = nullptr;\n Spec *ns = getSpec(nodeType);\n ValueMap vm = YAMLUtils::toValueMap(\n nodeParams.c_str(), \n ns->parameters, \n nodeType, \n region->getName());\n \n if (nodeType == \"TestNode\")\n {\n mn = new TestNode(vm, region);\n } else if (nodeType == \"VectorFileEffector\")\n {\n mn = new VectorFileEffector(vm, region);\n } else if (nodeType == \"VectorFileSensor\")\n {\n mn = new VectorFileSensor(vm, region);\n } else if ((nodeType.find(std::string(\"py.\")) == 0))\n {\n if (!pyLib_)\n pyLib_ = boost::shared_ptr(new DynamicPythonLibrary());\n \n mn = createPyNode(pyLib_.get(), nodeType, &vm, region);\n } else\n {\n NTA_THROW << \"Unsupported node type '\" << nodeType << \"'\";\n }\n return mn;\n\n}\n\nRegionImpl* RegionImplFactory::deserializeRegionImpl(const std::string nodeType, \n BundleIO& bundle,\n Region* region)\n{\n\n RegionImpl *mn = nullptr;\n\n if (nodeType == \"TestNode\")\n {\n mn = new TestNode(bundle, region);\n } else if (nodeType == \"VectorFileEffector\")\n {\n mn = new VectorFileEffector(bundle, region);\n } else if (nodeType == \"VectorFileSensor\")\n {\n mn = new VectorFileSensor(bundle, region);\n } else if (StringUtils::startsWith(nodeType, \"py.\"))\n {\n if (!pyLib_)\n pyLib_ = boost::shared_ptr(new DynamicPythonLibrary());\n \n mn = deserializePyNode(pyLib_.get(), nodeType, bundle, region);\n } else\n {\n NTA_THROW << \"Unsupported node type '\" << nodeType << \"'\";\n }\n return mn;\n\n}\n\n\/\/ This function returns the node spec of a NuPIC 2 or NuPIC 1 Python node \nstatic Spec * getPySpec(DynamicPythonLibrary * pyLib,\n const std::string & nodeType)\n{\n for (auto package : packages)\n {\n \n\n \/\/ Construct the full module path to the requested node\n std::string fullNodeType = std::string(package);\n if (!fullNodeType.empty()) \/\/ Not in current directory\n fullNodeType += std::string(\".\");\n fullNodeType += std::string(nodeType.c_str() + 3);\n\n void * exception = nullptr;\n void * ns = pyLib->createSpec(fullNodeType, &exception);\n if (ns) {\n return (Spec *)ns;\n }\n }\n\n NTA_THROW << \"Matching Python module for \" << nodeType << \" not found.\";\n}\n\nSpec * RegionImplFactory::getSpec(const std::string nodeType)\n{\n std::map::iterator it;\n \/\/ return from cache if we already have it\n it = nodespecCache_.find(nodeType);\n if (it != nodespecCache_.end())\n return it->second;\n\n \/\/ grab the nodespec and cache it\n \/\/ one entry per supported node type\n Spec * ns = nullptr;\n if (nodeType == \"TestNode\")\n {\n ns = TestNode::createSpec();\n } \n else if (nodeType == \"VectorFileEffector\")\n {\n ns = VectorFileEffector::createSpec();\n }\n else if (nodeType == \"VectorFileSensor\")\n {\n ns = VectorFileSensor::createSpec();\n }\n else if (nodeType.find(std::string(\"py.\")) == 0)\n {\n if (!pyLib_)\n pyLib_ = boost::shared_ptr(new DynamicPythonLibrary());\n\n ns = getPySpec(pyLib_.get(), nodeType);\n } \n else \n {\n NTA_THROW << \"getSpec() -- Unsupported node type '\" << nodeType << \"'\";\n }\n\n if (!ns)\n NTA_THROW << \"Unable to get node spec for: \" << nodeType;\n\n nodespecCache_[nodeType] = ns;\n return ns;\n}\n \nvoid RegionImplFactory::cleanup()\n{\n std::map::iterator ns;\n \/\/ destroy all nodespecs\n for (ns = nodespecCache_.begin(); ns != nodespecCache_.end(); ns++)\n {\n assert(ns->second != nullptr);\n \/\/ PyNode node specs are destroyed by the C++ PyNode\n if (ns->first.substr(0, 3) == \"py.\")\n {\n pyLib_->destroySpec(ns->first);\n }\n else\n {\n delete ns->second;\n }\n\n ns->second = nullptr;\n }\n\n nodespecCache_.clear();\n\n \/\/ Never release the Python dynamic library!\n \/\/ This is due to cleanup issues of Python itself\n \/\/ See: http:\/\/docs.python.org\/c-api\/init.html#Py_Finalize\n \/\/pyLib_.reset();\n}\n\n}\n\n<|endoftext|>"} {"text":"\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified \n * freely and without restriction, both in commericial and non commericial\n * applications, as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"daeReader.h\"\n#include \"daeWriter.h\"\n\n#define EXTENSION_NAME \"dae\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OSG reader\/writer plugin for the COLLADA 1.4.x \".dae\" format.\n\/\/ See http:\/\/collada.org\/ and http:\/\/khronos.org\/collada\/\n\nclass ReaderWriterDAE : public osgDB::ReaderWriter\n{\npublic:\n ReaderWriterDAE() : dae_(NULL)\n {\n }\n\n ~ReaderWriterDAE()\n {\n if(dae_ != NULL){\n delete dae_;\n DAE::cleanup();\n dae_ = NULL;\n }\n }\n\n const char* className() const { return \"COLLADA 1.4.x DAE reader\/writer\"; }\n\n bool acceptsExtension(const std::string& extension) const\n { \n return osgDB::equalCaseInsensitive( extension, EXTENSION_NAME );\n }\n\n ReadResult readNode(const std::string&, const Options*) const;\n\n WriteResult writeNode(const osg::Node&, const std::string&, const Options*) const;\n \nprivate:\n\n DAE *dae_;\n \n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nosgDB::ReaderWriter::ReadResult\nReaderWriterDAE::readNode(const std::string& fname,\n const osgDB::ReaderWriter::Options* options) const\n{\n std::string ext( osgDB::getLowerCaseFileExtension(fname) );\n if( ! acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName( osgDB::findDataFile( fname, options ) );\n if( fileName.empty() ) return ReadResult::FILE_NOT_FOUND;\n\n osg::notify(osg::INFO) << \"ReaderWriterDAE( \\\"\" << fileName << \"\\\" )\" << std::endl;\n\n if (dae_ == NULL)\n const_cast(this)->dae_ = new DAE();\n\n osgdae::daeReader daeReader(dae_);\n std::string fileURI( osgDB::convertFileNameToUnixStyle(fileName) );\n if ( ! daeReader.convert( fileURI ) )\n {\n osg::notify( osg::WARN ) << \"Load failed in COLLADA DOM conversion\" << std::endl;\n return ReadResult::ERROR_IN_READING_FILE;\n }\n\n osg::Node* rootNode( daeReader.getRootNode() );\n return rootNode;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nosgDB::ReaderWriter::WriteResult\nReaderWriterDAE::writeNode( const osg::Node& node,\n const std::string& fname, const osgDB::ReaderWriter::Options* options ) const\n{\n std::string ext( osgDB::getLowerCaseFileExtension(fname) );\n if( ! acceptsExtension(ext) ) return WriteResult::FILE_NOT_HANDLED;\n\n \/\/ Process options\n bool usePolygon(false);\n if( options )\n {\n std::istringstream iss( options->getOptionString() );\n std::string opt;\n\n while( std::getline( iss, opt, ',' ) )\n {\n if( opt == \"polygon\") usePolygon = true;\n else\n {\n osg::notify(osg::WARN)\n << \"\\n\" \"COLLADA dae plugin: unrecognized option \\\"\" << opt << \"\\\"\\n\"\n << \"comma-delimited options:\\n\"\n << \"\\tpolygon = use polygons instead of polylists for element\\n\"\n << \"example: osgviewer -O polygon bar.dae\" \"\\n\"\n << std::endl;\n }\n }\n }\n \n if (dae_ == NULL)\n const_cast(this)->dae_ = new DAE();\n\n osgdae::daeWriter daeWriter(dae_, fname, usePolygon );\n daeWriter.setRootNode( node );\n const_cast(&node)->accept( daeWriter );\n\n osgDB::ReaderWriter::WriteResult retVal( WriteResult::ERROR_IN_WRITING_FILE );\n if ( daeWriter.isSuccess() )\n {\n if ( daeWriter.writeFile() )\n {\n retVal = WriteResult::FILE_SAVED;\n }\n }\n \n return retVal;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Add ourself to the Registry to instantiate the reader\/writer.\n\nosgDB::RegisterReaderWriterProxy g_readerWriter_DAE_Proxy;\n\n\/\/ vim: set sw=4 ts=8 et ic ai:\nAdded SERIALIZER to ReaderWriterDAE to make sure initialization is thread safe.\/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield \n *\n * This application is open source and may be redistributed and\/or modified \n * freely and without restriction, both in commericial and non commericial\n * applications, as long as this copyright notice is maintained.\n * \n * This application is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n *\n*\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"daeReader.h\"\n#include \"daeWriter.h\"\n\n#define EXTENSION_NAME \"dae\"\n\n#define SERIALIZER() OpenThreads::ScopedLock lock(_serializerMutex) \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OSG reader\/writer plugin for the COLLADA 1.4.x \".dae\" format.\n\/\/ See http:\/\/collada.org\/ and http:\/\/khronos.org\/collada\/\n\nclass ReaderWriterDAE : public osgDB::ReaderWriter\n{\npublic:\n ReaderWriterDAE() : _dae(NULL)\n {\n }\n\n ~ReaderWriterDAE()\n {\n if(_dae != NULL){\n delete _dae;\n DAE::cleanup();\n _dae = NULL;\n }\n }\n\n const char* className() const { return \"COLLADA 1.4.x DAE reader\/writer\"; }\n\n bool acceptsExtension(const std::string& extension) const\n { \n return osgDB::equalCaseInsensitive( extension, EXTENSION_NAME );\n }\n\n ReadResult readNode(const std::string&, const Options*) const;\n\n WriteResult writeNode(const osg::Node&, const std::string&, const Options*) const;\n \nprivate:\n\n mutable DAE *_dae;\n mutable osgDB::ReentrantMutex _serializerMutex;\n\n};\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nosgDB::ReaderWriter::ReadResult\nReaderWriterDAE::readNode(const std::string& fname,\n const osgDB::ReaderWriter::Options* options) const\n{\n SERIALIZER();\n \n std::string ext( osgDB::getLowerCaseFileExtension(fname) );\n if( ! acceptsExtension(ext) ) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName( osgDB::findDataFile( fname, options ) );\n if( fileName.empty() ) return ReadResult::FILE_NOT_FOUND;\n\n osg::notify(osg::INFO) << \"ReaderWriterDAE( \\\"\" << fileName << \"\\\" )\" << std::endl;\n\n if (_dae == NULL)\n _dae = new DAE();\n\n osgdae::daeReader daeReader(_dae);\n std::string fileURI( osgDB::convertFileNameToUnixStyle(fileName) );\n if ( ! daeReader.convert( fileURI ) )\n {\n osg::notify( osg::WARN ) << \"Load failed in COLLADA DOM conversion\" << std::endl;\n return ReadResult::ERROR_IN_READING_FILE;\n }\n\n osg::Node* rootNode( daeReader.getRootNode() );\n return rootNode;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nosgDB::ReaderWriter::WriteResult\nReaderWriterDAE::writeNode( const osg::Node& node,\n const std::string& fname, const osgDB::ReaderWriter::Options* options ) const\n{\n SERIALIZER();\n\n std::string ext( osgDB::getLowerCaseFileExtension(fname) );\n if( ! acceptsExtension(ext) ) return WriteResult::FILE_NOT_HANDLED;\n\n \/\/ Process options\n bool usePolygon(false);\n if( options )\n {\n std::istringstream iss( options->getOptionString() );\n std::string opt;\n\n while( std::getline( iss, opt, ',' ) )\n {\n if( opt == \"polygon\") usePolygon = true;\n else\n {\n osg::notify(osg::WARN)\n << \"\\n\" \"COLLADA dae plugin: unrecognized option \\\"\" << opt << \"\\\"\\n\"\n << \"comma-delimited options:\\n\"\n << \"\\tpolygon = use polygons instead of polylists for element\\n\"\n << \"example: osgviewer -O polygon bar.dae\" \"\\n\"\n << std::endl;\n }\n }\n }\n \n if (_dae == NULL)\n _dae = new DAE();\n\n osgdae::daeWriter daeWriter(_dae, fname, usePolygon );\n daeWriter.setRootNode( node );\n const_cast(&node)->accept( daeWriter );\n\n osgDB::ReaderWriter::WriteResult retVal( WriteResult::ERROR_IN_WRITING_FILE );\n if ( daeWriter.isSuccess() )\n {\n if ( daeWriter.writeFile() )\n {\n retVal = WriteResult::FILE_SAVED;\n }\n }\n \n return retVal;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Add ourself to the Registry to instantiate the reader\/writer.\n\nosgDB::RegisterReaderWriterProxy g_readerWriter_DAE_Proxy;\n\n\/\/ vim: set sw=4 ts=8 et ic ai:\n<|endoftext|>"} {"text":"#include \"MatrixTransform.h\"\n#include \"Group.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace osg;\nusing namespace osgDB;\n\nclass IVEReaderWriter : public ReaderWriter\n{\n public:\n virtual const char* className() const { return \"IVE Reader\/Writer\"; }\n\n virtual bool acceptsExtension(const std::string& extension) const\n {\n return equalCaseInsensitive(extension,\"ive\");\n }\n\n virtual ReadResult readObject(const std::string& file, const Options* options) const\n {\n return readNode(file, options);\n }\n \n virtual ReadResult readNode(const std::string& file, const Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, options );\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->setDatabasePath(osgDB::getFilePath(fileName));\n \n std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);\n return readNode(istream,local_opt.get());\n }\n \n virtual ReadResult readObject(std::istream& fin, const Options* options) const\n {\n return readNode(fin, options);\n }\n \n virtual ReadResult readNode(std::istream& fin, const Options* options) const\n {\n try{\n \/\/ Create datainputstream.\n ive::DataInputStream in(&fin);\n in.setOptions(options);\n\n return in.readNode();\n }\n catch(ive::Exception e)\n {\n osg::notify(osg::NOTICE)<<\"Error reading file: \"<< e.getError()<(&object);\n if (node) return writeNode( *node, fileName, options );\n return WriteResult::FILE_NOT_HANDLED;\n }\n\n virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n if(local_opt->getDatabasePathList().empty())\n local_opt->setDatabasePath(osgDB::getFilePath(fileName));\n\n std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);\n if (!fout) return WriteResult::ERROR_IN_WRITING_FILE;\n \n WriteResult result = writeNode(node, fout, local_opt.get());\n fout.close();\n return result;\n }\n \n virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n const Node* node = dynamic_cast(&object);\n if (node) return writeNode( *node, fout, options );\n return WriteResult::FILE_NOT_HANDLED;\n }\n\n virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n try\n {\n ive::DataOutputStream out(&fout);\n\n out.setOptions(options);\n\n out.writeNode(const_cast(&node));\n\n if ( fout.fail() ) return WriteResult::ERROR_IN_WRITING_FILE;\n\n return WriteResult::FILE_SAVED;\n }\n catch(ive::Exception e)\n {\n osg::notify(osg::WARN)<<\"Error writing IVE file: \"<< e.getError() << std::endl;\n }\n return WriteResult::FILE_NOT_HANDLED;\n\n }\n\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nRegisterReaderWriterProxy g_IVEReaderWriterProxy;\nFrom Eric Sokolowski, \"Added the ability to read and write images directly in the ive plugin, through the osgDB::readImageFile and osgDB::writeImageFile functions. This is useful for storing compressed textures on disk for rapid playback for animations.\"#include \"MatrixTransform.h\"\n#include \"Group.h\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace osg;\nusing namespace osgDB;\n\nclass IVEReaderWriter : public ReaderWriter\n{\n public:\n virtual const char* className() const { return \"IVE Reader\/Writer\"; }\n\n virtual bool acceptsExtension(const std::string& extension) const\n {\n return equalCaseInsensitive(extension,\"ive\");\n }\n\n virtual ReadResult readObject(const std::string& file, const Options* options) const\n {\n return readNode(file, options);\n }\n\n virtual ReadResult readImage(const std::string& file, const Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n std::string fileName = osgDB::findDataFile(file, options);\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced files are searched for on relative paths.\n osg::ref_ptr local_opt = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->setDatabasePath(osgDB::getFilePath(fileName));\n std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);\n return readImage(istream, local_opt.get());\n }\n \n virtual ReadResult readNode(const std::string& file, const Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, options );\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->setDatabasePath(osgDB::getFilePath(fileName));\n \n std::ifstream istream(fileName.c_str(), std::ios::in | std::ios::binary);\n return readNode(istream,local_opt.get());\n }\n \n virtual ReadResult readObject(std::istream& fin, const Options* options) const\n {\n return readNode(fin, options);\n }\n\n virtual ReadResult readImage(std::istream& fin, const Options* options) const\n {\n try{\n ive::DataInputStream in(&fin);\n in.setOptions(options);\n return in.readImage(ive::IMAGE_INCLUDE_DATA);\n }\n catch(ive::Exception e)\n {\n osg::notify(osg::NOTICE)<<\"Error reading image: \"<(&object);\n if (node) return writeNode( *node, fileName, options );\n const Image* image = dynamic_cast(&object);\n if (image) return writeImage(*image, fileName, options);\n return WriteResult::FILE_NOT_HANDLED;\n }\n\n virtual WriteResult writeImage(const Image& image,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n if(local_opt->getDatabasePathList().empty())\n local_opt->setDatabasePath(osgDB::getFilePath(fileName));\n std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);\n if (!fout) return WriteResult::ERROR_IN_WRITING_FILE;\n WriteResult result = writeImage(image, fout, local_opt.get());\n fout.close();\n return result;\n }\n\n virtual WriteResult writeNode(const Node& node,const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = options ? static_cast(options->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n if(local_opt->getDatabasePathList().empty())\n local_opt->setDatabasePath(osgDB::getFilePath(fileName));\n\n std::ofstream fout(fileName.c_str(), std::ios::out | std::ios::binary);\n if (!fout) return WriteResult::ERROR_IN_WRITING_FILE;\n \n WriteResult result = writeNode(node, fout, local_opt.get());\n fout.close();\n return result;\n }\n \n virtual WriteResult writeObject(const Object& object,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n const Node* node = dynamic_cast(&object);\n if (node) return writeNode( *node, fout, options );\n const Image* image = dynamic_cast(&object);\n if (image) return writeImage(*image, fout, options);\n return WriteResult::FILE_NOT_HANDLED;\n }\n\n virtual WriteResult writeImage(const Image& image,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n try\n {\n ive::DataOutputStream out(&fout);\n out.setOptions(options);\n out.writeImage(ive::IMAGE_INCLUDE_DATA, const_cast(&image));\n if (fout.fail()) return WriteResult::ERROR_IN_WRITING_FILE;\n return WriteResult::FILE_SAVED;\n }\n catch(ive::Exception e)\n {\n osg::notify(osg::WARN)<<\"Error writing IVE image: \"<< e.getError() << std::endl;\n }\n return WriteResult::FILE_NOT_HANDLED;\n }\n\n virtual WriteResult writeNode(const Node& node,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n try\n {\n ive::DataOutputStream out(&fout);\n\n out.setOptions(options);\n\n out.writeNode(const_cast(&node));\n\n if ( fout.fail() ) return WriteResult::ERROR_IN_WRITING_FILE;\n\n return WriteResult::FILE_SAVED;\n }\n catch(ive::Exception e)\n {\n osg::notify(osg::WARN)<<\"Error writing IVE file: \"<< e.getError() << std::endl;\n }\n return WriteResult::FILE_NOT_HANDLED;\n\n }\n\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nRegisterReaderWriterProxy g_IVEReaderWriterProxy;\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sockinet.h\"\n\n \/*\n * Semantics:\n * Two methods for using the .net loader.\n * 1) Add a hostname prefix and a '.net' suffix on a model when passing \n * to osgDB::readNodeFile() \n * e.g: osgDB::readNodeFile( \"openscenegraph.org:cow.osg.net\" );\n *\n * 2) Explicitely load the .net plugin and pass the plugin options including\n * hostname=\n *\n * Method #1 takes precedence. SO, if the hostname option is passed the\n * plugin, but the name also contains a hostname prefix, the hostname\n * prefix on the file name will override the option\n *\n * Plugin options:\n * hostname= - Specify the host where the data file is to \n * be fetched from.\n *\n * prefix= - Specify a server directory to prefix the \n * file name with.\n * \n * local_cache_dir= - Specify a directory in which to cache files\n * on the local machine once they've been fetched. \n * This directory is also searched before fetching\n * the file from the server when Read mode is \n * enabled on the cache.\n *\n * cache_mode= - Set the mode for the local cache if local_cache\n * was specified. If local_cache was not specified\n * this directive is ignored. may\n * be specified with ReadOnly, WriteOnly, or\n * ReadWrite. Behavior for the different modes is\n * defined as:\n *\n * ReadOnly - When retrieving files, cache is \n * searched first, and if the file is\n * not present, it is fetched from the\n * server. If it is fetched from the\n * server it is not stored in local cache\n *\n * WriteOnly - When retrieving files, cache is not\n * searched, file is always retrieved\n * from the server and always written to\n * cache.\n *\n * ReadWrite - (the default). When retrieving files\n * cache is searched first, if file is\n * not present in cache, it is fetched from\n * the server. If fetched, it is written\n * to cache.\n *\n *\/\n\n\nclass NetReader : public osgDB::ReaderWriter\n{\n public:\n NetReader() {}\n \n virtual const char* className() { return \"HTTP Protocol Model Reader\"; }\n \n virtual bool acceptsExtension(const std::string& extension)\n {\n return osgDB::equalCaseInsensitive(extension,\"net\");\n }\n\n enum ObjectType\n {\n OBJECT,\n IMAGE,\n HEIGHTFIELD,\n NODE\n };\n \n virtual ReadResult readObject(const std::string& fileName, const Options* options)\n {\n return readFile(OBJECT,fileName,options);\n }\n \n virtual ReadResult readImage(const std::string& fileName, const Options *options)\n {\n return readFile(IMAGE,fileName,options);\n }\n\n virtual ReadResult readHeightField(const std::string& fileName, const Options *options)\n {\n return readFile(HEIGHTFIELD,fileName,options);\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options *options)\n {\n return readFile(NODE,fileName,options);\n }\n\n ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)\n {\n switch(objectType)\n {\n case(OBJECT): return rw->readObject(fin,options);\n case(IMAGE): return rw->readImage(fin,options);\n case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n case(NODE): return rw->readNode(fin,options);\n default: break;\n }\n }\n\n virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)\n {\n osg::Timer_t start = osg::Timer::instance()->tick();\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: start load\" << inFileName << std::endl;\n\n std::string hostname;\n std::string serverPrefix;\n std::string localCacheDir;\n int port = 80;\n\n enum CacheMode {\n Read = 1,\n Write = 2,\n ReadWrite = 3\n };\n\n CacheMode cacheMode = ReadWrite;\n\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt) \n {\n int index = opt.find( \"=\" );\n if( opt.substr( 0, index ) == \"hostname\" ||\n opt.substr( 0, index ) == \"HOSTNAME\" )\n {\n hostname = opt.substr( index+1 );\n }\n else if( opt.substr( 0, index ) == \"port\" ||\n opt.substr( 0, index ) == \"PORT\" )\n {\n port = atoi( opt.substr(index+1).c_str() );\n }\n else if( opt.substr( 0, index ) == \"server_prefix\" ||\n opt.substr( 0, index ) == \"SERVER_PREFIX\" ||\n opt.substr( 0, index ) == \"prefix\" ||\n opt.substr( 0, index ) == \"PREFIX\" )\n {\n serverPrefix = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"local_cache_dir\" ||\n opt.substr( 0, index ) == \"LOCAL_CACHE_DIR\" )\n {\n localCacheDir = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"cache_mode\" ||\n opt.substr( 0, index ) == \"CACHE_MODE\" )\n {\n if( opt.substr(index+1) == \"ReadOnly\" )\n cacheMode = Read;\n else if( opt.substr(index+1) == \"WriteOnly\" )\n cacheMode = Write;\n else if( opt.substr(index+1) == \"ReadWrite\" )\n cacheMode = ReadWrite;\n else\n osg::notify(osg::WARN) << \n \"NET plug-in warning: cache_mode \" << opt.substr(index+1) << \n \" not understood. Defaulting to ReadWrite.\" << std::endl;\n }\n }\n }\n\n ReadResult readResult = ReadResult::FILE_NOT_HANDLED;\n\n \/* * we accept all extensions\n std::string ext = osgDB::getFileExtension(inFileName);\n if (!acceptsExtension(ext))\n return ReadResult::FILE_NOT_HANDLED;\n *\/\n\n std::string fileName;\n int index = inFileName.find(\":\");\n \/\/ If we haven't been given a hostname as an option\n \/\/ and it hasn't been prefixed to the name, we fail\n if( index != -1 )\n {\n hostname = inFileName.substr( 0, index);\n \/\/ need to strip the inFileName of the hostname prefix\n fileName = inFileName.substr( index+1 );\n }\n else\n {\n if( hostname.empty() )\n return ReadResult::FILE_NOT_HANDLED;\n else\n fileName = inFileName;\n }\n\n \/\/ Let's also strip the possible .net extension\n if( osgDB::getFileExtension( fileName ) == \"net\" )\n {\n int rindex = fileName.rfind( \".\" );\n fileName = fileName.substr( 0, rindex );\n }\n\n if( !serverPrefix.empty() )\n fileName = serverPrefix + '\/' + fileName;\n\n \/\/ Invoke the reader corresponding to the extension\n osgDB::ReaderWriter *reader = \n osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n if( reader == 0L )\n return ReadResult::FILE_NOT_HANDLED;\n\n \/\/ Before we go to the network, lets see if it is in local cache, if cache\n \/\/ was specified and Read bit is set\n if( !localCacheDir.empty() && (cacheMode & Read) )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::fileExists( cacheFile ))\n {\n std::ifstream in(cacheFile.c_str());\n readResult = readFile(objectType, reader, in, options );\n\n in.close();\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from local cache.\" << std::endl;\n return readResult;\n }\n }\n\n \/\/ Fetch from the network\n iosockinet sio (sockbuf::sock_stream);\n try {\n sio->connect( hostname.c_str(), port );\n }\n catch( sockerr e )\n {\n osg::notify(osg::WARN) << \"osgPlugin .net reader: Unable to connect to host \" << hostname << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n\n sio << \"GET \/\" << fileName << \" HTTP\/1.1\\n\" << \"Host:\\n\\n\";\n sio.flush();\n \n char linebuff[256];\n do\n {\n sio.getline( linebuff, sizeof( linebuff ));\n\n std::istringstream iss(linebuff);\n std::string directive;\n iss >> directive;\n if( directive.substr(0,4) == \"HTTP\" )\n {\n iss >> directive;\n \/\/ Code 200. We be ok.\n if( directive == \"200\" )\n ;\n \/\/ Code 400 Bad Request\n else if( directive == \"400\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 400 - Bad Request\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 401 Bad Request\n else if( directive == \"401\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 401 - Unauthorized Access\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 403 Bad Request\n else if( directive == \"403\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 403 - Access Forbidden\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 404 File not found\n else if( directive == \"404\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 404 - File Not Found\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 405 Method not allowed\n else if( directive == \"405\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 405 - Method Not Allowed\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ There's more....\n }\n\n } while( linebuff[0] != '\\r' );\n\n \/\/ code for setting up the database path so that any paged\n \/\/ databases can be automatically located. \n osg::ref_ptr local_opt = const_cast(options);\n if (!local_opt) local_opt = new Options;\n\n if (local_opt.valid() && local_opt->getDatabasePath().empty())\n {\n local_opt->setDatabasePath(osgDB::getFilePath(inFileName));\n }\n \n \n\n\n if( reader != 0L )\n readResult = readFile(objectType, reader, sio, local_opt.get() );\n\n double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from server. in\" << ms <<\" ms\"<< std::endl;\n\n if( !localCacheDir.empty() && cacheMode & Write )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::makeDirectoryForFile( cacheFile ) )\n {\n \n switch(objectType)\n {\n case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );\n case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );\n case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );\n case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;\n default: break;\n }\n \n \n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" stored to local cache.\" << std::endl;\n }\n }\n\n return readResult;\n }\n \n};\n\nosgDB::RegisterReaderWriterProxy g_netReader_Proxy;\n\n \n\n\nSmall warning fix by Marco.#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sockinet.h\"\n\n \/*\n * Semantics:\n * Two methods for using the .net loader.\n * 1) Add a hostname prefix and a '.net' suffix on a model when passing \n * to osgDB::readNodeFile() \n * e.g: osgDB::readNodeFile( \"openscenegraph.org:cow.osg.net\" );\n *\n * 2) Explicitely load the .net plugin and pass the plugin options including\n * hostname=\n *\n * Method #1 takes precedence. SO, if the hostname option is passed the\n * plugin, but the name also contains a hostname prefix, the hostname\n * prefix on the file name will override the option\n *\n * Plugin options:\n * hostname= - Specify the host where the data file is to \n * be fetched from.\n *\n * prefix= - Specify a server directory to prefix the \n * file name with.\n * \n * local_cache_dir= - Specify a directory in which to cache files\n * on the local machine once they've been fetched. \n * This directory is also searched before fetching\n * the file from the server when Read mode is \n * enabled on the cache.\n *\n * cache_mode= - Set the mode for the local cache if local_cache\n * was specified. If local_cache was not specified\n * this directive is ignored. may\n * be specified with ReadOnly, WriteOnly, or\n * ReadWrite. Behavior for the different modes is\n * defined as:\n *\n * ReadOnly - When retrieving files, cache is \n * searched first, and if the file is\n * not present, it is fetched from the\n * server. If it is fetched from the\n * server it is not stored in local cache\n *\n * WriteOnly - When retrieving files, cache is not\n * searched, file is always retrieved\n * from the server and always written to\n * cache.\n *\n * ReadWrite - (the default). When retrieving files\n * cache is searched first, if file is\n * not present in cache, it is fetched from\n * the server. If fetched, it is written\n * to cache.\n *\n *\/\n\n\nclass NetReader : public osgDB::ReaderWriter\n{\n public:\n NetReader() {}\n \n virtual const char* className() { return \"HTTP Protocol Model Reader\"; }\n \n virtual bool acceptsExtension(const std::string& extension)\n {\n return osgDB::equalCaseInsensitive(extension,\"net\");\n }\n\n enum ObjectType\n {\n OBJECT,\n IMAGE,\n HEIGHTFIELD,\n NODE\n };\n \n virtual ReadResult readObject(const std::string& fileName, const Options* options)\n {\n return readFile(OBJECT,fileName,options);\n }\n \n virtual ReadResult readImage(const std::string& fileName, const Options *options)\n {\n return readFile(IMAGE,fileName,options);\n }\n\n virtual ReadResult readHeightField(const std::string& fileName, const Options *options)\n {\n return readFile(HEIGHTFIELD,fileName,options);\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options *options)\n {\n return readFile(NODE,fileName,options);\n }\n\n ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)\n {\n switch(objectType)\n {\n case(OBJECT): return rw->readObject(fin,options);\n case(IMAGE): return rw->readImage(fin,options);\n case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n case(NODE): return rw->readNode(fin,options);\n default: break;\n }\n\t\t\treturn ReadResult::FILE_NOT_HANDLED;\n }\n\n virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)\n {\n osg::Timer_t start = osg::Timer::instance()->tick();\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: start load\" << inFileName << std::endl;\n\n std::string hostname;\n std::string serverPrefix;\n std::string localCacheDir;\n int port = 80;\n\n enum CacheMode {\n Read = 1,\n Write = 2,\n ReadWrite = 3\n };\n\n CacheMode cacheMode = ReadWrite;\n\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt) \n {\n int index = opt.find( \"=\" );\n if( opt.substr( 0, index ) == \"hostname\" ||\n opt.substr( 0, index ) == \"HOSTNAME\" )\n {\n hostname = opt.substr( index+1 );\n }\n else if( opt.substr( 0, index ) == \"port\" ||\n opt.substr( 0, index ) == \"PORT\" )\n {\n port = atoi( opt.substr(index+1).c_str() );\n }\n else if( opt.substr( 0, index ) == \"server_prefix\" ||\n opt.substr( 0, index ) == \"SERVER_PREFIX\" ||\n opt.substr( 0, index ) == \"prefix\" ||\n opt.substr( 0, index ) == \"PREFIX\" )\n {\n serverPrefix = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"local_cache_dir\" ||\n opt.substr( 0, index ) == \"LOCAL_CACHE_DIR\" )\n {\n localCacheDir = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"cache_mode\" ||\n opt.substr( 0, index ) == \"CACHE_MODE\" )\n {\n if( opt.substr(index+1) == \"ReadOnly\" )\n cacheMode = Read;\n else if( opt.substr(index+1) == \"WriteOnly\" )\n cacheMode = Write;\n else if( opt.substr(index+1) == \"ReadWrite\" )\n cacheMode = ReadWrite;\n else\n osg::notify(osg::WARN) << \n \"NET plug-in warning: cache_mode \" << opt.substr(index+1) << \n \" not understood. Defaulting to ReadWrite.\" << std::endl;\n }\n }\n }\n\n ReadResult readResult = ReadResult::FILE_NOT_HANDLED;\n\n \/* * we accept all extensions\n std::string ext = osgDB::getFileExtension(inFileName);\n if (!acceptsExtension(ext))\n return ReadResult::FILE_NOT_HANDLED;\n *\/\n\n std::string fileName;\n int index = inFileName.find(\":\");\n \/\/ If we haven't been given a hostname as an option\n \/\/ and it hasn't been prefixed to the name, we fail\n if( index != -1 )\n {\n hostname = inFileName.substr( 0, index);\n \/\/ need to strip the inFileName of the hostname prefix\n fileName = inFileName.substr( index+1 );\n }\n else\n {\n if( hostname.empty() )\n return ReadResult::FILE_NOT_HANDLED;\n else\n fileName = inFileName;\n }\n\n \/\/ Let's also strip the possible .net extension\n if( osgDB::getFileExtension( fileName ) == \"net\" )\n {\n int rindex = fileName.rfind( \".\" );\n fileName = fileName.substr( 0, rindex );\n }\n\n if( !serverPrefix.empty() )\n fileName = serverPrefix + '\/' + fileName;\n\n \/\/ Invoke the reader corresponding to the extension\n osgDB::ReaderWriter *reader = \n osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n if( reader == 0L )\n return ReadResult::FILE_NOT_HANDLED;\n\n \/\/ Before we go to the network, lets see if it is in local cache, if cache\n \/\/ was specified and Read bit is set\n if( !localCacheDir.empty() && (cacheMode & Read) )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::fileExists( cacheFile ))\n {\n std::ifstream in(cacheFile.c_str());\n readResult = readFile(objectType, reader, in, options );\n\n in.close();\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from local cache.\" << std::endl;\n return readResult;\n }\n }\n\n \/\/ Fetch from the network\n iosockinet sio (sockbuf::sock_stream);\n try {\n sio->connect( hostname.c_str(), port );\n }\n catch( sockerr e )\n {\n osg::notify(osg::WARN) << \"osgPlugin .net reader: Unable to connect to host \" << hostname << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n\n sio << \"GET \/\" << fileName << \" HTTP\/1.1\\n\" << \"Host:\\n\\n\";\n sio.flush();\n \n char linebuff[256];\n do\n {\n sio.getline( linebuff, sizeof( linebuff ));\n\n std::istringstream iss(linebuff);\n std::string directive;\n iss >> directive;\n if( directive.substr(0,4) == \"HTTP\" )\n {\n iss >> directive;\n \/\/ Code 200. We be ok.\n if( directive == \"200\" )\n ;\n \/\/ Code 400 Bad Request\n else if( directive == \"400\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 400 - Bad Request\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 401 Bad Request\n else if( directive == \"401\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 401 - Unauthorized Access\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 403 Bad Request\n else if( directive == \"403\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 403 - Access Forbidden\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 404 File not found\n else if( directive == \"404\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 404 - File Not Found\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 405 Method not allowed\n else if( directive == \"405\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 405 - Method Not Allowed\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ There's more....\n }\n\n } while( linebuff[0] != '\\r' );\n\n \/\/ code for setting up the database path so that any paged\n \/\/ databases can be automatically located. \n osg::ref_ptr local_opt = const_cast(options);\n if (!local_opt) local_opt = new Options;\n\n if (local_opt.valid() && local_opt->getDatabasePath().empty())\n {\n local_opt->setDatabasePath(osgDB::getFilePath(inFileName));\n }\n \n \n\n\n if( reader != 0L )\n readResult = readFile(objectType, reader, sio, local_opt.get() );\n\n double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from server. in\" << ms <<\" ms\"<< std::endl;\n\n if( !localCacheDir.empty() && cacheMode & Write )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::makeDirectoryForFile( cacheFile ) )\n {\n \n switch(objectType)\n {\n case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );\n case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );\n case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );\n case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;\n default: break;\n }\n \n \n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" stored to local cache.\" << std::endl;\n }\n }\n\n return readResult;\n }\n \n};\n\nosgDB::RegisterReaderWriterProxy g_netReader_Proxy;\n\n \n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sockinet.h\"\n\n \/*\n * Semantics:\n * Two methods for using the .net loader.\n * 1) Add a hostname prefix and a '.net' suffix on a model when passing \n * to osgDB::readNodeFile() \n * e.g: osgDB::readNodeFile( \"openscenegraph.org:cow.osg.net\" );\n *\n * 2) Explicitely load the .net plugin and pass the plugin options including\n * hostname=\n *\n * Method #1 takes precedence. SO, if the hostname option is passed the\n * plugin, but the name also contains a hostname prefix, the hostname\n * prefix on the file name will override the option\n *\n * Plugin options:\n * hostname= - Specify the host where the data file is to \n * be fetched from.\n *\n * prefix= - Specify a server directory to prefix the \n * file name with.\n * \n * local_cache_dir= - Specify a directory in which to cache files\n * on the local machine once they've been fetched. \n * This directory is also searched before fetching\n * the file from the server when Read mode is \n * enabled on the cache.\n *\n * cache_mode= - Set the mode for the local cache if local_cache\n * was specified. If local_cache was not specified\n * this directive is ignored. may\n * be specified with ReadOnly, WriteOnly, or\n * ReadWrite. Behavior for the different modes is\n * defined as:\n *\n * ReadOnly - When retrieving files, cache is \n * searched first, and if the file is\n * not present, it is fetched from the\n * server. If it is fetched from the\n * server it is not stored in local cache\n *\n * WriteOnly - When retrieving files, cache is not\n * searched, file is always retrieved\n * from the server and always written to\n * cache.\n *\n * ReadWrite - (the default). When retrieving files\n * cache is searched first, if file is\n * not present in cache, it is fetched from\n * the server. If fetched, it is written\n * to cache.\n *\n *\/\n\n\nclass NetReader : public osgDB::ReaderWriter\n{\n public:\n NetReader() {}\n \n virtual const char* className() { return \"HTTP Protocol Model Reader\"; }\n \n virtual bool acceptsExtension(const std::string& extension)\n {\n return osgDB::equalCaseInsensitive(extension,\"net\");\n }\n\n enum ObjectType\n {\n OBJECT,\n IMAGE,\n HEIGHTFIELD,\n NODE\n };\n \n virtual ReadResult readObject(const std::string& fileName, const Options* options)\n {\n return readFile(OBJECT,fileName,options);\n }\n \n virtual ReadResult readImage(const std::string& fileName, const Options *options)\n {\n return readFile(IMAGE,fileName,options);\n }\n\n virtual ReadResult readHeightField(const std::string& fileName, const Options *options)\n {\n return readFile(HEIGHTFIELD,fileName,options);\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options *options)\n {\n return readFile(NODE,fileName,options);\n }\n\n ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)\n {\n switch(objectType)\n {\n case(OBJECT): return rw->readObject(fin,options);\n case(IMAGE): return rw->readImage(fin,options);\n case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n case(NODE): return rw->readNode(fin,options);\n }\n }\n\n virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)\n {\n osg::Timer_t start = osg::Timer::instance()->tick();\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: start load\" << inFileName << std::endl;\n\n std::string hostname;\n std::string serverPrefix;\n std::string localCacheDir;\n int port = 80;\n\n enum CacheMode {\n Read = 1,\n Write = 2,\n ReadWrite = 3\n };\n\n CacheMode cacheMode = ReadWrite;\n\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt) \n {\n int index = opt.find( \"=\" );\n if( opt.substr( 0, index ) == \"hostname\" ||\n opt.substr( 0, index ) == \"HOSTNAME\" )\n {\n hostname = opt.substr( index+1 );\n }\n else if( opt.substr( 0, index ) == \"port\" ||\n opt.substr( 0, index ) == \"PORT\" )\n {\n port = atoi( opt.substr(index+1).c_str() );\n }\n else if( opt.substr( 0, index ) == \"server_prefix\" ||\n opt.substr( 0, index ) == \"SERVER_PREFIX\" ||\n opt.substr( 0, index ) == \"prefix\" ||\n opt.substr( 0, index ) == \"PREFIX\" )\n {\n serverPrefix = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"local_cache_dir\" ||\n opt.substr( 0, index ) == \"LOCAL_CACHE_DIR\" )\n {\n localCacheDir = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"cache_mode\" ||\n opt.substr( 0, index ) == \"CACHE_MODE\" )\n {\n if( opt.substr(index+1) == \"ReadOnly\" )\n cacheMode = Read;\n else if( opt.substr(index+1) == \"WriteOnly\" )\n cacheMode = Write;\n else if( opt.substr(index+1) == \"ReadWrite\" )\n cacheMode = ReadWrite;\n else\n osg::notify(osg::WARN) << \n \"NET plug-in warning: cache_mode \" << opt.substr(index+1) << \n \" not understood. Defaulting to ReadWrite.\" << std::endl;\n }\n }\n }\n\n ReadResult readResult = ReadResult::FILE_NOT_HANDLED;\n\n \/* * we accept all extensions\n std::string ext = osgDB::getFileExtension(inFileName);\n if (!acceptsExtension(ext))\n return ReadResult::FILE_NOT_HANDLED;\n *\/\n\n std::string fileName;\n int index = inFileName.find(\":\");\n \/\/ If we haven't been given a hostname as an option\n \/\/ and it hasn't been prefixed to the name, we fail\n if( index != -1 )\n {\n hostname = inFileName.substr( 0, index);\n \/\/ need to strip the inFileName of the hostname prefix\n fileName = inFileName.substr( index+1 );\n }\n else\n {\n if( hostname.empty() )\n return ReadResult::FILE_NOT_HANDLED;\n else\n fileName = inFileName;\n }\n\n \/\/ Let's also strip the possible .net extension\n if( osgDB::getFileExtension( fileName ) == \"net\" )\n {\n int rindex = fileName.rfind( \".\" );\n fileName = fileName.substr( 0, rindex );\n }\n\n if( !serverPrefix.empty() )\n fileName = serverPrefix + '\/' + fileName;\n\n \/\/ Invoke the reader corresponding to the extension\n osgDB::ReaderWriter *reader = \n osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n if( reader == 0L )\n return ReadResult::FILE_NOT_HANDLED;\n\n \/\/ Before we go to the network, lets see if it is in local cache, if cache\n \/\/ was specified and Read bit is set\n if( !localCacheDir.empty() && (cacheMode & Read) )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::fileExists( cacheFile ))\n {\n std::ifstream in(cacheFile.c_str());\n readResult = readFile(objectType, reader, in, options );\n\n in.close();\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from local cache.\" << std::endl;\n return readResult;\n }\n }\n\n \/\/ Fetch from the network\n iosockinet sio (sockbuf::sock_stream);\n try {\n sio->connect( hostname.c_str(), port );\n }\n catch( sockerr e )\n {\n osg::notify(osg::WARN) << \"osgPlugin .net reader: Unable to connect to host \" << hostname << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n\n sio << \"GET \/\" << fileName << \" HTTP\/1.1\\n\" << \"Host:\\n\\n\";\n sio.flush();\n \n char linebuff[256];\n do\n {\n sio.getline( linebuff, sizeof( linebuff ));\n\n std::istringstream iss(linebuff);\n std::string directive;\n iss >> directive;\n if( directive.substr(0,4) == \"HTTP\" )\n {\n iss >> directive;\n \/\/ Code 200. We be ok.\n if( directive == \"200\" )\n ;\n \/\/ Code 400 Bad Request\n else if( directive == \"400\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 400 - Bad Request\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 401 Bad Request\n else if( directive == \"401\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 401 - Unauthorized Access\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 403 Bad Request\n else if( directive == \"403\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 403 - Access Forbidden\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 404 File not found\n else if( directive == \"404\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 404 - File Not Found\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 405 Method not allowed\n else if( directive == \"405\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 405 - Method Not Allowed\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ There's more....\n }\n\n } while( linebuff[0] != '\\r' );\n\n \/\/ code for setting up the database path so that any paged\n \/\/ databases can be automatically located. \n osg::ref_ptr local_opt = const_cast(options);\n if (!local_opt) local_opt = new Options;\n\n if (local_opt.valid() && local_opt->getDatabasePath().empty())\n {\n local_opt->setDatabasePath(osgDB::getFilePath(inFileName));\n }\n \n \n\n\n if( reader != 0L )\n readResult = readFile(objectType, reader, sio, local_opt.get() );\n\n double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from server. in\" << ms <<\" ms\"<< std::endl;\n\n if( !localCacheDir.empty() && cacheMode & Write )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::makeDirectoryForFile( cacheFile ) )\n {\n \n switch(objectType)\n {\n case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );\n case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );\n case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );\n case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;\n }\n \n \n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" stored to local cache.\" << std::endl;\n }\n }\n\n return readResult;\n }\n \n};\n\nosgDB::RegisterReaderWriterProxy g_netReader_Proxy;\n\n \n\n\nAdded default: case for both switch() statements#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"sockinet.h\"\n\n \/*\n * Semantics:\n * Two methods for using the .net loader.\n * 1) Add a hostname prefix and a '.net' suffix on a model when passing \n * to osgDB::readNodeFile() \n * e.g: osgDB::readNodeFile( \"openscenegraph.org:cow.osg.net\" );\n *\n * 2) Explicitely load the .net plugin and pass the plugin options including\n * hostname=\n *\n * Method #1 takes precedence. SO, if the hostname option is passed the\n * plugin, but the name also contains a hostname prefix, the hostname\n * prefix on the file name will override the option\n *\n * Plugin options:\n * hostname= - Specify the host where the data file is to \n * be fetched from.\n *\n * prefix= - Specify a server directory to prefix the \n * file name with.\n * \n * local_cache_dir= - Specify a directory in which to cache files\n * on the local machine once they've been fetched. \n * This directory is also searched before fetching\n * the file from the server when Read mode is \n * enabled on the cache.\n *\n * cache_mode= - Set the mode for the local cache if local_cache\n * was specified. If local_cache was not specified\n * this directive is ignored. may\n * be specified with ReadOnly, WriteOnly, or\n * ReadWrite. Behavior for the different modes is\n * defined as:\n *\n * ReadOnly - When retrieving files, cache is \n * searched first, and if the file is\n * not present, it is fetched from the\n * server. If it is fetched from the\n * server it is not stored in local cache\n *\n * WriteOnly - When retrieving files, cache is not\n * searched, file is always retrieved\n * from the server and always written to\n * cache.\n *\n * ReadWrite - (the default). When retrieving files\n * cache is searched first, if file is\n * not present in cache, it is fetched from\n * the server. If fetched, it is written\n * to cache.\n *\n *\/\n\n\nclass NetReader : public osgDB::ReaderWriter\n{\n public:\n NetReader() {}\n \n virtual const char* className() { return \"HTTP Protocol Model Reader\"; }\n \n virtual bool acceptsExtension(const std::string& extension)\n {\n return osgDB::equalCaseInsensitive(extension,\"net\");\n }\n\n enum ObjectType\n {\n OBJECT,\n IMAGE,\n HEIGHTFIELD,\n NODE\n };\n \n virtual ReadResult readObject(const std::string& fileName, const Options* options)\n {\n return readFile(OBJECT,fileName,options);\n }\n \n virtual ReadResult readImage(const std::string& fileName, const Options *options)\n {\n return readFile(IMAGE,fileName,options);\n }\n\n virtual ReadResult readHeightField(const std::string& fileName, const Options *options)\n {\n return readFile(HEIGHTFIELD,fileName,options);\n }\n\n virtual ReadResult readNode(const std::string& fileName, const Options *options)\n {\n return readFile(NODE,fileName,options);\n }\n\n ReadResult readFile(ObjectType objectType, ReaderWriter* rw, std::istream& fin, const Options *options)\n {\n switch(objectType)\n {\n case(OBJECT): return rw->readObject(fin,options);\n case(IMAGE): return rw->readImage(fin,options);\n case(HEIGHTFIELD): return rw->readHeightField(fin,options);\n case(NODE): return rw->readNode(fin,options);\n default: break;\n }\n }\n\n virtual ReadResult readFile(ObjectType objectType, const std::string& inFileName, const Options *options)\n {\n osg::Timer_t start = osg::Timer::instance()->tick();\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: start load\" << inFileName << std::endl;\n\n std::string hostname;\n std::string serverPrefix;\n std::string localCacheDir;\n int port = 80;\n\n enum CacheMode {\n Read = 1,\n Write = 2,\n ReadWrite = 3\n };\n\n CacheMode cacheMode = ReadWrite;\n\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt) \n {\n int index = opt.find( \"=\" );\n if( opt.substr( 0, index ) == \"hostname\" ||\n opt.substr( 0, index ) == \"HOSTNAME\" )\n {\n hostname = opt.substr( index+1 );\n }\n else if( opt.substr( 0, index ) == \"port\" ||\n opt.substr( 0, index ) == \"PORT\" )\n {\n port = atoi( opt.substr(index+1).c_str() );\n }\n else if( opt.substr( 0, index ) == \"server_prefix\" ||\n opt.substr( 0, index ) == \"SERVER_PREFIX\" ||\n opt.substr( 0, index ) == \"prefix\" ||\n opt.substr( 0, index ) == \"PREFIX\" )\n {\n serverPrefix = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"local_cache_dir\" ||\n opt.substr( 0, index ) == \"LOCAL_CACHE_DIR\" )\n {\n localCacheDir = opt.substr(index+1);\n }\n else if( opt.substr( 0, index ) == \"cache_mode\" ||\n opt.substr( 0, index ) == \"CACHE_MODE\" )\n {\n if( opt.substr(index+1) == \"ReadOnly\" )\n cacheMode = Read;\n else if( opt.substr(index+1) == \"WriteOnly\" )\n cacheMode = Write;\n else if( opt.substr(index+1) == \"ReadWrite\" )\n cacheMode = ReadWrite;\n else\n osg::notify(osg::WARN) << \n \"NET plug-in warning: cache_mode \" << opt.substr(index+1) << \n \" not understood. Defaulting to ReadWrite.\" << std::endl;\n }\n }\n }\n\n ReadResult readResult = ReadResult::FILE_NOT_HANDLED;\n\n \/* * we accept all extensions\n std::string ext = osgDB::getFileExtension(inFileName);\n if (!acceptsExtension(ext))\n return ReadResult::FILE_NOT_HANDLED;\n *\/\n\n std::string fileName;\n int index = inFileName.find(\":\");\n \/\/ If we haven't been given a hostname as an option\n \/\/ and it hasn't been prefixed to the name, we fail\n if( index != -1 )\n {\n hostname = inFileName.substr( 0, index);\n \/\/ need to strip the inFileName of the hostname prefix\n fileName = inFileName.substr( index+1 );\n }\n else\n {\n if( hostname.empty() )\n return ReadResult::FILE_NOT_HANDLED;\n else\n fileName = inFileName;\n }\n\n \/\/ Let's also strip the possible .net extension\n if( osgDB::getFileExtension( fileName ) == \"net\" )\n {\n int rindex = fileName.rfind( \".\" );\n fileName = fileName.substr( 0, rindex );\n }\n\n if( !serverPrefix.empty() )\n fileName = serverPrefix + '\/' + fileName;\n\n \/\/ Invoke the reader corresponding to the extension\n osgDB::ReaderWriter *reader = \n osgDB::Registry::instance()->getReaderWriterForExtension( osgDB::getFileExtension(fileName));\n if( reader == 0L )\n return ReadResult::FILE_NOT_HANDLED;\n\n \/\/ Before we go to the network, lets see if it is in local cache, if cache\n \/\/ was specified and Read bit is set\n if( !localCacheDir.empty() && (cacheMode & Read) )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::fileExists( cacheFile ))\n {\n std::ifstream in(cacheFile.c_str());\n readResult = readFile(objectType, reader, in, options );\n\n in.close();\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from local cache.\" << std::endl;\n return readResult;\n }\n }\n\n \/\/ Fetch from the network\n iosockinet sio (sockbuf::sock_stream);\n try {\n sio->connect( hostname.c_str(), port );\n }\n catch( sockerr e )\n {\n osg::notify(osg::WARN) << \"osgPlugin .net reader: Unable to connect to host \" << hostname << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n\n sio << \"GET \/\" << fileName << \" HTTP\/1.1\\n\" << \"Host:\\n\\n\";\n sio.flush();\n \n char linebuff[256];\n do\n {\n sio.getline( linebuff, sizeof( linebuff ));\n\n std::istringstream iss(linebuff);\n std::string directive;\n iss >> directive;\n if( directive.substr(0,4) == \"HTTP\" )\n {\n iss >> directive;\n \/\/ Code 200. We be ok.\n if( directive == \"200\" )\n ;\n \/\/ Code 400 Bad Request\n else if( directive == \"400\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 400 - Bad Request\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 401 Bad Request\n else if( directive == \"401\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 401 - Unauthorized Access\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 403 Bad Request\n else if( directive == \"403\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 403 - Access Forbidden\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 404 File not found\n else if( directive == \"404\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 404 - File Not Found\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ Code 405 Method not allowed\n else if( directive == \"405\" )\n {\n osg::notify(osg::WARN) << \n \"osgPlugin .net: http server response 405 - Method Not Allowed\" << std::endl;\n return ReadResult::FILE_NOT_FOUND;\n }\n \/\/ There's more....\n }\n\n } while( linebuff[0] != '\\r' );\n\n \/\/ code for setting up the database path so that any paged\n \/\/ databases can be automatically located. \n osg::ref_ptr local_opt = const_cast(options);\n if (!local_opt) local_opt = new Options;\n\n if (local_opt.valid() && local_opt->getDatabasePath().empty())\n {\n local_opt->setDatabasePath(osgDB::getFilePath(inFileName));\n }\n \n \n\n\n if( reader != 0L )\n readResult = readFile(objectType, reader, sio, local_opt.get() );\n\n double ms = osg::Timer::instance()->delta_m(start,osg::Timer::instance()->tick());\n\n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" fetched from server. in\" << ms <<\" ms\"<< std::endl;\n\n if( !localCacheDir.empty() && cacheMode & Write )\n {\n std::string cacheFile = localCacheDir + '\/' + fileName;\n if( osgDB::makeDirectoryForFile( cacheFile ) )\n {\n \n switch(objectType)\n {\n case(OBJECT): osgDB::writeObjectFile( *(readResult.getObject()), cacheFile );\n case(IMAGE): osgDB::writeImageFile( *(readResult.getImage()), cacheFile );\n case(HEIGHTFIELD): osgDB::writeHeightFieldFile( *(readResult.getHeightField()), cacheFile );\n case(NODE): osgDB::writeNodeFile( *(readResult.getNode()), cacheFile );;\n default: break;\n }\n \n \n osg::notify(osg::DEBUG_INFO) << \"osgPlugin .net: \" << fileName << \n \" stored to local cache.\" << std::endl;\n }\n }\n\n return readResult;\n }\n \n};\n\nosgDB::RegisterReaderWriterProxy g_netReader_Proxy;\n\n \n\n\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace osg;\nusing namespace osgDB;\n\n\/\/ pull in symbols from individual .o's to enable the static build to work\nUSE_DOTOSGWRAPPER(AlphaFunc)\nUSE_DOTOSGWRAPPER(AnimationPath)\nUSE_DOTOSGWRAPPER(AutoTransform)\nUSE_DOTOSGWRAPPER(Billboard)\nUSE_DOTOSGWRAPPER(BlendColor)\nUSE_DOTOSGWRAPPER(BlendEquation)\nUSE_DOTOSGWRAPPER(BlendFunc)\nUSE_DOTOSGWRAPPER(Camera)\nUSE_DOTOSGWRAPPER(CameraView)\nUSE_DOTOSGWRAPPER(ClearNode)\nUSE_DOTOSGWRAPPER(ClipNode)\nUSE_DOTOSGWRAPPER(ClipPlane)\nUSE_DOTOSGWRAPPER(ClusterCullingCallback)\nUSE_DOTOSGWRAPPER(ColorMask)\nUSE_DOTOSGWRAPPER(ColorMatrix)\nUSE_DOTOSGWRAPPER(ConvexPlanarOccluder)\nUSE_DOTOSGWRAPPER(CoordinateSystemNode)\nUSE_DOTOSGWRAPPER(CullFace)\nUSE_DOTOSGWRAPPER(Depth)\nUSE_DOTOSGWRAPPER(Drawable)\nUSE_DOTOSGWRAPPER(EllipsoidModel)\nUSE_DOTOSGWRAPPER(Fog)\nUSE_DOTOSGWRAPPER(FragmentProgram)\nUSE_DOTOSGWRAPPER(FrontFace)\nUSE_DOTOSGWRAPPER(Geode)\nUSE_DOTOSGWRAPPER(Geometry)\nUSE_DOTOSGWRAPPER(Group)\nUSE_DOTOSGWRAPPER(Image)\nUSE_DOTOSGWRAPPER(ImageSequence)\nUSE_DOTOSGWRAPPER(Light)\nUSE_DOTOSGWRAPPER(LightModel)\nUSE_DOTOSGWRAPPER(LightSource)\nUSE_DOTOSGWRAPPER(LineStipple)\nUSE_DOTOSGWRAPPER(LineWidth)\nUSE_DOTOSGWRAPPER(LOD)\nUSE_DOTOSGWRAPPER(Material)\nUSE_DOTOSGWRAPPER(MatrixTransform)\nUSE_DOTOSGWRAPPER(NodeCallback)\nUSE_DOTOSGWRAPPER(Node)\nUSE_DOTOSGWRAPPER(Object)\nUSE_DOTOSGWRAPPER(OccluderNode)\nUSE_DOTOSGWRAPPER(OcclusionQueryNode)\nUSE_DOTOSGWRAPPER(PagedLOD)\nUSE_DOTOSGWRAPPER(Point)\nUSE_DOTOSGWRAPPER(PointSprite)\nUSE_DOTOSGWRAPPER(PolygonMode)\nUSE_DOTOSGWRAPPER(PolygonOffset)\nUSE_DOTOSGWRAPPER(PositionAttitudeTransform)\nUSE_DOTOSGWRAPPER(Program)\nUSE_DOTOSGWRAPPER(Projection)\nUSE_DOTOSGWRAPPER(ProxyNode)\nUSE_DOTOSGWRAPPER(Scissor)\nUSE_DOTOSGWRAPPER(Sequence)\nUSE_DOTOSGWRAPPER(ShadeModel)\nUSE_DOTOSGWRAPPER(Shader)\nUSE_DOTOSGWRAPPER(Sphere)\nUSE_DOTOSGWRAPPER(Cone)\nUSE_DOTOSGWRAPPER(Capsule)\nUSE_DOTOSGWRAPPER(Box)\nUSE_DOTOSGWRAPPER(HeightField)\nUSE_DOTOSGWRAPPER(CompositeShape)\nUSE_DOTOSGWRAPPER(Cylinder)\nUSE_DOTOSGWRAPPER(ShapeDrawable)\nUSE_DOTOSGWRAPPER(StateAttribute)\nUSE_DOTOSGWRAPPER(StateSet)\nUSE_DOTOSGWRAPPER(Stencil)\nUSE_DOTOSGWRAPPER(Switch)\nUSE_DOTOSGWRAPPER(TessellationHints)\nUSE_DOTOSGWRAPPER(TexEnvCombine)\nUSE_DOTOSGWRAPPER(TexEnv)\nUSE_DOTOSGWRAPPER(TexEnvFilter)\nUSE_DOTOSGWRAPPER(TexGen)\nUSE_DOTOSGWRAPPER(TexGenNode)\nUSE_DOTOSGWRAPPER(TexMat)\nUSE_DOTOSGWRAPPER(Texture1D)\nUSE_DOTOSGWRAPPER(Texture2D)\nUSE_DOTOSGWRAPPER(Texture3D)\nUSE_DOTOSGWRAPPER(Texture)\nUSE_DOTOSGWRAPPER(TextureCubeMap)\nUSE_DOTOSGWRAPPER(TextureRectangle)\nUSE_DOTOSGWRAPPER(Transform)\nUSE_DOTOSGWRAPPER(Uniform)\nUSE_DOTOSGWRAPPER(VertexProgram)\nUSE_DOTOSGWRAPPER(Viewport)\n\nclass OSGReaderWriter : public ReaderWriter\n{\n public:\n \n OSGReaderWriter()\n {\n supportsExtension(\"osg\",\"OpenSceneGraph Ascii file format\");\n supportsExtension(\"osgs\",\"Psuedo OpenSceneGraph file loaded, with file encoded in filename string\");\n supportsOption(\"precision\",\"Set the floating point precision when writing out files\");\n supportsOption(\"OutputTextureFiles\",\"Write out the texture images to file\");\n }\n \n virtual const char* className() const { return \"OSG Reader\/Writer\"; }\n\n virtual ReadResult readObject(const std::string& file, const Options* opt) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n \n if (equalCaseInsensitive(ext,\"osgs\"))\n { \n std::istringstream fin(osgDB::getNameLessExtension(file));\n if (fin) return readNode(fin,opt);\n return ReadResult::ERROR_IN_READING_FILE;\n } \n \n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, opt );\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = opt ? static_cast(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));\n\n osgDB::ifstream fin(fileName.c_str());\n if (fin)\n {\n return readObject(fin, local_opt.get());\n }\n return 0L;\n } \n\n virtual ReadResult readObject(std::istream& fin, const Options* options) const\n {\n fin.imbue(std::locale::classic());\n\n Input fr;\n fr.attach(&fin);\n fr.setOptions(options);\n \n typedef std::vector ObjectList;\n ObjectList objectList;\n\n \/\/ load all nodes in file, placing them in a group.\n while(!fr.eof())\n {\n Object *object = fr.readObject();\n if (object) objectList.push_back(object);\n else fr.advanceOverCurrentFieldOrBlock();\n }\n\n if (objectList.empty())\n {\n return ReadResult(\"No data loaded\");\n }\n else if (objectList.size()==1)\n {\n return objectList.front();\n }\n else\n {\n return objectList.front();\n }\n }\n\n virtual ReadResult readNode(const std::string& file, const Options* opt) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n\n if (equalCaseInsensitive(ext,\"osgs\"))\n { \n std::istringstream fin(osgDB::getNameLessExtension(file));\n if (fin) return readNode(fin,opt);\n return ReadResult::ERROR_IN_READING_FILE;\n } \n \n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, opt );\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = opt ? static_cast(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));\n\n osgDB::ifstream fin(fileName.c_str());\n if (fin)\n {\n return readNode(fin, local_opt.get());\n }\n return 0L;\n \n }\n \n virtual ReadResult readNode(std::istream& fin, const Options* options) const\n {\n fin.imbue(std::locale::classic());\n\n Input fr;\n fr.attach(&fin);\n fr.setOptions(options);\n \n typedef std::vector NodeList;\n NodeList nodeList;\n\n \/\/ load all nodes in file, placing them in a group.\n while(!fr.eof())\n {\n Node *node = fr.readNode();\n if (node) nodeList.push_back(node);\n else fr.advanceOverCurrentFieldOrBlock();\n }\n\n if (nodeList.empty())\n {\n return ReadResult(\"No data loaded\");\n }\n else if (nodeList.size()==1)\n {\n return nodeList.front();\n }\n else\n {\n Group* group = new Group;\n group->setName(\"import group\");\n for(NodeList::iterator itr=nodeList.begin();\n itr!=nodeList.end();\n ++itr)\n {\n group->addChild(*itr);\n }\n return group;\n }\n\n }\n\n void setPrecision(Output& fout, const osgDB::ReaderWriter::Options* options) const\n {\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt)\n {\n if(opt==\"PRECISION\" || opt==\"precision\") \n {\n int prec;\n iss >> prec;\n fout.precision(prec);\n }\n if (opt==\"OutputTextureFiles\")\n {\n fout.setOutputTextureFiles(true);\n }\n }\n }\n } \n\n virtual WriteResult writeObject(const Object& obj, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n Output fout(fileName.c_str());\n if (fout)\n {\n fout.setOptions(options);\n\n setPrecision(fout,options);\n\n fout.imbue(std::locale::classic());\n\n fout.writeObject(obj);\n fout.close();\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to open file for output\");\n }\n\n virtual WriteResult writeObject(const Object& obj,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n\n if (fout)\n {\n Output foutput;\n foutput.setOptions(options);\n\n std::ios &fios = foutput;\n fios.rdbuf(fout.rdbuf());\n\n fout.imbue(std::locale::classic());\n\n setPrecision(foutput,options);\n\n foutput.writeObject(obj);\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to write to output stream\");\n }\n\n\n virtual WriteResult writeNode(const Node& node, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n\n Output fout(fileName.c_str());\n if (fout)\n {\n fout.setOptions(options);\n\n fout.imbue(std::locale::classic());\n\n setPrecision(fout,options);\n\n fout.writeObject(node);\n fout.close();\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to open file for output\");\n }\n\n virtual WriteResult writeNode(const Node& node, std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n\n\n if (fout)\n {\n Output foutput;\n foutput.setOptions(options);\n\n std::ios &fios = foutput;\n fios.rdbuf(fout.rdbuf());\n\n foutput.imbue(std::locale::classic());\n\n setPrecision(foutput,options);\n\n foutput.writeObject(node);\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to write to output stream\");\n }\n\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(osg, OSGReaderWriter)\nFrom Bryan Thrall, \"The .osg plugin doesn't seem to support an option to write shader files separately, so it always inlines them in the .osg file (as far as I can tell). This change adds that ability. \"#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace osg;\nusing namespace osgDB;\n\n\/\/ pull in symbols from individual .o's to enable the static build to work\nUSE_DOTOSGWRAPPER(AlphaFunc)\nUSE_DOTOSGWRAPPER(AnimationPath)\nUSE_DOTOSGWRAPPER(AutoTransform)\nUSE_DOTOSGWRAPPER(Billboard)\nUSE_DOTOSGWRAPPER(BlendColor)\nUSE_DOTOSGWRAPPER(BlendEquation)\nUSE_DOTOSGWRAPPER(BlendFunc)\nUSE_DOTOSGWRAPPER(Camera)\nUSE_DOTOSGWRAPPER(CameraView)\nUSE_DOTOSGWRAPPER(ClearNode)\nUSE_DOTOSGWRAPPER(ClipNode)\nUSE_DOTOSGWRAPPER(ClipPlane)\nUSE_DOTOSGWRAPPER(ClusterCullingCallback)\nUSE_DOTOSGWRAPPER(ColorMask)\nUSE_DOTOSGWRAPPER(ColorMatrix)\nUSE_DOTOSGWRAPPER(ConvexPlanarOccluder)\nUSE_DOTOSGWRAPPER(CoordinateSystemNode)\nUSE_DOTOSGWRAPPER(CullFace)\nUSE_DOTOSGWRAPPER(Depth)\nUSE_DOTOSGWRAPPER(Drawable)\nUSE_DOTOSGWRAPPER(EllipsoidModel)\nUSE_DOTOSGWRAPPER(Fog)\nUSE_DOTOSGWRAPPER(FragmentProgram)\nUSE_DOTOSGWRAPPER(FrontFace)\nUSE_DOTOSGWRAPPER(Geode)\nUSE_DOTOSGWRAPPER(Geometry)\nUSE_DOTOSGWRAPPER(Group)\nUSE_DOTOSGWRAPPER(Image)\nUSE_DOTOSGWRAPPER(ImageSequence)\nUSE_DOTOSGWRAPPER(Light)\nUSE_DOTOSGWRAPPER(LightModel)\nUSE_DOTOSGWRAPPER(LightSource)\nUSE_DOTOSGWRAPPER(LineStipple)\nUSE_DOTOSGWRAPPER(LineWidth)\nUSE_DOTOSGWRAPPER(LOD)\nUSE_DOTOSGWRAPPER(Material)\nUSE_DOTOSGWRAPPER(MatrixTransform)\nUSE_DOTOSGWRAPPER(NodeCallback)\nUSE_DOTOSGWRAPPER(Node)\nUSE_DOTOSGWRAPPER(Object)\nUSE_DOTOSGWRAPPER(OccluderNode)\nUSE_DOTOSGWRAPPER(OcclusionQueryNode)\nUSE_DOTOSGWRAPPER(PagedLOD)\nUSE_DOTOSGWRAPPER(Point)\nUSE_DOTOSGWRAPPER(PointSprite)\nUSE_DOTOSGWRAPPER(PolygonMode)\nUSE_DOTOSGWRAPPER(PolygonOffset)\nUSE_DOTOSGWRAPPER(PositionAttitudeTransform)\nUSE_DOTOSGWRAPPER(Program)\nUSE_DOTOSGWRAPPER(Projection)\nUSE_DOTOSGWRAPPER(ProxyNode)\nUSE_DOTOSGWRAPPER(Scissor)\nUSE_DOTOSGWRAPPER(Sequence)\nUSE_DOTOSGWRAPPER(ShadeModel)\nUSE_DOTOSGWRAPPER(Shader)\nUSE_DOTOSGWRAPPER(Sphere)\nUSE_DOTOSGWRAPPER(Cone)\nUSE_DOTOSGWRAPPER(Capsule)\nUSE_DOTOSGWRAPPER(Box)\nUSE_DOTOSGWRAPPER(HeightField)\nUSE_DOTOSGWRAPPER(CompositeShape)\nUSE_DOTOSGWRAPPER(Cylinder)\nUSE_DOTOSGWRAPPER(ShapeDrawable)\nUSE_DOTOSGWRAPPER(StateAttribute)\nUSE_DOTOSGWRAPPER(StateSet)\nUSE_DOTOSGWRAPPER(Stencil)\nUSE_DOTOSGWRAPPER(Switch)\nUSE_DOTOSGWRAPPER(TessellationHints)\nUSE_DOTOSGWRAPPER(TexEnvCombine)\nUSE_DOTOSGWRAPPER(TexEnv)\nUSE_DOTOSGWRAPPER(TexEnvFilter)\nUSE_DOTOSGWRAPPER(TexGen)\nUSE_DOTOSGWRAPPER(TexGenNode)\nUSE_DOTOSGWRAPPER(TexMat)\nUSE_DOTOSGWRAPPER(Texture1D)\nUSE_DOTOSGWRAPPER(Texture2D)\nUSE_DOTOSGWRAPPER(Texture3D)\nUSE_DOTOSGWRAPPER(Texture)\nUSE_DOTOSGWRAPPER(TextureCubeMap)\nUSE_DOTOSGWRAPPER(TextureRectangle)\nUSE_DOTOSGWRAPPER(Transform)\nUSE_DOTOSGWRAPPER(Uniform)\nUSE_DOTOSGWRAPPER(VertexProgram)\nUSE_DOTOSGWRAPPER(Viewport)\n\nclass OSGReaderWriter : public ReaderWriter\n{\n public:\n \n OSGReaderWriter()\n {\n supportsExtension(\"osg\",\"OpenSceneGraph Ascii file format\");\n supportsExtension(\"osgs\",\"Psuedo OpenSceneGraph file loaded, with file encoded in filename string\");\n supportsOption(\"precision\",\"Set the floating point precision when writing out files\");\n supportsOption(\"OutputTextureFiles\",\"Write out the texture images to file\");\n }\n \n virtual const char* className() const { return \"OSG Reader\/Writer\"; }\n\n virtual ReadResult readObject(const std::string& file, const Options* opt) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n \n if (equalCaseInsensitive(ext,\"osgs\"))\n { \n std::istringstream fin(osgDB::getNameLessExtension(file));\n if (fin) return readNode(fin,opt);\n return ReadResult::ERROR_IN_READING_FILE;\n } \n \n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, opt );\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = opt ? static_cast(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));\n\n osgDB::ifstream fin(fileName.c_str());\n if (fin)\n {\n return readObject(fin, local_opt.get());\n }\n return 0L;\n } \n\n virtual ReadResult readObject(std::istream& fin, const Options* options) const\n {\n fin.imbue(std::locale::classic());\n\n Input fr;\n fr.attach(&fin);\n fr.setOptions(options);\n \n typedef std::vector ObjectList;\n ObjectList objectList;\n\n \/\/ load all nodes in file, placing them in a group.\n while(!fr.eof())\n {\n Object *object = fr.readObject();\n if (object) objectList.push_back(object);\n else fr.advanceOverCurrentFieldOrBlock();\n }\n\n if (objectList.empty())\n {\n return ReadResult(\"No data loaded\");\n }\n else if (objectList.size()==1)\n {\n return objectList.front();\n }\n else\n {\n return objectList.front();\n }\n }\n\n virtual ReadResult readNode(const std::string& file, const Options* opt) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(file);\n\n if (equalCaseInsensitive(ext,\"osgs\"))\n { \n std::istringstream fin(osgDB::getNameLessExtension(file));\n if (fin) return readNode(fin,opt);\n return ReadResult::ERROR_IN_READING_FILE;\n } \n \n if (!acceptsExtension(ext)) return ReadResult::FILE_NOT_HANDLED;\n\n std::string fileName = osgDB::findDataFile( file, opt );\n if (fileName.empty()) return ReadResult::FILE_NOT_FOUND;\n\n \/\/ code for setting up the database path so that internally referenced file are searched for on relative paths. \n osg::ref_ptr local_opt = opt ? static_cast(opt->clone(osg::CopyOp::SHALLOW_COPY)) : new Options;\n local_opt->getDatabasePathList().push_front(osgDB::getFilePath(fileName));\n\n osgDB::ifstream fin(fileName.c_str());\n if (fin)\n {\n return readNode(fin, local_opt.get());\n }\n return 0L;\n \n }\n \n virtual ReadResult readNode(std::istream& fin, const Options* options) const\n {\n fin.imbue(std::locale::classic());\n\n Input fr;\n fr.attach(&fin);\n fr.setOptions(options);\n \n typedef std::vector NodeList;\n NodeList nodeList;\n\n \/\/ load all nodes in file, placing them in a group.\n while(!fr.eof())\n {\n Node *node = fr.readNode();\n if (node) nodeList.push_back(node);\n else fr.advanceOverCurrentFieldOrBlock();\n }\n\n if (nodeList.empty())\n {\n return ReadResult(\"No data loaded\");\n }\n else if (nodeList.size()==1)\n {\n return nodeList.front();\n }\n else\n {\n Group* group = new Group;\n group->setName(\"import group\");\n for(NodeList::iterator itr=nodeList.begin();\n itr!=nodeList.end();\n ++itr)\n {\n group->addChild(*itr);\n }\n return group;\n }\n\n }\n\n void setPrecision(Output& fout, const osgDB::ReaderWriter::Options* options) const\n {\n if (options)\n {\n std::istringstream iss(options->getOptionString());\n std::string opt;\n while (iss >> opt)\n {\n if(opt==\"PRECISION\" || opt==\"precision\") \n {\n int prec;\n iss >> prec;\n fout.precision(prec);\n }\n if (opt==\"OutputTextureFiles\")\n {\n fout.setOutputTextureFiles(true);\n }\n if (opt==\"OutputShaderFiles\")\n {\n fout.setOutputShaderFiles(true);\n }\n }\n }\n } \n\n virtual WriteResult writeObject(const Object& obj, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = osgDB::getLowerCaseFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n Output fout(fileName.c_str());\n if (fout)\n {\n fout.setOptions(options);\n\n setPrecision(fout,options);\n\n fout.imbue(std::locale::classic());\n\n fout.writeObject(obj);\n fout.close();\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to open file for output\");\n }\n\n virtual WriteResult writeObject(const Object& obj,std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n\n if (fout)\n {\n Output foutput;\n foutput.setOptions(options);\n\n std::ios &fios = foutput;\n fios.rdbuf(fout.rdbuf());\n\n fout.imbue(std::locale::classic());\n\n setPrecision(foutput,options);\n\n foutput.writeObject(obj);\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to write to output stream\");\n }\n\n\n virtual WriteResult writeNode(const Node& node, const std::string& fileName, const osgDB::ReaderWriter::Options* options) const\n {\n std::string ext = getFileExtension(fileName);\n if (!acceptsExtension(ext)) return WriteResult::FILE_NOT_HANDLED;\n\n\n Output fout(fileName.c_str());\n if (fout)\n {\n fout.setOptions(options);\n\n fout.imbue(std::locale::classic());\n\n setPrecision(fout,options);\n\n fout.writeObject(node);\n fout.close();\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to open file for output\");\n }\n\n virtual WriteResult writeNode(const Node& node, std::ostream& fout, const osgDB::ReaderWriter::Options* options) const\n {\n\n\n if (fout)\n {\n Output foutput;\n foutput.setOptions(options);\n\n std::ios &fios = foutput;\n fios.rdbuf(fout.rdbuf());\n\n foutput.imbue(std::locale::classic());\n\n setPrecision(foutput,options);\n\n foutput.writeObject(node);\n return WriteResult::FILE_SAVED;\n }\n return WriteResult(\"Unable to write to output stream\");\n }\n\n};\n\n\/\/ now register with Registry to instantiate the above\n\/\/ reader\/writer.\nREGISTER_OSGPLUGIN(osg, OSGReaderWriter)\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ This source file is part of the YETI open source package under the\n\/\/ BSD (2-clause) licence (see LICENCE file for details).\n\/\/\n\/\/ (c) H Hathrell, R F L Evans 2014. All rights reserved.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n\/\/ System headers\n#include \n\n\/\/ Program headers\n#include \"material.hpp\"\n#include \"object.hpp\"\n#include \"yeti.hpp\"\n\nnamespace yeti{\n \n\/\/-----------------------------------------------------------------------------\n\/\/ Function to determine material properties as a function of position\n\/\/-----------------------------------------------------------------------------\nmaterial_t get_material_properties(double x,double y,double z){ \/\/determine pAZ from inshape\n\n \/\/ declare temporary object to store result\n material_t result;\n\n \/\/ define negative starting order\n int maxorder = -1;\n\n \/\/ loop over all objects in list\n for (unsigned int i=0; iinshape(x,y,z);\n\n \/\/ Test if object has greater hierarchy\n bool test_hierarchy = objects::object_list[i]->order>maxorder;\n\n \/\/ check for both conditions true\n if (test_inside && test_hierarchy ){\n\n \/\/ update result with copy of object\n result.p = objects::object_list[i]->p;\n\n \/\/ update max order\n maxorder=objects::object_list[i]->order;\n\n }\n\n }\n\n \/\/ return final parameters\n return result;\n\n}\n\n}\nBugfix: Corrected missing pointers to Z and A values in material properties function\/\/-----------------------------------------------------------------------------\n\/\/\n\/\/ This source file is part of the YETI open source package under the\n\/\/ BSD (2-clause) licence (see LICENCE file for details).\n\/\/\n\/\/ (c) H Hathrell, R F L Evans 2014. All rights reserved.\n\/\/\n\/\/-----------------------------------------------------------------------------\n\n\/\/ System headers\n#include \n\n\/\/ Program headers\n#include \"material.hpp\"\n#include \"object.hpp\"\n#include \"yeti.hpp\"\n\nnamespace yeti{\n \n\/\/-----------------------------------------------------------------------------\n\/\/ Function to determine material properties as a function of position\n\/\/-----------------------------------------------------------------------------\nmaterial_t get_material_properties(double x,double y,double z){ \/\/determine pAZ from inshape\n\n \/\/ declare temporary object to store result\n material_t result;\n\n \/\/ define negative starting order\n int maxorder = -1;\n\n \/\/ loop over all objects in list\n for (unsigned int i=0; iinshape(x,y,z);\n\n \/\/ Test if object has greater hierarchy\n bool test_hierarchy = objects::object_list[i]->order>maxorder;\n\n \/\/ check for both conditions true\n if (test_inside && test_hierarchy ){\n\n \/\/ update result with copy of object\n result.p = objects::object_list[i]->p;\n result.Z = objects::object_list[i]->Z;\n result.A = objects::object_list[i]->A;\n\n \/\/ update max order\n maxorder=objects::object_list[i]->order;\n\n }\n\n }\n\n \/\/ return final parameters\n return result;\n\n}\n\n}\n<|endoftext|>"} {"text":"#include \n\n#if NODE_VERSION_AT_LEAST(0, 11, 1) && !defined(_MSC_VER)\n#include \n#endif\n\n#include \n\n#include \n\n#if defined(_MSC_VER)\n#include \n#include \n\n\/\/ Pick GetSystemTimePreciseAsFileTime or GetSystemTimeAsFileTime depending\n\/\/ on which is available at runtime.\ntypedef VOID(WINAPI *WinGetSystemTime)(LPFILETIME);\nstatic WinGetSystemTime getSystemTime = NULL;\n\nstruct timezone {\n int tz_minuteswest;\n int tz_dsttime;\n};\n\nint gettimeofday(struct timeval *tv, struct timezone *tz) {\n FILETIME ft;\n (*getSystemTime)(&ft);\n unsigned long long t = ft.dwHighDateTime;\n t <<= 32;\n t |= ft.dwLowDateTime;\n t \/= 10;\n t -= 11644473600000000ULL;\n tv->tv_sec = (long)(t \/ 1000000UL);\n tv->tv_usec = (long)(t % 1000000UL);\n\n return 0;\n}\n#else\n#include \n#endif\n\nNapi::Value Now(const Napi::CallbackInfo &info) {\n timeval t;\n int r = gettimeofday(&t, NULL);\n\n if (r < 0) {\n Napi::Error e = Napi::Error::New(info.Env(), \"gettimeofday\");\n e.Set(\"code\", Napi::Number::New(info.Env(), errno));\n throw e;\n }\n\n return Napi::Number::New(info.Env(), ((t.tv_sec * 1000000.0) + t.tv_usec));\n}\n\nNapi::Value NowDouble(const Napi::CallbackInfo &info) {\n timeval t;\n int r = gettimeofday(&t, NULL);\n if (r < 0) {\n Napi::Error e = Napi::Error::New(info.Env(), \"gettimeofday\");\n e.Set(\"code\", Napi::Number::New(info.Env(), errno));\n throw e;\n }\n\n return Napi::Number::New(info.Env(), t.tv_sec + (t.tv_usec * 0.000001));\n}\n\nNapi::Value NowStruct(const Napi::CallbackInfo &info) {\n timeval t;\n int r = gettimeofday(&t, NULL);\n\n if (r < 0) {\n Napi::Error e = Napi::Error::New(info.Env(), \"gettimeofday\");\n e.Set(\"code\", Napi::Number::New(info.Env(), errno));\n throw e;\n }\n\n Napi::Array array = Napi::Array::New(info.Env(), 2);\n array.Set((uint32_t)0, (double)t.tv_sec);\n array.Set((uint32_t)1, (double)t.tv_usec);\n\n return array;\n}\n\nNapi::Object Init(Napi::Env env, Napi::Object exports) {\n exports.Set(Napi::String::New(env, \"now\"), Napi::Function::New(env, Now));\n exports.Set(Napi::String::New(env, \"nowDouble\"),\n Napi::Function::New(env, NowDouble));\n exports.Set(Napi::String::New(env, \"nowStruct\"),\n Napi::Function::New(env, NowStruct));\n#if defined(_MSC_VER)\n getSystemTime = (WinGetSystemTime)GetProcAddress(\n GetModuleHandle(TEXT(\"kernel32.dll\")), \"GetSystemTimePreciseAsFileTime\");\n if (getSystemTime == NULL) {\n getSystemTime = &GetSystemTimeAsFileTime;\n }\n#endif\n return exports;\n}\n\nNODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);\nAdd more robust ErrnoException#include \n\n#if NODE_VERSION_AT_LEAST(0, 11, 1) && !defined(_MSC_VER)\n#include \n#endif\n\n#include \n\n#include \n\n#if defined(_MSC_VER)\n#include \n#include \n\n\/\/ Pick GetSystemTimePreciseAsFileTime or GetSystemTimeAsFileTime depending\n\/\/ on which is available at runtime.\ntypedef VOID(WINAPI *WinGetSystemTime)(LPFILETIME);\nstatic WinGetSystemTime getSystemTime = NULL;\n\nstruct timezone {\n int tz_minuteswest;\n int tz_dsttime;\n};\n\nint gettimeofday(struct timeval *tv, struct timezone *tz) {\n FILETIME ft;\n (*getSystemTime)(&ft);\n unsigned long long t = ft.dwHighDateTime;\n t <<= 32;\n t |= ft.dwLowDateTime;\n t \/= 10;\n t -= 11644473600000000ULL;\n tv->tv_sec = (long)(t \/ 1000000UL);\n tv->tv_usec = (long)(t % 1000000UL);\n\n return 0;\n}\n#else\n#include \n#endif\n\n\/\/ A very basic version of Node::ErrnoException since Napi doesn't expose it\nNapi::Error ErrnoException(Napi::Env env, int errorno) {\n Napi::Error e = Napi::Error::New(env, strerror(errorno));\n e.Set(\"syscall\", Napi::String::New(env, \"gettimeofday\"));\n e.Set(\"errno\", Napi::Number::New(env, errno));\n \/\/ NOTE: in Node::ErrnoException this would be the string of the code\n \/\/ like \"EFAULT\", just simplify with the number here.\n e.Set(\"code\", Napi::Number::New(env, errno));\n return e;\n}\n\nNapi::Value Now(const Napi::CallbackInfo &info) {\n timeval t;\n int r = gettimeofday(&t, NULL);\n\n if (r < 0) {\n throw ErrnoException(info.Env(), errno);\n }\n\n return Napi::Number::New(info.Env(), ((t.tv_sec * 1000000.0) + t.tv_usec));\n}\n\nNapi::Value NowDouble(const Napi::CallbackInfo &info) {\n timeval t;\n int r = gettimeofday(&t, NULL);\n if (r < 0) {\n throw ErrnoException(info.Env(), errno);\n }\n\n return Napi::Number::New(info.Env(), t.tv_sec + (t.tv_usec * 0.000001));\n}\n\nNapi::Value NowStruct(const Napi::CallbackInfo &info) {\n timeval t;\n int r = gettimeofday(&t, NULL);\n\n if (r < 0) {\n throw ErrnoException(info.Env(), errno);\n }\n\n Napi::Array array = Napi::Array::New(info.Env(), 2);\n array.Set((uint32_t)0, (double)t.tv_sec);\n array.Set((uint32_t)1, (double)t.tv_usec);\n\n return array;\n}\n\nNapi::Object Init(Napi::Env env, Napi::Object exports) {\n exports.Set(Napi::String::New(env, \"now\"), Napi::Function::New(env, Now));\n exports.Set(Napi::String::New(env, \"nowDouble\"),\n Napi::Function::New(env, NowDouble));\n exports.Set(Napi::String::New(env, \"nowStruct\"),\n Napi::Function::New(env, NowStruct));\n#if defined(_MSC_VER)\n getSystemTime = (WinGetSystemTime)GetProcAddress(\n GetModuleHandle(TEXT(\"kernel32.dll\")), \"GetSystemTimePreciseAsFileTime\");\n if (getSystemTime == NULL) {\n getSystemTime = &GetSystemTimeAsFileTime;\n }\n#endif\n return exports;\n}\n\nNODE_API_MODULE(NODE_GYP_MODULE_NAME, Init);\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Las Venturas Playground. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license, a copy of which can\n\/\/ be found in the LICENSE file.\n\n#include \"playground\/plugin\/native_parser.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_piece.h\"\n#include \"bindings\/provided_natives.h\"\n#include \"plugin\/native_parameters.h\"\n#include \"plugin\/sdk\/amx.h\"\n\n#if defined(LINUX)\n#define _strdup strdup\n#endif\n\nnamespace plugin {\nnamespace {\n\n\/\/ The whitespace characters as specified by CSS 2.1.\nconst char kWhitespaceCharacters[] = \"\\x09\\x0A\\x0C\\x0D\\x20\";\n\n\/\/ The global instance of the NativeParser object. Required for the native functions themselves.\nNativeParser* g_native_parser = nullptr;\n\n\/\/ Removes all whitespace from the front and back of |string|, and returns the result.\nbase::StringPiece Trim(const base::StringPiece& input) {\n if (input.empty())\n return input;\n\n const size_t first_good_char = input.find_first_not_of(kWhitespaceCharacters);\n const size_t last_good_char = input.find_last_not_of(kWhitespaceCharacters);\n\n if (first_good_char == base::StringPiece::npos ||\n last_good_char == base::StringPiece::npos)\n return base::StringPiece();\n\n return input.substr(first_good_char, last_good_char - first_good_char + 1);\n}\n\n\/\/ Returns whether |character| is valid for use in a native function name.\nbool IsValidCharacter(char character) {\n return (character >= 'A' && character <= 'Z') ||\n (character >= 'a' && character <= 'z') || character == '_';\n}\n\n\/\/ Registers |N| native functions, creates |N| functions that will automagically forward the call\n\/\/ to the ProvidedNatives bindings class when called with minimal overhead.\ntemplate struct NativeRegistrar {\n static void Register() {\n DCHECK(g_native_parser);\n\n constexpr size_t native_index = NativeParser::kMaxNatives - N;\n if (native_index < g_native_parser->size()) {\n AMX_NATIVE_INFO* native = &g_native_parser->GetNativeTable()[native_index];\n native->name = _strdup(g_native_parser->at(native_index).c_str());\n native->func = &NativeRegistrar::Invoke;\n }\n\n NativeRegistrar::Register();\n }\n\n static int32_t AMX_NATIVE_CALL Invoke(AMX* amx, cell* params) {\n DCHECK(g_native_parser);\n\n constexpr size_t native_index = NativeParser::kMaxNatives - N;\n\n NativeParameters parameters(amx, params);\n return bindings::ProvidedNatives::GetInstance()->Call(g_native_parser->at(native_index), parameters);\n }\n};\n\ntemplate <> struct NativeRegistrar<0> {\n static void Register() {}\n};\n\n} \/\/ namespace\n\nstd::unique_ptr NativeParser::FromFile(const base::FilePath& filename) {\n std::ifstream file(filename.value().c_str());\n if (!file.is_open() || file.fail())\n return nullptr;\n\n std::string content((std::istreambuf_iterator(file)),\n std::istreambuf_iterator());\n\n std::unique_ptr parser(new NativeParser);\n if (!parser->Parse(content))\n return nullptr;\n\n return parser;\n}\n\nNativeParser::NativeParser() {\n g_native_parser = this;\n memset(native_table_, 0, sizeof(native_table_));\n}\n\nNativeParser::~NativeParser() {\n g_native_parser = nullptr;\n}\n\nsize_t NativeParser::size() const {\n return natives_.size();\n}\n\nconst std::string& NativeParser::at(size_t index) const {\n DCHECK(natives_.size() > index);\n return natives_[index];\n}\n\nbool NativeParser::Parse(const std::string& content) {\n base::StringPiece content_lines(content);\n if (!content_lines.length())\n return true; \/\/ empty contents\n\n size_t start = 0;\n while (start != base::StringPiece::npos) {\n size_t end = content_lines.find_first_of(\"\\n\", start);\n\n base::StringPiece line;\n if (end == base::StringPiece::npos) {\n line = content_lines.substr(start);\n start = end;\n }\n else {\n line = content_lines.substr(start, end - start);\n start = end + 1;\n }\n\n line = Trim(line);\n if (line.empty())\n continue; \/\/ do not process empty lines.\n\n if (line.starts_with(\"#\") || line.starts_with(\"\/\/\"))\n continue; \/\/ comment line.\n\n if (!ParseLine(line))\n return false;\n }\n\n if (natives_.size() > kMaxNatives) {\n LOG(ERROR) << \"No more than \" << kMaxNatives << \" may be defined in natives.txt.\";\n return false;\n }\n\n bindings::ProvidedNatives::GetInstance()->SetNatives(natives_);\n BuildNativeTable();\n\n return true;\n}\n\nbool NativeParser::ParseLine(base::StringPiece line) {\n for (size_t i = 0; i < line.length(); ++i) {\n if (!IsValidCharacter(line[i])) {\n LOG(ERROR) << \"Invalid native function name: \" << line.as_string();\n return false;\n }\n }\n\n const std::string name = line.as_string();\n if (std::find(natives_.begin(), natives_.end(), name) != natives_.end()) {\n LOG(ERROR) << \"Native has been listed multiple times: \" << line.as_string();\n return false;\n }\n\n natives_.push_back(name);\n return true;\n}\n\nvoid NativeParser::BuildNativeTable() {\n NativeRegistrar::Register();\n}\n\n} \/\/ namespace plugin\nAllow numbers in native names too\/\/ Copyright 2016 Las Venturas Playground. All rights reserved.\n\/\/ Use of this source code is governed by the MIT license, a copy of which can\n\/\/ be found in the LICENSE file.\n\n#include \"playground\/plugin\/native_parser.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_piece.h\"\n#include \"bindings\/provided_natives.h\"\n#include \"plugin\/native_parameters.h\"\n#include \"plugin\/sdk\/amx.h\"\n\n#if defined(LINUX)\n#define _strdup strdup\n#endif\n\nnamespace plugin {\nnamespace {\n\n\/\/ The whitespace characters as specified by CSS 2.1.\nconst char kWhitespaceCharacters[] = \"\\x09\\x0A\\x0C\\x0D\\x20\";\n\n\/\/ The global instance of the NativeParser object. Required for the native functions themselves.\nNativeParser* g_native_parser = nullptr;\n\n\/\/ Removes all whitespace from the front and back of |string|, and returns the result.\nbase::StringPiece Trim(const base::StringPiece& input) {\n if (input.empty())\n return input;\n\n const size_t first_good_char = input.find_first_not_of(kWhitespaceCharacters);\n const size_t last_good_char = input.find_last_not_of(kWhitespaceCharacters);\n\n if (first_good_char == base::StringPiece::npos ||\n last_good_char == base::StringPiece::npos)\n return base::StringPiece();\n\n return input.substr(first_good_char, last_good_char - first_good_char + 1);\n}\n\n\/\/ Returns whether |character| is valid for use in a native function name.\nbool IsValidCharacter(char character) {\n return (character >= 'A' && character <= 'Z') ||\n (character >= 'a' && character <= 'z') ||\n (character >= '0' && character <= '9') || character == '_';\n}\n\n\/\/ Registers |N| native functions, creates |N| functions that will automagically forward the call\n\/\/ to the ProvidedNatives bindings class when called with minimal overhead.\ntemplate struct NativeRegistrar {\n static void Register() {\n DCHECK(g_native_parser);\n\n constexpr size_t native_index = NativeParser::kMaxNatives - N;\n if (native_index < g_native_parser->size()) {\n AMX_NATIVE_INFO* native = &g_native_parser->GetNativeTable()[native_index];\n native->name = _strdup(g_native_parser->at(native_index).c_str());\n native->func = &NativeRegistrar::Invoke;\n }\n\n NativeRegistrar::Register();\n }\n\n static int32_t AMX_NATIVE_CALL Invoke(AMX* amx, cell* params) {\n DCHECK(g_native_parser);\n\n constexpr size_t native_index = NativeParser::kMaxNatives - N;\n\n NativeParameters parameters(amx, params);\n return bindings::ProvidedNatives::GetInstance()->Call(g_native_parser->at(native_index), parameters);\n }\n};\n\ntemplate <> struct NativeRegistrar<0> {\n static void Register() {}\n};\n\n} \/\/ namespace\n\nstd::unique_ptr NativeParser::FromFile(const base::FilePath& filename) {\n std::ifstream file(filename.value().c_str());\n if (!file.is_open() || file.fail())\n return nullptr;\n\n std::string content((std::istreambuf_iterator(file)),\n std::istreambuf_iterator());\n\n std::unique_ptr parser(new NativeParser);\n if (!parser->Parse(content))\n return nullptr;\n\n return parser;\n}\n\nNativeParser::NativeParser() {\n g_native_parser = this;\n memset(native_table_, 0, sizeof(native_table_));\n}\n\nNativeParser::~NativeParser() {\n g_native_parser = nullptr;\n}\n\nsize_t NativeParser::size() const {\n return natives_.size();\n}\n\nconst std::string& NativeParser::at(size_t index) const {\n DCHECK(natives_.size() > index);\n return natives_[index];\n}\n\nbool NativeParser::Parse(const std::string& content) {\n base::StringPiece content_lines(content);\n if (!content_lines.length())\n return true; \/\/ empty contents\n\n size_t start = 0;\n while (start != base::StringPiece::npos) {\n size_t end = content_lines.find_first_of(\"\\n\", start);\n\n base::StringPiece line;\n if (end == base::StringPiece::npos) {\n line = content_lines.substr(start);\n start = end;\n }\n else {\n line = content_lines.substr(start, end - start);\n start = end + 1;\n }\n\n line = Trim(line);\n if (line.empty())\n continue; \/\/ do not process empty lines.\n\n if (line.starts_with(\"#\") || line.starts_with(\"\/\/\"))\n continue; \/\/ comment line.\n\n if (!ParseLine(line))\n return false;\n }\n\n if (natives_.size() > kMaxNatives) {\n LOG(ERROR) << \"No more than \" << kMaxNatives << \" may be defined in natives.txt.\";\n return false;\n }\n\n bindings::ProvidedNatives::GetInstance()->SetNatives(natives_);\n BuildNativeTable();\n\n return true;\n}\n\nbool NativeParser::ParseLine(base::StringPiece line) {\n for (size_t i = 0; i < line.length(); ++i) {\n if (!IsValidCharacter(line[i])) {\n LOG(ERROR) << \"Invalid native function name: \" << line.as_string();\n return false;\n }\n }\n\n const std::string name = line.as_string();\n if (std::find(natives_.begin(), natives_.end(), name) != natives_.end()) {\n LOG(ERROR) << \"Native has been listed multiple times: \" << line.as_string();\n return false;\n }\n\n natives_.push_back(name);\n return true;\n}\n\nvoid NativeParser::BuildNativeTable() {\n NativeRegistrar::Register();\n}\n\n} \/\/ namespace plugin\n<|endoftext|>"} {"text":"#include \"assembly_reader.h\"\n\n#include \n\n#include \"..\/common\/ptr_util.h\"\n#include \"opcodes.h\"\n#include \"..\/pe\/coded_index.h\"\n#include \"..\/pe\/pe_image_reader.h\"\n#include \"assembly.h\"\n\nnamespace stereo {\n namespace assemblies {\n\n AssemblyReader::AssemblyReader(const char* file_path)\n :\n logger_(std::make_unique()),\n image_(pe::PEImageReader::load_image(file_path))\n {\n }\n\n u32 AssemblyReader::get_entry_point()\n {\n auto ept = pe::MetadataToken(image_->cli_header.entry_point_token);\n return ept.rid();\n }\n\n const ModuleDef* AssemblyReader::read_module_def()\n {\n if (module_ != nullptr)\n return module_.get();\n\n auto module = std::make_unique();\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Module, 1);\n\n \/\/ Skip the generation column since it's always zero\n table_row_ptr += 2;\n\n module->name = read_string(&table_row_ptr);\n\n \/\/ TODO: Read the mvid guid\n\n module_ = std::move(module);\n return module_.get();\n }\n\n const MethodDef* AssemblyReader::read_method_def(u32 rid)\n {\n if (already_read(method_defs_, rid))\n return method_defs_[get_index_from_rid(rid)].get();\n\n resize_if_needed(method_defs_, pe::MetadataTable::Method);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Method, rid);\n auto method_def = std::make_unique();\n\n \/\/ RVA (a 4-byte constant) \n method_def->rva = ptrutil::read32(&table_row_ptr);\n\n \/\/ ImplFlags (a 2-byte bitmask of type MethodImplAttributes, II.23.1.10) \n method_def->impl_attributes = static_cast(ptrutil::read16(&table_row_ptr));\n\n \/\/ Flags (a 2-byte bitmask of type MethodAttributes, II.23.1.10) \n method_def->attributes = static_cast(ptrutil::read16(&table_row_ptr));\n\n \/\/ Name (an index into the String heap) \n method_def->name = read_string(&table_row_ptr);\n\n \/\/ TODO: Read signature, parameters etc\n\n read_method_body(method_def.get());\n\n method_defs_[get_index_from_rid(rid)] = std::move(method_def);\n return method_defs_[get_index_from_rid(rid)].get();\n }\n\n const MemberRef* AssemblyReader::read_member_ref(u32 rid)\n {\n if (already_read(member_refs_, rid))\n return member_refs_[get_index_from_rid(rid)].get();\n\n resize_if_needed(member_refs_, pe::MetadataTable::MemberRef);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::MemberRef, rid);\n auto member_ref = std::make_unique();\n\n \/\/ Class (an index into the MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec tables; more precisely, a MemberRefParent(II.24.2.6) coded index)\n auto token = read_metadata_token(&table_row_ptr, pe::CodedIndexType::MemberRefParent);\n\n \/\/ Name (an index into the String heap) \n member_ref->name = read_string(&table_row_ptr);\n\n \/\/ Signature (an index into the Blob heap) \n auto signature = read_blob(&table_row_ptr);\n\n \/\/ TODO: Implement all token type cases\n if (token.type() == pe::MetadataTokenType::TypeRef)\n {\n member_ref->type_ref = read_type_ref(token.rid());\n }\n else\n {\n throw \"read_member_ref -> unsupported token type\";\n }\n\n member_refs_[get_index_from_rid(rid)] = std::move(member_ref);\n return member_refs_[get_index_from_rid(rid)].get();\n }\n\n const TypeRef* AssemblyReader::read_type_ref(u32 rid)\n {\n if (already_read(type_refs_, rid))\n return type_refs_[get_index_from_rid(rid)].get();\n\n resize_if_needed(type_refs_, pe::MetadataTable::TypeRef);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::TypeRef, rid);\n\n auto type_ref = std::make_unique();\n\n \/\/ ResolutionScope (an index into a Module, ModuleRef, AssemblyRef or TypeRef table, or null; more precisely, a ResolutionScope(II.24.2.6) coded index)\n auto res_scope = read_metadata_token(&table_row_ptr, pe::CodedIndexType::ResolutionScope);\n\n if (res_scope.type() == pe::MetadataTokenType::AssemblyRef)\n {\n type_ref->resolution_scope = read_assembly_ref(res_scope.rid());\n }\n else\n {\n throw \"read_type_ref -> unsupported ResolutionScope type\";\n }\n\n \/\/ TypeName(an index into the String heap)\n type_ref->name = read_string(&table_row_ptr);\n\n \/\/ TypeNamespace(an index into the String heap)\n type_ref->name_space = read_string(&table_row_ptr);\n\n type_refs_[get_index_from_rid(rid)] = std::make_unique();\n return type_refs_[get_index_from_rid(rid)].get();\n }\n\n const AssemblyRef* AssemblyReader::read_assembly_ref(u32 rid)\n {\n if (already_read(assembly_refs_, rid))\n {\n return assembly_refs_[get_index_from_rid(rid)].get();\n }\n\n resize_if_needed(assembly_refs_, pe::MetadataTable::AssemblyRef);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::AssemblyRef, rid);\n\n auto asm_ref = std::make_unique();\n\n \/\/ MajorVersion, MinorVersion, BuildNumber, RevisionNumber (each being 2-byte constants)\n asm_ref->major_version = ptrutil::read16(&table_row_ptr);\n asm_ref->minor_version = ptrutil::read16(&table_row_ptr);\n asm_ref->build_number = ptrutil::read16(&table_row_ptr);\n asm_ref->revision_number = ptrutil::read16(&table_row_ptr);\n\n auto flags = ptrutil::read32(&table_row_ptr);\n\n auto key_or_token_blob = read_blob(&table_row_ptr);\n \n \/\/PublicKeyOrToken (an index into the Blob heap, indicating the public key or token that identifies the author of this Assembly)\n if ((static_cast(asm_ref->flags) & static_cast(AssemblyFlags::PublicKey)) != 0)\n {\n asm_ref->public_key = std::move(key_or_token_blob);\n }\n else\n {\n asm_ref->token = std::move(key_or_token_blob);\n }\n\n \/\/ Name (an index into the String heap)\n asm_ref->name = read_string(&table_row_ptr);\n\n \/\/ Culture (an index into the String heap) \n asm_ref->culture = read_string(&table_row_ptr);\n\n \/\/ HashValue (an index into the Blob heap)\n asm_ref->hash_value = read_blob(&table_row_ptr);\n\n assembly_refs_[get_index_from_rid(rid)] = std::move(asm_ref);\n return assembly_refs_[get_index_from_rid(rid)].get();\n }\n\n void AssemblyReader::read_method_body(MethodDef* method)\n {\n method->body = std::make_unique();\n auto method_body_ptr = get_method_body_ptr(method->rva);\n\n \/\/ The two least significant bits of the first byte of the method header indicate what type of header is present.\n auto header_flag = *method_body_ptr;\n method_body_ptr++;\n\n auto tiny_header = (header_flag & 0x3) == CorILMethod_TinyFormat;\n if (tiny_header)\n {\n \/\/ Tiny headers use a 6-bit length encoding\n method->body->code_size = header_flag >> 2;\n \/\/ The operand stack shall be no bigger than 8 entries\n method->body->max_stack_size = 8;\n\n read_method_body_instructions(method, method_body_ptr);\n }\n else\n {\n \/\/ TODO: Implement fat header reading\n }\n }\n\n void AssemblyReader::read_method_body_instructions(MethodDef* method, u8* method_body_ptr)\n {\n auto opcode = read_opcode(&method_body_ptr);\n auto stop_addr = method_body_ptr + method->body->code_size;\n\n while (method_body_ptr != stop_addr)\n {\n switch (opcode.code)\n {\n case Code::LDSTR: {\n auto str_token = read_metadata_token(&method_body_ptr);\n auto str = read_us_string(str_token.rid());\n\n method->body->instructions.push_back(std::make_unique(opcode, str));\n break;\n }\n case Code::CALL: {\n auto token = read_metadata_token(&method_body_ptr);\n\n auto rid = token.rid();\n auto type = token.type();\n\n method->body->instructions.push_back(std::make_unique(opcode, read_member_ref(rid)));\n break;\n }\n case Code::RET: {\n method->body->instructions.push_back(std::make_unique(opcode));\n break;\n }\n default:\n logger_->LogError(L\"AssemblyReader::read_method_body_instructions -> Unhandled opcode\");\n break;\n }\n\n opcode = read_opcode(&method_body_ptr);\n }\n }\n\n const Opcode& AssemblyReader::read_opcode(u8** method_body_ptr)\n {\n auto code = ptrutil::read8(method_body_ptr);\n return code == 0xff ? opcodes::get_two_byte_code(ptrutil::read8(method_body_ptr)) : opcodes::get_one_byte_code(code);\n }\n\n const InlineString* AssemblyReader::read_us_string(u32 index)\n {\n auto size = index + 1;\n\n if (us_strings_.size() < size)\n us_strings_.resize(size);\n\n if (us_strings_[index] != nullptr)\n return us_strings_[index].get();\n\n if (index == 0)\n return nullptr;\n\n auto str_ptr = image_->heap_us.data + index;\n\n \/\/ II.24.2.4 #US and #Blob heaps\n auto length = read_us_or_blob_length(&str_ptr) & 0xfffffffe;\n\n us_strings_[index] = std::make_unique(strutil::to_utf16wstr(str_ptr, length));\n return us_strings_[index].get();\n }\n\n std::wstring AssemblyReader::read_string(u8** index_ptr)\n {\n auto index = read_string_index(index_ptr);\n\n std::wstring value;\n\n if (index == 0)\n return value;\n\n auto string_ptr = image_->heap_strings.data + index;\n\n auto utf8_str = std::string(reinterpret_cast(string_ptr));\n return strutil::utf8str_to_utf16wstr(utf8_str);\n }\n\n u32 AssemblyReader::read_string_index(u8** index_ptr)\n {\n auto index_size = image_->string_idx_size;\n\n u32 str_index = 0;\n if (index_size == 2)\n {\n str_index = ptrutil::read16(index_ptr);\n }\n else\n {\n str_index = ptrutil::read32(index_ptr);\n }\n\n return str_index;\n }\n\n u32 AssemblyReader::read_blob_index(u8** index_ptr)\n {\n if (image_->blob_idx_size == 2)\n return ptrutil::read16(index_ptr);\n\n return ptrutil::read32(index_ptr);\n }\n\n std::unique_ptr AssemblyReader::read_blob(u8** index_ptr)\n {\n auto index = read_blob_index(index_ptr);\n auto blob_ptr = image_->heap_blob.data + index;\n auto length = read_us_or_blob_length(&blob_ptr);\n\n auto buffer = new u8[length];\n std::memcpy(buffer, blob_ptr, length);\n\n return std::make_unique(buffer, length);\n }\n\n pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr)\n {\n auto value = ptrutil::read32(ptr);\n return pe::MetadataToken(value);\n }\n\n pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr, pe::CodedIndexType index_type)\n {\n auto coded_index_info = pe::get_coded_index_info(index_type, image_->tables);\n u32 token;\n if (coded_index_info.size == 2)\n token = ptrutil::read16(ptr);\n else\n token = ptrutil::read32(ptr);\n\n return pe::get_metadata_token_from_coded_index(coded_index_info, token);\n }\n\n u8* AssemblyReader::get_table_row_ptr(pe::MetadataTable table_type, u32 rid)\n {\n auto table = image_->tables[static_cast(table_type)];\n if (table.rows == 0)\n return nullptr;\n\n return const_cast(table.base + (table.row_size * (rid - 1)));\n }\n\n u8* AssemblyReader::get_method_body_ptr(u32 rva)\n {\n return const_cast(image_->raw_data) + resolve_rva(rva);\n }\n\n u32 AssemblyReader::read_us_or_blob_length(const u8** blob_ptr)\n {\n u32 length;\n auto ptr = *blob_ptr;\n\n \/\/ II.24.2.4 #US and #Blob heaps\n if ((ptr[0] & 0x80) == 0)\n {\n *blob_ptr += 1;\n length = ptr[0];\n }\n else if ((ptr[0] & 0x40) == 0)\n {\n *blob_ptr += 2;\n length = (u32)(ptr[0] & ~0x80) << 8;\n length |= ptr[1];\n }\n else\n {\n *blob_ptr += 4;\n length = (u32)(ptr[0] & ~0xc0) << 24;\n length |= (u32)ptr[1] << 16;\n length |= (u32)ptr[2] << 8;\n length |= (u32)ptr[3];\n }\n\n return length;\n }\n\n u32 AssemblyReader::resolve_rva(u32 rva)\n {\n auto section = resolve_rva_section(rva);\n return rva + section->raw_data_ptr - section->virtual_address;\n }\n\n const pe::SectionTable* AssemblyReader::resolve_rva_section(u32 rva)\n {\n for (auto& s : image_->cli_section_tables)\n {\n if (rva >= s->virtual_address && rva < s->virtual_address + s->raw_data_size)\n return s.get();\n }\n\n return nullptr;\n }\n\n u32 AssemblyReader::get_num_entries(pe::MetadataTable table)\n {\n auto table_info = image_->tables[static_cast(table)];\n return table_info.rows;\n }\n\n u32 AssemblyReader::get_index_from_rid(u32 rid)\n {\n return rid - 1;\n }\n }\n}\nmove the read type ref#include \"assembly_reader.h\"\n\n#include \n\n#include \"..\/common\/ptr_util.h\"\n#include \"opcodes.h\"\n#include \"..\/pe\/coded_index.h\"\n#include \"..\/pe\/pe_image_reader.h\"\n#include \"assembly.h\"\n\nnamespace stereo {\n namespace assemblies {\n\n AssemblyReader::AssemblyReader(const char* file_path)\n :\n logger_(std::make_unique()),\n image_(pe::PEImageReader::load_image(file_path))\n {\n }\n\n const pe::PEImage * AssemblyReader::get_image()\n {\n return image_.get();\n }\n\n u32 AssemblyReader::get_entry_point()\n {\n auto ept = pe::MetadataToken(image_->cli_header.entry_point_token);\n return ept.rid();\n }\n\n const ModuleDef* AssemblyReader::read_module_def()\n {\n if (module_ != nullptr)\n return module_.get();\n\n auto module = std::make_unique();\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Module, 1);\n\n \/\/ Skip the generation column since it's always zero\n table_row_ptr += 2;\n\n module->name = read_string(&table_row_ptr);\n\n \/\/ TODO: Read the mvid guid\n\n module_ = std::move(module);\n return module_.get();\n }\n\n const MethodDef* AssemblyReader::read_method_def(u32 rid)\n {\n if (already_read(method_defs_, rid))\n return method_defs_[get_index_from_rid(rid)].get();\n\n resize_if_needed(method_defs_, pe::MetadataTable::Method);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::Method, rid);\n auto method_def = std::make_unique();\n\n \/\/ RVA (a 4-byte constant) \n method_def->rva = ptrutil::read32(&table_row_ptr);\n\n \/\/ ImplFlags (a 2-byte bitmask of type MethodImplAttributes, II.23.1.10) \n method_def->impl_attributes = static_cast(ptrutil::read16(&table_row_ptr));\n\n \/\/ Flags (a 2-byte bitmask of type MethodAttributes, II.23.1.10) \n method_def->attributes = static_cast(ptrutil::read16(&table_row_ptr));\n\n \/\/ Name (an index into the String heap) \n method_def->name = read_string(&table_row_ptr);\n\n \/\/ TODO: Read signature, parameters etc\n\n read_method_body(method_def.get());\n\n method_defs_[get_index_from_rid(rid)] = std::move(method_def);\n return method_defs_[get_index_from_rid(rid)].get();\n }\n\n const MemberRef* AssemblyReader::read_member_ref(u32 rid)\n {\n if (already_read(member_refs_, rid))\n return member_refs_[get_index_from_rid(rid)].get();\n\n resize_if_needed(member_refs_, pe::MetadataTable::MemberRef);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::MemberRef, rid);\n auto member_ref = std::make_unique();\n\n \/\/ Class (an index into the MethodDef, ModuleRef, TypeDef, TypeRef, or TypeSpec tables; more precisely, a MemberRefParent(II.24.2.6) coded index)\n auto token = read_metadata_token(&table_row_ptr, pe::CodedIndexType::MemberRefParent);\n\n \/\/ Name (an index into the String heap) \n member_ref->name = read_string(&table_row_ptr);\n\n \/\/ Signature (an index into the Blob heap) \n auto signature = read_blob(&table_row_ptr);\n\n \/\/ TODO: Implement all token type cases\n if (token.type() == pe::MetadataTokenType::TypeRef)\n {\n member_ref->type_ref = read_type_ref(token.rid());\n }\n else\n {\n throw \"read_member_ref -> unsupported token type\";\n }\n\n member_refs_[get_index_from_rid(rid)] = std::move(member_ref);\n return member_refs_[get_index_from_rid(rid)].get();\n }\n\n const TypeRef* AssemblyReader::read_type_ref(u32 rid)\n {\n if (already_read(type_refs_, rid))\n return type_refs_[get_index_from_rid(rid)].get();\n\n resize_if_needed(type_refs_, pe::MetadataTable::TypeRef);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::TypeRef, rid);\n\n auto type_ref = std::make_unique();\n\n \/\/ ResolutionScope (an index into a Module, ModuleRef, AssemblyRef or TypeRef table, or null; more precisely, a ResolutionScope(II.24.2.6) coded index)\n auto res_scope = read_metadata_token(&table_row_ptr, pe::CodedIndexType::ResolutionScope);\n\n if (res_scope.type() == pe::MetadataTokenType::AssemblyRef)\n {\n type_ref->resolution_scope = read_assembly_ref(res_scope.rid());\n }\n else\n {\n throw \"read_type_ref -> unsupported ResolutionScope type\";\n }\n\n \/\/ TypeName(an index into the String heap)\n type_ref->name = read_string(&table_row_ptr);\n\n \/\/ TypeNamespace(an index into the String heap)\n type_ref->name_space = read_string(&table_row_ptr);\n\n type_refs_[get_index_from_rid(rid)] = std::move(type_ref);\n return type_refs_[get_index_from_rid(rid)].get();\n }\n\n const AssemblyRef* AssemblyReader::read_assembly_ref(u32 rid)\n {\n if (already_read(assembly_refs_, rid))\n {\n return assembly_refs_[get_index_from_rid(rid)].get();\n }\n\n resize_if_needed(assembly_refs_, pe::MetadataTable::AssemblyRef);\n\n auto table_row_ptr = get_table_row_ptr(pe::MetadataTable::AssemblyRef, rid);\n\n auto asm_ref = std::make_unique();\n\n \/\/ MajorVersion, MinorVersion, BuildNumber, RevisionNumber (each being 2-byte constants)\n asm_ref->major_version = ptrutil::read16(&table_row_ptr);\n asm_ref->minor_version = ptrutil::read16(&table_row_ptr);\n asm_ref->build_number = ptrutil::read16(&table_row_ptr);\n asm_ref->revision_number = ptrutil::read16(&table_row_ptr);\n\n auto flags = ptrutil::read32(&table_row_ptr);\n\n auto key_or_token_blob = read_blob(&table_row_ptr);\n \n \/\/PublicKeyOrToken (an index into the Blob heap, indicating the public key or token that identifies the author of this Assembly)\n if ((static_cast(asm_ref->flags) & static_cast(AssemblyFlags::PublicKey)) != 0)\n {\n asm_ref->public_key = std::move(key_or_token_blob);\n }\n else\n {\n asm_ref->token = std::move(key_or_token_blob);\n }\n\n \/\/ Name (an index into the String heap)\n asm_ref->name = read_string(&table_row_ptr);\n\n \/\/ Culture (an index into the String heap) \n asm_ref->culture = read_string(&table_row_ptr);\n\n \/\/ HashValue (an index into the Blob heap)\n asm_ref->hash_value = read_blob(&table_row_ptr);\n\n assembly_refs_[get_index_from_rid(rid)] = std::move(asm_ref);\n return assembly_refs_[get_index_from_rid(rid)].get();\n }\n\n void AssemblyReader::read_method_body(MethodDef* method)\n {\n method->body = std::make_unique();\n auto method_body_ptr = get_method_body_ptr(method->rva);\n\n \/\/ The two least significant bits of the first byte of the method header indicate what type of header is present.\n auto header_flag = *method_body_ptr;\n method_body_ptr++;\n\n auto tiny_header = (header_flag & 0x3) == CorILMethod_TinyFormat;\n if (tiny_header)\n {\n \/\/ Tiny headers use a 6-bit length encoding\n method->body->code_size = header_flag >> 2;\n \/\/ The operand stack shall be no bigger than 8 entries\n method->body->max_stack_size = 8;\n\n read_method_body_instructions(method, method_body_ptr);\n }\n else\n {\n \/\/ TODO: Implement fat header reading\n }\n }\n\n void AssemblyReader::read_method_body_instructions(MethodDef* method, u8* method_body_ptr)\n {\n auto opcode = read_opcode(&method_body_ptr);\n auto stop_addr = method_body_ptr + method->body->code_size;\n\n while (method_body_ptr != stop_addr)\n {\n switch (opcode.code)\n {\n case Code::LDSTR: {\n auto str_token = read_metadata_token(&method_body_ptr);\n auto str = read_us_string(str_token.rid());\n\n method->body->instructions.push_back(std::make_unique(opcode, str));\n break;\n }\n case Code::CALL: {\n auto token = read_metadata_token(&method_body_ptr);\n\n auto rid = token.rid();\n auto type = token.type();\n\n method->body->instructions.push_back(std::make_unique(opcode, read_member_ref(rid)));\n break;\n }\n case Code::RET: {\n method->body->instructions.push_back(std::make_unique(opcode));\n break;\n }\n default:\n logger_->LogError(L\"AssemblyReader::read_method_body_instructions -> Unhandled opcode\");\n break;\n }\n\n opcode = read_opcode(&method_body_ptr);\n }\n }\n\n const Opcode& AssemblyReader::read_opcode(u8** method_body_ptr)\n {\n auto code = ptrutil::read8(method_body_ptr);\n return code == 0xff ? opcodes::get_two_byte_code(ptrutil::read8(method_body_ptr)) : opcodes::get_one_byte_code(code);\n }\n\n const InlineString* AssemblyReader::read_us_string(u32 index)\n {\n auto size = index + 1;\n\n if (us_strings_.size() < size)\n us_strings_.resize(size);\n\n if (us_strings_[index] != nullptr)\n return us_strings_[index].get();\n\n if (index == 0)\n return nullptr;\n\n auto str_ptr = image_->heap_us.data + index;\n\n \/\/ II.24.2.4 #US and #Blob heaps\n auto length = read_us_or_blob_length(&str_ptr) & 0xfffffffe;\n\n us_strings_[index] = std::make_unique(strutil::to_utf16wstr(str_ptr, length));\n return us_strings_[index].get();\n }\n\n std::wstring AssemblyReader::read_string(u8** index_ptr)\n {\n auto index = read_string_index(index_ptr);\n\n std::wstring value;\n\n if (index == 0)\n return value;\n\n auto string_ptr = image_->heap_strings.data + index;\n\n auto utf8_str = std::string(reinterpret_cast(string_ptr));\n return strutil::utf8str_to_utf16wstr(utf8_str);\n }\n\n u32 AssemblyReader::read_string_index(u8** index_ptr)\n {\n auto index_size = image_->string_idx_size;\n\n u32 str_index = 0;\n if (index_size == 2)\n {\n str_index = ptrutil::read16(index_ptr);\n }\n else\n {\n str_index = ptrutil::read32(index_ptr);\n }\n\n return str_index;\n }\n\n u32 AssemblyReader::read_blob_index(u8** index_ptr)\n {\n if (image_->blob_idx_size == 2)\n return ptrutil::read16(index_ptr);\n\n return ptrutil::read32(index_ptr);\n }\n\n std::unique_ptr AssemblyReader::read_blob(u8** index_ptr)\n {\n auto index = read_blob_index(index_ptr);\n auto blob_ptr = image_->heap_blob.data + index;\n auto length = read_us_or_blob_length(&blob_ptr);\n\n auto buffer = new u8[length];\n std::memcpy(buffer, blob_ptr, length);\n\n return std::make_unique(buffer, length);\n }\n\n pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr)\n {\n auto value = ptrutil::read32(ptr);\n return pe::MetadataToken(value);\n }\n\n pe::MetadataToken AssemblyReader::read_metadata_token(u8** ptr, pe::CodedIndexType index_type)\n {\n auto coded_index_info = pe::get_coded_index_info(index_type, image_->tables);\n u32 token;\n if (coded_index_info.size == 2)\n token = ptrutil::read16(ptr);\n else\n token = ptrutil::read32(ptr);\n\n return pe::get_metadata_token_from_coded_index(coded_index_info, token);\n }\n\n u8* AssemblyReader::get_table_row_ptr(pe::MetadataTable table_type, u32 rid)\n {\n auto table = image_->tables[static_cast(table_type)];\n if (table.rows == 0)\n return nullptr;\n\n return const_cast(table.base + (table.row_size * (rid - 1)));\n }\n\n u8* AssemblyReader::get_method_body_ptr(u32 rva)\n {\n return const_cast(image_->raw_data) + resolve_rva(rva);\n }\n\n u32 AssemblyReader::read_us_or_blob_length(const u8** blob_ptr)\n {\n u32 length;\n auto ptr = *blob_ptr;\n\n \/\/ II.24.2.4 #US and #Blob heaps\n if ((ptr[0] & 0x80) == 0)\n {\n *blob_ptr += 1;\n length = ptr[0];\n }\n else if ((ptr[0] & 0x40) == 0)\n {\n *blob_ptr += 2;\n length = (u32)(ptr[0] & ~0x80) << 8;\n length |= ptr[1];\n }\n else\n {\n *blob_ptr += 4;\n length = (u32)(ptr[0] & ~0xc0) << 24;\n length |= (u32)ptr[1] << 16;\n length |= (u32)ptr[2] << 8;\n length |= (u32)ptr[3];\n }\n\n return length;\n }\n\n u32 AssemblyReader::resolve_rva(u32 rva)\n {\n auto section = resolve_rva_section(rva);\n return rva + section->raw_data_ptr - section->virtual_address;\n }\n\n const pe::SectionTable* AssemblyReader::resolve_rva_section(u32 rva)\n {\n for (auto& s : image_->cli_section_tables)\n {\n if (rva >= s->virtual_address && rva < s->virtual_address + s->raw_data_size)\n return s.get();\n }\n\n return nullptr;\n }\n\n u32 AssemblyReader::get_num_entries(pe::MetadataTable table)\n {\n auto table_info = image_->tables[static_cast(table)];\n return table_info.rows;\n }\n\n u32 AssemblyReader::get_index_from_rid(u32 rid)\n {\n return rid - 1;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\n#include \".\/nbt.h\"\n#include \".\/settings.h\"\n#include \".\/colors.h\"\n\nint main(int ac, const char* av[]) {\n if (ac != 2) {\n std::cerr << \"Usage: .\/nbtparse [filename | world number]\" << std::endl;\n exit(1);\n }\n int world = atoi(av[1]);\n nbt bf;\n if (world == 0) {\n bf = nbt(av[1]);\n } else {\n bf = nbt(world);\n }\n std::cout << bf.string();\n Settings set;\n set.topview = true;\n set.heightmap = false;\n set.color = false;\n QImage img((bf.xPos_max() - bf.xPos_min() + 1) * 16,\n (bf.zPos_max() - bf.zPos_min() + 1) * 16,\n QImage::Format_ARGB32_Premultiplied);\n img.fill(0);\n int min = 300, max = -10;\n for (int i = bf.zPos_min(); i <= bf.zPos_max(); ++i) {\n for (int j = bf.xPos_min(); j <= bf.xPos_max(); ++j) {\n const nbt::tag_ptr tag = bf.tag_at(j, i);\n if (tag) {\n nbt::tag_ptr comp(tag->sub(\"Level\"));\n int32_t xPos = comp->sub(\"xPos\")->pay_();\n int32_t zPos = comp->sub(\"zPos\")->pay_();\n const std::string& heightMap = comp->sub(\"HeightMap\")->\n pay_().p;\n const std::string& blocks = comp->sub(\"Blocks\")->\n pay_().p;\n const std::string& skylight = comp->sub(\"SkyLight\")->\n pay_().p;\n uint64_t xtmp = (xPos - bf.xPos_min()) * 16;\n uint64_t ztmp = (zPos - bf.zPos_min()) * 16;\n int32_t max_int = std::numeric_limits::max();\n if (xtmp + 15 > static_cast(max_int)\n || ztmp + 15 > static_cast(max_int)) {\n std::cerr << \"Map is too large for an image!\" << std::endl;\n exit(1);\n }\n int32_t xPos_img = static_cast(xtmp);\n int32_t zPos_img = static_cast(ztmp);\n int index = 0;\n for (int32_t ii = zPos_img; ii < zPos_img + 16; ++ii) {\n for (int32_t jj = xPos_img; jj < xPos_img + 16; ++jj) {\n int32_t ii0 = ii - zPos_img;\n int32_t jj0 = jj - xPos_img;\n uint8_t height = heightMap[index++];\n QColor color;\n if (set.heightmap) {\n if (set.color) {\n color.setHsvF(atan(((1.0 - height \/ 127.0) - 0.5) * 10) \/ M_PI + 0.5, 1.0, 1.0, 1.0);\n } else {\n color.setRgba(QColor(height, height, height, 255).rgba());\n }\n } else {\n int height_low_bound = height;\n while (colors[blocks[height_low_bound-- + ii0 * 128\n + jj0 * 128 * 16]].alpha() != 255);\n for (int h = height_low_bound; h <= height; ++h) {\n uint8_t blknr = blocks[h + ii0 * 128 + jj0 * 128 * 16];\n color = blend(colors[blknr], color);\n }\n img.setPixel(static_cast(jj), static_cast(ii),\n color.lighter((height - 64) \/ 2 + 64).rgba());\n }\n \/\/ uint8_t light = skylight[(height + ii0 * 128 + jj0 * 128 * 16) \/ 2];\n \/\/ if (height % 2 == 1) {\n \/\/ light >>= 4;\n \/\/ } else {\n \/\/ light &= 0x0F;\n \/\/ }\n \/\/ light <<= 4;\n\n }\n }\n \/\/ std::cout << j << \" \" << xPos << \" \"\n \/\/ << i << \" \" << zPos << std::endl;\n }\n }\n }\n img.save(\"test.png\");\n return 0;\n}\nremove those#include \n#include \n#include \n#include \n#include \n\n#include \".\/nbt.h\"\n#include \".\/settings.h\"\n#include \".\/colors.h\"\n\nint main(int ac, const char* av[]) {\n if (ac != 2) {\n std::cerr << \"Usage: .\/nbtparse [filename | world number]\" << std::endl;\n exit(1);\n }\n int world = atoi(av[1]);\n nbt bf;\n if (world == 0) {\n bf = nbt(av[1]);\n } else {\n bf = nbt(world);\n }\n std::cout << bf.string();\n Settings set;\n set.topview = true;\n set.heightmap = false;\n set.color = false;\n QImage img((bf.xPos_max() - bf.xPos_min() + 1) * 16,\n (bf.zPos_max() - bf.zPos_min() + 1) * 16,\n QImage::Format_ARGB32_Premultiplied);\n img.fill(0);\n for (int i = bf.zPos_min(); i <= bf.zPos_max(); ++i) {\n for (int j = bf.xPos_min(); j <= bf.xPos_max(); ++j) {\n const nbt::tag_ptr tag = bf.tag_at(j, i);\n if (tag) {\n nbt::tag_ptr comp(tag->sub(\"Level\"));\n int32_t xPos = comp->sub(\"xPos\")->pay_();\n int32_t zPos = comp->sub(\"zPos\")->pay_();\n const std::string& heightMap = comp->sub(\"HeightMap\")->\n pay_().p;\n const std::string& blocks = comp->sub(\"Blocks\")->\n pay_().p;\n const std::string& skylight = comp->sub(\"SkyLight\")->\n pay_().p;\n uint64_t xtmp = (xPos - bf.xPos_min()) * 16;\n uint64_t ztmp = (zPos - bf.zPos_min()) * 16;\n int32_t max_int = std::numeric_limits::max();\n if (xtmp + 15 > static_cast(max_int)\n || ztmp + 15 > static_cast(max_int)) {\n std::cerr << \"Map is too large for an image!\" << std::endl;\n exit(1);\n }\n int32_t xPos_img = static_cast(xtmp);\n int32_t zPos_img = static_cast(ztmp);\n int index = 0;\n for (int32_t ii = zPos_img; ii < zPos_img + 16; ++ii) {\n for (int32_t jj = xPos_img; jj < xPos_img + 16; ++jj) {\n int32_t ii0 = ii - zPos_img;\n int32_t jj0 = jj - xPos_img;\n uint8_t height = heightMap[index++];\n QColor color;\n if (set.heightmap) {\n if (set.color) {\n color.setHsvF(atan(((1.0 - height \/ 127.0) - 0.5) * 10) \/ M_PI + 0.5, 1.0, 1.0, 1.0);\n } else {\n color.setRgba(QColor(height, height, height, 255).rgba());\n }\n } else {\n int height_low_bound = height;\n while (colors[blocks[height_low_bound-- + ii0 * 128\n + jj0 * 128 * 16]].alpha() != 255);\n for (int h = height_low_bound; h <= height; ++h) {\n uint8_t blknr = blocks[h + ii0 * 128 + jj0 * 128 * 16];\n color = blend(colors[blknr], color);\n }\n img.setPixel(static_cast(jj), static_cast(ii),\n color.lighter((height - 64) \/ 2 + 64).rgba());\n }\n \/\/ uint8_t light = skylight[(height + ii0 * 128 + jj0 * 128 * 16) \/ 2];\n \/\/ if (height % 2 == 1) {\n \/\/ light >>= 4;\n \/\/ } else {\n \/\/ light &= 0x0F;\n \/\/ }\n \/\/ light <<= 4;\n\n }\n }\n \/\/ std::cout << j << \" \" << xPos << \" \"\n \/\/ << i << \" \" << zPos << std::endl;\n }\n }\n }\n img.save(\"test.png\");\n return 0;\n}\n<|endoftext|>"} {"text":"\/*-------------------------------------------------------------------------\n *\n * stack_trace.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/src\/backend\/bridge\/stack_trace.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"backend\/common\/stack_trace.h\"\n#include \"backend\/common\/logger.h\"\n\nnamespace peloton {\n\n\/\/ Based on :: http:\/\/panthema.net\/2008\/0901-stacktrace-demangled\/\nvoid GetStackTrace(){\n std::stringstream stack_trace;\n std::stringstream internal_info;\n unsigned int max_frames = 63;\n\n \/\/\/ storage array for stack trace address data\n void* addrlist[max_frames+1];\n\n \/\/\/ retrieve current stack addresses\n int addrlen = backtrace(addrlist, sizeof(addrlist) \/ sizeof(void*));\n\n if (addrlen == 0) {\n stack_trace << \"\\n\";\n return;\n }\n\n \/\/\/ resolve addresses into strings containing \"filename(function+address)\",\n \/\/\/ this array must be free()-ed\n char** symbol_list = backtrace_symbols(addrlist, addrlen);\n\n \/\/\/ allocate string which will be filled with the demangled function name\n size_t func_name_size = 1024;\n char* func_name = (char*) malloc(func_name_size);\n\n \/\/\/ iterate over the returned symbol lines. skip the first, it is the\n \/\/\/ address of this function.\n for (int i = 1; i < addrlen; i++){\n char *begin_name = 0, *begin_offset = 0, *end_offset = 0;\n\n \/\/\/ find parentheses and +address offset surrounding the mangled name:\n \/\/\/ .\/module(function+0x15c) [0x8048a6d]\n for (char *p = symbol_list[i]; *p; ++p){\n if (*p == '(')\n begin_name = p;\n else if (*p == '+')\n begin_offset = p;\n else if (*p == ')' && begin_offset) {\n end_offset = p;\n break;\n }\n }\n\n if (begin_name && begin_offset && end_offset && begin_name < begin_offset){\n *begin_name++ = '\\0';\n *begin_offset++ = '\\0';\n *end_offset = '\\0';\n\n \/\/\/ mangled name is now in [begin_name, begin_offset) and caller\n \/\/\/ offset in [begin_offset, end_offset). now apply __cxa_demangle():\n int status;\n char* ret = abi::__cxa_demangle(begin_name, func_name, &func_name_size, &status);\n if (status == 0) {\n func_name = ret; \/\/ use possibly realloc()-ed string\n stack_trace << symbol_list[i] << \": \" << func_name << \" + \" << begin_offset << \"\\n\";\n }\n else {\n \/\/\/ demangling failed. Output function name as a C function with\n \/\/\/ no arguments.\n stack_trace << symbol_list[i] << \": \" << begin_name << \" + \" << begin_offset << \"\\n\";\n }\n }\n else\n {\n \/\/\/ couldn't parse the line ? print the whole line.\n stack_trace << symbol_list[i] << \"\\n\";\n }\n }\n\n internal_info << \"process : \" << getpid() << \" thread : \" << std::this_thread::get_id();\n\n LOG_INFO(\"segmentation fault\");\n LOG_INFO(\"info : %s\", internal_info.str().c_str());\n LOG_INFO(\"stack trace :\\n%s\", stack_trace.str().c_str());\n\n free(func_name);\n free(symbol_list);\n}\n\n\n} \/\/ namespace peloton\nClean up stack trace.\/*-------------------------------------------------------------------------\n *\n * stack_trace.cpp\n * file description\n *\n * Copyright(c) 2015, CMU\n *\n * \/peloton\/src\/backend\/bridge\/stack_trace.cpp\n *\n *-------------------------------------------------------------------------\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"backend\/common\/stack_trace.h\"\n#include \"backend\/common\/logger.h\"\n\nnamespace peloton {\n\n\/\/ Based on :: http:\/\/panthema.net\/2008\/0901-stacktrace-demangled\/\nvoid GetStackTrace(){\n std::stringstream stack_trace;\n std::stringstream internal_info;\n unsigned int max_frames = 63;\n\n \/\/\/ storage array for stack trace address data\n void* addrlist[max_frames+1];\n\n \/\/\/ retrieve current stack addresses\n int addrlen = backtrace(addrlist, sizeof(addrlist) \/ sizeof(void*));\n\n if (addrlen == 0) {\n stack_trace << \"\\n\";\n return;\n }\n\n \/\/\/ resolve addresses into strings containing \"filename(function+address)\",\n \/\/\/ this array must be free()-ed\n char** symbol_list = backtrace_symbols(addrlist, addrlen);\n\n \/\/\/ allocate string which will be filled with the demangled function name\n size_t func_name_size = 4096;\n char* func_name = (char*) malloc(func_name_size);\n\n \/\/\/ iterate over the returned symbol lines. skip the first, it is the\n \/\/\/ address of this function.\n for (int i = 1; i < addrlen; i++){\n char *begin_name = 0, *begin_offset = 0, *end_offset = 0;\n\n \/\/\/ find parentheses and +address offset surrounding the mangled name:\n \/\/\/ .\/module(function+0x15c) [0x8048a6d]\n for (char *p = symbol_list[i]; *p; ++p){\n if (*p == '(')\n begin_name = p;\n else if (*p == '+')\n begin_offset = p;\n else if (*p == ')' && begin_offset) {\n end_offset = p;\n break;\n }\n }\n\n if (begin_name && begin_offset && end_offset && begin_name < begin_offset){\n *begin_name++ = '\\0';\n *begin_offset++ = '\\0';\n *end_offset = '\\0';\n\n \/\/\/ mangled name is now in [begin_name, begin_offset) and caller\n \/\/\/ offset in [begin_offset, end_offset). now apply __cxa_demangle():\n int status;\n char* ret = abi::__cxa_demangle(begin_name, func_name, &func_name_size, &status);\n if (status == 0) {\n func_name = ret; \/\/ use possibly realloc()-ed string\n stack_trace << std::left << std::setw(15) << addrlist[i] << \" :: \"\n << symbol_list[i] << \" [ \"\n << func_name << \" \"\n << begin_offset << \" ]\\n\";\n }\n else {\n \/\/\/ demangling failed. Output function name as a C function with\n \/\/\/ no arguments.\n stack_trace << std::left << std::setw(15) << addrlist[i] << \" :: \"\n << symbol_list[i] << \" [ \"\n << begin_name << \" \"\n << begin_offset << \" ]\\n\";\n }\n }\n else {\n \/\/\/ couldn't parse the line ? print the whole line.\n stack_trace << std::left << std::setw(15) << addrlist[i] << \" :: \"\n << std::setw(30) << symbol_list[i] << \"\\n\";\n }\n }\n\n internal_info << \"process : \" << getpid() << \" thread : \" << std::this_thread::get_id();\n\n LOG_INFO(\"segmentation fault\");\n LOG_INFO(\"%s\", internal_info.str().c_str());\n LOG_INFO(\"stack trace :\\n\");\n LOG_INFO(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\");\n LOG_INFO(\"%s\", stack_trace.str().c_str());\n LOG_INFO(\"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\\n\");\n\n free(func_name);\n free(symbol_list);\n}\n\n\n} \/\/ namespace peloton\n<|endoftext|>"} {"text":"\/*******************************************************\n * Copyright (c) 2015, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#pragma once\n#include \n\nnamespace cpu\n{\nnamespace kernel\n{\n\ntemplate\nclass LabelNode\n{\nprivate:\n T label;\n T minLabel;\n unsigned rank;\n LabelNode* parent;\n\npublic:\n LabelNode() : label(0), minLabel(0), rank(0), parent(this) { }\n LabelNode(T label) : label(label), minLabel(label), rank(0), parent(this) { }\n\n T getLabel()\n {\n return label;\n }\n\n T getMinLabel()\n {\n return minLabel;\n }\n\n LabelNode* getParent()\n {\n return parent;\n }\n\n unsigned getRank()\n {\n return rank;\n }\n\n void setMinLabel(T l)\n {\n minLabel = l;\n }\n\n void setParent(LabelNode* p)\n {\n parent = p;\n }\n\n void setRank(unsigned r)\n {\n rank = r;\n }\n};\n\ntemplate\nstatic LabelNode* find(LabelNode* x)\n{\n if (x->getParent() != x)\n x->setParent(find(x->getParent()));\n return x->getParent();\n}\n\ntemplate\nstatic void setUnion(LabelNode* x, LabelNode* y)\n{\n LabelNode* xRoot = find(x);\n LabelNode* yRoot = find(y);\n if (xRoot == yRoot)\n return;\n\n T xMinLabel = xRoot->getMinLabel();\n T yMinLabel = yRoot->getMinLabel();\n xRoot->setMinLabel(min(xMinLabel, yMinLabel));\n yRoot->setMinLabel(min(xMinLabel, yMinLabel));\n\n if (xRoot->getRank() < yRoot->getRank())\n xRoot->setParent(yRoot);\n else if (xRoot->getRank() > yRoot->getRank())\n yRoot->setParent(xRoot);\n else {\n yRoot->setParent(xRoot);\n xRoot->setRank(xRoot->getRank() + 1);\n }\n}\n\ntemplate\nvoid regions(Array out, const Array in, af_connectivity connectivity)\n{\n const af::dim4 in_dims = in.dims();\n const char *in_ptr = in.get();\n T *out_ptr = out.get();\n\n \/\/ Map labels\n typedef typename std::map* > label_map_t;\n typedef typename label_map_t::iterator label_map_iterator_t;\n\n label_map_t lmap;\n\n \/\/ Initial label\n T label = (T)1;\n\n for (int j = 0; j < (int)in_dims[1]; j++) {\n for (int i = 0; i < (int)in_dims[0]; i++) {\n int idx = j * in_dims[0] + i;\n if (in_ptr[idx] != 0) {\n std::vector l;\n\n \/\/ Test neighbors\n if (i > 0 && out_ptr[j * (int)in_dims[0] + i-1] > 0)\n l.push_back(out_ptr[j * in_dims[0] + i-1]);\n if (j > 0 && out_ptr[(j-1) * (int)in_dims[0] + i] > 0)\n l.push_back(out_ptr[(j-1) * in_dims[0] + i]);\n if (connectivity == AF_CONNECTIVITY_8 && i > 0 &&\n j > 0 && out_ptr[(j-1) * in_dims[0] + i-1] > 0)\n l.push_back(out_ptr[(j-1) * in_dims[0] + i-1]);\n if (connectivity == AF_CONNECTIVITY_8 &&\n i < (int)in_dims[0] - 1 && j > 0 && out_ptr[(j-1) * in_dims[0] + i+1] != 0)\n l.push_back(out_ptr[(j-1) * in_dims[0] + i+1]);\n\n if (!l.empty()) {\n T minl = l[0];\n for (size_t k = 0; k < l.size(); k++) {\n minl = min(l[k], minl);\n label_map_iterator_t cur_map = lmap.find(l[k]);\n LabelNode *node = cur_map->second;\n \/\/ Group labels of the same region under a disjoint set\n for (size_t m = k+1; m < l.size(); m++)\n setUnion(node, lmap.find(l[m])->second);\n }\n \/\/ Set label to smallest neighbor label\n out_ptr[idx] = minl;\n }\n else {\n \/\/ Insert new label in map\n LabelNode *node = new LabelNode(label);\n lmap.insert(std::pair* >(label, node));\n out_ptr[idx] = label++;\n }\n }\n }\n }\n\n std::set removed;\n\n for (int j = 0; j < (int)in_dims[1]; j++) {\n for (int i = 0; i < (int)in_dims[0]; i++) {\n int idx = j * (int)in_dims[0] + i;\n if (in_ptr[idx] != 0) {\n T l = out_ptr[idx];\n label_map_iterator_t cur_map = lmap.find(l);\n\n if (cur_map != lmap.end()) {\n LabelNode* node = cur_map->second;\n\n LabelNode* node_root = find(node);\n out_ptr[idx] = node_root->getMinLabel();\n\n \/\/ Mark removed labels (those that are part of a region\n \/\/ that contains a smaller label)\n if (node->getMinLabel() < l || node_root->getMinLabel() < l)\n removed.insert(l);\n if (node->getLabel() > node->getMinLabel())\n removed.insert(node->getLabel());\n }\n }\n }\n }\n\n \/\/ Calculate final neighbors (ensure final labels are sequential)\n for (int j = 0; j < (int)in_dims[1]; j++) {\n for (int i = 0; i < (int)in_dims[0]; i++) {\n int idx = j * (int)in_dims[0] + i;\n if (out_ptr[idx] > 0) {\n out_ptr[idx] -= distance(removed.begin(), removed.lower_bound(out_ptr[idx]));\n }\n }\n }\n}\n\n}\n}\nfix memory leak in regions cpu backend\/*******************************************************\n * Copyright (c) 2015, ArrayFire\n * All rights reserved.\n *\n * This file is distributed under 3-clause BSD license.\n * The complete license agreement can be obtained at:\n * http:\/\/arrayfire.com\/licenses\/BSD-3-Clause\n ********************************************************\/\n\n#pragma once\n#include \n#include \n\nnamespace cpu\n{\nnamespace kernel\n{\n\ntemplate\nclass LabelNode\n{\nprivate:\n T label;\n T minLabel;\n unsigned rank;\n LabelNode* parent;\n\npublic:\n LabelNode() : label(0), minLabel(0), rank(0), parent(this) { }\n LabelNode(T label) : label(label), minLabel(label), rank(0), parent(this) { }\n\n T getLabel()\n {\n return label;\n }\n\n T getMinLabel()\n {\n return minLabel;\n }\n\n LabelNode* getParent()\n {\n return parent;\n }\n\n unsigned getRank()\n {\n return rank;\n }\n\n void setMinLabel(T l)\n {\n minLabel = l;\n }\n\n void setParent(LabelNode* p)\n {\n parent = p;\n }\n\n void setRank(unsigned r)\n {\n rank = r;\n }\n};\n\ntemplate\nstatic LabelNode* find(LabelNode* x)\n{\n if (x->getParent() != x)\n x->setParent(find(x->getParent()));\n return x->getParent();\n}\n\ntemplate\nstatic void setUnion(LabelNode* x, LabelNode* y)\n{\n LabelNode* xRoot = find(x);\n LabelNode* yRoot = find(y);\n if (xRoot == yRoot)\n return;\n\n T xMinLabel = xRoot->getMinLabel();\n T yMinLabel = yRoot->getMinLabel();\n xRoot->setMinLabel(min(xMinLabel, yMinLabel));\n yRoot->setMinLabel(min(xMinLabel, yMinLabel));\n\n if (xRoot->getRank() < yRoot->getRank())\n xRoot->setParent(yRoot);\n else if (xRoot->getRank() > yRoot->getRank())\n yRoot->setParent(xRoot);\n else {\n yRoot->setParent(xRoot);\n xRoot->setRank(xRoot->getRank() + 1);\n }\n}\n\ntemplate\nvoid regions(Array out, const Array in, af_connectivity connectivity)\n{\n const af::dim4 inDims = in.dims();\n const char *inPtr = in.get();\n T *outPtr = out.get();\n\n \/\/ Map labels\n typedef typename std::unique_ptr< LabelNode > UnqLabelPtr;\n typedef typename std::map LabelMap;\n typedef typename LabelMap::iterator LabelMapIterator;\n\n LabelMap lmap;\n\n \/\/ Initial label\n T label = (T)1;\n\n for (int j = 0; j < (int)inDims[1]; j++) {\n for (int i = 0; i < (int)inDims[0]; i++) {\n int idx = j * inDims[0] + i;\n if (inPtr[idx] != 0) {\n std::vector l;\n\n \/\/ Test neighbors\n if (i > 0 && outPtr[j * (int)inDims[0] + i-1] > 0)\n l.push_back(outPtr[j * inDims[0] + i-1]);\n if (j > 0 && outPtr[(j-1) * (int)inDims[0] + i] > 0)\n l.push_back(outPtr[(j-1) * inDims[0] + i]);\n if (connectivity == AF_CONNECTIVITY_8 && i > 0 &&\n j > 0 && outPtr[(j-1) * inDims[0] + i-1] > 0)\n l.push_back(outPtr[(j-1) * inDims[0] + i-1]);\n if (connectivity == AF_CONNECTIVITY_8 &&\n i < (int)inDims[0] - 1 && j > 0 && outPtr[(j-1) * inDims[0] + i+1] != 0)\n l.push_back(outPtr[(j-1) * inDims[0] + i+1]);\n\n if (!l.empty()) {\n T minl = l[0];\n for (size_t k = 0; k < l.size(); k++) {\n minl = min(l[k], minl);\n LabelMapIterator currentMap = lmap.find(l[k]);\n LabelNode *node = currentMap->second.get();\n \/\/ Group labels of the same region under a disjoint set\n for (size_t m = k+1; m < l.size(); m++)\n setUnion(node, lmap.find(l[m])->second.get());\n }\n \/\/ Set label to smallest neighbor label\n outPtr[idx] = minl;\n } else {\n \/\/ Insert new label in map\n lmap.insert(std::make_pair(label, UnqLabelPtr(new LabelNode(label))));\n outPtr[idx] = label++;\n }\n }\n }\n }\n\n std::set removed;\n\n for (int j = 0; j < (int)inDims[1]; j++) {\n for (int i = 0; i < (int)inDims[0]; i++) {\n int idx = j * (int)inDims[0] + i;\n if (inPtr[idx] != 0) {\n T l = outPtr[idx];\n LabelMapIterator currentMap = lmap.find(l);\n\n if (currentMap != lmap.end()) {\n LabelNode* node = currentMap->second.get();\n\n LabelNode* nodeRoot = find(node);\n outPtr[idx] = nodeRoot->getMinLabel();\n\n \/\/ Mark removed labels (those that are part of a region\n \/\/ that contains a smaller label)\n if (node->getMinLabel() < l || nodeRoot->getMinLabel() < l)\n removed.insert(l);\n if (node->getLabel() > node->getMinLabel())\n removed.insert(node->getLabel());\n }\n }\n }\n }\n\n \/\/ Calculate final neighbors (ensure final labels are sequential)\n for (int j = 0; j < (int)inDims[1]; j++) {\n for (int i = 0; i < (int)inDims[0]; i++) {\n int idx = j * (int)inDims[0] + i;\n if (outPtr[idx] > 0) {\n outPtr[idx] -= distance(removed.begin(), removed.lower_bound(outPtr[idx]));\n }\n }\n }\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _WIN32\n# include \/\/_wopen\n# include \/\/Sleep\n#else\n# include \n# include \n#endif\n\n#include \n#include \n#include \n#include \"src\/filesystem.hpp\"\n\nnamespace qi {\n namespace os {\n\n FILE* fopen(const char *filename, const char *mode) {\n return ::fopen(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),\n boost::filesystem::path(mode, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());\n\n }\n\n int stat(const char *filename, struct ::stat* status) {\n return ::stat(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), status);\n }\n\n std::string getenv(const char *var) {\n char *res = ::getenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());\n if (res == NULL)\n return \"\";\n return std::string(res);\n }\n\n int setenv(const char *var, const char *value) {\n return ::setenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),\n boost::filesystem::path(value, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), 1);\n }\n\n void sleep(unsigned int seconds) {\n \/\/ In case sleep was interrupted by a signal,\n \/\/ keep sleeping until we have slept the correct amount\n \/\/ of time.\n while (seconds != 0) {\n seconds = ::sleep(seconds);\n }\n }\n\n void msleep(unsigned int milliseconds) {\n \/\/ Not the same for usleep: it returns a non-zero\n \/\/ error code if it was interupted...\n usleep(milliseconds * 1000);\n }\n\n\n std::string home()\n {\n std::string envHome = qi::os::getenv(\"HOME\");\n if (envHome != \"\")\n {\n return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());\n }\n\n \/\/ $HOME environment variable not defined:\n char *lgn;\n struct passwd *pw;\n if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL)\n {\n return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());\n }\n\n \/\/ Give up:\n return \"\";\n }\n\n std::string tmpdir(const char *prefix) {\n char buffer[L_tmpnam];\n memset(buffer, 0, L_tmpnam);\n tmpnam(buffer);\n\n boost::filesystem::path path;\n if (buffer == NULL)\n {\n #ifdef __APPLE__\n path = boost::filesystem::path(::qi::os::home(),\n qi::unicodeFacet()).append(\"Cache\", qi::unicodeFacet());\n #else\n path = boost::filesystem::path(::qi::os::home(),\n qi::unicodeFacet()).append(\".cache\", qi::unicodeFacet());\n #endif\n }\n else\n {\n path = buffer;\n }\n\n std::string filename(prefix);\n filename += path.filename().string(qi::unicodeFacet());\n path = path.parent_path().append(filename, qi::unicodeFacet());\n\n try\n {\n if (!boost::filesystem::exists(path))\n boost::filesystem::create_directories(path);\n }\n catch (const boost::filesystem::filesystem_error &e)\n {\n throw qi::os::QiException(e.what());\n }\n\n return path.string(qi::unicodeFacet());\n }\n\n std::string tmp()\n {\n std::string temp = ::qi::os::getenv(\"TMPDIR\");\n if (temp.empty())\n temp = \"\/tmp\/\";\n\n boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());\n\n return p.string(qi::unicodeFacet());\n }\n\n int gettimeofday(qi::os::timeval *tp) {\n struct ::timeval tv;\n int ret = ::gettimeofday(&tv, 0);\n tp->tv_sec = tv.tv_sec;\n tp->tv_usec = tv.tv_usec;\n return ret;\n }\n };\n};\nFix wrong behavior of tmpdir (linux) when tmpnam fail.\/*\n * Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n * Use of this source code is governed by a BSD-style license that can be\n * found in the COPYING file.\n *\/\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef _WIN32\n# include \/\/_wopen\n# include \/\/Sleep\n#else\n# include \n# include \n#endif\n\n#include \n#include \n#include \n#include \"src\/filesystem.hpp\"\n\nnamespace qi {\n namespace os {\n\n FILE* fopen(const char *filename, const char *mode) {\n return ::fopen(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),\n boost::filesystem::path(mode, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());\n\n }\n\n int stat(const char *filename, struct ::stat* status) {\n return ::stat(boost::filesystem::path(filename, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), status);\n }\n\n std::string getenv(const char *var) {\n char *res = ::getenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str());\n if (res == NULL)\n return \"\";\n return std::string(res);\n }\n\n int setenv(const char *var, const char *value) {\n return ::setenv(boost::filesystem::path(var, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(),\n boost::filesystem::path(value, qi::unicodeFacet()).string(qi::unicodeFacet()).c_str(), 1);\n }\n\n void sleep(unsigned int seconds) {\n \/\/ In case sleep was interrupted by a signal,\n \/\/ keep sleeping until we have slept the correct amount\n \/\/ of time.\n while (seconds != 0) {\n seconds = ::sleep(seconds);\n }\n }\n\n void msleep(unsigned int milliseconds) {\n \/\/ Not the same for usleep: it returns a non-zero\n \/\/ error code if it was interupted...\n usleep(milliseconds * 1000);\n }\n\n\n std::string home()\n {\n std::string envHome = qi::os::getenv(\"HOME\");\n if (envHome != \"\")\n {\n return boost::filesystem::path(envHome, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());\n }\n\n \/\/ $HOME environment variable not defined:\n char *lgn;\n struct passwd *pw;\n if ((lgn = getlogin()) == NULL || (pw = getpwnam(lgn)) == NULL)\n {\n return boost::filesystem::path(pw->pw_dir, qi::unicodeFacet()).make_preferred().string(qi::unicodeFacet());\n }\n\n \/\/ Give up:\n return \"\";\n }\n\n std::string tmpdir(const char *prefix) {\n char buffer[L_tmpnam];\n memset(buffer, 0, L_tmpnam);\n tmpnam(buffer);\n\n boost::filesystem::path path;\n if (buffer == NULL)\n {\n #ifdef __APPLE__\n path = boost::filesystem::path(::qi::os::home(),\n qi::unicodeFacet()).append(\"Cache\", qi::unicodeFacet());\n #else\n path = boost::filesystem::path(::qi::os::home(),\n qi::unicodeFacet()).append(\".cache\", qi::unicodeFacet());\n #endif\n path.append(prefix, qi::unicodeFacet());\n\n \/\/ FIXME Add random value for unique dir name.\n }\n else\n {\n path = buffer;\n std::string filename = prefix;\n filename += path.filename().string(qi::unicodeFacet());\n path = path.parent_path().append(filename, qi::unicodeFacet());\n }\n\n try\n {\n if (!boost::filesystem::exists(path))\n boost::filesystem::create_directories(path);\n }\n catch (const boost::filesystem::filesystem_error &e)\n {\n throw qi::os::QiException(e.what());\n }\n\n return path.string(qi::unicodeFacet());\n }\n\n std::string tmp()\n {\n std::string temp = ::qi::os::getenv(\"TMPDIR\");\n if (temp.empty())\n temp = \"\/tmp\/\";\n\n boost::filesystem::path p = boost::filesystem::path(temp, qi::unicodeFacet());\n\n return p.string(qi::unicodeFacet());\n }\n\n int gettimeofday(qi::os::timeval *tp) {\n struct ::timeval tv;\n int ret = ::gettimeofday(&tv, 0);\n tp->tv_sec = tv.tv_sec;\n tp->tv_usec = tv.tv_usec;\n return ret;\n }\n };\n};\n<|endoftext|>"} {"text":"\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetScopeTask.cpp\n * @brief Module for oscilloscope data\n * Reads oscilloscope ASCII files and produces JPetRecoSignal objects.\n *\/\n\n#include \"JPetScopeTask.h\"\n#include \"..\/JPetParamManager\/JPetParamManager.h\"\n\n#include \n#include \n#include \"JPetScopeTaskUtils.h\"\n\n#include \nusing namespace boost::filesystem;\n\n\nJPetScopeTask::JPetScopeTask(const char * name, const char * description):\n JPetTask(name, description),\n fWriter(0)\n{\n}\n\nint JPetScopeTask::getTimeWindowIndex(const std::string& pathAndFileName) const\n{\n int time_window_index = -1;\n sscanf(path(pathAndFileName).filename().string().c_str(), \"%*3s %d\", &time_window_index);\n return time_window_index;\n}\n\nvoid JPetScopeTask::exec() \n{\n assert(fParamManager);\n DEBUG(\"JPetScopeTask - getParamBank() called\"); \n const std::vector pms = fParamManager->getParamBank().getPMs(); \n assert(pms.size() == 4);\n for(size_t i = 0u; i < pms.size(); ++i ) {\n JPetPM* pm = pms[i];\n assert(pm);\n if (fInputFiles.find(i) != fInputFiles.end()) {\n const auto& files = fInputFiles.find(i)->second; \n for (const auto& file: files) {\n JPetRecoSignal sig = RecoSignalUtils::generateSignal(file.c_str());\n sig.setTimeWindowIndex(getTimeWindowIndex(file));\n sig.setPM(*pm);\n assert(fWriter);\n fWriter->write(sig);\n }\n } else {\n ERROR(\"Could not find the Input Files for given set\");\n }\n }\n}\nAdd more protective conditions to JPetScopeTask\/**\n * @copyright Copyright 2016 The J-PET Framework Authors. All rights reserved.\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may find a copy of the License in the LICENCE file.\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @file JPetScopeTask.cpp\n * @brief Module for oscilloscope data\n * Reads oscilloscope ASCII files and produces JPetRecoSignal objects.\n *\/\n\n#include \"JPetScopeTask.h\"\n#include \"..\/JPetParamManager\/JPetParamManager.h\"\n\n#include \n#include \n#include \"JPetScopeTaskUtils.h\"\n#include \"..\/JPetCommonTools\/JPetCommonTools.h\"\n\n#include \nusing namespace boost::filesystem;\n\n\nJPetScopeTask::JPetScopeTask(const char * name, const char * description):\n JPetTask(name, description),\n fWriter(0)\n{\n}\n\nint JPetScopeTask::getTimeWindowIndex(const std::string& pathAndFileName) const\n{\n DEBUG(\"JPetScopeTask\");\n int time_window_index = -1;\n if (!boost::filesystem::exists(pathAndFileName)) {\n ERROR(\"File does not exist \"); \n }\n int res = sscanf(JPetCommonTools::extractFileNameFromFullPath(pathAndFileName).c_str(), \"%*3s %d\", &time_window_index);\n if (res <= 0) {\n ERROR(\"scanf failed\");\n return -1;\n } else {\n return time_window_index;\n }\n}\n\nvoid JPetScopeTask::exec() \n{\n DEBUG(\"JPetScopeTask getParamBank() called\"); \n assert(fParamManager);\n auto& bank = fParamManager->getParamBank(); \n if (bank.isDummy()) {\n ERROR(\"bank is Dummy\");\n } else {\n const std::vector pms = bank.getPMs(); \n assert(pms.size() == 4);\n for(size_t i = 0u; i < pms.size(); ++i ) {\n JPetPM* pm = pms[i];\n assert(pm);\n if (fInputFiles.find(i) != fInputFiles.end()) {\n const auto& files = fInputFiles.find(i)->second; \n for (const auto& file: files) {\n DEBUG(std::string(\"file to open:\")+file);\n JPetRecoSignal sig = RecoSignalUtils::generateSignal(file.c_str());\n sig.setTimeWindowIndex(getTimeWindowIndex(file));\n DEBUG(\"before setPM\");\n sig.setPM(*pm);\n DEBUG(\"after setPM\");\n assert(fWriter);\n fWriter->write(sig);\n }\n } else {\n ERROR(\"Could not find the Input Files for given set\");\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\n#pragma once\n\n#include \n#include \n#include \n\n#include \"Werk\/Commands\/Command.hpp\"\n#include \"Werk\/Commands\/EchoCommand.hpp\"\n#include \"Werk\/Logging\/Logger.hpp\"\n\nnamespace werk\n{\n\nclass CommandManager\n{\npublic:\n\n\tCommandManager(Logger *log) : _log(log) {\n\t\t\/\/Default commands\n\t\t_commands[\"echo\"] = new EchoCommand(log);\n\t\t_commands[\"error\"] = new EchoCommand(log, LogLevel::ERROR);\n\t\t_commands[\"null\"] = new NullCommand();\n\t\t_commands[\"warning\"] = new EchoCommand(log, LogLevel::WARNING);\n\t}\n\n\tstd::map &commands() { return _commands; }\n\tconst std::map &commands() const { return _commands; }\n\n\tbool execute(const std::string &commandLine);\n\tbool execute(const std::vector &arguments);\n\nprivate:\n\tLogger *_log;\n\n\tstd::map _commands;\n};\n\n}\nMake default commands optional\n#pragma once\n\n#include \n#include \n#include \n\n#include \"Werk\/Commands\/Command.hpp\"\n#include \"Werk\/Commands\/EchoCommand.hpp\"\n#include \"Werk\/Logging\/Logger.hpp\"\n\nnamespace werk\n{\n\nclass CommandManager\n{\npublic:\n\n\tCommandManager(Logger *log, bool defaultCommands=true) : _log(log) {\n\t\t\/\/Default commands\n\t\tif (defaultCommands) {\n\t\t\t_commands[\"echo\"] = new EchoCommand(log);\n\t\t\t_commands[\"error\"] = new EchoCommand(log, LogLevel::ERROR);\n\t\t\t_commands[\"null\"] = new NullCommand();\n\t\t\t_commands[\"warning\"] = new EchoCommand(log, LogLevel::WARNING);\n\t\t}\n\t}\n\n\tstd::map &commands() { return _commands; }\n\tconst std::map &commands() const { return _commands; }\n\n\tbool execute(const std::string &commandLine);\n\tbool execute(const std::vector &arguments);\n\nprivate:\n\tLogger *_log;\n\n\tstd::map _commands;\n};\n\n}\n<|endoftext|>"} {"text":"#include \"dsa_common.h\"\n\n#include \"broker_config.h\"\n\n#include \n#include \n#include \"module\/logger.h\"\n\nnamespace fs = boost::filesystem;\n\nnamespace dsa {\nBrokerConfig::BrokerConfig(int argc, const char* argv[]) {\n init();\n load();\n}\n\nconst string_& BrokerConfig::get_file_path() {\n static string_ default_path = \"broker.json\";\n\n if (_file_path.empty()) {\n return default_path;\n }\n return _file_path;\n}\n\n\/\/ init all the config properties\nvoid BrokerConfig::init() {\n add_item(\"thread\", Var(2), VarValidatorInt(1, 100));\n add_item(\"host\", Var(\"0.0.0.0\"), [](const Var& var) {\n return var.is_string() && !var.get_string().empty();\n });\n add_item(\"port\", Var(4120), VarValidatorInt(1, 65535));\n add_item(\"secure-port\", Var(4128), VarValidatorInt(1, 65535));\n add_item(\"http-port\", Var(80), VarValidatorInt(1, 65535));\n add_item(\"https-port\", Var(443), VarValidatorInt(1, 65535));\n add_item(\"log-level\", Var(\"warn\"), [](const Var& var) {\n string_ str = var.to_string();\n return str == \"trace\" || str == \"debug\" || str == \"info\" || str == \"warn\" ||\n str == \"error\" || str == \"fatal\";\n });\n}\n\/\/ load config json from file\nvoid BrokerConfig::load() {\n auto& path = get_file_path();\n if (fs::exists(path)) {\n if (fs::is_regular_file(path)) {\n std::ifstream config_file(get_file_path(), std::ios::in);\n if (config_file.is_open()) {\n std::stringstream buffer;\n buffer << config_file.rdbuf();\n Var data = Var::from_json(buffer.str());\n if (data.is_map()) {\n try {\n \/\/ allows config to be stored in different location\n if (_file_path.empty() && data.get_map().count(\"config-path\") > 0 &&\n !data[\"config-path\"].to_string().empty()) {\n \/\/ load broker config from different path\n _file_path = data[\"config-path\"].get_string();\n load();\n return;\n }\n } catch (std::exception& e) {\n \/\/ config-path doesn't exist, use default\n }\n for (auto& it : data.get_map()) {\n auto search = _items.find(it.first);\n if (search != _items.end()) {\n search->second.set_value(std::move(it.second));\n }\n }\n return;\n }\n }\n }\n\n LOG_FATAL(LOG << \"failed to open broker config file: \" << path);\n } else {\n \/\/ config doesn't exist, write a default config file\n save();\n }\n}\nvoid BrokerConfig::save() {\n auto& path = get_file_path();\n std::ofstream config_file(path, std::ios::out | std::ios::trunc);\n if (config_file.is_open()) {\n config_file << \"{\\n\"\n << R\"(\"dsa-version\": \")\" << int(DSA_MAJOR_VERSION) << \".\"\n << int(DSA_MINOR_VERSION) << \"\\\",\\n\";\n#ifdef DSA_DEBUG\n config_file << R\"(\"broker-build\": \"debug\")\";\n#else\n config_file << R\"(\"broker-build\": \"release\")\";\n#endif\n for (auto& name : _names) {\n config_file << \",\\n\\\"\" << name << \"\\\": \";\n config_file << _items[name].get_value().to_json(2);\n }\n config_file << \"\\n}\";\n } else {\n LOG_ERROR(Logger::_(), LOG << \"failed to write the broker config file\");\n }\n}\nvoid BrokerConfig::add_item(const string_& name, Var&& value,\n VarValidator&& validator) {\n _names.emplace_back(name);\n _items.emplace(name,\n BrokerConfigItem(std::move(value), std::move(validator)));\n}\n}\ndefault http port shouldn't be 80 to avoid port in use error in test#include \"dsa_common.h\"\n\n#include \"broker_config.h\"\n\n#include \n#include \n#include \"module\/logger.h\"\n\nnamespace fs = boost::filesystem;\n\nnamespace dsa {\nBrokerConfig::BrokerConfig(int argc, const char* argv[]) {\n init();\n load();\n}\n\nconst string_& BrokerConfig::get_file_path() {\n static string_ default_path = \"broker.json\";\n\n if (_file_path.empty()) {\n return default_path;\n }\n return _file_path;\n}\n\n\/\/ init all the config properties\nvoid BrokerConfig::init() {\n add_item(\"thread\", Var(2), VarValidatorInt(1, 100));\n add_item(\"host\", Var(\"0.0.0.0\"), [](const Var& var) {\n return var.is_string() && !var.get_string().empty();\n });\n add_item(\"port\", Var(4120), VarValidatorInt(1, 65535));\n add_item(\"secure-port\", Var(4128), VarValidatorInt(1, 65535));\n add_item(\"http-port\", Var(8080), VarValidatorInt(1, 65535));\n add_item(\"https-port\", Var(8443), VarValidatorInt(1, 65535));\n add_item(\"log-level\", Var(\"warn\"), [](const Var& var) {\n string_ str = var.to_string();\n return str == \"trace\" || str == \"debug\" || str == \"info\" || str == \"warn\" ||\n str == \"error\" || str == \"fatal\";\n });\n}\n\/\/ load config json from file\nvoid BrokerConfig::load() {\n auto& path = get_file_path();\n if (fs::exists(path)) {\n if (fs::is_regular_file(path)) {\n std::ifstream config_file(get_file_path(), std::ios::in);\n if (config_file.is_open()) {\n std::stringstream buffer;\n buffer << config_file.rdbuf();\n Var data = Var::from_json(buffer.str());\n if (data.is_map()) {\n try {\n \/\/ allows config to be stored in different location\n if (_file_path.empty() && data.get_map().count(\"config-path\") > 0 &&\n !data[\"config-path\"].to_string().empty()) {\n \/\/ load broker config from different path\n _file_path = data[\"config-path\"].get_string();\n load();\n return;\n }\n } catch (std::exception& e) {\n \/\/ config-path doesn't exist, use default\n }\n for (auto& it : data.get_map()) {\n auto search = _items.find(it.first);\n if (search != _items.end()) {\n search->second.set_value(std::move(it.second));\n }\n }\n return;\n }\n }\n }\n\n LOG_FATAL(LOG << \"failed to open broker config file: \" << path);\n } else {\n \/\/ config doesn't exist, write a default config file\n save();\n }\n}\nvoid BrokerConfig::save() {\n auto& path = get_file_path();\n std::ofstream config_file(path, std::ios::out | std::ios::trunc);\n if (config_file.is_open()) {\n config_file << \"{\\n\"\n << R\"(\"dsa-version\": \")\" << int(DSA_MAJOR_VERSION) << \".\"\n << int(DSA_MINOR_VERSION) << \"\\\",\\n\";\n#ifdef DSA_DEBUG\n config_file << R\"(\"broker-build\": \"debug\")\";\n#else\n config_file << R\"(\"broker-build\": \"release\")\";\n#endif\n for (auto& name : _names) {\n config_file << \",\\n\\\"\" << name << \"\\\": \";\n config_file << _items[name].get_value().to_json(2);\n }\n config_file << \"\\n}\";\n } else {\n LOG_ERROR(Logger::_(), LOG << \"failed to write the broker config file\");\n }\n}\nvoid BrokerConfig::add_item(const string_& name, Var&& value,\n VarValidator&& validator) {\n _names.emplace_back(name);\n _items.emplace(name,\n BrokerConfigItem(std::move(value), std::move(validator)));\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2021 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ CLASS HEADER\n#include \n\n\/\/ EXTERNAL INCLUDES\n#include \n\nnamespace\n{\n#if defined(DEBUG_ENABLED)\nDebug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, \"LOG_TEXT_RENDERING\");\n#endif\n\n} \/\/ namespace\n\nnamespace Dali\n{\nnamespace Toolkit\n{\nnamespace Text\n{\nstatic void\nEncodeBlobCoordinate(unsigned int cornerX, unsigned int cornerY, unsigned int atlasX, unsigned int atlasY, unsigned int nominalWidth, unsigned int nominalHeight, BlobCoordinate* v)\n{\n DALI_ASSERT_DEBUG(0 == (atlasX & ~0x7F));\n DALI_ASSERT_DEBUG(0 == (atlasY & ~0x7F));\n DALI_ASSERT_DEBUG(0 == (cornerX & ~1));\n DALI_ASSERT_DEBUG(0 == (cornerY & ~1));\n DALI_ASSERT_DEBUG(0 == (nominalWidth & ~0x3F));\n DALI_ASSERT_DEBUG(0 == (nominalHeight & ~0x3F));\n\n unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX;\n unsigned int y = (((atlasY << 6) | nominalHeight) << 1) | cornerY;\n\n unsigned int encoded = (x << 16) | y;\n\n v->u = encoded >> 16;\n v->v = encoded & 0xFFFF;\n}\n\nVectorBlobAtlas::VectorBlobAtlas(unsigned int textureWidth,\n unsigned int textureHeight,\n unsigned int itemWidth,\n unsigned int itemHeightQuantum)\n: mTextureWidth(textureWidth),\n mTextureHeight(textureHeight),\n mItemWidth(itemWidth),\n mItemHeightQuantum(itemHeightQuantum),\n mCursorX(0),\n mCursorY(0),\n mIsFull(false)\n{\n DALI_LOG_INFO(gLogFilter, Debug::General, \"Blob atlas %p size %dx%d, item width %d, height quantum %d\\n\", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum);\n\n mAtlasTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight);\n\n mTextureSet = TextureSet::New();\n mTextureSet.SetTexture(0, mAtlasTexture);\n}\n\nbool VectorBlobAtlas::IsFull() const\n{\n return mIsFull;\n}\n\nbool VectorBlobAtlas::FindGlyph(FontId fontId,\n GlyphIndex glyphIndex,\n BlobCoordinate* coords)\n{\n const unsigned int size(mItemLookup.size());\n\n for(unsigned int i = 0; i < size; ++i)\n {\n if(mItemLookup[i].fontId == fontId &&\n mItemLookup[i].glyphIndex == glyphIndex)\n {\n const Item& item = mItemCache[mItemLookup[i].cacheIndex];\n\n coords[0] = item.coords[0];\n coords[1] = item.coords[1];\n coords[2] = item.coords[2];\n coords[3] = item.coords[3];\n\n return true;\n }\n }\n\n return false;\n}\n\nbool VectorBlobAtlas::AddGlyph(unsigned int fontId,\n unsigned int glyphIndex,\n VectorBlob* blob,\n unsigned int length,\n unsigned int nominalWidth,\n unsigned int nominalHeight,\n BlobCoordinate* coords)\n{\n if(mIsFull)\n {\n return false;\n }\n\n unsigned int w, h, x, y;\n\n w = mItemWidth;\n h = (length + w - 1) \/ w;\n\n if(mCursorY + h > mTextureHeight)\n {\n \/\/ Go to next column\n mCursorX += mItemWidth;\n mCursorY = 0;\n }\n\n if(mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight)\n {\n x = mCursorX;\n y = mCursorY;\n mCursorY += (h + mItemHeightQuantum - 1) & ~(mItemHeightQuantum - 1);\n }\n else\n {\n DALI_LOG_INFO(gLogFilter, Debug::General, \"Blob atlas %p is now FULL\\n\", this);\n\n \/\/ The atlas is now considered to be full\n mIsFull = true;\n return false;\n }\n\n if(w * h == length)\n {\n TexSubImage(x, y, w, h, blob);\n }\n else\n {\n TexSubImage(x, y, w, h - 1, blob);\n\n \/\/ Upload the last row separately\n TexSubImage(x, y + h - 1, length - (w * (h - 1)), 1, blob + w * (h - 1));\n }\n\n DALI_LOG_INFO(gLogFilter, Debug::General, \"Blob atlas %p capacity %d filled %d %f\\%\\n\", this, mTextureWidth * mTextureHeight, mCursorY * mItemWidth + mCursorX * mTextureHeight, 100.0f * (float)(mCursorY * mItemWidth + mCursorX * mTextureHeight) \/ (float)(mTextureWidth * mTextureHeight));\n\n Key key;\n key.fontId = fontId;\n key.glyphIndex = glyphIndex;\n key.cacheIndex = mItemCache.size();\n mItemLookup.push_back(key);\n\n x \/= mItemWidth;\n y \/= mItemHeightQuantum;\n\n Item item;\n EncodeBlobCoordinate(0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0]); \/\/ BOTTOM_LEFT\n EncodeBlobCoordinate(0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1]); \/\/ TOP_LEFT\n EncodeBlobCoordinate(1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2]); \/\/ BOTTOM_RIGHT\n EncodeBlobCoordinate(1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3]); \/\/ TOP_RIGHT\n mItemCache.push_back(item);\n\n coords[0] = item.coords[0];\n coords[1] = item.coords[1];\n coords[2] = item.coords[2];\n coords[3] = item.coords[3];\n\n return true;\n}\n\nvoid VectorBlobAtlas::TexSubImage(unsigned int offsetX,\n unsigned int offsetY,\n unsigned int width,\n unsigned int height,\n VectorBlob* blob)\n{\n const size_t size = width * height * 4;\n uint8_t* pixbuf = new uint8_t[size];\n\n size_t pos;\n size_t dataIndex = 0;\n for(size_t y = 0; y < height; y++)\n {\n pos = y * mTextureWidth * 4;\n for(size_t x = 0; x < width; x++)\n {\n pixbuf[pos + x * 4] = 0xFF & blob[dataIndex].r;\n pixbuf[pos + x * 4 + 1] = 0xFF & blob[dataIndex].g;\n pixbuf[pos + x * 4 + 2] = 0xFF & blob[dataIndex].b;\n pixbuf[pos + x * 4 + 3] = 0xFF & blob[dataIndex].a;\n dataIndex++;\n }\n }\n\n PixelData pixelData = PixelData::New(pixbuf, size, width, height, Pixel::RGBA8888, PixelData::DELETE_ARRAY);\n mAtlasTexture.Upload(pixelData, 0u, 0u, offsetX, offsetY, width, height);\n}\n\n} \/\/ namespace Text\n\n} \/\/ namespace Toolkit\n\n} \/\/ namespace Dali\nFixed memory scribbler in text vector blob\/*\n * Copyright (c) 2021 Samsung Electronics Co., Ltd.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *\/\n\n\/\/ CLASS HEADER\n#include \n\n\/\/ EXTERNAL INCLUDES\n#include \n\nnamespace\n{\n#if defined(DEBUG_ENABLED)\nDebug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, \"LOG_TEXT_RENDERING\");\n#endif\n\n} \/\/ namespace\n\nnamespace Dali\n{\nnamespace Toolkit\n{\nnamespace Text\n{\nstatic void\nEncodeBlobCoordinate(unsigned int cornerX, unsigned int cornerY, unsigned int atlasX, unsigned int atlasY, unsigned int nominalWidth, unsigned int nominalHeight, BlobCoordinate* v)\n{\n DALI_ASSERT_DEBUG(0 == (atlasX & ~0x7F));\n DALI_ASSERT_DEBUG(0 == (atlasY & ~0x7F));\n DALI_ASSERT_DEBUG(0 == (cornerX & ~1));\n DALI_ASSERT_DEBUG(0 == (cornerY & ~1));\n DALI_ASSERT_DEBUG(0 == (nominalWidth & ~0x3F));\n DALI_ASSERT_DEBUG(0 == (nominalHeight & ~0x3F));\n\n unsigned int x = (((atlasX << 6) | nominalWidth) << 1) | cornerX;\n unsigned int y = (((atlasY << 6) | nominalHeight) << 1) | cornerY;\n\n unsigned int encoded = (x << 16) | y;\n\n v->u = encoded >> 16;\n v->v = encoded & 0xFFFF;\n}\n\nVectorBlobAtlas::VectorBlobAtlas(unsigned int textureWidth,\n unsigned int textureHeight,\n unsigned int itemWidth,\n unsigned int itemHeightQuantum)\n: mTextureWidth(textureWidth),\n mTextureHeight(textureHeight),\n mItemWidth(itemWidth),\n mItemHeightQuantum(itemHeightQuantum),\n mCursorX(0),\n mCursorY(0),\n mIsFull(false)\n{\n DALI_LOG_INFO(gLogFilter, Debug::General, \"Blob atlas %p size %dx%d, item width %d, height quantum %d\\n\", this, textureWidth, textureHeight, itemWidth, itemHeightQuantum);\n\n mAtlasTexture = Texture::New(TextureType::TEXTURE_2D, Pixel::RGBA8888, textureWidth, textureHeight);\n\n mTextureSet = TextureSet::New();\n mTextureSet.SetTexture(0, mAtlasTexture);\n}\n\nbool VectorBlobAtlas::IsFull() const\n{\n return mIsFull;\n}\n\nbool VectorBlobAtlas::FindGlyph(FontId fontId,\n GlyphIndex glyphIndex,\n BlobCoordinate* coords)\n{\n const unsigned int size(mItemLookup.size());\n\n for(unsigned int i = 0; i < size; ++i)\n {\n if(mItemLookup[i].fontId == fontId &&\n mItemLookup[i].glyphIndex == glyphIndex)\n {\n const Item& item = mItemCache[mItemLookup[i].cacheIndex];\n\n coords[0] = item.coords[0];\n coords[1] = item.coords[1];\n coords[2] = item.coords[2];\n coords[3] = item.coords[3];\n\n return true;\n }\n }\n\n return false;\n}\n\nbool VectorBlobAtlas::AddGlyph(unsigned int fontId,\n unsigned int glyphIndex,\n VectorBlob* blob,\n unsigned int length,\n unsigned int nominalWidth,\n unsigned int nominalHeight,\n BlobCoordinate* coords)\n{\n if(mIsFull)\n {\n return false;\n }\n\n unsigned int w, h, x, y;\n\n w = mItemWidth;\n h = (length + w - 1) \/ w;\n\n if(mCursorY + h > mTextureHeight)\n {\n \/\/ Go to next column\n mCursorX += mItemWidth;\n mCursorY = 0;\n }\n\n if(mCursorX + w <= mTextureWidth && mCursorY + h <= mTextureHeight)\n {\n x = mCursorX;\n y = mCursorY;\n mCursorY += (h + mItemHeightQuantum - 1) & ~(mItemHeightQuantum - 1);\n }\n else\n {\n DALI_LOG_INFO(gLogFilter, Debug::General, \"Blob atlas %p is now FULL\\n\", this);\n\n \/\/ The atlas is now considered to be full\n mIsFull = true;\n return false;\n }\n\n if(w * h == length)\n {\n TexSubImage(x, y, w, h, blob);\n }\n else\n {\n TexSubImage(x, y, w, h - 1, blob);\n\n \/\/ Upload the last row separately\n TexSubImage(x, y + h - 1, length - (w * (h - 1)), 1, blob + w * (h - 1));\n }\n\n DALI_LOG_INFO(gLogFilter, Debug::General, \"Blob atlas %p capacity %d filled %d %f\\%\\n\", this, mTextureWidth * mTextureHeight, mCursorY * mItemWidth + mCursorX * mTextureHeight, 100.0f * (float)(mCursorY * mItemWidth + mCursorX * mTextureHeight) \/ (float)(mTextureWidth * mTextureHeight));\n\n Key key;\n key.fontId = fontId;\n key.glyphIndex = glyphIndex;\n key.cacheIndex = mItemCache.size();\n mItemLookup.push_back(key);\n\n x \/= mItemWidth;\n y \/= mItemHeightQuantum;\n\n Item item;\n EncodeBlobCoordinate(0, 0, x, y, nominalWidth, nominalHeight, &item.coords[0]); \/\/ BOTTOM_LEFT\n EncodeBlobCoordinate(0, 1, x, y, nominalWidth, nominalHeight, &item.coords[1]); \/\/ TOP_LEFT\n EncodeBlobCoordinate(1, 0, x, y, nominalWidth, nominalHeight, &item.coords[2]); \/\/ BOTTOM_RIGHT\n EncodeBlobCoordinate(1, 1, x, y, nominalWidth, nominalHeight, &item.coords[3]); \/\/ TOP_RIGHT\n mItemCache.push_back(item);\n\n coords[0] = item.coords[0];\n coords[1] = item.coords[1];\n coords[2] = item.coords[2];\n coords[3] = item.coords[3];\n\n return true;\n}\n\nvoid VectorBlobAtlas::TexSubImage(unsigned int offsetX,\n unsigned int offsetY,\n unsigned int width,\n unsigned int height,\n VectorBlob* blob)\n{\n const size_t size = width * height * 4;\n uint8_t* pixbuf = new uint8_t[size];\n\n size_t pos;\n size_t dataIndex = 0;\n for(size_t y = 0; y < height; y++)\n {\n pos = y * width * 4;\n for(size_t x = 0; x < width; x++)\n {\n pixbuf[pos + x * 4] = 0xFF & blob[dataIndex].r;\n pixbuf[pos + x * 4 + 1] = 0xFF & blob[dataIndex].g;\n pixbuf[pos + x * 4 + 2] = 0xFF & blob[dataIndex].b;\n pixbuf[pos + x * 4 + 3] = 0xFF & blob[dataIndex].a;\n dataIndex++;\n }\n }\n\n PixelData pixelData = PixelData::New(pixbuf, size, width, height, Pixel::RGBA8888, PixelData::DELETE_ARRAY);\n mAtlasTexture.Upload(pixelData, 0u, 0u, offsetX, offsetY, width, height);\n}\n\n} \/\/ namespace Text\n\n} \/\/ namespace Toolkit\n\n} \/\/ namespace Dali\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ This test performs a series false positive checks using a list of URLs\n\/\/ against a known set of SafeBrowsing data.\n\/\/\n\/\/ It uses a normal SafeBrowsing database to create a bloom filter where it\n\/\/ looks up all the URLs in the url file. A URL that has a prefix found in the\n\/\/ bloom filter and found in the database is considered a hit: a valid lookup\n\/\/ that will result in a gethash request. A URL that has a prefix found in the\n\/\/ bloom filter but not in the database is a miss: a false positive lookup that\n\/\/ will result in an unnecessary gethash request.\n\/\/\n\/\/ By varying the size of the bloom filter and using a constant set of\n\/\/ SafeBrowsing data, we can check a known set of URLs against the filter and\n\/\/ determine the false positive rate.\n\/\/\n\/\/ Usage:\n\/\/ $ .\/perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives\n\/\/ --filter-start=\n\/\/ --filter-steps=\n\/\/ --filter-verbose\n\/\/\n\/\/ --filter-start: The filter multiplier to begin with. This represents the\n\/\/ number of bits per prefix of memory to use in the filter.\n\/\/ The default value is identical to the current SafeBrowsing\n\/\/ database value.\n\/\/ --filter-steps: The number of iterations to run, with each iteration\n\/\/ increasing the filter multiplier by 1. The default value\n\/\/ is 1.\n\/\/ --filter-verbose: Used to print out the hit \/ miss results per URL.\n\/\/ --filter-csv: The URL file contains information about the number of\n\/\/ unique views (the popularity) of each URL. See the format\n\/\/ description below.\n\/\/\n\/\/ Data files:\n\/\/ chrome\/test\/data\/safe_browsing\/filter\/database\n\/\/ chrome\/test\/data\/safe_browsing\/filter\/urls\n\/\/\n\/\/ database: A normal SafeBrowsing database.\n\/\/ urls: A text file containing a list of URLs, one per line. If the option\n\/\/ --filter-csv is specified, the format of each line in the file is\n\/\/ , where weight is an integer indicating the number of\n\/\/ unique views for the URL.\n\n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/sha2.h\"\n#include \"base\/string_util.h\"\n#include \"chrome\/browser\/safe_browsing\/bloom_filter.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_util.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/sqlite_compiled_statement.h\"\n#include \"chrome\/common\/sqlite_utils.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nnamespace {\n\n\/\/ Ensures the SafeBrowsing database is closed properly.\nclass ScopedPerfDatabase {\n public:\n explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}\n ~ScopedPerfDatabase() {\n sqlite3_close(db_);\n }\n\n private:\n sqlite3* db_;\n\n DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);\n};\n\n\/\/ Command line flags.\nconst wchar_t kFilterVerbose[] = L\"filter-verbose\";\nconst wchar_t kFilterStart[] = L\"filter-start\";\nconst wchar_t kFilterSteps[] = L\"filter-steps\";\nconst wchar_t kFilterCsv[] = L\"filter-csv\";\n\n\/\/ Returns the path to the data used in this test, relative to the top of the\n\/\/ source directory.\nFilePath GetFullDataPath() {\n FilePath full_path;\n CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));\n full_path = full_path.Append(FILE_PATH_LITERAL(\"safe_browsing\"));\n full_path = full_path.Append(FILE_PATH_LITERAL(\"filter\"));\n CHECK(file_util::PathExists(full_path));\n return full_path;\n}\n\n\/\/ Constructs a bloom filter of the appropriate size from the provided prefixes.\nvoid BuildBloomFilter(int size_multiplier,\n const std::vector& prefixes,\n BloomFilter** bloom_filter) {\n \/\/ Create a BloomFilter with the specified size.\n const int key_count = std::max(static_cast(prefixes.size()), 250000);\n const int filter_size = key_count * size_multiplier;\n *bloom_filter = new BloomFilter(filter_size);\n\n \/\/ Add the prefixes to it.\n for (size_t i = 0; i < prefixes.size(); ++i)\n (*bloom_filter)->Insert(prefixes[i]);\n\n std::cout << \"Bloom filter with prefixes: \" << prefixes.size()\n << \", multiplier: \" << size_multiplier\n << \", size (bytes): \" << (*bloom_filter)->size()\n << std::endl;\n}\n\n\/\/ Reads the set of add prefixes contained in a SafeBrowsing database into a\n\/\/ sorted array suitable for fast searching. This takes significantly less time\n\/\/ to look up a given prefix than performing SQL queries.\nbool ReadDatabase(const FilePath& path, std::vector* prefixes) {\n FilePath database_file = path.Append(FILE_PATH_LITERAL(\"database\"));\n sqlite3* db = NULL;\n if (OpenSqliteDb(database_file, &db) != SQLITE_OK) {\n sqlite3_close(db);\n return false;\n }\n\n ScopedPerfDatabase database(db);\n scoped_ptr sql_cache(new SqliteStatementCache(db));\n\n \/\/ Get the number of items in the add_prefix table.\n std::string sql = \"SELECT COUNT(*) FROM add_prefix\";\n SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());\n if (!count_statement.is_valid())\n return false;\n\n if (count_statement->step() != SQLITE_ROW)\n return false;\n\n const int count = count_statement->column_int(0);\n\n \/\/ Load them into a prefix vector and sort\n prefixes->reserve(count);\n sql = \"SELECT prefix FROM add_prefix\";\n SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());\n if (!prefix_statement.is_valid())\n return false;\n\n while (prefix_statement->step() == SQLITE_ROW)\n prefixes->push_back(prefix_statement->column_int(0));\n\n DCHECK(static_cast(prefixes->size()) == count);\n sort(prefixes->begin(), prefixes->end());\n\n return true;\n}\n\n\/\/ Generates all legal SafeBrowsing prefixes for the specified URL, and returns\n\/\/ the set of Prefixes that exist in the bloom filter. The function returns the\n\/\/ number of host + path combinations checked.\nint GeneratePrefixHits(const std::string url,\n BloomFilter* bloom_filter,\n std::vector* prefixes) {\n GURL url_check(url);\n std::vector hosts;\n if (url_check.HostIsIPAddress()) {\n hosts.push_back(url_check.host());\n } else {\n safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);\n }\n\n std::vector paths;\n safe_browsing_util::GeneratePathsToCheck(url_check, &paths);\n\n for (size_t i = 0; i < hosts.size(); ++i) {\n for (size_t j = 0; j < paths.size(); ++j) {\n SBPrefix prefix;\n base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));\n if (bloom_filter->Exists(prefix))\n prefixes->push_back(prefix);\n }\n }\n\n return hosts.size() * paths.size();\n}\n\n\/\/ Binary search of sorted prefixes.\nbool IsPrefixInDatabase(SBPrefix prefix,\n const std::vector& prefixes) {\n if (prefixes.empty())\n return false;\n\n int low = 0;\n int high = prefixes.size() - 1;\n while (low <= high) {\n int mid = ((unsigned int)low + (unsigned int)high) >> 1;\n SBPrefix prefix_mid = prefixes[mid];\n if (prefix_mid == prefix)\n return true;\n if (prefix_mid < prefix)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return false;\n}\n\n\/\/ Construct a bloom filter with the given prefixes and multiplier, and test the\n\/\/ false positive rate (misses) against a URL list.\nvoid CalculateBloomFilterFalsePositives(\n int size_multiplier,\n const FilePath& data_dir,\n const std::vector& prefix_list) {\n BloomFilter* bloom_filter = NULL;\n BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);\n scoped_refptr scoped_filter(bloom_filter);\n\n \/\/ Read in data file line at a time.\n FilePath url_file = data_dir.Append(FILE_PATH_LITERAL(\"urls\"));\n std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());\n\n \/\/ Keep track of stats\n int hits = 0;\n int misses = 0;\n int weighted_hits = 0;\n int weighted_misses = 0;\n int url_count = 0;\n int prefix_count = 0;\n\n \/\/ Print out volumes of data (per URL hit and miss information).\n bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);\n bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);\n\n std::string url;\n while (std::getline(url_stream, url)) {\n ++url_count;\n\n \/\/ Handle a format that contains URLs weighted by unique views.\n int weight = 1;\n if (use_weights) {\n std::string::size_type pos = url.find_last_of(\",\");\n if (pos != std::string::npos) {\n weight = StringToInt(std::string(url, pos + 1));\n url = url.substr(0, pos);\n }\n }\n\n \/\/ See if the URL is in the bloom filter.\n std::vector prefixes;\n prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);\n\n \/\/ See if the prefix is actually in the database (in-memory prefix list).\n for (size_t i = 0; i < prefixes.size(); ++i) {\n if (IsPrefixInDatabase(prefixes[i], prefix_list)) {\n ++hits;\n weighted_hits += weight;\n if (verbose) {\n std::cout << \"Hit for URL: \" << url\n << \" (prefix = \" << prefixes[i] << \")\"\n << std::endl;\n }\n } else {\n ++misses;\n weighted_misses += weight;\n if (verbose) {\n std::cout << \"Miss for URL: \" << url\n << \" (prefix = \" << prefixes[i] << \")\"\n << std::endl;\n }\n }\n }\n }\n\n \/\/ Print out the results for this test.\n std::cout << \"URLs checked: \" << url_count\n << \", prefix compares: \" << prefix_count\n << \", hits: \" << hits\n << \", misses: \" << misses;\n if (use_weights) {\n std::cout << \", weighted hits: \" << weighted_hits\n << \", weighted misses: \" << weighted_misses;\n }\n std::cout << std::endl;\n}\n\n} \/\/ namespace\n\n\/\/ This test can take several minutes to perform its calculations, so it should\n\/\/ be disabled until you need to run it.\nTEST(SafeBrowsingBloomFilter, FalsePositives) {\n std::vector prefix_list;\n FilePath data_dir = GetFullDataPath();\n if (!ReadDatabase(data_dir, &prefix_list))\n return;\n\n int start = BloomFilter::kBloomFilterSizeRatio;\n if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterStart)) {\n start = StringToInt(\n CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterStart));\n }\n\n int steps = 1;\n if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterSteps)) {\n steps = StringToInt(\n CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterSteps));\n }\n\n int stop = start + steps;\n\n for (int multiplier = start; multiplier < stop; ++multiplier)\n CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);\n}\n\nAdd a performance test for measuring hash implementation time.\/\/ Copyright (c) 2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\/\/\n\/\/ This test performs a series false positive checks using a list of URLs\n\/\/ against a known set of SafeBrowsing data.\n\/\/\n\/\/ It uses a normal SafeBrowsing database to create a bloom filter where it\n\/\/ looks up all the URLs in the url file. A URL that has a prefix found in the\n\/\/ bloom filter and found in the database is considered a hit: a valid lookup\n\/\/ that will result in a gethash request. A URL that has a prefix found in the\n\/\/ bloom filter but not in the database is a miss: a false positive lookup that\n\/\/ will result in an unnecessary gethash request.\n\/\/\n\/\/ By varying the size of the bloom filter and using a constant set of\n\/\/ SafeBrowsing data, we can check a known set of URLs against the filter and\n\/\/ determine the false positive rate.\n\/\/\n\/\/ False positive calculation usage:\n\/\/ $ .\/perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.FalsePositives\n\/\/ --filter-start=\n\/\/ --filter-steps=\n\/\/ --filter-verbose\n\/\/\n\/\/ --filter-start: The filter multiplier to begin with. This represents the\n\/\/ number of bits per prefix of memory to use in the filter.\n\/\/ The default value is identical to the current SafeBrowsing\n\/\/ database value.\n\/\/ --filter-steps: The number of iterations to run, with each iteration\n\/\/ increasing the filter multiplier by 1. The default value\n\/\/ is 1.\n\/\/ --filter-verbose: Used to print out the hit \/ miss results per URL.\n\/\/ --filter-csv: The URL file contains information about the number of\n\/\/ unique views (the popularity) of each URL. See the format\n\/\/ description below.\n\/\/\n\/\/\n\/\/ Hash compute time usage:\n\/\/ $ .\/perf_tests.exe --gtest_filter=SafeBrowsingBloomFilter.HashTime\n\/\/ --filter-num-checks=\n\/\/\n\/\/ --filter-num-checks: The number of hash look ups to perform on the bloom\n\/\/ filter. The default is 10 million.\n\/\/\n\/\/ Data files:\n\/\/ chrome\/test\/data\/safe_browsing\/filter\/database\n\/\/ chrome\/test\/data\/safe_browsing\/filter\/urls\n\/\/\n\/\/ database: A normal SafeBrowsing database.\n\/\/ urls: A text file containing a list of URLs, one per line. If the option\n\/\/ --filter-csv is specified, the format of each line in the file is\n\/\/ , where weight is an integer indicating the number of\n\/\/ unique views for the URL.\n\n#include \n#include \n#include \n\n#include \"base\/command_line.h\"\n#include \"base\/file_path.h\"\n#include \"base\/file_util.h\"\n#include \"base\/logging.h\"\n#include \"base\/path_service.h\"\n#include \"base\/rand_util.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/sha2.h\"\n#include \"base\/string_util.h\"\n#include \"base\/time.h\"\n#include \"chrome\/browser\/safe_browsing\/bloom_filter.h\"\n#include \"chrome\/browser\/safe_browsing\/safe_browsing_util.h\"\n#include \"chrome\/common\/chrome_paths.h\"\n#include \"chrome\/common\/sqlite_compiled_statement.h\"\n#include \"chrome\/common\/sqlite_utils.h\"\n#include \"googleurl\/src\/gurl.h\"\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n\nusing base::Time;\nusing base::TimeDelta;\n\nnamespace {\n\n\/\/ Ensures the SafeBrowsing database is closed properly.\nclass ScopedPerfDatabase {\n public:\n explicit ScopedPerfDatabase(sqlite3* db) : db_(db) {}\n ~ScopedPerfDatabase() {\n sqlite3_close(db_);\n }\n\n private:\n sqlite3* db_;\n\n DISALLOW_COPY_AND_ASSIGN(ScopedPerfDatabase);\n};\n\n\/\/ Command line flags.\nconst wchar_t kFilterVerbose[] = L\"filter-verbose\";\nconst wchar_t kFilterStart[] = L\"filter-start\";\nconst wchar_t kFilterSteps[] = L\"filter-steps\";\nconst wchar_t kFilterCsv[] = L\"filter-csv\";\nconst wchar_t kFilterNumChecks[] = L\"filter-num-checks\";\n\n\/\/ Number of hash checks to make during performance testing.\nstatic const int kNumHashChecks = 10000000;\n\n\/\/ Returns the path to the data used in this test, relative to the top of the\n\/\/ source directory.\nFilePath GetFullDataPath() {\n FilePath full_path;\n CHECK(PathService::Get(chrome::DIR_TEST_DATA, &full_path));\n full_path = full_path.Append(FILE_PATH_LITERAL(\"safe_browsing\"));\n full_path = full_path.Append(FILE_PATH_LITERAL(\"filter\"));\n CHECK(file_util::PathExists(full_path));\n return full_path;\n}\n\n\/\/ Constructs a bloom filter of the appropriate size from the provided prefixes.\nvoid BuildBloomFilter(int size_multiplier,\n const std::vector& prefixes,\n BloomFilter** bloom_filter) {\n \/\/ Create a BloomFilter with the specified size.\n const int key_count = std::max(static_cast(prefixes.size()),\n BloomFilter::kBloomFilterMinSize);\n const int filter_size = key_count * size_multiplier;\n *bloom_filter = new BloomFilter(filter_size);\n\n \/\/ Add the prefixes to it.\n for (size_t i = 0; i < prefixes.size(); ++i)\n (*bloom_filter)->Insert(prefixes[i]);\n\n std::cout << \"Bloom filter with prefixes: \" << prefixes.size()\n << \", multiplier: \" << size_multiplier\n << \", size (bytes): \" << (*bloom_filter)->size()\n << std::endl;\n}\n\n\/\/ Reads the set of add prefixes contained in a SafeBrowsing database into a\n\/\/ sorted array suitable for fast searching. This takes significantly less time\n\/\/ to look up a given prefix than performing SQL queries.\nbool ReadDatabase(const FilePath& path, std::vector* prefixes) {\n FilePath database_file = path.Append(FILE_PATH_LITERAL(\"database\"));\n sqlite3* db = NULL;\n if (OpenSqliteDb(database_file, &db) != SQLITE_OK) {\n sqlite3_close(db);\n return false;\n }\n\n ScopedPerfDatabase database(db);\n scoped_ptr sql_cache(new SqliteStatementCache(db));\n\n \/\/ Get the number of items in the add_prefix table.\n std::string sql = \"SELECT COUNT(*) FROM add_prefix\";\n SQLITE_UNIQUE_STATEMENT(count_statement, *sql_cache, sql.c_str());\n if (!count_statement.is_valid())\n return false;\n\n if (count_statement->step() != SQLITE_ROW)\n return false;\n\n const int count = count_statement->column_int(0);\n\n \/\/ Load them into a prefix vector and sort\n prefixes->reserve(count);\n sql = \"SELECT prefix FROM add_prefix\";\n SQLITE_UNIQUE_STATEMENT(prefix_statement, *sql_cache, sql.c_str());\n if (!prefix_statement.is_valid())\n return false;\n\n while (prefix_statement->step() == SQLITE_ROW)\n prefixes->push_back(prefix_statement->column_int(0));\n\n DCHECK(static_cast(prefixes->size()) == count);\n sort(prefixes->begin(), prefixes->end());\n\n return true;\n}\n\n\/\/ Generates all legal SafeBrowsing prefixes for the specified URL, and returns\n\/\/ the set of Prefixes that exist in the bloom filter. The function returns the\n\/\/ number of host + path combinations checked.\nint GeneratePrefixHits(const std::string url,\n BloomFilter* bloom_filter,\n std::vector* prefixes) {\n GURL url_check(url);\n std::vector hosts;\n if (url_check.HostIsIPAddress()) {\n hosts.push_back(url_check.host());\n } else {\n safe_browsing_util::GenerateHostsToCheck(url_check, &hosts);\n }\n\n std::vector paths;\n safe_browsing_util::GeneratePathsToCheck(url_check, &paths);\n\n for (size_t i = 0; i < hosts.size(); ++i) {\n for (size_t j = 0; j < paths.size(); ++j) {\n SBPrefix prefix;\n base::SHA256HashString(hosts[i] + paths[j], &prefix, sizeof(prefix));\n if (bloom_filter->Exists(prefix))\n prefixes->push_back(prefix);\n }\n }\n\n return hosts.size() * paths.size();\n}\n\n\/\/ Binary search of sorted prefixes.\nbool IsPrefixInDatabase(SBPrefix prefix,\n const std::vector& prefixes) {\n if (prefixes.empty())\n return false;\n\n int low = 0;\n int high = prefixes.size() - 1;\n while (low <= high) {\n int mid = ((unsigned int)low + (unsigned int)high) >> 1;\n SBPrefix prefix_mid = prefixes[mid];\n if (prefix_mid == prefix)\n return true;\n if (prefix_mid < prefix)\n low = mid + 1;\n else\n high = mid - 1;\n }\n\n return false;\n}\n\n\/\/ Construct a bloom filter with the given prefixes and multiplier, and test the\n\/\/ false positive rate (misses) against a URL list.\nvoid CalculateBloomFilterFalsePositives(\n int size_multiplier,\n const FilePath& data_dir,\n const std::vector& prefix_list) {\n BloomFilter* bloom_filter = NULL;\n BuildBloomFilter(size_multiplier, prefix_list, &bloom_filter);\n scoped_refptr scoped_filter(bloom_filter);\n\n \/\/ Read in data file line at a time.\n FilePath url_file = data_dir.Append(FILE_PATH_LITERAL(\"urls\"));\n std::ifstream url_stream(WideToASCII(url_file.ToWStringHack()).c_str());\n\n \/\/ Keep track of stats\n int hits = 0;\n int misses = 0;\n int weighted_hits = 0;\n int weighted_misses = 0;\n int url_count = 0;\n int prefix_count = 0;\n\n \/\/ Print out volumes of data (per URL hit and miss information).\n bool verbose = CommandLine::ForCurrentProcess()->HasSwitch(kFilterVerbose);\n bool use_weights = CommandLine::ForCurrentProcess()->HasSwitch(kFilterCsv);\n\n std::string url;\n while (std::getline(url_stream, url)) {\n ++url_count;\n\n \/\/ Handle a format that contains URLs weighted by unique views.\n int weight = 1;\n if (use_weights) {\n std::string::size_type pos = url.find_last_of(\",\");\n if (pos != std::string::npos) {\n weight = StringToInt(std::string(url, pos + 1));\n url = url.substr(0, pos);\n }\n }\n\n \/\/ See if the URL is in the bloom filter.\n std::vector prefixes;\n prefix_count += GeneratePrefixHits(url, bloom_filter, &prefixes);\n\n \/\/ See if the prefix is actually in the database (in-memory prefix list).\n for (size_t i = 0; i < prefixes.size(); ++i) {\n if (IsPrefixInDatabase(prefixes[i], prefix_list)) {\n ++hits;\n weighted_hits += weight;\n if (verbose) {\n std::cout << \"Hit for URL: \" << url\n << \" (prefix = \" << prefixes[i] << \")\"\n << std::endl;\n }\n } else {\n ++misses;\n weighted_misses += weight;\n if (verbose) {\n std::cout << \"Miss for URL: \" << url\n << \" (prefix = \" << prefixes[i] << \")\"\n << std::endl;\n }\n }\n }\n }\n\n \/\/ Print out the results for this test.\n std::cout << \"URLs checked: \" << url_count\n << \", prefix compares: \" << prefix_count\n << \", hits: \" << hits\n << \", misses: \" << misses;\n if (use_weights) {\n std::cout << \", weighted hits: \" << weighted_hits\n << \", weighted misses: \" << weighted_misses;\n }\n std::cout << std::endl;\n}\n\n} \/\/ namespace\n\n\/\/ This test can take several minutes to perform its calculations, so it should\n\/\/ be disabled until you need to run it.\nTEST(SafeBrowsingBloomFilter, FalsePositives) {\n std::vector prefix_list;\n FilePath data_dir = GetFullDataPath();\n ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));\n\n int start = BloomFilter::kBloomFilterSizeRatio;\n if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterStart)) {\n start = StringToInt(\n CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterStart));\n }\n\n int steps = 1;\n if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterSteps)) {\n steps = StringToInt(\n CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterSteps));\n }\n\n int stop = start + steps;\n\n for (int multiplier = start; multiplier < stop; ++multiplier)\n CalculateBloomFilterFalsePositives(multiplier, data_dir, prefix_list);\n}\n\n\/\/ Computes the time required for performing a number of look ups in a bloom\n\/\/ filter. This is useful for measuring the performance of new hash functions.\nTEST(SafeBrowsingBloomFilter, HashTime) {\n \/\/ Read the data from the database.\n std::vector prefix_list;\n FilePath data_dir = GetFullDataPath();\n ASSERT_TRUE(ReadDatabase(data_dir, &prefix_list));\n\n int num_checks = kNumHashChecks;\n if (CommandLine::ForCurrentProcess()->HasSwitch(kFilterNumChecks)) {\n num_checks = StringToInt(\n CommandLine::ForCurrentProcess()->GetSwitchValue(kFilterNumChecks));\n }\n\n \/\/ Populate the bloom filter and measure the time.\n BloomFilter* bloom_filter = NULL;\n Time populate_before = Time::Now();\n BuildBloomFilter(BloomFilter::kBloomFilterSizeRatio,\n prefix_list, &bloom_filter);\n TimeDelta populate = Time::Now() - populate_before;\n\n \/\/ Check a large number of random prefixes against the filter.\n int hits = 0;\n Time check_before = Time::Now();\n for (int i = 0; i < num_checks; ++i) {\n uint32 prefix = static_cast(base::RandUint64());\n if (bloom_filter->Exists(prefix))\n ++hits;\n }\n TimeDelta check = Time::Now() - check_before;\n\n int64 time_per_insert = populate.InMicroseconds() \/\n static_cast(prefix_list.size());\n int64 time_per_check = check.InMicroseconds() \/ num_checks;\n\n std::cout << \"Time results for checks: \" << num_checks\n << \", prefixes: \" << prefix_list.size()\n << \", populate time (ms): \" << populate.InMilliseconds()\n << \", check time (ms): \" << check.InMilliseconds()\n << \", hits: \" << hits\n << \", per-populate (us): \" << time_per_insert\n << \", per-check (us): \" << time_per_check\n << std::endl;\n}\n\n<|endoftext|>"} {"text":"\/*\n Copyright 2002-2013 CEA LIST\n\n This file is part of LIMA.\n\n LIMA is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n LIMA is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with LIMA. If not, see \n*\/\n\/***************************************************************************\n * Copyright (C) 2004-2012 by CEA LIST *\n * *\n ***************************************************************************\/\n#include \"MorphoSyntacticData.h\"\n#include \"MorphoSyntacticDataUtils.h\"\n\n#include \"common\/MediaticData\/mediaticData.h\"\n#include \"common\/Data\/strwstrtools.h\"\n\n#include \n\nusing namespace std;\nusing namespace Lima::Common::MediaticData;\n\nnamespace Lima\n{\n\nnamespace LinguisticProcessing\n{\n\nnamespace LinguisticAnalysisStructure\n{\n\nbool LinguisticElement::operator==(const LinguisticElement& le) const\n{\n return ((properties==le.properties) &&\n (inflectedForm==le.inflectedForm) &&\n (lemma==le.lemma) &&\n (normalizedForm==le.normalizedForm) &&\n (type==le.type));\n}\n\nbool LinguisticElement::operator<(const LinguisticElement& le) const\n{\n if (inflectedForm!=le.inflectedForm) return inflectedForm& microFilter)\n{\n LinguisticCode micro(0);\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n LinguisticCode tmp=microAccessor.readValue(it->properties);\n if (micro!=static_cast(0))\n {\n if (micro!=tmp)\n {\n return false;\n }\n }\n else\n {\n micro=tmp;\n }\n bool found=false;\n for (list::const_iterator filterItr=microFilter.begin();\n filterItr!=microFilter.end();\n filterItr++)\n {\n if (tmp==*filterItr)\n {\n found=true;\n break;\n }\n }\n if (!found)\n {\n return false;\n }\n }\n \/\/ if micro is 0, then there was no micros, return false\n return micro!=static_cast(0);\n}\n\nuint64_t MorphoSyntacticData::countValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor)\n{\n set values;\n allValues(propertyAccessor,values);\n return values.size();\n}\n\nvoid MorphoSyntacticData::allValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor,std::set& result) const\n {\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n if (!propertyAccessor.empty(it->properties))\n {\n result.insert(propertyAccessor.readValue(it->properties));\n }\n }\n }\n\nvoid MorphoSyntacticData::outputXml(std::ostream& xmlStream,const Common::PropertyCode::PropertyCodeManager& pcm,const FsaStringsPool& sp) const\n{\n xmlStream << \" \" << std::endl;\n\n if (!empty())\n {\n \/\/ trie pour avoir les donn�s group�s par strings\n MorphoSyntacticData tmp(*this);\n sort(tmp.begin(),tmp.end(),ltString());\n MorphoSyntacticType type(NO_MORPHOSYNTACTICTYPE);\n StringsPoolIndex form(0);\n StringsPoolIndex lemma(0);\n StringsPoolIndex norm(0);\n string currentType;\n bool firstEntry=true;\n for (const_iterator it=tmp.begin();\n it!=tmp.end();\n it++)\n {\n if (it->type != type)\n {\n \/\/ Changement type\n if (!firstEntry)\n {\n xmlStream << \" <\/form>\" << std::endl;\n xmlStream << \" <\/\" << currentType << \">\" << std::endl;\n }\n type=it->type;\n switch ( type )\n {\n case SIMPLE_WORD :\n currentType = \"simple_word\";\n break;\n case IDIOMATIC_EXPRESSION :\n currentType = \"idiomatic_expression\";\n break;\n case UNKNOWN_WORD :\n currentType = \"unknown_word\";\n break;\n case ABBREV_ALTERNATIVE :\n currentType = \"abbrev_alternative\";\n break;\n case HYPHEN_ALTERNATIVE :\n currentType = \"hyphen_alternative\";\n break;\n case CONCATENATED_ALTERNATIVE :\n currentType = \"concatenated_alternative\";\n break;\n case CAPITALFIRST_WORD :\n currentType = \"capitalfirst_word\";\n break;\n case AGGLUTINATED_WORD:\n currentType = \"agglutinated_word\";\n break;\n case DESAGGLUTINATED_WORD :\n currentType = \"desagglutinated_word\";\n break;\n case SPECIFIC_ENTITY :\n currentType = \"specific_entity\";\n break;\n case HYPERWORD_ALTERNATIVE:\n currentType = \"hyperwordstemmer_alternative\";\n break;\n case CHINESE_SEGMENTER:\n currentType = \"chinese_segmenter\";\n break;\n default :\n currentType = \"UNKNOWN_MORPHOSYNTACTIC_TYPE\";\n break;\n }\n xmlStream << \" <\" << currentType << \">\" << std::endl;\n }\n if ((it->inflectedForm != form) || (it->lemma != lemma) || (it->normalizedForm != norm))\n {\n if (!firstEntry)\n {\n xmlStream << \" <\/form>\" << std::endl;\n }\n form=it->inflectedForm;\n lemma=it->lemma;\n norm=it->normalizedForm;\n xmlStream << \"
\" << std::endl;\n }\n const std::map& managers=pcm.getPropertyManagers();\n xmlStream << \" \" << std::endl;\n for (std::map::const_iterator propItr=managers.begin();\n propItr!=managers.end();\n propItr++)\n {\n if (!propItr->second.getPropertyAccessor().empty(it->properties))\n {\n xmlStream << \"

first << \"\\\" val=\\\"\" << propItr->second.getPropertySymbolicValue(it->properties) << \"\\\"\/>\" << std::endl;\n }\n }\n xmlStream << \" <\/property>\" << std::endl;\n firstEntry=false;\n }\n xmlStream << \" <\/form>\" << std::endl;\n xmlStream << \" <\/\" << currentType << \">\" << std::endl;\n }\n xmlStream << \" <\/data>\" << std::endl;\n}\n\nstd::set MorphoSyntacticData::allInflectedForms() const\n {\n set forms;\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n forms.insert(it->inflectedForm);\n }\n return forms;\n }\n\nstd::set MorphoSyntacticData::allLemma() const\n {\n set lemma;\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n lemma.insert(it->lemma);\n }\n return lemma;\n }\n\nstd::set MorphoSyntacticData::allNormalizedForms() const\n {\n set norms;\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n norms.insert(it->normalizedForm);\n }\n return norms;\n }\n\nLinguisticCode MorphoSyntacticData::firstValue(const Common::PropertyCode::PropertyAccessor& propertyAccessor) const\n{\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n if (!propertyAccessor.empty(it->properties))\n {\n return propertyAccessor.readValue(it->properties);\n }\n }\n return static_cast(0);\n}\n\n\n\n} \/\/ LinguisticAnalysisStructure\n\n} \/\/ LinguisticProcessing\n\n} \/\/ Lima\nadd ENCHANT_LIBRARIES for spell checking\/*\n Copyright 2002-2013 CEA LIST\n\n This file is part of LIMA.\n\n LIMA is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n LIMA is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with LIMA. If not, see \n*\/\n\/***************************************************************************\n * Copyright (C) 2004-2012 by CEA LIST *\n * *\n ***************************************************************************\/\n#include \"MorphoSyntacticData.h\"\n#include \"MorphoSyntacticDataUtils.h\"\n\n#include \"common\/MediaticData\/mediaticData.h\"\n#include \"common\/Data\/strwstrtools.h\"\n\n#include \n\nusing namespace std;\nusing namespace Lima::Common::MediaticData;\n\nnamespace Lima\n{\n\nnamespace LinguisticProcessing\n{\n\nnamespace LinguisticAnalysisStructure\n{\n\nbool LinguisticElement::operator==(const LinguisticElement& le) const\n{\n return ((properties==le.properties) &&\n (inflectedForm==le.inflectedForm) &&\n (lemma==le.lemma) &&\n (normalizedForm==le.normalizedForm) &&\n (type==le.type));\n}\n\nbool LinguisticElement::operator<(const LinguisticElement& le) const\n{\n if (inflectedForm!=le.inflectedForm) return inflectedForm& microFilter)\n{\n LinguisticCode micro(0);\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n LinguisticCode tmp=microAccessor.readValue(it->properties);\n if (micro!=static_cast(0))\n {\n if (micro!=tmp)\n {\n return false;\n }\n }\n else\n {\n micro=tmp;\n }\n bool found=false;\n for (list::const_iterator filterItr=microFilter.begin();\n filterItr!=microFilter.end();\n filterItr++)\n {\n if (tmp==*filterItr)\n {\n found=true;\n break;\n }\n }\n if (!found)\n {\n return false;\n }\n }\n \/\/ if micro is 0, then there was no micros, return false\n return micro!=static_cast(0);\n}\n\nuint64_t MorphoSyntacticData::countValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor)\n{\n set values;\n allValues(propertyAccessor,values);\n return values.size();\n}\n\nvoid MorphoSyntacticData::allValues(const Common::PropertyCode::PropertyAccessor& propertyAccessor,std::set& result) const\n {\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n if (!propertyAccessor.empty(it->properties))\n {\n result.insert(propertyAccessor.readValue(it->properties));\n }\n }\n }\n\nvoid MorphoSyntacticData::outputXml(std::ostream& xmlStream,const Common::PropertyCode::PropertyCodeManager& pcm,const FsaStringsPool& sp) const\n{\n xmlStream << \" \" << std::endl;\n\n if (!empty())\n {\n \/\/ trie pour avoir les donn�s group�s par strings\n MorphoSyntacticData tmp(*this);\n sort(tmp.begin(),tmp.end(),ltString());\n MorphoSyntacticType type(NO_MORPHOSYNTACTICTYPE);\n StringsPoolIndex form(0);\n StringsPoolIndex lemma(0);\n StringsPoolIndex norm(0);\n string currentType;\n bool firstEntry=true;\n for (const_iterator it=tmp.begin();\n it!=tmp.end();\n it++)\n {\n if (it->type != type)\n {\n \/\/ Changement type\n if (!firstEntry)\n {\n xmlStream << \" <\/form>\" << std::endl;\n xmlStream << \" <\/\" << currentType << \">\" << std::endl;\n }\n type=it->type;\n switch ( type )\n {\n case SIMPLE_WORD :\n currentType = \"simple_word\";\n break;\n case IDIOMATIC_EXPRESSION :\n currentType = \"idiomatic_expression\";\n break;\n case UNKNOWN_WORD :\n currentType = \"unknown_word\";\n break;\n case ABBREV_ALTERNATIVE :\n currentType = \"abbrev_alternative\";\n break;\n case HYPHEN_ALTERNATIVE :\n currentType = \"hyphen_alternative\";\n break;\n case CONCATENATED_ALTERNATIVE :\n currentType = \"concatenated_alternative\";\n break;\n case SPELLING_ALTERNATIVE :\n currentType = \"spelling_alternative\";\n break;\n case CAPITALFIRST_WORD :\n currentType = \"capitalfirst_word\";\n break;\n case AGGLUTINATED_WORD:\n currentType = \"agglutinated_word\";\n break;\n case DESAGGLUTINATED_WORD :\n currentType = \"desagglutinated_word\";\n break;\n case SPECIFIC_ENTITY :\n currentType = \"specific_entity\";\n break;\n case HYPERWORD_ALTERNATIVE:\n currentType = \"hyperwordstemmer_alternative\";\n break;\n case CHINESE_SEGMENTER:\n currentType = \"chinese_segmenter\";\n break;\n default :\n currentType = \"UNKNOWN_MORPHOSYNTACTIC_TYPE\";\n break;\n }\n xmlStream << \" <\" << currentType << \">\" << std::endl;\n }\n if ((it->inflectedForm != form) || (it->lemma != lemma) || (it->normalizedForm != norm))\n {\n if (!firstEntry)\n {\n xmlStream << \" <\/form>\" << std::endl;\n }\n form=it->inflectedForm;\n lemma=it->lemma;\n norm=it->normalizedForm;\n xmlStream << \" \" << std::endl;\n }\n const std::map& managers=pcm.getPropertyManagers();\n xmlStream << \" \" << std::endl;\n for (std::map::const_iterator propItr=managers.begin();\n propItr!=managers.end();\n propItr++)\n {\n if (!propItr->second.getPropertyAccessor().empty(it->properties))\n {\n xmlStream << \"

first << \"\\\" val=\\\"\" << propItr->second.getPropertySymbolicValue(it->properties) << \"\\\"\/>\" << std::endl;\n }\n }\n xmlStream << \" <\/property>\" << std::endl;\n firstEntry=false;\n }\n xmlStream << \" <\/form>\" << std::endl;\n xmlStream << \" <\/\" << currentType << \">\" << std::endl;\n }\n xmlStream << \" <\/data>\" << std::endl;\n}\n\nstd::set MorphoSyntacticData::allInflectedForms() const\n {\n set forms;\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n forms.insert(it->inflectedForm);\n }\n return forms;\n }\n\nstd::set MorphoSyntacticData::allLemma() const\n {\n set lemma;\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n lemma.insert(it->lemma);\n }\n return lemma;\n }\n\nstd::set MorphoSyntacticData::allNormalizedForms() const\n {\n set norms;\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n norms.insert(it->normalizedForm);\n }\n return norms;\n }\n\nLinguisticCode MorphoSyntacticData::firstValue(const Common::PropertyCode::PropertyAccessor& propertyAccessor) const\n{\n for (const_iterator it=begin();\n it!=end();\n it++)\n {\n if (!propertyAccessor.empty(it->properties))\n {\n return propertyAccessor.readValue(it->properties);\n }\n }\n return static_cast(0);\n}\n\n\n\n} \/\/ LinguisticAnalysisStructure\n\n} \/\/ LinguisticProcessing\n\n} \/\/ Lima\n<|endoftext|>"} {"text":"\/\/=================================================================================================\n\/*!\n\/\/ \\file src\/mathtest\/lapack\/OperationTest.cpp\n\/\/ \\brief Source file for the LAPACK operation test\n\/\/\n\/\/ Copyright (C) 2013 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/ This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/ the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/ forms, with or without modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/ conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/ of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/ provided with the distribution.\n\/\/ 3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/ SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include \n#include \n#include \n#include \n\n\nnamespace blazetest {\n\nnamespace mathtest {\n\nnamespace lapack {\n\n\/\/=================================================================================================\n\/\/\n\/\/ CONSTRUCTORS\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\n\/*!\\brief Constructor for the OperationTest class test.\n\/\/\n\/\/ \\exception std::runtime_error Operation error detected.\n*\/\nOperationTest::OperationTest()\n{\n\/*\n testGeqrf< float >();\n testGeqrf< double >();\n testGeqrf< blaze::complex >();\n testGeqrf< blaze::complex >();\n\n testGetrf< float >();\n testGetrf< double >();\n testGetrf< blaze::complex >();\n testGetrf< blaze::complex >();\n\n testSytrf< float >();\n testSytrf< double >();\n testSytrf< blaze::complex >();\n testSytrf< blaze::complex >();\n\n testHetrf< blaze::complex >();\n testHetrf< blaze::complex >();\n\n testPotrf< float >();\n testPotrf< double >();\n testPotrf< blaze::complex >();\n testPotrf< blaze::complex >();\n\n testGetri< float >();\n testGetri< double >();\n testGetri< blaze::complex >();\n testGetri< blaze::complex >();\n\n testSytri< float >();\n testSytri< double >();\n testSytri< blaze::complex >();\n testSytri< blaze::complex >();\n *\/\n\n \/\/testHetri< blaze::complex >();\n testHetri< blaze::complex >();\n\n \/*\n testPotri< float >();\n testPotri< double >();\n testPotri< blaze::complex >();\n testPotri< blaze::complex >();\n\n testTrtri< float >();\n testTrtri< double >();\n testTrtri< blaze::complex >();\n testTrtri< blaze::complex >();\n\n testGesv< float >();\n testGesv< double >();\n testGesv< blaze::complex >();\n testGesv< blaze::complex >();\n *\/\n}\n\/\/*************************************************************************************************\n\n} \/\/ namespace lapack\n\n} \/\/ namespace mathtest\n\n} \/\/ namespace blazetest\n\n\n\n\n\/\/=================================================================================================\n\/\/\n\/\/ MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n std::cout << \" Running LAPACK operation test...\" << std::endl;\n\n try\n {\n RUN_LAPACK_OPERATION_TEST;\n }\n catch( std::exception& ex ) {\n std::cerr << \"\\n\\n ERROR DETECTED during LAPACK operation test:\\n\"\n << ex.what() << \"\\n\";\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\nFix the operation test for the LAPACK wrapper functions\/\/=================================================================================================\n\/*!\n\/\/ \\file src\/mathtest\/lapack\/OperationTest.cpp\n\/\/ \\brief Source file for the LAPACK operation test\n\/\/\n\/\/ Copyright (C) 2013 Klaus Iglberger - All Rights Reserved\n\/\/\n\/\/ This file is part of the Blaze library. You can redistribute it and\/or modify it under\n\/\/ the terms of the New (Revised) BSD License. Redistribution and use in source and binary\n\/\/ forms, with or without modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice, this list of\n\/\/ conditions and the following disclaimer.\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice, this list\n\/\/ of conditions and the following disclaimer in the documentation and\/or other materials\n\/\/ provided with the distribution.\n\/\/ 3. Neither the names of the Blaze development group nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software without specific\n\/\/ prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY\n\/\/ EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES\n\/\/ OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT\n\/\/ SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED\n\/\/ TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR\n\/\/ BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n\/\/ DAMAGE.\n*\/\n\/\/=================================================================================================\n\n\n\/\/*************************************************************************************************\n\/\/ Includes\n\/\/*************************************************************************************************\n\n#include \n#include \n#include \n#include \n\n\nnamespace blazetest {\n\nnamespace mathtest {\n\nnamespace lapack {\n\n\/\/=================================================================================================\n\/\/\n\/\/ CONSTRUCTORS\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\n\/*!\\brief Constructor for the OperationTest class test.\n\/\/\n\/\/ \\exception std::runtime_error Operation error detected.\n*\/\nOperationTest::OperationTest()\n{\n testGeqrf< float >();\n testGeqrf< double >();\n testGeqrf< blaze::complex >();\n testGeqrf< blaze::complex >();\n\n testGetrf< float >();\n testGetrf< double >();\n testGetrf< blaze::complex >();\n testGetrf< blaze::complex >();\n\n testSytrf< float >();\n testSytrf< double >();\n testSytrf< blaze::complex >();\n testSytrf< blaze::complex >();\n\n testHetrf< blaze::complex >();\n testHetrf< blaze::complex >();\n\n testPotrf< float >();\n testPotrf< double >();\n testPotrf< blaze::complex >();\n testPotrf< blaze::complex >();\n\n testGetri< float >();\n testGetri< double >();\n testGetri< blaze::complex >();\n testGetri< blaze::complex >();\n\n testSytri< float >();\n testSytri< double >();\n testSytri< blaze::complex >();\n testSytri< blaze::complex >();\n\n testHetri< blaze::complex >();\n testHetri< blaze::complex >();\n\n testPotri< float >();\n testPotri< double >();\n testPotri< blaze::complex >();\n testPotri< blaze::complex >();\n\n testTrtri< float >();\n testTrtri< double >();\n testTrtri< blaze::complex >();\n testTrtri< blaze::complex >();\n\n testGesv< float >();\n testGesv< double >();\n testGesv< blaze::complex >();\n testGesv< blaze::complex >();\n}\n\/\/*************************************************************************************************\n\n} \/\/ namespace lapack\n\n} \/\/ namespace mathtest\n\n} \/\/ namespace blazetest\n\n\n\n\n\/\/=================================================================================================\n\/\/\n\/\/ MAIN FUNCTION\n\/\/\n\/\/=================================================================================================\n\n\/\/*************************************************************************************************\nint main()\n{\n std::cout << \" Running LAPACK operation test...\" << std::endl;\n\n try\n {\n RUN_LAPACK_OPERATION_TEST;\n }\n catch( std::exception& ex ) {\n std::cerr << \"\\n\\n ERROR DETECTED during LAPACK operation test:\\n\"\n << ex.what() << \"\\n\";\n return EXIT_FAILURE;\n }\n\n return EXIT_SUCCESS;\n}\n\/\/*************************************************************************************************\n<|endoftext|>"} {"text":"#include \"Adafruit_MCP23008.h\"\r\n\r\n\r\n\/\/ This is a library for the MCP23008 i2c port expander\r\n\r\n\/\/ These displays use I2C to communicate, 2 pins are required to\r\n\/\/ interface\r\n\/\/ Adafruit invests time and resources providing this open source code,\r\n\/\/ please support Adafruit and open-source hardware by purchasing\r\n\/\/ products from Adafruit!\r\n\r\n\/\/ Written by Limor Fried\/Ladyada for Adafruit Industries.\r\n\/\/ BSD license, all text above must be included in any redistribution\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ RTC_DS1307 implementation\r\n\r\nvoid Adafruit_MCP23008::begin(uint8_t addr) {\r\n if (addr > 7) {\r\n addr = 7;\r\n }\r\n i2caddr = addr;\r\n\r\n Wire.setSpeed(CLOCK_SPEED_100KHZ);\r\n Wire.stretchClock(true);\r\n Wire.begin();\r\n delayMicroseconds(2);\r\n \/\/ set defaults!\r\n Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)MCP23008_IODIR);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0xFF); \/\/ all inputs\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\t\r\n delayMicroseconds(2);\r\n Wire.endTransmission();\r\n delayMicroseconds(2);\r\n}\r\n\r\nvoid Adafruit_MCP23008::begin(void) {\r\n begin(0);\r\n}\r\n\r\nvoid Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) {\r\n uint8_t iodir;\r\n \r\n\r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return;\r\n \r\n iodir = read8(MCP23008_IODIR);\r\n\r\n \/\/ set the pin and direction\r\n if (d == INPUT) {\r\n iodir |= 1 << p; \r\n } else {\r\n iodir &= ~(1 << p);\r\n }\r\n\r\n \/\/ write the new IODIR\r\n write8(MCP23008_IODIR, iodir);\r\n}\r\n\r\nuint8_t Adafruit_MCP23008::readGPIO(void) {\r\n \/\/ read the current GPIO input\r\n return read8(MCP23008_GPIO);\r\n}\r\n\r\nvoid Adafruit_MCP23008::writeGPIO(uint8_t gpio) {\r\n write8(MCP23008_GPIO, gpio);\r\n}\r\n\r\n\r\nvoid Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) {\r\n uint8_t gpio;\r\n \r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return;\r\n\r\n \/\/ read the current GPIO output latches\r\n gpio = readGPIO();\r\n\r\n \/\/ set the pin and direction\r\n if (d == HIGH) {\r\n gpio |= 1 << p; \r\n } else {\r\n gpio &= ~(1 << p);\r\n }\r\n\r\n \/\/ write the new GPIO\r\n writeGPIO(gpio);\r\n}\r\n\r\nvoid Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) {\r\n uint8_t gppu;\r\n \r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return;\r\n\r\n gppu = read8(MCP23008_GPPU);\r\n \/\/ set the pin and direction\r\n if (d == HIGH) {\r\n gppu |= 1 << p; \r\n } else {\r\n gppu &= ~(1 << p);\r\n }\r\n \/\/ write the new GPIO\r\n write8(MCP23008_GPPU, gppu);\r\n}\r\n\r\nuint8_t Adafruit_MCP23008::digitalRead(uint8_t p) {\r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return 0;\r\n\r\n \/\/ read the current GPIO\r\n return (readGPIO() >> p) & 0x1;\r\n}\r\n\r\nuint8_t Adafruit_MCP23008::read8(uint8_t addr) {\r\n Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)addr);\t\r\n delayMicroseconds(2);\r\n Wire.endTransmission();\r\n delayMicroseconds(2);\r\n Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1);\r\n delayMicroseconds(2);\r\n \r\n return Wire.read();\r\n}\r\n\r\n\r\nvoid Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) {\r\n Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)addr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)data);\r\n delayMicroseconds(2);\r\n Wire.endTransmission();\r\n delayMicroseconds(2);\r\n}\r\nmodified end of transmission delay#include \"Adafruit_MCP23008.h\"\r\n\r\n\r\n\/\/ This is a library for the MCP23008 i2c port expander\r\n\r\n\/\/ These displays use I2C to communicate, 2 pins are required to\r\n\/\/ interface\r\n\/\/ Adafruit invests time and resources providing this open source code,\r\n\/\/ please support Adafruit and open-source hardware by purchasing\r\n\/\/ products from Adafruit!\r\n\r\n\/\/ Written by Limor Fried\/Ladyada for Adafruit Industries.\r\n\/\/ BSD license, all text above must be included in any redistribution\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ RTC_DS1307 implementation\r\n\r\nvoid Adafruit_MCP23008::begin(uint8_t addr) {\r\n if (addr > 7) {\r\n addr = 7;\r\n }\r\n i2caddr = addr;\r\n\r\n \/\/Wire.setSpeed(CLOCK_SPEED_100KHZ);\r\n \/\/Wire.stretchClock(true);\r\n Wire.begin();\r\n delayMicroseconds(2);\r\n \/\/ set defaults!\r\n Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)MCP23008_IODIR);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0xFF); \/\/ all inputs\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\r\n delayMicroseconds(2);\r\n Wire.write((byte)0x00);\t\r\n delayMicroseconds(2);\r\n Wire.endTransmission();\r\n delayMicroseconds(5);\r\n}\r\n\r\nvoid Adafruit_MCP23008::begin(void) {\r\n begin(0);\r\n}\r\n\r\nvoid Adafruit_MCP23008::pinMode(uint8_t p, uint8_t d) {\r\n uint8_t iodir;\r\n \r\n\r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return;\r\n \r\n iodir = read8(MCP23008_IODIR);\r\n\r\n \/\/ set the pin and direction\r\n if (d == INPUT) {\r\n iodir |= 1 << p; \r\n } else {\r\n iodir &= ~(1 << p);\r\n }\r\n\r\n \/\/ write the new IODIR\r\n write8(MCP23008_IODIR, iodir);\r\n}\r\n\r\nuint8_t Adafruit_MCP23008::readGPIO(void) {\r\n \/\/ read the current GPIO input\r\n return read8(MCP23008_GPIO);\r\n}\r\n\r\nvoid Adafruit_MCP23008::writeGPIO(uint8_t gpio) {\r\n write8(MCP23008_GPIO, gpio);\r\n}\r\n\r\n\r\nvoid Adafruit_MCP23008::digitalWrite(uint8_t p, uint8_t d) {\r\n uint8_t gpio;\r\n \r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return;\r\n\r\n \/\/ read the current GPIO output latches\r\n gpio = readGPIO();\r\n\r\n \/\/ set the pin and direction\r\n if (d == HIGH) {\r\n gpio |= 1 << p; \r\n } else {\r\n gpio &= ~(1 << p);\r\n }\r\n\r\n \/\/ write the new GPIO\r\n writeGPIO(gpio);\r\n}\r\n\r\nvoid Adafruit_MCP23008::pullUp(uint8_t p, uint8_t d) {\r\n uint8_t gppu;\r\n \r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return;\r\n\r\n gppu = read8(MCP23008_GPPU);\r\n \/\/ set the pin and direction\r\n if (d == HIGH) {\r\n gppu |= 1 << p; \r\n } else {\r\n gppu &= ~(1 << p);\r\n }\r\n \/\/ write the new GPIO\r\n write8(MCP23008_GPPU, gppu);\r\n}\r\n\r\nuint8_t Adafruit_MCP23008::digitalRead(uint8_t p) {\r\n \/\/ only 8 bits!\r\n if (p > 7)\r\n return 0;\r\n\r\n \/\/ read the current GPIO\r\n return (readGPIO() >> p) & 0x1;\r\n}\r\n\r\nuint8_t Adafruit_MCP23008::read8(uint8_t addr) {\r\n Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)addr);\t\r\n delayMicroseconds(2);\r\n Wire.endTransmission();\r\n delayMicroseconds(5);\r\n Wire.requestFrom(MCP23008_ADDRESS | i2caddr, 1);\r\n delayMicroseconds(2);\r\n \r\n return Wire.read();\r\n}\r\n\r\n\r\nvoid Adafruit_MCP23008::write8(uint8_t addr, uint8_t data) {\r\n Wire.beginTransmission(MCP23008_ADDRESS | i2caddr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)addr);\r\n delayMicroseconds(2);\r\n Wire.write((byte)data);\r\n delayMicroseconds(2);\r\n Wire.endTransmission();\r\n delayMicroseconds(5);\r\n}\r\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"gain_schedule.h\"\n#include \"MPU6050.h\"\n\nnamespace control {\n\nvector_t StateEstimator::update(const vector_t& x,\n const vector_t& u) const\n{\n return A * x + B * u;\n}\n\nvector_t LQRController::update(const vector_t& x) const\n{\n return C * x;\n}\n\nvector_t PIController::update(const vector_t& x,\n const vector_t& e) const\n{\n return Kp * x + Ki * e;\n}\n\nbool rt_controller_t::operator<(const rt_controller_t& rhs) const\n{\n return rate < rhs.rate;\n}\n\nGainSchedule::GainSchedule() : state_{{}}, pi_control_enabled_{false}\n{\n\n}\n\nfloat GainSchedule::rate() const\n{\n return rate_;\n}\n\nbool GainSchedule::set_sample(Sample& s)\n{\n s_ = &s;\n return set_rate(s.encoder.rear_wheel_rate);\n}\n\nvoid GainSchedule::set_state(const vector_t& state)\n{\n state_ = state;\n}\n\nbool GainSchedule::set_rate(float rate)\n{\n bool valid = true;\n rate_ = rate;\n\n r.rate = rate;\n auto it = std::upper_bound(schedule_.begin(), schedule_.end(), r);\n if (it == schedule_.begin() || it == schedule_.end()) {\n valid = false;\n if (it == schedule_.begin()) {\n s_->estimate.theta_R_dot_upper = it->rate;\n s_->estimate.theta_R_dot_lower = NAN;\n } else {\n s_->estimate.theta_R_dot_upper = NAN;\n s_->estimate.theta_R_dot_lower = (--it)->rate;\n }\n } else {\n valid = true;\n s_->estimate.theta_R_dot_upper = it->rate;\n ss_upper_ = const_cast(&(it->controller));\n s_->estimate.theta_R_dot_lower = (--it)->rate;\n ss_lower_ = const_cast(&(it->controller));\n\n alpha_ = (rate - s_->estimate.theta_R_dot_lower) \/\n (s_->estimate.theta_R_dot_upper - s_->estimate.theta_R_dot_lower);\n }\n\n return valid;\n}\n\nvoid GainSchedule::state_estimate(float torque_prev)\n{\n if (state_estimate_time_ == s_->loop_count)\n return;\n state_estimate_time_ = s_->loop_count;\n vector_t input {{torque_prev, s_->encoder.steer,\n hardware::MPU6050::phi_dot(*s_)}};\n auto state_lower = ss_lower_->estimator.update(state_, input);\n auto state_upper = ss_upper_->estimator.update(state_, input);\n state_ = alpha_ * (state_upper - state_lower) + state_lower;\n s_->estimate.phi = state_(0, 0);\n s_->estimate.delta = state_(1, 0);\n s_->estimate.phi_dot = state_(2, 0);\n s_->estimate.delta_dot = state_(3, 0);\n}\n\nfloat GainSchedule::lqr_output() const\n{\n const float t0 = ss_lower_->lqr.update(state_)(0, 0);\n const float t1 = ss_upper_->lqr.update(state_)(0, 0);\n return alpha_ * (t1 - t0) + t0;\n}\n\nfloat GainSchedule::pi_output() const\n{\n vector_t x {{s_->yaw_rate_pi.x}};\n vector_t e {{s_->yaw_rate_pi.e}};\n const float t0 = ss_lower_->pi.update(x, e)(0, 0);\n const float t1 = ss_upper_->pi.update(x, e)(0, 0);\n return alpha_ * (t1 - t0) + t0;\n}\n\nfloat GainSchedule::compute_updated_torque(float torque_prev)\n{\n state_estimate(torque_prev);\n return lqr_output() + pi_output();\n}\n\n} \/\/ namespace control\nAlways update state estimate when called.#include \n#include \n\n#include \"gain_schedule.h\"\n#include \"MPU6050.h\"\n\nnamespace control {\n\nvector_t StateEstimator::update(const vector_t& x,\n const vector_t& u) const\n{\n return A * x + B * u;\n}\n\nvector_t LQRController::update(const vector_t& x) const\n{\n return C * x;\n}\n\nvector_t PIController::update(const vector_t& x,\n const vector_t& e) const\n{\n return Kp * x + Ki * e;\n}\n\nbool rt_controller_t::operator<(const rt_controller_t& rhs) const\n{\n return rate < rhs.rate;\n}\n\nGainSchedule::GainSchedule() : state_{{}}, pi_control_enabled_{false}\n{\n\n}\n\nfloat GainSchedule::rate() const\n{\n return rate_;\n}\n\nbool GainSchedule::set_sample(Sample& s)\n{\n s_ = &s;\n return set_rate(s.encoder.rear_wheel_rate);\n}\n\nvoid GainSchedule::set_state(const vector_t& state)\n{\n state_ = state;\n}\n\nbool GainSchedule::set_rate(float rate)\n{\n bool valid = true;\n rate_ = rate;\n\n r.rate = rate;\n auto it = std::upper_bound(schedule_.begin(), schedule_.end(), r);\n if (it == schedule_.begin() || it == schedule_.end()) {\n valid = false;\n if (it == schedule_.begin()) {\n s_->estimate.theta_R_dot_upper = it->rate;\n s_->estimate.theta_R_dot_lower = NAN;\n } else {\n s_->estimate.theta_R_dot_upper = NAN;\n s_->estimate.theta_R_dot_lower = (--it)->rate;\n }\n } else {\n valid = true;\n s_->estimate.theta_R_dot_upper = it->rate;\n ss_upper_ = const_cast(&(it->controller));\n s_->estimate.theta_R_dot_lower = (--it)->rate;\n ss_lower_ = const_cast(&(it->controller));\n\n alpha_ = (rate - s_->estimate.theta_R_dot_lower) \/\n (s_->estimate.theta_R_dot_upper - s_->estimate.theta_R_dot_lower);\n }\n\n return valid;\n}\n\nvoid GainSchedule::state_estimate(float torque_prev)\n{\n state_estimate_time_ = s_->loop_count;\n vector_t input {{torque_prev, s_->encoder.steer,\n hardware::MPU6050::phi_dot(*s_)}};\n auto state_lower = ss_lower_->estimator.update(state_, input);\n auto state_upper = ss_upper_->estimator.update(state_, input);\n state_ = alpha_ * (state_upper - state_lower) + state_lower;\n s_->estimate.phi = state_(0, 0);\n s_->estimate.delta = state_(1, 0);\n s_->estimate.phi_dot = state_(2, 0);\n s_->estimate.delta_dot = state_(3, 0);\n}\n\nfloat GainSchedule::lqr_output() const\n{\n const float t0 = ss_lower_->lqr.update(state_)(0, 0);\n const float t1 = ss_upper_->lqr.update(state_)(0, 0);\n return alpha_ * (t1 - t0) + t0;\n}\n\nfloat GainSchedule::pi_output() const\n{\n vector_t x {{s_->yaw_rate_pi.x}};\n vector_t e {{s_->yaw_rate_pi.e}};\n const float t0 = ss_lower_->pi.update(x, e)(0, 0);\n const float t1 = ss_upper_->pi.update(x, e)(0, 0);\n return alpha_ * (t1 - t0) + t0;\n}\n\nfloat GainSchedule::compute_updated_torque(float torque_prev)\n{\n state_estimate(torque_prev);\n return lqr_output() + pi_output();\n}\n\n} \/\/ namespace control\n<|endoftext|>"} {"text":"\/**\n * @file uart.cpp\n *\n * @brief Contains uart access functionality\n *\n * Example usage:\n * @code\n *\n * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n * uart0.Init(9600);\n *\n * @endcode\n *\/\n\n\n#include \n#include \n#include \n\n#include \"uart.h\"\n#include \"util\/ringbuffer.h\"\n\n\/**\n * @brief Used to access uart0 \n *\n * On atmega2561:\n * Pin2: RXD0 \n * Pin3: TXD0\n *\/\nUart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n\n\/**\n * @brief Used to access uart1\n *\n * On atmega2561:\n * Pin27: RXD0 \n * Pin28: TXD0\n *\/\nUart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);\n\n\/**\n * @brief Calculates the clock scale needed to run uart at the specified baud rate.\n *\n * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.\n * If not specified 9600 is used.\n *\/\nuint16_t Uart::BaudScale(uint16_t baudrate) \n{ \n return (((F_CPU \/ (baudrate * 16UL))) - 1); \n}\n\n\n\/**\n * @brief Initializes uart with specified baud rate.\n *\n * @param ubrr \n * @param ucsra \n * @param ucsrb \n * @param ucsrc \n * @param udr\n * \n * Example usage:\n * @code\n *\n * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n * Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n *\n * @endcode\n *\/\nUart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr)\n{\n _ubrr = ubrr;\n _ucsra = ucsra;\n _ucsrb = ucsrb;\n _ucsrc = ucsrc;\n _udr = udr;\n}\n\n\n\/**\n * @brief Initializes uart with specified baud rate.\n *\n * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.\n * If not specified 9600 is used.\n *\n * Example usage:\n * @code\n *\n * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n * uart0.Init(9600);\n *\n * @endcode\n *\/\nvoid Uart::Init(uint16_t baudrate)\n{\n \/\/ initializing uart to specified baud rate\n *_ubrr = BaudScale(baudrate); \n\n \/\/ setting 8 data bits, 1 stop bit, no parity\n *_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01));\n\n \/\/ enabling receiver and transmitter\n *_ucsrb = ((1 << RXEN0) | (1 << TXEN0));\n\n \/\/ enabling uart interrupts\n *_ucsrb |= ((1 << RXCIE0) | (1 << TXCIE0));\n}\n\n\n\/**\n * @brief Pushes byte to rx buffer. If buffer is full, nothing happens.\n *\n * @param byte Byte to push to buffer.\n *\/\nvoid _PushRx(Uart *uart, char byte) \n{ \n uart->_rx_buffer.Push(byte); \n}\n\n\nISR(USART0_RX_vect)\n{\n char rxbyte;\n\n \/\/ echo rx to tx\n rxbyte = UDR0;\n UDR0 = rxbyte;\n\n \/\/ pushing byte to rxbuff\n _PushRx(&uart0, rxbyte);\n}\nAdded loopback isr and tested for uart1\/**\n * @file uart.cpp\n *\n * @brief Contains uart access functionality\n *\n * Example usage:\n * @code\n *\n * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n * uart0.Init(9600);\n *\n * @endcode\n *\/\n\n\n#include \n#include \n#include \n\n#include \"uart.h\"\n#include \"util\/ringbuffer.h\"\n\n\/**\n * @brief Used to access uart0 \n *\n * On atmega2561:\n * Pin2: RXD0 \n * Pin3: TXD0\n *\/\nUart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n\n\/**\n * @brief Used to access uart1\n *\n * On atmega2561:\n * Pin27: RXD0 \n * Pin28: TXD0\n *\/\nUart uart1(&UBRR1, &UCSR1A, &UCSR1B, &UCSR1C, &UDR1);\n\n\/**\n * @brief Calculates the clock scale needed to run uart at the specified baud rate.\n *\n * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.\n * If not specified 9600 is used.\n *\/\nuint16_t Uart::BaudScale(uint16_t baudrate) \n{ \n return (((F_CPU \/ (baudrate * 16UL))) - 1); \n}\n\n\n\/**\n * @brief Initializes uart with specified baud rate.\n *\n * @param ubrr \n * @param ucsra \n * @param ucsrb \n * @param ucsrc \n * @param udr\n * \n * Example usage:\n * @code\n *\n * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n * Uart uart1(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n *\n * @endcode\n *\/\nUart::Uart(volatile uint16_t *ubrr, volatile uint8_t *ucsra, volatile uint8_t *ucsrb, volatile uint8_t *ucsrc, volatile uint8_t *udr)\n{\n _ubrr = ubrr;\n _ucsra = ucsra;\n _ucsrb = ucsrb;\n _ucsrc = ucsrc;\n _udr = udr;\n}\n\n\n\/**\n * @brief Initializes uart with specified baud rate.\n *\n * @param baudrate Typical values include 1200, 2400, 4800, 9600, 14400, 19200, 38400, 57600, 128000, 256000.\n * If not specified 9600 is used.\n *\n * Example usage:\n * @code\n *\n * Uart uart0(&UBRR0, &UCSR0A, &UCSR0B, &UCSR0C, &UDR0);\n * uart0.Init(9600);\n *\n * @endcode\n *\/\nvoid Uart::Init(uint16_t baudrate)\n{\n \/\/ initializing uart to specified baud rate\n *_ubrr = BaudScale(baudrate); \n\n \/\/ setting 8 data bits, 1 stop bit, no parity\n *_ucsrc = ((0 << USBS0) | (1 << UCSZ00) | (1 << UCSZ01));\n\n \/\/ enabling receiver and transmitter\n *_ucsrb = ((1 << RXEN0) | (1 << TXEN0));\n\n \/\/ enabling uart interrupts\n *_ucsrb |= ((1 << RXCIE0) | (1 << TXCIE0));\n}\n\n\n\/**\n * @brief Pushes byte to rx buffer. If buffer is full, nothing happens.\n *\n * @param byte Byte to push to buffer.\n *\/\nvoid _PushRx(Uart *uart, char byte) \n{ \n uart->_rx_buffer.Push(byte); \n}\n\n\nISR(USART0_RX_vect)\n{\n char rxbyte;\n\n \/\/ echo rx to tx\n rxbyte = UDR0;\n UDR0 = rxbyte;\n\n \/\/ pushing byte to rxbuff\n _PushRx(&uart0, rxbyte);\n}\n\nISR(USART1_RX_vect)\n{\n char rxbyte;\n\n \/\/ echo rx to tx\n rxbyte = UDR1;\n UDR1 = rxbyte;\n\n \/\/ pushing byte to rxbuff\n _PushRx(&uart1, rxbyte);\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2020 Dmitry Chapyshev \n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\/\/\n\n#include \"base\/audio\/audio_output_win.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/audio\/win\/audio_util_win.h\"\n#include \"base\/audio\/win\/scoped_mmcss_registration.h\"\n#include \"base\/threading\/simple_thread.h\"\n#include \"base\/win\/scoped_com_initializer.h\"\n\nnamespace base {\n\nnamespace {\n\nconst char* sessionStateToString(AudioSessionState state)\n{\n switch (state)\n {\n case AudioSessionStateActive:\n return \"Active\";\n case AudioSessionStateInactive:\n return \"Inactive\";\n case AudioSessionStateExpired:\n return \"Expired\";\n default:\n return \"Invalid\";\n }\n}\n\n} \/\/ namespace\n\nAudioOutputWin::AudioOutputWin(const NeedMoreDataCB& need_more_data_cb)\n : AudioOutput(need_more_data_cb)\n{\n \/\/ Create the event which the audio engine will signal each time a buffer becomes ready to be\n \/\/ processed by the client.\n audio_samples_event_.reset(CreateEventW(nullptr, false, false, nullptr));\n DCHECK(audio_samples_event_.isValid());\n\n \/\/ Event to be set in Stop() when rendering\/capturing shall stop.\n stop_event_.reset(CreateEventW(nullptr, false, false, nullptr));\n DCHECK(stop_event_.isValid());\n\n \/\/ Event to be set when it has been detected that an active device has been invalidated or the\n \/\/ stream format has changed.\n restart_event_.reset(CreateEventW(nullptr, false, false, nullptr));\n DCHECK(restart_event_.isValid());\n\n is_initialized_ = init();\n}\n\nAudioOutputWin::~AudioOutputWin()\n{\n stop();\n}\n\nbool AudioOutputWin::start()\n{\n if (!is_initialized_)\n return false;\n\n if (is_restarting_)\n {\n DCHECK(audio_thread_);\n }\n\n if (!fillRenderEndpointBufferWithSilence(audio_client_.Get(), audio_render_client_.Get()))\n {\n LOG(LS_WARNING) << \"Failed to prepare output endpoint with silence\";\n }\n\n num_frames_written_ = endpoint_buffer_size_frames_;\n\n if (!audio_thread_)\n {\n audio_thread_ = std::make_unique();\n audio_thread_->start(std::bind(&AudioOutputWin::threadRun, this));\n\n if (!audio_thread_->isRunning())\n {\n stopThread();\n LOG(LS_ERROR) << \"Failed to start audio thread\";\n return false;\n }\n }\n\n HRESULT hr = audio_client_->Start();\n if (FAILED(hr))\n {\n stopThread();\n LOG(LS_ERROR) << \"IAudioClient::Start failed: \" << SystemError(hr).toString();\n return false;\n }\n\n is_active_ = true;\n return true;\n}\n\nbool AudioOutputWin::stop()\n{\n if (!is_initialized_)\n return true;\n\n if (!is_active_)\n {\n DLOG(LS_WARNING) << \"No output stream is active\";\n releaseCOMObjects();\n is_initialized_ = false;\n return true;\n }\n\n \/\/ Stop audio streaming.\n HRESULT hr = audio_client_->Stop();\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::Stop failed: \" << SystemError(hr).toString();\n }\n\n \/\/ Stop and destroy the audio thread but only when a restart attempt is not ongoing.\n if (!is_restarting_)\n stopThread();\n\n hr = audio_client_->Reset();\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::Reset failed: \" << SystemError(hr).toString();\n }\n\n \/\/ Extra safety check to ensure that the buffers are cleared. If the buffers are not cleared\n \/\/ correctly, the next call to start() would fail with AUDCLNT_E_BUFFER_ERROR at\n \/\/ IAudioRenderClient::GetBuffer().\n UINT32 num_queued_frames = 0;\n audio_client_->GetCurrentPadding(&num_queued_frames);\n DCHECK_EQ(0u, num_queued_frames);\n\n \/\/ Release all allocated COM interfaces to allow for a restart without intermediate destruction.\n releaseCOMObjects();\n return true;\n}\n\nvoid AudioOutputWin::threadRun()\n{\n if (!isMMCSSSupported())\n {\n LOG(LS_ERROR) << \"MMCSS is not supported\";\n return;\n }\n\n ScopedMMCSSRegistration mmcss_registration(L\"Pro Audio\");\n win::ScopedCOMInitializer com_initializer(win::ScopedCOMInitializer::kMTA);\n\n DCHECK(mmcss_registration.isSucceeded());\n DCHECK(com_initializer.isSucceeded());\n DCHECK(stop_event_.isValid());\n DCHECK(audio_samples_event_.isValid());\n\n bool streaming = true;\n bool error = false;\n HANDLE wait_array[] = { stop_event_.get(), restart_event_.get(), audio_samples_event_.get() };\n\n \/\/ Keep streaming audio until the stop event or the stream-switch event\n \/\/ is signaled. An error event can also break the main thread loop.\n while (streaming && !error)\n {\n \/\/ Wait for a close-down event, stream-switch event or a new render event.\n DWORD wait_result = WaitForMultipleObjects(\n std::size(wait_array), wait_array, false, INFINITE);\n switch (wait_result)\n {\n case WAIT_OBJECT_0 + 0:\n \/\/ |stop_event_| has been set.\n streaming = false;\n break;\n case WAIT_OBJECT_0 + 1:\n \/\/ |restart_event_| has been set.\n error = !handleRestartEvent();\n break;\n case WAIT_OBJECT_0 + 2:\n \/\/ |audio_samples_event_| has been set.\n error = !handleDataRequest();\n break;\n default:\n error = true;\n break;\n }\n }\n\n if (streaming && error)\n {\n LOG(LS_ERROR) << \"WASAPI streaming failed\";\n \/\/ Stop audio streaming since something has gone wrong in our main thread loop. Note that,\n \/\/ we are still in a \"started\" state, hence a stop() call is required to join the thread\n \/\/ properly.\n HRESULT hr = audio_client_->Stop();\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::Stop failed: \" << SystemError(hr).toString();\n }\n }\n}\n\nbool AudioOutputWin::init()\n{\n Microsoft::WRL::ComPtr device(createDevice());\n if (!device.Get())\n return false;\n\n Microsoft::WRL::ComPtr audio_client = createClient(device.Get());\n if (!audio_client.Get())\n return false;\n\n \/\/ Define the output WAVEFORMATEXTENSIBLE format in |format_|.\n WAVEFORMATEXTENSIBLE format_extensible;\n memset(&format_extensible, 0, sizeof(format_extensible));\n\n WAVEFORMATEX& format = format_extensible.Format;\n format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;\n format.nChannels = kChannels;\n format.nSamplesPerSec = kSampleRate;\n format.wBitsPerSample = kBitsPerSample;\n format.nBlockAlign = (format.wBitsPerSample \/ 8) * format.nChannels;\n format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;\n format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);\n\n \/\/ Add the parts which are unique for the WAVE_FORMAT_EXTENSIBLE structure.\n format_extensible.Samples.wValidBitsPerSample = kBitsPerSample;\n format_extensible.dwChannelMask = KSAUDIO_SPEAKER_STEREO;\n format_extensible.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;\n\n if (!isFormatSupported(audio_client.Get(), AUDCLNT_SHAREMODE_SHARED, &format_extensible))\n return false;\n\n \/\/ Initialize the audio stream between the client and the device in shared mode using\n \/\/ event-driven buffer handling. Also, using 0 as requested buffer size results in a default\n \/\/ (minimum) endpoint buffer size.\n const REFERENCE_TIME requested_buffer_size = 0;\n if (!sharedModeInitialize(audio_client.Get(), &format_extensible, audio_samples_event_,\n requested_buffer_size, true, &endpoint_buffer_size_frames_))\n {\n return false;\n }\n\n \/\/ Create an IAudioRenderClient for an initialized IAudioClient. The IAudioRenderClient\n \/\/ interface enables us to write output data to a rendering endpoint buffer.\n Microsoft::WRL::ComPtr audio_render_client =\n createRenderClient(audio_client.Get());\n if (!audio_render_client.Get())\n return false;\n\n \/\/ Create an AudioSessionControl interface given the initialized client. The IAudioControl\n \/\/ interface enables a client to configure the control parameters for an audio session and to\n \/\/ monitor events in the session.\n Microsoft::WRL::ComPtr audio_session_control =\n createAudioSessionControl(audio_client.Get());\n if (!audio_session_control.Get())\n return false;\n\n \/\/ The Sndvol program displays volume and mute controls for sessions that are in the active and\n \/\/ inactive states.\n AudioSessionState state;\n if (FAILED(audio_session_control->GetState(&state)))\n return false;\n\n LOG(LS_INFO) << \"Audio session state: \" << sessionStateToString(state);\n\n \/\/ Register the client to receive notifications of session events, including changes in the\n \/\/ stream state.\n if (FAILED(audio_session_control->RegisterAudioSessionNotification(this)))\n {\n LOG(LS_ERROR) << \"IAudioSessionControl::RegisterAudioSessionNotification failed\";\n return false;\n }\n\n \/\/ Store valid COM interfaces.\n audio_client_ = audio_client;\n audio_render_client_ = audio_render_client;\n audio_session_control_ = audio_session_control;\n return true;\n}\n\nbool AudioOutputWin::handleDataRequest()\n{\n \/\/ Get the padding value which indicates the amount of valid unread data that the endpoint\n \/\/ buffer currently contains.\n UINT32 num_unread_frames = 0;\n HRESULT hr = audio_client_->GetCurrentPadding(&num_unread_frames);\n if (hr == AUDCLNT_E_DEVICE_INVALIDATED)\n {\n \/\/ Avoid breaking the thread loop implicitly by returning false and return true instead for\n \/\/ AUDCLNT_E_DEVICE_INVALIDATED even it is a valid error message. We will use notifications\n \/\/ about device changes instead to stop data callbacks and attempt to restart streaming.\n DLOG(LS_ERROR) << \"AUDCLNT_E_DEVICE_INVALIDATED\";\n return true;\n }\n\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::GetCurrentPadding failed: \" << SystemError(hr).toString();\n return false;\n }\n\n \/\/ Contains how much new data we can write to the buffer without the risk of overwriting\n \/\/ previously written data that the audio engine has not yet read from the buffer. I.e., it is\n \/\/ the maximum buffer size we can request when calling IAudioRenderClient::GetBuffer().\n UINT32 num_requested_frames = endpoint_buffer_size_frames_ - num_unread_frames;\n if (num_requested_frames == 0)\n {\n DLOG(LS_WARNING) << \"Audio thread is signaled but no new audio samples are needed\";\n return true;\n }\n\n \/\/ Request all available space in the rendering endpoint buffer into which the client can later\n \/\/ write an audio packet.\n uint8_t* audio_data;\n hr = audio_render_client_->GetBuffer(num_requested_frames, &audio_data);\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioRenderClient::GetBuffer failed: \" << SystemError(hr).toString();\n return false;\n }\n\n \/\/ Get audio data and write it to the allocated buffer in |audio_data|. The playout latency is\n \/\/ not updated for each callback.\n onDataRequest(reinterpret_cast(audio_data), num_requested_frames * kChannels);\n\n \/\/ Release the buffer space acquired in IAudioRenderClient::GetBuffer.\n hr = audio_render_client_->ReleaseBuffer(num_requested_frames, 0);\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioRenderClient::ReleaseBuffer failed: \"\n << SystemError(hr).toString();\n return false;\n }\n\n num_frames_written_ += num_requested_frames;\n return true;\n}\n\nbool AudioOutputWin::handleRestartEvent()\n{\n DCHECK(audio_thread_);\n DCHECK(is_restarting_);\n\n if (!is_initialized_ || !is_active_)\n return true;\n\n if (!stop())\n return false;\n\n if (!init())\n return false;\n\n if (!start())\n return false;\n\n return true;\n}\n\nvoid AudioOutputWin::stopThread()\n{\n DCHECK(!is_restarting_);\n\n if (audio_thread_)\n {\n if (audio_thread_->isRunning())\n {\n SetEvent(stop_event_);\n audio_thread_->stop();\n }\n\n audio_thread_.reset();\n\n \/\/ Ensure that we don't quit the main thread loop immediately next time start() is called.\n ResetEvent(stop_event_);\n ResetEvent(restart_event_);\n }\n}\n\nvoid AudioOutputWin::releaseCOMObjects()\n{\n if (audio_client_)\n audio_client_.Reset();\n\n if (audio_session_control_.Get())\n audio_session_control_.Reset();\n\n if (audio_render_client_.Get())\n audio_render_client_.Reset();\n}\n\nULONG AudioOutputWin::AddRef()\n{\n ULONG new_ref = InterlockedIncrement(&ref_count_);\n return new_ref;\n}\n\nULONG AudioOutputWin::Release()\n{\n ULONG new_ref = InterlockedDecrement(&ref_count_);\n return new_ref;\n}\n\nHRESULT AudioOutputWin::QueryInterface(REFIID iid, void** object)\n{\n if (object == nullptr)\n return E_POINTER;\n\n if (iid == IID_IUnknown || iid == __uuidof(IAudioSessionEvents))\n {\n *object = static_cast(this);\n return S_OK;\n };\n\n *object = nullptr;\n return E_NOINTERFACE;\n}\n\nHRESULT AudioOutputWin::OnStateChanged(AudioSessionState new_state)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnSessionDisconnected(AudioSessionDisconnectReason disconnect_reason)\n{\n if (is_restarting_)\n {\n DLOG(LS_WARNING) << \"Ignoring since restart is already active\";\n return S_OK;\n }\n\n \/\/ Internal test method which can be used in tests to emulate a restart signal. It simply sets\n \/\/ the same event which is normally triggered by session and device notifications. Hence, the\n \/\/ emulated restart sequence covers most parts of a real sequence expect the actual device\n \/\/ switch.\n if (disconnect_reason == DisconnectReasonDeviceRemoval ||\n disconnect_reason == DisconnectReasonFormatChanged)\n {\n is_restarting_ = true;\n SetEvent(restart_event_);\n }\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnDisplayNameChanged(LPCWSTR new_display_name, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnIconPathChanged(LPCWSTR new_icon_path, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnSimpleVolumeChanged(\n float new_simple_volume, BOOL new_mute, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnChannelVolumeChanged(\n DWORD channel_count, float new_channel_volumes[], DWORD changed_channel, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnGroupingParamChanged(LPCGUID new_grouping_param, LPCGUID event_context)\n{\n return S_OK;\n}\n\n} \/\/ namespace base\nSet priority for audio thread.\/\/\n\/\/ Aspia Project\n\/\/ Copyright (C) 2020 Dmitry Chapyshev \n\/\/\n\/\/ This program is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program. If not, see .\n\/\/\n\n#include \"base\/audio\/audio_output_win.h\"\n\n#include \"base\/logging.h\"\n#include \"base\/audio\/win\/audio_util_win.h\"\n#include \"base\/audio\/win\/scoped_mmcss_registration.h\"\n#include \"base\/threading\/simple_thread.h\"\n#include \"base\/win\/scoped_com_initializer.h\"\n\nnamespace base {\n\nnamespace {\n\nconst char* sessionStateToString(AudioSessionState state)\n{\n switch (state)\n {\n case AudioSessionStateActive:\n return \"Active\";\n case AudioSessionStateInactive:\n return \"Inactive\";\n case AudioSessionStateExpired:\n return \"Expired\";\n default:\n return \"Invalid\";\n }\n}\n\n} \/\/ namespace\n\nAudioOutputWin::AudioOutputWin(const NeedMoreDataCB& need_more_data_cb)\n : AudioOutput(need_more_data_cb)\n{\n \/\/ Create the event which the audio engine will signal each time a buffer becomes ready to be\n \/\/ processed by the client.\n audio_samples_event_.reset(CreateEventW(nullptr, false, false, nullptr));\n DCHECK(audio_samples_event_.isValid());\n\n \/\/ Event to be set in Stop() when rendering\/capturing shall stop.\n stop_event_.reset(CreateEventW(nullptr, false, false, nullptr));\n DCHECK(stop_event_.isValid());\n\n \/\/ Event to be set when it has been detected that an active device has been invalidated or the\n \/\/ stream format has changed.\n restart_event_.reset(CreateEventW(nullptr, false, false, nullptr));\n DCHECK(restart_event_.isValid());\n\n is_initialized_ = init();\n}\n\nAudioOutputWin::~AudioOutputWin()\n{\n stop();\n}\n\nbool AudioOutputWin::start()\n{\n if (!is_initialized_)\n return false;\n\n if (is_restarting_)\n {\n DCHECK(audio_thread_);\n }\n\n if (!fillRenderEndpointBufferWithSilence(audio_client_.Get(), audio_render_client_.Get()))\n {\n LOG(LS_WARNING) << \"Failed to prepare output endpoint with silence\";\n }\n\n num_frames_written_ = endpoint_buffer_size_frames_;\n\n if (!audio_thread_)\n {\n audio_thread_ = std::make_unique();\n audio_thread_->start(std::bind(&AudioOutputWin::threadRun, this));\n\n if (!audio_thread_->isRunning())\n {\n stopThread();\n LOG(LS_ERROR) << \"Failed to start audio thread\";\n return false;\n }\n }\n\n HRESULT hr = audio_client_->Start();\n if (FAILED(hr))\n {\n stopThread();\n LOG(LS_ERROR) << \"IAudioClient::Start failed: \" << SystemError(hr).toString();\n return false;\n }\n\n is_active_ = true;\n return true;\n}\n\nbool AudioOutputWin::stop()\n{\n if (!is_initialized_)\n return true;\n\n if (!is_active_)\n {\n DLOG(LS_WARNING) << \"No output stream is active\";\n releaseCOMObjects();\n is_initialized_ = false;\n return true;\n }\n\n \/\/ Stop audio streaming.\n HRESULT hr = audio_client_->Stop();\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::Stop failed: \" << SystemError(hr).toString();\n }\n\n \/\/ Stop and destroy the audio thread but only when a restart attempt is not ongoing.\n if (!is_restarting_)\n stopThread();\n\n hr = audio_client_->Reset();\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::Reset failed: \" << SystemError(hr).toString();\n }\n\n \/\/ Extra safety check to ensure that the buffers are cleared. If the buffers are not cleared\n \/\/ correctly, the next call to start() would fail with AUDCLNT_E_BUFFER_ERROR at\n \/\/ IAudioRenderClient::GetBuffer().\n UINT32 num_queued_frames = 0;\n audio_client_->GetCurrentPadding(&num_queued_frames);\n DCHECK_EQ(0u, num_queued_frames);\n\n \/\/ Release all allocated COM interfaces to allow for a restart without intermediate destruction.\n releaseCOMObjects();\n return true;\n}\n\nvoid AudioOutputWin::threadRun()\n{\n if (!isMMCSSSupported())\n {\n LOG(LS_ERROR) << \"MMCSS is not supported\";\n return;\n }\n\n SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);\n\n ScopedMMCSSRegistration mmcss_registration(L\"Pro Audio\");\n win::ScopedCOMInitializer com_initializer(win::ScopedCOMInitializer::kMTA);\n\n DCHECK(mmcss_registration.isSucceeded());\n DCHECK(com_initializer.isSucceeded());\n DCHECK(stop_event_.isValid());\n DCHECK(audio_samples_event_.isValid());\n\n bool streaming = true;\n bool error = false;\n HANDLE wait_array[] = { stop_event_.get(), restart_event_.get(), audio_samples_event_.get() };\n\n \/\/ Keep streaming audio until the stop event or the stream-switch event\n \/\/ is signaled. An error event can also break the main thread loop.\n while (streaming && !error)\n {\n \/\/ Wait for a close-down event, stream-switch event or a new render event.\n DWORD wait_result = WaitForMultipleObjects(\n std::size(wait_array), wait_array, false, INFINITE);\n switch (wait_result)\n {\n case WAIT_OBJECT_0 + 0:\n \/\/ |stop_event_| has been set.\n streaming = false;\n break;\n case WAIT_OBJECT_0 + 1:\n \/\/ |restart_event_| has been set.\n error = !handleRestartEvent();\n break;\n case WAIT_OBJECT_0 + 2:\n \/\/ |audio_samples_event_| has been set.\n error = !handleDataRequest();\n break;\n default:\n error = true;\n break;\n }\n }\n\n if (streaming && error)\n {\n LOG(LS_ERROR) << \"WASAPI streaming failed\";\n \/\/ Stop audio streaming since something has gone wrong in our main thread loop. Note that,\n \/\/ we are still in a \"started\" state, hence a stop() call is required to join the thread\n \/\/ properly.\n HRESULT hr = audio_client_->Stop();\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::Stop failed: \" << SystemError(hr).toString();\n }\n }\n}\n\nbool AudioOutputWin::init()\n{\n Microsoft::WRL::ComPtr device(createDevice());\n if (!device.Get())\n return false;\n\n Microsoft::WRL::ComPtr audio_client = createClient(device.Get());\n if (!audio_client.Get())\n return false;\n\n \/\/ Define the output WAVEFORMATEXTENSIBLE format in |format_|.\n WAVEFORMATEXTENSIBLE format_extensible;\n memset(&format_extensible, 0, sizeof(format_extensible));\n\n WAVEFORMATEX& format = format_extensible.Format;\n format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;\n format.nChannels = kChannels;\n format.nSamplesPerSec = kSampleRate;\n format.wBitsPerSample = kBitsPerSample;\n format.nBlockAlign = (format.wBitsPerSample \/ 8) * format.nChannels;\n format.nAvgBytesPerSec = format.nSamplesPerSec * format.nBlockAlign;\n format.cbSize = sizeof(WAVEFORMATEXTENSIBLE) - sizeof(WAVEFORMATEX);\n\n \/\/ Add the parts which are unique for the WAVE_FORMAT_EXTENSIBLE structure.\n format_extensible.Samples.wValidBitsPerSample = kBitsPerSample;\n format_extensible.dwChannelMask = KSAUDIO_SPEAKER_STEREO;\n format_extensible.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;\n\n if (!isFormatSupported(audio_client.Get(), AUDCLNT_SHAREMODE_SHARED, &format_extensible))\n return false;\n\n \/\/ Initialize the audio stream between the client and the device in shared mode using\n \/\/ event-driven buffer handling. Also, using 0 as requested buffer size results in a default\n \/\/ (minimum) endpoint buffer size.\n const REFERENCE_TIME requested_buffer_size = 0;\n if (!sharedModeInitialize(audio_client.Get(), &format_extensible, audio_samples_event_,\n requested_buffer_size, true, &endpoint_buffer_size_frames_))\n {\n return false;\n }\n\n \/\/ Create an IAudioRenderClient for an initialized IAudioClient. The IAudioRenderClient\n \/\/ interface enables us to write output data to a rendering endpoint buffer.\n Microsoft::WRL::ComPtr audio_render_client =\n createRenderClient(audio_client.Get());\n if (!audio_render_client.Get())\n return false;\n\n \/\/ Create an AudioSessionControl interface given the initialized client. The IAudioControl\n \/\/ interface enables a client to configure the control parameters for an audio session and to\n \/\/ monitor events in the session.\n Microsoft::WRL::ComPtr audio_session_control =\n createAudioSessionControl(audio_client.Get());\n if (!audio_session_control.Get())\n return false;\n\n \/\/ The Sndvol program displays volume and mute controls for sessions that are in the active and\n \/\/ inactive states.\n AudioSessionState state;\n if (FAILED(audio_session_control->GetState(&state)))\n return false;\n\n LOG(LS_INFO) << \"Audio session state: \" << sessionStateToString(state);\n\n \/\/ Register the client to receive notifications of session events, including changes in the\n \/\/ stream state.\n if (FAILED(audio_session_control->RegisterAudioSessionNotification(this)))\n {\n LOG(LS_ERROR) << \"IAudioSessionControl::RegisterAudioSessionNotification failed\";\n return false;\n }\n\n \/\/ Store valid COM interfaces.\n audio_client_ = audio_client;\n audio_render_client_ = audio_render_client;\n audio_session_control_ = audio_session_control;\n return true;\n}\n\nbool AudioOutputWin::handleDataRequest()\n{\n \/\/ Get the padding value which indicates the amount of valid unread data that the endpoint\n \/\/ buffer currently contains.\n UINT32 num_unread_frames = 0;\n HRESULT hr = audio_client_->GetCurrentPadding(&num_unread_frames);\n if (hr == AUDCLNT_E_DEVICE_INVALIDATED)\n {\n \/\/ Avoid breaking the thread loop implicitly by returning false and return true instead for\n \/\/ AUDCLNT_E_DEVICE_INVALIDATED even it is a valid error message. We will use notifications\n \/\/ about device changes instead to stop data callbacks and attempt to restart streaming.\n DLOG(LS_ERROR) << \"AUDCLNT_E_DEVICE_INVALIDATED\";\n return true;\n }\n\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioClient::GetCurrentPadding failed: \" << SystemError(hr).toString();\n return false;\n }\n\n \/\/ Contains how much new data we can write to the buffer without the risk of overwriting\n \/\/ previously written data that the audio engine has not yet read from the buffer. I.e., it is\n \/\/ the maximum buffer size we can request when calling IAudioRenderClient::GetBuffer().\n UINT32 num_requested_frames = endpoint_buffer_size_frames_ - num_unread_frames;\n if (num_requested_frames == 0)\n {\n DLOG(LS_WARNING) << \"Audio thread is signaled but no new audio samples are needed\";\n return true;\n }\n\n \/\/ Request all available space in the rendering endpoint buffer into which the client can later\n \/\/ write an audio packet.\n uint8_t* audio_data;\n hr = audio_render_client_->GetBuffer(num_requested_frames, &audio_data);\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioRenderClient::GetBuffer failed: \" << SystemError(hr).toString();\n return false;\n }\n\n \/\/ Get audio data and write it to the allocated buffer in |audio_data|. The playout latency is\n \/\/ not updated for each callback.\n onDataRequest(reinterpret_cast(audio_data), num_requested_frames * kChannels);\n\n \/\/ Release the buffer space acquired in IAudioRenderClient::GetBuffer.\n hr = audio_render_client_->ReleaseBuffer(num_requested_frames, 0);\n if (FAILED(hr))\n {\n LOG(LS_ERROR) << \"IAudioRenderClient::ReleaseBuffer failed: \"\n << SystemError(hr).toString();\n return false;\n }\n\n num_frames_written_ += num_requested_frames;\n return true;\n}\n\nbool AudioOutputWin::handleRestartEvent()\n{\n DCHECK(audio_thread_);\n DCHECK(is_restarting_);\n\n if (!is_initialized_ || !is_active_)\n return true;\n\n if (!stop())\n return false;\n\n if (!init())\n return false;\n\n if (!start())\n return false;\n\n return true;\n}\n\nvoid AudioOutputWin::stopThread()\n{\n DCHECK(!is_restarting_);\n\n if (audio_thread_)\n {\n if (audio_thread_->isRunning())\n {\n SetEvent(stop_event_);\n audio_thread_->stop();\n }\n\n audio_thread_.reset();\n\n \/\/ Ensure that we don't quit the main thread loop immediately next time start() is called.\n ResetEvent(stop_event_);\n ResetEvent(restart_event_);\n }\n}\n\nvoid AudioOutputWin::releaseCOMObjects()\n{\n if (audio_client_)\n audio_client_.Reset();\n\n if (audio_session_control_.Get())\n audio_session_control_.Reset();\n\n if (audio_render_client_.Get())\n audio_render_client_.Reset();\n}\n\nULONG AudioOutputWin::AddRef()\n{\n ULONG new_ref = InterlockedIncrement(&ref_count_);\n return new_ref;\n}\n\nULONG AudioOutputWin::Release()\n{\n ULONG new_ref = InterlockedDecrement(&ref_count_);\n return new_ref;\n}\n\nHRESULT AudioOutputWin::QueryInterface(REFIID iid, void** object)\n{\n if (object == nullptr)\n return E_POINTER;\n\n if (iid == IID_IUnknown || iid == __uuidof(IAudioSessionEvents))\n {\n *object = static_cast(this);\n return S_OK;\n };\n\n *object = nullptr;\n return E_NOINTERFACE;\n}\n\nHRESULT AudioOutputWin::OnStateChanged(AudioSessionState new_state)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnSessionDisconnected(AudioSessionDisconnectReason disconnect_reason)\n{\n if (is_restarting_)\n {\n DLOG(LS_WARNING) << \"Ignoring since restart is already active\";\n return S_OK;\n }\n\n \/\/ Internal test method which can be used in tests to emulate a restart signal. It simply sets\n \/\/ the same event which is normally triggered by session and device notifications. Hence, the\n \/\/ emulated restart sequence covers most parts of a real sequence expect the actual device\n \/\/ switch.\n if (disconnect_reason == DisconnectReasonDeviceRemoval ||\n disconnect_reason == DisconnectReasonFormatChanged)\n {\n is_restarting_ = true;\n SetEvent(restart_event_);\n }\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnDisplayNameChanged(LPCWSTR new_display_name, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnIconPathChanged(LPCWSTR new_icon_path, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnSimpleVolumeChanged(\n float new_simple_volume, BOOL new_mute, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnChannelVolumeChanged(\n DWORD channel_count, float new_channel_volumes[], DWORD changed_channel, LPCGUID event_context)\n{\n return S_OK;\n}\n\nHRESULT AudioOutputWin::OnGroupingParamChanged(LPCGUID new_grouping_param, LPCGUID event_context)\n{\n return S_OK;\n}\n\n} \/\/ namespace base\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: property.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: kz $ $Date: 2007-05-10 09:59:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_forms.hxx\"\n\n#ifndef FRM_STRINGS_HXX\n#include \"frm_strings.hxx\"\n#endif\n\n#ifndef _FRM_PROPERTY_HXX_\n#include \"property.hxx\"\n#endif\n\n#ifndef _FRM_PROPERTY_HRC_\n#include \"property.hrc\"\n#endif\n\n#ifndef _CPPUHELPER_QUERYINTERFACE_HXX_\n#include \n#endif\n\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYATTRIBUTE_HPP_\n#include \n#endif\n\n#include \n\n\/\/... namespace frm .......................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n\/\/==================================================================\n\/\/= PropertyInfoService\n\/\/==================================================================\nPropertyInfoService::PropertyMap PropertyInfoService::s_AllKnownProperties;\n\/\/------------------------------------------------------------------\nsal_Int32 PropertyInfoService::getPropertyId(const ::rtl::OUString& _rName)\n{\n initialize();\n\n PropertyAssignment aCompareName(_rName, -1);\n\n ::std::pair aPair = equal_range(\n s_AllKnownProperties.begin(),\n s_AllKnownProperties.end(),\n aCompareName,\n PropertyAssignmentNameCompareLess());\n\n sal_Int32 nHandle = -1;\n if (aPair.first != aPair.second)\n { \/\/ we found something _and_ we have an identity\n nHandle = aPair.first->nHandle;\n }\n\n return nHandle;\n}\n\n\/\/------------------------------------------------------------------\nsal_Int32 ConcreteInfoService::getPreferedPropertyId(const ::rtl::OUString& _rName)\n{\n return PropertyInfoService::getPropertyId(_rName);\n}\n\n\/\/------------------------------------------------------------------\n#define ADD_PROP_ASSIGNMENT(varname) \\\n s_AllKnownProperties.push_back(PropertyAssignment(PROPERTY_##varname, PROPERTY_ID_##varname))\n\/\/..................................................................\nvoid PropertyInfoService::initialize()\n{\n if (!s_AllKnownProperties.empty())\n return;\n\n s_AllKnownProperties.reserve(220);\n\n ADD_PROP_ASSIGNMENT(NAME);\n ADD_PROP_ASSIGNMENT(TAG);\n ADD_PROP_ASSIGNMENT(TABINDEX);\n ADD_PROP_ASSIGNMENT(CLASSID);\n ADD_PROP_ASSIGNMENT(ALIGN);\n ADD_PROP_ASSIGNMENT(FETCHSIZE);\n ADD_PROP_ASSIGNMENT(VALUE);\n ADD_PROP_ASSIGNMENT(VALUEMIN);\n ADD_PROP_ASSIGNMENT(VALUEMAX);\n ADD_PROP_ASSIGNMENT(VALUESTEP);\n ADD_PROP_ASSIGNMENT(TEXT);\n ADD_PROP_ASSIGNMENT(LABEL);\n ADD_PROP_ASSIGNMENT(NAVIGATION);\n ADD_PROP_ASSIGNMENT(CYCLE);\n ADD_PROP_ASSIGNMENT(CONTROLSOURCE);\n ADD_PROP_ASSIGNMENT(ENABLED);\n ADD_PROP_ASSIGNMENT(SPIN);\n ADD_PROP_ASSIGNMENT(READONLY);\n ADD_PROP_ASSIGNMENT(FILTER);\n ADD_PROP_ASSIGNMENT(WIDTH);\n ADD_PROP_ASSIGNMENT(SEARCHABLE);\n ADD_PROP_ASSIGNMENT(MULTILINE);\n ADD_PROP_ASSIGNMENT(TARGET_URL);\n ADD_PROP_ASSIGNMENT(DEFAULTCONTROL);\n ADD_PROP_ASSIGNMENT(MAXTEXTLEN);\n ADD_PROP_ASSIGNMENT(SIZE);\n ADD_PROP_ASSIGNMENT(DATE);\n ADD_PROP_ASSIGNMENT(TIME);\n ADD_PROP_ASSIGNMENT(STATE);\n ADD_PROP_ASSIGNMENT(TRISTATE);\n ADD_PROP_ASSIGNMENT(HIDDEN_VALUE);\n ADD_PROP_ASSIGNMENT(TARGET_FRAME);\n ADD_PROP_ASSIGNMENT(BUTTONTYPE);\n ADD_PROP_ASSIGNMENT(STRINGITEMLIST);\n ADD_PROP_ASSIGNMENT(DEFAULT_TEXT);\n ADD_PROP_ASSIGNMENT(DEFAULTCHECKED);\n ADD_PROP_ASSIGNMENT(DEFAULT_DATE);\n ADD_PROP_ASSIGNMENT(DEFAULT_TIME);\n ADD_PROP_ASSIGNMENT(DEFAULT_VALUE);\n ADD_PROP_ASSIGNMENT(FORMATKEY);\n ADD_PROP_ASSIGNMENT(FORMATSSUPPLIER);\n ADD_PROP_ASSIGNMENT(SUBMIT_ACTION);\n ADD_PROP_ASSIGNMENT(SUBMIT_TARGET);\n ADD_PROP_ASSIGNMENT(SUBMIT_METHOD);\n ADD_PROP_ASSIGNMENT(SUBMIT_ENCODING);\n ADD_PROP_ASSIGNMENT(IMAGE_URL);\n ADD_PROP_ASSIGNMENT(EMPTY_IS_NULL);\n ADD_PROP_ASSIGNMENT(LISTSOURCETYPE);\n ADD_PROP_ASSIGNMENT(LISTSOURCE);\n ADD_PROP_ASSIGNMENT(SELECT_SEQ);\n ADD_PROP_ASSIGNMENT(VALUE_SEQ);\n ADD_PROP_ASSIGNMENT(DEFAULT_SELECT_SEQ);\n ADD_PROP_ASSIGNMENT(MULTISELECTION);\n ADD_PROP_ASSIGNMENT(DECIMAL_ACCURACY);\n ADD_PROP_ASSIGNMENT(EDITMASK);\n ADD_PROP_ASSIGNMENT(ISREADONLY);\n ADD_PROP_ASSIGNMENT(FIELDTYPE);\n ADD_PROP_ASSIGNMENT(DECIMALS);\n ADD_PROP_ASSIGNMENT(REFVALUE);\n ADD_PROP_ASSIGNMENT(STRICTFORMAT);\n ADD_PROP_ASSIGNMENT(DATASOURCE);\n ADD_PROP_ASSIGNMENT(ALLOWADDITIONS);\n ADD_PROP_ASSIGNMENT(ALLOWEDITS);\n ADD_PROP_ASSIGNMENT(ALLOWDELETIONS);\n ADD_PROP_ASSIGNMENT(MASTERFIELDS);\n ADD_PROP_ASSIGNMENT(ISPASSTHROUGH);\n ADD_PROP_ASSIGNMENT(QUERY);\n ADD_PROP_ASSIGNMENT(LITERALMASK);\n ADD_PROP_ASSIGNMENT(SHOWTHOUSANDSEP);\n ADD_PROP_ASSIGNMENT(CURRENCYSYMBOL);\n ADD_PROP_ASSIGNMENT(DATEFORMAT);\n ADD_PROP_ASSIGNMENT(DATEMIN);\n ADD_PROP_ASSIGNMENT(DATEMAX);\n ADD_PROP_ASSIGNMENT(DATE_SHOW_CENTURY);\n ADD_PROP_ASSIGNMENT(TIMEFORMAT);\n ADD_PROP_ASSIGNMENT(TIMEMIN);\n ADD_PROP_ASSIGNMENT(TIMEMAX);\n ADD_PROP_ASSIGNMENT(LINECOUNT);\n ADD_PROP_ASSIGNMENT(BOUNDCOLUMN);\n ADD_PROP_ASSIGNMENT(HASNAVIGATION);\n ADD_PROP_ASSIGNMENT(FONT);\n ADD_PROP_ASSIGNMENT(BACKGROUNDCOLOR);\n ADD_PROP_ASSIGNMENT(FILLCOLOR);\n ADD_PROP_ASSIGNMENT(TEXTCOLOR);\n ADD_PROP_ASSIGNMENT(LINECOLOR);\n ADD_PROP_ASSIGNMENT(BORDER);\n ADD_PROP_ASSIGNMENT(DROPDOWN);\n ADD_PROP_ASSIGNMENT(HSCROLL);\n ADD_PROP_ASSIGNMENT(VSCROLL);\n ADD_PROP_ASSIGNMENT(TABSTOP);\n ADD_PROP_ASSIGNMENT(AUTOCOMPLETE);\n ADD_PROP_ASSIGNMENT(HARDLINEBREAKS);\n ADD_PROP_ASSIGNMENT(PRINTABLE);\n ADD_PROP_ASSIGNMENT(ECHO_CHAR);\n ADD_PROP_ASSIGNMENT(ROWHEIGHT);\n ADD_PROP_ASSIGNMENT(HELPTEXT);\n ADD_PROP_ASSIGNMENT(FONT_NAME);\n ADD_PROP_ASSIGNMENT(FONT_STYLENAME);\n ADD_PROP_ASSIGNMENT(FONT_FAMILY);\n ADD_PROP_ASSIGNMENT(FONT_CHARSET);\n ADD_PROP_ASSIGNMENT(FONT_HEIGHT);\n ADD_PROP_ASSIGNMENT(FONT_WEIGHT);\n ADD_PROP_ASSIGNMENT(FONT_SLANT);\n ADD_PROP_ASSIGNMENT(FONT_UNDERLINE);\n ADD_PROP_ASSIGNMENT(FONT_WORDLINEMODE);\n ADD_PROP_ASSIGNMENT(FONT_STRIKEOUT);\n ADD_PROP_ASSIGNMENT(TEXTLINECOLOR);\n ADD_PROP_ASSIGNMENT(FONTEMPHASISMARK);\n ADD_PROP_ASSIGNMENT(FONTRELIEF);\n ADD_PROP_ASSIGNMENT(HELPURL);\n ADD_PROP_ASSIGNMENT(RECORDMARKER);\n ADD_PROP_ASSIGNMENT(BOUNDFIELD);\n ADD_PROP_ASSIGNMENT(TREATASNUMERIC);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_VALUE);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_DEFAULT);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_MIN);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_MAX);\n ADD_PROP_ASSIGNMENT(HIDDEN);\n ADD_PROP_ASSIGNMENT(FILTERPROPOSAL);\n ADD_PROP_ASSIGNMENT(FIELDSOURCE);\n ADD_PROP_ASSIGNMENT(TABLENAME);\n ADD_PROP_ASSIGNMENT(CONTROLLABEL);\n ADD_PROP_ASSIGNMENT(CURRSYM_POSITION);\n ADD_PROP_ASSIGNMENT(CURSORCOLOR);\n ADD_PROP_ASSIGNMENT(ALWAYSSHOWCURSOR);\n ADD_PROP_ASSIGNMENT(DISPLAYSYNCHRON);\n ADD_PROP_ASSIGNMENT(ISMODIFIED);\n ADD_PROP_ASSIGNMENT(ISNEW);\n ADD_PROP_ASSIGNMENT(PRIVILEGES);\n ADD_PROP_ASSIGNMENT(DETAILFIELDS);\n ADD_PROP_ASSIGNMENT(COMMAND);\n ADD_PROP_ASSIGNMENT(COMMANDTYPE);\n ADD_PROP_ASSIGNMENT(RESULTSET_CONCURRENCY);\n ADD_PROP_ASSIGNMENT(INSERTONLY);\n ADD_PROP_ASSIGNMENT(RESULTSET_TYPE);\n ADD_PROP_ASSIGNMENT(ESCAPE_PROCESSING);\n ADD_PROP_ASSIGNMENT(APPLYFILTER);\n ADD_PROP_ASSIGNMENT(ISNULLABLE);\n ADD_PROP_ASSIGNMENT(ACTIVECOMMAND);\n ADD_PROP_ASSIGNMENT(ISCURRENCY);\n ADD_PROP_ASSIGNMENT(URL);\n ADD_PROP_ASSIGNMENT(TITLE);\n ADD_PROP_ASSIGNMENT(ACTIVE_CONNECTION);\n ADD_PROP_ASSIGNMENT(SCALE);\n ADD_PROP_ASSIGNMENT(SORT);\n ADD_PROP_ASSIGNMENT(PERSISTENCE_MAXTEXTLENGTH);\n ADD_PROP_ASSIGNMENT(SCROLL_VALUE);\n ADD_PROP_ASSIGNMENT(SPIN_VALUE);\n ADD_PROP_ASSIGNMENT(DEFAULT_SCROLL_VALUE);\n ADD_PROP_ASSIGNMENT(DEFAULT_SPIN_VALUE);\n\n \/\/ now sort the array by name\n\n std::sort(\n s_AllKnownProperties.begin(),\n s_AllKnownProperties.end(),\n PropertyAssignmentNameCompareLess()\n );\n}\n\n\/\/.........................................................................\n}\n\/\/... namespace frm .......................................................\n\nINTEGRATION: CWS changefileheader (1.17.78); FILE MERGED 2008\/04\/01 15:16:37 thb 1.17.78.3: #i85898# Stripping all external header guards 2008\/04\/01 12:30:29 thb 1.17.78.2: #i85898# Stripping all external header guards 2008\/03\/31 13:11:40 rt 1.17.78.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: property.cxx,v $\n * $Revision: 1.18 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_forms.hxx\"\n#include \"frm_strings.hxx\"\n#include \"property.hxx\"\n\n#ifndef _FRM_PROPERTY_HRC_\n#include \"property.hrc\"\n#endif\n#include \n#include \n#include \n\n#include \n\n\/\/... namespace frm .......................................................\nnamespace frm\n{\n\/\/.........................................................................\n\n\/\/==================================================================\n\/\/= PropertyInfoService\n\/\/==================================================================\nPropertyInfoService::PropertyMap PropertyInfoService::s_AllKnownProperties;\n\/\/------------------------------------------------------------------\nsal_Int32 PropertyInfoService::getPropertyId(const ::rtl::OUString& _rName)\n{\n initialize();\n\n PropertyAssignment aCompareName(_rName, -1);\n\n ::std::pair aPair = equal_range(\n s_AllKnownProperties.begin(),\n s_AllKnownProperties.end(),\n aCompareName,\n PropertyAssignmentNameCompareLess());\n\n sal_Int32 nHandle = -1;\n if (aPair.first != aPair.second)\n { \/\/ we found something _and_ we have an identity\n nHandle = aPair.first->nHandle;\n }\n\n return nHandle;\n}\n\n\/\/------------------------------------------------------------------\nsal_Int32 ConcreteInfoService::getPreferedPropertyId(const ::rtl::OUString& _rName)\n{\n return PropertyInfoService::getPropertyId(_rName);\n}\n\n\/\/------------------------------------------------------------------\n#define ADD_PROP_ASSIGNMENT(varname) \\\n s_AllKnownProperties.push_back(PropertyAssignment(PROPERTY_##varname, PROPERTY_ID_##varname))\n\/\/..................................................................\nvoid PropertyInfoService::initialize()\n{\n if (!s_AllKnownProperties.empty())\n return;\n\n s_AllKnownProperties.reserve(220);\n\n ADD_PROP_ASSIGNMENT(NAME);\n ADD_PROP_ASSIGNMENT(TAG);\n ADD_PROP_ASSIGNMENT(TABINDEX);\n ADD_PROP_ASSIGNMENT(CLASSID);\n ADD_PROP_ASSIGNMENT(ALIGN);\n ADD_PROP_ASSIGNMENT(FETCHSIZE);\n ADD_PROP_ASSIGNMENT(VALUE);\n ADD_PROP_ASSIGNMENT(VALUEMIN);\n ADD_PROP_ASSIGNMENT(VALUEMAX);\n ADD_PROP_ASSIGNMENT(VALUESTEP);\n ADD_PROP_ASSIGNMENT(TEXT);\n ADD_PROP_ASSIGNMENT(LABEL);\n ADD_PROP_ASSIGNMENT(NAVIGATION);\n ADD_PROP_ASSIGNMENT(CYCLE);\n ADD_PROP_ASSIGNMENT(CONTROLSOURCE);\n ADD_PROP_ASSIGNMENT(ENABLED);\n ADD_PROP_ASSIGNMENT(SPIN);\n ADD_PROP_ASSIGNMENT(READONLY);\n ADD_PROP_ASSIGNMENT(FILTER);\n ADD_PROP_ASSIGNMENT(WIDTH);\n ADD_PROP_ASSIGNMENT(SEARCHABLE);\n ADD_PROP_ASSIGNMENT(MULTILINE);\n ADD_PROP_ASSIGNMENT(TARGET_URL);\n ADD_PROP_ASSIGNMENT(DEFAULTCONTROL);\n ADD_PROP_ASSIGNMENT(MAXTEXTLEN);\n ADD_PROP_ASSIGNMENT(SIZE);\n ADD_PROP_ASSIGNMENT(DATE);\n ADD_PROP_ASSIGNMENT(TIME);\n ADD_PROP_ASSIGNMENT(STATE);\n ADD_PROP_ASSIGNMENT(TRISTATE);\n ADD_PROP_ASSIGNMENT(HIDDEN_VALUE);\n ADD_PROP_ASSIGNMENT(TARGET_FRAME);\n ADD_PROP_ASSIGNMENT(BUTTONTYPE);\n ADD_PROP_ASSIGNMENT(STRINGITEMLIST);\n ADD_PROP_ASSIGNMENT(DEFAULT_TEXT);\n ADD_PROP_ASSIGNMENT(DEFAULTCHECKED);\n ADD_PROP_ASSIGNMENT(DEFAULT_DATE);\n ADD_PROP_ASSIGNMENT(DEFAULT_TIME);\n ADD_PROP_ASSIGNMENT(DEFAULT_VALUE);\n ADD_PROP_ASSIGNMENT(FORMATKEY);\n ADD_PROP_ASSIGNMENT(FORMATSSUPPLIER);\n ADD_PROP_ASSIGNMENT(SUBMIT_ACTION);\n ADD_PROP_ASSIGNMENT(SUBMIT_TARGET);\n ADD_PROP_ASSIGNMENT(SUBMIT_METHOD);\n ADD_PROP_ASSIGNMENT(SUBMIT_ENCODING);\n ADD_PROP_ASSIGNMENT(IMAGE_URL);\n ADD_PROP_ASSIGNMENT(EMPTY_IS_NULL);\n ADD_PROP_ASSIGNMENT(LISTSOURCETYPE);\n ADD_PROP_ASSIGNMENT(LISTSOURCE);\n ADD_PROP_ASSIGNMENT(SELECT_SEQ);\n ADD_PROP_ASSIGNMENT(VALUE_SEQ);\n ADD_PROP_ASSIGNMENT(DEFAULT_SELECT_SEQ);\n ADD_PROP_ASSIGNMENT(MULTISELECTION);\n ADD_PROP_ASSIGNMENT(DECIMAL_ACCURACY);\n ADD_PROP_ASSIGNMENT(EDITMASK);\n ADD_PROP_ASSIGNMENT(ISREADONLY);\n ADD_PROP_ASSIGNMENT(FIELDTYPE);\n ADD_PROP_ASSIGNMENT(DECIMALS);\n ADD_PROP_ASSIGNMENT(REFVALUE);\n ADD_PROP_ASSIGNMENT(STRICTFORMAT);\n ADD_PROP_ASSIGNMENT(DATASOURCE);\n ADD_PROP_ASSIGNMENT(ALLOWADDITIONS);\n ADD_PROP_ASSIGNMENT(ALLOWEDITS);\n ADD_PROP_ASSIGNMENT(ALLOWDELETIONS);\n ADD_PROP_ASSIGNMENT(MASTERFIELDS);\n ADD_PROP_ASSIGNMENT(ISPASSTHROUGH);\n ADD_PROP_ASSIGNMENT(QUERY);\n ADD_PROP_ASSIGNMENT(LITERALMASK);\n ADD_PROP_ASSIGNMENT(SHOWTHOUSANDSEP);\n ADD_PROP_ASSIGNMENT(CURRENCYSYMBOL);\n ADD_PROP_ASSIGNMENT(DATEFORMAT);\n ADD_PROP_ASSIGNMENT(DATEMIN);\n ADD_PROP_ASSIGNMENT(DATEMAX);\n ADD_PROP_ASSIGNMENT(DATE_SHOW_CENTURY);\n ADD_PROP_ASSIGNMENT(TIMEFORMAT);\n ADD_PROP_ASSIGNMENT(TIMEMIN);\n ADD_PROP_ASSIGNMENT(TIMEMAX);\n ADD_PROP_ASSIGNMENT(LINECOUNT);\n ADD_PROP_ASSIGNMENT(BOUNDCOLUMN);\n ADD_PROP_ASSIGNMENT(HASNAVIGATION);\n ADD_PROP_ASSIGNMENT(FONT);\n ADD_PROP_ASSIGNMENT(BACKGROUNDCOLOR);\n ADD_PROP_ASSIGNMENT(FILLCOLOR);\n ADD_PROP_ASSIGNMENT(TEXTCOLOR);\n ADD_PROP_ASSIGNMENT(LINECOLOR);\n ADD_PROP_ASSIGNMENT(BORDER);\n ADD_PROP_ASSIGNMENT(DROPDOWN);\n ADD_PROP_ASSIGNMENT(HSCROLL);\n ADD_PROP_ASSIGNMENT(VSCROLL);\n ADD_PROP_ASSIGNMENT(TABSTOP);\n ADD_PROP_ASSIGNMENT(AUTOCOMPLETE);\n ADD_PROP_ASSIGNMENT(HARDLINEBREAKS);\n ADD_PROP_ASSIGNMENT(PRINTABLE);\n ADD_PROP_ASSIGNMENT(ECHO_CHAR);\n ADD_PROP_ASSIGNMENT(ROWHEIGHT);\n ADD_PROP_ASSIGNMENT(HELPTEXT);\n ADD_PROP_ASSIGNMENT(FONT_NAME);\n ADD_PROP_ASSIGNMENT(FONT_STYLENAME);\n ADD_PROP_ASSIGNMENT(FONT_FAMILY);\n ADD_PROP_ASSIGNMENT(FONT_CHARSET);\n ADD_PROP_ASSIGNMENT(FONT_HEIGHT);\n ADD_PROP_ASSIGNMENT(FONT_WEIGHT);\n ADD_PROP_ASSIGNMENT(FONT_SLANT);\n ADD_PROP_ASSIGNMENT(FONT_UNDERLINE);\n ADD_PROP_ASSIGNMENT(FONT_WORDLINEMODE);\n ADD_PROP_ASSIGNMENT(FONT_STRIKEOUT);\n ADD_PROP_ASSIGNMENT(TEXTLINECOLOR);\n ADD_PROP_ASSIGNMENT(FONTEMPHASISMARK);\n ADD_PROP_ASSIGNMENT(FONTRELIEF);\n ADD_PROP_ASSIGNMENT(HELPURL);\n ADD_PROP_ASSIGNMENT(RECORDMARKER);\n ADD_PROP_ASSIGNMENT(BOUNDFIELD);\n ADD_PROP_ASSIGNMENT(TREATASNUMERIC);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_VALUE);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_DEFAULT);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_MIN);\n ADD_PROP_ASSIGNMENT(EFFECTIVE_MAX);\n ADD_PROP_ASSIGNMENT(HIDDEN);\n ADD_PROP_ASSIGNMENT(FILTERPROPOSAL);\n ADD_PROP_ASSIGNMENT(FIELDSOURCE);\n ADD_PROP_ASSIGNMENT(TABLENAME);\n ADD_PROP_ASSIGNMENT(CONTROLLABEL);\n ADD_PROP_ASSIGNMENT(CURRSYM_POSITION);\n ADD_PROP_ASSIGNMENT(CURSORCOLOR);\n ADD_PROP_ASSIGNMENT(ALWAYSSHOWCURSOR);\n ADD_PROP_ASSIGNMENT(DISPLAYSYNCHRON);\n ADD_PROP_ASSIGNMENT(ISMODIFIED);\n ADD_PROP_ASSIGNMENT(ISNEW);\n ADD_PROP_ASSIGNMENT(PRIVILEGES);\n ADD_PROP_ASSIGNMENT(DETAILFIELDS);\n ADD_PROP_ASSIGNMENT(COMMAND);\n ADD_PROP_ASSIGNMENT(COMMANDTYPE);\n ADD_PROP_ASSIGNMENT(RESULTSET_CONCURRENCY);\n ADD_PROP_ASSIGNMENT(INSERTONLY);\n ADD_PROP_ASSIGNMENT(RESULTSET_TYPE);\n ADD_PROP_ASSIGNMENT(ESCAPE_PROCESSING);\n ADD_PROP_ASSIGNMENT(APPLYFILTER);\n ADD_PROP_ASSIGNMENT(ISNULLABLE);\n ADD_PROP_ASSIGNMENT(ACTIVECOMMAND);\n ADD_PROP_ASSIGNMENT(ISCURRENCY);\n ADD_PROP_ASSIGNMENT(URL);\n ADD_PROP_ASSIGNMENT(TITLE);\n ADD_PROP_ASSIGNMENT(ACTIVE_CONNECTION);\n ADD_PROP_ASSIGNMENT(SCALE);\n ADD_PROP_ASSIGNMENT(SORT);\n ADD_PROP_ASSIGNMENT(PERSISTENCE_MAXTEXTLENGTH);\n ADD_PROP_ASSIGNMENT(SCROLL_VALUE);\n ADD_PROP_ASSIGNMENT(SPIN_VALUE);\n ADD_PROP_ASSIGNMENT(DEFAULT_SCROLL_VALUE);\n ADD_PROP_ASSIGNMENT(DEFAULT_SPIN_VALUE);\n\n \/\/ now sort the array by name\n\n std::sort(\n s_AllKnownProperties.begin(),\n s_AllKnownProperties.end(),\n PropertyAssignmentNameCompareLess()\n );\n}\n\n\/\/.........................................................................\n}\n\/\/... namespace frm .......................................................\n\n<|endoftext|>"} {"text":"\/*\n * Modularity.cpp\n *\n * Created on: 10.12.2012\n * Author: cls\n *\/\n\n#include \"Modularity.h\"\n\n\n\nnamespace EnsembleClustering {\n\n\nModularity::Modularity() : QualityMeasure() {\n}\n\nModularity::~Modularity() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\ndouble Modularity::getQuality(const Clustering& zeta, Graph& G) {\n\tassert (G.numberOfNodes() <= zeta.numberOfNodes());\n\n\tDEBUG(\"m = \" << G.numberOfEdges());\n\tDEBUG(\"l = \" << G.numberOfSelfLoops());\n\n\tCoverage coverage;\n\tdouble cov = coverage.getQuality(zeta, G); \/\/ deprecated: intraEdgeWeightSum \/ totalEdgeWeight;\n\tDEBUG(\"coverage = \" << cov);\n\tdouble expCov; \/\/ term $\\frac{ \\sum_{C \\in \\zeta}( \\sum_{v \\in C} \\omega(v) )^2 }{4( \\sum_{e \\in E} \\omega(e) )^2 }$\n\tdouble modularity; \t\/\/ mod = coverage - expected coverage\n\tdouble totalEdgeWeight = G.totalEdgeWeight(); \/\/ add edge weight\n\tDEBUG(\"total edge weight: \" << totalEdgeWeight)\n\n\n\tif (totalEdgeWeight == 0.0) {\n\t\tERROR(\"G: m=\" << G.numberOfEdges() << \"n=\" << G.numberOfNodes());\n\t\tthrow std::invalid_argument(\"Modularity is undefined for graphs without edges (including self-loops).\");\n\t}\n\n\tIndexMap incidentWeightSum(zeta.upperBound(), 0.0);\t\/\/!< cluster -> sum of the weights of incident edges for all nodes\n\n\t\/\/ compute volume of each cluster\n\tG.forNodes([&](node v){\n\t\t\/\/ add to cluster weight\n\t\tcluster c = zeta[v];\n\t\tassert (zeta.lowerBound() <= c);\n\t\tassert (c < zeta.upperBound());\n\t\tincidentWeightSum[c] += G.weightedDegree(v) + G.weight(v,v); \/\/ account for self-loops a second time\n\t});\n\n\t\/\/ compute sum of squared cluster volumes and divide by squared graph volume\n\t\/\/ double totalIncidentWeight = 0.0; \t\/\/!< term $\\sum_{C \\in \\zeta}( \\sum_{v \\in C} \\omega(v) )^2 $\n\texpCov = 0.0;\n\/\/\tdouble divisor = 4 * totalEdgeWeight * totalEdgeWeight;\n\/\/\tassert (divisor != 0);\t\/\/ do not divide by 0\n\n\t#pragma omp parallel for reduction(+:expCov)\n\tfor (cluster c = zeta.lowerBound(); c < zeta.upperBound(); ++c) {\n\t\texpCov += ((incidentWeightSum[c] \/ totalEdgeWeight) * (incidentWeightSum[c] \/ totalEdgeWeight )) \/ 4;\t\/\/ squared\n\t}\n\n\tDEBUG(\"expected coverage: \" << expCov);\n\n\tDEBUG(\"expected coverage: \" << expCov);\n\n\t\/\/ assert ranges of coverage\n\tassert(cov <= 1.0);\n\tassert(cov >= 0.0);\n\tassert(expCov <= 1.0);\n\tassert(expCov >= 0.0);\n\n\tmodularity = cov - expCov;\n\n\tassert(! std::isnan(modularity));\t\/\/ do not return NaN\n\t\/\/ do not return anything not in the range of modularity values\n\tassert(modularity >= -0.5);\n\tassert(modularity <= 1);\n\treturn modularity;\n}\n\n} \/* namespace EnsembleClustering *\/\ndebug statements in modularity\/*\n * Modularity.cpp\n *\n * Created on: 10.12.2012\n * Author: cls\n *\/\n\n#include \"Modularity.h\"\n\n\n\nnamespace EnsembleClustering {\n\n\nModularity::Modularity() : QualityMeasure() {\n}\n\nModularity::~Modularity() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\n\ndouble Modularity::getQuality(const Clustering& zeta, Graph& G) {\n\tassert (G.numberOfNodes() <= zeta.numberOfNodes());\n\n\tDEBUG(\"m = \" << G.numberOfEdges());\n\tDEBUG(\"l = \" << G.numberOfSelfLoops());\n\n\tCoverage coverage;\n\tdouble cov = coverage.getQuality(zeta, G); \/\/ deprecated: intraEdgeWeightSum \/ totalEdgeWeight;\n\tDEBUG(\"coverage = \" << cov);\n\tdouble expCov; \/\/ term $\\frac{ \\sum_{C \\in \\zeta}( \\sum_{v \\in C} \\omega(v) )^2 }{4( \\sum_{e \\in E} \\omega(e) )^2 }$\n\tdouble modularity; \t\/\/ mod = coverage - expected coverage\n\tdouble totalEdgeWeight = G.totalEdgeWeight(); \/\/ add edge weight\n\tDEBUG(\"total edge weight: \" << totalEdgeWeight)\n\n\n\tif (totalEdgeWeight == 0.0) {\n\t\tERROR(\"G: m=\" << G.numberOfEdges() << \"n=\" << G.numberOfNodes());\n\t\tthrow std::invalid_argument(\"Modularity is undefined for graphs without edges (including self-loops).\");\n\t}\n\n\tIndexMap incidentWeightSum(zeta.upperBound(), 0.0);\t\/\/!< cluster -> sum of the weights of incident edges for all nodes\n\n\t\/\/ compute volume of each cluster\n\tG.forNodes([&](node v){\n\t\t\/\/ add to cluster weight\n\t\tcluster c = zeta[v];\n\t\tassert (zeta.lowerBound() <= c);\n\t\tassert (c < zeta.upperBound());\n\t\tincidentWeightSum[c] += G.weightedDegree(v) + G.weight(v,v); \/\/ account for self-loops a second time\n\t});\n\n\t\/\/ compute sum of squared cluster volumes and divide by squared graph volume\n\t\/\/ double totalIncidentWeight = 0.0; \t\/\/!< term $\\sum_{C \\in \\zeta}( \\sum_{v \\in C} \\omega(v) )^2 $\n\texpCov = 0.0;\n\/\/\tdouble divisor = 4 * totalEdgeWeight * totalEdgeWeight;\n\/\/\tassert (divisor != 0);\t\/\/ do not divide by 0\n\n\t#pragma omp parallel for reduction(+:expCov)\n\tfor (cluster c = zeta.lowerBound(); c < zeta.upperBound(); ++c) {\n\t\texpCov += ((incidentWeightSum[c] \/ totalEdgeWeight) * (incidentWeightSum[c] \/ totalEdgeWeight )) \/ 4;\t\/\/ squared\n\t}\n\n\tDEBUG(\"expected coverage: \" << expCov);\n\n\t\/\/ assert ranges of coverage\n\tassert(cov <= 1.0);\n\tassert(cov >= 0.0);\n\tassert(expCov <= 1.0);\n\tassert(expCov >= 0.0);\n\n\tmodularity = cov - expCov;\n\tDEBUG(\"modularity = \" << modularity)\n\n\tassert(! std::isnan(modularity));\t\/\/ do not return NaN\n\t\/\/ do not return anything not in the range of modularity values\n\tassert(modularity >= -0.5);\n\tassert(modularity <= 1);\n\treturn modularity;\n}\n\n} \/* namespace EnsembleClustering *\/\n<|endoftext|>"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ abstract_backend.h\n\/\/\n\/\/ Identification: src\/backend\/storage\/backend_file.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"backend\/storage\/backend_file.h\"\n#include \"backend\/logging\/log_manager.h\"\n#include \n#include \n#include \n#include \n\nnamespace peloton {\nnamespace storage {\n\nBackendFile::BackendFile() {\n if (EnableBackFileType()) {\n \/\/ create a big file\n std::ofstream backend_file(file_name, std::ios::binary | std::ios::out);\n backend_file.seekp(file_size - 1);\n backend_file.write(\"\", 1);\n\n \/\/ do mmap\n fd = open(file_name.c_str(), O_RDWR, 0);\n backend_space = (char *) mmap(nullptr, file_size, PROT_READ | PROT_WRITE,\n MAP_FILE | MAP_SHARED, fd, 0);\n close(fd);\n assert(backend_space != nullptr);\n \/\/ create vmem pool\n vmp = vmem_create_in_region(backend_space, file_size);\n assert(vmp != nullptr);\n }\n}\n\nBackendFile::~BackendFile() {\n if (vmp != nullptr) {\n vmem_delete(vmp);\n }\n if (backend_space != nullptr) {\n munmap(backend_space, file_size);\n \/\/remove(file_name.c_str());\n }\n}\n\nvoid *BackendFile::Allocate(size_t size) {\n if (backend_space != nullptr) {\n return vmem_malloc(vmp, size);;\n } else {\n return ::operator new(size);\n }\n}\n\nvoid BackendFile::Free(void *ptr) {\n if (backend_space != nullptr) {\n vmem_free(vmp, ptr);\n } else {\n ::operator delete(ptr);\n }\n}\n\nvoid BackendFile::Sync(void *ptr) {\n if (backend_space != nullptr) {\n size_t ptr_size = vmem_malloc_usable_size(vmp, ptr);\n if (ptr_size != 0) {\n msync(ptr, ptr_size, MS_SYNC);\n }\n }\n}\n\n} \/\/ End storage namespace\n} \/\/ End peloton namespace\nBackend file should finish creating file before map it.\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ abstract_backend.h\n\/\/\n\/\/ Identification: src\/backend\/storage\/backend_file.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"backend\/storage\/backend_file.h\"\n#include \"backend\/logging\/log_manager.h\"\n#include \n#include \n#include \n#include \n\nnamespace peloton {\nnamespace storage {\n\nBackendFile::BackendFile() {\n if (EnableBackFileType()) {\n \/\/ create a big file\n std::ofstream backend_file(file_name, std::ios::binary | std::ios::out);\n backend_file.seekp(file_size - 1);\n backend_file.write(\"\", 1);\n backend_file.close();\n\n \/\/ do mmap\n fd = open(file_name.c_str(), O_RDWR, 0);\n backend_space = (char *) mmap(nullptr, file_size, PROT_READ | PROT_WRITE,\n MAP_FILE | MAP_SHARED, fd, 0);\n close(fd);\n assert(backend_space != nullptr);\n \/\/ create vmem pool\n vmp = vmem_create_in_region(backend_space, file_size);\n assert(vmp != nullptr);\n }\n}\n\nBackendFile::~BackendFile() {\n if (vmp != nullptr) {\n vmem_delete(vmp);\n }\n if (backend_space != nullptr) {\n munmap(backend_space, file_size);\n \/\/remove(file_name.c_str());\n }\n}\n\nvoid *BackendFile::Allocate(size_t size) {\n if (backend_space != nullptr) {\n return vmem_malloc(vmp, size);;\n } else {\n return ::operator new(size);\n }\n}\n\nvoid BackendFile::Free(void *ptr) {\n if (backend_space != nullptr) {\n vmem_free(vmp, ptr);\n } else {\n ::operator delete(ptr);\n }\n}\n\nvoid BackendFile::Sync(void *ptr) {\n if (backend_space != nullptr) {\n size_t ptr_size = vmem_malloc_usable_size(vmp, ptr);\n if (ptr_size != 0) {\n msync(ptr, ptr_size, MS_SYNC);\n }\n }\n}\n\n} \/\/ End storage namespace\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"\/* This file is part of the Palabos library.\n *\n * Copyright (C) 2011-2015 FlowKit Sarl\n * Route d'Oron 2\n * 1010 Lausanne, Switzerland\n * E-mail contact: contact@flowkit.com\n *\n * The most recent release of Palabos can be downloaded at \n * \n *\n * The library Palabos is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * The library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#ifndef TRT_DYNAMICS_HH\n#define TRT_DYNAMICS_HH\n\n#include \"complexDynamics\/trtDynamics.h\"\n#include \"latticeBoltzmann\/dynamicsTemplates.h\"\n#include \"latticeBoltzmann\/momentTemplates.h\"\n#include \"core\/latticeStatistics.h\"\n#include \n#include \n\nnamespace plb {\n\n\/* *************** Class TRTdynamics *********************************************** *\/\n\ntemplate class Descriptor>\nconst T TRTdynamics::sMinus = 1.1;\n\ntemplate class Descriptor>\nint TRTdynamics::id =\n meta::registerOneParamDynamics >(\"TRT\");\n\n\/** \\param omega_ relaxation parameter, related to the dynamic viscosity\n *\/\ntemplate class Descriptor>\nTRTdynamics::TRTdynamics(T omega_ )\n : IsoThermalBulkDynamics(omega_)\n{ }\n\ntemplate class Descriptor>\nTRTdynamics* TRTdynamics::clone() const {\n return new TRTdynamics(*this);\n}\n \ntemplate class Descriptor>\nint TRTdynamics::getId() const {\n return id;\n}\n\ntemplate class Descriptor>\nvoid TRTdynamics::collide (\n Cell& cell, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n Array j;\n T rhoBar;\n momentTemplates::get_rhoBar_j(cell, rhoBar, j);\n T jSqr = normSqr(j);\n T invRho = Descriptor::invRho(rhoBar);\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr * invRho * invRho );\n }\n}\n\ntemplate class Descriptor>\nvoid TRTdynamics::collideExternal (\n Cell& cell, T rhoBar, Array::d> const& j,\n T thetaBar, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n T jSqr = normSqr(j);\n T invRho = Descriptor::invRho(rhoBar);\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr * Descriptor::invRho(rhoBar) * Descriptor::invRho(rhoBar) );\n }\n}\n\ntemplate class Descriptor>\nT TRTdynamics::computeEquilibrium(plint iPop, T rhoBar, Array::d> const& j,\n T jSqr, T thetaBar) const\n{\n T invRho = Descriptor::invRho(rhoBar);\n return dynamicsTemplates::bgk_ma2_equilibrium(iPop, rhoBar, invRho, j, jSqr);\n}\n\n\/* *************** Class IncTRTdynamics *********************************************** *\/\n\ntemplate class Descriptor>\nconst T IncTRTdynamics::sMinus = 1.1;\n\ntemplate class Descriptor>\nint IncTRTdynamics::id =\n meta::registerOneParamDynamics >(\"IncTRT\");\n \n\/** \\param omega_ relaxation parameter, related to the dynamic viscosity\n *\/\ntemplate class Descriptor>\nIncTRTdynamics::IncTRTdynamics(T omega_ )\n : IsoThermalBulkDynamics(omega_)\n{ }\n\ntemplate class Descriptor>\nIncTRTdynamics* IncTRTdynamics::clone() const {\n return new IncTRTdynamics(*this);\n}\n \ntemplate class Descriptor>\nint IncTRTdynamics::getId() const {\n return id;\n}\n\ntemplate class Descriptor>\nvoid IncTRTdynamics::collide (\n Cell& cell, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n Array j;\n T rhoBar;\n momentTemplates::get_rhoBar_j(cell, rhoBar, j);\n T jSqr = normSqr(j);\n T invRho0 = 1.;\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr);\n }\n}\n\ntemplate class Descriptor>\nvoid IncTRTdynamics::collideExternal (\n Cell& cell, T rhoBar, Array::d> const& j,\n T thetaBar, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n T jSqr = normSqr(j);\n T invRho0 = 1.;\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr);\n }\n}\n\ntemplate class Descriptor>\nT IncTRTdynamics::computeEquilibrium(plint iPop, T rhoBar, Array::d> const& j,\n T jSqr, T thetaBar) const\n{\n return dynamicsTemplates::bgk_ma2_equilibrium(iPop, rhoBar, (T)1, j, jSqr);\n}\n\ntemplate class Descriptor>\nbool IncTRTdynamics::velIsJ() const {\n return true;\n}\n\ntemplate class Descriptor>\nvoid IncTRTdynamics::computeVelocity( Cell const& cell,\n Array::d>& u ) const \n{\n T dummyRhoBar;\n this->computeRhoBarJ(cell, dummyRhoBar, u);\n}\n\n\n}\n\n#endif \/\/ TRT_DYNAMICS_HH\n\nfixing bug in TRTDynamics: code was limited to 3D simulation only\/* This file is part of the Palabos library.\n *\n * Copyright (C) 2011-2015 FlowKit Sarl\n * Route d'Oron 2\n * 1010 Lausanne, Switzerland\n * E-mail contact: contact@flowkit.com\n *\n * The most recent release of Palabos can be downloaded at \n * \n *\n * The library Palabos is free software: you can redistribute it and\/or\n * modify it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * The library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with this program. If not, see .\n*\/\n\n#ifndef TRT_DYNAMICS_HH\n#define TRT_DYNAMICS_HH\n\n#include \"complexDynamics\/trtDynamics.h\"\n#include \"latticeBoltzmann\/dynamicsTemplates.h\"\n#include \"latticeBoltzmann\/momentTemplates.h\"\n#include \"core\/latticeStatistics.h\"\n#include \n#include \n\nnamespace plb {\n\n\/* *************** Class TRTdynamics *********************************************** *\/\n\ntemplate class Descriptor>\nconst T TRTdynamics::sMinus = 1.1;\n\ntemplate class Descriptor>\nint TRTdynamics::id =\n meta::registerOneParamDynamics >(\"TRT\");\n\n\/** \\param omega_ relaxation parameter, related to the dynamic viscosity\n *\/\ntemplate class Descriptor>\nTRTdynamics::TRTdynamics(T omega_ )\n : IsoThermalBulkDynamics(omega_)\n{ }\n\ntemplate class Descriptor>\nTRTdynamics* TRTdynamics::clone() const {\n return new TRTdynamics(*this);\n}\n \ntemplate class Descriptor>\nint TRTdynamics::getId() const {\n return id;\n}\n\ntemplate class Descriptor>\nvoid TRTdynamics::collide (\n Cell& cell, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n Array::d> j;\n T rhoBar;\n momentTemplates::get_rhoBar_j(cell, rhoBar, j);\n T jSqr = normSqr(j);\n T invRho = Descriptor::invRho(rhoBar);\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr * invRho * invRho );\n }\n}\n\ntemplate class Descriptor>\nvoid TRTdynamics::collideExternal (\n Cell& cell, T rhoBar, Array::d> const& j,\n T thetaBar, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n T jSqr = normSqr(j);\n T invRho = Descriptor::invRho(rhoBar);\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr * Descriptor::invRho(rhoBar) * Descriptor::invRho(rhoBar) );\n }\n}\n\ntemplate class Descriptor>\nT TRTdynamics::computeEquilibrium(plint iPop, T rhoBar, Array::d> const& j,\n T jSqr, T thetaBar) const\n{\n T invRho = Descriptor::invRho(rhoBar);\n return dynamicsTemplates::bgk_ma2_equilibrium(iPop, rhoBar, invRho, j, jSqr);\n}\n\n\/* *************** Class IncTRTdynamics *********************************************** *\/\n\ntemplate class Descriptor>\nconst T IncTRTdynamics::sMinus = 1.1;\n\ntemplate class Descriptor>\nint IncTRTdynamics::id =\n meta::registerOneParamDynamics >(\"IncTRT\");\n \n\/** \\param omega_ relaxation parameter, related to the dynamic viscosity\n *\/\ntemplate class Descriptor>\nIncTRTdynamics::IncTRTdynamics(T omega_ )\n : IsoThermalBulkDynamics(omega_)\n{ }\n\ntemplate class Descriptor>\nIncTRTdynamics* IncTRTdynamics::clone() const {\n return new IncTRTdynamics(*this);\n}\n \ntemplate class Descriptor>\nint IncTRTdynamics::getId() const {\n return id;\n}\n\ntemplate class Descriptor>\nvoid IncTRTdynamics::collide (\n Cell& cell, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n Array j;\n T rhoBar;\n momentTemplates::get_rhoBar_j(cell, rhoBar, j);\n T jSqr = normSqr(j);\n T invRho0 = 1.;\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr);\n }\n}\n\ntemplate class Descriptor>\nvoid IncTRTdynamics::collideExternal (\n Cell& cell, T rhoBar, Array::d> const& j,\n T thetaBar, BlockStatistics& statistics )\n{\n const T sPlus = this->getOmega();\n\n Array::q> eq;\n \/\/ In the following, we number the plus\/minus variables from 1 to (Q-1)\/2.\n \/\/ So we allocate the index-zero memory location, and waste some memory\n \/\/ for convenience.\n Array::q\/2+1> eq_plus, eq_minus, f_plus, f_minus;\n\n T jSqr = normSqr(j);\n T invRho0 = 1.;\n dynamicsTemplates::bgk_ma2_equilibria(rhoBar, invRho0, j, jSqr, eq);\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n eq_plus[i] = 0.5*(eq[i] + eq[i+Descriptor::q\/2]);\n eq_minus[i] = 0.5*(eq[i] - eq[i+Descriptor::q\/2]);\n f_plus[i] = 0.5*(cell[i] + cell[i+Descriptor::q\/2]);\n f_minus[i] = 0.5*(cell[i] - cell[i+Descriptor::q\/2]);\n }\n\n cell[0] += -sPlus*cell[0] + sPlus*eq[0];\n\n for (plint i=1; i<=Descriptor::q\/2; ++i) {\n cell[i] += -sPlus*(f_plus[i]-eq_plus[i]) - sMinus*(f_minus[i]-eq_minus[i]);\n cell[i+Descriptor::q\/2] += -sPlus*(f_plus[i]-eq_plus[i]) + sMinus*(f_minus[i]-eq_minus[i]);\n }\n \n if (cell.takesStatistics()) {\n gatherStatistics(statistics, rhoBar, jSqr);\n }\n}\n\ntemplate class Descriptor>\nT IncTRTdynamics::computeEquilibrium(plint iPop, T rhoBar, Array::d> const& j,\n T jSqr, T thetaBar) const\n{\n return dynamicsTemplates::bgk_ma2_equilibrium(iPop, rhoBar, (T)1, j, jSqr);\n}\n\ntemplate class Descriptor>\nbool IncTRTdynamics::velIsJ() const {\n return true;\n}\n\ntemplate class Descriptor>\nvoid IncTRTdynamics::computeVelocity( Cell const& cell,\n Array::d>& u ) const \n{\n T dummyRhoBar;\n this->computeRhoBarJ(cell, dummyRhoBar, u);\n}\n\n\n}\n\n#endif \/\/ TRT_DYNAMICS_HH\n\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"generic_query.h\"\n#include \"condor_attributes.h\"\n#include \"condor_classad.h\"\n#include \"MyString.h\"\n\nstatic char *new_strdup (const char *);\n\nGenericQuery::\nGenericQuery ()\n{\n\t\/\/ initialize category counts\n\tintegerThreshold = 0;\n\tstringThreshold = 0;\n\tfloatThreshold = 0;\n\n\t\/\/ initialize pointers\n\tintegerConstraints = 0;\n\tfloatConstraints = 0;\n\tstringConstraints = 0;\n\n\tfloatKeywordList = NULL;\n\tintegerKeywordList = NULL;\n\tstringKeywordList = NULL;\n}\n\n\nGenericQuery::\nGenericQuery (const GenericQuery &gq)\n{\n\t\/\/ initialize category counts\n\tintegerThreshold = 0;\n\tstringThreshold = 0;\n\tfloatThreshold = 0;\n\n\t\/\/ initialize pointers\n\tintegerConstraints = 0;\n\tfloatConstraints = 0;\n\tstringConstraints = 0;\n\n\tfloatKeywordList = NULL;\n\tintegerKeywordList = NULL;\n\tstringKeywordList = NULL;\n\n\tcopyQueryObject(gq);\n}\n\n\nGenericQuery::\n~GenericQuery ()\n{\n\tclearQueryObject ();\n\t\n\t\/\/ release memory\n\tif (stringConstraints) delete [] stringConstraints;\n\tif (floatConstraints) delete [] floatConstraints;\n\tif (integerConstraints)delete [] integerConstraints;\n}\n\n\nint GenericQuery::\nsetNumIntegerCats (const int numCats)\n{\n\tintegerThreshold = (numCats > 0) ? numCats : 0;\n\tif (integerThreshold)\n\t{\n\t\tintegerConstraints = new SimpleList [integerThreshold];\n\t\tif (!integerConstraints)\n\t\t\treturn Q_MEMORY_ERROR;\n\t\treturn Q_OK;\n\t}\n\treturn Q_INVALID_CATEGORY;\n}\n\n\nint GenericQuery::\nsetNumStringCats (const int numCats)\n{\n\tstringThreshold = (numCats > 0) ? numCats : 0;\n\tif (stringThreshold)\n\t{\n\t\tstringConstraints = new List [stringThreshold];\n\t\tif (!stringConstraints)\n\t\t\treturn Q_MEMORY_ERROR;\n\t\treturn Q_OK;\n\t}\n\treturn Q_INVALID_CATEGORY;\n}\n\n\nint GenericQuery::\nsetNumFloatCats (const int numCats)\n{\n\tfloatThreshold = (numCats > 0) ? numCats : 0;\n\tif (floatThreshold)\n\t{\t\n\t\tfloatConstraints = new SimpleList [floatThreshold];\n\t\tif (!floatConstraints)\n\t\t\treturn Q_MEMORY_ERROR;\n\t\treturn Q_OK;\n\t}\n\treturn Q_INVALID_CATEGORY;\n}\n\n\n\/\/ add an integer constraint\nint GenericQuery::\naddInteger (const int cat, int value)\n{\n if (cat >= 0 && cat < integerThreshold)\n {\n if (!integerConstraints [cat].Append (value))\n return Q_MEMORY_ERROR;\n return Q_OK;\n }\n\n return Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\naddFloat (const int cat, float value)\n{\n if (cat >= 0 && cat < floatThreshold)\n {\n if (!floatConstraints [cat].Append (value))\n return Q_MEMORY_ERROR;\n return Q_OK;\n }\n\n return Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\naddString (const int cat, const char *value)\n{\n char *x;\n\n if (cat >= 0 && cat < stringThreshold)\n {\n x = new_strdup (value);\n if (!x) return Q_MEMORY_ERROR;\n stringConstraints [cat].Append (x);\n return Q_OK;\n }\n\n return Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\naddCustomOR (const char *value)\n{\n char *x = new_strdup (value);\n\tif (!x) return Q_MEMORY_ERROR;\n\tcustomORConstraints.Append (x);\n\treturn Q_OK;\n}\n\nint GenericQuery::\naddCustomAND (const char *value)\n{\n char *x = new_strdup (value);\n\tif (!x) return Q_MEMORY_ERROR;\n\tcustomANDConstraints.Append (x);\n\treturn Q_OK;\n}\n\n\n\/\/ clear functions\nint GenericQuery::\nclearInteger (const int cat)\n{\n\tif (cat >= 0 && cat < integerThreshold)\n\t{\n\t\tclearIntegerCategory (integerConstraints [cat]);\n\t\treturn Q_OK;\n\t}\n\telse\n\t\treturn Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\nclearString (const int cat)\n{\n\tif (cat >= 0 && cat < stringThreshold)\n\t{\n\t\tclearStringCategory (stringConstraints [cat]);\n\t\treturn Q_OK;\n\t}\n\telse\n\t\treturn Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\nclearFloat (const int cat)\n{\n\tif (cat >= 0 && cat < floatThreshold)\n\t{\n\t\tclearFloatCategory (floatConstraints [cat]);\n\t\treturn Q_OK;\n\t}\n\telse\n\t\treturn Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\nclearCustomOR ()\n{\n\tclearStringCategory (customORConstraints);\n\treturn Q_OK;\n}\n\nint GenericQuery::\nclearCustomAND ()\n{\n\tclearStringCategory (customANDConstraints);\n\treturn Q_OK;\n}\n\n\n\/\/ set keyword lists\nvoid GenericQuery::\nsetIntegerKwList (char **value)\n{\n\tintegerKeywordList = value;\n}\n\n\nvoid GenericQuery::\nsetStringKwList (char **value)\n{\n\tstringKeywordList = value;\n}\n\n\nvoid GenericQuery::\nsetFloatKwList (char **value)\n{\n\tfloatKeywordList = value;\n}\n\n\n\/\/ make query\nint GenericQuery::\nmakeQuery (MyString &req)\n{\n\tint\t\ti, value;\n\tchar\t*item;\n\tfloat fvalue;\n\n\treq = \"\";\n\n\t\/\/ construct query requirement expression\n\tbool firstCategory = true;\n\n\t\/\/ add string constraints\n\tfor (i = 0; i < stringThreshold; i++)\n\t{\n\t\tstringConstraints [i].Rewind ();\n\t\tif (!stringConstraints [i].AtEnd ())\n\t\t{\n\t\t\tbool firstTime = true;\n\t\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\t\twhile ((item = stringConstraints [i].Next ()))\n\t\t\t{\n\t\t\t\treq.formatstr_cat (\"%s(%s == \\\"%s\\\")\", \n\t\t\t\t\t\t firstTime ? \" \" : \" || \", \n\t\t\t\t\t\t stringKeywordList [i], item);\n\t\t\t\tfirstTime = false;\n\t\t\t\tfirstCategory = false;\n\t\t\t}\n\t\t\treq += \" )\";\n\t\t}\n\t}\n\n\t\/\/ add integer constraints\n\tfor (i = 0; i < integerThreshold; i++)\n\t{\n\t\tintegerConstraints [i].Rewind ();\n\t\tif (!integerConstraints [i].AtEnd ())\n\t\t{\n\t\t\tbool firstTime = true;\n\t\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\t\twhile (integerConstraints [i].Next (value))\n\t\t\t{\n\t\t\t\treq.formatstr_cat (\"%s(%s == %d)\", \n\t\t\t\t\t\t firstTime ? \" \" : \" || \",\n\t\t\t\t\t\t integerKeywordList [i], value);\n\t\t\t\tfirstTime = false;\n\t\t\t\tfirstCategory = false;\n\t\t\t}\n\t\t\treq += \" )\";\n\t\t}\n\t}\n\n\t\/\/ add float constraints\n\tfor (i = 0; i < floatThreshold; i++)\n\t{\n\t\tfloatConstraints [i].Rewind ();\n\t\tif (!floatConstraints [i].AtEnd ())\n\t\t{\n\t\t\tbool firstTime = true;\n\t\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\t\twhile (floatConstraints [i].Next (fvalue))\n\t\t\t{\n\t\t\t\treq.formatstr_cat (\"%s(%s == %f)\", \n\t\t\t\t\t\t firstTime ? \" \" : \" || \",\n\t\t\t\t\t\t floatKeywordList [i], fvalue);\n\t\t\t\tfirstTime = false;\n\t\t\t\tfirstCategory = false;\n\t\t\t}\n\t\t\treq += \" )\";\n\t\t}\n\t}\n\n\t\/\/ add custom AND constraints\n\tcustomANDConstraints.Rewind ();\n\tif (!customANDConstraints.AtEnd ())\n\t{\n\t\tbool firstTime = true;\n\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\twhile ((item = customANDConstraints.Next ()))\n\t\t{\n\t\t\treq.formatstr_cat (\"%s(%s)\", firstTime ? \" \" : \" && \", item);\n\t\t\tfirstTime = false;\n\t\t\tfirstCategory = false;\n\t\t}\n\t\treq += \" )\";\n\t}\n\n\t\/\/ add custom OR constraints\n\tcustomORConstraints.Rewind ();\n\tif (!customORConstraints.AtEnd ())\n\t{\n\t\tbool firstTime = true;\n\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\twhile ((item = customORConstraints.Next ()))\n\t\t{\n\t\t\treq.formatstr_cat (\"%s(%s)\", firstTime ? \" \" : \" || \", item);\n\t\t\tfirstTime = false;\n\t\t\tfirstCategory = false;\n\t\t}\n\t\treq += \" )\";\n\t}\n\n\treturn Q_OK;\n}\n\nint GenericQuery::\nmakeQuery (ExprTree *&tree)\n{\n\tMyString req;\n\tint status = makeQuery(req);\n\tif (status != Q_OK) return status;\n\n\t\/\/ If there are no constraints, then we match everything.\n\tif (req.empty()) req = \"TRUE\";\n\n\t\/\/ parse constraints and insert into query ad\n\tif (ParseClassAdRvalExpr (req.Value(), tree) > 0) return Q_PARSE_ERROR;\n\n\treturn Q_OK;\n}\n\n\/\/ helper functions --- clear \nvoid GenericQuery::\nclearQueryObject (void)\n{\n\tint i;\n\tfor (i = 0; i < stringThreshold; i++)\n\t\tif (stringConstraints) clearStringCategory (stringConstraints[i]);\n\t\n\tfor (i = 0; i < integerThreshold; i++)\n\t\tif (integerConstraints) clearIntegerCategory (integerConstraints[i]);\n\n\tfor (i = 0; i < floatThreshold; i++)\n\t\tif (integerConstraints) clearFloatCategory (floatConstraints[i]);\n\n\tclearStringCategory (customANDConstraints);\n\tclearStringCategory (customORConstraints);\n}\n\nvoid GenericQuery::\nclearStringCategory (List &str_category)\n{\n char *x;\n str_category.Rewind ();\n while ((x = str_category.Next ()))\n {\n delete [] x;\n str_category.DeleteCurrent ();\n }\n}\n\nvoid GenericQuery::\nclearIntegerCategory (SimpleList &int_category)\n{\n int item;\n\n int_category.Rewind ();\n while (int_category.Next (item))\n int_category.DeleteCurrent ();\n}\n\nvoid GenericQuery::\nclearFloatCategory (SimpleList &float_category)\n{\n float item;\n\n float_category.Rewind ();\n while (float_category.Next (item))\n float_category.DeleteCurrent ();\n}\n\n\n\/\/ helper functions --- copy\nvoid GenericQuery::\ncopyQueryObject (const GenericQuery &from)\n{\n\tint i;\n\n\t\/\/ copy string constraints\n \tfor (i = 0; i < from.stringThreshold; i++)\n\t\tcopyStringCategory (stringConstraints[i], from.stringConstraints[i]);\n\t\n\t\/\/ copy integer constraints\n\tfor (i = 0; i < from.integerThreshold; i++)\n\t\tcopyIntegerCategory (integerConstraints[i],from.integerConstraints[i]);\n\n\t\/\/ copy custom constraints\n\tcopyStringCategory (customANDConstraints, const_cast &>(from.customANDConstraints));\n\tcopyStringCategory (customORConstraints, const_cast &>(from.customORConstraints));\n\n\t\/\/ copy misc fields\n\tstringThreshold = from.stringThreshold;\n\tintegerThreshold = from.integerThreshold;\n\tfloatThreshold = from.floatThreshold;\n\n\tintegerKeywordList = from.integerKeywordList;\n\tstringKeywordList = from.stringKeywordList;\n\tfloatKeywordList = from.floatKeywordList;\n\n\tfloatConstraints = from.floatConstraints;\n\tintegerConstraints = from.integerConstraints;\n\tstringConstraints = from.stringConstraints;\n}\n\nvoid GenericQuery::\ncopyStringCategory (List &to, List &from)\n{\n\tchar *item;\n\n\tclearStringCategory (to);\n\tfrom.Rewind ();\n\twhile ((item = from.Next ()))\n\t\tto.Append (new_strdup (item));\n}\n\nvoid GenericQuery::\ncopyIntegerCategory (SimpleList &to, SimpleList &from)\n{\n\tint item;\n\n\tclearIntegerCategory (to);\n\twhile (from.Next (item))\n\t\tto.Append (item);\n}\n\nvoid GenericQuery::\ncopyFloatCategory (SimpleList &to, SimpleList &from)\n{\n\tfloat item;\n\n\tclearFloatCategory (to);\n\twhile (from.Next (item))\n\t\tto.Append (item);\n}\n\n\/\/ strdup() which uses new\nstatic char *new_strdup (const char *str)\n{\n char *x = new char [strlen (str) + 1];\n if (!x) return 0;\n strcpy (x, str);\n return x;\n}\nMore coverity appeasement #6992\/***************************************************************\n *\n * Copyright (C) 1990-2011, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n#include \"condor_common.h\"\n#include \"generic_query.h\"\n#include \"condor_attributes.h\"\n#include \"condor_classad.h\"\n#include \"MyString.h\"\n\nstatic char *new_strdup (const char *);\n\nGenericQuery::\nGenericQuery ()\n{\n\t\/\/ initialize category counts\n\tintegerThreshold = 0;\n\tstringThreshold = 0;\n\tfloatThreshold = 0;\n\n\t\/\/ initialize pointers\n\tintegerConstraints = 0;\n\tfloatConstraints = 0;\n\tstringConstraints = 0;\n\n\tfloatKeywordList = NULL;\n\tintegerKeywordList = NULL;\n\tstringKeywordList = NULL;\n}\n\n\nGenericQuery::\nGenericQuery (const GenericQuery &gq)\n{\n\t\/\/ initialize category counts\n\tintegerThreshold = 0;\n\tstringThreshold = 0;\n\tfloatThreshold = 0;\n\n\t\/\/ initialize pointers\n\tintegerConstraints = 0;\n\tfloatConstraints = 0;\n\tstringConstraints = 0;\n\n\tfloatKeywordList = NULL;\n\tintegerKeywordList = NULL;\n\tstringKeywordList = NULL;\n\n\tcopyQueryObject(gq);\n}\n\n\nGenericQuery::\n~GenericQuery ()\n{\n\tclearQueryObject ();\n\t\n\t\/\/ release memory\n\tif (stringConstraints) delete [] stringConstraints;\n\tif (floatConstraints) delete [] floatConstraints;\n\tif (integerConstraints)delete [] integerConstraints;\n}\n\n\nint GenericQuery::\nsetNumIntegerCats (const int numCats)\n{\n\tintegerThreshold = (numCats > 0) ? numCats : 0;\n\tif (integerThreshold)\n\t{\n\t\tintegerConstraints = new SimpleList [integerThreshold];\n\t\tif (!integerConstraints)\n\t\t\treturn Q_MEMORY_ERROR;\n\t\treturn Q_OK;\n\t}\n\treturn Q_INVALID_CATEGORY;\n}\n\n\nint GenericQuery::\nsetNumStringCats (const int numCats)\n{\n\tstringThreshold = (numCats > 0) ? numCats : 0;\n\tif (stringThreshold)\n\t{\n\t\tstringConstraints = new List [stringThreshold];\n\t\tif (!stringConstraints)\n\t\t\treturn Q_MEMORY_ERROR;\n\t\treturn Q_OK;\n\t}\n\treturn Q_INVALID_CATEGORY;\n}\n\n\nint GenericQuery::\nsetNumFloatCats (const int numCats)\n{\n\tfloatThreshold = (numCats > 0) ? numCats : 0;\n\tif (floatThreshold)\n\t{\t\n\t\tfloatConstraints = new SimpleList [floatThreshold];\n\t\tif (!floatConstraints)\n\t\t\treturn Q_MEMORY_ERROR;\n\t\treturn Q_OK;\n\t}\n\treturn Q_INVALID_CATEGORY;\n}\n\n\n\/\/ add an integer constraint\nint GenericQuery::\naddInteger (const int cat, int value)\n{\n if (cat >= 0 && cat < integerThreshold)\n {\n if (!integerConstraints [cat].Append (value))\n return Q_MEMORY_ERROR;\n return Q_OK;\n }\n\n return Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\naddFloat (const int cat, float value)\n{\n if (cat >= 0 && cat < floatThreshold)\n {\n if (!floatConstraints [cat].Append (value))\n return Q_MEMORY_ERROR;\n return Q_OK;\n }\n\n return Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\naddString (const int cat, const char *value)\n{\n char *x;\n\n if (cat >= 0 && cat < stringThreshold)\n {\n x = new_strdup (value);\n if (!x) return Q_MEMORY_ERROR;\n stringConstraints [cat].Append (x);\n return Q_OK;\n }\n\n return Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\naddCustomOR (const char *value)\n{\n char *x = new_strdup (value);\n\tif (!x) return Q_MEMORY_ERROR;\n\tcustomORConstraints.Append (x);\n\treturn Q_OK;\n}\n\nint GenericQuery::\naddCustomAND (const char *value)\n{\n char *x = new_strdup (value);\n\tif (!x) return Q_MEMORY_ERROR;\n\tcustomANDConstraints.Append (x);\n\treturn Q_OK;\n}\n\n\n\/\/ clear functions\nint GenericQuery::\nclearInteger (const int cat)\n{\n\tif (cat >= 0 && cat < integerThreshold)\n\t{\n\t\tclearIntegerCategory (integerConstraints [cat]);\n\t\treturn Q_OK;\n\t}\n\telse\n\t\treturn Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\nclearString (const int cat)\n{\n\tif (cat >= 0 && cat < stringThreshold)\n\t{\n\t\tclearStringCategory (stringConstraints [cat]);\n\t\treturn Q_OK;\n\t}\n\telse\n\t\treturn Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\nclearFloat (const int cat)\n{\n\tif (cat >= 0 && cat < floatThreshold)\n\t{\n\t\tclearFloatCategory (floatConstraints [cat]);\n\t\treturn Q_OK;\n\t}\n\telse\n\t\treturn Q_INVALID_CATEGORY;\n}\n\nint GenericQuery::\nclearCustomOR ()\n{\n\tclearStringCategory (customORConstraints);\n\treturn Q_OK;\n}\n\nint GenericQuery::\nclearCustomAND ()\n{\n\tclearStringCategory (customANDConstraints);\n\treturn Q_OK;\n}\n\n\n\/\/ set keyword lists\nvoid GenericQuery::\nsetIntegerKwList (char **value)\n{\n\tintegerKeywordList = value;\n}\n\n\nvoid GenericQuery::\nsetStringKwList (char **value)\n{\n\tstringKeywordList = value;\n}\n\n\nvoid GenericQuery::\nsetFloatKwList (char **value)\n{\n\tfloatKeywordList = value;\n}\n\n\n\/\/ make query\nint GenericQuery::\nmakeQuery (MyString &req)\n{\n\tint\t\ti, value;\n\tchar\t*item;\n\tfloat fvalue;\n\n\treq = \"\";\n\n\t\/\/ construct query requirement expression\n\tbool firstCategory = true;\n\n\t\/\/ add string constraints\n\tfor (i = 0; i < stringThreshold; i++)\n\t{\n\t\tstringConstraints [i].Rewind ();\n\t\tif (!stringConstraints [i].AtEnd ())\n\t\t{\n\t\t\tbool firstTime = true;\n\t\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\t\twhile ((item = stringConstraints [i].Next ()))\n\t\t\t{\n\t\t\t\treq.formatstr_cat (\"%s(%s == \\\"%s\\\")\", \n\t\t\t\t\t\t firstTime ? \" \" : \" || \", \n\t\t\t\t\t\t stringKeywordList [i], item);\n\t\t\t\tfirstTime = false;\n\t\t\t\tfirstCategory = false;\n\t\t\t}\n\t\t\treq += \" )\";\n\t\t}\n\t}\n\n\t\/\/ add integer constraints\n\tfor (i = 0; i < integerThreshold; i++)\n\t{\n\t\tintegerConstraints [i].Rewind ();\n\t\tif (!integerConstraints [i].AtEnd ())\n\t\t{\n\t\t\tbool firstTime = true;\n\t\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\t\twhile (integerConstraints [i].Next (value))\n\t\t\t{\n\t\t\t\treq.formatstr_cat (\"%s(%s == %d)\", \n\t\t\t\t\t\t firstTime ? \" \" : \" || \",\n\t\t\t\t\t\t integerKeywordList [i], value);\n\t\t\t\tfirstTime = false;\n\t\t\t\tfirstCategory = false;\n\t\t\t}\n\t\t\treq += \" )\";\n\t\t}\n\t}\n\n\t\/\/ add float constraints\n\tfor (i = 0; i < floatThreshold; i++)\n\t{\n\t\tfloatConstraints [i].Rewind ();\n\t\tif (!floatConstraints [i].AtEnd ())\n\t\t{\n\t\t\tbool firstTime = true;\n\t\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\t\twhile (floatConstraints [i].Next (fvalue))\n\t\t\t{\n\t\t\t\treq.formatstr_cat (\"%s(%s == %f)\", \n\t\t\t\t\t\t firstTime ? \" \" : \" || \",\n\t\t\t\t\t\t floatKeywordList [i], fvalue);\n\t\t\t\tfirstTime = false;\n\t\t\t\tfirstCategory = false;\n\t\t\t}\n\t\t\treq += \" )\";\n\t\t}\n\t}\n\n\t\/\/ add custom AND constraints\n\tcustomANDConstraints.Rewind ();\n\tif (!customANDConstraints.AtEnd ())\n\t{\n\t\tbool firstTime = true;\n\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\twhile ((item = customANDConstraints.Next ()))\n\t\t{\n\t\t\treq.formatstr_cat (\"%s(%s)\", firstTime ? \" \" : \" && \", item);\n\t\t\tfirstTime = false;\n\t\t\tfirstCategory = false;\n\t\t}\n\t\treq += \" )\";\n\t}\n\n\t\/\/ add custom OR constraints\n\tcustomORConstraints.Rewind ();\n\tif (!customORConstraints.AtEnd ())\n\t{\n\t\tbool firstTime = true;\n\t\treq += firstCategory ? \"(\" : \" && (\";\n\t\twhile ((item = customORConstraints.Next ()))\n\t\t{\n\t\t\treq.formatstr_cat (\"%s(%s)\", firstTime ? \" \" : \" || \", item);\n\t\t\tfirstTime = false;\n\t\t\tfirstCategory = false;\n\t\t}\n\t\treq += \" )\";\n\t}\n\n\treturn Q_OK;\n}\n\nint GenericQuery::\nmakeQuery (ExprTree *&tree)\n{\n\tMyString req;\n\tint status = makeQuery(req);\n\tif (status != Q_OK) return status;\n\n\t\/\/ If there are no constraints, then we match everything.\n\tif (req.empty()) req = \"TRUE\";\n\n\t\/\/ parse constraints and insert into query ad\n\tif (ParseClassAdRvalExpr (req.Value(), tree) > 0) return Q_PARSE_ERROR;\n\n\treturn Q_OK;\n}\n\n\/\/ helper functions --- clear \nvoid GenericQuery::\nclearQueryObject (void)\n{\n\tint i;\n\tfor (i = 0; i < stringThreshold; i++)\n\t\tif (stringConstraints) clearStringCategory (stringConstraints[i]);\n\t\n\tfor (i = 0; i < integerThreshold; i++)\n\t\tif (integerConstraints) clearIntegerCategory (integerConstraints[i]);\n\n\tfor (i = 0; i < floatThreshold; i++)\n\t\tif (integerConstraints) clearFloatCategory (floatConstraints[i]);\n\n\tclearStringCategory (customANDConstraints);\n\tclearStringCategory (customORConstraints);\n}\n\nvoid GenericQuery::\nclearStringCategory (List &str_category)\n{\n char *x;\n str_category.Rewind ();\n while ((x = str_category.Next ()))\n {\n delete [] x;\n str_category.DeleteCurrent ();\n }\n}\n\nvoid GenericQuery::\nclearIntegerCategory (SimpleList &int_category)\n{\n int item;\n\n int_category.Rewind ();\n while (int_category.Next (item))\n int_category.DeleteCurrent ();\n}\n\nvoid GenericQuery::\nclearFloatCategory (SimpleList &float_category)\n{\n float item;\n\n float_category.Rewind ();\n while (float_category.Next (item))\n float_category.DeleteCurrent ();\n}\n\n\n\/\/ helper functions --- copy\nvoid GenericQuery::\ncopyQueryObject (const GenericQuery &from)\n{\n\tint i;\n\n\t\/\/ copy string constraints\n \tfor (i = 0; i < from.stringThreshold; i++)\n\t\tif (stringConstraints) copyStringCategory (stringConstraints[i], from.stringConstraints[i]);\n\t\n\t\/\/ copy integer constraints\n\tfor (i = 0; i < from.integerThreshold; i++)\n\t\tif (integerConstraints) copyIntegerCategory (integerConstraints[i],from.integerConstraints[i]);\n\n\t\/\/ copy custom constraints\n\tcopyStringCategory (customANDConstraints, const_cast &>(from.customANDConstraints));\n\tcopyStringCategory (customORConstraints, const_cast &>(from.customORConstraints));\n\n\t\/\/ copy misc fields\n\tstringThreshold = from.stringThreshold;\n\tintegerThreshold = from.integerThreshold;\n\tfloatThreshold = from.floatThreshold;\n\n\tintegerKeywordList = from.integerKeywordList;\n\tstringKeywordList = from.stringKeywordList;\n\tfloatKeywordList = from.floatKeywordList;\n\n\tfloatConstraints = from.floatConstraints;\n\tintegerConstraints = from.integerConstraints;\n\tstringConstraints = from.stringConstraints;\n}\n\nvoid GenericQuery::\ncopyStringCategory (List &to, List &from)\n{\n\tchar *item;\n\n\tclearStringCategory (to);\n\tfrom.Rewind ();\n\twhile ((item = from.Next ()))\n\t\tto.Append (new_strdup (item));\n}\n\nvoid GenericQuery::\ncopyIntegerCategory (SimpleList &to, SimpleList &from)\n{\n\tint item;\n\n\tclearIntegerCategory (to);\n\twhile (from.Next (item))\n\t\tto.Append (item);\n}\n\nvoid GenericQuery::\ncopyFloatCategory (SimpleList &to, SimpleList &from)\n{\n\tfloat item;\n\n\tclearFloatCategory (to);\n\twhile (from.Next (item))\n\t\tto.Append (item);\n}\n\n\/\/ strdup() which uses new\nstatic char *new_strdup (const char *str)\n{\n char *x = new char [strlen (str) + 1];\n if (!x) return 0;\n strcpy (x, str);\n return x;\n}\n<|endoftext|>"} {"text":"\/*\n * PoolingGenConn.cpp\n *\n * Created on: Apr 25, 2011\n * Author: peteschultz\n *\/\n\n#include \"PoolingGenConn.hpp\"\n\nnamespace PV {\nPoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,\n const char * filename, InitWeights *weightInit) {\n initialize_base();\n initialize(name, hc, pre, post, pre2, post2, filename, weightInit);\n} \/\/ end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,\n \/\/ HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)\n\nint PoolingGenConn::initialize_base() {\n pre2 = NULL;\n post2 = NULL;\n return PV_SUCCESS;\n}\n\nint PoolingGenConn::initialize(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,\n const char * filename, InitWeights *weightInit) {\n int status;\n PVParams * params = hc->parameters();\n status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);\n if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {\n this->pre2 = pre2;\n this->post2 = post2;\n }\n else {\n status = PV_FAILURE;\n }\n if( status == PV_SUCCESS ) {\n slownessFlag = params->value(name, \"slownessFlag\", 0.0\/*default is false*\/);\n }\n if( slownessFlag ) {\n status = getSlownessLayer(&slownessPre, \"slownessPre\");\n status = getSlownessLayer(&slownessPost, \"slownessPost\")==PV_SUCCESS ? status : PV_FAILURE;\n }\n if( slownessFlag && status == PV_SUCCESS ) {\n status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;\n status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;\n }\n if( status != PV_SUCCESS ) {\n abort();\n }\n return status;\n} \/\/ end of PoolingGenConn::initialize(const char *, HyPerCol *,\n \/\/ HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)\n\nbool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {\n\tint nx1 = layer1->getLayerLoc()->nx;\n\tint nx2 = layer2->getLayerLoc()->nx;\n\tint ny1 = layer1->getLayerLoc()->ny;\n\tint ny2 = layer2->getLayerLoc()->ny;\n\tint nf1 = layer1->getLayerLoc()->nf;\n\tint nf2 = layer2->getLayerLoc()->nf;\n\tint nb1 = layer1->getLayerLoc()->nb;\n\tint nb2 = layer2->getLayerLoc()->nb;\n bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;\n if( !result ) {\n \tconst char * name1 = layer1->getName();\n \tconst char * name2 = layer2->getName();\n fprintf(stderr, \"Group \\\"%s\\\": Layers \\\"%s\\\" and \\\"%s\\\" do not have compatible sizes\\n\", name, name1, name2);\n int len1 = (int) strlen(name1);\n int len2 = (int) strlen(name2);\n int len = len1 >= len2 ? len1 : len2;\n fprintf(stderr, \"Layer \\\"%*s\\\": nx=%d, ny=%d, nf=%d, nb=%d\\n\", len, name1, nx1, ny1, nf1, nb1);\n fprintf(stderr, \"Layer \\\"%*s\\\": nx=%d, ny=%d, nf=%d, nb=%d\\n\", len, name2, nx2, ny2, nf2, nb2);\n }\n return result;\n} \/\/ end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)\n\nint PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {\n int status = PV_SUCCESS;\n assert(slownessFlag);\n const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);\n if( slownessLayerName == NULL ) {\n status = PV_FAILURE;\n fprintf(stderr, \"PoolingGenConn \\\"%s\\\": if slownessFlag is set, parameter \\\"%s\\\" must be set\\n\", name, paramname);\n }\n if( status == PV_SUCCESS ) {\n *l = parent->getLayerFromName(slownessLayerName);\n if( *l == NULL ) {\n status = PV_FAILURE;\n fprintf(stderr, \"PoolingGenConn \\\"%s\\\": %s layer \\\"%s\\\" was not found\\n\", name, paramname, slownessLayerName);\n }\n }\n return status;\n}\n\nint PoolingGenConn::updateWeights(int axonID) {\n int nPre = preSynapticLayer()->getNumNeurons();\n int nx = preSynapticLayer()->getLayerLoc()->nx;\n int ny = preSynapticLayer()->getLayerLoc()->ny;\n int nf = preSynapticLayer()->getLayerLoc()->nf;\n int pad = preSynapticLayer()->getLayerLoc()->nb;\n for(int kPre=0; kPregetCLayer()->activity->data[kExt];\n pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];\n PVPatch * weights = getWeights(kPre,axonID);\n int nyp = weights->ny;\n int nk = weights->nx * nfp;\n pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);\n pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);\n int sya = getPostNonextStrides()->sy;\n pvdata_t * wtpatch = get_wData(axonID, kExt); \/\/ weights->data;\n int syw = syp;\n for( int y=0; yoffset;\n int lineoffseta = 0;\n for( int k=0; kgetCLayer()->activity->data[kExt];\n PVPatch * weights = getWeights(kPre,axonID);\n int nyp = weights->ny;\n int nk = weights->nx * nfp;\n pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);\n int sya = getPostNonextStrides()->sy;\n pvdata_t * wtpatch = get_wData(axonID, kExt); \/\/ weights->data;\n int syw = syp;\n for( int y=0; ygetKernelPatch(axonID, kPatch);\n pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); \/\/ weights->data;\n int nk = nxp * nfp;\n int syw = nxp*nfp;\n for( int y=0; y < nyp; y++ ) {\n int lineoffsetw = 0;\n for( int k=0; ksimulationTime();\n\n return PV_SUCCESS;\n}\n\n} \/\/ end namespace PV\nBugfix for PoolingGenConn\/*\n * PoolingGenConn.cpp\n *\n * Created on: Apr 25, 2011\n * Author: peteschultz\n *\/\n\n#include \"PoolingGenConn.hpp\"\n\nnamespace PV {\nPoolingGenConn::PoolingGenConn(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,\n const char * filename, InitWeights *weightInit) {\n initialize_base();\n initialize(name, hc, pre, post, pre2, post2, filename, weightInit);\n} \/\/ end of PoolingGenConn::PoolingGenConn(const char *, HyPerCol *,\n \/\/ HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *)\n\nint PoolingGenConn::initialize_base() {\n pre2 = NULL;\n post2 = NULL;\n return PV_SUCCESS;\n}\n\nint PoolingGenConn::initialize(const char * name, HyPerCol * hc,\n HyPerLayer * pre, HyPerLayer * post, HyPerLayer * pre2, HyPerLayer * post2,\n const char * filename, InitWeights *weightInit) {\n int status;\n PVParams * params = hc->parameters();\n status = GenerativeConn::initialize(name, hc, pre, post, filename, weightInit);\n if( status == PV_SUCCESS && checkLayersCompatible(pre, pre2) && checkLayersCompatible(post, post2) ) {\n this->pre2 = pre2;\n this->post2 = post2;\n }\n else {\n status = PV_FAILURE;\n }\n if( status == PV_SUCCESS ) {\n slownessFlag = params->value(name, \"slownessFlag\", 0.0\/*default is false*\/);\n }\n if( slownessFlag ) {\n status = getSlownessLayer(&slownessPre, \"slownessPre\");\n status = getSlownessLayer(&slownessPost, \"slownessPost\")==PV_SUCCESS ? status : PV_FAILURE;\n }\n if( slownessFlag && status == PV_SUCCESS ) {\n status = checkLayersCompatible(pre, slownessPre) ? status : PV_FAILURE;\n status = checkLayersCompatible(post, slownessPost) ? status : PV_FAILURE;\n }\n if( status != PV_SUCCESS ) {\n abort();\n }\n return status;\n} \/\/ end of PoolingGenConn::initialize(const char *, HyPerCol *,\n \/\/ HyPerLayer *, HyPerLayer *, HyPerLayer *, HyPerLayer *, int, const char *, InitWeights *)\n\nbool PoolingGenConn::checkLayersCompatible(HyPerLayer * layer1, HyPerLayer * layer2) {\n\tint nx1 = layer1->getLayerLoc()->nx;\n\tint nx2 = layer2->getLayerLoc()->nx;\n\tint ny1 = layer1->getLayerLoc()->ny;\n\tint ny2 = layer2->getLayerLoc()->ny;\n\tint nf1 = layer1->getLayerLoc()->nf;\n\tint nf2 = layer2->getLayerLoc()->nf;\n\tint nb1 = layer1->getLayerLoc()->nb;\n\tint nb2 = layer2->getLayerLoc()->nb;\n bool result = nx1==nx2 && ny1==ny2 && nf1==nf2 && nb1==nb2;\n if( !result ) {\n \tconst char * name1 = layer1->getName();\n \tconst char * name2 = layer2->getName();\n fprintf(stderr, \"Group \\\"%s\\\": Layers \\\"%s\\\" and \\\"%s\\\" do not have compatible sizes\\n\", name, name1, name2);\n int len1 = (int) strlen(name1);\n int len2 = (int) strlen(name2);\n int len = len1 >= len2 ? len1 : len2;\n fprintf(stderr, \"Layer \\\"%*s\\\": nx=%d, ny=%d, nf=%d, nb=%d\\n\", len, name1, nx1, ny1, nf1, nb1);\n fprintf(stderr, \"Layer \\\"%*s\\\": nx=%d, ny=%d, nf=%d, nb=%d\\n\", len, name2, nx2, ny2, nf2, nb2);\n }\n return result;\n} \/\/ end of PoolingGenConn::PoolingGenConn(HyPerLayer *, HyPerLayer *)\n\nint PoolingGenConn::getSlownessLayer(HyPerLayer ** l, const char * paramname) {\n int status = PV_SUCCESS;\n assert(slownessFlag);\n const char * slownessLayerName = parent->parameters()->stringValue(name, paramname, false);\n if( slownessLayerName == NULL ) {\n status = PV_FAILURE;\n fprintf(stderr, \"PoolingGenConn \\\"%s\\\": if slownessFlag is set, parameter \\\"%s\\\" must be set\\n\", name, paramname);\n }\n if( status == PV_SUCCESS ) {\n *l = parent->getLayerFromName(slownessLayerName);\n if( *l == NULL ) {\n status = PV_FAILURE;\n fprintf(stderr, \"PoolingGenConn \\\"%s\\\": %s layer \\\"%s\\\" was not found\\n\", name, paramname, slownessLayerName);\n }\n }\n return status;\n}\n\nint PoolingGenConn::updateWeights(int axonID) {\n int nPre = preSynapticLayer()->getNumNeurons();\n int nx = preSynapticLayer()->getLayerLoc()->nx;\n int ny = preSynapticLayer()->getLayerLoc()->ny;\n int nf = preSynapticLayer()->getLayerLoc()->nf;\n int pad = preSynapticLayer()->getLayerLoc()->nb;\n for(int kPre=0; kPregetCLayer()->activity->data[kExt];\n pvdata_t preact2 = getPre2()->getCLayer()->activity->data[kExt];\n PVPatch * weights = getWeights(kPre,axonID);\n int nyp = weights->ny;\n int nk = weights->nx * nfp;\n pvdata_t * postactRef = &(postSynapticLayer()->getCLayer()->activity->data[offset]);\n pvdata_t * postact2Ref = &(getPost2()->getCLayer()->activity->data[offset]);\n int sya = getPostNonextStrides()->sy;\n pvdata_t * wtpatch = get_wData(axonID, kExt); \/\/ weights->data;\n int syw = syp;\n int lineoffsetw = weights->offset;\n int lineoffseta = 0;\n for( int y=0; ygetCLayer()->activity->data[kExt];\n PVPatch * weights = getWeights(kPre,axonID);\n int nyp = weights->ny;\n int nk = weights->nx * nfp;\n pvdata_t * postactRef = &(slownessPost->getCLayer()->activity->data[offset]);\n int sya = getPostNonextStrides()->sy;\n pvdata_t * wtpatch = get_wData(axonID, kExt); \/\/ weights->data;\n int syw = syp;\n for( int y=0; ygetKernelPatch(axonID, kPatch);\n pvdata_t * wtpatch = get_wDataHead(axonID, kPatch); \/\/ weights->data;\n int nk = nxp * nfp;\n int syw = nxp*nfp;\n for( int y=0; y < nyp; y++ ) {\n int lineoffsetw = 0;\n for( int k=0; ksimulationTime();\n\n return PV_SUCCESS;\n}\n\n} \/\/ end namespace PV\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qcontactmanager.h\"\n#include \"qcontactmanager_p.h\"\n#include \"qcontactmanagerengine.h\"\n#include \"qcontactmanagerenginefactory.h\"\n#include \"qcontactmanagerenginev2wrapper_p.h\"\n\n#include \"qcontact_p.h\"\n\n#include \"qcontactaction.h\"\n#include \"qcontactactiondescriptor.h\"\n#ifdef QT_SIMULATOR\n#include \"qcontactsimulatorbackend_p.h\"\n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\n#if defined(Q_OS_SYMBIAN)\n# include \n#endif\n\n#include \"qcontactmemorybackend_p.h\"\n#include \"qcontactinvalidbackend_p.h\"\n#include \"qmobilitypluginsearch.h\"\n\nQTM_BEGIN_NAMESPACE\n\n\/* Shared QContactManager stuff here, default engine stuff below *\/\nQHash QContactManagerData::m_engines;\nQSet QContactManagerData::m_aliveEngines;\nQList QContactManagerData::m_actionManagers;\n\nbool QContactManagerData::m_discoveredStatic;\nQStringList QContactManagerData::m_pluginPaths;\n\nstatic void qContactsCleanEngines()\n{\n \/\/ This is complicated by needing to remove any engines before we unload factories\n foreach(QContactManager* manager, QContactManagerData::m_aliveEngines) {\n \/\/ We don't delete the managers here, we just kill their engines\n \/\/ and replace it with an invalid engine (for safety :\/)\n QContactManagerData* d = QContactManagerData::managerData(manager);\n delete d->m_engine;\n d->m_engine = new QContactInvalidEngine();\n }\n\n QList factories = QContactManagerData::m_engines.values();\n\n for (int i=0; i < factories.count(); i++) {\n delete factories.at(i);\n }\n QContactManagerData::m_engines.clear();\n QContactManagerData::m_actionManagers.clear();\n QContactManagerData::m_aliveEngines.clear();\n}\n\nstatic int parameterValue(const QMap& parameters, const char* key, int defaultValue)\n{\n if (parameters.contains(QString::fromAscii(key))) {\n bool ok;\n int version = parameters.value(QString::fromAscii(key)).toInt(&ok);\n\n if (ok)\n return version;\n }\n return defaultValue;\n}\n\nvoid QContactManagerData::createEngine(const QString& managerName, const QMap& parameters)\n{\n m_engine = 0;\n\n QString builtManagerName = managerName.isEmpty() ? QContactManager::availableManagers().value(0) : managerName;\n if (builtManagerName == QLatin1String(\"memory\")) {\n QContactManagerEngine* engine = QContactMemoryEngine::createMemoryEngine(parameters);\n m_engine = new QContactManagerEngineV2Wrapper(engine);\n m_signalSource = engine;\n#ifdef QT_SIMULATOR\n } else if (builtManagerName == QLatin1String(\"simulator\")) {\n QContactManagerEngine* engine = QContactSimulatorEngine::createSimulatorEngine(parameters);\n m_engine = new QContactManagerEngineV2Wrapper(engine);\n m_signalSource = engine;\n#endif\n } else {\n int implementationVersion = parameterValue(parameters, QTCONTACTS_IMPLEMENTATION_VERSION_NAME, -1);\n\n bool found = false;\n bool loadedDynamic = false;\n\n \/* First check static factories *\/\n loadStaticFactories();\n\n \/* See if we got a fast hit *\/\n QList factories = m_engines.values(builtManagerName);\n m_lastError = QContactManager::NoError;\n\n while(!found) {\n foreach (QContactManagerEngineFactory* f, factories) {\n QList versions = f->supportedImplementationVersions();\n if (implementationVersion == -1 ||\/\/no given implementation version required\n versions.isEmpty() || \/\/the manager engine factory does not report any version\n versions.contains(implementationVersion)) {\n QContactManagerEngine* engine = f->engine(parameters, &m_lastError);\n \/\/ if it's a V2, use it\n m_engine = qobject_cast(engine);\n if (!m_engine && engine) {\n \/\/ Nope, v1, so wrap it\n m_engine = new QContactManagerEngineV2Wrapper(engine);\n m_signalSource = engine;\n } else {\n m_signalSource = m_engine; \/\/ use the v2 engine directly\n }\n found = true;\n break;\n }\n }\n\n \/\/ Break if found or if this is the second time through\n if (loadedDynamic || found)\n break;\n\n \/\/ otherwise load dynamic factories and reloop\n loadFactories();\n factories = m_engines.values(builtManagerName);\n loadedDynamic = true;\n }\n\n \/\/ XXX remove this\n \/\/ the engine factory could lie to us, so check the real implementation version\n if (m_engine && (implementationVersion != -1 && m_engine->managerVersion() != implementationVersion)) {\n m_lastError = QContactManager::VersionMismatchError;\n m_signalSource = m_engine = 0;\n }\n\n if (!m_engine) {\n if (m_lastError == QContactManager::NoError)\n m_lastError = QContactManager::DoesNotExistError;\n m_signalSource = m_engine = new QContactInvalidEngine();\n }\n }\n}\n\n\nvoid QContactManagerData::loadStaticFactories()\n{\n if (!m_discoveredStatic) {\n#if !defined QT_NO_DEBUG\n const bool showDebug = qgetenv(\"QT_DEBUG_PLUGINS\").toInt() > 0;\n#endif\n\n m_discoveredStatic = true;\n\n \/* Clean stuff up at the end *\/\n qAddPostRoutine(qContactsCleanEngines);\n\n \/* Loop over all the static plugins *\/\n QObjectList staticPlugins = QPluginLoader::staticInstances();\n for (int i=0; i < staticPlugins.count(); i++ ){\n QContactManagerEngineFactory *f = qobject_cast(staticPlugins.at(i));\n if (f) {\n QString name = f->managerName();\n#if !defined QT_NO_DEBUG\n if (showDebug)\n qDebug() << \"Static: found an engine plugin\" << f << \"with name\" << name;\n#endif\n if (name != QLatin1String(\"memory\") && name != QLatin1String(\"invalid\") && !name.isEmpty()) {\n \/\/ we also need to ensure that we haven't already loaded this factory.\n if (m_engines.keys().contains(name)) {\n qWarning() << \"Static contacts plugin\" << name << \"has the same name as a currently loaded plugin; ignored\";\n } else {\n m_engines.insertMulti(name, f);\n }\n } else {\n qWarning() << \"Static contacts plugin with reserved name\" << name << \"ignored\";\n }\n }\n }\n }\n}\n\n\n\/* Plugin loader *\/\nvoid QContactManagerData::loadFactories()\n{\n#if !defined QT_NO_DEBUG\n const bool showDebug = qgetenv(\"QT_DEBUG_PLUGINS\").toInt() > 0;\n#endif\n\n \/\/ Always do this..\n loadStaticFactories();\n\n \/\/ But only load dynamic plugins when the paths change\n QStringList paths = QCoreApplication::libraryPaths();\n#ifdef QTM_PLUGIN_PATH\n paths << QLatin1String(QTM_PLUGIN_PATH);\n#endif\n\n if (paths != m_pluginPaths) {\n m_pluginPaths = paths;\n\n QStringList plugins = mobilityPlugins(QLatin1String(\"contacts\"));\n\n \/* Now discover the dynamic plugins *\/\n for (int i=0; i < plugins.count(); i++) {\n QPluginLoader qpl(plugins.at(i));\n\n#if !defined QT_NO_DEBUG\n if (showDebug)\n qDebug() << \"Loading plugin\" << plugins.at(i);\n#endif\n\n QContactManagerEngineFactory *f = qobject_cast(qpl.instance());\n QContactActionManagerPlugin *m = qobject_cast(qpl.instance());\n\n if (f) {\n QString name = f->managerName();\n#if !defined QT_NO_DEBUG\n if (showDebug)\n qDebug() << \"Dynamic: found a contact engine plugin\" << f << \"with name\" << name;\n#endif\n if (name != QLatin1String(\"memory\") && name != QLatin1String(\"invalid\") && !name.isEmpty()) {\n \/\/ we also need to ensure that we haven't already loaded this factory.\n if (m_engines.keys().contains(name)) {\n qWarning() << \"Contacts plugin\" << plugins.at(i) << \"has the same name as currently loaded plugin\" << name << \"; ignored\";\n } else {\n m_engines.insertMulti(name, f);\n }\n } else {\n qWarning() << \"Contacts plugin\" << plugins.at(i) << \"with reserved name\" << name << \"ignored\";\n }\n }\n\n if (m) {\n m_actionManagers.append(m);\n }\n\n \/* Debugging *\/\n#if !defined QT_NO_DEBUG\n if (showDebug && !f && !m) {\n qDebug() << \"Unknown plugin:\" << qpl.errorString();\n if (qpl.instance()) {\n qDebug() << \"[qobject:\" << qpl.instance() << \"]\";\n }\n }\n#endif\n }\n \n QStringList engineNames;\n foreach (QContactManagerEngineFactory* f, m_engines.values()) {\n QStringList versions;\n foreach (int v, f->supportedImplementationVersions()) {\n versions << QString::fromAscii(\"%1\").arg(v);\n }\n engineNames << QString::fromAscii(\"%1[%2]\").arg(f->managerName()).arg(versions.join(QString::fromAscii(\",\")));\n }\n#if !defined QT_NO_DEBUG\n if (showDebug) {\n qDebug() << \"Found engines:\" << engineNames;\n qDebug() << \"Found action engines:\" << m_actionManagers;\n }\n#endif\n }\n}\n\n\/\/ Observer stuff\n\nvoid QContactManagerData::registerObserver(QContactManager* manager, QContactObserver* observer)\n{\n if (!manager)\n return;\n\n QContactManagerData* d = QContactManagerData::get(manager);\n\n d->m_observerForContact.insert(observer->contactLocalId(), observer);\n\n \/\/ If this is the first observer, connect to the engine too\n if (d->m_observerForContact.size() == 1) {\n \/\/ This takes advantage of the manager connectNotify code\n QObject::connect(manager, SIGNAL(contactsChanged(QList)),\n manager, SLOT(_q_contactsUpdated(QList)));\n QObject::connect(manager, SIGNAL(contactsRemoved(QList)),\n manager, SLOT(_q_contactsDeleted(QList)));\n }\n}\n\nvoid QContactManagerData::unregisterObserver(QContactManager* manager, QContactObserver* observer)\n{\n Q_ASSERT(manager);\n\n QContactManagerData* d = QContactManagerData::get(manager);\n\n QContactLocalId key = d->m_observerForContact.key(observer);\n if (key != 0) {\n d->m_observerForContact.remove(key, observer);\n\n \/\/ If there are now no more observers, disconnect from the engine\n if (d->m_observerForContact.size() == 0) {\n \/\/ This takes advantage of the manager disconnectNotify code\n QObject::disconnect(manager, SIGNAL(contactsChanged(QList)),\n manager, SLOT(_q_contactsUpdated(QList)));\n QObject::disconnect(manager, SIGNAL(contactsRemoved(QList)),\n manager, SLOT(_q_contactsDeleted(QList)));\n }\n }\n}\n\nvoid QContactManagerData::_q_contactsUpdated(const QList& ids)\n{\n foreach (QContactLocalId id, ids) {\n QList observers = m_observerForContact.values(id);\n foreach (QContactObserver* observer, observers) {\n QMetaObject::invokeMethod(observer, \"contactChanged\");\n }\n }\n}\n\nvoid QContactManagerData::_q_contactsDeleted(const QList& ids)\n{\n foreach (QContactLocalId id, ids) {\n QList observers = m_observerForContact.values(id);\n foreach (QContactObserver* observer, observers) {\n QMetaObject::invokeMethod(observer, \"contactRemoved\");\n }\n }\n}\n\n\/\/ trampolines for private classes\nQContactManagerData* QContactManagerData::get(const QContactManager* manager)\n{\n return manager->d;\n}\n\nQContactManagerEngineV2* QContactManagerData::engine(const QContactManager* manager)\n{\n if (manager)\n return manager->d->m_engine;\n return 0;\n}\n\nQTM_END_NAMESPACE\n\nFixing double delete segfault in qContactsCleanEngines\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qcontactmanager.h\"\n#include \"qcontactmanager_p.h\"\n#include \"qcontactmanagerengine.h\"\n#include \"qcontactmanagerenginefactory.h\"\n#include \"qcontactmanagerenginev2wrapper_p.h\"\n\n#include \"qcontact_p.h\"\n\n#include \"qcontactaction.h\"\n#include \"qcontactactiondescriptor.h\"\n#ifdef QT_SIMULATOR\n#include \"qcontactsimulatorbackend_p.h\"\n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\n#if defined(Q_OS_SYMBIAN)\n# include \n#endif\n\n#include \"qcontactmemorybackend_p.h\"\n#include \"qcontactinvalidbackend_p.h\"\n#include \"qmobilitypluginsearch.h\"\n\nQTM_BEGIN_NAMESPACE\n\n\/* Shared QContactManager stuff here, default engine stuff below *\/\nQHash QContactManagerData::m_engines;\nQSet QContactManagerData::m_aliveEngines;\nQList QContactManagerData::m_actionManagers;\n\nbool QContactManagerData::m_discoveredStatic;\nQStringList QContactManagerData::m_pluginPaths;\n\nstatic void qContactsCleanEngines()\n{\n \/\/ This is complicated by needing to remove any engines before we unload factories\n \/\/ guard pointers as one engine could be parent of another manager and cause doubledelete\n QList > aliveManagers;\n foreach(QContactManager* manager, QContactManagerData::m_aliveEngines) {\n aliveManagers << QWeakPointer(manager);\n }\n\n foreach(QWeakPointer manager, aliveManagers) {\n if (not manager) {\n \/\/ deleting engine of one manager, could cause deleting next manager in list (aggregation case)\n continue;\n }\n \/\/ We don't delete the managers here, we just kill their engines\n \/\/ and replace it with an invalid engine (for safety :\/)\n QContactManagerData* d = QContactManagerData::managerData(manager.data());\n\n delete d->m_engine;\n d->m_engine = new QContactInvalidEngine();\n }\n\n QList factories = QContactManagerData::m_engines.values();\n\n for (int i=0; i < factories.count(); i++) {\n delete factories.at(i);\n }\n QContactManagerData::m_engines.clear();\n QContactManagerData::m_actionManagers.clear();\n QContactManagerData::m_aliveEngines.clear();\n}\n\nstatic int parameterValue(const QMap& parameters, const char* key, int defaultValue)\n{\n if (parameters.contains(QString::fromAscii(key))) {\n bool ok;\n int version = parameters.value(QString::fromAscii(key)).toInt(&ok);\n\n if (ok)\n return version;\n }\n return defaultValue;\n}\n\nvoid QContactManagerData::createEngine(const QString& managerName, const QMap& parameters)\n{\n m_engine = 0;\n\n QString builtManagerName = managerName.isEmpty() ? QContactManager::availableManagers().value(0) : managerName;\n if (builtManagerName == QLatin1String(\"memory\")) {\n QContactManagerEngine* engine = QContactMemoryEngine::createMemoryEngine(parameters);\n m_engine = new QContactManagerEngineV2Wrapper(engine);\n m_signalSource = engine;\n#ifdef QT_SIMULATOR\n } else if (builtManagerName == QLatin1String(\"simulator\")) {\n QContactManagerEngine* engine = QContactSimulatorEngine::createSimulatorEngine(parameters);\n m_engine = new QContactManagerEngineV2Wrapper(engine);\n m_signalSource = engine;\n#endif\n } else {\n int implementationVersion = parameterValue(parameters, QTCONTACTS_IMPLEMENTATION_VERSION_NAME, -1);\n\n bool found = false;\n bool loadedDynamic = false;\n\n \/* First check static factories *\/\n loadStaticFactories();\n\n \/* See if we got a fast hit *\/\n QList factories = m_engines.values(builtManagerName);\n m_lastError = QContactManager::NoError;\n\n while(!found) {\n foreach (QContactManagerEngineFactory* f, factories) {\n QList versions = f->supportedImplementationVersions();\n if (implementationVersion == -1 ||\/\/no given implementation version required\n versions.isEmpty() || \/\/the manager engine factory does not report any version\n versions.contains(implementationVersion)) {\n QContactManagerEngine* engine = f->engine(parameters, &m_lastError);\n \/\/ if it's a V2, use it\n m_engine = qobject_cast(engine);\n if (!m_engine && engine) {\n \/\/ Nope, v1, so wrap it\n m_engine = new QContactManagerEngineV2Wrapper(engine);\n m_signalSource = engine;\n } else {\n m_signalSource = m_engine; \/\/ use the v2 engine directly\n }\n found = true;\n break;\n }\n }\n\n \/\/ Break if found or if this is the second time through\n if (loadedDynamic || found)\n break;\n\n \/\/ otherwise load dynamic factories and reloop\n loadFactories();\n factories = m_engines.values(builtManagerName);\n loadedDynamic = true;\n }\n\n \/\/ XXX remove this\n \/\/ the engine factory could lie to us, so check the real implementation version\n if (m_engine && (implementationVersion != -1 && m_engine->managerVersion() != implementationVersion)) {\n m_lastError = QContactManager::VersionMismatchError;\n m_signalSource = m_engine = 0;\n }\n\n if (!m_engine) {\n if (m_lastError == QContactManager::NoError)\n m_lastError = QContactManager::DoesNotExistError;\n m_signalSource = m_engine = new QContactInvalidEngine();\n }\n }\n}\n\n\nvoid QContactManagerData::loadStaticFactories()\n{\n if (!m_discoveredStatic) {\n#if !defined QT_NO_DEBUG\n const bool showDebug = qgetenv(\"QT_DEBUG_PLUGINS\").toInt() > 0;\n#endif\n\n m_discoveredStatic = true;\n\n \/* Clean stuff up at the end *\/\n qAddPostRoutine(qContactsCleanEngines);\n\n \/* Loop over all the static plugins *\/\n QObjectList staticPlugins = QPluginLoader::staticInstances();\n for (int i=0; i < staticPlugins.count(); i++ ){\n QContactManagerEngineFactory *f = qobject_cast(staticPlugins.at(i));\n if (f) {\n QString name = f->managerName();\n#if !defined QT_NO_DEBUG\n if (showDebug)\n qDebug() << \"Static: found an engine plugin\" << f << \"with name\" << name;\n#endif\n if (name != QLatin1String(\"memory\") && name != QLatin1String(\"invalid\") && !name.isEmpty()) {\n \/\/ we also need to ensure that we haven't already loaded this factory.\n if (m_engines.keys().contains(name)) {\n qWarning() << \"Static contacts plugin\" << name << \"has the same name as a currently loaded plugin; ignored\";\n } else {\n m_engines.insertMulti(name, f);\n }\n } else {\n qWarning() << \"Static contacts plugin with reserved name\" << name << \"ignored\";\n }\n }\n }\n }\n}\n\n\n\/* Plugin loader *\/\nvoid QContactManagerData::loadFactories()\n{\n#if !defined QT_NO_DEBUG\n const bool showDebug = qgetenv(\"QT_DEBUG_PLUGINS\").toInt() > 0;\n#endif\n\n \/\/ Always do this..\n loadStaticFactories();\n\n \/\/ But only load dynamic plugins when the paths change\n QStringList paths = QCoreApplication::libraryPaths();\n#ifdef QTM_PLUGIN_PATH\n paths << QLatin1String(QTM_PLUGIN_PATH);\n#endif\n\n if (paths != m_pluginPaths) {\n m_pluginPaths = paths;\n\n QStringList plugins = mobilityPlugins(QLatin1String(\"contacts\"));\n\n \/* Now discover the dynamic plugins *\/\n for (int i=0; i < plugins.count(); i++) {\n QPluginLoader qpl(plugins.at(i));\n\n#if !defined QT_NO_DEBUG\n if (showDebug)\n qDebug() << \"Loading plugin\" << plugins.at(i);\n#endif\n\n QContactManagerEngineFactory *f = qobject_cast(qpl.instance());\n QContactActionManagerPlugin *m = qobject_cast(qpl.instance());\n\n if (f) {\n QString name = f->managerName();\n#if !defined QT_NO_DEBUG\n if (showDebug)\n qDebug() << \"Dynamic: found a contact engine plugin\" << f << \"with name\" << name;\n#endif\n if (name != QLatin1String(\"memory\") && name != QLatin1String(\"invalid\") && !name.isEmpty()) {\n \/\/ we also need to ensure that we haven't already loaded this factory.\n if (m_engines.keys().contains(name)) {\n qWarning() << \"Contacts plugin\" << plugins.at(i) << \"has the same name as currently loaded plugin\" << name << \"; ignored\";\n } else {\n m_engines.insertMulti(name, f);\n }\n } else {\n qWarning() << \"Contacts plugin\" << plugins.at(i) << \"with reserved name\" << name << \"ignored\";\n }\n }\n\n if (m) {\n m_actionManagers.append(m);\n }\n\n \/* Debugging *\/\n#if !defined QT_NO_DEBUG\n if (showDebug && !f && !m) {\n qDebug() << \"Unknown plugin:\" << qpl.errorString();\n if (qpl.instance()) {\n qDebug() << \"[qobject:\" << qpl.instance() << \"]\";\n }\n }\n#endif\n }\n \n QStringList engineNames;\n foreach (QContactManagerEngineFactory* f, m_engines.values()) {\n QStringList versions;\n foreach (int v, f->supportedImplementationVersions()) {\n versions << QString::fromAscii(\"%1\").arg(v);\n }\n engineNames << QString::fromAscii(\"%1[%2]\").arg(f->managerName()).arg(versions.join(QString::fromAscii(\",\")));\n }\n#if !defined QT_NO_DEBUG\n if (showDebug) {\n qDebug() << \"Found engines:\" << engineNames;\n qDebug() << \"Found action engines:\" << m_actionManagers;\n }\n#endif\n }\n}\n\n\/\/ Observer stuff\n\nvoid QContactManagerData::registerObserver(QContactManager* manager, QContactObserver* observer)\n{\n if (!manager)\n return;\n\n QContactManagerData* d = QContactManagerData::get(manager);\n\n d->m_observerForContact.insert(observer->contactLocalId(), observer);\n\n \/\/ If this is the first observer, connect to the engine too\n if (d->m_observerForContact.size() == 1) {\n \/\/ This takes advantage of the manager connectNotify code\n QObject::connect(manager, SIGNAL(contactsChanged(QList)),\n manager, SLOT(_q_contactsUpdated(QList)));\n QObject::connect(manager, SIGNAL(contactsRemoved(QList)),\n manager, SLOT(_q_contactsDeleted(QList)));\n }\n}\n\nvoid QContactManagerData::unregisterObserver(QContactManager* manager, QContactObserver* observer)\n{\n Q_ASSERT(manager);\n\n QContactManagerData* d = QContactManagerData::get(manager);\n\n QContactLocalId key = d->m_observerForContact.key(observer);\n if (key != 0) {\n d->m_observerForContact.remove(key, observer);\n\n \/\/ If there are now no more observers, disconnect from the engine\n if (d->m_observerForContact.size() == 0) {\n \/\/ This takes advantage of the manager disconnectNotify code\n QObject::disconnect(manager, SIGNAL(contactsChanged(QList)),\n manager, SLOT(_q_contactsUpdated(QList)));\n QObject::disconnect(manager, SIGNAL(contactsRemoved(QList)),\n manager, SLOT(_q_contactsDeleted(QList)));\n }\n }\n}\n\nvoid QContactManagerData::_q_contactsUpdated(const QList& ids)\n{\n foreach (QContactLocalId id, ids) {\n QList observers = m_observerForContact.values(id);\n foreach (QContactObserver* observer, observers) {\n QMetaObject::invokeMethod(observer, \"contactChanged\");\n }\n }\n}\n\nvoid QContactManagerData::_q_contactsDeleted(const QList& ids)\n{\n foreach (QContactLocalId id, ids) {\n QList observers = m_observerForContact.values(id);\n foreach (QContactObserver* observer, observers) {\n QMetaObject::invokeMethod(observer, \"contactRemoved\");\n }\n }\n}\n\n\/\/ trampolines for private classes\nQContactManagerData* QContactManagerData::get(const QContactManager* manager)\n{\n return manager->d;\n}\n\nQContactManagerEngineV2* QContactManagerData::engine(const QContactManager* manager)\n{\n if (manager)\n return manager->d->m_engine;\n return 0;\n}\n\nQTM_END_NAMESPACE\n\n<|endoftext|>"} {"text":"\/*\n * ConnectedComponents.cpp\n *\n * Created on: Dec 16, 2013\n * Author: cls\n *\/\n\n#include \"ConnectedComponents.h\"\n\n#include \n\nnamespace NetworKit {\n\nConnectedComponents::ConnectedComponents() {\n\n}\n\nConnectedComponents::~ConnectedComponents() {\n\n}\n\nvoid ConnectedComponents::run(const Graph& G) {\n\t\/\/ calculate connected components by label propagation\n\tcount z = G.numberOfNodes();\n\tthis->component = std::vector(z, none);\n\n\tG.parallelForNodes([&](node v){\n\t\tcomponent[v] = v;\n\t});\n\n\tbool change = false;\n\tdo {\n\t\tDEBUG(\"next iteration\");\n\t\tchange = false;\n\t\tG.parallelForNodes([&](node u) {\n\t\t\tG.forNeighborsOf(u, [&](node v) {\n\t\t\t\tif (component[v] < component[u]) {\n\t\t\t\t\tcomponent[u] = component[v];\n\t\t\t\t\tchange = true;\n\t\t\t\t}\n\t\t\t});\n\t\t\t\/\/ minimum neighboring label assigned\n\t\t});\n\t} while (change);\n}\n\n\nstd::vector ConnectedComponents::getComponentData() {\n\treturn this->component;\n}\n\nstd::map ConnectedComponents::getComponentSizes() {\n\tstd::map componentSize;\n\tfor (node u = 0; u < component.size(); ++u) {\n\t\tif (component[u] != none) {\n\t\t\tcomponentSize[component[u]] += 1;\n\t\t}\n\t}\n\treturn componentSize;\n}\n\n\nstd::vector ConnectedComponents::getComponent(index label) {\n\tstd::vector nodesOfComponent;\n\tfor (node u = 0; u < component.size(); ++u) {\n\t\tif (this->component[u] == label) {\n\t\t\tnodesOfComponent.push_back(u);\n\t\t}\n\t}\n\treturn nodesOfComponent;\n}\n\ncount ConnectedComponents::numberOfComponents() {\n\tcount nc = 0;\n\tstd::set componentLabels;\n\tfor (index i = 0; i < component.size(); ++i) {\n\t\tindex c = component[i];\n\t\tif ((componentLabels.find(c) == componentLabels.end()) && (c != none)) { \/\/ label not encountered yet\n\t\t\tcomponentLabels.insert(c);\n\t\t\tnc++;\n\t\t}\n\t}\n\treturn nc;\n}\n\ncount ConnectedComponents::componentOfNode(node u) {\n\tassert (component[u] != none);\n\treturn component[u];\n}\n\n}\n\nbetter load balancing for ConnectedComponents\/*\n * ConnectedComponents.cpp\n *\n * Created on: Dec 16, 2013\n * Author: cls\n *\/\n\n#include \"ConnectedComponents.h\"\n\n#include \n\nnamespace NetworKit {\n\nConnectedComponents::ConnectedComponents() {\n\n}\n\nConnectedComponents::~ConnectedComponents() {\n\n}\n\nvoid ConnectedComponents::run(const Graph& G) {\n\t\/\/ calculate connected components by label propagation\n\tcount z = G.numberOfNodes();\n\tthis->component = std::vector(z, none);\n\n\tG.parallelForNodes([&](node v){\n\t\tcomponent[v] = v;\n\t});\n\n\tbool change = false;\n\tdo {\n\t\tDEBUG(\"next iteration\");\n\t\tchange = false;\n\t\tG.balancedParallelForNodes([&](node u) {\n\t\t\tG.forNeighborsOf(u, [&](node v) {\n\t\t\t\tif (component[v] < component[u]) {\n\t\t\t\t\tcomponent[u] = component[v];\n\t\t\t\t\tchange = true;\n\t\t\t\t}\n\t\t\t});\n\t\t\t\/\/ minimum neighboring label assigned\n\t\t});\n\t} while (change);\n}\n\n\nstd::vector ConnectedComponents::getComponentData() {\n\treturn this->component;\n}\n\nstd::map ConnectedComponents::getComponentSizes() {\n\tstd::map componentSize;\n\tfor (node u = 0; u < component.size(); ++u) {\n\t\tif (component[u] != none) {\n\t\t\tcomponentSize[component[u]] += 1;\n\t\t}\n\t}\n\treturn componentSize;\n}\n\n\nstd::vector ConnectedComponents::getComponent(index label) {\n\tstd::vector nodesOfComponent;\n\tfor (node u = 0; u < component.size(); ++u) {\n\t\tif (this->component[u] == label) {\n\t\t\tnodesOfComponent.push_back(u);\n\t\t}\n\t}\n\treturn nodesOfComponent;\n}\n\ncount ConnectedComponents::numberOfComponents() {\n\tcount nc = 0;\n\tstd::set componentLabels;\n\tfor (index i = 0; i < component.size(); ++i) {\n\t\tindex c = component[i];\n\t\tif ((componentLabels.find(c) == componentLabels.end()) && (c != none)) { \/\/ label not encountered yet\n\t\t\tcomponentLabels.insert(c);\n\t\t\tnc++;\n\t\t}\n\t}\n\treturn nc;\n}\n\ncount ConnectedComponents::componentOfNode(node u) {\n\tassert (component[u] != none);\n\treturn component[u];\n}\n\n}\n\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2009 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n\n\/* interface header *\/\n#include \"bzfio.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n#include \n#include \n#include \n#ifdef HAVE_UNISTD_H\n# include \n#endif\n#ifdef __BEOS__\n# include \n#endif\n#if !defined(_WIN32)\n# include \n# include \n#else \/* !defined(_WIN32) *\/\n# include \n#endif\n\n\n\/** global used to control logging level across all applications *\/\nint debugLevel = 0;\n\nstatic bool doMicros = false;\nstatic bool doTimestamp = false;\n\nstatic int callProcDepth = 0;\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\nstruct LoggingProcPair {\n LoggingProcPair(LoggingProc p, void* d)\n : proc(p)\n , data(d)\n {}\n bool operator==(const LoggingProcPair& lpp) const {\n return (proc == lpp.proc) && (data == lpp.data);\n }\n LoggingProc proc;\n void* data;\n};\ntypedef std::vector LoggingProcVec;\nstatic LoggingProcVec loggingProcs;\n\n\nbool registerLoggingProc(LoggingProc proc, void* data)\n{\n if (proc == NULL) {\n return false;\n }\n LoggingProcPair lpp(proc, data);\n for (size_t i = 0; i < loggingProcs.size(); i++) {\n if (lpp == loggingProcs[i]) {\n return false; \/\/ already registered\n }\n }\n loggingProcs.push_back(lpp);\n return true;\n}\n\n\nbool unregisterLoggingProc(LoggingProc proc, void* data)\n{\n if (callProcDepth != 0) {\n logDebugMessage(0, \"error: unregisterLoggingProc() used in a LoggingProc\");\n return false;\n }\n LoggingProcPair lpp(proc, data);\n for (size_t i = 0; i < loggingProcs.size(); i++) {\n if (lpp == loggingProcs[i]) {\n loggingProcs.erase(loggingProcs.begin() + i);\n return true;\n }\n }\n return false;\n}\n\n\nstatic void callProcs(int level, const std::string& msg)\n{\n callProcDepth++;\n for (size_t i = 0; i < loggingProcs.size(); i++) {\n const LoggingProcPair& lpp = loggingProcs[i];\n lpp.proc(level, msg, lpp.data);\n }\n callProcDepth--;\n}\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\nvoid setDebugTimestamp(bool enable, bool micros)\n{\n#ifdef _WIN32\n micros = false;\n#endif\n doTimestamp = enable;\n doMicros = micros;\n}\n\n\nstatic const int tsBufferSize = 26;\n\nstatic char *timestamp(char *buf, bool micros)\n{\n struct tm *tm;\n if (micros) {\n#if !defined(_WIN32)\n struct timeval tv;\n gettimeofday(&tv, NULL);\n tm = localtime((const time_t *)&tv.tv_sec);\n snprintf(buf, tsBufferSize, \"%04d-%02d-%02d %02d:%02d:%02ld.%06ld: \",\n tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,\n tm->tm_hour, tm->tm_min, (long)tm->tm_sec, (long)tv.tv_usec);\n#endif\n } else {\n time_t tt;\n time(&tt);\n tm = localtime(&tt);\n snprintf(buf, tsBufferSize, \"%04d-%02d-%02d %02d:%02d:%02d: \",\n tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,\n tm->tm_hour, tm->tm_min, tm->tm_sec);\n }\n return buf;\n}\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\nstatic void realLogDebugMessage(int level, const char* text)\n{\n if ((debugLevel >= level) || (level == 0)) {\n#if defined(_MSC_VER)\n if (doTimestamp) {\n char tsbuf[tsBufferSize] = { 0 };\n W32_DEBUG_TRACE(timestamp(tsbuf, false));\n }\n W32_DEBUG_TRACE(text);\n#else\n if (doTimestamp) {\n char tsbuf[tsBufferSize] = { 0 };\n std::cout << timestamp(tsbuf, doMicros);\n }\n std::cout << text;\n fflush(stdout);\n#endif\n\n callProcs(level, text);\n }\n}\n\n\nvoid logDebugMessageArgs(int level, const char* fmt, va_list ap)\n{\n char buffer[8192] = { 0 };\n\n if (!fmt) {\n return;\n }\n\n vsnprintf(buffer, sizeof(buffer), fmt, ap);\n\n realLogDebugMessage(level, buffer);\n}\n\n\nvoid logDebugMessage(int level, const char* fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n logDebugMessageArgs(level, fmt, ap);\n va_end(ap);\n}\n\n\nvoid logDebugMessage(int level, const std::string &text)\n{\n if (text.empty()) {\n return;\n }\n realLogDebugMessage(level, text.c_str());\n}\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nbzfs: Fix timestamp buffer size so -ts micros output fits\/* bzflag\n * Copyright (c) 1993 - 2009 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"common.h\"\n\n\/* interface header *\/\n#include \"bzfio.h\"\n\n\/* system implementation headers *\/\n#include \n#include \n#include \n#include \n#include \n#ifdef HAVE_UNISTD_H\n# include \n#endif\n#ifdef __BEOS__\n# include \n#endif\n#if !defined(_WIN32)\n# include \n# include \n#else \/* !defined(_WIN32) *\/\n# include \n#endif\n\n\n\/** global used to control logging level across all applications *\/\nint debugLevel = 0;\n\nstatic bool doMicros = false;\nstatic bool doTimestamp = false;\n\nstatic int callProcDepth = 0;\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\nstruct LoggingProcPair {\n LoggingProcPair(LoggingProc p, void* d)\n : proc(p)\n , data(d)\n {}\n bool operator==(const LoggingProcPair& lpp) const {\n return (proc == lpp.proc) && (data == lpp.data);\n }\n LoggingProc proc;\n void* data;\n};\ntypedef std::vector LoggingProcVec;\nstatic LoggingProcVec loggingProcs;\n\n\nbool registerLoggingProc(LoggingProc proc, void* data)\n{\n if (proc == NULL) {\n return false;\n }\n LoggingProcPair lpp(proc, data);\n for (size_t i = 0; i < loggingProcs.size(); i++) {\n if (lpp == loggingProcs[i]) {\n return false; \/\/ already registered\n }\n }\n loggingProcs.push_back(lpp);\n return true;\n}\n\n\nbool unregisterLoggingProc(LoggingProc proc, void* data)\n{\n if (callProcDepth != 0) {\n logDebugMessage(0, \"error: unregisterLoggingProc() used in a LoggingProc\");\n return false;\n }\n LoggingProcPair lpp(proc, data);\n for (size_t i = 0; i < loggingProcs.size(); i++) {\n if (lpp == loggingProcs[i]) {\n loggingProcs.erase(loggingProcs.begin() + i);\n return true;\n }\n }\n return false;\n}\n\n\nstatic void callProcs(int level, const std::string& msg)\n{\n callProcDepth++;\n for (size_t i = 0; i < loggingProcs.size(); i++) {\n const LoggingProcPair& lpp = loggingProcs[i];\n lpp.proc(level, msg, lpp.data);\n }\n callProcDepth--;\n}\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\nvoid setDebugTimestamp(bool enable, bool micros)\n{\n#ifdef _WIN32\n micros = false;\n#endif\n doTimestamp = enable;\n doMicros = micros;\n}\n\n\nstatic const int tsBufferSize = 29;\n\nstatic char *timestamp(char *buf, bool micros)\n{\n struct tm *tm;\n if (micros) {\n#if !defined(_WIN32)\n struct timeval tv;\n gettimeofday(&tv, NULL);\n tm = localtime((const time_t *)&tv.tv_sec);\n snprintf(buf, tsBufferSize, \"%04d-%02d-%02d %02d:%02d:%02ld.%06ld: \",\n tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,\n tm->tm_hour, tm->tm_min, (long)tm->tm_sec, (long)tv.tv_usec);\n#endif\n } else {\n time_t tt;\n time(&tt);\n tm = localtime(&tt);\n snprintf(buf, tsBufferSize, \"%04d-%02d-%02d %02d:%02d:%02d: \",\n tm->tm_year+1900, tm->tm_mon+1, tm->tm_mday,\n tm->tm_hour, tm->tm_min, tm->tm_sec);\n }\n return buf;\n}\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\nstatic void realLogDebugMessage(int level, const char* text)\n{\n if ((debugLevel >= level) || (level == 0)) {\n#if defined(_MSC_VER)\n if (doTimestamp) {\n char tsbuf[tsBufferSize] = { 0 };\n W32_DEBUG_TRACE(timestamp(tsbuf, false));\n }\n W32_DEBUG_TRACE(text);\n#else\n if (doTimestamp) {\n char tsbuf[tsBufferSize] = { 0 };\n std::cout << timestamp(tsbuf, doMicros);\n }\n std::cout << text;\n fflush(stdout);\n#endif\n\n callProcs(level, text);\n }\n}\n\n\nvoid logDebugMessageArgs(int level, const char* fmt, va_list ap)\n{\n char buffer[8192] = { 0 };\n\n if (!fmt) {\n return;\n }\n\n vsnprintf(buffer, sizeof(buffer), fmt, ap);\n\n realLogDebugMessage(level, buffer);\n}\n\n\nvoid logDebugMessage(int level, const char* fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n logDebugMessageArgs(level, fmt, ap);\n va_end(ap);\n}\n\n\nvoid logDebugMessage(int level, const std::string &text)\n{\n if (text.empty()) {\n return;\n }\n realLogDebugMessage(level, text.c_str());\n}\n\n\n\/\/============================================================================\/\/\n\/\/============================================================================\/\/\n\n\/\/ Local Variables: ***\n\/\/ mode: C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/*!\n * \\author ddubois\n * \\date 28-Apr-18.\n *\/\n\n#ifndef NOVA_RENDERER_FRAMEBUFFER_MANAGER_H\n#define NOVA_RENDERER_FRAMEBUFFER_MANAGER_H\n\n#include \n#include \n#include \n#include \n#include \"..\/..\/util\/utils.hpp\"\n\nnamespace nova::renderer {\n class vulkan_render_engine;\n\n NOVA_EXCEPTION(swapchain_creation_failed);\n NOVA_EXCEPTION(present_failed);\n\n \/*!\n * \\brief Deals with the swapchain, yo\n *\n * Methods to get he next swapchain image and whatnot are found here\n *\n * You can even get the framebuffer constructed from the current swapchain. Wow!\n *\/\n class swapchain_manager {\n public:\n swapchain_manager(uint32_t num_swapchain_images,\n vulkan_render_engine& render_engine,\n glm::ivec2 window_dimensions,\n const std::vector& present_modes);\n\n void present_current_image(VkSemaphore wait_semaphores) const;\n\n \/*!\n * \\brief Acquires the next image in the swapchain, signalling the provided semaphore when the image is ready \n * to be rendered to\n * \n * \\param image_acquire_semaphore The semaphore to signal when the image is ready to be rendered to\n *\/\n void acquire_next_swapchain_image(VkSemaphore image_acquire_semaphore);\n\n void set_current_layout(VkImageLayout new_layout);\n\n VkFramebuffer get_current_framebuffer();\n VkFence get_current_frame_fence();\n\n VkImage get_current_image();\n VkImageLayout get_current_layout();\n [[nodiscard]] VkExtent2D get_swapchain_extent() const;\n [[nodiscard]] VkFormat get_swapchain_format() const;\n\n \/\/ I've had a lot of bugs with RAII so here's an explicit cleanup method\n void deinit();\n\n [[nodiscard]] uint32_t get_current_index() const;\n [[nodiscard]] uint32_t get_num_images() const;\n\n private:\n vulkan_render_engine& render_engine;\n\n VkSwapchainKHR swapchain{};\n VkExtent2D swapchain_extent;\n VkPresentModeKHR present_mode;\n VkFormat swapchain_format;\n\n std::vector framebuffers;\n std::vector swapchain_image_views;\n std::vector swapchain_images;\n std::vector swapchain_image_layouts;\n std::vector fences;\n\n uint32_t num_swapchain_images;\n uint32_t cur_swapchain_index = 0;\n\n static VkSurfaceFormatKHR choose_surface_format(const std::vector& formats);\n\n static VkPresentModeKHR choose_present_mode(const std::vector& modes);\n\n static VkExtent2D choose_surface_extent(const VkSurfaceCapabilitiesKHR& caps, const glm::ivec2& window_dimensions);\n\n void transition_swapchain_images_into_correct_layout(const std::vector& images) const;\n };\n} \/\/ namespace nova::renderer\n\n#endif \/\/ NOVA_RENDERER_FRAMEBUFFER_MANAGER_HReal format\/*!\n * \\author ddubois\n * \\date 28-Apr-18.\n *\/\n\n#ifndef NOVA_RENDERER_FRAMEBUFFER_MANAGER_H\n#define NOVA_RENDERER_FRAMEBUFFER_MANAGER_H\n\n#include \n#include \n#include \n#include \n#include \"..\/..\/util\/utils.hpp\"\n\nnamespace nova::renderer {\n class vulkan_render_engine;\n\n NOVA_EXCEPTION(swapchain_creation_failed);\n NOVA_EXCEPTION(present_failed);\n\n \/*!\n * \\brief Deals with the swapchain, yo\n *\n * Methods to get he next swapchain image and whatnot are found here\n *\n * You can even get the framebuffer constructed from the current swapchain. Wow!\n *\/\n class swapchain_manager {\n public:\n swapchain_manager(uint32_t num_swapchain_images,\n vulkan_render_engine& render_engine,\n glm::ivec2 window_dimensions,\n const std::vector& present_modes);\n\n void present_current_image(VkSemaphore wait_semaphores) const;\n\n \/*!\n * \\brief Acquires the next image in the swapchain, signalling the provided semaphore when the image is ready\n * to be rendered to\n *\n * \\param image_acquire_semaphore The semaphore to signal when the image is ready to be rendered to\n *\/\n void acquire_next_swapchain_image(VkSemaphore image_acquire_semaphore);\n\n void set_current_layout(VkImageLayout new_layout);\n\n VkFramebuffer get_current_framebuffer();\n VkFence get_current_frame_fence();\n\n VkImage get_current_image();\n VkImageLayout get_current_layout();\n [[nodiscard]] VkExtent2D get_swapchain_extent() const;\n [[nodiscard]] VkFormat get_swapchain_format() const;\n\n \/\/ I've had a lot of bugs with RAII so here's an explicit cleanup method\n void deinit();\n\n [[nodiscard]] uint32_t get_current_index() const;\n [[nodiscard]] uint32_t get_num_images() const;\n\n private:\n vulkan_render_engine& render_engine;\n\n VkSwapchainKHR swapchain{};\n VkExtent2D swapchain_extent;\n VkPresentModeKHR present_mode;\n VkFormat swapchain_format;\n\n std::vector framebuffers;\n std::vector swapchain_image_views;\n std::vector swapchain_images;\n std::vector swapchain_image_layouts;\n std::vector fences;\n\n uint32_t num_swapchain_images;\n uint32_t cur_swapchain_index = 0;\n\n static VkSurfaceFormatKHR choose_surface_format(const std::vector& formats);\n\n static VkPresentModeKHR choose_present_mode(const std::vector& modes);\n\n static VkExtent2D choose_surface_extent(const VkSurfaceCapabilitiesKHR& caps, const glm::ivec2& window_dimensions);\n\n void transition_swapchain_images_into_correct_layout(const std::vector& images) const;\n };\n} \/\/ namespace nova::renderer\n\n#endif \/\/ NOVA_RENDERER_FRAMEBUFFER_MANAGER_H<|endoftext|>"} {"text":"\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"ConstantIC.h\"\n#include \"libmesh\/point.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.set(\"value\") = 0.0;\n return params;\n}\n\nConstantIC::ConstantIC(const std::string & name, InputParameters parameters) :\n InitialCondition(name, parameters),\n _value(getParam(\"value\"))\n{\n}\n\nReal\nConstantIC::value(const Point & \/*p*\/)\n{\n return _value;\n}\n\nFixing ConstantIC's input parameters (refs #2300)\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"ConstantIC.h\"\n#include \"libmesh\/point.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addRequiredParam(\"value\", \"The value to be set in IC\");\n return params;\n}\n\nConstantIC::ConstantIC(const std::string & name, InputParameters parameters) :\n InitialCondition(name, parameters),\n _value(getParam(\"value\"))\n{\n}\n\nReal\nConstantIC::value(const Point & \/*p*\/)\n{\n return _value;\n}\n\n<|endoftext|>"} {"text":"\/*\n * SessionOptions.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace core ;\n\nnamespace session { \n\nnamespace {\n\nconst char* const kDefaultPostbackPath = \"bin\/postback\/rpostback\";\n\nvoid resolvePath(const FilePath& resourcePath, std::string* pPath)\n{\n if (!pPath->empty())\n *pPath = resourcePath.complete(*pPath).absolutePath();\n}\n\n#ifdef __APPLE__\n\nvoid resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)\n{\n \/\/ On OSX we keep the postback scripts over in the MacOS directory\n \/\/ rather than in the Resources directory -- make this adjustment\n \/\/ when the default postback path has been passed\n if (*pPath == kDefaultPostbackPath)\n {\n FilePath path = resourcePath.parent().complete(\"MacOS\/postback\/rpostback\");\n *pPath = path.absolutePath();\n }\n else\n {\n resolvePath(resourcePath, pPath);\n }\n}\n\n#else\n\nvoid resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)\n{\n resolvePath(resourcePath, pPath);\n}\n\n#endif\n\n}\n\nOptions& options()\n{\n static Options instance ;\n return instance ;\n}\n \ncore::ProgramStatus Options::read(int argc, char * const argv[])\n{\n using namespace boost::program_options ;\n \n \/\/ compute the resource path\n FilePath resourcePath;\n Error error = core::system::installPath(\"..\", argc, argv, &resourcePath);\n if (error)\n {\n LOG_ERROR_MESSAGE(\"Unable to determine install path: \"+error.summary());\n return ProgramStatus::exitFailure();\n }\n\n \/\/ detect running in OSX bundle and tweak resource path\n#ifdef __APPLE__\n if (resourcePath.complete(\"Info.plist\").exists())\n resourcePath = resourcePath.complete(\"Resources\");\n#endif\n\n \/\/ detect running in x64 directory and tweak resource path\n#ifdef _WIN32\n if (resourcePath.complete(\"x64\").exists())\n resourcePath = resourcePath.parent();\n#endif\n\n \/\/ verify installation flag\n options_description verify(\"verify\");\n verify.add_options()\n (kVerifyInstallationSessionOption,\n value(&verifyInstallation_)->default_value(false),\n \"verify the current installation\");\n\n \/\/ program - name and execution\n options_description program(\"program\");\n program.add_options()\n (kProgramModeSessionOption,\n value(&programMode_)->default_value(\"server\"),\n \"program mode (desktop or server\");\n \n \/\/ agreement\n options_description agreement(\"agreement\");\n agreement.add_options()\n (\"agreement-file\",\n value(&agreementFilePath_)->default_value(\"\"),\n \"agreement file\");\n\n \/\/ docs url\n options_description docs(\"docs\");\n docs.add_options()\n (\"docs-url\",\n value(&docsURL_)->default_value(\"\"),\n \"custom docs url\");\n\n \/\/ www options\n options_description www(\"www\") ;\n www.add_options()\n (\"www-local-path\",\n value(&wwwLocalPath_)->default_value(\"www\"),\n \"www local path\")\n (\"www-port\",\n value(&wwwPort_)->default_value(\"8787\"),\n \"port to listen on\");\n\n \/\/ session options\n options_description session(\"session\") ;\n session.add_options()\n (\"session-timeout-minutes\",\n value(&timeoutMinutes_)->default_value(120),\n \"session timeout (minutes)\" )\n (\"session-preflight-script\",\n value(&preflightScript_)->default_value(\"\"),\n \"session preflight script\")\n (\"session-create-public-folder\",\n value(&createPublicFolder_)->default_value(false),\n \"automatically create public folder\")\n (\"session-rprofile-on-resume-default\",\n value(&rProfileOnResumeDefault_)->default_value(false),\n \"default user setting for running Rprofile on resume\");\n\n \/\/ r options\n bool rShellEscape; \/\/ no longer works but don't want to break any\n \/\/ config files which formerly used it\n \/\/ TODO: eliminate this option entirely\n options_description r(\"r\") ;\n r.add_options()\n (\"r-core-source\",\n value(&coreRSourcePath_)->default_value(\"R\"),\n \"Core R source path\")\n (\"r-modules-source\", \n value(&modulesRSourcePath_)->default_value(\"R\/modules\"),\n \"Modules R source path\")\n (\"r-session-packages\",\n value(&sessionPackagesPath_)->default_value(\"R\/library\"),\n \"R packages path\")\n (\"r-libs-user\",\n value(&rLibsUser_)->default_value(\"~\/R\/library\"),\n \"R user library path\")\n (\"r-cran-repos\",\n value(&rCRANRepos_)->default_value(\"\"),\n \"Default CRAN repository\")\n (\"r-auto-reload-source\",\n value(&autoReloadSource_)->default_value(false),\n \"Reload R source if it changes during the session\")\n (\"r-compatible-graphics-engine-version\",\n value(&rCompatibleGraphicsEngineVersion_)->default_value(10),\n \"Maximum graphics engine version we are compatible with\")\n (\"r-resources-path\",\n value(&rResourcesPath_)->default_value(\"resources\"),\n \"Directory containing external resources\")\n (\"r-shell-escape\",\n value(&rShellEscape)->default_value(false),\n \"Support shell escape (deprecated, no longer works)\")\n (\"r-home-dir-override\",\n value(&rHomeDirOverride_)->default_value(\"\"),\n \"Override for R_HOME (used for debug configurations)\")\n (\"r-doc-dir-override\",\n value(&rDocDirOverride_)->default_value(\"\"),\n \"Override for R_DOC_DIR (used for debug configurations)\");\n\n \/\/ limits options\n options_description limits(\"limits\");\n limits.add_options()\n (\"limit-file-upload-size-mb\",\n value(&limitFileUploadSizeMb_)->default_value(0),\n \"limit of file upload size\")\n (\"limit-cpu-time-minutes\",\n value(&limitCpuTimeMinutes_)->default_value(0),\n \"limit on time of top level computations\")\n (\"limit-xfs-disk-quota\",\n value(&limitXfsDiskQuota_)->default_value(false),\n \"limit xfs disk quota\");\n \n \/\/ external options\n options_description external(\"external\");\n external.add_options()\n (\"external-rpostback-path\", \n value(&rpostbackPath_)->default_value(kDefaultPostbackPath),\n \"Path to rpostback executable\")\n (\"external-consoleio-path\",\n value(&consoleIoPath_)->default_value(\"bin\/consoleio.exe\"),\n \"Path to consoleio executable\")\n (\"external-gnudiff-path\",\n value(&gnudiffPath_)->default_value(\"bin\/gnudiff\"),\n \"Path to gnudiff utilities (windows-only)\")\n (\"external-gnugrep-path\",\n value(&gnugrepPath_)->default_value(\"bin\/gnugrep\"),\n \"Path to gnugrep utilities (windows-only)\")\n (\"external-msysssh-path\",\n value(&msysSshPath_)->default_value(\"bin\/msys_ssh\"),\n \"Path to msys_ssh utilities (windows-only)\")\n (\"external-sumatra-path\",\n value(&sumatraPath_)->default_value(\"bin\/sumatra\"),\n \"Path to SumatraPDF (windows-only)\")\n (\"external-hunspell-dictionaries-path\",\n value(&hunspellDictionariesPath_)->default_value(\"resources\/dictionaries\"),\n \"Path to hunspell dictionaries\")\n (\"external-mathjax-path\",\n value(&mathjaxPath_)->default_value(\"resources\/mathjax\"),\n \"Path to mathjax library\");\n\n \/\/ user options (default user identity to current username)\n std::string currentUsername = core::system::username();\n options_description user(\"user\") ;\n user.add_options()\n (kUserIdentitySessionOption \",\" kUserIdentitySessionOptionShort,\n value(&userIdentity_)->default_value(currentUsername),\n \"user identity\" );\n \n \/\/ define program options\n FilePath defaultConfigPath(\"\/etc\/rstudio\/rsession.conf\");\n std::string configFile = defaultConfigPath.exists() ?\n defaultConfigPath.absolutePath() : \"\";\n core::program_options::OptionsDescription optionsDesc(\"rsession\",\n configFile);\n\n optionsDesc.commandLine.add(verify);\n optionsDesc.commandLine.add(program);\n optionsDesc.commandLine.add(agreement);\n optionsDesc.commandLine.add(docs);\n optionsDesc.commandLine.add(www);\n optionsDesc.commandLine.add(session);\n optionsDesc.commandLine.add(r);\n optionsDesc.commandLine.add(limits);\n optionsDesc.commandLine.add(external);\n optionsDesc.commandLine.add(user);\n\n \/\/ define groups included in config-file processing\n optionsDesc.configFile.add(program);\n optionsDesc.configFile.add(agreement);\n optionsDesc.configFile.add(docs);\n optionsDesc.configFile.add(www);\n optionsDesc.configFile.add(session);\n optionsDesc.configFile.add(r);\n optionsDesc.configFile.add(limits);\n optionsDesc.configFile.add(external);\n optionsDesc.configFile.add(user);\n\n \/\/ read configuration\n ProgramStatus status = core::program_options::read(optionsDesc, argc,argv);\n if (status.exit())\n return status;\n \n \/\/ make sure the program mode is valid\n if (programMode_ != kSessionProgramModeDesktop &&\n programMode_ != kSessionProgramModeServer)\n {\n LOG_ERROR_MESSAGE(\"invalid program mode: \" + programMode_);\n return ProgramStatus::exitFailure();\n }\n\n \/\/ compute program identity\n programIdentity_ = \"rsession-\" + userIdentity_;\n\n \/\/ provide special home path in temp directory if we are verifying\n if (verifyInstallation_)\n {\n \/\/ we create a special home directory in server mode (since the\n \/\/ user we are running under might not have a home directory)\n if (programMode_ == kSessionProgramModeServer)\n {\n verifyInstallationHomeDir_ = \"\/tmp\/rstudio-verify-installation\";\n Error error = FilePath(verifyInstallationHomeDir_).ensureDirectory();\n if (error)\n {\n LOG_ERROR(error);\n return ProgramStatus::exitFailure();\n }\n core::system::setenv(\"R_USER\", verifyInstallationHomeDir_);\n }\n }\n\n \/\/ compute user home path\n FilePath userHomePath = core::system::userHomePath(\"R_USER|HOME\");\n\n userHomePath_ = userHomePath.absolutePath();\n\n \/\/ compute user scratch path\n std::string scratchPathName;\n if (programMode_ == kSessionProgramModeDesktop)\n scratchPathName = \"RStudio-Desktop\";\n else\n scratchPathName = \"RStudio\";\n userScratchPath_ = core::system::userSettingsPath(\n userHomePath,\n scratchPathName).absolutePath();\n\n \/\/ session timeout seconds is always -1 in desktop mode\n if (programMode_ == kSessionProgramModeDesktop)\n timeoutMinutes_ = 0;\n\n \/\/ convert relative paths by completing from the app resource path\n resolvePath(resourcePath, &rResourcesPath_);\n resolvePath(resourcePath, &agreementFilePath_);\n resolvePath(resourcePath, &wwwLocalPath_);\n resolvePath(resourcePath, &coreRSourcePath_);\n resolvePath(resourcePath, &modulesRSourcePath_);\n resolvePath(resourcePath, &sessionPackagesPath_);\n resolvePostbackPath(resourcePath, &rpostbackPath_);\n#ifdef _WIN32\n resolvePath(resourcePath, &consoleIoPath_);\n resolvePath(resourcePath, &gnudiffPath_);\n resolvePath(resourcePath, &gnugrepPath_);\n resolvePath(resourcePath, &msysSshPath_);\n resolvePath(resourcePath, &sumatraPath_);\n#endif\n resolvePath(resourcePath, &hunspellDictionariesPath_);\n resolvePath(resourcePath, &mathjaxPath_);\n\n \/\/ shared secret with parent\n secret_ = core::system::getenv(\"RS_SHARED_SECRET\");\n \/* SECURITY: Need RS_SHARED_SECRET to be available to\n rpostback. However, we really ought to communicate\n it in a more secure manner than this, at least on\n Windows where even within the same user session some\n processes can have different priviliges (integrity\n levels) than others. For example, using a named pipe\n with proper SACL to retrieve the shared secret, where\n the name of the pipe is in an environment variable. *\/\n \/\/core::system::unsetenv(\"RS_SHARED_SECRET\");\n\n \/\/ initial working dir override\n initialWorkingDirOverride_ = core::system::getenv(\"RS_INITIAL_WD\");\n core::system::unsetenv(\"RS_INITIAL_WD\");\n\n \/\/ initial environment file override\n initialEnvironmentFileOverride_ = core::system::getenv(\"RS_INITIAL_ENV\");\n core::system::unsetenv(\"RS_INITIAL_ENV\");\n\n \/\/ initial project\n initialProjectPath_ = core::system::getenv(\"RS_INITIAL_PROJECT\");\n core::system::unsetenv(\"RS_INITIAL_PROJECT\");\n\n \/\/ limit rpc client uid\n limitRpcClientUid_ = -1;\n std::string limitUid = core::system::getenv(kRStudioLimitRpcClientUid);\n if (!limitUid.empty())\n {\n limitRpcClientUid_ = core::safe_convert::stringTo(limitUid, -1);\n core::system::unsetenv(kRStudioLimitRpcClientUid);\n }\n\n \/\/ return status\n return status;\n}\n \n} \/\/ namespace session\nallow session timeout to be supressed via an environment variable\/*\n * SessionOptions.cpp\n *\n * Copyright (C) 2009-12 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n\nusing namespace core ;\n\nnamespace session { \n\nnamespace {\n\nconst char* const kDefaultPostbackPath = \"bin\/postback\/rpostback\";\n\nvoid resolvePath(const FilePath& resourcePath, std::string* pPath)\n{\n if (!pPath->empty())\n *pPath = resourcePath.complete(*pPath).absolutePath();\n}\n\n#ifdef __APPLE__\n\nvoid resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)\n{\n \/\/ On OSX we keep the postback scripts over in the MacOS directory\n \/\/ rather than in the Resources directory -- make this adjustment\n \/\/ when the default postback path has been passed\n if (*pPath == kDefaultPostbackPath)\n {\n FilePath path = resourcePath.parent().complete(\"MacOS\/postback\/rpostback\");\n *pPath = path.absolutePath();\n }\n else\n {\n resolvePath(resourcePath, pPath);\n }\n}\n\n#else\n\nvoid resolvePostbackPath(const FilePath& resourcePath, std::string* pPath)\n{\n resolvePath(resourcePath, pPath);\n}\n\n#endif\n\n}\n\nOptions& options()\n{\n static Options instance ;\n return instance ;\n}\n \ncore::ProgramStatus Options::read(int argc, char * const argv[])\n{\n using namespace boost::program_options ;\n \n \/\/ compute the resource path\n FilePath resourcePath;\n Error error = core::system::installPath(\"..\", argc, argv, &resourcePath);\n if (error)\n {\n LOG_ERROR_MESSAGE(\"Unable to determine install path: \"+error.summary());\n return ProgramStatus::exitFailure();\n }\n\n \/\/ detect running in OSX bundle and tweak resource path\n#ifdef __APPLE__\n if (resourcePath.complete(\"Info.plist\").exists())\n resourcePath = resourcePath.complete(\"Resources\");\n#endif\n\n \/\/ detect running in x64 directory and tweak resource path\n#ifdef _WIN32\n if (resourcePath.complete(\"x64\").exists())\n resourcePath = resourcePath.parent();\n#endif\n\n \/\/ verify installation flag\n options_description verify(\"verify\");\n verify.add_options()\n (kVerifyInstallationSessionOption,\n value(&verifyInstallation_)->default_value(false),\n \"verify the current installation\");\n\n \/\/ program - name and execution\n options_description program(\"program\");\n program.add_options()\n (kProgramModeSessionOption,\n value(&programMode_)->default_value(\"server\"),\n \"program mode (desktop or server\");\n \n \/\/ agreement\n options_description agreement(\"agreement\");\n agreement.add_options()\n (\"agreement-file\",\n value(&agreementFilePath_)->default_value(\"\"),\n \"agreement file\");\n\n \/\/ docs url\n options_description docs(\"docs\");\n docs.add_options()\n (\"docs-url\",\n value(&docsURL_)->default_value(\"\"),\n \"custom docs url\");\n\n \/\/ www options\n options_description www(\"www\") ;\n www.add_options()\n (\"www-local-path\",\n value(&wwwLocalPath_)->default_value(\"www\"),\n \"www local path\")\n (\"www-port\",\n value(&wwwPort_)->default_value(\"8787\"),\n \"port to listen on\");\n\n \/\/ session options\n options_description session(\"session\") ;\n session.add_options()\n (\"session-timeout-minutes\",\n value(&timeoutMinutes_)->default_value(120),\n \"session timeout (minutes)\" )\n (\"session-preflight-script\",\n value(&preflightScript_)->default_value(\"\"),\n \"session preflight script\")\n (\"session-create-public-folder\",\n value(&createPublicFolder_)->default_value(false),\n \"automatically create public folder\")\n (\"session-rprofile-on-resume-default\",\n value(&rProfileOnResumeDefault_)->default_value(false),\n \"default user setting for running Rprofile on resume\");\n\n \/\/ r options\n bool rShellEscape; \/\/ no longer works but don't want to break any\n \/\/ config files which formerly used it\n \/\/ TODO: eliminate this option entirely\n options_description r(\"r\") ;\n r.add_options()\n (\"r-core-source\",\n value(&coreRSourcePath_)->default_value(\"R\"),\n \"Core R source path\")\n (\"r-modules-source\", \n value(&modulesRSourcePath_)->default_value(\"R\/modules\"),\n \"Modules R source path\")\n (\"r-session-packages\",\n value(&sessionPackagesPath_)->default_value(\"R\/library\"),\n \"R packages path\")\n (\"r-libs-user\",\n value(&rLibsUser_)->default_value(\"~\/R\/library\"),\n \"R user library path\")\n (\"r-cran-repos\",\n value(&rCRANRepos_)->default_value(\"\"),\n \"Default CRAN repository\")\n (\"r-auto-reload-source\",\n value(&autoReloadSource_)->default_value(false),\n \"Reload R source if it changes during the session\")\n (\"r-compatible-graphics-engine-version\",\n value(&rCompatibleGraphicsEngineVersion_)->default_value(10),\n \"Maximum graphics engine version we are compatible with\")\n (\"r-resources-path\",\n value(&rResourcesPath_)->default_value(\"resources\"),\n \"Directory containing external resources\")\n (\"r-shell-escape\",\n value(&rShellEscape)->default_value(false),\n \"Support shell escape (deprecated, no longer works)\")\n (\"r-home-dir-override\",\n value(&rHomeDirOverride_)->default_value(\"\"),\n \"Override for R_HOME (used for debug configurations)\")\n (\"r-doc-dir-override\",\n value(&rDocDirOverride_)->default_value(\"\"),\n \"Override for R_DOC_DIR (used for debug configurations)\");\n\n \/\/ limits options\n options_description limits(\"limits\");\n limits.add_options()\n (\"limit-file-upload-size-mb\",\n value(&limitFileUploadSizeMb_)->default_value(0),\n \"limit of file upload size\")\n (\"limit-cpu-time-minutes\",\n value(&limitCpuTimeMinutes_)->default_value(0),\n \"limit on time of top level computations\")\n (\"limit-xfs-disk-quota\",\n value(&limitXfsDiskQuota_)->default_value(false),\n \"limit xfs disk quota\");\n \n \/\/ external options\n options_description external(\"external\");\n external.add_options()\n (\"external-rpostback-path\", \n value(&rpostbackPath_)->default_value(kDefaultPostbackPath),\n \"Path to rpostback executable\")\n (\"external-consoleio-path\",\n value(&consoleIoPath_)->default_value(\"bin\/consoleio.exe\"),\n \"Path to consoleio executable\")\n (\"external-gnudiff-path\",\n value(&gnudiffPath_)->default_value(\"bin\/gnudiff\"),\n \"Path to gnudiff utilities (windows-only)\")\n (\"external-gnugrep-path\",\n value(&gnugrepPath_)->default_value(\"bin\/gnugrep\"),\n \"Path to gnugrep utilities (windows-only)\")\n (\"external-msysssh-path\",\n value(&msysSshPath_)->default_value(\"bin\/msys_ssh\"),\n \"Path to msys_ssh utilities (windows-only)\")\n (\"external-sumatra-path\",\n value(&sumatraPath_)->default_value(\"bin\/sumatra\"),\n \"Path to SumatraPDF (windows-only)\")\n (\"external-hunspell-dictionaries-path\",\n value(&hunspellDictionariesPath_)->default_value(\"resources\/dictionaries\"),\n \"Path to hunspell dictionaries\")\n (\"external-mathjax-path\",\n value(&mathjaxPath_)->default_value(\"resources\/mathjax\"),\n \"Path to mathjax library\");\n\n \/\/ user options (default user identity to current username)\n std::string currentUsername = core::system::username();\n options_description user(\"user\") ;\n user.add_options()\n (kUserIdentitySessionOption \",\" kUserIdentitySessionOptionShort,\n value(&userIdentity_)->default_value(currentUsername),\n \"user identity\" );\n \n \/\/ define program options\n FilePath defaultConfigPath(\"\/etc\/rstudio\/rsession.conf\");\n std::string configFile = defaultConfigPath.exists() ?\n defaultConfigPath.absolutePath() : \"\";\n core::program_options::OptionsDescription optionsDesc(\"rsession\",\n configFile);\n\n optionsDesc.commandLine.add(verify);\n optionsDesc.commandLine.add(program);\n optionsDesc.commandLine.add(agreement);\n optionsDesc.commandLine.add(docs);\n optionsDesc.commandLine.add(www);\n optionsDesc.commandLine.add(session);\n optionsDesc.commandLine.add(r);\n optionsDesc.commandLine.add(limits);\n optionsDesc.commandLine.add(external);\n optionsDesc.commandLine.add(user);\n\n \/\/ define groups included in config-file processing\n optionsDesc.configFile.add(program);\n optionsDesc.configFile.add(agreement);\n optionsDesc.configFile.add(docs);\n optionsDesc.configFile.add(www);\n optionsDesc.configFile.add(session);\n optionsDesc.configFile.add(r);\n optionsDesc.configFile.add(limits);\n optionsDesc.configFile.add(external);\n optionsDesc.configFile.add(user);\n\n \/\/ read configuration\n ProgramStatus status = core::program_options::read(optionsDesc, argc,argv);\n if (status.exit())\n return status;\n \n \/\/ make sure the program mode is valid\n if (programMode_ != kSessionProgramModeDesktop &&\n programMode_ != kSessionProgramModeServer)\n {\n LOG_ERROR_MESSAGE(\"invalid program mode: \" + programMode_);\n return ProgramStatus::exitFailure();\n }\n\n \/\/ compute program identity\n programIdentity_ = \"rsession-\" + userIdentity_;\n\n \/\/ provide special home path in temp directory if we are verifying\n if (verifyInstallation_)\n {\n \/\/ we create a special home directory in server mode (since the\n \/\/ user we are running under might not have a home directory)\n if (programMode_ == kSessionProgramModeServer)\n {\n verifyInstallationHomeDir_ = \"\/tmp\/rstudio-verify-installation\";\n Error error = FilePath(verifyInstallationHomeDir_).ensureDirectory();\n if (error)\n {\n LOG_ERROR(error);\n return ProgramStatus::exitFailure();\n }\n core::system::setenv(\"R_USER\", verifyInstallationHomeDir_);\n }\n }\n\n \/\/ compute user home path\n FilePath userHomePath = core::system::userHomePath(\"R_USER|HOME\");\n\n userHomePath_ = userHomePath.absolutePath();\n\n \/\/ compute user scratch path\n std::string scratchPathName;\n if (programMode_ == kSessionProgramModeDesktop)\n scratchPathName = \"RStudio-Desktop\";\n else\n scratchPathName = \"RStudio\";\n userScratchPath_ = core::system::userSettingsPath(\n userHomePath,\n scratchPathName).absolutePath();\n\n \/\/ session timeout seconds is always -1 in desktop mode\n if (programMode_ == kSessionProgramModeDesktop)\n timeoutMinutes_ = 0;\n\n \/\/ allow session timeout to be supressed via environment variable\n if (!core::system::getenv(\"RSTUDIO_NO_SESSION_TIMEOUT\").empty())\n timeoutMinutes_ = 0;\n\n \/\/ convert relative paths by completing from the app resource path\n resolvePath(resourcePath, &rResourcesPath_);\n resolvePath(resourcePath, &agreementFilePath_);\n resolvePath(resourcePath, &wwwLocalPath_);\n resolvePath(resourcePath, &coreRSourcePath_);\n resolvePath(resourcePath, &modulesRSourcePath_);\n resolvePath(resourcePath, &sessionPackagesPath_);\n resolvePostbackPath(resourcePath, &rpostbackPath_);\n#ifdef _WIN32\n resolvePath(resourcePath, &consoleIoPath_);\n resolvePath(resourcePath, &gnudiffPath_);\n resolvePath(resourcePath, &gnugrepPath_);\n resolvePath(resourcePath, &msysSshPath_);\n resolvePath(resourcePath, &sumatraPath_);\n#endif\n resolvePath(resourcePath, &hunspellDictionariesPath_);\n resolvePath(resourcePath, &mathjaxPath_);\n\n \/\/ shared secret with parent\n secret_ = core::system::getenv(\"RS_SHARED_SECRET\");\n \/* SECURITY: Need RS_SHARED_SECRET to be available to\n rpostback. However, we really ought to communicate\n it in a more secure manner than this, at least on\n Windows where even within the same user session some\n processes can have different priviliges (integrity\n levels) than others. For example, using a named pipe\n with proper SACL to retrieve the shared secret, where\n the name of the pipe is in an environment variable. *\/\n \/\/core::system::unsetenv(\"RS_SHARED_SECRET\");\n\n \/\/ initial working dir override\n initialWorkingDirOverride_ = core::system::getenv(\"RS_INITIAL_WD\");\n core::system::unsetenv(\"RS_INITIAL_WD\");\n\n \/\/ initial environment file override\n initialEnvironmentFileOverride_ = core::system::getenv(\"RS_INITIAL_ENV\");\n core::system::unsetenv(\"RS_INITIAL_ENV\");\n\n \/\/ initial project\n initialProjectPath_ = core::system::getenv(\"RS_INITIAL_PROJECT\");\n core::system::unsetenv(\"RS_INITIAL_PROJECT\");\n\n \/\/ limit rpc client uid\n limitRpcClientUid_ = -1;\n std::string limitUid = core::system::getenv(kRStudioLimitRpcClientUid);\n if (!limitUid.empty())\n {\n limitRpcClientUid_ = core::safe_convert::stringTo(limitUid, -1);\n core::system::unsetenv(kRStudioLimitRpcClientUid);\n }\n\n \/\/ return status\n return status;\n}\n \n} \/\/ namespace session\n<|endoftext|>"} {"text":"\/**\n * @file device_properties.hpp\n *\n * @brief Classes for holding CUDA device properties and\n * CUDA compute capability values.\n *\n *\/\n#pragma once\n#ifndef CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_\n#define CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_\n\n#include \n#include \n#include \n\n#include \n\nnamespace cuda {\n\nnamespace device {\n\n\/**\n * A numeric designator of an architectural generation of CUDA devices\n *\n * @note See @url https:\/\/en.wikipedia.org\/wiki\/Volta_(microarchitecture)\n * and previous architectures' pages via \"previous\" links.\n * Also see @ref compute_capability_t .\n *\/\nstruct compute_architecture_t {\n\t\/**\n\t * A @ref compute_capability_t has a \"major\" and a \"minor\" number,\n\t * with \"major\" indicating the architecture; so this struct only\n\t * has a \"major\" numner\n\t *\/\n\tunsigned major;\n\n\tstatic const char* name(unsigned major_compute_capability_version);\n\tunsigned max_warp_schedulings_per_processor_cycle() const;\n\tunsigned max_resident_warps_per_processor() const;\n\tunsigned max_in_flight_threads_per_processor() const;\n\t\/**\n\t * @note On some architectures, the shared memory \/ L1 balance is configurable,\n\t * so you might not get the maxima here without making this configuration\n\t * setting\n\t *\/\n\tmemory::shared::size_t max_shared_memory_per_block() const;\n\tconst char* name() const { return name(major); }\n\n\tbool is_valid() const noexcept\n\t{\n\t\treturn (major > 0) and (major < 9999); \/\/ Picked this up from the CUDA code somwhere\n\t}\n\n};\n\ninline bool operator ==(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major == rhs.major;\n}\ninline bool operator !=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major != rhs.major;\n}\ninline bool operator <(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major < rhs.major;\n}\ninline bool operator <=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major < rhs.major;\n}\ninline bool operator >(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major > rhs.major;\n}\ninline bool operator >=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major > rhs.major;\n}\n\n\n\/\/ TODO: Consider making this a non-POD struct,\n\/\/ with a proper ctor checking validity, an operator converting to pair etc;\n\/\/ however, that would require including at least std::utility, if not other\n\/\/ stuff (e.g. for an std::hash specialization)\n\/\/ TODO: If we constrained this to versions we know about, we could make the\n\/\/ methods noexcept\n\/**\n * A numeric designator of the computational capabilities of a CUDA device\n *\n * @note See @url https:\/\/en.wikipedia.org\/wiki\/CUDA#Version_features_and_specifications\n * for a specification of capabilities by CC values\n *\/\nstruct compute_capability_t {\n\n\tcompute_architecture_t architecture;\n\tunsigned minor_;\n\n\tunsigned as_combined_number() const noexcept { return major() * 10 + minor_; }\n\tunsigned max_warp_schedulings_per_processor_cycle() const;\n\tunsigned max_resident_warps_per_processor() const;\n\tunsigned max_in_flight_threads_per_processor() const;\n\t\/**\n\t * @note On some architectures, the shared memory \/ L1 balance is configurable,\n\t * so you might not get the maxima here without making this configuration\n\t * setting\n\t *\/\n\tmemory::shared::size_t max_shared_memory_per_block() const;\n\n\tunsigned major() const { return architecture.major; }\n\n\t\/\/ We don't really need this method, but it allows for the same access pattern as for the\n\t\/\/ major number, i.e. major() and minor(). Alternatively, we could have\n\t\/\/ used a proxy\n\tunsigned minor() const { return minor_; }\n\n\tbool is_valid() const\n\t{\n\t\treturn (major() > 0) and (major() < 9999) and (minor_ > 0) and (minor_ < 9999);\n\t\t\t\/\/ Picked this up from the CUDA code somwhere\n\t}\n\n\tstatic compute_capability_t from_combined_number(unsigned combined)\n\t{\n\t\treturn { combined \/ 10, combined % 10 };\n\t}\n};\n\ninline bool operator ==(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() == rhs.major() and lhs.minor_ == rhs.minor_;\n}\ninline bool operator !=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() != rhs.major() or lhs.minor_ != rhs.minor_;\n}\ninline bool operator <(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ < rhs.minor_);\n}\ninline bool operator <=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ <= rhs.minor_);\n}\ninline bool operator >(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ > rhs.minor_);\n}\ninline bool operator >=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ >= rhs.minor_);\n}\n\ninline compute_capability_t make_compute_capability(unsigned combined) noexcept\n{\n\treturn compute_capability_t::from_combined_number(combined);\n}\n\ninline compute_capability_t make_compute_capability(unsigned major, unsigned minor) noexcept\n{\n\treturn { major, minor };\n}\n\n\/**\n * @brief A structure holding a collection various properties of a device\n *\n * @note Somewhat annoyingly, CUDA devices have attributes, properties and flags.\n * Attributes have integral number values; properties have all sorts of values,\n * including arrays and limited-length strings (see\n * @ref cuda::device::properties_t), and flags are either binary or\n * small-finite-domain type fitting into an overall flagss value (see\n * @ref cuda::device_t::flags_t). Flags and properties are obtained all at once,\n * attributes are more one-at-a-time.\n *\n *\/\nstruct properties_t : public cudaDeviceProp {\n\n\tproperties_t() = default;\n\tproperties_t(const cudaDeviceProp& cdp) noexcept : cudaDeviceProp(cdp) { };\n\tproperties_t(cudaDeviceProp&& cdp) noexcept : cudaDeviceProp(cdp) { };\n\tbool usable_for_compute() const noexcept\n\t{\n\t\treturn computeMode != cudaComputeModeProhibited;\n\t}\n\tcompute_capability_t compute_capability() const { return { (unsigned) major, (unsigned) minor }; }\n\tcompute_architecture_t compute_architecture() const noexcept { return { (unsigned) major }; };\n\tpci_location_t pci_id() const noexcept { return { pciDomainID, pciBusID, pciDeviceID }; }\n\n\tunsigned long long max_in_flight_threads_on_device() const\n\t{\n\t\treturn compute_capability().max_in_flight_threads_per_processor() * multiProcessorCount;\n\t}\n\n\tgrid_block_dimension_t max_threads_per_block() const noexcept { return maxThreadsPerBlock; }\n\tgrid_block_dimension_t max_warps_per_block() const noexcept { return maxThreadsPerBlock \/ warp_size; }\n\tsize_t max_shared_memory_per_block() const noexcept { return sharedMemPerBlock; }\n\tsize_t global_memory_size() const noexcept { return totalGlobalMem; }\n\tbool can_map_host_memory() const noexcept { return canMapHostMemory != 0; }\n};\n\n} \/\/ namespace device\n} \/\/ namespace cuda\n\n#endif \/\/ CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_\nTrying to avoid a GNU C Library warning about the use of identifier named `major` and `minor`.\/**\n * @file device_properties.hpp\n *\n * @brief Classes for holding CUDA device properties and\n * CUDA compute capability values.\n *\n *\/\n#pragma once\n#ifndef CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_\n#define CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_\n\n#include \n#include \n#include \n\n#include \n\n\n\/\/ The following un-definitions avoid warnings about\n\/\/ the use of `major` and `minor` in certain versions\n\/\/ of the GNU C library\n#ifdef major\n#undef major\n#endif\n\n#ifdef minor\n#undef minor\n#endif\n\nnamespace cuda {\n\nnamespace device {\n\n\/**\n * A numeric designator of an architectural generation of CUDA devices\n *\n * @note See @url https:\/\/en.wikipedia.org\/wiki\/Volta_(microarchitecture)\n * and previous architectures' pages via \"previous\" links.\n * Also see @ref compute_capability_t .\n *\/\nstruct compute_architecture_t {\n\t\/**\n\t * A @ref compute_capability_t has a \"major\" and a \"minor\" number,\n\t * with \"major\" indicating the architecture; so this struct only\n\t * has a \"major\" numner\n\t *\/\n\tunsigned major;\n\n\tstatic const char* name(unsigned major_compute_capability_version);\n\tunsigned max_warp_schedulings_per_processor_cycle() const;\n\tunsigned max_resident_warps_per_processor() const;\n\tunsigned max_in_flight_threads_per_processor() const;\n\t\/**\n\t * @note On some architectures, the shared memory \/ L1 balance is configurable,\n\t * so you might not get the maxima here without making this configuration\n\t * setting\n\t *\/\n\tmemory::shared::size_t max_shared_memory_per_block() const;\n\tconst char* name() const { return name(major); }\n\n\tbool is_valid() const noexcept\n\t{\n\t\treturn (major > 0) and (major < 9999); \/\/ Picked this up from the CUDA code somwhere\n\t}\n\n};\n\ninline bool operator ==(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major == rhs.major;\n}\ninline bool operator !=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major != rhs.major;\n}\ninline bool operator <(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major < rhs.major;\n}\ninline bool operator <=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major < rhs.major;\n}\ninline bool operator >(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major > rhs.major;\n}\ninline bool operator >=(const compute_architecture_t& lhs, const compute_architecture_t& rhs) noexcept\n{\n\treturn lhs.major > rhs.major;\n}\n\n\n\/\/ TODO: Consider making this a non-POD struct,\n\/\/ with a proper ctor checking validity, an operator converting to pair etc;\n\/\/ however, that would require including at least std::utility, if not other\n\/\/ stuff (e.g. for an std::hash specialization)\n\/\/ TODO: If we constrained this to versions we know about, we could make the\n\/\/ methods noexcept\n\/**\n * A numeric designator of the computational capabilities of a CUDA device\n *\n * @note See @url https:\/\/en.wikipedia.org\/wiki\/CUDA#Version_features_and_specifications\n * for a specification of capabilities by CC values\n *\/\nstruct compute_capability_t {\n\n\tcompute_architecture_t architecture;\n\tunsigned minor_;\n\n\tunsigned as_combined_number() const noexcept { return major() * 10 + minor_; }\n\tunsigned max_warp_schedulings_per_processor_cycle() const;\n\tunsigned max_resident_warps_per_processor() const;\n\tunsigned max_in_flight_threads_per_processor() const;\n\t\/**\n\t * @note On some architectures, the shared memory \/ L1 balance is configurable,\n\t * so you might not get the maxima here without making this configuration\n\t * setting\n\t *\/\n\tmemory::shared::size_t max_shared_memory_per_block() const;\n\n\tunsigned major() const { return architecture.major; }\n\n\t\/\/ We don't really need this method, but it allows for the same access pattern as for the\n\t\/\/ major number, i.e. major() and minor(). Alternatively, we could have\n\t\/\/ used a proxy\n\tunsigned minor() const { return minor_; }\n\n\tbool is_valid() const\n\t{\n\t\treturn (major() > 0) and (major() < 9999) and (minor_ > 0) and (minor_ < 9999);\n\t\t\t\/\/ Picked this up from the CUDA code somwhere\n\t}\n\n\tstatic compute_capability_t from_combined_number(unsigned combined)\n\t{\n\t\treturn { combined \/ 10, combined % 10 };\n\t}\n};\n\ninline bool operator ==(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() == rhs.major() and lhs.minor_ == rhs.minor_;\n}\ninline bool operator !=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() != rhs.major() or lhs.minor_ != rhs.minor_;\n}\ninline bool operator <(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ < rhs.minor_);\n}\ninline bool operator <=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() < rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ <= rhs.minor_);\n}\ninline bool operator >(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ > rhs.minor_);\n}\ninline bool operator >=(const compute_capability_t& lhs, const compute_capability_t& rhs) noexcept\n{\n\treturn lhs.major() > rhs.major() or (lhs.major() == rhs.major() and lhs.minor_ >= rhs.minor_);\n}\n\ninline compute_capability_t make_compute_capability(unsigned combined) noexcept\n{\n\treturn compute_capability_t::from_combined_number(combined);\n}\n\ninline compute_capability_t make_compute_capability(unsigned major, unsigned minor) noexcept\n{\n\treturn { major, minor };\n}\n\n\/**\n * @brief A structure holding a collection various properties of a device\n *\n * @note Somewhat annoyingly, CUDA devices have attributes, properties and flags.\n * Attributes have integral number values; properties have all sorts of values,\n * including arrays and limited-length strings (see\n * @ref cuda::device::properties_t), and flags are either binary or\n * small-finite-domain type fitting into an overall flagss value (see\n * @ref cuda::device_t::flags_t). Flags and properties are obtained all at once,\n * attributes are more one-at-a-time.\n *\n *\/\nstruct properties_t : public cudaDeviceProp {\n\n\tproperties_t() = default;\n\tproperties_t(const cudaDeviceProp& cdp) noexcept : cudaDeviceProp(cdp) { };\n\tproperties_t(cudaDeviceProp&& cdp) noexcept : cudaDeviceProp(cdp) { };\n\tbool usable_for_compute() const noexcept\n\t{\n\t\treturn computeMode != cudaComputeModeProhibited;\n\t}\n\tcompute_capability_t compute_capability() const { return { (unsigned) major, (unsigned) minor }; }\n\tcompute_architecture_t compute_architecture() const noexcept { return { (unsigned) major }; };\n\tpci_location_t pci_id() const noexcept { return { pciDomainID, pciBusID, pciDeviceID }; }\n\n\tunsigned long long max_in_flight_threads_on_device() const\n\t{\n\t\treturn compute_capability().max_in_flight_threads_per_processor() * multiProcessorCount;\n\t}\n\n\tgrid_block_dimension_t max_threads_per_block() const noexcept { return maxThreadsPerBlock; }\n\tgrid_block_dimension_t max_warps_per_block() const noexcept { return maxThreadsPerBlock \/ warp_size; }\n\tsize_t max_shared_memory_per_block() const noexcept { return sharedMemPerBlock; }\n\tsize_t global_memory_size() const noexcept { return totalGlobalMem; }\n\tbool can_map_host_memory() const noexcept { return canMapHostMemory != 0; }\n};\n\n} \/\/ namespace device\n} \/\/ namespace cuda\n\n#endif \/\/ CUDA_API_WRAPPERS_DEVICE_PROPERTIES_HPP_\n<|endoftext|>"} {"text":"\/*\n L3G4200D implementation based on code by:\n * http:\/\/bildr.org\/2011\/06\/l3g4200d-arduino\/\n * http:\/\/www.pieter-jan.com\/node\/7\n * https:\/\/github.com\/sparkfun\/Tri-Axis_Gyro_Breakout-L3G4200D\n*\/\n#include \"GY50.hpp\"\n#include \"..\/..\/..\/utilities\/Utilities.hpp\"\n\nnamespace\n{\nconst uint8_t kGyroAddress = 105;\nconst auto kMeasurementInterval = 100;\nconst float kGyroSensitivity = 0.07f;\nconst int kGyroThreshold = 12; \/\/ Smaller changes are to be ignored\n} \/\/ namespace\n\nusing namespace smartcarlib::utils;\nusing namespace smartcarlib::constants::gy50;\n\nGY50::GY50(int offset, unsigned long samplingInterval, Runtime& runtime)\n : kOffset{ offset }\n , kSamplingInterval{ samplingInterval }\n , mRuntime(runtime)\n , mPreviousSample{ 0 }\n , mAttached{ false }\n , mAngularDisplacement{ 0 }\n{\n}\n\nint GY50::getHeading()\n{\n \/\/ Get the reading from (-180,180) to [0, 360) scale\n auto normalizedReading = static_cast(mAngularDisplacement) % 360;\n return normalizedReading < 0 ? normalizedReading + 360 : normalizedReading;\n}\n\nvoid GY50::update()\n{\n unsigned long currentTime = mRuntime.currentTimeMillis();\n unsigned long interval = currentTime - mPreviousSample;\n if (interval <= kSamplingInterval)\n {\n return; \/\/ Not the time to read yet\n }\n\n int drift = kOffset - getAngularVelocity();\n\n if (getAbsolute(drift) > kGyroThreshold)\n {\n float gyroRate = drift * kGyroSensitivity;\n mAngularDisplacement += gyroRate \/ (1000.0 \/ interval);\n }\n mPreviousSample = currentTime;\n}\n\nvoid GY50::attach()\n{\n if (mAttached)\n {\n return;\n }\n\n static const uint8_t controlRegister1 = 0x20;\n static const uint8_t controlRegister2 = 0x21;\n static const uint8_t controlRegister3 = 0x22;\n static const uint8_t controlRegister4 = 0x23;\n static const uint8_t controlRegister5 = 0x24;\n\n mRuntime.i2cInit();\n \/\/ Enable z and turn off power down\n writeL3G4200DRegister(controlRegister1, 0b00001100);\n \/\/ If you'd like to adjust\/use the HPF, you can edit the line below to configure CTRL_REG2\n writeL3G4200DRegister(controlRegister2, 0b00000000);\n \/\/ Configure CTRL_REG3 to generate data ready interrupt on INT2\n \/\/ No interrupts used on INT1, if you'd like to configure INT1\n \/\/ or INT2 otherwise, consult the datasheet\n writeL3G4200DRegister(controlRegister3, 0b00001000);\n \/\/ CTRL_REG4 controls the full-scale range, among other things\n writeL3G4200DRegister(controlRegister4, 0b00110000);\n \/\/ CTRL_REG5 controls high-pass filtering of outputs, use it if you'd like\n writeL3G4200DRegister(controlRegister5, 0b00000000);\n\n mAttached = true;\n}\n\nint GY50::getOffset(int measurements)\n{\n if (measurements <= 0)\n {\n return kError;\n }\n\n long sum = 0;\n for (auto i = 0; i < measurements; i++)\n {\n sum += getAngularVelocity();\n mRuntime.delayMillis(kMeasurementInterval);\n }\n\n return sum \/ measurements;\n}\n\nint GY50::getAngularVelocity()\n{\n attach();\n\n static const uint8_t zAxisFirstByteRegister = 0x2D;\n static const uint8_t zAxisSecondByteRegister = 0x2C;\n\n auto firstByte = readL3G4200DRegister(zAxisFirstByteRegister);\n \/\/ Serial.println(\"Bytes:\");\n \/\/ Serial.println(firstByte, BIN);\n auto secondByte = readL3G4200DRegister(zAxisSecondByteRegister);\n\n return static_cast((firstByte << 8) | secondByte);\n}\n\nint GY50::readL3G4200DRegister(uint8_t registerAddress)\n{\n mRuntime.i2cBeginTransmission(kGyroAddress);\n mRuntime.i2cWrite(registerAddress);\n mRuntime.i2cEndTransmission();\n mRuntime.i2cRequestFrom(kGyroAddress, 1);\n\n return mRuntime.i2cAvailable() ? mRuntime.i2cRead() : 0;\n}\n\nvoid GY50::writeL3G4200DRegister(uint8_t registerAddress, uint8_t value)\n{\n mRuntime.i2cBeginTransmission(kGyroAddress);\n mRuntime.i2cWrite(registerAddress);\n mRuntime.i2cWrite(value);\n mRuntime.i2cEndTransmission();\n}\nRemove unnecessary comments\/*\n L3G4200D implementation based on code by:\n * http:\/\/bildr.org\/2011\/06\/l3g4200d-arduino\/\n * http:\/\/www.pieter-jan.com\/node\/7\n * https:\/\/github.com\/sparkfun\/Tri-Axis_Gyro_Breakout-L3G4200D\n*\/\n#include \"GY50.hpp\"\n#include \"..\/..\/..\/utilities\/Utilities.hpp\"\n\nnamespace\n{\nconst uint8_t kGyroAddress = 105;\nconst auto kMeasurementInterval = 100;\nconst float kGyroSensitivity = 0.07f;\nconst int kGyroThreshold = 12; \/\/ Smaller changes are to be ignored\n} \/\/ namespace\n\nusing namespace smartcarlib::utils;\nusing namespace smartcarlib::constants::gy50;\n\nGY50::GY50(int offset, unsigned long samplingInterval, Runtime& runtime)\n : kOffset{ offset }\n , kSamplingInterval{ samplingInterval }\n , mRuntime(runtime)\n , mPreviousSample{ 0 }\n , mAttached{ false }\n , mAngularDisplacement{ 0 }\n{\n}\n\nint GY50::getHeading()\n{\n \/\/ Get the reading from (-180,180) to [0, 360) scale\n auto normalizedReading = static_cast(mAngularDisplacement) % 360;\n return normalizedReading < 0 ? normalizedReading + 360 : normalizedReading;\n}\n\nvoid GY50::update()\n{\n unsigned long currentTime = mRuntime.currentTimeMillis();\n unsigned long interval = currentTime - mPreviousSample;\n if (interval <= kSamplingInterval)\n {\n return; \/\/ Not the time to read yet\n }\n\n int drift = kOffset - getAngularVelocity();\n\n if (getAbsolute(drift) > kGyroThreshold)\n {\n float gyroRate = drift * kGyroSensitivity;\n mAngularDisplacement += gyroRate \/ (1000.0 \/ interval);\n }\n mPreviousSample = currentTime;\n}\n\nvoid GY50::attach()\n{\n if (mAttached)\n {\n return;\n }\n\n static const uint8_t controlRegister1 = 0x20;\n static const uint8_t controlRegister2 = 0x21;\n static const uint8_t controlRegister3 = 0x22;\n static const uint8_t controlRegister4 = 0x23;\n static const uint8_t controlRegister5 = 0x24;\n\n mRuntime.i2cInit();\n \/\/ Enable z and turn off power down\n writeL3G4200DRegister(controlRegister1, 0b00001100);\n \/\/ If you'd like to adjust\/use the HPF, you can edit the line below to configure CTRL_REG2\n writeL3G4200DRegister(controlRegister2, 0b00000000);\n \/\/ Configure CTRL_REG3 to generate data ready interrupt on INT2\n \/\/ No interrupts used on INT1, if you'd like to configure INT1\n \/\/ or INT2 otherwise, consult the datasheet\n writeL3G4200DRegister(controlRegister3, 0b00001000);\n \/\/ CTRL_REG4 controls the full-scale range, among other things\n writeL3G4200DRegister(controlRegister4, 0b00110000);\n \/\/ CTRL_REG5 controls high-pass filtering of outputs, use it if you'd like\n writeL3G4200DRegister(controlRegister5, 0b00000000);\n\n mAttached = true;\n}\n\nint GY50::getOffset(int measurements)\n{\n if (measurements <= 0)\n {\n return kError;\n }\n\n long sum = 0;\n for (auto i = 0; i < measurements; i++)\n {\n sum += getAngularVelocity();\n mRuntime.delayMillis(kMeasurementInterval);\n }\n\n return sum \/ measurements;\n}\n\nint GY50::getAngularVelocity()\n{\n attach();\n\n static const uint8_t zAxisFirstByteRegister = 0x2D;\n static const uint8_t zAxisSecondByteRegister = 0x2C;\n\n auto firstByte = readL3G4200DRegister(zAxisFirstByteRegister);\n auto secondByte = readL3G4200DRegister(zAxisSecondByteRegister);\n\n return static_cast((firstByte << 8) | secondByte);\n}\n\nint GY50::readL3G4200DRegister(uint8_t registerAddress)\n{\n mRuntime.i2cBeginTransmission(kGyroAddress);\n mRuntime.i2cWrite(registerAddress);\n mRuntime.i2cEndTransmission();\n mRuntime.i2cRequestFrom(kGyroAddress, 1);\n\n return mRuntime.i2cAvailable() ? mRuntime.i2cRead() : 0;\n}\n\nvoid GY50::writeL3G4200DRegister(uint8_t registerAddress, uint8_t value)\n{\n mRuntime.i2cBeginTransmission(kGyroAddress);\n mRuntime.i2cWrite(registerAddress);\n mRuntime.i2cWrite(value);\n mRuntime.i2cEndTransmission();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n* UrBackup - Client\/Server backup system\n* Copyright (C) 2011 Martin Raiber\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n**************************************************************************\/\n\n#ifndef CLIENT_ONLY\r\n\r\n#include \"server_writer.h\"\r\n#include \"..\/Interface\/Mutex.h\"\r\n#include \"..\/Interface\/Condition.h\"\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"..\/fsimageplugin\/IVHDFile.h\"\r\n#include \"..\/fsimageplugin\/IFSImageFactory.h\"\r\n#include \"..\/stringtools.h\"\r\n#include \"os_functions.h\"\r\n#include \"server_log.h\"\r\n#include \"server_cleanup.h\"\r\n\r\nextern IFSImageFactory *image_fak;\r\nconst size_t free_space_lim=1000*1024*1024; \/\/1000MB\r\nconst uint64 filebuf_lim=1000*1024*1024; \/\/1000MB\r\n\r\nServerVHDWriter::ServerVHDWriter(IVHDFile *pVHD, unsigned int blocksize, unsigned int nbufs, int pClientid)\r\n{\r\n\tfilebuffer=true;\r\n\r\n\tclientid=pClientid;\r\n\tvhd=pVHD;\r\n\tbufmgr=new CBufMgr2(nbufs, blocksize);\r\n\r\n\tif(filebuffer)\r\n\t{\r\n\t\tfilebuf=new CFileBufMgr(500, false);\r\n\t\tfilebuf_writer=new ServerFileBufferWriter(this, blocksize);\r\n\t\tfilebuf_writer_ticket=Server->getThreadPool()->execute(filebuf_writer);\r\n\t\tcurrfile=filebuf->getBuffer();\r\n\t\tcurrfile_size=0;\r\n\t}\r\n\r\n\tmutex=Server->createMutex();\r\n\tvhd_mutex=Server->createMutex();\r\n\tcond=Server->createCondition();\r\n\texit=false;\r\n\texit_now=false;\r\n\thas_error=false;\r\n\twritten=free_space_lim;\r\n}\r\n\r\nServerVHDWriter::~ServerVHDWriter(void)\r\n{\r\n\tdelete bufmgr;\r\n\r\n\tif(filebuffer)\r\n\t{\r\n\t\tdelete filebuf_writer;\r\n\t\tdelete filebuf;\r\n\t}\r\n\r\n\tServer->destroy(mutex);\r\n\tServer->destroy(vhd_mutex);\r\n\tServer->destroy(cond);\r\n}\r\n\r\nvoid ServerVHDWriter::operator()(void)\r\n{\r\n\t{\r\n\t\twhile(!exit_now)\r\n\t\t{\r\n\t\t\tBufferVHDItem item;\r\n\t\t\tbool has_item=false;\r\n\t\t\tbool do_exit;\r\n\t\t\t{\r\n\t\t\t\tIScopedLock lock(mutex);\r\n\t\t\t\tdo_exit=exit;\r\n\t\t\t\tif(tqueue.empty() && exit==false)\r\n\t\t\t\t\tcond->wait(&lock);\r\n\t\t\t\tif(!tqueue.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\titem=tqueue.front();\r\n\t\t\t\t\ttqueue.pop();\r\n\t\t\t\t\thas_item=true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(has_item)\r\n\t\t\t{\r\n\t\t\t\tif(!has_error)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(!filebuffer)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twriteVHD(item.pos, item.buf, item.bsize);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tFileBufferVHDItem fbi;\r\n\t\t\t\t\t\tfbi.pos=item.pos;\r\n\t\t\t\t\t\tfbi.bsize=item.bsize;\r\n\t\t\t\t\t\twriteRetry(currfile, (char*)&fbi, sizeof(FileBufferVHDItem));\r\n\t\t\t\t\t\tcurrfile_size+=sizeof(FileBufferVHDItem);\r\n\t\t\t\t\t\twriteRetry(currfile, item.buf, item.bsize);\r\n\t\t\t\t\t\tcurrfile_size+=item.bsize;\r\n\r\n\t\t\t\t\t\tif(currfile_size>filebuf_lim)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfilebuf_writer->writeBuffer(currfile);\r\n\t\t\t\t\t\t\tcurrfile=filebuf->getBuffer();\r\n\t\t\t\t\t\t\tcurrfile_size=0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tbufmgr->releaseBuffer(item.buf);\r\n\t\t\t}\r\n\t\t\telse if(do_exit)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif(!filebuffer && written>=free_space_lim\/2)\r\n\t\t\t{\r\n\t\t\t\twritten=0;\r\n\t\t\t\tcheckFreeSpaceAndCleanup();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif(filebuf)\r\n\t{\r\n\t\tfilebuf_writer->writeBuffer(currfile);\r\n\r\n\t\tif(!exit_now)\r\n\t\t\tfilebuf_writer->doExit();\r\n\t\telse\r\n\t\t\tfilebuf_writer->doExitNow();\r\n\r\n\t\tServer->getThreadPool()->waitFor(filebuf_writer_ticket);\r\n\t}\r\n\r\n\timage_fak->destroyVHDFile(vhd);\r\n}\r\n\r\nvoid ServerVHDWriter::checkFreeSpaceAndCleanup(void)\r\n{\r\n\tstd::wstring p;\r\n\t{\r\n\t\tIScopedLock lock(vhd_mutex);\r\n\t\tp=ExtractFilePath(vhd->getFilename());\r\n\t}\r\n\tint64 fs=os_free_space(os_file_prefix()+p);\r\n\tif(fs!=-1 && fs <= free_space_lim )\r\n\t{\r\n\t\tServer->Log(\"Not enough free space. Waiting for cleanup...\");\r\n\t\tif(!cleanupSpace())\r\n\t\t{\r\n\t\t\tServer->Log(\"Not enough free space.\", LL_WARNING);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid ServerVHDWriter::writeVHD(uint64 pos, char *buf, unsigned int bsize)\r\n{\r\n\tIScopedLock lock(vhd_mutex);\r\n\tvhd->Seek(pos);\r\n\tbool b=vhd->Write(buf, bsize);\r\n\twritten+=bsize;\r\n\tif(!b)\r\n\t{\r\n\t\tstd::wstring p=ExtractFilePath(vhd->getFilename());\r\n\t\tint64 fs=os_free_space(os_file_prefix()+p);\r\n\t\tif(fs!=-1 && fs <= free_space_lim )\r\n\t\t{\r\n\t\t\tServer->Log(\"Not enough free space. Waiting for cleanup...\");\r\n\t\t\tif(cleanupSpace())\r\n\t\t\t{\r\n\t\t\t\tif(!vhd->Write(buf, bsize))\r\n\t\t\t\t{\r\n\t\t\t\t\tServerLogger::Log(clientid, \"FATAL: Writing failed after cleanup\", LL_ERROR);\r\n\t\t\t\t\thas_error=true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\thas_error=true;\r\n\t\t\t\tServer->Log(\"FATAL: NOT ENOUGH free space. Cleanup failed.\", LL_ERROR);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\thas_error=true;\r\n\t\t\tServerLogger::Log(clientid, \"FATAL: Error writing to VHD-File.\", LL_ERROR);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nchar *ServerVHDWriter::getBuffer(void)\r\n{\r\n\treturn bufmgr->getBuffer();\r\n}\r\n\r\nvoid ServerVHDWriter::writeBuffer(uint64 pos, char *buf, unsigned int bsize)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tBufferVHDItem item;\r\n\titem.pos=pos;\r\n\titem.buf=buf;\r\n\titem.bsize=bsize;\r\n\ttqueue.push(item);\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerVHDWriter::freeBuffer(char *buf)\r\n{\r\n\tbufmgr->releaseBuffer(buf);\r\n}\r\n\r\nvoid ServerVHDWriter::doExit(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\texit=true;\r\n\tfinish=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerVHDWriter::doExitNow(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\texit=true;\r\n\texit_now=true;\r\n\tfinish=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerVHDWriter::doFinish(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tfinish=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nsize_t ServerVHDWriter::getQueueSize(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\treturn tqueue.size();\r\n}\r\n\r\nbool ServerVHDWriter::hasError(void)\r\n{\r\n\treturn has_error;\r\n}\r\n\r\nIMutex * ServerVHDWriter::getVHDMutex(void)\r\n{\r\n\treturn vhd_mutex;\r\n}\r\n\r\nIVHDFile* ServerVHDWriter::getVHD(void)\r\n{\r\n\treturn vhd;\r\n}\r\n\r\nbool ServerVHDWriter::cleanupSpace(void)\r\n{\r\n\tServerLogger::Log(clientid, \"Not enough free space. Cleaning up.\", LL_INFO);\r\n\tServerCleanupThread cleanup;\r\n\tif(!cleanup.do_cleanup(free_space_lim) )\r\n\t{\r\n\t\tServerLogger::Log(clientid, \"Could not free space for image. NOT ENOUGH FREE SPACE.\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid ServerVHDWriter::freeFile(IFile *buf)\r\n{\r\n\tfilebuf->releaseBuffer(buf);\r\n}\r\n\r\nvoid ServerVHDWriter::writeRetry(IFile *f, char *buf, unsigned int bsize)\r\n{\r\n\tunsigned int off=0;\r\n\tunsigned int r;\r\n\twhile( (r=f->Write(buf+off, bsize-off))!=bsize-off)\r\n\t{\r\n\t\toff+=r;\r\n\t\tServer->Log(\"Error writing to file \\\"\"+f->getFilename()+\"\\\". Retrying\", LL_WARNING);\r\n\t\tServer->wait(10000);\r\n\t}\r\n}\r\n\r\nServerFileBufferWriter::ServerFileBufferWriter(ServerVHDWriter *pParent, unsigned int pBlocksize) : parent(pParent), blocksize(pBlocksize)\r\n{\r\n\tmutex=Server->createMutex();\r\n\tcond=Server->createCondition();\r\n\texit=false;\r\n\texit_now=false;\r\n\twritten=free_space_lim;\r\n}\r\n\r\nServerFileBufferWriter::~ServerFileBufferWriter(void)\r\n{\r\n\twhile(!fb_queue.empty())\r\n\t{\r\n\t\tparent->freeFile(fb_queue.front());\r\n\t\tfb_queue.pop();\r\n\t}\r\n\tServer->destroy(mutex);\r\n\tServer->destroy(cond);\r\n}\r\n\r\nvoid ServerFileBufferWriter::operator()(void)\r\n{\r\n\tchar *blockbuf=new char[blocksize];\r\n\tunsigned int blockbuf_size=blocksize;\r\n\r\n\twhile(!exit_now)\r\n\t{\r\n\t\tIFile* tmp;\r\n\t\tbool has_item=false;\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\twhile(fb_queue.empty() && exit==false)\r\n\t\t\t{\r\n\t\t\t\tcond->wait(&lock);\r\n\t\t\t}\r\n\t\t\tif(!fb_queue.empty())\r\n\t\t\t{\r\n\t\t\t\thas_item=true;\r\n\t\t\t\ttmp=fb_queue.front();\r\n\t\t\t\tfb_queue.pop();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(has_item)\r\n\t\t{\r\n\t\t\ttmp->Seek(0);\r\n\t\t\tuint64 tpos=0;\r\n\t\t\tuint64 tsize=tmp->Size();\r\n\t\t\twhile(tposhasError())\r\n\t\t\t\t{\r\n\t\t\t\t\tFileBufferVHDItem item;\r\n\t\t\t\t\tif(tmp->Read((char*)&item, sizeof(FileBufferVHDItem))!=sizeof(FileBufferVHDItem))\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tServer->Log(\"Error reading FileBufferVHDItem\", LL_ERROR);\r\n\t\t\t\t\t}\r\n\t\t\t\t\ttpos+=sizeof(FileBufferVHDItem);\r\n\t\t\t\t\tunsigned int tw=item.bsize;\r\n\t\t\t\t\tif(tpos+tw>tsize)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tServer->Log(\"Size field is wrong\", LL_ERROR);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(tw>blockbuf_size)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tdelete []blockbuf;\r\n\t\t\t\t\t\tblockbuf=new char[tw];\r\n\t\t\t\t\t\tblockbuf_size=tw;\r\n\t\t\t\t\t}\r\n\t\t\t\t\tif(tmp->Read(blockbuf, tw)!=tw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tServer->Log(\"Error reading from tmp.f\", LL_ERROR);\r\n\t\t\t\t\t}\r\n\t\t\t\t\tparent->writeVHD(item.pos, blockbuf, tw);\r\n\t\t\t\t\twritten+=tw;\r\n\r\n\t\t\t\t\ttpos+=item.bsize;\r\n\r\n\t\t\t\t\tif( written>=free_space_lim\/2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twritten=0;\r\n\t\t\t\t\t\tparent->checkFreeSpaceAndCleanup();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tparent->freeFile(tmp);\r\n\t\t}\r\n\t\telse if(exit)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tdelete []blockbuf;\r\n}\r\n\r\nvoid ServerFileBufferWriter::doExit(void)\r\n{\r\n\texit=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerFileBufferWriter::doExitNow(void)\r\n{\r\n\texit_now=true;\r\n\texit=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerFileBufferWriter::writeBuffer(IFile *buf)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tfb_queue.push(buf);\r\n\tcond->notify_all();\r\n}\r\n\r\n#endif \/\/CLIENT_ONLYSped up imaging\/*************************************************************************\n* UrBackup - Client\/Server backup system\n* Copyright (C) 2011 Martin Raiber\n*\n* This program is free software: you can redistribute it and\/or modify\n* it under the terms of the GNU General Public License as published by\n* the Free Software Foundation, either version 3 of the License, or\n* (at your option) any later version.\n*\n* This program is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n* GNU General Public License for more details.\n*\n* You should have received a copy of the GNU General Public License\n* along with this program. If not, see .\n**************************************************************************\/\n\n#ifndef CLIENT_ONLY\r\n\r\n#include \"server_writer.h\"\r\n#include \"..\/Interface\/Mutex.h\"\r\n#include \"..\/Interface\/Condition.h\"\r\n#include \"..\/Interface\/Server.h\"\r\n#include \"..\/fsimageplugin\/IVHDFile.h\"\r\n#include \"..\/fsimageplugin\/IFSImageFactory.h\"\r\n#include \"..\/stringtools.h\"\r\n#include \"os_functions.h\"\r\n#include \"server_log.h\"\r\n#include \"server_cleanup.h\"\r\n\r\nextern IFSImageFactory *image_fak;\r\nconst size_t free_space_lim=1000*1024*1024; \/\/1000MB\r\nconst uint64 filebuf_lim=1000*1024*1024; \/\/1000MB\r\n\r\nServerVHDWriter::ServerVHDWriter(IVHDFile *pVHD, unsigned int blocksize, unsigned int nbufs, int pClientid)\r\n{\r\n\tfilebuffer=true;\r\n\r\n\tclientid=pClientid;\r\n\tvhd=pVHD;\r\n\tif(filebuffer)\r\n\t{\r\n\t\tbufmgr=new CBufMgr2(nbufs, sizeof(FileBufferVHDItem)+blocksize);\r\n\t}\r\n\telse\r\n\t{\r\n\t\tbufmgr=new CBufMgr2(nbufs, blocksize);\r\n\t}\r\n\r\n\tif(filebuffer)\r\n\t{\r\n\t\tfilebuf=new CFileBufMgr(500, false);\r\n\t\tfilebuf_writer=new ServerFileBufferWriter(this, blocksize);\r\n\t\tfilebuf_writer_ticket=Server->getThreadPool()->execute(filebuf_writer);\r\n\t\tcurrfile=filebuf->getBuffer();\r\n\t\tcurrfile_size=0;\r\n\t}\r\n\r\n\tmutex=Server->createMutex();\r\n\tvhd_mutex=Server->createMutex();\r\n\tcond=Server->createCondition();\r\n\texit=false;\r\n\texit_now=false;\r\n\thas_error=false;\r\n\twritten=free_space_lim;\r\n}\r\n\r\nServerVHDWriter::~ServerVHDWriter(void)\r\n{\r\n\tdelete bufmgr;\r\n\r\n\tif(filebuffer)\r\n\t{\r\n\t\tdelete filebuf_writer;\r\n\t\tdelete filebuf;\r\n\t}\r\n\r\n\tServer->destroy(mutex);\r\n\tServer->destroy(vhd_mutex);\r\n\tServer->destroy(cond);\r\n}\r\n\r\nvoid ServerVHDWriter::operator()(void)\r\n{\r\n\t{\r\n\t\twhile(!exit_now)\r\n\t\t{\r\n\t\t\tBufferVHDItem item;\r\n\t\t\tbool has_item=false;\r\n\t\t\tbool do_exit;\r\n\t\t\t{\r\n\t\t\t\tIScopedLock lock(mutex);\r\n\t\t\t\tdo_exit=exit;\r\n\t\t\t\tif(tqueue.empty() && exit==false)\r\n\t\t\t\t\tcond->wait(&lock);\r\n\t\t\t\tif(!tqueue.empty())\r\n\t\t\t\t{\r\n\t\t\t\t\titem=tqueue.front();\r\n\t\t\t\t\ttqueue.pop();\r\n\t\t\t\t\thas_item=true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tif(has_item)\r\n\t\t\t{\r\n\t\t\t\tif(!has_error)\r\n\t\t\t\t{\r\n\t\t\t\t\tif(!filebuffer)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twriteVHD(item.pos, item.buf, item.bsize);\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tFileBufferVHDItem *fbi=(FileBufferVHDItem*)(item.buf-sizeof(FileBufferVHDItem));\r\n\t\t\t\t\t\tfbi->pos=item.pos;\r\n\t\t\t\t\t\tfbi->bsize=item.bsize;\r\n\t\t\t\t\t\twriteRetry(currfile, (char*)fbi, sizeof(FileBufferVHDItem)+item.bsize);\r\n\t\t\t\t\t\tcurrfile_size+=item.bsize+sizeof(FileBufferVHDItem);\r\n\r\n\t\t\t\t\t\tif(currfile_size>filebuf_lim)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tfilebuf_writer->writeBuffer(currfile);\r\n\t\t\t\t\t\t\tcurrfile=filebuf->getBuffer();\r\n\t\t\t\t\t\t\tcurrfile_size=0;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\r\n\t\t\t\tfreeBuffer(item.buf);\r\n\t\t\t}\r\n\t\t\telse if(do_exit)\r\n\t\t\t{\r\n\t\t\t\tbreak;\r\n\t\t\t}\r\n\r\n\t\t\tif(!filebuffer && written>=free_space_lim\/2)\r\n\t\t\t{\r\n\t\t\t\twritten=0;\r\n\t\t\t\tcheckFreeSpaceAndCleanup();\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\tif(filebuf)\r\n\t{\r\n\t\tfilebuf_writer->writeBuffer(currfile);\r\n\r\n\t\tif(!exit_now)\r\n\t\t\tfilebuf_writer->doExit();\r\n\t\telse\r\n\t\t\tfilebuf_writer->doExitNow();\r\n\r\n\t\tServer->getThreadPool()->waitFor(filebuf_writer_ticket);\r\n\t}\r\n\r\n\timage_fak->destroyVHDFile(vhd);\r\n}\r\n\r\nvoid ServerVHDWriter::checkFreeSpaceAndCleanup(void)\r\n{\r\n\tstd::wstring p;\r\n\t{\r\n\t\tIScopedLock lock(vhd_mutex);\r\n\t\tp=ExtractFilePath(vhd->getFilename());\r\n\t}\r\n\tint64 fs=os_free_space(os_file_prefix()+p);\r\n\tif(fs!=-1 && fs <= free_space_lim )\r\n\t{\r\n\t\tServer->Log(\"Not enough free space. Waiting for cleanup...\");\r\n\t\tif(!cleanupSpace())\r\n\t\t{\r\n\t\t\tServer->Log(\"Not enough free space.\", LL_WARNING);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid ServerVHDWriter::writeVHD(uint64 pos, char *buf, unsigned int bsize)\r\n{\r\n\tIScopedLock lock(vhd_mutex);\r\n\tvhd->Seek(pos);\r\n\tbool b=vhd->Write(buf, bsize);\r\n\twritten+=bsize;\r\n\tif(!b)\r\n\t{\r\n\t\tstd::wstring p=ExtractFilePath(vhd->getFilename());\r\n\t\tint64 fs=os_free_space(os_file_prefix()+p);\r\n\t\tif(fs!=-1 && fs <= free_space_lim )\r\n\t\t{\r\n\t\t\tServer->Log(\"Not enough free space. Waiting for cleanup...\");\r\n\t\t\tif(cleanupSpace())\r\n\t\t\t{\r\n\t\t\t\tif(!vhd->Write(buf, bsize))\r\n\t\t\t\t{\r\n\t\t\t\t\tServerLogger::Log(clientid, \"FATAL: Writing failed after cleanup\", LL_ERROR);\r\n\t\t\t\t\thas_error=true;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\thas_error=true;\r\n\t\t\t\tServer->Log(\"FATAL: NOT ENOUGH free space. Cleanup failed.\", LL_ERROR);\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\thas_error=true;\r\n\t\t\tServerLogger::Log(clientid, \"FATAL: Error writing to VHD-File.\", LL_ERROR);\r\n\t\t}\r\n\t}\r\n}\r\n\r\nchar *ServerVHDWriter::getBuffer(void)\r\n{\r\n\tif(filebuffer)\r\n\t\treturn bufmgr->getBuffer()+sizeof(FileBufferVHDItem);\r\n\telse\r\n\t\treturn bufmgr->getBuffer();\r\n}\r\n\r\nvoid ServerVHDWriter::writeBuffer(uint64 pos, char *buf, unsigned int bsize)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tBufferVHDItem item;\r\n\titem.pos=pos;\r\n\titem.buf=buf;\r\n\titem.bsize=bsize;\r\n\ttqueue.push(item);\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerVHDWriter::freeBuffer(char *buf)\r\n{\r\n\tif(filebuffer)\r\n\t\tbufmgr->releaseBuffer(buf-sizeof(FileBufferVHDItem));\r\n\telse\r\n\t\tbufmgr->releaseBuffer(buf);\r\n}\r\n\r\nvoid ServerVHDWriter::doExit(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\texit=true;\r\n\tfinish=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerVHDWriter::doExitNow(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\texit=true;\r\n\texit_now=true;\r\n\tfinish=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerVHDWriter::doFinish(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tfinish=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nsize_t ServerVHDWriter::getQueueSize(void)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\treturn tqueue.size();\r\n}\r\n\r\nbool ServerVHDWriter::hasError(void)\r\n{\r\n\treturn has_error;\r\n}\r\n\r\nIMutex * ServerVHDWriter::getVHDMutex(void)\r\n{\r\n\treturn vhd_mutex;\r\n}\r\n\r\nIVHDFile* ServerVHDWriter::getVHD(void)\r\n{\r\n\treturn vhd;\r\n}\r\n\r\nbool ServerVHDWriter::cleanupSpace(void)\r\n{\r\n\tServerLogger::Log(clientid, \"Not enough free space. Cleaning up.\", LL_INFO);\r\n\tServerCleanupThread cleanup;\r\n\tif(!cleanup.do_cleanup(free_space_lim) )\r\n\t{\r\n\t\tServerLogger::Log(clientid, \"Could not free space for image. NOT ENOUGH FREE SPACE.\", LL_ERROR);\r\n\t\treturn false;\r\n\t}\r\n\treturn true;\r\n}\r\n\r\nvoid ServerVHDWriter::freeFile(IFile *buf)\r\n{\r\n\tfilebuf->releaseBuffer(buf);\r\n}\r\n\r\nvoid ServerVHDWriter::writeRetry(IFile *f, char *buf, unsigned int bsize)\r\n{\r\n\tunsigned int off=0;\r\n\twhile( offWrite(buf+off, bsize-off);\r\n\t\toff+=r;\r\n\t\tif(offLog(\"Error writing to file \\\"\"+f->getFilename()+\"\\\". Retrying\", LL_WARNING);\r\n\t\t\tServer->wait(10000);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\/\/-------------FilebufferWriter-----------------\r\n\r\nServerFileBufferWriter::ServerFileBufferWriter(ServerVHDWriter *pParent, unsigned int pBlocksize) : parent(pParent), blocksize(pBlocksize)\r\n{\r\n\tmutex=Server->createMutex();\r\n\tcond=Server->createCondition();\r\n\texit=false;\r\n\texit_now=false;\r\n\twritten=free_space_lim;\r\n}\r\n\r\nServerFileBufferWriter::~ServerFileBufferWriter(void)\r\n{\r\n\twhile(!fb_queue.empty())\r\n\t{\r\n\t\tparent->freeFile(fb_queue.front());\r\n\t\tfb_queue.pop();\r\n\t}\r\n\tServer->destroy(mutex);\r\n\tServer->destroy(cond);\r\n}\r\n\r\nvoid ServerFileBufferWriter::operator()(void)\r\n{\r\n\tchar *blockbuf=new char[blocksize+sizeof(FileBufferVHDItem)];\r\n\tunsigned int blockbuf_size=blocksize+sizeof(FileBufferVHDItem);\r\n\r\n\twhile(!exit_now)\r\n\t{\r\n\t\tIFile* tmp;\r\n\t\tbool has_item=false;\r\n\t\t{\r\n\t\t\tIScopedLock lock(mutex);\r\n\t\t\twhile(fb_queue.empty() && exit==false)\r\n\t\t\t{\r\n\t\t\t\tcond->wait(&lock);\r\n\t\t\t}\r\n\t\t\tif(!fb_queue.empty())\r\n\t\t\t{\r\n\t\t\t\thas_item=true;\r\n\t\t\t\ttmp=fb_queue.front();\r\n\t\t\t\tfb_queue.pop();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif(has_item)\r\n\t\t{\r\n\t\t\ttmp->Seek(0);\r\n\t\t\tuint64 tpos=0;\r\n\t\t\tuint64 tsize=tmp->Size();\r\n\t\t\twhile(tposhasError())\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned int tw=blockbuf_size;\r\n\t\t\t\t\tbool old_method=false;\r\n\t\t\t\t\tif(twRead(blockbuf, tw)!=tw)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\told_method=true;\r\n\t\t\t\t\t}\r\n\t\t\t\t\telse\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tFileBufferVHDItem *item=(FileBufferVHDItem*)blockbuf;\r\n\t\t\t\t\t\tif(tw==item->bsize+sizeof(FileBufferVHDItem) )\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tparent->writeVHD(item->pos, blockbuf+sizeof(FileBufferVHDItem), item->bsize);\r\n\t\t\t\t\t\t\twritten+=item->bsize;\r\n\t\t\t\t\t\t\ttpos+=item->bsize+sizeof(FileBufferVHDItem);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\telse\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\told_method=true;\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif(old_method==true)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttmp->Seek(tpos);\r\n\t\t\t\t\t\tFileBufferVHDItem item;\r\n\t\t\t\t\t\tif(tmp->Read((char*)&item, sizeof(FileBufferVHDItem))!=sizeof(FileBufferVHDItem))\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tServer->Log(\"Error reading FileBufferVHDItem\", LL_ERROR);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\ttpos+=sizeof(FileBufferVHDItem);\r\n\t\t\t\t\t\tunsigned int tw=item.bsize;\r\n\t\t\t\t\t\tif(tpos+tw>tsize)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tServer->Log(\"Size field is wrong\", LL_ERROR);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(tw>blockbuf_size)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tdelete []blockbuf;\r\n\t\t\t\t\t\t\tblockbuf=new char[tw+sizeof(FileBufferVHDItem)];\r\n\t\t\t\t\t\t\tblockbuf_size=tw+sizeof(FileBufferVHDItem);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tif(tmp->Read(blockbuf, tw)!=tw)\r\n\t\t\t\t\t\t{\r\n\t\t\t\t\t\t\tServer->Log(\"Error reading from tmp.f\", LL_ERROR);\r\n\t\t\t\t\t\t}\r\n\t\t\t\t\t\tparent->writeVHD(item.pos, blockbuf, tw);\r\n\t\t\t\t\t\twritten+=tw;\r\n\t\t\t\t\t\ttpos+=item.bsize;\r\n\t\t\t\t\t}\r\n\r\n\t\t\t\t\tif( written>=free_space_lim\/2)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\twritten=0;\r\n\t\t\t\t\t\tparent->checkFreeSpaceAndCleanup();\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t\telse\r\n\t\t\t\t{\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\tparent->freeFile(tmp);\r\n\t\t}\r\n\t\telse if(exit)\r\n\t\t{\r\n\t\t\tbreak;\r\n\t\t}\r\n\t}\r\n\r\n\tdelete []blockbuf;\r\n}\r\n\r\nvoid ServerFileBufferWriter::doExit(void)\r\n{\r\n\texit=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerFileBufferWriter::doExitNow(void)\r\n{\r\n\texit_now=true;\r\n\texit=true;\r\n\tcond->notify_all();\r\n}\r\n\r\nvoid ServerFileBufferWriter::writeBuffer(IFile *buf)\r\n{\r\n\tIScopedLock lock(mutex);\r\n\tfb_queue.push(buf);\r\n\tcond->notify_all();\r\n}\r\n\r\n#endif \/\/CLIENT_ONLY<|endoftext|>"} {"text":"\/\/ -*- C++ -*-\n\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2021 Alexander Samoilov\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"PoissonProblem.hpp\"\n#include \"ChebyshevDifferentiate.hpp\"\n\nPoissonProblem::PoissonProblem(size_t M, size_t N,\n double x_min, double x_max,\n double y_min, double y_max,\n bool verbose)\n: verbose_(verbose),\n M_(M), N_(N),\n x_grid_(M + 1),\n y_grid_(N + 1),\n ome_ (M + 1, N + 1),\n psi_ (M + 1, N + 1),\n border_(M, N)\n{\n double xa = 0.5*(x_min-x_max);\n double xb = 0.5*(x_min+x_max);\n double ya = 0.5*(y_min-y_max);\n double yb = 0.5*(y_min+y_max);\n\n for (size_t i = 0; i <= M_; ++i) {\n x_grid_[i] = xa*std::cos(M_PI*i\/(double)M_)+xb;\n }\n\n for (size_t i = 0; i <= N_; ++i) {\n y_grid_[i] = ya*std::cos(M_PI*i\/(double)N_)+yb;\n }\n\n if (verbose_) {\n std::cout << \"x_grid: [\" << x_grid_ << \"]\\n\";\n std::cout << \"y_grid: [\" << y_grid_ << \"]\\n\";\n }\n\n \/\/ zero boundary conditions\n border_.left_ = RowVectorXd::Zero(M_ + 1);\n border_.down_ = RowVectorXd::Zero(N_ + 1);\n border_.right_ = RowVectorXd::Zero(M_ + 1);\n border_.up_ = RowVectorXd::Zero(N_ + 1);\n\n \/\/ fill right hand function\n for (size_t i = 0; i <= M_; ++i) {\n for (size_t j = 0; j <= N_; ++j) {\n ome_(i, j) = 32.*M_PI*M_PI * std::sin(4.*M_PI*x_grid_[i])\n * std::sin(4.*M_PI*y_grid_[j]);\n }\n }\n}\n\nvoid PoissonProblem::generate_matrix(size_t n, Eigen::Ref ma)\n{\n \/\/ TODO use MatrixXd::Identity(rows,cols)\n for (size_t i=0; i<=n; ++i) {\n for (size_t j=0; j<=n; ++j) {\n ma(i, j) = detail::id(i, j);\n }\n }\n laplacian(n, ma, ma);\n}\n\nvoid PoissonProblem::homogeneous_boundary(size_t n,\n Eigen::Ref in,\n Eigen::Ref out)\n{\n for (size_t i=0; i<=n; i++) {\n double evens = 0.0, odds = 0.0;\n for (size_t j=1; j<=n-2; j+=2) {\n odds -= in(i, j);\n evens -= in(i, j+1);\n }\n\n if (out != in) {\n for (size_t j=0; j<=n-2; j++) {\n out(i, j) = in(i, j);\n }\n }\n\n out(i, n-1) = odds;\n out(i, n) = evens-in(i, 0);\n\/*\n out(i, 0) = out(i, 1) = 0.0;\n*\/\n }\n}\n\nvoid PoissonProblem::laplacian(size_t n,\n Eigen::Ref in,\n Eigen::Ref out)\n{\n homogeneous_boundary(n, in, out);\n for (size_t i = 0; i <= n; ++i) {\n }\n}\nimplemented laplacian in spectral space.\/\/ -*- C++ -*-\n\n\/\/ The MIT License (MIT)\n\/\/\n\/\/ Copyright (c) 2021 Alexander Samoilov\n\/\/\n\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/ in the Software without restriction, including without limitation the rights\n\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/ furnished to do so, subject to the following conditions:\n\/\/\n\/\/ The above copyright notice and this permission notice shall be included in all\n\/\/ copies or substantial portions of the Software.\n\/\/\n\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n\/\/ SOFTWARE.\n\n#include \"PoissonProblem.hpp\"\n#include \"ChebyshevDifferentiate.hpp\"\n\nPoissonProblem::PoissonProblem(size_t M, size_t N,\n double x_min, double x_max,\n double y_min, double y_max,\n bool verbose)\n: verbose_(verbose),\n M_(M), N_(N),\n x_grid_(M + 1),\n y_grid_(N + 1),\n ome_ (M + 1, N + 1),\n psi_ (M + 1, N + 1),\n border_(M, N)\n{\n double xa = 0.5*(x_min-x_max);\n double xb = 0.5*(x_min+x_max);\n double ya = 0.5*(y_min-y_max);\n double yb = 0.5*(y_min+y_max);\n\n for (size_t i = 0; i <= M_; ++i) {\n x_grid_[i] = xa*std::cos(M_PI*i\/(double)M_)+xb;\n }\n\n for (size_t i = 0; i <= N_; ++i) {\n y_grid_[i] = ya*std::cos(M_PI*i\/(double)N_)+yb;\n }\n\n if (verbose_) {\n std::cout << \"x_grid: [\" << x_grid_ << \"]\\n\";\n std::cout << \"y_grid: [\" << y_grid_ << \"]\\n\";\n }\n\n \/\/ zero boundary conditions\n border_.left_ = RowVectorXd::Zero(M_ + 1);\n border_.down_ = RowVectorXd::Zero(N_ + 1);\n border_.right_ = RowVectorXd::Zero(M_ + 1);\n border_.up_ = RowVectorXd::Zero(N_ + 1);\n\n \/\/ fill right hand function\n for (size_t i = 0; i <= M_; ++i) {\n for (size_t j = 0; j <= N_; ++j) {\n ome_(i, j) = 32.*M_PI*M_PI * std::sin(4.*M_PI*x_grid_[i])\n * std::sin(4.*M_PI*y_grid_[j]);\n }\n }\n}\n\nvoid PoissonProblem::generate_matrix(size_t n, Eigen::Ref ma)\n{\n \/\/ TODO use MatrixXd::Identity(rows,cols)\n for (size_t i=0; i<=n; ++i) {\n for (size_t j=0; j<=n; ++j) {\n ma(i, j) = detail::id(i, j);\n }\n }\n laplacian(n, ma, ma);\n}\n\nvoid PoissonProblem::homogeneous_boundary(size_t n,\n Eigen::Ref in,\n Eigen::Ref out)\n{\n for (size_t i=0; i<=n; i++) {\n double evens = 0.0, odds = 0.0;\n for (size_t j=1; j<=n-2; j+=2) {\n odds -= in(i, j);\n evens -= in(i, j+1);\n }\n\n if (out != in) {\n for (size_t j=0; j<=n-2; j++) {\n out(i, j) = in(i, j);\n }\n }\n\n out(i, n-1) = odds;\n out(i, n) = evens-in(i, 0);\n\/*\n out(i, 0) = out(i, 1) = 0.0;\n*\/\n }\n}\n\nvoid PoissonProblem::laplacian(size_t n,\n Eigen::Ref in,\n Eigen::Ref out)\n{\n homogeneous_boundary(n, in, out);\n for (size_t i = 0; i <= n; ++i) {\n spectral_differentiate(n, out.row(i), out.row(i));\n spectral_differentiate(n, out.row(i), out.row(i));\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/values.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/json_value_serializer.h\"\n\n\/\/ ExtensionsService\n\nconst FilePath::CharType* ExtensionsService::kInstallDirectoryName =\n FILE_PATH_LITERAL(\"Extensions\");\n\nExtensionsService::ExtensionsService(const FilePath& profile_directory)\n : message_loop_(MessageLoop::current()),\n backend_(new ExtensionsServiceBackend),\n install_directory_(profile_directory.Append(kInstallDirectoryName)) {\n}\n\nExtensionsService::~ExtensionsService() {\n for (ExtensionList::iterator iter = extensions_.begin();\n iter != extensions_.end(); ++iter) {\n delete *iter;\n }\n}\n\nbool ExtensionsService::Init() {\n \/\/ TODO(aa): This message loop should probably come from a backend\n \/\/ interface, similar to how the message loop for the frontend comes\n \/\/ from the frontend interface.\n g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,\n NewRunnableMethod(backend_.get(),\n &ExtensionsServiceBackend::LoadExtensionsFromDirectory,\n install_directory_,\n scoped_refptr(this)));\n \/\/ TODO(aa): Load extensions from other registered directories.\n\n return true;\n}\n\nMessageLoop* ExtensionsService::GetMessageLoop() {\n return message_loop_;\n}\n\nvoid ExtensionsService::OnExtensionsLoadedFromDirectory(\n ExtensionList* new_extensions) {\n extensions_.insert(extensions_.end(), new_extensions->begin(),\n new_extensions->end());\n delete new_extensions;\n\n \/\/ TODO(aa): Notify extensions are loaded.\n}\n\nvoid ExtensionsService::OnExtensionLoadError(const std::string& error) {\n \/\/ TODO(aa): Print the error message out somewhere better. I think we are\n \/\/ going to need some sort of 'extension inspector'.\n LOG(WARNING) << error;\n}\n\n\n\/\/ ExtensionsServicesBackend\n\nbool ExtensionsServiceBackend::LoadExtensionsFromDirectory(\n const FilePath& path,\n scoped_refptr frontend) {\n \/\/ Find all child directories in the install directory and load their\n \/\/ manifests. Post errors and results to the frontend.\n scoped_ptr extensions(new ExtensionList);\n file_util::FileEnumerator enumerator(path.ToWStringHack(),\n false, \/\/ not recursive\n file_util::FileEnumerator::DIRECTORIES);\n for (std::wstring child_path = enumerator.Next(); !child_path.empty();\n child_path = enumerator.Next()) {\n FilePath manifest_path = FilePath::FromWStringHack(child_path).Append(\n Extension::kManifestFilename);\n if (!file_util::PathExists(manifest_path)) {\n ReportExtensionLoadError(frontend.get(), child_path,\n Extension::kInvalidManifestError);\n continue;\n }\n\n JSONFileValueSerializer serializer(manifest_path.ToWStringHack());\n Value* root = NULL;\n std::string error;\n if (!serializer.Deserialize(&root, &error)) {\n ReportExtensionLoadError(frontend.get(), child_path, error);\n continue;\n }\n\n scoped_ptr scoped_root(root);\n if (!root->IsType(Value::TYPE_DICTIONARY)) {\n ReportExtensionLoadError(frontend.get(), child_path,\n Extension::kInvalidManifestError);\n continue;\n }\n\n scoped_ptr extension(new Extension());\n if (!extension->InitFromValue(*static_cast(root),\n &error)) {\n ReportExtensionLoadError(frontend.get(), child_path, error);\n continue;\n }\n\n extensions->push_back(extension.release());\n delete root;\n }\n\n ReportExtensionsLoaded(frontend.get(), extensions.release());\n return true;\n}\n\nvoid ExtensionsServiceBackend::ReportExtensionLoadError(\n ExtensionsServiceFrontendInterface *frontend, const std::wstring& path,\n const std::string &error) {\n std::string message = StringPrintf(\"Could not load extension from '%s'. %s\",\n WideToASCII(path).c_str(), error.c_str());\n frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(\n frontend, &ExtensionsServiceFrontendInterface::OnExtensionLoadError,\n message));\n}\n\nvoid ExtensionsServiceBackend::ReportExtensionsLoaded(\n ExtensionsServiceFrontendInterface *frontend, ExtensionList* extensions) {\n frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(\n frontend,\n &ExtensionsServiceFrontendInterface::OnExtensionsLoadedFromDirectory,\n extensions));\n}\nbad merge, no need to delete a scoped_ptr\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/extensions\/extensions_service.h\"\n\n#include \"base\/file_util.h\"\n#include \"base\/values.h\"\n#include \"base\/string_util.h\"\n#include \"base\/thread.h\"\n#include \"chrome\/browser\/browser_process.h\"\n#include \"chrome\/common\/json_value_serializer.h\"\n\n\/\/ ExtensionsService\n\nconst FilePath::CharType* ExtensionsService::kInstallDirectoryName =\n FILE_PATH_LITERAL(\"Extensions\");\n\nExtensionsService::ExtensionsService(const FilePath& profile_directory)\n : message_loop_(MessageLoop::current()),\n backend_(new ExtensionsServiceBackend),\n install_directory_(profile_directory.Append(kInstallDirectoryName)) {\n}\n\nExtensionsService::~ExtensionsService() {\n for (ExtensionList::iterator iter = extensions_.begin();\n iter != extensions_.end(); ++iter) {\n delete *iter;\n }\n}\n\nbool ExtensionsService::Init() {\n \/\/ TODO(aa): This message loop should probably come from a backend\n \/\/ interface, similar to how the message loop for the frontend comes\n \/\/ from the frontend interface.\n g_browser_process->file_thread()->message_loop()->PostTask(FROM_HERE,\n NewRunnableMethod(backend_.get(),\n &ExtensionsServiceBackend::LoadExtensionsFromDirectory,\n install_directory_,\n scoped_refptr(this)));\n \/\/ TODO(aa): Load extensions from other registered directories.\n\n return true;\n}\n\nMessageLoop* ExtensionsService::GetMessageLoop() {\n return message_loop_;\n}\n\nvoid ExtensionsService::OnExtensionsLoadedFromDirectory(\n ExtensionList* new_extensions) {\n extensions_.insert(extensions_.end(), new_extensions->begin(),\n new_extensions->end());\n delete new_extensions;\n\n \/\/ TODO(aa): Notify extensions are loaded.\n}\n\nvoid ExtensionsService::OnExtensionLoadError(const std::string& error) {\n \/\/ TODO(aa): Print the error message out somewhere better. I think we are\n \/\/ going to need some sort of 'extension inspector'.\n LOG(WARNING) << error;\n}\n\n\n\/\/ ExtensionsServicesBackend\n\nbool ExtensionsServiceBackend::LoadExtensionsFromDirectory(\n const FilePath& path,\n scoped_refptr frontend) {\n \/\/ Find all child directories in the install directory and load their\n \/\/ manifests. Post errors and results to the frontend.\n scoped_ptr extensions(new ExtensionList);\n file_util::FileEnumerator enumerator(path.ToWStringHack(),\n false, \/\/ not recursive\n file_util::FileEnumerator::DIRECTORIES);\n for (std::wstring child_path = enumerator.Next(); !child_path.empty();\n child_path = enumerator.Next()) {\n FilePath manifest_path = FilePath::FromWStringHack(child_path).Append(\n Extension::kManifestFilename);\n if (!file_util::PathExists(manifest_path)) {\n ReportExtensionLoadError(frontend.get(), child_path,\n Extension::kInvalidManifestError);\n continue;\n }\n\n JSONFileValueSerializer serializer(manifest_path.ToWStringHack());\n Value* root = NULL;\n std::string error;\n if (!serializer.Deserialize(&root, &error)) {\n ReportExtensionLoadError(frontend.get(), child_path, error);\n continue;\n }\n\n scoped_ptr scoped_root(root);\n if (!root->IsType(Value::TYPE_DICTIONARY)) {\n ReportExtensionLoadError(frontend.get(), child_path,\n Extension::kInvalidManifestError);\n continue;\n }\n\n scoped_ptr extension(new Extension());\n if (!extension->InitFromValue(*static_cast(root),\n &error)) {\n ReportExtensionLoadError(frontend.get(), child_path, error);\n continue;\n }\n\n extensions->push_back(extension.release());\n }\n\n ReportExtensionsLoaded(frontend.get(), extensions.release());\n return true;\n}\n\nvoid ExtensionsServiceBackend::ReportExtensionLoadError(\n ExtensionsServiceFrontendInterface *frontend, const std::wstring& path,\n const std::string &error) {\n std::string message = StringPrintf(\"Could not load extension from '%s'. %s\",\n WideToASCII(path).c_str(), error.c_str());\n frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(\n frontend, &ExtensionsServiceFrontendInterface::OnExtensionLoadError,\n message));\n}\n\nvoid ExtensionsServiceBackend::ReportExtensionsLoaded(\n ExtensionsServiceFrontendInterface *frontend, ExtensionList* extensions) {\n frontend->GetMessageLoop()->PostTask(FROM_HERE, NewRunnableMethod(\n frontend,\n &ExtensionsServiceFrontendInterface::OnExtensionsLoadedFromDirectory,\n extensions));\n}\n<|endoftext|>"} {"text":"\/********************************************************************************\n ** The MIT License (MIT)\n **\n ** Copyright (c) 2013 Sascha Ludwig Häusler\n **\n ** Permission is hereby granted, free of charge, to any person obtaining a copy of\n ** this software and associated documentation files (the \"Software\"), to deal in\n ** the Software without restriction, including without limitation the rights to\n ** use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n ** the Software, and to permit persons to whom the Software is furnished to do so,\n ** subject to the following conditions:\n **\n ** The above copyright notice and this permission notice shall be included in all\n ** copies or substantial portions of the Software.\n **\n ** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n ** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n ** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n ** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n ** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *********************************************************************************\/\n\n#include \"AbstractModel.h\"\n#include \"AbstractModel_p.h\"\n\nnamespace PublicServerSystem\n{\nnamespace Web\n{\nnamespace Model\n{\n\nAbstractModel::AbstractModel(QObject *parent) :\n AbstractModel(new AbstractModelPrivate, parent)\n{\n}\n\nAbstractModel::AbstractModel(arangodb::Document *doc, QObject *parent) :\n AbstractModel(doc, new AbstractModelPrivate, parent)\n{\n}\n\nAbstractModel::AbstractModel(const AbstractModel &mo) :\n AbstractModel(new AbstractModelPrivate, mo.parent())\n{\n Q_D(AbstractModel);\n d->doc = mo.d_ptr->doc;\n}\n\nAbstractModel::~AbstractModel()\n{\n if (! d_ptr->hasDocumentDestroyed) delete d_ptr->doc;\n delete d_ptr;\n}\n\nvoid AbstractModel::save()\n{\n Q_D(AbstractModel);\n\n if ( d->doc->save() ) {\n d->doc->waitForResult();\n }\n}\n\nvoid AbstractModel::saveAndDelete()\n{\n Q_D(AbstractModel);\n\n d->hasDocumentDestroyed = true;\n\n QObject::connect( d->doc, &arangodb::Document::destroyed,\n this, &AbstractModel::deleteLater\n );\n\n d->doc->save();\n d->doc->deleteAfterFinished();\n}\n\nQString AbstractModel::dbCollectionKey() const\n{\n Q_D(const AbstractModel);\n return d->doc->key();\n}\n\nAbstractModel::AbstractModel(arangodb::Document *doc, AbstractModelPrivate *ptr, QObject *parent) :\n AbstractModel(ptr, parent)\n{\n Q_D(AbstractModel);\n d->doc = doc;\n}\n\nAbstractModel::AbstractModel(AbstractModelPrivate *ptr, QObject *parent) :\n QObject(parent),\n d_ptr(ptr)\n{\n}\n\nQVariant AbstractModel::get(const QString &name) const\n{\n Q_D(const AbstractModel);\n\n return d->doc->get(name);\n}\n\nvoid AbstractModel::set(const QString &name, QVariant val)\n{\n Q_D(AbstractModel);\n\n d->doc->set(name, val);\n}\n\nForm::AbstractFormField *AbstractModel::field(const QString &referencingPropertyName, const QMetaObject &fieldClassObj, const QString &description)\n{\n Q_D(AbstractModel);\n\n Form::AbstractFormField * thisField;\n\n \/\/ If the field has already been created\n if (d->fields.contains(referencingPropertyName)) {\n thisField = d->fields.value(referencingPropertyName);\n }\n else {\n thisField = qobject_cast(fieldClassObj.newInstance(\n Q_ARG(QString, referencingPropertyName),\n Q_ARG(QString, description),\n Q_ARG(QObject *, 0)\n ));\n d->fields.insert(referencingPropertyName, thisField);\n }\n\n \/\/ Get current value for the field\n thisField->setValue(d->doc->get(referencingPropertyName));\n\n return thisField;\n}\n\n}\n}\n}\nObjects are only saved if they haven't been created\/********************************************************************************\n ** The MIT License (MIT)\n **\n ** Copyright (c) 2013 Sascha Ludwig Häusler\n **\n ** Permission is hereby granted, free of charge, to any person obtaining a copy of\n ** this software and associated documentation files (the \"Software\"), to deal in\n ** the Software without restriction, including without limitation the rights to\n ** use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of\n ** the Software, and to permit persons to whom the Software is furnished to do so,\n ** subject to the following conditions:\n **\n ** The above copyright notice and this permission notice shall be included in all\n ** copies or substantial portions of the Software.\n **\n ** THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n ** IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS\n ** FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n ** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER\n ** IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n ** CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *********************************************************************************\/\n\n#include \"AbstractModel.h\"\n#include \"AbstractModel_p.h\"\n\nnamespace PublicServerSystem\n{\nnamespace Web\n{\nnamespace Model\n{\n\nAbstractModel::AbstractModel(QObject *parent) :\n AbstractModel(new AbstractModelPrivate, parent)\n{\n}\n\nAbstractModel::AbstractModel(arangodb::Document *doc, QObject *parent) :\n AbstractModel(doc, new AbstractModelPrivate, parent)\n{\n}\n\nAbstractModel::AbstractModel(const AbstractModel &mo) :\n AbstractModel(new AbstractModelPrivate, mo.parent())\n{\n Q_D(AbstractModel);\n d->doc = mo.d_ptr->doc;\n}\n\nAbstractModel::~AbstractModel()\n{\n if (! d_ptr->hasDocumentDestroyed) delete d_ptr->doc;\n delete d_ptr;\n}\n\nvoid AbstractModel::save()\n{\n Q_D(AbstractModel);\n\n if ( d->doc->isCreated() ) {\n d->doc->update();\n d->doc->waitForResult();\n }\n else if ( d->doc->save() ) {\n d->doc->waitForResult();\n }\n}\n\nvoid AbstractModel::saveAndDelete()\n{\n Q_D(AbstractModel);\n\n d->hasDocumentDestroyed = true;\n\n QObject::connect( d->doc, &arangodb::Document::destroyed,\n this, &AbstractModel::deleteLater\n );\n\n d->doc->save();\n d->doc->deleteAfterFinished();\n}\n\nQString AbstractModel::dbCollectionKey() const\n{\n Q_D(const AbstractModel);\n return d->doc->key();\n}\n\nAbstractModel::AbstractModel(arangodb::Document *doc, AbstractModelPrivate *ptr, QObject *parent) :\n AbstractModel(ptr, parent)\n{\n Q_D(AbstractModel);\n d->doc = doc;\n}\n\nAbstractModel::AbstractModel(AbstractModelPrivate *ptr, QObject *parent) :\n QObject(parent),\n d_ptr(ptr)\n{\n}\n\nQVariant AbstractModel::get(const QString &name) const\n{\n Q_D(const AbstractModel);\n\n return d->doc->get(name);\n}\n\nvoid AbstractModel::set(const QString &name, QVariant val)\n{\n Q_D(AbstractModel);\n\n d->doc->set(name, val);\n}\n\nForm::AbstractFormField *AbstractModel::field(const QString &referencingPropertyName, const QMetaObject &fieldClassObj, const QString &description)\n{\n Q_D(AbstractModel);\n\n Form::AbstractFormField * thisField;\n\n \/\/ If the field has already been created\n if (d->fields.contains(referencingPropertyName)) {\n thisField = d->fields.value(referencingPropertyName);\n }\n else {\n thisField = qobject_cast(fieldClassObj.newInstance(\n Q_ARG(QString, referencingPropertyName),\n Q_ARG(QString, description),\n Q_ARG(QObject *, 0)\n ));\n d->fields.insert(referencingPropertyName, thisField);\n }\n\n \/\/ Get current value for the field\n thisField->setValue(d->doc->get(referencingPropertyName));\n\n return thisField;\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"#include \"Halide.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"configure.h\"\n#include \"fused_resnet_block_generator_tiramisu.o.h\"\n#include \nusing namespace std;\n\nbool compareFiles(const std::string &p1, const std::string &p2)\n{\n std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate);\n std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate);\n\n if (f1.fail() || f2.fail())\n {\n return false; \/\/File problem\n }\n\n if (f1.tellg() != f2.tellg())\n {\n return false; \/\/Size mismatch\n }\n\n \/\/Seek back to beginning and use std::equal to compare contents\n f1.seekg(0, std::ifstream::beg);\n f2.seekg(0, std::ifstream::beg);\n return std::equal(std::istreambuf_iterator(f1.rdbuf()),\n std::istreambuf_iterator(),\n std::istreambuf_iterator(f2.rdbuf()));\n}\n\nint main(int, char **)\n{\n Halide::Buffer parameters(2);\n\n Halide::Buffer input(N, N, 3, BATCH_SIZE);\n Halide::Buffer filter1(3, 3, 3, 64);\n Halide::Buffer filter2(3, 3, 64, 64);\n Halide::Buffer padd1(N + 2, N + 2, 3, BATCH_SIZE);\n Halide::Buffer conv1(N, N, 64, BATCH_SIZE);\n Halide::Buffer padd2(N + 2, N + 2, 64, BATCH_SIZE);\n Halide::Buffer conv2(N, N, 64, BATCH_SIZE);\n Halide::Buffer bn1(N, N, 64, BATCH_SIZE);\n Halide::Buffer bn2(N, N, 64, BATCH_SIZE);\n Halide::Buffer mean(N, N, 64, BATCH_SIZE);\n Halide::Buffer variance(N, N, 64, BATCH_SIZE);\n\n std::vector> duration_vector;\n srand(1);\n for (int n = 0; n < BATCH_SIZE; ++n)\n for (int z = 0; z < 3; ++z)\n for (int y = 0; y < N; ++y)\n for (int x = 0; x < N; ++x)\n input(x, y, z, n) = rand() % 1000;\n\n for (int x = 0; x < 3; ++x)\n for (int y = 0; y < 3; ++y)\n for (int z = 0; z < 3; ++z)\n for (int q = 0; q < 64; ++q)\n filter1(x, y, z, q) = 1;\n\n for (int x = 0; x < 3; ++x)\n for (int y = 0; y < 3; ++y)\n for (int z = 0; z < 64; ++z)\n for (int q = 0; q < 64; ++q)\n filter2(x, y, z, q) = 1;\n\n std::cout << \"\\t\\tBuffers initialized\" << std::endl;\n\n \/\/ Initialize parameters[]\n parameters(0) = N;\n parameters(1) = BATCH_SIZE;\n\n for (int i = 0; i < NB_TESTS; i++)\n {\n auto start1 = std::chrono::high_resolution_clock::now();\n fused_resnet_block(parameters.raw_buffer(), filter1.raw_buffer(),\n filter2.raw_buffer(), input.raw_buffer(), padd1.raw_buffer(),\n conv1.raw_buffer(), mean.raw_buffer(), variance.raw_buffer(),\n bn1.raw_buffer(), padd2.raw_buffer(), conv2.raw_buffer(), bn2.raw_buffer());\n auto end1 = std::chrono::high_resolution_clock::now();\n std::chrono::duration duration = end1 - start1;\n duration_vector.push_back(duration);\n }\n std::cout << \"\\t\\tTiramisu convolution duration\"\n << \": \" << median(duration_vector) << \"; \" << std::endl;\n\n std::ofstream resultfile;\n resultfile.open(\"tiramisu_result.txt\");\n\n for (int n = 0; n < BATCH_SIZE; ++n)\n for (int z = 0; z < 64; ++z)\n for (int y = 0; y < N; ++y)\n for (int x = 0; x < N; ++x)\n resultfile << fixed << setprecision(2) << (float)((int)(bn2(x, y, z, n) * 1000) \/ 1000.0);\n resultfile.close();\n\n std::cout << \"\\t\\t Result\"\n << \":\\n\\n\";\n\n FILE *fp1, *fp2;\n char line1[5], line2[5];\n\n float file_count = 0, corr = 0;\n fp1 = fopen(\"tiramisu_result.txt\", \"r\");\n fp2 = fopen(\"mkldnn_result.txt\", \"r\");\n\n while (!feof(fp1))\n {\n fgets(line1, sizeof(line1), fp1);\n fgets(line2, sizeof(line2), fp2);\n file_count += 1;\n if (strcmp(line1, line2) == 0)\n corr += 1;\n }\n fclose(fp1);\n fclose(fp2);\n\n printf(\"\\t\\t Percentage of correctness %f \\n\\n\", corr \/ file_count * 100);\n\n return 0;\n}\nCorrectness test modifed#include \"Halide.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"configure.h\"\n#include \"fused_resnet_block_generator_tiramisu.o.h\"\n#include \nusing namespace std;\n\nbool compareFiles(const std::string &p1, const std::string &p2)\n{\n std::ifstream f1(p1, std::ifstream::binary | std::ifstream::ate);\n std::ifstream f2(p2, std::ifstream::binary | std::ifstream::ate);\n\n if (f1.fail() || f2.fail())\n {\n return false; \/\/File problem\n }\n\n if (f1.tellg() != f2.tellg())\n {\n return false; \/\/Size mismatch\n }\n\n \/\/Seek back to beginning and use std::equal to compare contents\n f1.seekg(0, std::ifstream::beg);\n f2.seekg(0, std::ifstream::beg);\n return std::equal(std::istreambuf_iterator(f1.rdbuf()),\n std::istreambuf_iterator(),\n std::istreambuf_iterator(f2.rdbuf()));\n}\n\nint main(int, char **)\n{\n Halide::Buffer parameters(2);\n\n Halide::Buffer input(N, N, 3, BATCH_SIZE);\n Halide::Buffer filter1(3, 3, 3, 64);\n Halide::Buffer filter2(3, 3, 64, 64);\n Halide::Buffer padd1(N + 2, N + 2, 3, BATCH_SIZE);\n Halide::Buffer conv1(N, N, 64, BATCH_SIZE);\n Halide::Buffer padd2(N + 2, N + 2, 64, BATCH_SIZE);\n Halide::Buffer conv2(N, N, 64, BATCH_SIZE);\n Halide::Buffer bn1(N, N, 64, BATCH_SIZE);\n Halide::Buffer bn2(N, N, 64, BATCH_SIZE);\n Halide::Buffer mean(N, N, 64, BATCH_SIZE);\n Halide::Buffer variance(N, N, 64, BATCH_SIZE);\n\n std::vector> duration_vector;\n srand(1);\n for (int n = 0; n < BATCH_SIZE; ++n)\n for (int z = 0; z < 3; ++z)\n for (int y = 0; y < N; ++y)\n for (int x = 0; x < N; ++x)\n input(x, y, z, n) = rand() % 1000;\n\n for (int x = 0; x < 3; ++x)\n for (int y = 0; y < 3; ++y)\n for (int z = 0; z < 3; ++z)\n for (int q = 0; q < 64; ++q)\n filter1(x, y, z, q) = 1;\n\n for (int x = 0; x < 3; ++x)\n for (int y = 0; y < 3; ++y)\n for (int z = 0; z < 64; ++z)\n for (int q = 0; q < 64; ++q)\n filter2(x, y, z, q) = 1;\n\n std::cout << \"\\t\\tBuffers initialized\" << std::endl;\n\n \/\/ Initialize parameters[]\n parameters(0) = N;\n parameters(1) = BATCH_SIZE;\n\n for (int i = 0; i < NB_TESTS; i++)\n {\n auto start1 = std::chrono::high_resolution_clock::now();\n fused_resnet_block(parameters.raw_buffer(), filter1.raw_buffer(),\n filter2.raw_buffer(), input.raw_buffer(), padd1.raw_buffer(),\n conv1.raw_buffer(), mean.raw_buffer(), variance.raw_buffer(),\n bn1.raw_buffer(), padd2.raw_buffer(), conv2.raw_buffer(), bn2.raw_buffer());\n auto end1 = std::chrono::high_resolution_clock::now();\n std::chrono::duration duration = end1 - start1;\n duration_vector.push_back(duration);\n }\n std::cout << \"\\t\\tTiramisu convolution duration\"\n << \": \" << median(duration_vector) << \"; \" << std::endl;\n\n std::ofstream resultfile;\n resultfile.open(\"tiramisu_result.txt\");\n\n for (int n = 0; n < BATCH_SIZE; ++n)\n for (int z = 0; z < 64; ++z)\n for (int y = 0; y < N; ++y)\n for (int x = 0; x < N; ++x)\n {\n resultfile << fixed << setprecision(2) << (float)((int)(bn2(x, y, z, n) * 1000) \/ 1000.0);\n resultfile << \"\\n\";\n }\n resultfile.close();\n\n std::cout << \"\\t\\t Result\"\n << \":\\n\\n\";\n\n std::ifstream infile1(\"tiramisu_result.txt\"), infile2(\"mkldnn_result.txt\");\n std::string line1, line2;\n float file_count = 0, corr = 0, f1, f2;\n \n while (std::getline(infile1, line1))\n {\n std::getline(infile2, line2);\n file_count += 1;\n f1 = std::stof(line1);\n f2 = std::stof(line2);\n\n if (f1 - f2 <= 0.01)\n corr += 1;\n }\n\n printf(\"\\t\\t Percentage of correctness %f \\n\\n\", corr \/ file_count * 100);\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ These declarations should remain global because we have to refer to\n\/\/ them in utility functions that are living outside of `main()`.\nusing DataType = double;\nusing VertexType = unsigned short;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\nusing PersistenceDiagram = aleph::PersistenceDiagram;\nusing Point = typename PersistenceDiagram::Point;\n\nPersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )\n{\n PersistenceDiagram F;\n\n if( D.dimension() != F.dimension() )\n throw std::runtime_error( \"Persistence diagram dimensions have to agree\" );\n\n for( auto&& diagram : { D, E } )\n for( auto&& p : diagram )\n F.add( p.x(), p.y() );\n\n return F;\n}\n\ntemplate\n<\n class Engine, \/\/ random engine to use for weight generation (e.g. std::default_random_engine)\n class Distribution \/\/ distribution to use for weight generation (e.g. std::uniform_real_distribution)\n>\nSimplicialComplex makeRandomStratifiedGraph(\n const std::vector& strata,\n Engine& engine,\n Distribution& distribution\n)\n{\n auto n = strata.size();\n\n if( n <= 1 )\n throw std::runtime_error( \"Invalid number of strata\" );\n\n std::vector simplices;\n\n \/\/ Create vertices ---------------------------------------------------\n \/\/\n \/\/ The `strata` vector contains the size of each stratum, so we just\n \/\/ have to add the correct number of vertices here.\n\n VertexType index = VertexType(0);\n for( auto&& stratum : strata )\n {\n for( unsigned i = 0; i < stratum; i++ )\n simplices.push_back( Simplex( index++ ) );\n }\n\n \/\/ Create edges ------------------------------------------------------\n \/\/\n \/\/ Every stratum is connected to every other stratum, but there are no\n \/\/ connections *within* a given stratum.\n\n VertexType offset = VertexType(0);\n for( decltype(n) i = 0; i < n - 1; i++ )\n {\n \/\/ All vertices in the next stratum start with this offset to their\n \/\/ indices. It depends on the sum of all vertices in *all* previous\n \/\/ strata.\n offset += strata[i];\n\n for( unsigned j = 0; j < strata[i]; j++ )\n {\n for( unsigned k = 0; k < strata[i+1]; k++ )\n {\n simplices.push_back(\n Simplex(\n {\n VertexType( offset - strata[i] + j ),\n VertexType( offset + k )\n },\n distribution( engine )\n )\n );\n }\n }\n }\n\n return SimplicialComplex( simplices.begin(), simplices.end() );\n}\n\nSimplicialComplex applyFiltration( const SimplicialComplex& K,\n const std::string& strategy,\n bool reverse = false )\n{\n auto L = K;\n\n if( strategy == \"standard\" )\n {\n if( reverse )\n {\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n }\n else\n {\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n }\n }\n else if( strategy == \"absolute\" )\n {\n if( reverse )\n {\n auto functor = [] ( const Simplex& s, const Simplex& t )\n {\n auto w1 = s.data();\n auto w2 = t.data();\n\n if( std::abs( w1 ) > std::abs( w2 ) )\n return true;\n else if( std::abs( w1 ) == std::abs( w2 ) )\n {\n \/\/ This amounts to saying that w1 is positive and w2 is\n \/\/ negative.\n if( w1 > w2 )\n return true;\n else\n {\n if( s.dimension() < t.dimension() )\n return true;\n\n \/\/ Absolute value is equal, signed value is equal, and the\n \/\/ dimension is equal. We thus have to fall back to merely\n \/\/ using the lexicographical order.\n else\n return s < t;\n }\n }\n\n return false;\n };\n\n L.sort( functor );\n }\n else\n {\n auto functor = [] ( const Simplex& s, const Simplex& t )\n {\n auto w1 = s.data();\n auto w2 = t.data();\n\n if( std::abs( w1 ) < std::abs( w2 ) )\n return true;\n else if( std::abs( w1 ) == std::abs( w2 ) )\n {\n \/\/ This amounts to saying that w1 is negative and w2 is\n \/\/ positive.\n if( w1 < w2 )\n return true;\n else\n {\n if( s.dimension() < t.dimension() )\n return true;\n\n \/\/ Absolute value is equal, signed value is equal, and the\n \/\/ dimension is equal. We thus have to fall back to merely\n \/\/ using the lexicographical order.\n else\n return s < t;\n }\n }\n\n return false;\n };\n\n L.sort( functor );\n }\n }\n\n return L;\n}\n\nSimplicialComplex assignVertexWeights( const SimplicialComplex& K,\n const std::string& strategy,\n bool reverse = false )\n{\n DataType minData = std::numeric_limits::max();\n DataType maxData = std::numeric_limits::lowest();\n\n for( auto&& s : K )\n {\n if( s.dimension() != 1 )\n continue;\n\n minData = std::min( minData, s.data() );\n maxData = std::max( maxData, s.data() );\n }\n\n \/\/ Setting up the weights --------------------------------------------\n \/\/\n \/\/ This function assumes that the simplicial complex is already in\n \/\/ filtration ordering with respect to its weights. Hence, we only\n \/\/ have to take the *first* weight that we encounter (when using a\n \/\/ global vertex weight assignment) or the *extremal* value, which\n \/\/ is either a minimum or a maximum depending on the direction.\n\n std::unordered_map weight;\n\n for( auto&& s : K )\n {\n if( s.dimension() != 1 )\n continue;\n\n auto u = s[0];\n auto v = s[1];\n DataType w = DataType(); \/\/ weight to assign; depends on filtration\n\n \/\/ Assign the global minimum or maximum. This is rather wasteful\n \/\/ because the values do not change, but at least the code makes\n \/\/ it clear that all updates are done in the same place.\n if( strategy == \"global\" )\n w = reverse ? maxData : minData;\n else if( strategy == \"local\" )\n w = s.data();\n else\n throw std::runtime_error( \"Unknown update strategy '\" + strategy + \"'\" );\n\n \/\/ This only performs the update *once*.\n weight.insert( {u,w} );\n weight.insert( {v,w} );\n }\n\n \/\/ Assign the weights ------------------------------------------------\n \/\/\n \/\/ Having set up the map of weights, we now only need to traverse it\n \/\/ in order to assign weights afterwards.\n\n auto L = K;\n\n for( auto it = L.begin(); it != L.end(); ++it )\n {\n if( it->dimension() == 0 )\n {\n auto s = *it; \/\/ simplex\n auto v = s[0]; \/\/ vertex\n\n s.setData( weight.at(v) );\n\n auto result = L.replace( it, s );\n if( !result )\n throw std::runtime_error( \"Unable to replace simplex in simplicial complex\" );\n }\n }\n\n return L;\n}\n\ntemplate std::vector loadSimplicialComplexes( int argc, char** argv )\n{\n Reader reader;\n\n std::vector simplicialComplexes;\n simplicialComplexes.reserve( static_cast( argc - optind ) );\n\n for( int i = optind; i < argc; i++ )\n {\n auto filename = std::string( argv[i] );\n\n std::cerr << \"* Processing \" << filename << \"...\";\n\n SimplicialComplex K;\n reader( filename, K );\n\n std::cerr << \"finished\\n\";\n\n simplicialComplexes.emplace_back( K );\n }\n\n return simplicialComplexes;\n}\n\nint main( int argc, char** argv )\n{\n bool bipartite = false;\n bool normalize = false;\n bool reverse = false;\n bool verbose = false;\n bool calculateDiagrams = false;\n\n \/\/ The default filtration sorts simplices by their weights. Negative\n \/\/ weights are treated as being less relevant than positive ones.\n std::string filtration = \"standard\";\n\n \/\/ Defines how the minimum value for the vertices is to be set. Valid\n \/\/ options include:\n \/\/\n \/\/ - global (uses the global extremal value)\n \/\/ - local (uses the local extremal value over all neighbours)\n std::string weights = \"global\";\n\n {\n static option commandLineOptions[] =\n {\n { \"bipartite\" , no_argument, nullptr, 'b' },\n { \"normalize\" , no_argument, nullptr, 'n' },\n { \"persistence-diagrams\", no_argument, nullptr, 'p' },\n { \"reverse\" , no_argument, nullptr, 'r' },\n { \"verbose\" , no_argument, nullptr, 'v' },\n { \"filtration\" , required_argument, nullptr, 'f' },\n { \"weights\" , required_argument, nullptr, 'w' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"bnprtvf:w:\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'b':\n bipartite = true;\n break;\n case 'f':\n filtration = optarg;\n break;\n case 'n':\n normalize = true;\n break;\n case 'p':\n calculateDiagrams = true;\n break;\n case 'r':\n reverse = true;\n break;\n case 'v':\n verbose = true;\n break;\n case 'w':\n weights = optarg;\n break;\n default:\n break;\n }\n }\n\n \/\/ Check filtration validity ---------------------------------------\n\n if( filtration != \"absolute\"\n && filtration != \"standard\" )\n {\n std::cerr << \"* Invalid filtration value '\" << filtration << \"', so falling back to standard one\\n\";\n filtration = \"standard\";\n }\n\n \/\/ Check validity of weight strategy -------------------------------\n\n if( weights != \"global\"\n && weights != \"local\" )\n {\n std::cerr << \"* Invalid weight strategy value '\" << weights << \"', so falling back to global one\\n\";\n weights = \"global\";\n }\n }\n\n \/\/ Be verbose about parameters ---------------------------------------\n\n if( bipartite )\n std::cerr << \"* Mode: reading bipartite adjacency matrices\\n\";\n else\n std::cerr << \"* Mode: reading edge lists\\n\";\n\n std::cerr << \"* Filtration: \" << filtration\n << \" (\" << ( reverse ? \"\" : \"not \" ) << \"reversed\" << \")\\n\"\n << \"* Vertex weight assignment strategy: \" << weights << \"\\n\";\n\n if( verbose )\n std::cerr << \"* Verbose output\\n\";\n\n \/\/ 1. Read simplicial complexes --------------------------------------\n\n std::vector simplicialComplexes;\n simplicialComplexes.reserve( static_cast( argc - optind - 1 ) );\n\n std::vector minData;\n std::vector maxData;\n\n minData.reserve( simplicialComplexes.size() );\n maxData.reserve( simplicialComplexes.size() );\n\n if( argc - optind >= 1 )\n {\n if( bipartite )\n {\n using Reader = aleph::topology::io::BipartiteAdjacencyMatrixReader;\n\n simplicialComplexes\n = loadSimplicialComplexes( argc, argv );\n }\n }\n else\n {\n std::default_random_engine engine;\n engine.seed(\n static_cast(\n std::chrono::system_clock::now().time_since_epoch().count()\n )\n );\n\n DataType minWeight = DataType(-1);\n DataType maxWeight = DataType( 1);\n\n std::uniform_real_distribution distribution(\n minWeight,\n std::nextafter( maxWeight, std::numeric_limits::max() )\n );\n\n for( unsigned i = 0; i < 1e5; i++ )\n {\n auto K\n = makeRandomStratifiedGraph( {2,3}, \/\/ FIXME: {2,3,1} for the complete network\n engine,\n distribution\n );\n\n simplicialComplexes.emplace_back( K );\n }\n }\n\n \/\/ Determine minimum and maximum values for each complex -------------\n\n for( auto&& K : simplicialComplexes )\n {\n DataType minData_ = std::numeric_limits::max();\n DataType maxData_ = std::numeric_limits::lowest();\n\n \/\/ *Always* determine minimum and maximum weights so that we may\n \/\/ report them later on. They are only used for normalization in\n \/\/ the persistence diagram calculation step.\n for( auto&& s : K )\n {\n minData_ = std::min( minData_, s.data() );\n maxData_ = std::max( maxData_, s.data() );\n }\n\n minData.push_back( minData_ );\n maxData.push_back( maxData_ );\n }\n\n \/\/ Establish filtration order ----------------------------------------\n\n for( auto&& K : simplicialComplexes )\n {\n K = applyFiltration( K, filtration, reverse );\n K = assignVertexWeights( K, weights, reverse );\n K = applyFiltration( K, filtration, reverse );\n }\n\n \/\/ 2. Calculate persistent homology ----------------------------------\n\n for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )\n {\n \/\/ The persistence diagram that will be used in the subsequent\n \/\/ analysis. This does not necessarily have to stem from data,\n \/\/ but can be calculated from a suitable transformation.\n PersistenceDiagram D;\n\n auto&& K = simplicialComplexes[i];\n auto diagrams = aleph::calculatePersistenceDiagrams( K );\n D = diagrams.back(); \/\/ Use the *last* diagram of the filtration so that\n \/\/ we get features in the highest dimension.\n\n D.removeDiagonal();\n D.removeUnpaired();\n\n if( normalize )\n {\n \/\/ Ensures that all weights are in [0:1] for the corresponding\n \/\/ diagram. This enables the comparison of time-varying graphs\n \/\/ or different instances.\n std::transform( D.begin(), D.end(), D.begin(),\n [&i, &minData, &maxData] ( const Point& p )\n {\n auto x = p.x();\n auto y = p.y();\n\n if( minData[i] != maxData[i] )\n {\n x = (x - minData[i]) \/ (maxData[i] - minData[i]);\n y = (y - minData[i]) \/ (maxData[i] - minData[i]);\n }\n\n return Point( x,y );\n }\n );\n }\n\n \/\/ Determine mode of operation -------------------------------------\n \/\/\n \/\/ Several modes of operation exist for this program. They can be\n \/\/ set using the flags specified above. At present, the following\n \/\/ operations are possible:\n \/\/\n \/\/ - Calculate persistence diagrams\n \/\/ - Calculate 2-norm of the persistence diagrams\n\n if( calculateDiagrams )\n std::cout << D << \"\\n\\n\";\n else\n std::cout << i << \"\\t\" << aleph::pNorm( D ) << \"\\n\";\n }\n}\nAdded (untested) support for reading edge lists#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ These declarations should remain global because we have to refer to\n\/\/ them in utility functions that are living outside of `main()`.\nusing DataType = double;\nusing VertexType = unsigned short;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\nusing PersistenceDiagram = aleph::PersistenceDiagram;\nusing Point = typename PersistenceDiagram::Point;\n\nPersistenceDiagram merge( const PersistenceDiagram& D, const PersistenceDiagram& E )\n{\n PersistenceDiagram F;\n\n if( D.dimension() != F.dimension() )\n throw std::runtime_error( \"Persistence diagram dimensions have to agree\" );\n\n for( auto&& diagram : { D, E } )\n for( auto&& p : diagram )\n F.add( p.x(), p.y() );\n\n return F;\n}\n\ntemplate\n<\n class Engine, \/\/ random engine to use for weight generation (e.g. std::default_random_engine)\n class Distribution \/\/ distribution to use for weight generation (e.g. std::uniform_real_distribution)\n>\nSimplicialComplex makeRandomStratifiedGraph(\n const std::vector& strata,\n Engine& engine,\n Distribution& distribution\n)\n{\n auto n = strata.size();\n\n if( n <= 1 )\n throw std::runtime_error( \"Invalid number of strata\" );\n\n std::vector simplices;\n\n \/\/ Create vertices ---------------------------------------------------\n \/\/\n \/\/ The `strata` vector contains the size of each stratum, so we just\n \/\/ have to add the correct number of vertices here.\n\n VertexType index = VertexType(0);\n for( auto&& stratum : strata )\n {\n for( unsigned i = 0; i < stratum; i++ )\n simplices.push_back( Simplex( index++ ) );\n }\n\n \/\/ Create edges ------------------------------------------------------\n \/\/\n \/\/ Every stratum is connected to every other stratum, but there are no\n \/\/ connections *within* a given stratum.\n\n VertexType offset = VertexType(0);\n for( decltype(n) i = 0; i < n - 1; i++ )\n {\n \/\/ All vertices in the next stratum start with this offset to their\n \/\/ indices. It depends on the sum of all vertices in *all* previous\n \/\/ strata.\n offset += strata[i];\n\n for( unsigned j = 0; j < strata[i]; j++ )\n {\n for( unsigned k = 0; k < strata[i+1]; k++ )\n {\n simplices.push_back(\n Simplex(\n {\n VertexType( offset - strata[i] + j ),\n VertexType( offset + k )\n },\n distribution( engine )\n )\n );\n }\n }\n }\n\n return SimplicialComplex( simplices.begin(), simplices.end() );\n}\n\nSimplicialComplex applyFiltration( const SimplicialComplex& K,\n const std::string& strategy,\n bool reverse = false )\n{\n auto L = K;\n\n if( strategy == \"standard\" )\n {\n if( reverse )\n {\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n }\n else\n {\n L.sort(\n aleph::topology::filtrations::Data >()\n );\n }\n }\n else if( strategy == \"absolute\" )\n {\n if( reverse )\n {\n auto functor = [] ( const Simplex& s, const Simplex& t )\n {\n auto w1 = s.data();\n auto w2 = t.data();\n\n if( std::abs( w1 ) > std::abs( w2 ) )\n return true;\n else if( std::abs( w1 ) == std::abs( w2 ) )\n {\n \/\/ This amounts to saying that w1 is positive and w2 is\n \/\/ negative.\n if( w1 > w2 )\n return true;\n else\n {\n if( s.dimension() < t.dimension() )\n return true;\n\n \/\/ Absolute value is equal, signed value is equal, and the\n \/\/ dimension is equal. We thus have to fall back to merely\n \/\/ using the lexicographical order.\n else\n return s < t;\n }\n }\n\n return false;\n };\n\n L.sort( functor );\n }\n else\n {\n auto functor = [] ( const Simplex& s, const Simplex& t )\n {\n auto w1 = s.data();\n auto w2 = t.data();\n\n if( std::abs( w1 ) < std::abs( w2 ) )\n return true;\n else if( std::abs( w1 ) == std::abs( w2 ) )\n {\n \/\/ This amounts to saying that w1 is negative and w2 is\n \/\/ positive.\n if( w1 < w2 )\n return true;\n else\n {\n if( s.dimension() < t.dimension() )\n return true;\n\n \/\/ Absolute value is equal, signed value is equal, and the\n \/\/ dimension is equal. We thus have to fall back to merely\n \/\/ using the lexicographical order.\n else\n return s < t;\n }\n }\n\n return false;\n };\n\n L.sort( functor );\n }\n }\n\n return L;\n}\n\nSimplicialComplex assignVertexWeights( const SimplicialComplex& K,\n const std::string& strategy,\n bool reverse = false )\n{\n DataType minData = std::numeric_limits::max();\n DataType maxData = std::numeric_limits::lowest();\n\n for( auto&& s : K )\n {\n if( s.dimension() != 1 )\n continue;\n\n minData = std::min( minData, s.data() );\n maxData = std::max( maxData, s.data() );\n }\n\n \/\/ Setting up the weights --------------------------------------------\n \/\/\n \/\/ This function assumes that the simplicial complex is already in\n \/\/ filtration ordering with respect to its weights. Hence, we only\n \/\/ have to take the *first* weight that we encounter (when using a\n \/\/ global vertex weight assignment) or the *extremal* value, which\n \/\/ is either a minimum or a maximum depending on the direction.\n\n std::unordered_map weight;\n\n for( auto&& s : K )\n {\n if( s.dimension() != 1 )\n continue;\n\n auto u = s[0];\n auto v = s[1];\n DataType w = DataType(); \/\/ weight to assign; depends on filtration\n\n \/\/ Assign the global minimum or maximum. This is rather wasteful\n \/\/ because the values do not change, but at least the code makes\n \/\/ it clear that all updates are done in the same place.\n if( strategy == \"global\" )\n w = reverse ? maxData : minData;\n else if( strategy == \"local\" )\n w = s.data();\n else\n throw std::runtime_error( \"Unknown update strategy '\" + strategy + \"'\" );\n\n \/\/ This only performs the update *once*.\n weight.insert( {u,w} );\n weight.insert( {v,w} );\n }\n\n \/\/ Assign the weights ------------------------------------------------\n \/\/\n \/\/ Having set up the map of weights, we now only need to traverse it\n \/\/ in order to assign weights afterwards.\n\n auto L = K;\n\n for( auto it = L.begin(); it != L.end(); ++it )\n {\n if( it->dimension() == 0 )\n {\n auto s = *it; \/\/ simplex\n auto v = s[0]; \/\/ vertex\n\n s.setData( weight.at(v) );\n\n auto result = L.replace( it, s );\n if( !result )\n throw std::runtime_error( \"Unable to replace simplex in simplicial complex\" );\n }\n }\n\n return L;\n}\n\ntemplate std::vector loadSimplicialComplexes( int argc, char** argv )\n{\n Reader reader;\n\n std::vector simplicialComplexes;\n simplicialComplexes.reserve( static_cast( argc - optind ) );\n\n for( int i = optind; i < argc; i++ )\n {\n auto filename = std::string( argv[i] );\n\n std::cerr << \"* Processing \" << filename << \"...\";\n\n SimplicialComplex K;\n reader( filename, K );\n\n std::cerr << \"finished\\n\";\n\n simplicialComplexes.emplace_back( K );\n }\n\n return simplicialComplexes;\n}\n\nint main( int argc, char** argv )\n{\n bool bipartite = false;\n bool normalize = false;\n bool reverse = false;\n bool verbose = false;\n bool calculateDiagrams = false;\n\n \/\/ The default filtration sorts simplices by their weights. Negative\n \/\/ weights are treated as being less relevant than positive ones.\n std::string filtration = \"standard\";\n\n \/\/ Defines how the minimum value for the vertices is to be set. Valid\n \/\/ options include:\n \/\/\n \/\/ - global (uses the global extremal value)\n \/\/ - local (uses the local extremal value over all neighbours)\n std::string weights = \"global\";\n\n {\n static option commandLineOptions[] =\n {\n { \"bipartite\" , no_argument, nullptr, 'b' },\n { \"normalize\" , no_argument, nullptr, 'n' },\n { \"persistence-diagrams\", no_argument, nullptr, 'p' },\n { \"reverse\" , no_argument, nullptr, 'r' },\n { \"verbose\" , no_argument, nullptr, 'v' },\n { \"filtration\" , required_argument, nullptr, 'f' },\n { \"weights\" , required_argument, nullptr, 'w' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"bnprtvf:w:\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'b':\n bipartite = true;\n break;\n case 'f':\n filtration = optarg;\n break;\n case 'n':\n normalize = true;\n break;\n case 'p':\n calculateDiagrams = true;\n break;\n case 'r':\n reverse = true;\n break;\n case 'v':\n verbose = true;\n break;\n case 'w':\n weights = optarg;\n break;\n default:\n break;\n }\n }\n\n \/\/ Check filtration validity ---------------------------------------\n\n if( filtration != \"absolute\"\n && filtration != \"standard\" )\n {\n std::cerr << \"* Invalid filtration value '\" << filtration << \"', so falling back to standard one\\n\";\n filtration = \"standard\";\n }\n\n \/\/ Check validity of weight strategy -------------------------------\n\n if( weights != \"global\"\n && weights != \"local\" )\n {\n std::cerr << \"* Invalid weight strategy value '\" << weights << \"', so falling back to global one\\n\";\n weights = \"global\";\n }\n }\n\n \/\/ Be verbose about parameters ---------------------------------------\n\n if( bipartite )\n std::cerr << \"* Mode: reading bipartite adjacency matrices\\n\";\n else\n std::cerr << \"* Mode: reading edge lists\\n\";\n\n std::cerr << \"* Filtration: \" << filtration\n << \" (\" << ( reverse ? \"\" : \"not \" ) << \"reversed\" << \")\\n\"\n << \"* Vertex weight assignment strategy: \" << weights << \"\\n\";\n\n if( verbose )\n std::cerr << \"* Verbose output\\n\";\n\n \/\/ 1. Read simplicial complexes --------------------------------------\n\n std::vector simplicialComplexes;\n simplicialComplexes.reserve( static_cast( argc - optind - 1 ) );\n\n std::vector minData;\n std::vector maxData;\n\n minData.reserve( simplicialComplexes.size() );\n maxData.reserve( simplicialComplexes.size() );\n\n if( argc - optind >= 1 )\n {\n if( bipartite )\n {\n using Reader = aleph::topology::io::BipartiteAdjacencyMatrixReader;\n\n simplicialComplexes\n = loadSimplicialComplexes( argc, argv );\n }\n else\n {\n using Reader = aleph::topology::io::EdgeListReader;\n\n simplicialComplexes\n = loadSimplicialComplexes( argc, argv );\n }\n }\n else\n {\n std::default_random_engine engine;\n engine.seed(\n static_cast(\n std::chrono::system_clock::now().time_since_epoch().count()\n )\n );\n\n DataType minWeight = DataType(-1);\n DataType maxWeight = DataType( 1);\n\n std::uniform_real_distribution distribution(\n minWeight,\n std::nextafter( maxWeight, std::numeric_limits::max() )\n );\n\n for( unsigned i = 0; i < 1e5; i++ )\n {\n auto K\n = makeRandomStratifiedGraph( {2,3}, \/\/ FIXME: {2,3,1} for the complete network\n engine,\n distribution\n );\n\n simplicialComplexes.emplace_back( K );\n }\n }\n\n \/\/ Determine minimum and maximum values for each complex -------------\n\n for( auto&& K : simplicialComplexes )\n {\n DataType minData_ = std::numeric_limits::max();\n DataType maxData_ = std::numeric_limits::lowest();\n\n \/\/ *Always* determine minimum and maximum weights so that we may\n \/\/ report them later on. They are only used for normalization in\n \/\/ the persistence diagram calculation step.\n for( auto&& s : K )\n {\n minData_ = std::min( minData_, s.data() );\n maxData_ = std::max( maxData_, s.data() );\n }\n\n minData.push_back( minData_ );\n maxData.push_back( maxData_ );\n }\n\n \/\/ Establish filtration order ----------------------------------------\n\n for( auto&& K : simplicialComplexes )\n {\n K = applyFiltration( K, filtration, reverse );\n K = assignVertexWeights( K, weights, reverse );\n K = applyFiltration( K, filtration, reverse );\n }\n\n \/\/ 2. Calculate persistent homology ----------------------------------\n\n for( std::size_t i = 0; i < simplicialComplexes.size(); i++ )\n {\n \/\/ The persistence diagram that will be used in the subsequent\n \/\/ analysis. This does not necessarily have to stem from data,\n \/\/ but can be calculated from a suitable transformation.\n PersistenceDiagram D;\n\n auto&& K = simplicialComplexes[i];\n auto diagrams = aleph::calculatePersistenceDiagrams( K );\n D = diagrams.back(); \/\/ Use the *last* diagram of the filtration so that\n \/\/ we get features in the highest dimension.\n\n D.removeDiagonal();\n D.removeUnpaired();\n\n if( normalize )\n {\n \/\/ Ensures that all weights are in [0:1] for the corresponding\n \/\/ diagram. This enables the comparison of time-varying graphs\n \/\/ or different instances.\n std::transform( D.begin(), D.end(), D.begin(),\n [&i, &minData, &maxData] ( const Point& p )\n {\n auto x = p.x();\n auto y = p.y();\n\n if( minData[i] != maxData[i] )\n {\n x = (x - minData[i]) \/ (maxData[i] - minData[i]);\n y = (y - minData[i]) \/ (maxData[i] - minData[i]);\n }\n\n return Point( x,y );\n }\n );\n }\n\n \/\/ Determine mode of operation -------------------------------------\n \/\/\n \/\/ Several modes of operation exist for this program. They can be\n \/\/ set using the flags specified above. At present, the following\n \/\/ operations are possible:\n \/\/\n \/\/ - Calculate persistence diagrams\n \/\/ - Calculate 2-norm of the persistence diagrams\n\n if( calculateDiagrams )\n std::cout << D << \"\\n\\n\";\n else\n std::cout << i << \"\\t\" << aleph::pNorm( D ) << \"\\n\";\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/predictors\/predictor_database.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/predictors\/autocomplete_action_predictor_table.h\"\n#include \"chrome\/browser\/predictors\/resource_prefetch_predictor.h\"\n#include \"chrome\/browser\/predictors\/resource_prefetch_predictor_tables.h\"\n#include \"chrome\/browser\/prerender\/prerender_field_trial.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"sql\/connection.h\"\n#include \"sql\/statement.h\"\n\nusing content::BrowserThread;\n\nnamespace {\n\n\/\/ TODO(shishir): This should move to a more generic name.\nconst base::FilePath::CharType kPredictorDatabaseName[] =\n FILE_PATH_LITERAL(\"Network Action Predictor\");\n\n} \/\/ namespace\n\nnamespace predictors {\n\n\/\/ Refcounted as it is created, initialized and destroyed on a different thread\n\/\/ to the DB thread that is required for all methods performing database access.\nclass PredictorDatabaseInternal\n : public base::RefCountedThreadSafe {\n private:\n friend class base::RefCountedThreadSafe;\n friend class PredictorDatabase;\n\n explicit PredictorDatabaseInternal(Profile* profile);\n virtual ~PredictorDatabaseInternal();\n\n \/\/ Opens the database file from the profile path. Separated from the\n \/\/ constructor to ease construction\/destruction of this object on one thread\n \/\/ but database access on the DB thread.\n void Initialize();\n void LogDatabaseStats(); \/\/ DB Thread.\n\n \/\/ Cancels pending DB transactions. Should only be called on the UI thread.\n void SetCancelled();\n\n bool is_resource_prefetch_predictor_enabled_;\n base::FilePath db_path_;\n scoped_ptr db_;\n\n \/\/ TODO(shishir): These tables may not need to be refcounted. Maybe move them\n \/\/ to using a WeakPtr instead.\n scoped_refptr autocomplete_table_;\n scoped_refptr resource_prefetch_tables_;\n\n DISALLOW_COPY_AND_ASSIGN(PredictorDatabaseInternal);\n};\n\n\nPredictorDatabaseInternal::PredictorDatabaseInternal(Profile* profile)\n : db_path_(profile->GetPath().Append(kPredictorDatabaseName)),\n db_(new sql::Connection()),\n autocomplete_table_(new AutocompleteActionPredictorTable()),\n resource_prefetch_tables_(new ResourcePrefetchPredictorTables()) {\n \/\/ TODO (tburkard): initialize logged_in_table_ member.\n ResourcePrefetchPredictorConfig config;\n is_resource_prefetch_predictor_enabled_ =\n IsSpeculativeResourcePrefetchingEnabled(profile, &config);\n}\n\nPredictorDatabaseInternal::~PredictorDatabaseInternal() {\n \/\/ The connection pointer needs to be deleted on the DB thread since there\n \/\/ might be a task in progress on the DB thread which uses this connection.\n BrowserThread::DeleteSoon(BrowserThread::DB, FROM_HERE, db_.release());\n}\n\nvoid PredictorDatabaseInternal::Initialize() {\n CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));\n db_->set_exclusive_locking();\n bool success = db_->Open(db_path_);\n\n if (!success)\n return;\n\n autocomplete_table_->Initialize(db_.get());\n resource_prefetch_tables_->Initialize(db_.get());\n\n LogDatabaseStats();\n}\n\nvoid PredictorDatabaseInternal::SetCancelled() {\n CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n autocomplete_table_->SetCancelled();\n resource_prefetch_tables_->SetCancelled();\n}\n\nvoid PredictorDatabaseInternal::LogDatabaseStats() {\n CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));\n\n int64 db_size;\n bool success = file_util::GetFileSize(db_path_, &db_size);\n DCHECK(success) << \"Failed to get file size for \" << db_path_.value();\n UMA_HISTOGRAM_MEMORY_KB(\"PredictorDatabase.DatabaseSizeKB\",\n static_cast(db_size \/ 1024));\n\n autocomplete_table_->LogDatabaseStats();\n if (is_resource_prefetch_predictor_enabled_)\n resource_prefetch_tables_->LogDatabaseStats();\n}\n\nPredictorDatabase::PredictorDatabase(Profile* profile)\n : db_(new PredictorDatabaseInternal(profile)) {\n BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,\n base::Bind(&PredictorDatabaseInternal::Initialize, db_));\n}\n\nPredictorDatabase::~PredictorDatabase() {\n}\n\nvoid PredictorDatabase::Shutdown() {\n db_->SetCancelled();\n}\n\nscoped_refptr\n PredictorDatabase::autocomplete_table() {\n return db_->autocomplete_table_;\n}\n\nscoped_refptr\n PredictorDatabase::resource_prefetch_tables() {\n return db_->resource_prefetch_tables_;\n}\n\nsql::Connection* PredictorDatabase::GetDatabase() {\n return db_->db_.get();\n}\n\n} \/\/ namespace predictors\nRevert 194504 \"Fix build break\"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/predictors\/predictor_database.h\"\n\n#include \"base\/bind.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/predictors\/autocomplete_action_predictor_table.h\"\n#include \"chrome\/browser\/predictors\/resource_prefetch_predictor.h\"\n#include \"chrome\/browser\/predictors\/resource_prefetch_predictor_tables.h\"\n#include \"chrome\/browser\/prerender\/prerender_field_trial.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"content\/public\/browser\/browser_thread.h\"\n#include \"sql\/connection.h\"\n#include \"sql\/statement.h\"\n\nusing content::BrowserThread;\n\nnamespace {\n\n\/\/ TODO(shishir): This should move to a more generic name.\nconst base::FilePath::CharType kPredictorDatabaseName[] =\n FILE_PATH_LITERAL(\"Network Action Predictor\");\n\n} \/\/ namespace\n\nnamespace predictors {\n\n\/\/ Refcounted as it is created, initialized and destroyed on a different thread\n\/\/ to the DB thread that is required for all methods performing database access.\nclass PredictorDatabaseInternal\n : public base::RefCountedThreadSafe {\n private:\n friend class base::RefCountedThreadSafe;\n friend class PredictorDatabase;\n\n explicit PredictorDatabaseInternal(Profile* profile);\n virtual ~PredictorDatabaseInternal();\n\n \/\/ Opens the database file from the profile path. Separated from the\n \/\/ constructor to ease construction\/destruction of this object on one thread\n \/\/ but database access on the DB thread.\n void Initialize();\n void LogDatabaseStats(); \/\/ DB Thread.\n\n \/\/ Cancels pending DB transactions. Should only be called on the UI thread.\n void SetCancelled();\n\n bool is_resource_prefetch_predictor_enabled_;\n base::FilePath db_path_;\n scoped_ptr db_;\n\n \/\/ TODO(shishir): These tables may not need to be refcounted. Maybe move them\n \/\/ to using a WeakPtr instead.\n scoped_refptr autocomplete_table_;\n scoped_refptr resource_prefetch_tables_;\n\n DISALLOW_COPY_AND_ASSIGN(PredictorDatabaseInternal);\n};\n\n\nPredictorDatabaseInternal::PredictorDatabaseInternal(Profile* profile)\n : db_path_(profile->GetPath().Append(kPredictorDatabaseName)),\n db_(new sql::Connection()),\n autocomplete_table_(new AutocompleteActionPredictorTable()),\n logged_in_table_(new LoggedInPredictorTable()),\n resource_prefetch_tables_(new ResourcePrefetchPredictorTables()) {\n ResourcePrefetchPredictorConfig config;\n is_resource_prefetch_predictor_enabled_ =\n IsSpeculativeResourcePrefetchingEnabled(profile, &config);\n}\n\nPredictorDatabaseInternal::~PredictorDatabaseInternal() {\n \/\/ The connection pointer needs to be deleted on the DB thread since there\n \/\/ might be a task in progress on the DB thread which uses this connection.\n BrowserThread::DeleteSoon(BrowserThread::DB, FROM_HERE, db_.release());\n}\n\nvoid PredictorDatabaseInternal::Initialize() {\n CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));\n db_->set_exclusive_locking();\n bool success = db_->Open(db_path_);\n\n if (!success)\n return;\n\n autocomplete_table_->Initialize(db_.get());\n resource_prefetch_tables_->Initialize(db_.get());\n\n LogDatabaseStats();\n}\n\nvoid PredictorDatabaseInternal::SetCancelled() {\n CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n\n autocomplete_table_->SetCancelled();\n resource_prefetch_tables_->SetCancelled();\n}\n\nvoid PredictorDatabaseInternal::LogDatabaseStats() {\n CHECK(BrowserThread::CurrentlyOn(BrowserThread::DB));\n\n int64 db_size;\n bool success = file_util::GetFileSize(db_path_, &db_size);\n DCHECK(success) << \"Failed to get file size for \" << db_path_.value();\n UMA_HISTOGRAM_MEMORY_KB(\"PredictorDatabase.DatabaseSizeKB\",\n static_cast(db_size \/ 1024));\n\n autocomplete_table_->LogDatabaseStats();\n if (is_resource_prefetch_predictor_enabled_)\n resource_prefetch_tables_->LogDatabaseStats();\n}\n\nPredictorDatabase::PredictorDatabase(Profile* profile)\n : db_(new PredictorDatabaseInternal(profile)) {\n BrowserThread::PostTask(BrowserThread::DB, FROM_HERE,\n base::Bind(&PredictorDatabaseInternal::Initialize, db_));\n}\n\nPredictorDatabase::~PredictorDatabase() {\n}\n\nvoid PredictorDatabase::Shutdown() {\n db_->SetCancelled();\n}\n\nscoped_refptr\n PredictorDatabase::autocomplete_table() {\n return db_->autocomplete_table_;\n}\n\nscoped_refptr\n PredictorDatabase::resource_prefetch_tables() {\n return db_->resource_prefetch_tables_;\n}\n\nsql::Connection* PredictorDatabase::GetDatabase() {\n return db_->db_.get();\n}\n\n} \/\/ namespace predictors\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"PersistentLDAPConnection.h\"\n\n\/\/--- project modules used -----------------------------------------------------\n#include \"LDAPMessageEntry.h\"\n#include \"LDAPConnectionManager.h\"\n#include \"ldap-extension.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Dbg.h\"\n#include \"Threads.h\"\n#include \"StringStream.h\"\n#include \"Base64.h\"\n#include \"MD5.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n\n\/* Function to set up thread-specific data. *\/\nvoid PersistentLDAPConnection::tsd_setup()\n{\n\tStartTrace(PersistentLDAPConnection.tsd_setup);\n\tvoid *tsd = NULL;\n\tif ( GETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd, void) ) {\n\t\tTrace(\"Thread specific data for fgErrnoKey already set up. Thread [\" << Thread::MyId() << \"]\");\n\t\treturn;\n\t}\n\n\ttsd = (void *) calloc( 1, sizeof(struct ldap_error) );\n\tif ( !SETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd) ) {\n\t\tTrace(\"Setting Thread specific data for fgErrnoKey failed. Thread [\" << Thread::MyId() << \"]\");\n\t}\n}\n\nvoid PersistentLDAPConnection::tsd_destruct(void *tsd)\n{\n\tStartTrace(PersistentLDAPConnection.tsd_destruct);\n\tif ( tsd != (void *) NULL ) {\n\t\tfree(tsd);\n\t}\n}\n\n\/* Function for setting an LDAP error. *\/\nvoid PersistentLDAPConnection::set_ld_error( int err, char *matched, char *errmsg, void *dummy )\n{\n\tStartTrace(PersistentLDAPConnection.set_ld_error);\n\n\tPersistentLDAPConnection::ldap_error *le = NULL;\n\tGETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error);\n\tle->le_errno = err;\n\tif ( le->le_matched != NULL ) {\n\t\tldap_memfree( le->le_matched );\n\t}\n\tle->le_matched = matched;\n\tif ( le->le_errmsg != NULL ) {\n\t\tldap_memfree( le->le_errmsg );\n\t}\n\tle->le_errmsg = errmsg;\n}\n\n\/* Function for getting an LDAP error. *\/\nint PersistentLDAPConnection::get_ld_error( char **matched, char **errmsg, void *dummy )\n{\n\tStartTrace(PersistentLDAPConnection.get_ld_error);\n\n\tPersistentLDAPConnection::ldap_error *le = NULL;\n\tGETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error);\n\tif ( matched != NULL ) {\n\t\t*matched = le->le_matched;\n\t}\n\tif ( errmsg != NULL ) {\n\t\t*errmsg = le->le_errmsg;\n\t}\n\treturn( le->le_errno );\n}\n\n\/* Function for setting errno. *\/\nvoid PersistentLDAPConnection::set_errno( int err )\n{\n\tStartTrace(PersistentLDAPConnection.set_errno);\n\terrno = err;\n}\n\n\/* Function for getting errno. *\/\nint PersistentLDAPConnection::get_errno( void )\n{\n\tStartTrace(PersistentLDAPConnection.get_errno);\n\treturn( errno );\n}\n\nPersistentLDAPConnection::PersistentLDAPConnection(ROAnything connectionParams) : LDAPConnection(connectionParams)\n{\n\tStartTrace(PersistentLDAPConnection.PersistentLDAPConnection);\n\tfRebindTimeout = connectionParams[\"RebindTimeout\"].AsLong(0L);\n\tfTryAutoRebind = connectionParams[\"TryAutoRebind\"].AsLong(0L) > 0L;\n\tfMaxConnections = connectionParams[\"MaxConnections\"].AsLong(0L);\n\tTraceAny(connectionParams, \"ConnectionParams\");\n\tfPoolId = \"\";\n}\n\nPersistentLDAPConnection::~PersistentLDAPConnection()\n{\n\tStartTrace(PersistentLDAPConnection.~PersistentLDAPConnection);\n}\n\nint PersistentLDAPConnection::GetMaxConnections()\n{\n\tStartTrace(PersistentLDAPConnection.GetMaxConnections);\n\treturn fMaxConnections;\n}\n\nbool PersistentLDAPConnection::SetErrnoHandler(LDAPErrorHandler eh)\n{\n\tStartTrace(PersistentLDAPConnection.SetErrnoHandler);\n\n\ttsd_setup();\n\tstruct ldap_thread_fns tfns;\n\n\t\/* Set the function pointers for dealing with mutexes\n\tand error information. *\/\n\tmemset( &tfns, '\\0', sizeof(struct ldap_thread_fns) );\n\ttfns.ltf_get_errno = get_errno;\n\ttfns.ltf_set_errno = set_errno;\n\ttfns.ltf_get_lderrno = get_ld_error;\n\ttfns.ltf_set_lderrno = set_ld_error;\n\ttfns.ltf_lderrno_arg = NULL;\n\n\t\/* Set up this session to use those function pointers. *\/\n\tif ( ::ldap_set_option( fHandle, LDAP_OPT_THREAD_FN_PTRS, (void *) &tfns ) != LDAP_SUCCESS ) {\n\t\tTrace(\"ldap_set_option: LDAP_OPT_THREAD_FN_PTRS FAILED\");\n\t\teh.HandleSessionError(fHandle, \"Could not set errno handlers.\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nPersistentLDAPConnection::EConnectState PersistentLDAPConnection::DoConnectHook(ROAnything bindParams, LDAPErrorHandler &eh)\n{\n\tStartTrace(PersistentLDAPConnection.DoConnectHook);\n\tTraceAny(bindParams, \"bindParams\");\n\tfPoolId = GetLdapPoolId(bindParams);\n\tAnything returned = LDAPConnectionManager::LDAPCONNMGR()->GetLdapConnection(eh.IsRetry(), GetMaxConnections(), fPoolId, fRebindTimeout);\n\tPersistentLDAPConnection::EConnectState eConnectState =\n\t\treturned[\"MustRebind\"].AsBool(1) == false ?\n\t\tPersistentLDAPConnection::eMustNotRebind : PersistentLDAPConnection::eMustRebind;\n\tfHandle = (LDAP *) returned[\"Handle\"].AsIFAObject(0);\n\tif ( eConnectState == PersistentLDAPConnection::eMustNotRebind ) {\n\t\tTrace(\"Retrning: \" << ConnectRetToString(PersistentLDAPConnection::eOk));\n\t\teConnectState = PersistentLDAPConnection::eOk;\n\t}\n\tTrace(\"eConnectState: \" << ConnectRetToString(eConnectState) << \" Handle: \" << DumpConnectionHandle(fHandle));\n\treturn eConnectState;\n}\n\nbool PersistentLDAPConnection::ReleaseHandleInfo()\n{\n\tStartTrace(PersistentLDAPConnection.ReleaseHandleInfo);\n\tbool ret = LDAPConnectionManager::LDAPCONNMGR()->ReleaseHandleInfo(fMaxConnections, fPoolId);\n\treturn ret;\n}\n\nbool PersistentLDAPConnection::Bind(String bindName, String bindPW, int &msgId, LDAPErrorHandler eh)\n{\n\tStartTrace(LDAPConnection.PersistentLDAPConnection);\n\n\tString errMsg = \"Binding request failed. \";\n\terrMsg << \"[Server: '\" << fServer << \"', Port: '\" << fPort << \"'] \";\n\n\tif ( bindName.IsEqual(\"\") || bindName.IsEqual(\"Anonymous\") ) {\n\t\tTrace(\"Binding as Anonymous\");\n\t\terrMsg << \" (Anonymous bind.)\";\n\t\tmsgId = ::ldap_simple_bind( fHandle, NULL, NULL );\n\t} else {\n\t\terrMsg << \" (Authorized bind.)\";\n\n\t\tif ( bindPW == \"undefined\" ) {\n\t\t\tTrace(\"Bindpassword NOT OK: pwd = [\" << bindPW << \"]\");\n\t\t\teh.HandleSessionError(fHandle, errMsg);\n\t\t\treturn false;\n\t\t} else {\n\t\t\tTrace(\"Binding with <\" << bindName << \"><\" << bindPW << \">\");\n\t\t\tmsgId = ::ldap_simple_bind( fHandle, bindName, bindPW );\n\t\t}\n\t}\n\n\t\/\/ bind request successful?\n\tif ( msgId == -1 ) {\n\t\tTrace(\"Binding request FAILED!\");\n\t\teh.HandleSessionError(fHandle, errMsg);\n\t\tDisconnect();\n\t\treturn false;\n\t}\n\n\tTrace(\"Binding request SUCCEEDED, waiting for connection...\");\n\treturn true;\n}\n\nLDAPConnection::EConnectState PersistentLDAPConnection::DoConnect(ROAnything bindParams, LDAPErrorHandler eh)\n{\n\tStartTrace(PersistentLDAPConnection.DoConnect);\n\n\t\/\/ set handle to null\n\tfHandle = NULL;\n\tString errMsg;\n\tString bindName = bindParams[\"BindName\"].AsString(\"\");\n\tString bindPW = bindParams[\"BindPW\"].AsString(\"\");\n\tlong maxConnections = bindParams[\"MaxConnections\"].AsLong(0);\n\tPersistentLDAPConnection::EConnectState eConnectState = PersistentLDAPConnection::eNok;\n\tif ( (eConnectState = DoConnectHook(bindParams, eh)) == PersistentLDAPConnection::eOk ) {\n\t\tSetErrnoHandler(eh);\n\t\treturn eConnectState;\n\t}\n\t\/\/ get connection handle\n\tif ( !(fHandle = Init(eh)) ) {\n\t\treturn eInitNok;\n\t}\n\n\t\/\/ set protocol, timeout and rebind procedure\n\tif ( !SetProtocol(eh)\t\t\t||\n\t\t !SetConnectionTimeout(eh)\t||\n\t\t !SetSearchTimeout(eh)\t\t||\n\t\t !SetErrnoHandler(eh)\n\t\t \/* || !SetRebindProc(eh) *\/ ) {\n\t\treturn eSetOptionsNok;\n\t}\n\t\/\/ send bind request (asynchronous)\n\tint msgId;\n\tif ( !Bind(bindName, bindPW, msgId, eh) ) {\n\t\treturn eBindNok;\n\t}\n\n\t\/\/ wait for bind result (using msgId)\n\tAnything result;\n\tbool ret = WaitForResult(msgId, result, eh);\n\tif ( ret ) {\n\t\tLDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(maxConnections, fPoolId, fHandle);\n\t\tif ( eConnectState == PersistentLDAPConnection::eMustRebind ) {\n\t\t\treturn PersistentLDAPConnection::eRebindOk;\n\t\t}\n\t}\n\treturn ret ? PersistentLDAPConnection::eOk : PersistentLDAPConnection::eBindNok;\n}\n\nbool PersistentLDAPConnection::WaitForResult(int msgId, Anything &result, LDAPErrorHandler &eh)\n{\n\tStartTrace(PersistentLDAPConnection.WaitForResult);\n\n\ttimeval tv;\n\ttv.tv_sec = fSearchTimeout;\n\ttv.tv_usec = 0;\n\n\ttimeval *tvp = (fSearchTimeout == 0) ? NULL : &tv;\n\n\tbool finished = false;\n\tbool success = false;\n\n\tString errMsg;\n\tint resultCode;\n\n\tLDAPMessage *ldapResult;\n\tLDAPMessageEntry lmAutoDestruct(&ldapResult);\t\/\/ automatic destructor for LDAPMessage\n\tlmAutoDestruct.Use();\n\n\twhile (!finished) {\n\t\t\/\/ wait for result\n\t\tresultCode = ldap_result(fHandle, msgId, 1, tvp, &ldapResult);\n\n\t\t\/\/ check result\n\t\tif (resultCode == -1 && fSearchTimeout == 0) {\n\t\t\t\/\/ error, abandon!\n\t\t\tTrace(\"WaitForResult [Timeout: 0] received an error\");\n\t\t\tint opRet;\n\t\t\tldap_parse_result( fHandle, ldapResult, &opRet, NULL, NULL, NULL, NULL, 0 );\n\t\t\terrMsg << \"Synchronous Wait4Result: ErrorCode: [\" << (long)opRet << \"] ErrorMsg: \" << ldap_err2string( opRet );\n\t\t\tHandleWait4ResultError(msgId, errMsg, eh);\n\t\t\tfinished = true;\n\t\t} else if (resultCode == 0 || (resultCode == -1 && fSearchTimeout != 0)) {\n\t\t\t\/\/ resultCode 0 means timeout, abandon\n\t\t\tTrace(\"WaitForResult [Timeout != 0] encountered a timeout ...\");\n\t\t\terrMsg << \"Asynchronous Wait4Result: The request <\" << (long) msgId << \"> timed out.\";\n\t\t\tHandleWait4ResultError(msgId, errMsg, eh);\n\t\t\tif ( fTryAutoRebind ) {\n\t\t\t\teh.SetShouldRetry();\n\t\t\t}\n\t\t\tfinished = true;\n\t\t} else {\n\t\t\t\/\/ received a result\n\t\t\tint errCode = ldap_result2error(fHandle, ldapResult, 0);\n\t\t\tif (errCode == LDAP_SUCCESS || errCode == LDAP_SIZELIMIT_EXCEEDED) {\n\t\t\t\tTrace(\"WaitForResult recieved a result and considers it to be ok ...\");\n\t\t\t\tsuccess = true;\n\n\t\t\t\t\/\/ transform LDAPResult into an Anything with Meta Information\n\t\t\t\tTransformResult(ldapResult, result, eh.GetQueryParams());\n\n\t\t\t\t\/\/ add extra flag to inform client, if sizelimit was exceeded\n\t\t\t\tif (errCode == LDAP_SIZELIMIT_EXCEEDED) {\n\t\t\t\t\tresult[\"SizeLimitExceeded\"] = 1;\n\t\t\t\t}\n\t\t\t} else if (errCode == LDAP_COMPARE_FALSE || errCode == LDAP_COMPARE_TRUE) {\n\t\t\t\tTrace(\"WaitForResult recieved a result and considers it to be ok (compare) ...\");\n\t\t\t\tsuccess = true;\n\n\t\t\t\t\/\/ this is a bit special\n\t\t\t\tint rc;\n\t\t\t\tldap_get_option(fHandle, LDAP_OPT_ERROR_NUMBER, &rc);\n\t\t\t\tresult[\"Type\"] = \"LDAP_RES_COMPARE\";\n\t\t\t\tresult[\"Equal\"] = (errCode == LDAP_COMPARE_TRUE);\n\t\t\t\tresult[\"LdapCode\"] = rc;\n\t\t\t\tresult[\"LdapMsg\"] = ldap_err2string(rc);\n\t\t\t} else {\n\t\t\t\tTrace(\"WaitForResult recieved a result and considers it to be WRONG ...\");\n\t\t\t\terrMsg = \"LDAP request failed.\";\n\t\t\t\teh.HandleSessionError(fHandle, errMsg);\n\t\t\t}\n\t\t\tfinished = true;\n\t\t}\n\t}\n\treturn success;\n}\n\nvoid PersistentLDAPConnection::HandleWait4ResultError(int msgId, String &errMsg, LDAPErrorHandler eh)\n{\n\tStartTrace(PersistentLDAPConnection.HandleWait4ResultError);\n\tif ( msgId != -1 ) {\n\t\tint errCode = ldap_abandon(fHandle, msgId);\n\t\terrMsg << \" Request abandoned: \" << (errCode == LDAP_SUCCESS ? \" successfully.\" : \" FAILED!\");\n\t} else {\n\t\terrMsg << \" Request abandoned: binding handle was invalid, ldap_abandon not called\";\n\t}\n\teh.HandleSessionError(fHandle, errMsg);\n\t\/\/ Invalidate our handle because LDAP server might be down, will rebind next time!\n\tLDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(GetMaxConnections(), fPoolId, (LDAP *) NULL);\n}\n\nString PersistentLDAPConnection::Base64ArmouredMD5Hash(const String &text)\n{\n\tStartTrace(PersistentLDAPConnection.Base64ArmouredMD5Hash);\n\tString hash, result;\n\tMD5Signer::DoHash(text, hash);\n\tBase64Regular b64(\"b64reg\");\n\tb64.DoEncode(result, hash);\n\treturn result;\n}\n\nString PersistentLDAPConnection::GetLdapPoolId(ROAnything bindParams)\n{\n\tStartTrace(PersistentLDAPConnection.GetLdapPoolId);\n\tString bindName = bindParams[\"BindName\"].AsString(\"\");\n\tString bindPW \t= Base64ArmouredMD5Hash(bindParams[\"BindPW\"].AsString(\"\"));\n\n\treturn\tString(\"Host[\") << fServer << \"] Port[\" << fPort << \"] DN[\" <<\n\t\t\tbindName << \"] BindPW[\" << bindPW << \"] ConnTimeout[\" << fConnectionTimeout << \"]\";\n}\n\nString PersistentLDAPConnection::GetLdapPoolId(const String &server, long port, const String &bindName,\n\t\tconst String &bindPW, long connectionTimeout)\n{\n\tStartTrace(PersistentLDAPConnection.GetLdapPoolId);\n\tString armouredPW = Base64ArmouredMD5Hash(bindPW);\n\n\treturn\tString(\"Host[\") << server << \"] Port[\" << port << \"] DN[\" <<\n\t\t\tbindName << \"] BindPW[\" << armouredPW << \"] ConnTimeout[\" << connectionTimeout << \"]\";\n}\nadded include for memeset\/*\n * Copyright (c) 2005, Peter Sommerlad and IFS Institute for Software at HSR Rapperswil, Switzerland\n * All rights reserved.\n *\n * This library\/application is free software; you can redistribute and\/or modify it under the terms of\n * the license that is included with this library\/application in the file license.txt.\n *\/\n\n\/\/--- interface include --------------------------------------------------------\n#include \"PersistentLDAPConnection.h\"\n\n\/\/--- project modules used -----------------------------------------------------\n#include \"LDAPMessageEntry.h\"\n#include \"LDAPConnectionManager.h\"\n#include \"ldap-extension.h\"\n\n\/\/--- standard modules used ----------------------------------------------------\n#include \"Dbg.h\"\n#include \"Threads.h\"\n#include \"StringStream.h\"\n#include \"Base64.h\"\n#include \"MD5.h\"\n\n\/\/--- c-modules used -----------------------------------------------------------\n#include \n\n\/* Function to set up thread-specific data. *\/\nvoid PersistentLDAPConnection::tsd_setup()\n{\n\tStartTrace(PersistentLDAPConnection.tsd_setup);\n\tvoid *tsd = NULL;\n\tif ( GETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd, void) ) {\n\t\tTrace(\"Thread specific data for fgErrnoKey already set up. Thread [\" << Thread::MyId() << \"]\");\n\t\treturn;\n\t}\n\n\ttsd = (void *) calloc( 1, sizeof(struct ldap_error) );\n\tif ( !SETTLSDATA(LDAPConnectionManager::fgErrnoKey, tsd) ) {\n\t\tTrace(\"Setting Thread specific data for fgErrnoKey failed. Thread [\" << Thread::MyId() << \"]\");\n\t}\n}\n\nvoid PersistentLDAPConnection::tsd_destruct(void *tsd)\n{\n\tStartTrace(PersistentLDAPConnection.tsd_destruct);\n\tif ( tsd != (void *) NULL ) {\n\t\tfree(tsd);\n\t}\n}\n\n\/* Function for setting an LDAP error. *\/\nvoid PersistentLDAPConnection::set_ld_error( int err, char *matched, char *errmsg, void *dummy )\n{\n\tStartTrace(PersistentLDAPConnection.set_ld_error);\n\n\tPersistentLDAPConnection::ldap_error *le = NULL;\n\tGETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error);\n\tle->le_errno = err;\n\tif ( le->le_matched != NULL ) {\n\t\tldap_memfree( le->le_matched );\n\t}\n\tle->le_matched = matched;\n\tif ( le->le_errmsg != NULL ) {\n\t\tldap_memfree( le->le_errmsg );\n\t}\n\tle->le_errmsg = errmsg;\n}\n\n\/* Function for getting an LDAP error. *\/\nint PersistentLDAPConnection::get_ld_error( char **matched, char **errmsg, void *dummy )\n{\n\tStartTrace(PersistentLDAPConnection.get_ld_error);\n\n\tPersistentLDAPConnection::ldap_error *le = NULL;\n\tGETTLSDATA(LDAPConnectionManager::fgErrnoKey, le, ldap_error);\n\tif ( matched != NULL ) {\n\t\t*matched = le->le_matched;\n\t}\n\tif ( errmsg != NULL ) {\n\t\t*errmsg = le->le_errmsg;\n\t}\n\treturn( le->le_errno );\n}\n\n\/* Function for setting errno. *\/\nvoid PersistentLDAPConnection::set_errno( int err )\n{\n\tStartTrace(PersistentLDAPConnection.set_errno);\n\terrno = err;\n}\n\n\/* Function for getting errno. *\/\nint PersistentLDAPConnection::get_errno( void )\n{\n\tStartTrace(PersistentLDAPConnection.get_errno);\n\treturn( errno );\n}\n\nPersistentLDAPConnection::PersistentLDAPConnection(ROAnything connectionParams) : LDAPConnection(connectionParams)\n{\n\tStartTrace(PersistentLDAPConnection.PersistentLDAPConnection);\n\tfRebindTimeout = connectionParams[\"RebindTimeout\"].AsLong(0L);\n\tfTryAutoRebind = connectionParams[\"TryAutoRebind\"].AsLong(0L) > 0L;\n\tfMaxConnections = connectionParams[\"MaxConnections\"].AsLong(0L);\n\tTraceAny(connectionParams, \"ConnectionParams\");\n\tfPoolId = \"\";\n}\n\nPersistentLDAPConnection::~PersistentLDAPConnection()\n{\n\tStartTrace(PersistentLDAPConnection.~PersistentLDAPConnection);\n}\n\nint PersistentLDAPConnection::GetMaxConnections()\n{\n\tStartTrace(PersistentLDAPConnection.GetMaxConnections);\n\treturn fMaxConnections;\n}\n\nbool PersistentLDAPConnection::SetErrnoHandler(LDAPErrorHandler eh)\n{\n\tStartTrace(PersistentLDAPConnection.SetErrnoHandler);\n\n\ttsd_setup();\n\tstruct ldap_thread_fns tfns;\n\n\t\/* Set the function pointers for dealing with mutexes\n\tand error information. *\/\n\tmemset( &tfns, '\\0', sizeof(struct ldap_thread_fns) );\n\ttfns.ltf_get_errno = get_errno;\n\ttfns.ltf_set_errno = set_errno;\n\ttfns.ltf_get_lderrno = get_ld_error;\n\ttfns.ltf_set_lderrno = set_ld_error;\n\ttfns.ltf_lderrno_arg = NULL;\n\n\t\/* Set up this session to use those function pointers. *\/\n\tif ( ::ldap_set_option( fHandle, LDAP_OPT_THREAD_FN_PTRS, (void *) &tfns ) != LDAP_SUCCESS ) {\n\t\tTrace(\"ldap_set_option: LDAP_OPT_THREAD_FN_PTRS FAILED\");\n\t\teh.HandleSessionError(fHandle, \"Could not set errno handlers.\");\n\t\treturn false;\n\t}\n\treturn true;\n}\n\nPersistentLDAPConnection::EConnectState PersistentLDAPConnection::DoConnectHook(ROAnything bindParams, LDAPErrorHandler &eh)\n{\n\tStartTrace(PersistentLDAPConnection.DoConnectHook);\n\tTraceAny(bindParams, \"bindParams\");\n\tfPoolId = GetLdapPoolId(bindParams);\n\tAnything returned = LDAPConnectionManager::LDAPCONNMGR()->GetLdapConnection(eh.IsRetry(), GetMaxConnections(), fPoolId, fRebindTimeout);\n\tPersistentLDAPConnection::EConnectState eConnectState =\n\t\treturned[\"MustRebind\"].AsBool(1) == false ?\n\t\tPersistentLDAPConnection::eMustNotRebind : PersistentLDAPConnection::eMustRebind;\n\tfHandle = (LDAP *) returned[\"Handle\"].AsIFAObject(0);\n\tif ( eConnectState == PersistentLDAPConnection::eMustNotRebind ) {\n\t\tTrace(\"Retrning: \" << ConnectRetToString(PersistentLDAPConnection::eOk));\n\t\teConnectState = PersistentLDAPConnection::eOk;\n\t}\n\tTrace(\"eConnectState: \" << ConnectRetToString(eConnectState) << \" Handle: \" << DumpConnectionHandle(fHandle));\n\treturn eConnectState;\n}\n\nbool PersistentLDAPConnection::ReleaseHandleInfo()\n{\n\tStartTrace(PersistentLDAPConnection.ReleaseHandleInfo);\n\tbool ret = LDAPConnectionManager::LDAPCONNMGR()->ReleaseHandleInfo(fMaxConnections, fPoolId);\n\treturn ret;\n}\n\nbool PersistentLDAPConnection::Bind(String bindName, String bindPW, int &msgId, LDAPErrorHandler eh)\n{\n\tStartTrace(LDAPConnection.PersistentLDAPConnection);\n\n\tString errMsg = \"Binding request failed. \";\n\terrMsg << \"[Server: '\" << fServer << \"', Port: '\" << fPort << \"'] \";\n\n\tif ( bindName.IsEqual(\"\") || bindName.IsEqual(\"Anonymous\") ) {\n\t\tTrace(\"Binding as Anonymous\");\n\t\terrMsg << \" (Anonymous bind.)\";\n\t\tmsgId = ::ldap_simple_bind( fHandle, NULL, NULL );\n\t} else {\n\t\terrMsg << \" (Authorized bind.)\";\n\n\t\tif ( bindPW == \"undefined\" ) {\n\t\t\tTrace(\"Bindpassword NOT OK: pwd = [\" << bindPW << \"]\");\n\t\t\teh.HandleSessionError(fHandle, errMsg);\n\t\t\treturn false;\n\t\t} else {\n\t\t\tTrace(\"Binding with <\" << bindName << \"><\" << bindPW << \">\");\n\t\t\tmsgId = ::ldap_simple_bind( fHandle, bindName, bindPW );\n\t\t}\n\t}\n\n\t\/\/ bind request successful?\n\tif ( msgId == -1 ) {\n\t\tTrace(\"Binding request FAILED!\");\n\t\teh.HandleSessionError(fHandle, errMsg);\n\t\tDisconnect();\n\t\treturn false;\n\t}\n\n\tTrace(\"Binding request SUCCEEDED, waiting for connection...\");\n\treturn true;\n}\n\nLDAPConnection::EConnectState PersistentLDAPConnection::DoConnect(ROAnything bindParams, LDAPErrorHandler eh)\n{\n\tStartTrace(PersistentLDAPConnection.DoConnect);\n\n\t\/\/ set handle to null\n\tfHandle = NULL;\n\tString errMsg;\n\tString bindName = bindParams[\"BindName\"].AsString(\"\");\n\tString bindPW = bindParams[\"BindPW\"].AsString(\"\");\n\tlong maxConnections = bindParams[\"MaxConnections\"].AsLong(0);\n\tPersistentLDAPConnection::EConnectState eConnectState = PersistentLDAPConnection::eNok;\n\tif ( (eConnectState = DoConnectHook(bindParams, eh)) == PersistentLDAPConnection::eOk ) {\n\t\tSetErrnoHandler(eh);\n\t\treturn eConnectState;\n\t}\n\t\/\/ get connection handle\n\tif ( !(fHandle = Init(eh)) ) {\n\t\treturn eInitNok;\n\t}\n\n\t\/\/ set protocol, timeout and rebind procedure\n\tif ( !SetProtocol(eh)\t\t\t||\n\t\t !SetConnectionTimeout(eh)\t||\n\t\t !SetSearchTimeout(eh)\t\t||\n\t\t !SetErrnoHandler(eh)\n\t\t \/* || !SetRebindProc(eh) *\/ ) {\n\t\treturn eSetOptionsNok;\n\t}\n\t\/\/ send bind request (asynchronous)\n\tint msgId;\n\tif ( !Bind(bindName, bindPW, msgId, eh) ) {\n\t\treturn eBindNok;\n\t}\n\n\t\/\/ wait for bind result (using msgId)\n\tAnything result;\n\tbool ret = WaitForResult(msgId, result, eh);\n\tif ( ret ) {\n\t\tLDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(maxConnections, fPoolId, fHandle);\n\t\tif ( eConnectState == PersistentLDAPConnection::eMustRebind ) {\n\t\t\treturn PersistentLDAPConnection::eRebindOk;\n\t\t}\n\t}\n\treturn ret ? PersistentLDAPConnection::eOk : PersistentLDAPConnection::eBindNok;\n}\n\nbool PersistentLDAPConnection::WaitForResult(int msgId, Anything &result, LDAPErrorHandler &eh)\n{\n\tStartTrace(PersistentLDAPConnection.WaitForResult);\n\n\ttimeval tv;\n\ttv.tv_sec = fSearchTimeout;\n\ttv.tv_usec = 0;\n\n\ttimeval *tvp = (fSearchTimeout == 0) ? NULL : &tv;\n\n\tbool finished = false;\n\tbool success = false;\n\n\tString errMsg;\n\tint resultCode;\n\n\tLDAPMessage *ldapResult;\n\tLDAPMessageEntry lmAutoDestruct(&ldapResult);\t\/\/ automatic destructor for LDAPMessage\n\tlmAutoDestruct.Use();\n\n\twhile (!finished) {\n\t\t\/\/ wait for result\n\t\tresultCode = ldap_result(fHandle, msgId, 1, tvp, &ldapResult);\n\n\t\t\/\/ check result\n\t\tif (resultCode == -1 && fSearchTimeout == 0) {\n\t\t\t\/\/ error, abandon!\n\t\t\tTrace(\"WaitForResult [Timeout: 0] received an error\");\n\t\t\tint opRet;\n\t\t\tldap_parse_result( fHandle, ldapResult, &opRet, NULL, NULL, NULL, NULL, 0 );\n\t\t\terrMsg << \"Synchronous Wait4Result: ErrorCode: [\" << (long)opRet << \"] ErrorMsg: \" << ldap_err2string( opRet );\n\t\t\tHandleWait4ResultError(msgId, errMsg, eh);\n\t\t\tfinished = true;\n\t\t} else if (resultCode == 0 || (resultCode == -1 && fSearchTimeout != 0)) {\n\t\t\t\/\/ resultCode 0 means timeout, abandon\n\t\t\tTrace(\"WaitForResult [Timeout != 0] encountered a timeout ...\");\n\t\t\terrMsg << \"Asynchronous Wait4Result: The request <\" << (long) msgId << \"> timed out.\";\n\t\t\tHandleWait4ResultError(msgId, errMsg, eh);\n\t\t\tif ( fTryAutoRebind ) {\n\t\t\t\teh.SetShouldRetry();\n\t\t\t}\n\t\t\tfinished = true;\n\t\t} else {\n\t\t\t\/\/ received a result\n\t\t\tint errCode = ldap_result2error(fHandle, ldapResult, 0);\n\t\t\tif (errCode == LDAP_SUCCESS || errCode == LDAP_SIZELIMIT_EXCEEDED) {\n\t\t\t\tTrace(\"WaitForResult recieved a result and considers it to be ok ...\");\n\t\t\t\tsuccess = true;\n\n\t\t\t\t\/\/ transform LDAPResult into an Anything with Meta Information\n\t\t\t\tTransformResult(ldapResult, result, eh.GetQueryParams());\n\n\t\t\t\t\/\/ add extra flag to inform client, if sizelimit was exceeded\n\t\t\t\tif (errCode == LDAP_SIZELIMIT_EXCEEDED) {\n\t\t\t\t\tresult[\"SizeLimitExceeded\"] = 1;\n\t\t\t\t}\n\t\t\t} else if (errCode == LDAP_COMPARE_FALSE || errCode == LDAP_COMPARE_TRUE) {\n\t\t\t\tTrace(\"WaitForResult recieved a result and considers it to be ok (compare) ...\");\n\t\t\t\tsuccess = true;\n\n\t\t\t\t\/\/ this is a bit special\n\t\t\t\tint rc;\n\t\t\t\tldap_get_option(fHandle, LDAP_OPT_ERROR_NUMBER, &rc);\n\t\t\t\tresult[\"Type\"] = \"LDAP_RES_COMPARE\";\n\t\t\t\tresult[\"Equal\"] = (errCode == LDAP_COMPARE_TRUE);\n\t\t\t\tresult[\"LdapCode\"] = rc;\n\t\t\t\tresult[\"LdapMsg\"] = ldap_err2string(rc);\n\t\t\t} else {\n\t\t\t\tTrace(\"WaitForResult recieved a result and considers it to be WRONG ...\");\n\t\t\t\terrMsg = \"LDAP request failed.\";\n\t\t\t\teh.HandleSessionError(fHandle, errMsg);\n\t\t\t}\n\t\t\tfinished = true;\n\t\t}\n\t}\n\treturn success;\n}\n\nvoid PersistentLDAPConnection::HandleWait4ResultError(int msgId, String &errMsg, LDAPErrorHandler eh)\n{\n\tStartTrace(PersistentLDAPConnection.HandleWait4ResultError);\n\tif ( msgId != -1 ) {\n\t\tint errCode = ldap_abandon(fHandle, msgId);\n\t\terrMsg << \" Request abandoned: \" << (errCode == LDAP_SUCCESS ? \" successfully.\" : \" FAILED!\");\n\t} else {\n\t\terrMsg << \" Request abandoned: binding handle was invalid, ldap_abandon not called\";\n\t}\n\teh.HandleSessionError(fHandle, errMsg);\n\t\/\/ Invalidate our handle because LDAP server might be down, will rebind next time!\n\tLDAPConnectionManager::LDAPCONNMGR()->SetLdapConnection(GetMaxConnections(), fPoolId, (LDAP *) NULL);\n}\n\nString PersistentLDAPConnection::Base64ArmouredMD5Hash(const String &text)\n{\n\tStartTrace(PersistentLDAPConnection.Base64ArmouredMD5Hash);\n\tString hash, result;\n\tMD5Signer::DoHash(text, hash);\n\tBase64Regular b64(\"b64reg\");\n\tb64.DoEncode(result, hash);\n\treturn result;\n}\n\nString PersistentLDAPConnection::GetLdapPoolId(ROAnything bindParams)\n{\n\tStartTrace(PersistentLDAPConnection.GetLdapPoolId);\n\tString bindName = bindParams[\"BindName\"].AsString(\"\");\n\tString bindPW \t= Base64ArmouredMD5Hash(bindParams[\"BindPW\"].AsString(\"\"));\n\n\treturn\tString(\"Host[\") << fServer << \"] Port[\" << fPort << \"] DN[\" <<\n\t\t\tbindName << \"] BindPW[\" << bindPW << \"] ConnTimeout[\" << fConnectionTimeout << \"]\";\n}\n\nString PersistentLDAPConnection::GetLdapPoolId(const String &server, long port, const String &bindName,\n\t\tconst String &bindPW, long connectionTimeout)\n{\n\tStartTrace(PersistentLDAPConnection.GetLdapPoolId);\n\tString armouredPW = Base64ArmouredMD5Hash(bindPW);\n\n\treturn\tString(\"Host[\") << server << \"] Port[\" << port << \"] DN[\" <<\n\t\t\tbindName << \"] BindPW[\" << armouredPW << \"] ConnTimeout[\" << connectionTimeout << \"]\";\n}\n<|endoftext|>"} {"text":"\/**\n * LLVM transformation pass to resolve indirect calls\n *\n * The transformation performs \"devirtualization\" which consists of\n * looking for indirect function calls and transforming them into a\n * switch statement that selects one of several direct function calls\n * to execute. Devirtualization happens if a pointer analysis can\n * resolve the indirect calls and compute all possible callees.\n **\/\n\n#include \"transforms\/DevirtFunctions.hh\"\n#include \"llvm\/Pass.h\"\n\/\/#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/IR\/MDBuilder.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \"seadsa\/CompleteCallGraph.hh\"\n#include \"seadsa\/InitializePasses.hh\"\n\nstatic llvm::cl::opt MaxNumTargets(\n \"Pmax-num-targets\",\n llvm::cl::desc(\n \"Do not resolve if number of targets is greater than this number.\"),\n llvm::cl::init(9999));\n\n\/*\n* Resolve first C++ virtual calls by using a Class Hierarchy Analysis (CHA)\n* before using seadsa.\n**\/\nstatic llvm::cl::opt\n ResolveCallsByCHA(\"Pdevirt-with-cha\",\n llvm::cl::desc(\"Resolve virtual calls by using CHA \"\n \"(useful for C++ programs)\"),\n llvm::cl::init(false));\n\nstatic llvm::cl::opt ResolveIncompleteCalls(\n \"Presolve-incomplete-calls\",\n llvm::cl::desc(\"Resolve indirect calls that might still require \"\n \"further reasoning about other modules\"\n \"(enable this option may be unsound)\"),\n llvm::cl::init(false), llvm::cl::Hidden);\n\nnamespace previrt {\nnamespace transforms {\n\nusing namespace llvm;\n\n\/** \n ** Resolve indirect calls by one direct call for possible callee\n ** function \n **\/\nclass DevirtualizeFunctionsPass : public ModulePass {\npublic:\n static char ID;\n\n DevirtualizeFunctionsPass() : ModulePass(ID) {\n \/\/ Initialize sea-dsa pass\n llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n llvm::initializeCompleteCallGraphPass(Registry);\n }\n\n virtual bool runOnModule(Module &M) override {\n \/\/ -- Get the call graph\n \/\/ CallGraph* CG = &(getAnalysis ().getCallGraph ());\n\n bool res = false;\n\n \/\/ -- Access to analysis pass which finds targets of indirect function calls\n DevirtualizeFunctions DF(\/*CG*\/ nullptr);\n\n if (ResolveCallsByCHA) {\n CallSiteResolverByCHA CSResolver(M);\n res |= DF.resolveCallSites(M, &CSResolver);\n }\n\n CallSiteResolverBySeaDsa CSResolver(\n M, getAnalysis(), ResolveIncompleteCalls,\n MaxNumTargets);\n res |= DF.resolveCallSites(M, &CSResolver);\n\n return res;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const override {\n \/\/ AU.addRequired();\n AU.addRequired();\n \/\/ FIXME: DevirtualizeFunctions does not fully update the call\n \/\/ graph so we don't claim it's preserved.\n \/\/ AU.setPreservesAll();\n \/\/ AU.addPreserved();\n }\n\n virtual StringRef getPassName() const override {\n return \"Devirtualize indirect calls\";\n }\n};\n\n\/\/ Currently unused but it might be useful in the future.\n\/** Annotate indirect calls with all possible callees.\n *\n * For a given call site, the metadata, if present, indicates the\n * set of functions the call site could possibly target at\n * run-time.\n **\/\nclass AnnotateIndirectCalls : public ModulePass {\npublic:\n static char ID;\n\n AnnotateIndirectCalls() : ModulePass(ID) {\n \/\/ Initialize sea-dsa pass\n llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n llvm::initializeCompleteCallGraphPass(Registry);\n }\n\n virtual bool runOnModule(Module &M) override {\n bool change = false;\n\n CallSiteResolverBySeaDsa CallSiteResolver(\n M, getAnalysis(), ResolveIncompleteCalls,\n MaxNumTargets);\n MDBuilder MDB(M.getContext());\n\n for (auto &F : M) {\n for (auto &B : F) {\n for (auto &I : B) {\n if (isa(I) || isa(I)) {\n CallSite CS(&I);\n if (CS.isIndirectCall()) {\n const SmallVector *Targets =\n CallSiteResolver.getTargets(CS);\n if (Targets) {\n std::vector Callees;\n \/\/ remove constness\n for (const Function *CalleeF : *Targets) {\n Callees.push_back(const_cast(CalleeF));\n }\n MDNode *MDCallees = MDB.createCallees(Callees);\n I.setMetadata(LLVMContext::MD_callees, MDCallees);\n change = true;\n }\n }\n }\n }\n }\n }\n return change;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired();\n AU.setPreservesAll();\n }\n\n virtual StringRef getPassName() const override {\n return \"Annotate indirect calls with all possible callees\";\n }\n};\n\nchar DevirtualizeFunctionsPass::ID = 0;\nchar AnnotateIndirectCalls::ID = 0;\n\n} \/\/ end namespace\n} \/\/ end namespace\n\nstatic llvm::RegisterPass\n X(\"Pdevirt\",\n \"Devirtualize indirect function calls by adding bounce functions\");\n\nstatic llvm::RegisterPass\n Y(\"Pannotate-indirect-calls\",\n \"Annotate indirect calls with metadata listing all possible callees\");\ndoc(DevirtFunctionsPass): fix description\/**\n * LLVM transformation pass to resolve indirect calls\n *\n * The transformation performs \"devirtualization\" which consists of\n * looking for indirect function calls and transforming them into a\n * switch statement that selects one of several direct function calls\n * to execute. Devirtualization happens if a pointer analysis can\n * resolve the indirect calls and compute all possible callees.\n **\/\n\n#include \"transforms\/DevirtFunctions.hh\"\n#include \"llvm\/Pass.h\"\n\/\/#include \"llvm\/Analysis\/CallGraph.h\"\n#include \"llvm\/IR\/MDBuilder.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n\n#include \"seadsa\/CompleteCallGraph.hh\"\n#include \"seadsa\/InitializePasses.hh\"\n\nstatic llvm::cl::opt MaxNumTargets(\n \"Pmax-num-targets\",\n llvm::cl::desc(\n \"Do not resolve if number of targets is greater than this number.\"),\n llvm::cl::init(9999));\n\n\/*\n* Resolve first C++ virtual calls by using a Class Hierarchy Analysis (CHA)\n* before using seadsa.\n**\/\nstatic llvm::cl::opt\n ResolveCallsByCHA(\"Pdevirt-with-cha\",\n llvm::cl::desc(\"Resolve virtual calls by using CHA \"\n \"(useful for C++ programs)\"),\n llvm::cl::init(false));\n\nstatic llvm::cl::opt ResolveIncompleteCalls(\n \"Presolve-incomplete-calls\",\n llvm::cl::desc(\"Resolve indirect calls that might still require \"\n \"further reasoning about other modules\"\n \"(enable this option may be unsound)\"),\n llvm::cl::init(false), llvm::cl::Hidden);\n\nnamespace previrt {\nnamespace transforms {\n\nusing namespace llvm;\n\n\/** \n ** Resolve indirect calls by one direct call for possible callee\n ** function \n **\/\nclass DevirtualizeFunctionsPass : public ModulePass {\npublic:\n static char ID;\n\n DevirtualizeFunctionsPass() : ModulePass(ID) {\n \/\/ Initialize sea-dsa pass\n llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n llvm::initializeCompleteCallGraphPass(Registry);\n }\n\n virtual bool runOnModule(Module &M) override {\n \/\/ -- Get the call graph\n \/\/ CallGraph* CG = &(getAnalysis ().getCallGraph ());\n\n bool res = false;\n\n \/\/ -- Access to analysis pass which finds targets of indirect function calls\n DevirtualizeFunctions DF(\/*CG*\/ nullptr);\n\n if (ResolveCallsByCHA) {\n CallSiteResolverByCHA CSResolver(M);\n res |= DF.resolveCallSites(M, &CSResolver);\n }\n\n CallSiteResolverBySeaDsa CSResolver(\n M, getAnalysis(), ResolveIncompleteCalls,\n MaxNumTargets);\n res |= DF.resolveCallSites(M, &CSResolver);\n\n return res;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const override {\n \/\/ AU.addRequired();\n AU.addRequired();\n \/\/ FIXME: DevirtualizeFunctions does not fully update the call\n \/\/ graph so we don't claim it's preserved.\n \/\/ AU.setPreservesAll();\n \/\/ AU.addPreserved();\n }\n\n virtual StringRef getPassName() const override {\n return \"Devirtualize indirect calls\";\n }\n};\n\n\/\/ Currently unused but it might be useful in the future.\n\/** Annotate indirect calls with all possible callees.\n *\n * For a given call site, the metadata, if present, indicates the\n * set of functions the call site could possibly target at\n * run-time.\n **\/\nclass AnnotateIndirectCalls : public ModulePass {\npublic:\n static char ID;\n\n AnnotateIndirectCalls() : ModulePass(ID) {\n \/\/ Initialize sea-dsa pass\n llvm::PassRegistry &Registry = *llvm::PassRegistry::getPassRegistry();\n llvm::initializeCompleteCallGraphPass(Registry);\n }\n\n virtual bool runOnModule(Module &M) override {\n bool change = false;\n\n CallSiteResolverBySeaDsa CallSiteResolver(\n M, getAnalysis(), ResolveIncompleteCalls,\n MaxNumTargets);\n MDBuilder MDB(M.getContext());\n\n for (auto &F : M) {\n for (auto &B : F) {\n for (auto &I : B) {\n if (isa(I) || isa(I)) {\n CallSite CS(&I);\n if (CS.isIndirectCall()) {\n const SmallVector *Targets =\n CallSiteResolver.getTargets(CS);\n if (Targets) {\n std::vector Callees;\n \/\/ remove constness\n for (const Function *CalleeF : *Targets) {\n Callees.push_back(const_cast(CalleeF));\n }\n MDNode *MDCallees = MDB.createCallees(Callees);\n I.setMetadata(LLVMContext::MD_callees, MDCallees);\n change = true;\n }\n }\n }\n }\n }\n }\n return change;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const override {\n AU.addRequired();\n AU.setPreservesAll();\n }\n\n virtual StringRef getPassName() const override {\n return \"Annotate indirect calls with all possible callees\";\n }\n};\n\nchar DevirtualizeFunctionsPass::ID = 0;\nchar AnnotateIndirectCalls::ID = 0;\n\n} \/\/ end namespace\n} \/\/ end namespace\n\nstatic llvm::RegisterPass\n X(\"Pdevirt\",\n \"Devirtualize indirect function calls by adding multiple direct calls\");\n\nstatic llvm::RegisterPass\n Y(\"Pannotate-indirect-calls\",\n \"Annotate indirect calls with metadata listing all possible callees\");\n<|endoftext|>"} {"text":"\/****************************************************************************\n *\n * Copyright (c) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file qshell.cpp\n * Listener for shell commands from posix\n *\n * @author Nicolas de Palezieux \n *\/\n\n#include \"qshell.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"modules\/uORB\/uORB.h\"\n#include \n#include \"DriverFramework.hpp\"\n\nextern void init_app_map(std::map &apps);\nextern void list_builtins(std::map &apps);\n\nusing std::map;\nusing std::string;\n\npx4::AppState QShell::appState;\n\nQShell::QShell()\n{\n\tinit_app_map(apps);\n}\n\nint QShell::main()\n{\n\tint rc;\n\tappState.setRunning(true);\n\tint sub_qshell_req = orb_subscribe(ORB_ID(qshell_req));\n\n\tif (sub_qshell_req == PX4_ERROR) {\n\t\tPX4_ERR(\"Error subscribing to qshell_req topic\");\n\t\treturn -1;\n\t}\n\n\tint i = 0;\n\n\twhile (!appState.exitRequested()) {\n\t\tbool updated = false;\n\n\t\tif (orb_check(sub_qshell_req, &updated) == 0) {\n\t\t\tif (updated) {\n\t\t\t\tPX4_DEBUG(\"[%d]qshell_req status is updated... reading new value\", i);\n\n\t\t\t\tif (orb_copy(ORB_ID(qshell_req), sub_qshell_req, &m_qshell_req) != 0) {\n\t\t\t\t\tPX4_ERR(\"[%d]Error calling orb copy for qshell_req... \", i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tchar current_char;\n\t\t\t\tstd::string arg;\n\t\t\t\tstd::vector appargs;\n\n\t\t\t\tfor (int str_idx = 0; str_idx < m_qshell_req.strlen; str_idx++) {\n\t\t\t\t\tcurrent_char = m_qshell_req.string[str_idx];\n\n\t\t\t\t\tif (isspace(current_char)) { \/\/ split at spaces\n\t\t\t\t\t\tif (arg.length()) {\n\t\t\t\t\t\t\tappargs.push_back(arg);\n\t\t\t\t\t\t\targ = \"\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\targ += current_char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tappargs.push_back(arg); \/\/ push last argument\n\n\t\t\t\tint ret = run_cmd(appargs);\n\n\t\t\t\tif (ret) {\n\t\t\t\t\tPX4_ERR(\"Failed to execute command\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tPX4_ERR(\"[%d]Error checking the updated status for qshell_req \", i);\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ sleep for 1\/2 sec.\n\t\tusleep(500000);\n\n\t\t++i;\n\t}\n\n\treturn 0;\n\tappState.setRunning(false);\n\treturn rc;\n}\n\nint QShell::run_cmd(const std::vector &appargs)\n{\n\t\/\/ command is appargs[0]\n\tstd::string command = appargs[0];\n\n\tif (command.compare(\"help\") == 0) {\n\t\tlist_builtins(apps);\n\t}\n\n\t\/\/replaces app.find with iterator code to avoid null pointer exception\n\tfor (map::iterator it = apps.begin(); it != apps.end(); ++it) {\n\t\tif (it->first == command) {\n\t\t\tconst char *arg[2 + 1];\n\n\t\t\tunsigned int i = 0;\n\n\t\t\twhile (i < appargs.size() && appargs[i].c_str()[0] != '\\0') {\n\t\t\t\targ[i] = (char *)appargs[i].c_str();\n\t\t\t\tPX4_DEBUG(\" arg%d = '%s'\\n\", i, arg[i]);\n\t\t\t\t++i;\n\t\t\t}\n\n\t\t\targ[i] = (char *)0;\n\n\t\t\t\/\/PX4_DEBUG_PRINTF(i);\n\t\t\tif (apps[command] == NULL) {\n\t\t\t\tPX4_ERR(\"Null function !!\\n\");\n\n\t\t\t} else {\n\t\t\t\treturn apps[command](i, (char **)arg);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tPX4_ERR(\"Command %s not found\", command.c_str());\n\treturn 1;\n}\nProper return value on qshell help\/****************************************************************************\n *\n * Copyright (c) 2016 PX4 Development Team. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * 3. Neither the name PX4 nor the names of its contributors may be\n * used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED\n * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n ****************************************************************************\/\n\n\/**\n * @file qshell.cpp\n * Listener for shell commands from posix\n *\n * @author Nicolas de Palezieux \n *\/\n\n#include \"qshell.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"modules\/uORB\/uORB.h\"\n#include \n#include \"DriverFramework.hpp\"\n\nextern void init_app_map(std::map &apps);\nextern void list_builtins(std::map &apps);\n\nusing std::map;\nusing std::string;\n\npx4::AppState QShell::appState;\n\nQShell::QShell()\n{\n\tinit_app_map(apps);\n}\n\nint QShell::main()\n{\n\tint rc;\n\tappState.setRunning(true);\n\tint sub_qshell_req = orb_subscribe(ORB_ID(qshell_req));\n\n\tif (sub_qshell_req == PX4_ERROR) {\n\t\tPX4_ERR(\"Error subscribing to qshell_req topic\");\n\t\treturn -1;\n\t}\n\n\tint i = 0;\n\n\twhile (!appState.exitRequested()) {\n\t\tbool updated = false;\n\n\t\tif (orb_check(sub_qshell_req, &updated) == 0) {\n\t\t\tif (updated) {\n\t\t\t\tPX4_DEBUG(\"[%d]qshell_req status is updated... reading new value\", i);\n\n\t\t\t\tif (orb_copy(ORB_ID(qshell_req), sub_qshell_req, &m_qshell_req) != 0) {\n\t\t\t\t\tPX4_ERR(\"[%d]Error calling orb copy for qshell_req... \", i);\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\n\t\t\t\tchar current_char;\n\t\t\t\tstd::string arg;\n\t\t\t\tstd::vector appargs;\n\n\t\t\t\tfor (int str_idx = 0; str_idx < m_qshell_req.strlen; str_idx++) {\n\t\t\t\t\tcurrent_char = m_qshell_req.string[str_idx];\n\n\t\t\t\t\tif (isspace(current_char)) { \/\/ split at spaces\n\t\t\t\t\t\tif (arg.length()) {\n\t\t\t\t\t\t\tappargs.push_back(arg);\n\t\t\t\t\t\t\targ = \"\";\n\t\t\t\t\t\t}\n\n\t\t\t\t\t} else {\n\t\t\t\t\t\targ += current_char;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tappargs.push_back(arg); \/\/ push last argument\n\n\t\t\t\tint ret = run_cmd(appargs);\n\n\t\t\t\tif (ret) {\n\t\t\t\t\tPX4_ERR(\"Failed to execute command\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t} else {\n\t\t\tPX4_ERR(\"[%d]Error checking the updated status for qshell_req \", i);\n\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ sleep for 1\/2 sec.\n\t\tusleep(500000);\n\n\t\t++i;\n\t}\n\n\treturn 0;\n\tappState.setRunning(false);\n\treturn rc;\n}\n\nint QShell::run_cmd(const std::vector &appargs)\n{\n\t\/\/ command is appargs[0]\n\tstd::string command = appargs[0];\n\n\tif (command.compare(\"help\") == 0) {\n\t\tlist_builtins(apps);\n\t\treturn 0;\n\t}\n\n\t\/\/replaces app.find with iterator code to avoid null pointer exception\n\tfor (map::iterator it = apps.begin(); it != apps.end(); ++it) {\n\t\tif (it->first == command) {\n\t\t\tconst char *arg[2 + 1];\n\n\t\t\tunsigned int i = 0;\n\n\t\t\twhile (i < appargs.size() && appargs[i].c_str()[0] != '\\0') {\n\t\t\t\targ[i] = (char *)appargs[i].c_str();\n\t\t\t\tPX4_DEBUG(\" arg%d = '%s'\\n\", i, arg[i]);\n\t\t\t\t++i;\n\t\t\t}\n\n\t\t\targ[i] = (char *)0;\n\n\t\t\t\/\/PX4_DEBUG_PRINTF(i);\n\t\t\tif (apps[command] == NULL) {\n\t\t\t\tPX4_ERR(\"Null function !!\\n\");\n\n\t\t\t} else {\n\t\t\t\treturn apps[command](i, (char **)arg);\n\t\t\t}\n\n\t\t}\n\t}\n\n\tPX4_ERR(\"Command %s not found\", command.c_str());\n\treturn 1;\n}\n<|endoftext|>"} {"text":"\/*\n * ClusterContracter.cpp\n *\n * Created on: 30.10.2012\n * Author: Christian Staudt (christian.staudt@kit.edu)\n *\/\n\n#include \"ClusterContracter.h\"\n\nnamespace NetworKit {\n\nClusterContracter::ClusterContracter() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nClusterContracter::~ClusterContracter() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nstd::pair > ClusterContracter::run(Graph& G, Clustering& zeta) {\n\n\tGraph Gcon(0); \/\/ empty graph\n\tGcon.markAsWeighted(); \/\/ Gcon will be a weighted graph\n\n\tIndexMap clusterToSuperNode(zeta.upperBound(), none); \/\/ there is one supernode for each cluster\n\n\t\/\/ populate map cluster -> supernode\n\tG.forNodes([&](node v){\n\t\tcluster c = zeta.clusterOf(v);\n\t\tif (! clusterToSuperNode.hasBeenSet(c)) {\n\t\t\tclusterToSuperNode[c] = Gcon.addNode(); \/\/ TODO: probably does not scale well, think about allocating ranges of nodes\n\t\t}\n\t});\n\n\n\tint64_t n = G.numberOfNodes();\n\tNodeMap nodeToSuperNode(n);\n\n\t\/\/ set entries node -> supernode\n\tG.parallelForNodes([&](node v){\n\t\tnodeToSuperNode[v] = clusterToSuperNode[zeta.clusterOf(v)];\n\t});\n\n\n\t\/\/ iterate over edges of G and create edges in Gcon or update edge and node weights in Gcon\n\tG.forWeightedEdges([&](node u, node v, edgeweight ew) {\n\t\tnode su = nodeToSuperNode[u];\n\t\tnode sv = nodeToSuperNode[v];\n\t\tif (zeta.clusterOf(u) == zeta.clusterOf(v)) {\n\t\t\t\/\/ add edge weight to supernode (self-loop) weight\n\t\t\tGcon.setWeight(su, su, Gcon.weight(su, su) + ew);\n\t\t} else {\n\t\t\t\/\/ add edge weight to weight between two supernodes (or insert edge)\n\t\t\tGcon.setWeight(su, sv, Gcon.weight(su, sv) + ew);\n\t\t}\n\t}); \/\/ TODO: parallel?\n\n\treturn std::make_pair(Gcon, nodeToSuperNode);\n\n}\n\n}\nbugfix TRACE\/*\n * ClusterContracter.cpp\n *\n * Created on: 30.10.2012\n * Author: Christian Staudt (christian.staudt@kit.edu)\n *\/\n\n#include \"ClusterContracter.h\"\n\nnamespace NetworKit {\n\nClusterContracter::ClusterContracter() {\n\t\/\/ TODO Auto-generated constructor stub\n\n}\n\nClusterContracter::~ClusterContracter() {\n\t\/\/ TODO Auto-generated destructor stub\n}\n\nstd::pair > ClusterContracter::run(Graph& G, Clustering& zeta) {\n\n\tGraph Gcon(0); \/\/ empty graph\n\tGcon.markAsWeighted(); \/\/ Gcon will be a weighted graph\n\n\tIndexMap clusterToSuperNode(zeta.upperBound(), none); \/\/ there is one supernode for each cluster\n\n\t\/\/ populate map cluster -> supernode\n\tG.forNodes([&](node v){\n\t\tcluster c = zeta.clusterOf(v);\n\t\tif (! clusterToSuperNode.hasBeenSet(c)) {\n\t\t\tclusterToSuperNode[c] = Gcon.addNode(); \/\/ TODO: probably does not scale well, think about allocating ranges of nodes\n\t\t}\n\t});\n\n\n\tint64_t n = G.numberOfNodes();\n\tNodeMap nodeToSuperNode(n);\n\n\t\/\/ set entries node -> supernode\n\tG.parallelForNodes([&](node v){\n\t\tnodeToSuperNode[v] = clusterToSuperNode[zeta.clusterOf(v)];\n\t});\n\n\n\t\/\/ iterate over edges of G and create edges in Gcon or update edge and node weights in Gcon\n\tG.forWeightedEdges([&](node u, node v, edgeweight ew) {\n\t\tnode su = nodeToSuperNode[u];\n\t\tnode sv = nodeToSuperNode[v];\n\t\tTRACE(\"edge (\", su, \", \", sv, \")\");\n\t\tif (zeta.clusterOf(u) == zeta.clusterOf(v)) {\n\t\t\t\/\/ add edge weight to supernode (self-loop) weight\n\t\t\tGcon.setWeight(su, su, Gcon.weight(su, su) + ew);\n\t\t} else {\n\t\t\t\/\/ add edge weight to weight between two supernodes (or insert edge)\n\t\t\tGcon.setWeight(su, sv, Gcon.weight(su, sv) + ew);\n\t\t}\n\t}); \/\/ TODO: parallel?\n\n\treturn std::make_pair(Gcon, nodeToSuperNode);\n\n}\n\n}\n<|endoftext|>"} {"text":"\/********************************************************************\n* Description: interp_execute.cc\n*\n* Derived from a work by Thomas Kramer\n*\n* Author:\n* License: GPL Version 2\n* System: Linux\n* \n* Copyright (c) 2004 All rights reserved.\n*\n* Last change:\n********************************************************************\/\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"rs274ngc.hh\"\n#include \"rs274ngc_return.hh\"\n#include \"interp_internal.hh\"\n#include \"rs274ngc_interp.hh\"\n\n#define RESULT_OK(x) ((x) == INTERP_OK || (x) == INTERP_EXECUTE_FINISH)\n\n\/****************************************************************************\/\n\n\/*! execute binary\n\nReturned value: int\n If execute_binary1 or execute_binary2 returns an error code, this\n returns that code.\n Otherwise, it returns INTERP_OK.\n\nSide effects: The value of left is set to the result of applying\n the operation to left and right.\n\nCalled by: read_real_expression\n\nThis just calls either execute_binary1 or execute_binary2.\n\n*\/\n\nint Interp::execute_binary(double *left, int operation, double *right)\n{\n if (operation < AND2)\n CHP(execute_binary1(left, operation, right));\n else\n CHP(execute_binary2(left, operation, right));\n return INTERP_OK;\n}\n\n\/****************************************************************************\/\n\n\/*! execute_binary1\n\nReturned Value: int\n If any of the following errors occur, this returns the error shown.\n Otherwise, it returns INTERP_OK.\n 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION\n 2. An attempt is made to divide by zero: NCE_ATTEMPT_TO_DIVIDE_BY_ZERO\n 3. An attempt is made to raise a negative number to a non-integer power:\n NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER\n\nSide effects:\n The result from performing the operation is put into what left points at.\n\nCalled by: read_real_expression.\n\nThis executes the operations: DIVIDED_BY, MODULO, POWER, TIMES.\n\n*\/\n\nint Interp::execute_binary1(double *left, \/\/!< pointer to the left operand \n int operation, \/\/!< integer code for the operation \n double *right) \/\/!< pointer to the right operand \n{\n switch (operation) {\n case DIVIDED_BY:\n CHKS((*right == 0.0), NCE_ATTEMPT_TO_DIVIDE_BY_ZERO);\n *left = (*left \/ *right);\n break;\n case MODULO: \/* always calculates a positive answer *\/\n *left = fmod(*left, *right);\n if (*left < 0.0) {\n *left = (*left + fabs(*right));\n }\n break;\n case POWER:\n CHKS(((*left < 0.0) && (floor(*right) != *right)),\n NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER);\n *left = pow(*left, *right);\n break;\n case TIMES:\n *left = (*left * *right);\n break;\n default:\n ERS(NCE_BUG_UNKNOWN_OPERATION);\n }\n return INTERP_OK;\n}\n\n\/****************************************************************************\/\n\n\/*! execute_binary2\n\nReturned Value: int\n If any of the following errors occur, this returns the error code shown.\n Otherwise, it returns INTERP_OK.\n 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION\n\nSide effects:\n The result from performing the operation is put into what left points at.\n\nCalled by: read_real_expression.\n\nThis executes the operations: AND2, EXCLUSIVE_OR, MINUS,\nNON_EXCLUSIVE_OR, PLUS. The RS274\/NGC manual [NCMS] does not say what\nthe calculated value of the three logical operations should be. This\nfunction calculates either 1.0 (meaning true) or 0.0 (meaning false).\nAny non-zero input value is taken as meaning true, and only 0.0 means\nfalse.\n\n\n*\/\n\nint Interp::execute_binary2(double *left, \/\/!< pointer to the left operand \n int operation, \/\/!< integer code for the operation \n double *right) \/\/!< pointer to the right operand \n{\n double diff;\n switch (operation) {\n case AND2:\n *left = ((*left == 0.0) || (*right == 0.0)) ? 0.0 : 1.0;\n break;\n case EXCLUSIVE_OR:\n *left = (((*left == 0.0) && (*right != 0.0))\n || ((*left != 0.0) && (*right == 0.0))) ? 1.0 : 0.0;\n break;\n case MINUS:\n *left = (*left - *right);\n break;\n case NON_EXCLUSIVE_OR:\n *left = ((*left != 0.0) || (*right != 0.0)) ? 1.0 : 0.0;\n break;\n case PLUS:\n *left = (*left + *right);\n break;\n\n case LT:\n *left = (*left < *right) ? 1.0 : 0.0;\n break;\n case EQ:\n diff = *left - *right;\n diff = (diff < 0) ? -diff : diff;\n *left = (diff < TOLERANCE_EQUAL) ? 1.0 : 0.0;\n break;\n case NE:\n diff = *left - *right;\n diff = (diff < 0) ? -diff : diff;\n *left = (diff >= TOLERANCE_EQUAL) ? 1.0 : 0.0;\n break;\n case LE:\n *left = (*left <= *right) ? 1.0 : 0.0;\n break;\n case GE:\n *left = (*left >= *right) ? 1.0 : 0.0;\n break;\n case GT:\n *left = (*left > *right) ? 1.0 : 0.0;\n break;\n\n default:\n ERS(NCE_BUG_UNKNOWN_OPERATION);\n }\n return INTERP_OK;\n}\n\n\n\/****************************************************************************\/\n\n\/*! execute_block\n\nReturned Value: int\n If convert_stop returns INTERP_EXIT, this returns INTERP_EXIT.\n If any of the following functions is called and returns an error code,\n this returns that code.\n convert_comment\n convert_feed_mode\n convert_feed_rate\n convert_g\n convert_m\n convert_speed\n convert_stop\n convert_tool_select\n Otherwise, if the probe_flag in the settings is true, \n or the input_flag is set to true this returns\n INTERP_EXECUTE_FINISH.\n Otherwise, it returns INTERP_OK.\n\nSide effects:\n One block of RS274\/NGC instructions is executed.\n\nCalled by:\n Interp::execute\n\nThis converts a block to zero to many actions. The order of execution\nof items in a block is critical to safe and effective machine operation,\nbut is not specified clearly in the RS274\/NGC documentation.\n\nActions are executed in the following order:\n1. any comment.\n2. a feed mode setting (g93, g94, g95)\n3. a feed rate (f) setting if in units_per_minute feed mode.\n4. a spindle speed (s) setting.\n5. a tool selection (t).\n6. \"m\" commands as described in convert_m (includes tool change).\n7. any g_codes (except g93, g94) as described in convert_g.\n8. stopping commands (m0, m1, m2, m30, or m60).\n\nIn inverse time feed mode, the explicit and implicit g code executions\ninclude feed rate setting with g1, g2, and g3. Also in inverse time\nfeed mode, attempting a canned cycle cycle (g81 to g89) or setting a\nfeed rate with g0 is illegal and will be detected and result in an\nerror message.\n\n*\/\n\nint Interp::execute_block(block_pointer block, \/\/!< pointer to a block of RS274\/NGC instructions\n\t\t\t setup_pointer settings) \/\/!< pointer to machine settings\n{\n int status;\n\n if (settings->remap_level == 0)\n {\n block->line_number = settings->sequence_number;\n } else\n { \/\/ use saved_line_number of toplevel for motion-id\n block->line_number = settings->blocks[settings->remap_level].saved_line_number;\n }\n\n if ((block->comment[0] != 0) && ONCE(STEP_COMMENT)) {\n status = convert_comment(block->comment);\n CHP(status);\n }\n if ((block->g_modes[GM_SPINDLE_MODE] != -1) && ONCE(STEP_SPINDLE_MODE)) {\n status = convert_spindle_mode(block, settings);\n CHP(status);\n }\n if ((block->g_modes[GM_FEED_MODE] != -1) && ONCE(STEP_FEED_MODE)) {\n status = convert_feed_mode(block->g_modes[GM_FEED_MODE], settings);\n CHP(status);\n\n }\n if (block->f_flag){\n if ((settings->feed_mode != INVERSE_TIME) && ONCE(STEP_SET_FEED_RATE)) {\n\t if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_FEED_RATE)) {\n\t return (convert_remapped_code(block, settings, STEP_SET_FEED_RATE, 'F'));\n\t } else {\n\t status = convert_feed_rate(block, settings);\n\t CHP(status);\n\t }\n }\n \/* INVERSE_TIME is handled elsewhere *\/\n }\n if ((block->s_flag) && ONCE(STEP_SET_SPINDLE_SPEED)){\n if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_SPINDLE_SPEED)) {\n\t return (convert_remapped_code(block,settings,STEP_SET_SPINDLE_SPEED,'S'));\n } else {\n\t status = convert_speed(block, settings);\n\t CHP(status);\n }\n }\n if ((block->t_flag) && ONCE(STEP_PREPARE)) {\n if (STEP_REMAPPED_IN_BLOCK(block, STEP_PREPARE)) {\n\t return (convert_remapped_code(block,settings,STEP_PREPARE,'T'));\n } else {\n\t CHP(convert_tool_select(block, settings));\n }\n }\n CHP(convert_m(block, settings));\n CHP(convert_g(block, settings));\n if ((block->m_modes[4] != -1) && ONCE(STEP_MGROUP4)) { \/* converts m0, m1, m2, m30, or m60 *\/\n if (STEP_REMAPPED_IN_BLOCK(block, STEP_MGROUP4)) {\n\t status = convert_remapped_code(block,settings,STEP_MGROUP4,'M',block->m_modes[4]);\n } else {\n\t status = convert_stop(block, settings);\n }\n if (status == INTERP_EXIT) {\n\treturn(INTERP_EXIT);\n }\n else if (status != INTERP_OK) {\n\tERP(status);\n }\n }\n if (settings->probe_flag)\n return (INTERP_EXECUTE_FINISH);\n\n if (settings->input_flag)\n return (INTERP_EXECUTE_FINISH);\n\n if (settings->toolchange_flag)\n return (INTERP_EXECUTE_FINISH);\n\n return INTERP_OK;\n}\n\n\/****************************************************************************\/\n\n\/*! execute_unary\n\nReturned Value: int\n If any of the following errors occur, this returns the error code shown.\n Otherwise, it returns INTERP_OK.\n 1. the operation is unknown: NCE_BUG_UNKNOWN_OPERATION\n 2. the argument to acos is not between minus and plus one:\n NCE_ARGUMENT_TO_ACOS_OUT_RANGE\n 3. the argument to asin is not between minus and plus one:\n NCE_ARGUMENT_TO_ASIN_OUT_RANGE\n 4. the argument to the natural logarithm is not positive:\n NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN\n 5. the argument to square root is negative:\n NCE_NEGATIVE_ARGUMENT_TO_SQRT\n\nSide effects:\n The result from performing the operation on the value in double_ptr\n is put into what double_ptr points at.\n\nCalled by: read_unary.\n\nThis executes the operations: ABS, ACOS, ASIN, COS, EXP, FIX, FUP, LN\nROUND, SIN, SQRT, TAN\n\nAll angle measures in the input or output are in degrees.\n\n*\/\n\nint Interp::execute_unary(double *double_ptr, \/\/!< pointer to the operand \n int operation) \/\/!< integer code for the operation \n{\n switch (operation) {\n case ABS:\n if (*double_ptr < 0.0)\n *double_ptr = (-1.0 * *double_ptr);\n break;\n case ACOS:\n CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)),\n NCE_ARGUMENT_TO_ACOS_OUT_OF_RANGE);\n *double_ptr = acos(*double_ptr);\n *double_ptr = ((*double_ptr * 180.0) \/ M_PIl);\n break;\n case ASIN:\n CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)),\n NCE_ARGUMENT_TO_ASIN_OUT_OF_RANGE);\n *double_ptr = asin(*double_ptr);\n *double_ptr = ((*double_ptr * 180.0) \/ M_PIl);\n break;\n case COS:\n *double_ptr = cos((*double_ptr * M_PIl) \/ 180.0);\n break;\n case EXISTS:\n \/\/ do nothing here\n \/\/ result for the EXISTS function is set by Interp:read_unary()\n break;\n case EXP:\n *double_ptr = exp(*double_ptr);\n break;\n case FIX:\n *double_ptr = floor(*double_ptr);\n break;\n case FUP:\n *double_ptr = ceil(*double_ptr);\n break;\n case LN:\n CHKS((*double_ptr <= 0.0), NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN);\n *double_ptr = log(*double_ptr);\n break;\n case ROUND:\n *double_ptr = (double)\n ((int) (*double_ptr + ((*double_ptr < 0.0) ? -0.5 : 0.5)));\n break;\n case SIN:\n *double_ptr = sin((*double_ptr * M_PIl) \/ 180.0);\n break;\n case SQRT:\n CHKS((*double_ptr < 0.0), NCE_NEGATIVE_ARGUMENT_TO_SQRT);\n *double_ptr = sqrt(*double_ptr);\n break;\n case TAN:\n *double_ptr = tan((*double_ptr * M_PIl) \/ 180.0);\n break;\n default:\n ERS(NCE_BUG_UNKNOWN_OPERATION);\n }\n return INTERP_OK;\n}\n\nInterp::execute_block(): remove INTERP_EXECUTE_FINISH\/********************************************************************\n* Description: interp_execute.cc\n*\n* Derived from a work by Thomas Kramer\n*\n* Author:\n* License: GPL Version 2\n* System: Linux\n* \n* Copyright (c) 2004 All rights reserved.\n*\n* Last change:\n********************************************************************\/\n#ifndef _GNU_SOURCE\n#define _GNU_SOURCE\n#endif\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"rs274ngc.hh\"\n#include \"rs274ngc_return.hh\"\n#include \"interp_internal.hh\"\n#include \"rs274ngc_interp.hh\"\n\n\/****************************************************************************\/\n\n\/*! execute binary\n\nReturned value: int\n If execute_binary1 or execute_binary2 returns an error code, this\n returns that code.\n Otherwise, it returns INTERP_OK.\n\nSide effects: The value of left is set to the result of applying\n the operation to left and right.\n\nCalled by: read_real_expression\n\nThis just calls either execute_binary1 or execute_binary2.\n\n*\/\n\nint Interp::execute_binary(double *left, int operation, double *right)\n{\n if (operation < AND2)\n CHP(execute_binary1(left, operation, right));\n else\n CHP(execute_binary2(left, operation, right));\n return INTERP_OK;\n}\n\n\/****************************************************************************\/\n\n\/*! execute_binary1\n\nReturned Value: int\n If any of the following errors occur, this returns the error shown.\n Otherwise, it returns INTERP_OK.\n 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION\n 2. An attempt is made to divide by zero: NCE_ATTEMPT_TO_DIVIDE_BY_ZERO\n 3. An attempt is made to raise a negative number to a non-integer power:\n NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER\n\nSide effects:\n The result from performing the operation is put into what left points at.\n\nCalled by: read_real_expression.\n\nThis executes the operations: DIVIDED_BY, MODULO, POWER, TIMES.\n\n*\/\n\nint Interp::execute_binary1(double *left, \/\/!< pointer to the left operand \n int operation, \/\/!< integer code for the operation \n double *right) \/\/!< pointer to the right operand \n{\n switch (operation) {\n case DIVIDED_BY:\n CHKS((*right == 0.0), NCE_ATTEMPT_TO_DIVIDE_BY_ZERO);\n *left = (*left \/ *right);\n break;\n case MODULO: \/* always calculates a positive answer *\/\n *left = fmod(*left, *right);\n if (*left < 0.0) {\n *left = (*left + fabs(*right));\n }\n break;\n case POWER:\n CHKS(((*left < 0.0) && (floor(*right) != *right)),\n NCE_ATTEMPT_TO_RAISE_NEGATIVE_TO_NON_INTEGER_POWER);\n *left = pow(*left, *right);\n break;\n case TIMES:\n *left = (*left * *right);\n break;\n default:\n ERS(NCE_BUG_UNKNOWN_OPERATION);\n }\n return INTERP_OK;\n}\n\n\/****************************************************************************\/\n\n\/*! execute_binary2\n\nReturned Value: int\n If any of the following errors occur, this returns the error code shown.\n Otherwise, it returns INTERP_OK.\n 1. operation is unknown: NCE_BUG_UNKNOWN_OPERATION\n\nSide effects:\n The result from performing the operation is put into what left points at.\n\nCalled by: read_real_expression.\n\nThis executes the operations: AND2, EXCLUSIVE_OR, MINUS,\nNON_EXCLUSIVE_OR, PLUS. The RS274\/NGC manual [NCMS] does not say what\nthe calculated value of the three logical operations should be. This\nfunction calculates either 1.0 (meaning true) or 0.0 (meaning false).\nAny non-zero input value is taken as meaning true, and only 0.0 means\nfalse.\n\n\n*\/\n\nint Interp::execute_binary2(double *left, \/\/!< pointer to the left operand \n int operation, \/\/!< integer code for the operation \n double *right) \/\/!< pointer to the right operand \n{\n double diff;\n switch (operation) {\n case AND2:\n *left = ((*left == 0.0) || (*right == 0.0)) ? 0.0 : 1.0;\n break;\n case EXCLUSIVE_OR:\n *left = (((*left == 0.0) && (*right != 0.0))\n || ((*left != 0.0) && (*right == 0.0))) ? 1.0 : 0.0;\n break;\n case MINUS:\n *left = (*left - *right);\n break;\n case NON_EXCLUSIVE_OR:\n *left = ((*left != 0.0) || (*right != 0.0)) ? 1.0 : 0.0;\n break;\n case PLUS:\n *left = (*left + *right);\n break;\n\n case LT:\n *left = (*left < *right) ? 1.0 : 0.0;\n break;\n case EQ:\n diff = *left - *right;\n diff = (diff < 0) ? -diff : diff;\n *left = (diff < TOLERANCE_EQUAL) ? 1.0 : 0.0;\n break;\n case NE:\n diff = *left - *right;\n diff = (diff < 0) ? -diff : diff;\n *left = (diff >= TOLERANCE_EQUAL) ? 1.0 : 0.0;\n break;\n case LE:\n *left = (*left <= *right) ? 1.0 : 0.0;\n break;\n case GE:\n *left = (*left >= *right) ? 1.0 : 0.0;\n break;\n case GT:\n *left = (*left > *right) ? 1.0 : 0.0;\n break;\n\n default:\n ERS(NCE_BUG_UNKNOWN_OPERATION);\n }\n return INTERP_OK;\n}\n\n\n\/****************************************************************************\/\n\n\/*! execute_block\n\nReturned Value: int\n If convert_stop returns INTERP_EXIT, this returns INTERP_EXIT.\n If any of the following functions is called and returns an error code,\n this returns that code.\n convert_comment\n convert_feed_mode\n convert_feed_rate\n convert_g\n convert_m\n convert_speed\n convert_stop\n convert_tool_select\n Otherwise, it returns INTERP_OK.\n\nSide effects:\n One block of RS274\/NGC instructions is executed.\n\nCalled by:\n Interp::execute\n\nThis converts a block to zero to many actions. The order of execution\nof items in a block is critical to safe and effective machine operation,\nbut is not specified clearly in the RS274\/NGC documentation.\n\nActions are executed in the following order:\n1. any comment.\n2. a feed mode setting (g93, g94, g95)\n3. a feed rate (f) setting if in units_per_minute feed mode.\n4. a spindle speed (s) setting.\n5. a tool selection (t).\n6. \"m\" commands as described in convert_m (includes tool change).\n7. any g_codes (except g93, g94) as described in convert_g.\n8. stopping commands (m0, m1, m2, m30, or m60).\n\nIn inverse time feed mode, the explicit and implicit g code executions\ninclude feed rate setting with g1, g2, and g3. Also in inverse time\nfeed mode, attempting a canned cycle cycle (g81 to g89) or setting a\nfeed rate with g0 is illegal and will be detected and result in an\nerror message.\n\n*\/\n\nint Interp::execute_block(block_pointer block, \/\/!< pointer to a block of RS274\/NGC instructions\n\t\t\t setup_pointer settings) \/\/!< pointer to machine settings\n{\n int status;\n\n if (settings->remap_level == 0)\n {\n block->line_number = settings->sequence_number;\n } else\n { \/\/ use saved_line_number of toplevel for motion-id\n block->line_number = settings->blocks[settings->remap_level].saved_line_number;\n }\n\n if ((block->comment[0] != 0) && ONCE(STEP_COMMENT)) {\n status = convert_comment(block->comment);\n CHP(status);\n }\n if ((block->g_modes[GM_SPINDLE_MODE] != -1) && ONCE(STEP_SPINDLE_MODE)) {\n status = convert_spindle_mode(block, settings);\n CHP(status);\n }\n if ((block->g_modes[GM_FEED_MODE] != -1) && ONCE(STEP_FEED_MODE)) {\n status = convert_feed_mode(block->g_modes[GM_FEED_MODE], settings);\n CHP(status);\n\n }\n if (block->f_flag){\n if ((settings->feed_mode != INVERSE_TIME) && ONCE(STEP_SET_FEED_RATE)) {\n\t if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_FEED_RATE)) {\n\t return (convert_remapped_code(block, settings, STEP_SET_FEED_RATE, 'F'));\n\t } else {\n\t status = convert_feed_rate(block, settings);\n\t CHP(status);\n\t }\n }\n \/* INVERSE_TIME is handled elsewhere *\/\n }\n if ((block->s_flag) && ONCE(STEP_SET_SPINDLE_SPEED)){\n if (STEP_REMAPPED_IN_BLOCK(block, STEP_SET_SPINDLE_SPEED)) {\n\t return (convert_remapped_code(block,settings,STEP_SET_SPINDLE_SPEED,'S'));\n } else {\n\t status = convert_speed(block, settings);\n\t CHP(status);\n }\n }\n if ((block->t_flag) && ONCE(STEP_PREPARE)) {\n if (STEP_REMAPPED_IN_BLOCK(block, STEP_PREPARE)) {\n\t return (convert_remapped_code(block,settings,STEP_PREPARE,'T'));\n } else {\n\t CHP(convert_tool_select(block, settings));\n }\n }\n CHP(convert_m(block, settings));\n CHP(convert_g(block, settings));\n if ((block->m_modes[4] != -1) && ONCE(STEP_MGROUP4)) { \/* converts m0, m1, m2, m30, or m60 *\/\n if (STEP_REMAPPED_IN_BLOCK(block, STEP_MGROUP4)) {\n\t status = convert_remapped_code(block,settings,STEP_MGROUP4,'M',block->m_modes[4]);\n } else {\n\t status = convert_stop(block, settings);\n }\n if (status == INTERP_EXIT) {\n\treturn(INTERP_EXIT);\n }\n else if (status != INTERP_OK) {\n\tERP(status);\n }\n }\n\n return INTERP_OK;\n}\n\n\/****************************************************************************\/\n\n\/*! execute_unary\n\nReturned Value: int\n If any of the following errors occur, this returns the error code shown.\n Otherwise, it returns INTERP_OK.\n 1. the operation is unknown: NCE_BUG_UNKNOWN_OPERATION\n 2. the argument to acos is not between minus and plus one:\n NCE_ARGUMENT_TO_ACOS_OUT_RANGE\n 3. the argument to asin is not between minus and plus one:\n NCE_ARGUMENT_TO_ASIN_OUT_RANGE\n 4. the argument to the natural logarithm is not positive:\n NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN\n 5. the argument to square root is negative:\n NCE_NEGATIVE_ARGUMENT_TO_SQRT\n\nSide effects:\n The result from performing the operation on the value in double_ptr\n is put into what double_ptr points at.\n\nCalled by: read_unary.\n\nThis executes the operations: ABS, ACOS, ASIN, COS, EXP, FIX, FUP, LN\nROUND, SIN, SQRT, TAN\n\nAll angle measures in the input or output are in degrees.\n\n*\/\n\nint Interp::execute_unary(double *double_ptr, \/\/!< pointer to the operand \n int operation) \/\/!< integer code for the operation \n{\n switch (operation) {\n case ABS:\n if (*double_ptr < 0.0)\n *double_ptr = (-1.0 * *double_ptr);\n break;\n case ACOS:\n CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)),\n NCE_ARGUMENT_TO_ACOS_OUT_OF_RANGE);\n *double_ptr = acos(*double_ptr);\n *double_ptr = ((*double_ptr * 180.0) \/ M_PIl);\n break;\n case ASIN:\n CHKS(((*double_ptr < -1.0) || (*double_ptr > 1.0)),\n NCE_ARGUMENT_TO_ASIN_OUT_OF_RANGE);\n *double_ptr = asin(*double_ptr);\n *double_ptr = ((*double_ptr * 180.0) \/ M_PIl);\n break;\n case COS:\n *double_ptr = cos((*double_ptr * M_PIl) \/ 180.0);\n break;\n case EXISTS:\n \/\/ do nothing here\n \/\/ result for the EXISTS function is set by Interp:read_unary()\n break;\n case EXP:\n *double_ptr = exp(*double_ptr);\n break;\n case FIX:\n *double_ptr = floor(*double_ptr);\n break;\n case FUP:\n *double_ptr = ceil(*double_ptr);\n break;\n case LN:\n CHKS((*double_ptr <= 0.0), NCE_ZERO_OR_NEGATIVE_ARGUMENT_TO_LN);\n *double_ptr = log(*double_ptr);\n break;\n case ROUND:\n *double_ptr = (double)\n ((int) (*double_ptr + ((*double_ptr < 0.0) ? -0.5 : 0.5)));\n break;\n case SIN:\n *double_ptr = sin((*double_ptr * M_PIl) \/ 180.0);\n break;\n case SQRT:\n CHKS((*double_ptr < 0.0), NCE_NEGATIVE_ARGUMENT_TO_SQRT);\n *double_ptr = sqrt(*double_ptr);\n break;\n case TAN:\n *double_ptr = tan((*double_ptr * M_PIl) \/ 180.0);\n break;\n default:\n ERS(NCE_BUG_UNKNOWN_OPERATION);\n }\n return INTERP_OK;\n}\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: listenernotification.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2004-11-26 21:08:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_INC_COMPHELPER_LISTENERNOTIFICATION_HXX\n#include \n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include \n#endif\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace comphelper\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n\n \/\/====================================================================\n \/\/= OListenerContainer\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OListenerContainer::OListenerContainer( ::osl::Mutex& _rMutex )\n :m_aListeners( _rMutex )\n {\n }\n\n \/\/--------------------------------------------------------------------\n void OListenerContainer::addListener( const Reference< XEventListener >& _rxListener )\n {\n OSL_PRECOND( _rxListener.is(), \"OListenerContainer::addListener: a NULL listener?!\" );\n if ( _rxListener.is() )\n m_aListeners.addInterface( _rxListener );\n }\n\n \/\/--------------------------------------------------------------------\n void OListenerContainer::removeListener( const Reference< XEventListener >& _rxListener )\n {\n#if OSL_DEBUG_LEVEL > 0\n ::cppu::OInterfaceIteratorHelper aIter( m_aListeners );\n bool bFound = false;\n while ( aIter.hasMoreElements() && !bFound )\n {\n bFound = ( Reference< XInterface >( aIter.next() ) == _rxListener );\n }\n OSL_ENSURE( bFound, \"OListenerContainer::removeListener: sure your listener handling is correct? The given listener is not registered!\" );\n#endif\n m_aListeners.removeInterface( _rxListener );\n }\n\n \/\/--------------------------------------------------------------------\n void OListenerContainer::disposing( const EventObject& _rEventSource )\n {\n m_aListeners.disposeAndClear( _rEventSource );\n }\n\n \/\/--------------------------------------------------------------------\n bool OListenerContainer::notify( const EventObject& _rEvent ) SAL_THROW(( Exception ))\n {\n ::cppu::OInterfaceIteratorHelper aIter( m_aListeners );\n bool bCancelled = false;\n while ( aIter.hasMoreElements() && !bCancelled )\n {\n Reference< XEventListener > xListener( static_cast< XEventListener* >( aIter.next() ) );\n if ( !xListener.is() )\n continue;\n\n try\n {\n bCancelled = !implNotify( xListener, _rEvent );\n }\n catch( const DisposedException& e )\n {\n \/\/ DisposedExceptions from the listener might indicate a\n \/\/ broken connection to a different environment.\n\n OSL_ENSURE( e.Context.is(), \"OListenerContainer::notify: caught dispose exception with empty Context field\" );\n\n \/\/ If the exception stems from the listener then remove it\n \/\/ from the list of listeners. If the Context field of the\n \/\/ exception is empty this is interpreted to indicate the\n \/\/ listener as well.\n if ( e.Context == xListener || !e.Context.is() )\n aIter.remove();\n }\n }\n\n return !bCancelled;\n }\n\n\/\/........................................................................\n} \/\/ namespace comphelper\n\/\/........................................................................\n\nINTEGRATION: CWS ooo19126 (1.4.84); FILE MERGED 2005\/09\/05 15:24:01 rt 1.4.84.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: listenernotification.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 02:50:23 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef COMPHELPER_INC_COMPHELPER_LISTENERNOTIFICATION_HXX\n#include \n#endif\n\n\/** === begin UNO includes === **\/\n#ifndef _COM_SUN_STAR_LANG_DISPOSEDEXCEPTION_HPP_\n#include \n#endif\n\/** === end UNO includes === **\/\n\n\/\/........................................................................\nnamespace comphelper\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::lang;\n\n \/\/====================================================================\n \/\/= OListenerContainer\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OListenerContainer::OListenerContainer( ::osl::Mutex& _rMutex )\n :m_aListeners( _rMutex )\n {\n }\n\n \/\/--------------------------------------------------------------------\n void OListenerContainer::addListener( const Reference< XEventListener >& _rxListener )\n {\n OSL_PRECOND( _rxListener.is(), \"OListenerContainer::addListener: a NULL listener?!\" );\n if ( _rxListener.is() )\n m_aListeners.addInterface( _rxListener );\n }\n\n \/\/--------------------------------------------------------------------\n void OListenerContainer::removeListener( const Reference< XEventListener >& _rxListener )\n {\n#if OSL_DEBUG_LEVEL > 0\n ::cppu::OInterfaceIteratorHelper aIter( m_aListeners );\n bool bFound = false;\n while ( aIter.hasMoreElements() && !bFound )\n {\n bFound = ( Reference< XInterface >( aIter.next() ) == _rxListener );\n }\n OSL_ENSURE( bFound, \"OListenerContainer::removeListener: sure your listener handling is correct? The given listener is not registered!\" );\n#endif\n m_aListeners.removeInterface( _rxListener );\n }\n\n \/\/--------------------------------------------------------------------\n void OListenerContainer::disposing( const EventObject& _rEventSource )\n {\n m_aListeners.disposeAndClear( _rEventSource );\n }\n\n \/\/--------------------------------------------------------------------\n bool OListenerContainer::notify( const EventObject& _rEvent ) SAL_THROW(( Exception ))\n {\n ::cppu::OInterfaceIteratorHelper aIter( m_aListeners );\n bool bCancelled = false;\n while ( aIter.hasMoreElements() && !bCancelled )\n {\n Reference< XEventListener > xListener( static_cast< XEventListener* >( aIter.next() ) );\n if ( !xListener.is() )\n continue;\n\n try\n {\n bCancelled = !implNotify( xListener, _rEvent );\n }\n catch( const DisposedException& e )\n {\n \/\/ DisposedExceptions from the listener might indicate a\n \/\/ broken connection to a different environment.\n\n OSL_ENSURE( e.Context.is(), \"OListenerContainer::notify: caught dispose exception with empty Context field\" );\n\n \/\/ If the exception stems from the listener then remove it\n \/\/ from the list of listeners. If the Context field of the\n \/\/ exception is empty this is interpreted to indicate the\n \/\/ listener as well.\n if ( e.Context == xListener || !e.Context.is() )\n aIter.remove();\n }\n }\n\n return !bCancelled;\n }\n\n\/\/........................................................................\n} \/\/ namespace comphelper\n\/\/........................................................................\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Unit tests for FileID\n\n#include \n#include \n\n#include \"common\/linux\/file_id.h\"\n#include \"breakpad_googletest_includes.h\"\n\nusing namespace google_breakpad;\n\n\nnamespace {\ntypedef testing::Test FileIDTest;\n}\n\nTEST(FileIDTest, FileIDStrip) {\n \/\/ Calculate the File ID of our binary using\n \/\/ FileID::ElfFileIdentifier, then make a copy of our binary,\n \/\/ strip it, and ensure that we still get the same result.\n char exe_name[PATH_MAX];\n ssize_t len = readlink(\"\/proc\/self\/exe\", exe_name, PATH_MAX - 1);\n ASSERT_NE(len, -1);\n exe_name[len] = '\\0';\n\n \/\/ copy our binary to a temp file, and strip it\n char templ[] = \"\/tmp\/file-id-unittest-XXXXXX\";\n mktemp(templ);\n char cmdline[4096];\n sprintf(cmdline, \"cp \\\"%s\\\" \\\"%s\\\"\", exe_name, templ);\n ASSERT_EQ(system(cmdline), 0);\n sprintf(cmdline, \"strip \\\"%s\\\"\", templ);\n ASSERT_EQ(system(cmdline), 0);\n\n uint8_t identifier1[sizeof(MDGUID)];\n uint8_t identifier2[sizeof(MDGUID)];\n FileID fileid1(exe_name);\n EXPECT_TRUE(fileid1.ElfFileIdentifier(identifier1));\n FileID fileid2(templ);\n EXPECT_TRUE(fileid2.ElfFileIdentifier(identifier2));\n char identifier_string1[37];\n char identifier_string2[37];\n FileID::ConvertIdentifierToString(identifier1, identifier_string1,\n 37);\n FileID::ConvertIdentifierToString(identifier2, identifier_string2,\n 37);\n EXPECT_STREQ(identifier_string1, identifier_string2);\n unlink(templ);\n}\n\nstruct ElfClass32 {\n typedef Elf32_Ehdr Ehdr;\n typedef Elf32_Shdr Shdr;\n static const int kClass = ELFCLASS32;\n};\n\nstruct ElfClass64 {\n typedef Elf64_Ehdr Ehdr;\n typedef Elf64_Shdr Shdr;\n static const int kClass = ELFCLASS64;\n};\n\ntemplate\nstruct ElfishElf {\n typedef typename ElfClass::Ehdr Ehdr;\n typedef typename ElfClass::Shdr Shdr;\n\n Ehdr elf_header;\n Shdr text_header;\n Shdr string_header;\n char text_section[128];\n char string_section[8];\n\n static void Populate(ElfishElf* elf) {\n memset(elf, 0, sizeof(ElfishElf));\n memcpy(elf, ELFMAG, SELFMAG);\n elf->elf_header.e_ident[EI_CLASS] = ElfClass::kClass;\n elf->elf_header.e_shoff = offsetof(ElfishElf, text_header);\n elf->elf_header.e_shnum = 2;\n elf->elf_header.e_shstrndx = 1;\n elf->text_header.sh_name = 0;\n elf->text_header.sh_type = SHT_PROGBITS;\n elf->text_header.sh_offset = offsetof(ElfishElf, text_section);\n elf->text_header.sh_size = sizeof(text_section);\n for (size_t i = 0; i < sizeof(text_section); ++i) {\n elf->text_section[i] = i * 3;\n }\n elf->string_header.sh_offset = offsetof(ElfishElf, string_section);\n strcpy(elf->string_section, \".text\");\n }\n};\n\nTEST(FileIDTest, ElfClass) {\n uint8_t identifier[sizeof(MDGUID)];\n const char expected_identifier_string[] =\n \"80808080-8080-0000-0000-008080808080\";\n char identifier_string[sizeof(expected_identifier_string)];\n\n ElfishElf elf32;\n ElfishElf::Populate(&elf32);\n EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf32, identifier));\n FileID::ConvertIdentifierToString(identifier, identifier_string,\n sizeof(identifier_string));\n EXPECT_STREQ(expected_identifier_string, identifier_string);\n\n memset(identifier, 0, sizeof(identifier));\n memset(identifier_string, 0, sizeof(identifier_string));\n\n ElfishElf elf64;\n ElfishElf::Populate(&elf64);\n EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf64, identifier));\n FileID::ConvertIdentifierToString(identifier, identifier_string,\n sizeof(identifier_string));\n EXPECT_STREQ(expected_identifier_string, identifier_string);\n}\nFix compilation of file_id_unittest. Review URL: http:\/\/breakpad.appspot.com\/198001\/\/ Copyright (c) 2010, Google Inc.\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are\n\/\/ met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ * Redistributions in binary form must reproduce the above\n\/\/ copyright notice, this list of conditions and the following disclaimer\n\/\/ in the documentation and\/or other materials provided with the\n\/\/ distribution.\n\/\/ * Neither the name of Google Inc. nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n\/\/ A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n\/\/ OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n\/\/ SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n\/\/ LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n\/\/ DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n\/\/ THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n\/\/ (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n\/\/ Unit tests for FileID\n\n#include \n#include \n\n#include \"common\/linux\/file_id.h\"\n#include \"breakpad_googletest_includes.h\"\n\nusing namespace google_breakpad;\n\nnamespace {\ntypedef testing::Test FileIDTest;\n}\n\nTEST(FileIDTest, FileIDStrip) {\n \/\/ Calculate the File ID of our binary using\n \/\/ FileID::ElfFileIdentifier, then make a copy of our binary,\n \/\/ strip it, and ensure that we still get the same result.\n char exe_name[PATH_MAX];\n ssize_t len = readlink(\"\/proc\/self\/exe\", exe_name, PATH_MAX - 1);\n ASSERT_NE(len, -1);\n exe_name[len] = '\\0';\n\n \/\/ copy our binary to a temp file, and strip it\n char templ[] = \"\/tmp\/file-id-unittest-XXXXXX\";\n mktemp(templ);\n char cmdline[4096];\n sprintf(cmdline, \"cp \\\"%s\\\" \\\"%s\\\"\", exe_name, templ);\n ASSERT_EQ(system(cmdline), 0);\n sprintf(cmdline, \"strip \\\"%s\\\"\", templ);\n ASSERT_EQ(system(cmdline), 0);\n\n uint8_t identifier1[sizeof(MDGUID)];\n uint8_t identifier2[sizeof(MDGUID)];\n FileID fileid1(exe_name);\n EXPECT_TRUE(fileid1.ElfFileIdentifier(identifier1));\n FileID fileid2(templ);\n EXPECT_TRUE(fileid2.ElfFileIdentifier(identifier2));\n char identifier_string1[37];\n char identifier_string2[37];\n FileID::ConvertIdentifierToString(identifier1, identifier_string1,\n 37);\n FileID::ConvertIdentifierToString(identifier2, identifier_string2,\n 37);\n EXPECT_STREQ(identifier_string1, identifier_string2);\n unlink(templ);\n}\n\nstruct ElfClass32 {\n typedef Elf32_Ehdr Ehdr;\n typedef Elf32_Shdr Shdr;\n static const int kClass = ELFCLASS32;\n};\n\nstruct ElfClass64 {\n typedef Elf64_Ehdr Ehdr;\n typedef Elf64_Shdr Shdr;\n static const int kClass = ELFCLASS64;\n};\n\ntemplate\nstruct ElfishElf {\n static const size_t kTextSectionSize = 128;\n typedef typename ElfClass::Ehdr Ehdr;\n typedef typename ElfClass::Shdr Shdr;\n\n Ehdr elf_header;\n Shdr text_header;\n Shdr string_header;\n char text_section[kTextSectionSize];\n char string_section[8];\n\n static void Populate(ElfishElf* elf) {\n memset(elf, 0, sizeof(ElfishElf));\n memcpy(elf, ELFMAG, SELFMAG);\n elf->elf_header.e_ident[EI_CLASS] = ElfClass::kClass;\n elf->elf_header.e_shoff = offsetof(ElfishElf, text_header);\n elf->elf_header.e_shnum = 2;\n elf->elf_header.e_shstrndx = 1;\n elf->text_header.sh_name = 0;\n elf->text_header.sh_type = SHT_PROGBITS;\n elf->text_header.sh_offset = offsetof(ElfishElf, text_section);\n elf->text_header.sh_size = kTextSectionSize;\n for (size_t i = 0; i < kTextSectionSize; ++i) {\n elf->text_section[i] = i * 3;\n }\n elf->string_header.sh_offset = offsetof(ElfishElf, string_section);\n strcpy(elf->string_section, \".text\");\n }\n};\n\nTEST(FileIDTest, ElfClass) {\n uint8_t identifier[sizeof(MDGUID)];\n const char expected_identifier_string[] =\n \"80808080-8080-0000-0000-008080808080\";\n char identifier_string[sizeof(expected_identifier_string)];\n\n ElfishElf elf32;\n ElfishElf::Populate(&elf32);\n EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf32, identifier));\n FileID::ConvertIdentifierToString(identifier, identifier_string,\n sizeof(identifier_string));\n EXPECT_STREQ(expected_identifier_string, identifier_string);\n\n memset(identifier, 0, sizeof(identifier));\n memset(identifier_string, 0, sizeof(identifier_string));\n\n ElfishElf elf64;\n ElfishElf::Populate(&elf64);\n EXPECT_TRUE(FileID::ElfFileIdentifierFromMappedFile(&elf64, identifier));\n FileID::ConvertIdentifierToString(identifier, identifier_string,\n sizeof(identifier_string));\n EXPECT_STREQ(expected_identifier_string, identifier_string);\n}\n<|endoftext|>"} {"text":"\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2015 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \n\n#include \"xenia\/base\/assert.h\"\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/math.h\"\n\n#include \"xenia\/ui\/vulkan\/circular_buffer.h\"\n\nnamespace xe {\nnamespace ui {\nnamespace vulkan {\n\nCircularBuffer::CircularBuffer(VulkanDevice* device, VkBufferUsageFlags usage,\n VkDeviceSize capacity, VkDeviceSize alignment)\n : device_(device), capacity_(capacity) {\n VkResult status = VK_SUCCESS;\n\n \/\/ Create our internal buffer.\n VkBufferCreateInfo buffer_info;\n buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n buffer_info.pNext = nullptr;\n buffer_info.flags = 0;\n buffer_info.size = capacity;\n buffer_info.usage = usage;\n buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n buffer_info.queueFamilyIndexCount = 0;\n buffer_info.pQueueFamilyIndices = nullptr;\n status = vkCreateBuffer(*device_, &buffer_info, nullptr, &gpu_buffer_);\n CheckResult(status, \"vkCreateBuffer\");\n if (status != VK_SUCCESS) {\n assert_always();\n }\n\n VkMemoryRequirements reqs;\n vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs);\n alignment_ = reqs.alignment;\n}\nCircularBuffer::~CircularBuffer() { Shutdown(); }\n\nVkResult CircularBuffer::Initialize(VkDeviceMemory memory,\n VkDeviceSize offset) {\n assert_true(offset % alignment_ == 0);\n gpu_memory_ = memory;\n gpu_base_ = offset;\n\n VkResult status = VK_SUCCESS;\n\n \/\/ Bind the buffer to its backing memory.\n status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_);\n CheckResult(status, \"vkBindBufferMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to bind memory!\");\n Shutdown();\n return status;\n }\n\n \/\/ Map the memory so we can access it.\n status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0,\n reinterpret_cast(&host_base_));\n CheckResult(status, \"vkMapMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to map memory!\");\n Shutdown();\n return status;\n }\n\n return VK_SUCCESS;\n}\n\nVkResult CircularBuffer::Initialize() {\n VkResult status = VK_SUCCESS;\n\n VkMemoryRequirements reqs;\n vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs);\n\n \/\/ Allocate memory from the device to back the buffer.\n owns_gpu_memory_ = true;\n gpu_memory_ = device_->AllocateMemory(reqs);\n if (!gpu_memory_) {\n XELOGE(\"CircularBuffer::Initialize - Failed to allocate memory!\");\n Shutdown();\n return VK_ERROR_INITIALIZATION_FAILED;\n }\n\n capacity_ = reqs.size;\n gpu_base_ = 0;\n\n \/\/ Bind the buffer to its backing memory.\n status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_);\n CheckResult(status, \"vkBindBufferMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to bind memory!\");\n Shutdown();\n return status;\n }\n\n \/\/ Map the memory so we can access it.\n status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0,\n reinterpret_cast(&host_base_));\n CheckResult(status, \"vkMapMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to map memory!\");\n Shutdown();\n return status;\n }\n\n return VK_SUCCESS;\n}\n\nvoid CircularBuffer::Shutdown() {\n Clear();\n if (host_base_) {\n vkUnmapMemory(*device_, gpu_memory_);\n host_base_ = nullptr;\n }\n if (gpu_buffer_) {\n vkDestroyBuffer(*device_, gpu_buffer_, nullptr);\n gpu_buffer_ = nullptr;\n }\n if (gpu_memory_ && owns_gpu_memory_) {\n vkFreeMemory(*device_, gpu_memory_, nullptr);\n gpu_memory_ = nullptr;\n }\n}\n\nvoid CircularBuffer::GetBufferMemoryRequirements(VkMemoryRequirements* reqs) {\n vkGetBufferMemoryRequirements(*device_, gpu_buffer_, reqs);\n}\n\nbool CircularBuffer::CanAcquire(VkDeviceSize length) {\n \/\/ Make sure the length is aligned.\n length = xe::round_up(length, alignment_);\n if (allocations_.empty()) {\n \/\/ Read head has caught up to write head (entire buffer available for write)\n assert_true(read_head_ == write_head_);\n return capacity_ >= length;\n } else if (write_head_ < read_head_) {\n \/\/ Write head wrapped around and is behind read head.\n \/\/ | write |---- read ----|\n return (read_head_ - write_head_) >= length;\n } else if (write_head_ > read_head_) {\n \/\/ Read head behind write head.\n \/\/ 1. Check if there's enough room from write -> capacity\n \/\/ | |---- read ----| write |\n if ((capacity_ - write_head_) >= length) {\n return true;\n }\n\n \/\/ 2. Check if there's enough room from 0 -> read\n \/\/ | write |---- read ----| |\n if ((read_head_ - 0) >= length) {\n return true;\n }\n }\n\n return false;\n}\n\nCircularBuffer::Allocation* CircularBuffer::Acquire(VkDeviceSize length,\n VkFence fence) {\n VkDeviceSize aligned_length = xe::round_up(length, alignment_);\n if (!CanAcquire(aligned_length)) {\n return nullptr;\n }\n\n assert_true(write_head_ % alignment_ == 0);\n if (write_head_ < read_head_) {\n \/\/ Write head behind read head.\n assert_true(read_head_ - write_head_ >= aligned_length);\n\n auto alloc = new Allocation();\n alloc->host_ptr = host_base_ + write_head_;\n alloc->gpu_memory = gpu_memory_;\n alloc->offset = gpu_base_ + write_head_;\n alloc->length = length;\n alloc->aligned_length = aligned_length;\n alloc->fence = fence;\n write_head_ += aligned_length;\n allocations_.push_back(alloc);\n\n return alloc;\n } else {\n \/\/ Write head equal to\/after read head\n if (capacity_ - write_head_ >= aligned_length) {\n \/\/ Free space from write -> capacity\n auto alloc = new Allocation();\n alloc->host_ptr = host_base_ + write_head_;\n alloc->gpu_memory = gpu_memory_;\n alloc->offset = gpu_base_ + write_head_;\n alloc->length = length;\n alloc->aligned_length = aligned_length;\n alloc->fence = fence;\n write_head_ += aligned_length;\n allocations_.push_back(alloc);\n\n return alloc;\n } else if ((read_head_ - 0) >= aligned_length) {\n \/\/ Not enough space from write -> capacity, but there is enough free space\n \/\/ from begin -> read\n auto alloc = new Allocation();\n alloc->host_ptr = host_base_ + 0;\n alloc->gpu_memory = gpu_memory_;\n alloc->offset = gpu_base_ + 0;\n alloc->length = length;\n alloc->aligned_length = aligned_length;\n alloc->fence = fence;\n write_head_ = aligned_length;\n allocations_.push_back(alloc);\n\n return alloc;\n }\n }\n\n return nullptr;\n}\n\nvoid CircularBuffer::Flush(Allocation* allocation) {\n VkMappedMemoryRange range;\n range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;\n range.pNext = nullptr;\n range.memory = gpu_memory_;\n range.offset = gpu_base_ + allocation->offset;\n range.size = allocation->length;\n vkFlushMappedMemoryRanges(*device_, 1, &range);\n}\n\nvoid CircularBuffer::Flush(VkDeviceSize offset, VkDeviceSize length) {\n VkMappedMemoryRange range;\n range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;\n range.pNext = nullptr;\n range.memory = gpu_memory_;\n range.offset = gpu_base_ + offset;\n range.size = length;\n vkFlushMappedMemoryRanges(*device_, 1, &range);\n}\n\nvoid CircularBuffer::Clear() {\n for (auto alloc : allocations_) {\n delete alloc;\n }\n allocations_.clear();\n\n write_head_ = read_head_ = 0;\n}\n\nvoid CircularBuffer::Scavenge() {\n for (auto it = allocations_.begin(); it != allocations_.end();) {\n if (vkGetFenceStatus(*device_, (*it)->fence) != VK_SUCCESS) {\n \/\/ Don't bother freeing following allocations to ensure proper ordering.\n break;\n }\n\n if (capacity_ - read_head_ < (*it)->aligned_length) {\n \/\/ This allocation is stored at the beginning of the buffer.\n read_head_ = (*it)->aligned_length;\n } else {\n read_head_ += (*it)->aligned_length;\n }\n\n delete *it;\n it = allocations_.erase(it);\n }\n\n if (allocations_.empty()) {\n \/\/ Reset R\/W heads to work around fragmentation issues.\n read_head_ = write_head_ = 0;\n }\n}\n\n} \/\/ namespace vulkan\n} \/\/ namespace ui\n} \/\/ namespace xe[Vulkan UI] CircularBuffer: Actually use provided alignment\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2015 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \n\n#include \"xenia\/base\/assert.h\"\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/math.h\"\n\n#include \"xenia\/ui\/vulkan\/circular_buffer.h\"\n\nnamespace xe {\nnamespace ui {\nnamespace vulkan {\n\nCircularBuffer::CircularBuffer(VulkanDevice* device, VkBufferUsageFlags usage,\n VkDeviceSize capacity, VkDeviceSize alignment)\n : device_(device), capacity_(capacity) {\n VkResult status = VK_SUCCESS;\n\n \/\/ Create our internal buffer.\n VkBufferCreateInfo buffer_info;\n buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;\n buffer_info.pNext = nullptr;\n buffer_info.flags = 0;\n buffer_info.size = capacity;\n buffer_info.usage = usage;\n buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;\n buffer_info.queueFamilyIndexCount = 0;\n buffer_info.pQueueFamilyIndices = nullptr;\n status = vkCreateBuffer(*device_, &buffer_info, nullptr, &gpu_buffer_);\n CheckResult(status, \"vkCreateBuffer\");\n if (status != VK_SUCCESS) {\n assert_always();\n }\n\n VkMemoryRequirements reqs;\n vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs);\n alignment_ = xe::round_up(alignment, reqs.alignment);\n}\nCircularBuffer::~CircularBuffer() { Shutdown(); }\n\nVkResult CircularBuffer::Initialize(VkDeviceMemory memory,\n VkDeviceSize offset) {\n assert_true(offset % alignment_ == 0);\n gpu_memory_ = memory;\n gpu_base_ = offset;\n\n VkResult status = VK_SUCCESS;\n\n \/\/ Bind the buffer to its backing memory.\n status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_);\n CheckResult(status, \"vkBindBufferMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to bind memory!\");\n Shutdown();\n return status;\n }\n\n \/\/ Map the memory so we can access it.\n status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0,\n reinterpret_cast(&host_base_));\n CheckResult(status, \"vkMapMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to map memory!\");\n Shutdown();\n return status;\n }\n\n return VK_SUCCESS;\n}\n\nVkResult CircularBuffer::Initialize() {\n VkResult status = VK_SUCCESS;\n\n VkMemoryRequirements reqs;\n vkGetBufferMemoryRequirements(*device_, gpu_buffer_, &reqs);\n\n \/\/ Allocate memory from the device to back the buffer.\n owns_gpu_memory_ = true;\n gpu_memory_ = device_->AllocateMemory(reqs);\n if (!gpu_memory_) {\n XELOGE(\"CircularBuffer::Initialize - Failed to allocate memory!\");\n Shutdown();\n return VK_ERROR_INITIALIZATION_FAILED;\n }\n\n capacity_ = reqs.size;\n gpu_base_ = 0;\n\n \/\/ Bind the buffer to its backing memory.\n status = vkBindBufferMemory(*device_, gpu_buffer_, gpu_memory_, gpu_base_);\n CheckResult(status, \"vkBindBufferMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to bind memory!\");\n Shutdown();\n return status;\n }\n\n \/\/ Map the memory so we can access it.\n status = vkMapMemory(*device_, gpu_memory_, gpu_base_, capacity_, 0,\n reinterpret_cast(&host_base_));\n CheckResult(status, \"vkMapMemory\");\n if (status != VK_SUCCESS) {\n XELOGE(\"CircularBuffer::Initialize - Failed to map memory!\");\n Shutdown();\n return status;\n }\n\n return VK_SUCCESS;\n}\n\nvoid CircularBuffer::Shutdown() {\n Clear();\n if (host_base_) {\n vkUnmapMemory(*device_, gpu_memory_);\n host_base_ = nullptr;\n }\n if (gpu_buffer_) {\n vkDestroyBuffer(*device_, gpu_buffer_, nullptr);\n gpu_buffer_ = nullptr;\n }\n if (gpu_memory_ && owns_gpu_memory_) {\n vkFreeMemory(*device_, gpu_memory_, nullptr);\n gpu_memory_ = nullptr;\n }\n}\n\nvoid CircularBuffer::GetBufferMemoryRequirements(VkMemoryRequirements* reqs) {\n vkGetBufferMemoryRequirements(*device_, gpu_buffer_, reqs);\n}\n\nbool CircularBuffer::CanAcquire(VkDeviceSize length) {\n \/\/ Make sure the length is aligned.\n length = xe::round_up(length, alignment_);\n if (allocations_.empty()) {\n \/\/ Read head has caught up to write head (entire buffer available for write)\n assert_true(read_head_ == write_head_);\n return capacity_ >= length;\n } else if (write_head_ < read_head_) {\n \/\/ Write head wrapped around and is behind read head.\n \/\/ | write |---- read ----|\n return (read_head_ - write_head_) >= length;\n } else if (write_head_ > read_head_) {\n \/\/ Read head behind write head.\n \/\/ 1. Check if there's enough room from write -> capacity\n \/\/ | |---- read ----| write |\n if ((capacity_ - write_head_) >= length) {\n return true;\n }\n\n \/\/ 2. Check if there's enough room from 0 -> read\n \/\/ | write |---- read ----| |\n if ((read_head_ - 0) >= length) {\n return true;\n }\n }\n\n return false;\n}\n\nCircularBuffer::Allocation* CircularBuffer::Acquire(VkDeviceSize length,\n VkFence fence) {\n VkDeviceSize aligned_length = xe::round_up(length, alignment_);\n if (!CanAcquire(aligned_length)) {\n return nullptr;\n }\n\n assert_true(write_head_ % alignment_ == 0);\n if (write_head_ < read_head_) {\n \/\/ Write head behind read head.\n assert_true(read_head_ - write_head_ >= aligned_length);\n\n auto alloc = new Allocation();\n alloc->host_ptr = host_base_ + write_head_;\n alloc->gpu_memory = gpu_memory_;\n alloc->offset = gpu_base_ + write_head_;\n alloc->length = length;\n alloc->aligned_length = aligned_length;\n alloc->fence = fence;\n write_head_ += aligned_length;\n allocations_.push_back(alloc);\n\n return alloc;\n } else {\n \/\/ Write head equal to\/after read head\n if (capacity_ - write_head_ >= aligned_length) {\n \/\/ Free space from write -> capacity\n auto alloc = new Allocation();\n alloc->host_ptr = host_base_ + write_head_;\n alloc->gpu_memory = gpu_memory_;\n alloc->offset = gpu_base_ + write_head_;\n alloc->length = length;\n alloc->aligned_length = aligned_length;\n alloc->fence = fence;\n write_head_ += aligned_length;\n allocations_.push_back(alloc);\n\n return alloc;\n } else if ((read_head_ - 0) >= aligned_length) {\n \/\/ Not enough space from write -> capacity, but there is enough free space\n \/\/ from begin -> read\n auto alloc = new Allocation();\n alloc->host_ptr = host_base_ + 0;\n alloc->gpu_memory = gpu_memory_;\n alloc->offset = gpu_base_ + 0;\n alloc->length = length;\n alloc->aligned_length = aligned_length;\n alloc->fence = fence;\n write_head_ = aligned_length;\n allocations_.push_back(alloc);\n\n return alloc;\n }\n }\n\n return nullptr;\n}\n\nvoid CircularBuffer::Flush(Allocation* allocation) {\n VkMappedMemoryRange range;\n range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;\n range.pNext = nullptr;\n range.memory = gpu_memory_;\n range.offset = gpu_base_ + allocation->offset;\n range.size = allocation->length;\n vkFlushMappedMemoryRanges(*device_, 1, &range);\n}\n\nvoid CircularBuffer::Flush(VkDeviceSize offset, VkDeviceSize length) {\n VkMappedMemoryRange range;\n range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE;\n range.pNext = nullptr;\n range.memory = gpu_memory_;\n range.offset = gpu_base_ + offset;\n range.size = length;\n vkFlushMappedMemoryRanges(*device_, 1, &range);\n}\n\nvoid CircularBuffer::Clear() {\n for (auto alloc : allocations_) {\n delete alloc;\n }\n allocations_.clear();\n\n write_head_ = read_head_ = 0;\n}\n\nvoid CircularBuffer::Scavenge() {\n for (auto it = allocations_.begin(); it != allocations_.end();) {\n if (vkGetFenceStatus(*device_, (*it)->fence) != VK_SUCCESS) {\n \/\/ Don't bother freeing following allocations to ensure proper ordering.\n break;\n }\n\n if (capacity_ - read_head_ < (*it)->aligned_length) {\n \/\/ This allocation is stored at the beginning of the buffer.\n read_head_ = (*it)->aligned_length;\n } else {\n read_head_ += (*it)->aligned_length;\n }\n\n delete *it;\n it = allocations_.erase(it);\n }\n\n if (allocations_.empty()) {\n \/\/ Reset R\/W heads to work around fragmentation issues.\n read_head_ = write_head_ = 0;\n }\n}\n\n} \/\/ namespace vulkan\n} \/\/ namespace ui\n} \/\/ namespace xe<|endoftext|>"} {"text":"\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"stdafx.h\"\n\n#include \"zorbatypes\/decimal.h\"\n#include \"zorbatypes\/float.h\"\n#include \"zorbatypes\/integer.h\"\n#include \"zorbatypes\/numconversions.h\"\n\n#include \"compiler\/parser\/symbol_table.h\"\n\n#include \"util\/ascii_util.h\"\n#include \"util\/xml_util.h\"\n#include \"util\/uri_util.h\"\n#include \"util\/utf8_util.h\"\n\n#include \"compiler\/parser\/xquery_driver.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace zorba {\n\n\nstatic bool decode_string(const char *yytext, size_t yyleng, string *result) {\n char delim = yytext [0];\n size_t i;\n for (i = 1; i + 1 < yyleng; i++) {\n char ch = yytext [i];\n if (ch == '&') {\n int d = xml::parse_entity(yytext + i + 1, result);\n if (d < 0) return false;\n i += d;\n } else {\n *result += ch;\n if (ch == delim) ++i;\n }\n }\n return true;\n}\n\nsymbol_table::symbol_table(size_t initial_heapsize)\n :\n heap(initial_heapsize),\n last_qname(-1)\n{\n}\n\nsymbol_table::~symbol_table()\n{\n}\n\nsize_t symbol_table::size() const\n{\n return (size_t)heap.size();\n}\n\n\/\/ bool attribute == true when an attribute value is normalized\nstatic void normalize_eol(const char *text, size_t length, string *out, bool attribute = false) {\n size_t i;\n out->reserve (length + 1);\n char lastCh = '\\0';\n for (i = 0; i < length; i++) {\n char ch = text [i];\n if (ch == '\\r')\n *out += attribute ? ' ' : '\\n';\n else if (ch != '\\n' || lastCh != '\\r')\n *out += (attribute && (ch == '\\t' || ch == '\\n'))? ' ' : ch;\n\n lastCh = ch;\n }\n}\n\noff_t symbol_table::put(char const* text)\n{\n return put(text, strlen(text));\n}\n\n\/\/ normalizationType == 2 is used for normalizing attribute values\noff_t symbol_table::put(char const* text, size_t length, int normalizationType)\n{\n string normStr;\n if (normalizationType == 1 || normalizationType == 2)\n {\n normalize_eol (text, length, &normStr, normalizationType == 2);\n text = normStr.c_str ();\n length = normStr.size ();\n }\n\n return heap.put(text, 0, length);\n}\n\noff_t symbol_table::put_ncname(char const* text, size_t length)\n{\n last_qname = heap.put(text, 0, length);\n return last_qname;\n}\n\noff_t symbol_table::put_qname(char const* text, size_t length, bool do_trim_start, bool do_trim_end, bool is_eqname)\n{\n if (do_trim_start)\n {\n text = ascii::trim_start_space(text, &length);\n }\n\n if (do_trim_end)\n {\n length = ascii::trim_end_space(text, length);\n }\n\n if (!is_eqname)\n {\n last_qname = heap.put(text, 0, length);\n }\n else\n {\n \/\/ EQName: Q{prefix}name\n string name;\n string prefix = text;\n string::size_type pos = prefix.rfind('}');\n name = prefix.substr(pos+1);\n prefix = prefix.substr(1, pos);\n\n off_t uri = put_uri(prefix.c_str(), prefix.size());\n name = get(uri) + \":\" + name;\n\n last_qname = heap.put(name.c_str(), 0, name.size());\n }\n \n return last_qname;\n}\n\noff_t symbol_table::put_uri(char const* text, size_t length)\n{\n \/\/ trim whitespace\n text = ascii::trim_space(text, &length);\n\n \/\/ normalize whitespace\n string result;\n if (! decode_string (text, length, &result))\n return -1;\n ascii::normalize_space( result );\n\n return heap.put (result.c_str (), 0, result.length ());\n}\n\noff_t symbol_table::put_varname(char const* text, size_t length)\n{\n return heap.put(text, 0, length);\n}\n\noff_t symbol_table::put_entityref(char const* text, size_t length)\n{\n string result;\n if (xml::parse_entity (text + 1, &result) < 0)\n return -1;\n return heap.put(result.c_str(), 0, result.size ());\n}\n\noff_t symbol_table::put_charref(char const* text, size_t length)\n{\n return heap.put (text + 1, 0, length - 1);\n}\n\noff_t symbol_table::put_stringlit(char const* yytext, size_t yyleng)\n{\n string eolNorm;\n normalize_eol (yytext, yyleng, &eolNorm);\n yytext = eolNorm.c_str ();\n yyleng = eolNorm.size ();\n string result;\n if (! decode_string (yytext, yyleng, &result))\n return -1;\n return heap.put (result.c_str (), 0, result.length ());\n}\n\noff_t symbol_table::put_json_stringliteral(char const* yytext, size_t yyleng, xquery_driver *driver, const location &loc)\n{\n string result;\n unsigned int cp;\n size_t len;\n bool found_escape = false;\n bool found_ampersand = false;\n\n for (const char* chr = yytext+1; (unsigned int)(chr-yytext)commonLanguageEnabled())\n driver->addCommonLanguageWarning(loc, ZED(ZWST0009_JSON_ESCAPE));\n \n if (found_ampersand && driver->commonLanguageEnabled())\n driver->addCommonLanguageWarning(loc, ZED(ZWST0009_CHAR_REF));\n \n return heap.put (result.c_str (), 0, result.length ());\n}\n\noff_t symbol_table::put_commentcontent(char const* yytext, size_t yyleng)\n{\n string eolNorm;\n normalize_eol (yytext, yyleng, &eolNorm);\n yytext = eolNorm.c_str (); yyleng = eolNorm.size ();\n return heap.put (yytext, 0, yyleng);\n}\n\nxs_decimal* symbol_table::decimalval(char const* text, size_t length)\n{\n return new xs_decimal(text);\n}\n\nxs_double* symbol_table::doubleval(char const* text, size_t length)\n{\n try {\n return new xs_double(text);\n }\n catch ( std::range_error const& ) {\n return NULL;\n }\n}\n\nxs_integer* symbol_table::integerval(char const* text, size_t length)\n{\n try {\n return new xs_integer(text);\n }\n catch ( std::invalid_argument const& ) {\n return NULL;\n }\n}\n\nstd::string symbol_table::get(off_t id)\n{\n size_t n = heap.get_length0(id); \n char *buf;\n buf = (char*)malloc(n+1);\n heap.get0(id, buf, 0, n+1);\n std::string retstr = string(buf, 0, n);\n free(buf);\n return retstr;\n}\n\nstd::string symbol_table::get_last_qname()\n{\n return get(last_qname);\n}\n\n}\t\/* namespace zorba *\/\n\/* vim:set et sw=2 ts=2: *\/\nFixed exception catching.\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \"stdafx.h\"\n\n#include \"zorbatypes\/decimal.h\"\n#include \"zorbatypes\/float.h\"\n#include \"zorbatypes\/integer.h\"\n#include \"zorbatypes\/numconversions.h\"\n\n#include \"compiler\/parser\/symbol_table.h\"\n\n#include \"util\/ascii_util.h\"\n#include \"util\/xml_util.h\"\n#include \"util\/uri_util.h\"\n#include \"util\/utf8_util.h\"\n\n#include \"compiler\/parser\/xquery_driver.h\"\n\n#include \n#include \n\nusing namespace std;\n\nnamespace zorba {\n\n\nstatic bool decode_string(const char *yytext, size_t yyleng, string *result) {\n char delim = yytext [0];\n size_t i;\n for (i = 1; i + 1 < yyleng; i++) {\n char ch = yytext [i];\n if (ch == '&') {\n int d = xml::parse_entity(yytext + i + 1, result);\n if (d < 0) return false;\n i += d;\n } else {\n *result += ch;\n if (ch == delim) ++i;\n }\n }\n return true;\n}\n\nsymbol_table::symbol_table(size_t initial_heapsize)\n :\n heap(initial_heapsize),\n last_qname(-1)\n{\n}\n\nsymbol_table::~symbol_table()\n{\n}\n\nsize_t symbol_table::size() const\n{\n return (size_t)heap.size();\n}\n\n\/\/ bool attribute == true when an attribute value is normalized\nstatic void normalize_eol(const char *text, size_t length, string *out, bool attribute = false) {\n size_t i;\n out->reserve (length + 1);\n char lastCh = '\\0';\n for (i = 0; i < length; i++) {\n char ch = text [i];\n if (ch == '\\r')\n *out += attribute ? ' ' : '\\n';\n else if (ch != '\\n' || lastCh != '\\r')\n *out += (attribute && (ch == '\\t' || ch == '\\n'))? ' ' : ch;\n\n lastCh = ch;\n }\n}\n\noff_t symbol_table::put(char const* text)\n{\n return put(text, strlen(text));\n}\n\n\/\/ normalizationType == 2 is used for normalizing attribute values\noff_t symbol_table::put(char const* text, size_t length, int normalizationType)\n{\n string normStr;\n if (normalizationType == 1 || normalizationType == 2)\n {\n normalize_eol (text, length, &normStr, normalizationType == 2);\n text = normStr.c_str ();\n length = normStr.size ();\n }\n\n return heap.put(text, 0, length);\n}\n\noff_t symbol_table::put_ncname(char const* text, size_t length)\n{\n last_qname = heap.put(text, 0, length);\n return last_qname;\n}\n\noff_t symbol_table::put_qname(char const* text, size_t length, bool do_trim_start, bool do_trim_end, bool is_eqname)\n{\n if (do_trim_start)\n {\n text = ascii::trim_start_space(text, &length);\n }\n\n if (do_trim_end)\n {\n length = ascii::trim_end_space(text, length);\n }\n\n if (!is_eqname)\n {\n last_qname = heap.put(text, 0, length);\n }\n else\n {\n \/\/ EQName: Q{prefix}name\n string name;\n string prefix = text;\n string::size_type pos = prefix.rfind('}');\n name = prefix.substr(pos+1);\n prefix = prefix.substr(1, pos);\n\n off_t uri = put_uri(prefix.c_str(), prefix.size());\n name = get(uri) + \":\" + name;\n\n last_qname = heap.put(name.c_str(), 0, name.size());\n }\n \n return last_qname;\n}\n\noff_t symbol_table::put_uri(char const* text, size_t length)\n{\n \/\/ trim whitespace\n text = ascii::trim_space(text, &length);\n\n \/\/ normalize whitespace\n string result;\n if (! decode_string (text, length, &result))\n return -1;\n ascii::normalize_space( result );\n\n return heap.put (result.c_str (), 0, result.length ());\n}\n\noff_t symbol_table::put_varname(char const* text, size_t length)\n{\n return heap.put(text, 0, length);\n}\n\noff_t symbol_table::put_entityref(char const* text, size_t length)\n{\n string result;\n if (xml::parse_entity (text + 1, &result) < 0)\n return -1;\n return heap.put(result.c_str(), 0, result.size ());\n}\n\noff_t symbol_table::put_charref(char const* text, size_t length)\n{\n return heap.put (text + 1, 0, length - 1);\n}\n\noff_t symbol_table::put_stringlit(char const* yytext, size_t yyleng)\n{\n string eolNorm;\n normalize_eol (yytext, yyleng, &eolNorm);\n yytext = eolNorm.c_str ();\n yyleng = eolNorm.size ();\n string result;\n if (! decode_string (yytext, yyleng, &result))\n return -1;\n return heap.put (result.c_str (), 0, result.length ());\n}\n\noff_t symbol_table::put_json_stringliteral(char const* yytext, size_t yyleng, xquery_driver *driver, const location &loc)\n{\n string result;\n unsigned int cp;\n size_t len;\n bool found_escape = false;\n bool found_ampersand = false;\n\n for (const char* chr = yytext+1; (unsigned int)(chr-yytext)commonLanguageEnabled())\n driver->addCommonLanguageWarning(loc, ZED(ZWST0009_JSON_ESCAPE));\n \n if (found_ampersand && driver->commonLanguageEnabled())\n driver->addCommonLanguageWarning(loc, ZED(ZWST0009_CHAR_REF));\n \n return heap.put (result.c_str (), 0, result.length ());\n}\n\noff_t symbol_table::put_commentcontent(char const* yytext, size_t yyleng)\n{\n string eolNorm;\n normalize_eol (yytext, yyleng, &eolNorm);\n yytext = eolNorm.c_str (); yyleng = eolNorm.size ();\n return heap.put (yytext, 0, yyleng);\n}\n\nxs_decimal* symbol_table::decimalval(char const* text, size_t length)\n{\n return new xs_decimal(text);\n}\n\nxs_double* symbol_table::doubleval(char const* text, size_t length)\n{\n try {\n return new xs_double(text);\n }\n catch ( std::exception const& ) {\n return NULL;\n }\n}\n\nxs_integer* symbol_table::integerval(char const* text, size_t length)\n{\n try {\n return new xs_integer(text);\n }\n catch ( std::exception const& ) {\n return NULL;\n }\n}\n\nstd::string symbol_table::get(off_t id)\n{\n size_t n = heap.get_length0(id); \n char *buf;\n buf = (char*)malloc(n+1);\n heap.get0(id, buf, 0, n+1);\n std::string retstr = string(buf, 0, n);\n free(buf);\n return retstr;\n}\n\nstd::string symbol_table::get_last_qname()\n{\n return get(last_qname);\n}\n\n}\t\/* namespace zorba *\/\n\/* vim:set et sw=2 ts=2: *\/\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\/*\n * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others.\n *\/\n\nclass SSHConnection {\n\tstruct SSHChannel {\n\t\tuint32_t local_channel_;\n\t\tuint32_t local_window_size_;\n\t\tuint32_t local_packet_size_;\n\t\tuint32_t remote_channel_;\n\t\tuint32_t remote_window_size_;\n\t\tuint32_t remote_packet_size_;\n\n\t\tstd::map environment_;\n\n\t\tSSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size)\n\t\t: local_channel_(local_channel),\n\t\t local_window_size_(local_window_size),\n\t\t local_packet_size_(local_packet_size),\n\t\t remote_channel_(remote_channel),\n\t\t remote_window_size_(remote_window_size),\n\t\t remote_packet_size_(remote_packet_size),\n\t\t environment_()\n\t\t{ }\n\t};\n\n\tLogHandle log_;\n\tSocket *peer_;\n\tSSH::Session session_;\n\tSSH::TransportPipe *pipe_;\n\tAction *receive_action_;\n\tSplice *splice_;\n\tAction *splice_action_;\n\tAction *close_action_;\n\tuint32_t channel_next_;\n\tstd::map channel_map_;\n\tstd::map remote_channel_map_;\npublic:\n\tSSHConnection(Socket *peer)\n\t: log_(\"\/ssh\/connection\"),\n\t peer_(peer),\n\t session_(SSH::ServerRole),\n\t pipe_(NULL),\n\t splice_(NULL),\n\t splice_action_(NULL),\n\t close_action_(NULL),\n\t channel_next_(0),\n\t channel_map_()\n\t{\n\t\tsession_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_);\n\t\tif (session_.role_ == SSH::ServerRole) {\n\t\t\tSSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, \"ssh-server1.pem\");\n\t\t\tsession_.algorithm_negotiation_->add_algorithm(server_host_key);\n\t\t}\n\t\tsession_.algorithm_negotiation_->add_algorithms();\n\n\t\tpipe_ = new SSH::TransportPipe(&session_);\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\n\t\tsplice_ = new Splice(log_ + \"\/splice\", peer_, pipe_, peer_);\n\t\tEventCallback *cb = callback(this, &SSHConnection::splice_complete);\n\t\tsplice_action_ = splice_->start(cb);\n\t}\n\n\t~SSHConnection()\n\t{\n\t\tASSERT(log_, close_action_ == NULL);\n\t\tASSERT(log_, splice_action_ == NULL);\n\t\tASSERT(log_, splice_ == NULL);\n\t\tASSERT(log_, receive_action_ == NULL);\n\t\tASSERT(log_, pipe_ == NULL);\n\t\tASSERT(log_, peer_ == NULL);\n\t}\n\nprivate:\n\tvoid receive_complete(Event e)\n\t{\n\t\treceive_action_->cancel();\n\t\treceive_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::Done:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Unexpected event while waiting for a packet: \" << e;\n\t\t\treturn;\n\t\t}\n\n\t\tASSERT(log_, !e.buffer_.empty());\n\n\t\tBuffer service;\n\t\tBuffer type;\n\t\tBuffer msg;\n\t\tSSHChannel *channel;\n\t\tuint32_t recipient_channel, sender_channel, window_size, packet_size;\n\t\tbool want_reply;\n\t\tstd::map::const_iterator rchit;\n\t\tstd::map::const_iterator chit;\n\t\tswitch (e.buffer_.peek()) {\n\t\tcase SSH::Message::TransportDisconnectMessage:\n\t\t\tbreak;\n\t\tcase SSH::Message::TransportServiceRequestMessage:\n\t\t\t\/* Claim to support any kind of service the client requests. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"No service name after transport request.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::String::decode(&service, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode service name.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"Extraneous data after service name.\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmsg.append(SSH::Message::TransportServiceAcceptMessage);\n\t\t\tSSH::String::encode(&msg, service);\n\t\t\tpipe_->send(&msg);\n\n\t\t\tif (service.equal(\"ssh-userauth\")) {\n\t\t\t\tmsg.append(SSH::Message::UserAuthenticationBannerMessage);\n\t\t\t\tSSH::String::encode(&msg, std::string(\" *\\r\\n\\007 * This is a test server. Sessions, including authentication, may be logged.\\r\\n *\\r\\n\"));\n\t\t\t\tSSH::String::encode(&msg, std::string(\"en-CA\"));\n\t\t\t\tpipe_->send(&msg);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH::Message::UserAuthenticationRequestMessage:\n\t\t\t\/* Any authentication request succeeds. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tmsg.append(SSH::Message::UserAuthenticationSuccessMessage);\n\t\t\tpipe_->send(&msg);\n\t\t\tbreak;\n\t\tcase SSH::Message::ConnectionChannelOpen:\n\t\t\t\/* Opening a channel. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"No channel type after channel open.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::String::decode(&type, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode channel type.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode sender channel.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&window_size, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode window size.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&packet_size, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode packet size.\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/* Only support session channels. *\/\n\t\t\tif (!type.equal(\"session\")) {\n\t\t\t\tmsg.append(SSH::Message::ConnectionChannelOpenFailure);\n\t\t\t\tSSH::UInt32::encode(&msg, sender_channel);\n\t\t\t\tSSH::UInt32::encode(&msg, 3);\n\t\t\t\tSSH::String::encode(&msg, std::string(\"Unsupported session type.\"));\n\t\t\t\tSSH::String::encode(&msg, std::string(\"en-CA\"));\n\t\t\t\tpipe_->send(&msg);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\trecipient_channel = sender_channel;\n\t\t\tsender_channel = channel_setup(recipient_channel, window_size, packet_size);\n\n\t\t\t\/* Set up session. *\/\n\t\t\tmsg.append(SSH::Message::ConnectionChannelOpenConfirmation);\n\t\t\tSSH::UInt32::encode(&msg, recipient_channel);\n\t\t\tSSH::UInt32::encode(&msg, sender_channel);\n\t\t\tSSH::UInt32::encode(&msg, window_size);\n\t\t\tSSH::UInt32::encode(&msg, packet_size);\n\t\t\tpipe_->send(&msg);\n\t\t\tbreak;\n\t\tcase SSH::Message::ConnectionChannelRequest:\n\t\t\t\/* For now just fail any channel request. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"No channel after channel request.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode recipient channel.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::String::decode(&type, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode channel request type.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"Missing want_reply field.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\twant_reply = e.buffer_.pop();\n\n\t\t\tchit = channel_map_.find(recipient_channel);\n\t\t\tif (chit == channel_map_.end()) {\n\t\t\t\tif (want_reply) {\n\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestFailure);\n\t\t\t\t\tSSH::UInt32::encode(&msg, 0); \/* XXX What to do for a request that fails due to unknown channel? *\/\n\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tchannel = chit->second;\n\n\t\t\tif (type.equal(\"pty-req\")) {\n\t\t\t\t\/* Fail for now. *\/\n\t\t\t} else if (type.equal(\"env\")) {\n\t\t\t\tBuffer keybuf;\n\t\t\t\tif (!SSH::String::decode(&keybuf, &e.buffer_)) {\n\t\t\t\t\tERROR(log_) << \"Could not decode environment key.\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tBuffer value;\n\t\t\t\tif (!SSH::String::decode(&value, &e.buffer_)) {\n\t\t\t\t\tERROR(log_) << \"Could not decode environment value.\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstd::string key;\n\t\t\t\tkeybuf.extract(key);\n\n\t\t\t\tif (channel->environment_.find(key) == channel->environment_.end()) {\n\t\t\t\t\tchannel->environment_[key] = value;\n\n\t\t\t\t\tDEBUG(log_) << \"Client set environment variable.\";\n\t\t\t\t\tif (want_reply) {\n\t\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestSuccess);\n\t\t\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tINFO(log_) << \"Client attempted to set environment variable twice.\";\n\t\t\t\tif (want_reply) {\n\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestFailure);\n\t\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else if (type.equal(\"shell\")) {\n\t\t\t\tif (want_reply) {\n\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestSuccess);\n\t\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else {\n\t\t\t\tDEBUG(log_) << \"Unhandled channel request type:\" << std::endl << type.hexdump();\n\t\t\t}\n\n\t\t\tif (want_reply) {\n\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestFailure);\n\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\tpipe_->send(&msg);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH::Message::ConnectionChannelWindowAdjust:\n\t\t\t\/* Follow our peer's lead on window adjustments. *\/\n\t\tcase SSH::Message::ConnectionChannelData:\n\t\t\t\/* Just echo data back. We do not need to decode at present because channels are the same in both directions. *\/\n\t\t\tpipe_->send(&e.buffer_);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDEBUG(log_) << \"Unhandled message:\" << std::endl << e.buffer_.hexdump();\n\t\t\tbreak;\n\t\t}\n\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\t}\n\n\tvoid close_complete(void)\n\t{\n\t\tclose_action_->cancel();\n\t\tclose_action_ = NULL;\n\n\t\tASSERT(log_, peer_ != NULL);\n\t\tdelete peer_;\n\t\tpeer_ = NULL;\n\n\t\tdelete this;\n\t}\n\n\tvoid splice_complete(Event e)\n\t{\n\t\tsplice_action_->cancel();\n\t\tsplice_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::EOS:\n\t\t\tDEBUG(log_) << \"Peer exiting normally.\";\n\t\t\tbreak;\n\t\tcase Event::Error:\n\t\t\tERROR(log_) << \"Peer exiting with error: \" << e;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Peer exiting with unknown event: \" << e;\n\t\t\tbreak;\n\t\t}\n\n\t ASSERT(log_, splice_ != NULL);\n\t\tdelete splice_;\n\t\tsplice_ = NULL;\n\n\t\tif (receive_action_ != NULL) {\n\t\t\tINFO(log_) << \"Peer exiting while waiting for a packet.\";\n\n\t\t\treceive_action_->cancel();\n\t\t\treceive_action_ = NULL;\n\t\t}\n\n\t\tASSERT(log_, pipe_ != NULL);\n\t\tdelete pipe_;\n\t\tpipe_ = NULL;\n\n\t\tASSERT(log_, close_action_ == NULL);\n\t\tSimpleCallback *cb = callback(this, &SSHConnection::close_complete);\n\t\tclose_action_ = peer_->close(cb);\n\t}\n\n\tuint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size)\n\t{\n\t\tstd::map::const_iterator it;\n\t\tuint32_t local_channel;\n\n\t\tuint32_t next = channel_next_;\n\t\tfor (;;) {\n\t\t\tit = channel_map_.find(next);\n\t\t\tif (it == channel_map_.end())\n\t\t\t\tbreak;\n\t\t\tnext++;\n\t\t}\n\t\tchannel_next_ = next + 1;\n\n\t\tlocal_channel = next;\n\t\tchannel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size);\n\t\treturn (local_channel);\n\t}\n};\n\nclass SSHServer : public SimpleServer {\npublic:\n\tSSHServer(SocketAddressFamily family, const std::string& interface)\n\t: SimpleServer(\"\/ssh\/server\", family, interface)\n\t{ }\n\n\t~SSHServer()\n\t{ }\n\n\tvoid client_connected(Socket *client)\n\t{\n\t\tnew SSHConnection(client);\n\t}\n};\n\n\nint\nmain(void)\n{\n\tnew SSHServer(SocketAddressFamilyIP, \"[::]:2299\");\n\tevent_main();\n}\nEnforce the provision that says that only a single resource may be connected to a session channel.#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n\/*\n * XXX Create an SSH chat program. Let only one of each user be connected at a time. Send lines of data to all others.\n *\/\n\nclass SSHConnection {\n\tstruct SSHChannel {\n\t\tenum Mode {\n\t\t\tSetupMode,\n\t\t\tShellMode,\n\t\t\tExecMode,\n\t\t\tSubsystemMode\n\t\t};\n\n\t\tMode mode_;\n\n\t\tuint32_t local_channel_;\n\t\tuint32_t local_window_size_;\n\t\tuint32_t local_packet_size_;\n\t\tuint32_t remote_channel_;\n\t\tuint32_t remote_window_size_;\n\t\tuint32_t remote_packet_size_;\n\n\t\tstd::map environment_;\n\n\t\tSSHChannel(uint32_t local_channel, uint32_t remote_channel, uint32_t local_window_size, uint32_t local_packet_size, uint32_t remote_window_size, uint32_t remote_packet_size)\n\t\t: mode_(SetupMode),\n\t\t local_channel_(local_channel),\n\t\t local_window_size_(local_window_size),\n\t\t local_packet_size_(local_packet_size),\n\t\t remote_channel_(remote_channel),\n\t\t remote_window_size_(remote_window_size),\n\t\t remote_packet_size_(remote_packet_size),\n\t\t environment_()\n\t\t{ }\n\t};\n\n\tLogHandle log_;\n\tSocket *peer_;\n\tSSH::Session session_;\n\tSSH::TransportPipe *pipe_;\n\tAction *receive_action_;\n\tSplice *splice_;\n\tAction *splice_action_;\n\tAction *close_action_;\n\tuint32_t channel_next_;\n\tstd::map channel_map_;\n\tstd::map remote_channel_map_;\npublic:\n\tSSHConnection(Socket *peer)\n\t: log_(\"\/ssh\/connection\"),\n\t peer_(peer),\n\t session_(SSH::ServerRole),\n\t pipe_(NULL),\n\t splice_(NULL),\n\t splice_action_(NULL),\n\t close_action_(NULL),\n\t channel_next_(0),\n\t channel_map_()\n\t{\n\t\tsession_.algorithm_negotiation_ = new SSH::AlgorithmNegotiation(&session_);\n\t\tif (session_.role_ == SSH::ServerRole) {\n\t\t\tSSH::ServerHostKey *server_host_key = SSH::ServerHostKey::server(&session_, \"ssh-server1.pem\");\n\t\t\tsession_.algorithm_negotiation_->add_algorithm(server_host_key);\n\t\t}\n\t\tsession_.algorithm_negotiation_->add_algorithms();\n\n\t\tpipe_ = new SSH::TransportPipe(&session_);\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\n\t\tsplice_ = new Splice(log_ + \"\/splice\", peer_, pipe_, peer_);\n\t\tEventCallback *cb = callback(this, &SSHConnection::splice_complete);\n\t\tsplice_action_ = splice_->start(cb);\n\t}\n\n\t~SSHConnection()\n\t{\n\t\tASSERT(log_, close_action_ == NULL);\n\t\tASSERT(log_, splice_action_ == NULL);\n\t\tASSERT(log_, splice_ == NULL);\n\t\tASSERT(log_, receive_action_ == NULL);\n\t\tASSERT(log_, pipe_ == NULL);\n\t\tASSERT(log_, peer_ == NULL);\n\t}\n\nprivate:\n\tvoid receive_complete(Event e)\n\t{\n\t\treceive_action_->cancel();\n\t\treceive_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::Done:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Unexpected event while waiting for a packet: \" << e;\n\t\t\treturn;\n\t\t}\n\n\t\tASSERT(log_, !e.buffer_.empty());\n\n\t\tBuffer service;\n\t\tBuffer type;\n\t\tBuffer msg;\n\t\tSSHChannel *channel;\n\t\tuint32_t recipient_channel, sender_channel, window_size, packet_size;\n\t\tbool want_reply;\n\t\tstd::map::const_iterator rchit;\n\t\tstd::map::const_iterator chit;\n\t\tswitch (e.buffer_.peek()) {\n\t\tcase SSH::Message::TransportDisconnectMessage:\n\t\t\tbreak;\n\t\tcase SSH::Message::TransportServiceRequestMessage:\n\t\t\t\/* Claim to support any kind of service the client requests. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"No service name after transport request.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::String::decode(&service, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode service name.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"Extraneous data after service name.\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tmsg.append(SSH::Message::TransportServiceAcceptMessage);\n\t\t\tSSH::String::encode(&msg, service);\n\t\t\tpipe_->send(&msg);\n\n\t\t\tif (service.equal(\"ssh-userauth\")) {\n\t\t\t\tmsg.append(SSH::Message::UserAuthenticationBannerMessage);\n\t\t\t\tSSH::String::encode(&msg, std::string(\" *\\r\\n\\007 * This is a test server. Sessions, including authentication, may be logged.\\r\\n *\\r\\n\"));\n\t\t\t\tSSH::String::encode(&msg, std::string(\"en-CA\"));\n\t\t\t\tpipe_->send(&msg);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH::Message::UserAuthenticationRequestMessage:\n\t\t\t\/* Any authentication request succeeds. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tmsg.append(SSH::Message::UserAuthenticationSuccessMessage);\n\t\t\tpipe_->send(&msg);\n\t\t\tbreak;\n\t\tcase SSH::Message::ConnectionChannelOpen:\n\t\t\t\/* Opening a channel. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"No channel type after channel open.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::String::decode(&type, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode channel type.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&sender_channel, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode sender channel.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&window_size, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode window size.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&packet_size, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode packet size.\";\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/* Only support session channels. *\/\n\t\t\tif (!type.equal(\"session\")) {\n\t\t\t\tmsg.append(SSH::Message::ConnectionChannelOpenFailure);\n\t\t\t\tSSH::UInt32::encode(&msg, sender_channel);\n\t\t\t\tSSH::UInt32::encode(&msg, 3);\n\t\t\t\tSSH::String::encode(&msg, std::string(\"Unsupported session type.\"));\n\t\t\t\tSSH::String::encode(&msg, std::string(\"en-CA\"));\n\t\t\t\tpipe_->send(&msg);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\trecipient_channel = sender_channel;\n\t\t\tsender_channel = channel_setup(recipient_channel, window_size, packet_size);\n\n\t\t\t\/* Set up session. *\/\n\t\t\tmsg.append(SSH::Message::ConnectionChannelOpenConfirmation);\n\t\t\tSSH::UInt32::encode(&msg, recipient_channel);\n\t\t\tSSH::UInt32::encode(&msg, sender_channel);\n\t\t\tSSH::UInt32::encode(&msg, window_size);\n\t\t\tSSH::UInt32::encode(&msg, packet_size);\n\t\t\tpipe_->send(&msg);\n\t\t\tbreak;\n\t\tcase SSH::Message::ConnectionChannelRequest:\n\t\t\t\/* For now just fail any channel request. *\/\n\t\t\te.buffer_.skip(1);\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"No channel after channel request.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::UInt32::decode(&recipient_channel, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode recipient channel.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!SSH::String::decode(&type, &e.buffer_)) {\n\t\t\t\tERROR(log_) << \"Could not decode channel request type.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (e.buffer_.empty()) {\n\t\t\t\tERROR(log_) << \"Missing want_reply field.\";\n\t\t\t\treturn;\n\t\t\t}\n\t\t\twant_reply = e.buffer_.pop();\n\n\t\t\tchit = channel_map_.find(recipient_channel);\n\t\t\tif (chit == channel_map_.end()) {\n\t\t\t\tif (want_reply) {\n\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestFailure);\n\t\t\t\t\tSSH::UInt32::encode(&msg, 0); \/* XXX What to do for a request that fails due to unknown channel? *\/\n\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tchannel = chit->second;\n\n\t\t\tif (type.equal(\"pty-req\")) {\n\t\t\t\t\/* Fail for now. *\/\n\t\t\t} else if (type.equal(\"env\")) {\n\t\t\t\tBuffer keybuf;\n\t\t\t\tif (!SSH::String::decode(&keybuf, &e.buffer_)) {\n\t\t\t\t\tERROR(log_) << \"Could not decode environment key.\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tBuffer value;\n\t\t\t\tif (!SSH::String::decode(&value, &e.buffer_)) {\n\t\t\t\t\tERROR(log_) << \"Could not decode environment value.\";\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tstd::string key;\n\t\t\t\tkeybuf.extract(key);\n\n\t\t\t\tif (channel->environment_.find(key) == channel->environment_.end()) {\n\t\t\t\t\tchannel->environment_[key] = value;\n\n\t\t\t\t\tDEBUG(log_) << \"Client set environment variable.\";\n\t\t\t\t\tif (want_reply) {\n\t\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestSuccess);\n\t\t\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tINFO(log_) << \"Client attempted to set environment variable twice.\";\n\t\t\t\tif (want_reply) {\n\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestFailure);\n\t\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t} else if (type.equal(\"shell\")) {\n\t\t\t\tif (channel->mode_ == SSHChannel::SetupMode) {\n\t\t\t\t\tchannel->mode_ = SSHChannel::ShellMode;\n\t\t\t\t\tif (want_reply) {\n\t\t\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestSuccess);\n\t\t\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\t\t\tpipe_->send(&msg);\n\t\t\t\t\t}\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tERROR(log_) << \"Client requested a shell session, but session is not in setup mode.\";\n\t\t\t} else {\n\t\t\t\tDEBUG(log_) << \"Unhandled channel request type:\" << std::endl << type.hexdump();\n\t\t\t}\n\n\t\t\tif (want_reply) {\n\t\t\t\tmsg.append(SSH::Message::ConnectionChannelRequestFailure);\n\t\t\t\tSSH::UInt32::encode(&msg, channel->remote_channel_);\n\t\t\t\tpipe_->send(&msg);\n\t\t\t}\n\t\t\tbreak;\n\t\tcase SSH::Message::ConnectionChannelWindowAdjust:\n\t\t\t\/* Follow our peer's lead on window adjustments. *\/\n\t\tcase SSH::Message::ConnectionChannelData:\n\t\t\t\/* Just echo data back. We do not need to decode at present because channels are the same in both directions. *\/\n\t\t\tpipe_->send(&e.buffer_);\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tDEBUG(log_) << \"Unhandled message:\" << std::endl << e.buffer_.hexdump();\n\t\t\tbreak;\n\t\t}\n\n\t\tEventCallback *rcb = callback(this, &SSHConnection::receive_complete);\n\t\treceive_action_ = pipe_->receive(rcb);\n\t}\n\n\tvoid close_complete(void)\n\t{\n\t\tclose_action_->cancel();\n\t\tclose_action_ = NULL;\n\n\t\tASSERT(log_, peer_ != NULL);\n\t\tdelete peer_;\n\t\tpeer_ = NULL;\n\n\t\tdelete this;\n\t}\n\n\tvoid splice_complete(Event e)\n\t{\n\t\tsplice_action_->cancel();\n\t\tsplice_action_ = NULL;\n\n\t\tswitch (e.type_) {\n\t\tcase Event::EOS:\n\t\t\tDEBUG(log_) << \"Peer exiting normally.\";\n\t\t\tbreak;\n\t\tcase Event::Error:\n\t\t\tERROR(log_) << \"Peer exiting with error: \" << e;\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tERROR(log_) << \"Peer exiting with unknown event: \" << e;\n\t\t\tbreak;\n\t\t}\n\n\t ASSERT(log_, splice_ != NULL);\n\t\tdelete splice_;\n\t\tsplice_ = NULL;\n\n\t\tif (receive_action_ != NULL) {\n\t\t\tINFO(log_) << \"Peer exiting while waiting for a packet.\";\n\n\t\t\treceive_action_->cancel();\n\t\t\treceive_action_ = NULL;\n\t\t}\n\n\t\tASSERT(log_, pipe_ != NULL);\n\t\tdelete pipe_;\n\t\tpipe_ = NULL;\n\n\t\tASSERT(log_, close_action_ == NULL);\n\t\tSimpleCallback *cb = callback(this, &SSHConnection::close_complete);\n\t\tclose_action_ = peer_->close(cb);\n\t}\n\n\tuint32_t channel_setup(const uint32_t& remote_channel, const uint32_t& window_size, const uint32_t& packet_size)\n\t{\n\t\tstd::map::const_iterator it;\n\t\tuint32_t local_channel;\n\n\t\tuint32_t next = channel_next_;\n\t\tfor (;;) {\n\t\t\tit = channel_map_.find(next);\n\t\t\tif (it == channel_map_.end())\n\t\t\t\tbreak;\n\t\t\tnext++;\n\t\t}\n\t\tchannel_next_ = next + 1;\n\n\t\tlocal_channel = next;\n\t\tchannel_map_[local_channel] = new SSHChannel(local_channel, remote_channel, 65536, 65536, window_size, packet_size);\n\t\treturn (local_channel);\n\t}\n};\n\nclass SSHServer : public SimpleServer {\npublic:\n\tSSHServer(SocketAddressFamily family, const std::string& interface)\n\t: SimpleServer(\"\/ssh\/server\", family, interface)\n\t{ }\n\n\t~SSHServer()\n\t{ }\n\n\tvoid client_connected(Socket *client)\n\t{\n\t\tnew SSHConnection(client);\n\t}\n};\n\n\nint\nmain(void)\n{\n\tnew SSHServer(SocketAddressFamilyIP, \"[::]:2299\");\n\tevent_main();\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n\nusing namespace stx;\n\nnamespace csql {\n\nvoid installDefaultSymbols(SymbolTable* rt) {\n \/* expressions\/aggregate.h *\/\n rt->registerFunction(\"count\", expressions::kCountExpr);\n rt->registerFunction(\"sum\", expressions::kSumExpr);\n rt->registerFunction(\"mean\", expressions::kMeanExpr);\n\n \/\/rt->registerSymbol(\n \/\/ \"mean\",\n \/\/ &expressions::meanExpr,\n \/\/ expressions::meanExprScratchpadSize(),\n \/\/ &expressions::meanExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"avg\",\n \/\/ &expressions::meanExpr,\n \/\/ expressions::meanExprScratchpadSize(),\n \/\/ &expressions::meanExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"average\",\n \/\/ &expressions::meanExpr,\n \/\/ expressions::meanExprScratchpadSize(),\n \/\/ &expressions::meanExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"min\",\n \/\/ &expressions::minExpr,\n \/\/ expressions::minExprScratchpadSize(),\n \/\/ &expressions::minExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"max\",\n \/\/ &expressions::maxExpr,\n \/\/ expressions::maxExprScratchpadSize(),\n \/\/ &expressions::maxExprFree);\n\n \/* expressions\/boolean.h *\/\n rt->registerFunction(\"eq\", PureFunction(&expressions::eqExpr));\n rt->registerFunction(\"neq\", PureFunction(&expressions::neqExpr));\n rt->registerFunction(\"and\", PureFunction(&expressions::andExpr));\n rt->registerFunction(\"or\", PureFunction(&expressions::orExpr));\n rt->registerFunction(\"neg\", PureFunction(&expressions::negExpr));\n rt->registerFunction(\"lt\", PureFunction(&expressions::ltExpr));\n rt->registerFunction(\"lte\", PureFunction(&expressions::lteExpr));\n rt->registerFunction(\"gt\", PureFunction(&expressions::gtExpr));\n rt->registerFunction(\"gte\", PureFunction(&expressions::gteExpr));\n\n \/* expressions\/UnixTime.h *\/\n rt->registerFunction(\n \"FROM_TIMESTAMP\",\n PureFunction(&expressions::fromTimestamp));\n\n \/* expressions\/math.h *\/\n rt->registerFunction(\"add\", PureFunction(&expressions::addExpr));\n rt->registerFunction(\"sub\", PureFunction(&expressions::subExpr));\n rt->registerFunction(\"mul\", PureFunction(&expressions::mulExpr));\n rt->registerFunction(\"div\", PureFunction(&expressions::divExpr));\n rt->registerFunction(\"mod\", PureFunction(&expressions::modExpr));\n rt->registerFunction(\"pow\", PureFunction(&expressions::powExpr));\n\n}\n\n} \/\/ namespace csql\nupdate deps\/**\n * This file is part of the \"libfnord\" project\n * Copyright (c) 2015 Paul Asmuth\n *\n * FnordMetric is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU General Public License v3.0. You should have received a\n * copy of the GNU General Public License along with this program. If not, see\n * .\n *\/\n#include \n\nusing namespace stx;\n\nnamespace csql {\n\nvoid installDefaultSymbols(SymbolTable* rt) {\n \/* expressions\/aggregate.h *\/\n rt->registerFunction(\"count\", expressions::kCountExpr);\n rt->registerFunction(\"sum\", expressions::kSumExpr);\n\n \/\/rt->registerSymbol(\n \/\/ \"mean\",\n \/\/ &expressions::meanExpr,\n \/\/ expressions::meanExprScratchpadSize(),\n \/\/ &expressions::meanExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"avg\",\n \/\/ &expressions::meanExpr,\n \/\/ expressions::meanExprScratchpadSize(),\n \/\/ &expressions::meanExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"average\",\n \/\/ &expressions::meanExpr,\n \/\/ expressions::meanExprScratchpadSize(),\n \/\/ &expressions::meanExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"min\",\n \/\/ &expressions::minExpr,\n \/\/ expressions::minExprScratchpadSize(),\n \/\/ &expressions::minExprFree);\n\n \/\/rt->registerSymbol(\n \/\/ \"max\",\n \/\/ &expressions::maxExpr,\n \/\/ expressions::maxExprScratchpadSize(),\n \/\/ &expressions::maxExprFree);\n\n \/* expressions\/boolean.h *\/\n rt->registerFunction(\"eq\", PureFunction(&expressions::eqExpr));\n rt->registerFunction(\"neq\", PureFunction(&expressions::neqExpr));\n rt->registerFunction(\"and\", PureFunction(&expressions::andExpr));\n rt->registerFunction(\"or\", PureFunction(&expressions::orExpr));\n rt->registerFunction(\"neg\", PureFunction(&expressions::negExpr));\n rt->registerFunction(\"lt\", PureFunction(&expressions::ltExpr));\n rt->registerFunction(\"lte\", PureFunction(&expressions::lteExpr));\n rt->registerFunction(\"gt\", PureFunction(&expressions::gtExpr));\n rt->registerFunction(\"gte\", PureFunction(&expressions::gteExpr));\n\n \/* expressions\/UnixTime.h *\/\n rt->registerFunction(\n \"FROM_TIMESTAMP\",\n PureFunction(&expressions::fromTimestamp));\n\n \/* expressions\/math.h *\/\n rt->registerFunction(\"add\", PureFunction(&expressions::addExpr));\n rt->registerFunction(\"sub\", PureFunction(&expressions::subExpr));\n rt->registerFunction(\"mul\", PureFunction(&expressions::mulExpr));\n rt->registerFunction(\"div\", PureFunction(&expressions::divExpr));\n rt->registerFunction(\"mod\", PureFunction(&expressions::modExpr));\n rt->registerFunction(\"pow\", PureFunction(&expressions::powExpr));\n\n}\n\n} \/\/ namespace csql\n<|endoftext|>"} {"text":"\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n\/* Here is the version string - update before a public release *\/\nstatic char* CondorVersionString = \"$Version: 6.1.2 1999\/01\/12 $\";\n\nextern \"C\" {\n\nchar*\nCondorVersion()\n{\n\treturn CondorVersionString;\n}\n\n} \/* extern \"C\" *\/\n6.1.3 version string.\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n\/* Here is the version string - update before a public release *\/\nstatic char* CondorVersionString = \"$Version: 6.1.3 1999\/02\/15 $\";\n\nextern \"C\" {\n\nchar*\nCondorVersion()\n{\n\treturn CondorVersionString;\n}\n\n} \/* extern \"C\" *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#define WPP_NAME \"secure_coap_server.tmh\"\n\n#include \n#include \n#include \n#include \n\n\/**\n * @file\n * This file implements the secure CoAP server.\n *\/\n\nnamespace Thread {\nnamespace Coap {\n\nSecureServer::SecureServer(ThreadNetif &aNetif, uint16_t aPort):\n Server(aNetif, aPort, &SecureServer::Send, &SecureServer::Receive),\n mTransmitCallback(NULL),\n mContext(NULL),\n mNetif(aNetif),\n mTransmitMessage(NULL),\n mTransmitTask(aNetif.GetIp6().mTaskletScheduler, &SecureServer::HandleUdpTransmit, this)\n{\n}\n\nThreadError SecureServer::Start(TransportCallback aCallback, void *aContext)\n{\n ThreadError error = kThreadError_None;\n mTransmitCallback = aCallback;\n mContext = aContext;\n\n \/\/ Passing mTransmitCallback means that we do not want to use socket\n \/\/ to transmit\/receive messages, so do not open it in that case.\n if (mTransmitCallback == NULL)\n {\n error = Server::Start();\n }\n\n return error;\n}\n\nThreadError SecureServer::Stop()\n{\n if (mNetif.GetDtls().IsStarted())\n {\n mNetif.GetDtls().Stop();\n }\n\n if (mTransmitMessage != NULL)\n {\n mTransmitMessage->Free();\n mTransmitMessage = NULL;\n }\n\n mTransmitCallback = NULL;\n mContext = NULL;\n\n otLogFuncExit();\n\n return Server::Stop();\n}\n\nbool SecureServer::IsConnectionActive(void)\n{\n return mNetif.GetDtls().IsStarted();\n};\n\nThreadError SecureServer::Send(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n return static_cast(aContext)->Send(aMessage, aMessageInfo);\n}\n\nThreadError SecureServer::Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n (void)aMessageInfo;\n return mNetif.GetDtls().Send(aMessage, aMessage.GetLength());\n}\n\nvoid SecureServer::Receive(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n return static_cast(aContext)->Receive(aMessage, aMessageInfo);\n}\n\nvoid SecureServer::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n otLogFuncEntry();\n\n if (!mNetif.GetDtls().IsStarted())\n {\n mPeerAddress.SetPeerAddr(aMessageInfo.GetPeerAddr());\n mPeerAddress.SetPeerPort(aMessageInfo.GetPeerPort());\n\n mNetif.GetDtls().Start(false, HandleDtlsConnected, HandleDtlsReceive, HandleDtlsSend, this);\n }\n else\n {\n \/\/ Once DTLS session is started, communicate only with a peer.\n VerifyOrExit((mPeerAddress.GetPeerAddr() == aMessageInfo.GetPeerAddr()) &&\n (mPeerAddress.GetPeerPort() == aMessageInfo.GetPeerPort()), ;);\n }\n\n mNetif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8,\n sizeof(mPeerAddress.GetPeerAddr().mFields));\n mNetif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset());\n\nexit:\n otLogFuncExit();\n}\n\nThreadError SecureServer::SetPsk(const uint8_t *aPsk, uint8_t aPskLength)\n{\n return mNetif.GetDtls().SetPsk(aPsk, aPskLength);\n}\n\nvoid SecureServer::HandleDtlsConnected(void *aContext, bool aConnected)\n{\n return static_cast(aContext)->HandleDtlsConnected(aConnected);\n}\n\nvoid SecureServer::HandleDtlsConnected(bool aConnected)\n{\n (void)aConnected;\n}\n\nvoid SecureServer::HandleDtlsReceive(void *aContext, uint8_t *aBuf, uint16_t aLength)\n{\n return static_cast(aContext)->HandleDtlsReceive(aBuf, aLength);\n}\n\nvoid SecureServer::HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength)\n{\n Message *message;\n\n otLogFuncEntry();\n\n VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, ;);\n SuccessOrExit(message->Append(aBuf, aLength));\n\n ProcessReceivedMessage(*message, mPeerAddress);\n\nexit:\n\n if (message != NULL)\n {\n message->Free();\n }\n\n otLogFuncExit();\n}\n\nThreadError SecureServer::HandleDtlsSend(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType)\n{\n return static_cast(aContext)->HandleDtlsSend(aBuf, aLength, aMessageSubType);\n}\n\nThreadError SecureServer::HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType)\n{\n ThreadError error = kThreadError_None;\n\n otLogFuncEntry();\n\n if (mTransmitMessage == NULL)\n {\n VerifyOrExit((mTransmitMessage = mSocket.NewMessage(0)) != NULL, error = kThreadError_NoBufs);\n mTransmitMessage->SetSubType(aMessageSubType);\n mTransmitMessage->SetLinkSecurityEnabled(false);\n }\n\n VerifyOrExit(mTransmitMessage->Append(aBuf, aLength) == kThreadError_None, error = kThreadError_NoBufs);\n\n mTransmitTask.Post();\n\nexit:\n\n if (error != kThreadError_None && mTransmitMessage != NULL)\n {\n mTransmitMessage->Free();\n }\n\n otLogFuncExitErr(error);\n\n return error;\n}\n\nvoid SecureServer::HandleUdpTransmit(void *aContext)\n{\n return static_cast(aContext)->HandleUdpTransmit();\n}\n\nvoid SecureServer::HandleUdpTransmit(void)\n{\n ThreadError error = kThreadError_None;\n\n otLogFuncEntry();\n\n VerifyOrExit(mTransmitMessage != NULL, error = kThreadError_NoBufs);\n\n if (mTransmitCallback)\n {\n SuccessOrExit(error = mTransmitCallback(mContext, *mTransmitMessage, mPeerAddress));\n }\n else\n {\n SuccessOrExit(error = mSocket.SendTo(*mTransmitMessage, mPeerAddress));\n }\n\nexit:\n\n if (error != kThreadError_None && mTransmitMessage != NULL)\n {\n mTransmitMessage->Free();\n }\n\n mTransmitMessage = NULL;\n\n otLogFuncExit();\n}\n\n} \/\/ namespace Coap\n} \/\/ namespace Thread\nFix mismatching source address of secured CoAP server (#1520)\/*\n * Copyright (c) 2016, The OpenThread Authors.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n * 1. Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * 2. Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution.\n * 3. Neither the name of the copyright holder nor the\n * names of its contributors may be used to endorse or promote products\n * derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#define WPP_NAME \"secure_coap_server.tmh\"\n\n#include \n#include \n#include \n#include \n\n\/**\n * @file\n * This file implements the secure CoAP server.\n *\/\n\nnamespace Thread {\nnamespace Coap {\n\nSecureServer::SecureServer(ThreadNetif &aNetif, uint16_t aPort):\n Server(aNetif, aPort, &SecureServer::Send, &SecureServer::Receive),\n mTransmitCallback(NULL),\n mContext(NULL),\n mNetif(aNetif),\n mTransmitMessage(NULL),\n mTransmitTask(aNetif.GetIp6().mTaskletScheduler, &SecureServer::HandleUdpTransmit, this)\n{\n}\n\nThreadError SecureServer::Start(TransportCallback aCallback, void *aContext)\n{\n ThreadError error = kThreadError_None;\n mTransmitCallback = aCallback;\n mContext = aContext;\n\n \/\/ Passing mTransmitCallback means that we do not want to use socket\n \/\/ to transmit\/receive messages, so do not open it in that case.\n if (mTransmitCallback == NULL)\n {\n error = Server::Start();\n }\n\n return error;\n}\n\nThreadError SecureServer::Stop()\n{\n if (mNetif.GetDtls().IsStarted())\n {\n mNetif.GetDtls().Stop();\n }\n\n if (mTransmitMessage != NULL)\n {\n mTransmitMessage->Free();\n mTransmitMessage = NULL;\n }\n\n mTransmitCallback = NULL;\n mContext = NULL;\n\n otLogFuncExit();\n\n return Server::Stop();\n}\n\nbool SecureServer::IsConnectionActive(void)\n{\n return mNetif.GetDtls().IsStarted();\n};\n\nThreadError SecureServer::Send(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n return static_cast(aContext)->Send(aMessage, aMessageInfo);\n}\n\nThreadError SecureServer::Send(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n (void)aMessageInfo;\n return mNetif.GetDtls().Send(aMessage, aMessage.GetLength());\n}\n\nvoid SecureServer::Receive(void *aContext, Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n return static_cast(aContext)->Receive(aMessage, aMessageInfo);\n}\n\nvoid SecureServer::Receive(Message &aMessage, const Ip6::MessageInfo &aMessageInfo)\n{\n otLogFuncEntry();\n\n if (!mNetif.GetDtls().IsStarted())\n {\n mPeerAddress.SetPeerAddr(aMessageInfo.GetPeerAddr());\n mPeerAddress.SetPeerPort(aMessageInfo.GetPeerPort());\n\n if (mNetif.IsUnicastAddress(aMessageInfo.GetSockAddr()))\n {\n mPeerAddress.SetSockAddr(aMessageInfo.GetSockAddr());\n }\n\n mPeerAddress.SetSockPort(aMessageInfo.GetSockPort());\n\n mNetif.GetDtls().Start(false, HandleDtlsConnected, HandleDtlsReceive, HandleDtlsSend, this);\n }\n else\n {\n \/\/ Once DTLS session is started, communicate only with a peer.\n VerifyOrExit((mPeerAddress.GetPeerAddr() == aMessageInfo.GetPeerAddr()) &&\n (mPeerAddress.GetPeerPort() == aMessageInfo.GetPeerPort()), ;);\n }\n\n mNetif.GetDtls().SetClientId(mPeerAddress.GetPeerAddr().mFields.m8,\n sizeof(mPeerAddress.GetPeerAddr().mFields));\n mNetif.GetDtls().Receive(aMessage, aMessage.GetOffset(), aMessage.GetLength() - aMessage.GetOffset());\n\nexit:\n otLogFuncExit();\n}\n\nThreadError SecureServer::SetPsk(const uint8_t *aPsk, uint8_t aPskLength)\n{\n return mNetif.GetDtls().SetPsk(aPsk, aPskLength);\n}\n\nvoid SecureServer::HandleDtlsConnected(void *aContext, bool aConnected)\n{\n return static_cast(aContext)->HandleDtlsConnected(aConnected);\n}\n\nvoid SecureServer::HandleDtlsConnected(bool aConnected)\n{\n (void)aConnected;\n}\n\nvoid SecureServer::HandleDtlsReceive(void *aContext, uint8_t *aBuf, uint16_t aLength)\n{\n return static_cast(aContext)->HandleDtlsReceive(aBuf, aLength);\n}\n\nvoid SecureServer::HandleDtlsReceive(uint8_t *aBuf, uint16_t aLength)\n{\n Message *message;\n\n otLogFuncEntry();\n\n VerifyOrExit((message = mNetif.GetIp6().mMessagePool.New(Message::kTypeIp6, 0)) != NULL, ;);\n SuccessOrExit(message->Append(aBuf, aLength));\n\n ProcessReceivedMessage(*message, mPeerAddress);\n\nexit:\n\n if (message != NULL)\n {\n message->Free();\n }\n\n otLogFuncExit();\n}\n\nThreadError SecureServer::HandleDtlsSend(void *aContext, const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType)\n{\n return static_cast(aContext)->HandleDtlsSend(aBuf, aLength, aMessageSubType);\n}\n\nThreadError SecureServer::HandleDtlsSend(const uint8_t *aBuf, uint16_t aLength, uint8_t aMessageSubType)\n{\n ThreadError error = kThreadError_None;\n\n otLogFuncEntry();\n\n if (mTransmitMessage == NULL)\n {\n VerifyOrExit((mTransmitMessage = mSocket.NewMessage(0)) != NULL, error = kThreadError_NoBufs);\n mTransmitMessage->SetSubType(aMessageSubType);\n mTransmitMessage->SetLinkSecurityEnabled(false);\n }\n\n VerifyOrExit(mTransmitMessage->Append(aBuf, aLength) == kThreadError_None, error = kThreadError_NoBufs);\n\n mTransmitTask.Post();\n\nexit:\n\n if (error != kThreadError_None && mTransmitMessage != NULL)\n {\n mTransmitMessage->Free();\n }\n\n otLogFuncExitErr(error);\n\n return error;\n}\n\nvoid SecureServer::HandleUdpTransmit(void *aContext)\n{\n return static_cast(aContext)->HandleUdpTransmit();\n}\n\nvoid SecureServer::HandleUdpTransmit(void)\n{\n ThreadError error = kThreadError_None;\n\n otLogFuncEntry();\n\n VerifyOrExit(mTransmitMessage != NULL, error = kThreadError_NoBufs);\n\n if (mTransmitCallback)\n {\n SuccessOrExit(error = mTransmitCallback(mContext, *mTransmitMessage, mPeerAddress));\n }\n else\n {\n SuccessOrExit(error = mSocket.SendTo(*mTransmitMessage, mPeerAddress));\n }\n\nexit:\n\n if (error != kThreadError_None && mTransmitMessage != NULL)\n {\n mTransmitMessage->Free();\n }\n\n mTransmitMessage = NULL;\n\n otLogFuncExit();\n}\n\n} \/\/ namespace Coap\n} \/\/ namespace Thread\n<|endoftext|>"} {"text":"#include \n#include \"keycode.hpp\"\n\nusing namespace org_pqrs_KeyRemap4MacBook;\n\nTEST(ModifierFlag, stripFN) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripFN(flags), flags);\n EXPECT_EQ(ModifierFlag::stripFN(flags | ModifierFlag::FN), flags);\n}\n\nTEST(ModifierFlag, stripCURSOR) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripCURSOR(flags), flags);\n EXPECT_EQ(ModifierFlag::stripCURSOR(flags | ModifierFlag::CURSOR), flags);\n}\n\nTEST(ModifierFlag, stripKEYPAD) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripKEYPAD(flags), flags);\n EXPECT_EQ(ModifierFlag::stripKEYPAD(flags | ModifierFlag::KEYPAD), flags);\n}\n\nTEST(ModifierFlag, stripNONE) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripNONE(flags), flags);\n EXPECT_EQ(ModifierFlag::stripNONE(flags | ModifierFlag::NONE), flags);\n}\n\nTEST(ModifierFlag, isOn) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_L));\n EXPECT_FALSE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_R));\n\n flags = ModifierFlag::NONE;\n EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::NONE));\n}\n\nnamespace {\n unsigned int keypads[][2] = {\n { KeyCode::KEYPAD_0, KeyCode::M },\n { KeyCode::KEYPAD_1, KeyCode::J },\n { KeyCode::KEYPAD_2, KeyCode::K },\n { KeyCode::KEYPAD_3, KeyCode::L },\n { KeyCode::KEYPAD_4, KeyCode::U },\n { KeyCode::KEYPAD_5, KeyCode::I },\n { KeyCode::KEYPAD_6, KeyCode::O },\n { KeyCode::KEYPAD_7, KeyCode::KEY_7 },\n { KeyCode::KEYPAD_8, KeyCode::KEY_8 },\n { KeyCode::KEYPAD_9, KeyCode::KEY_9 },\n { KeyCode::KEYPAD_CLEAR, KeyCode::KEY_6 },\n { KeyCode::KEYPAD_PLUS, KeyCode::SLASH },\n { KeyCode::KEYPAD_MINUS, KeyCode::SEMICOLON },\n { KeyCode::KEYPAD_MULTIPLY, KeyCode::P },\n { KeyCode::KEYPAD_SLASH, KeyCode::KEY_0 },\n { KeyCode::KEYPAD_EQUAL, KeyCode::MINUS },\n { KeyCode::KEYPAD_DOT, KeyCode::DOT },\n };\n\n unsigned int cursors[][2] = {\n { KeyCode::PAGEUP, KeyCode::CURSOR_UP },\n { KeyCode::PAGEDOWN, KeyCode::CURSOR_DOWN },\n { KeyCode::HOME, KeyCode::CURSOR_LEFT },\n { KeyCode::END, KeyCode::CURSOR_RIGHT },\n };\n}\n\n\nTEST(KeyCode, normalizeKey) {\n unsigned int key = 0;\n unsigned int flags = 0;\n unsigned int keyboardType = 0;\n\n \/\/ ENTER_POWERBOOK -> ENTER\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ normal key\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ KEYPAD\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n }\n\n \/\/ ENTER\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ FORWARD_DELETE\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ normal key(+FN)\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ KEYPAD(+FN)\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(keypads[i][1])); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP(+FN)\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][1]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::CURSOR));\n }\n\n \/\/ ENTER(+FN)\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ FORWARD_DELETE(+FN)\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n}\n\nTEST(KeyCode, reverseNormalizeKey) {\n unsigned int key = 0;\n unsigned int flags = 0;\n unsigned int keyboardType = 0;\n\n \/\/ ENTER_POWERBOOK -> ENTER\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ normal key\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ KEYPAD\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n }\n\n \/\/ ENTER\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ FORWARD_DELETE\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ CURSOR\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][1]; flags = ModifierFlag::CURSOR; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(cursors[i][1])); EXPECT_EQ(flags, static_cast(ModifierFlag::CURSOR));\n }\n\n \/\/ normal key(+FN)\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ KEYPAD(+FN)\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(keypads[i][0])); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP(+FN)\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n }\n\n \/\/ ENTER(+FN)\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ FORWARD_DELETE(+FN)\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n}\nupdate kext\/Tests#include \n#include \"keycode.hpp\"\n\nusing namespace org_pqrs_KeyRemap4MacBook;\n\nTEST(ModifierFlag, stripFN) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripFN(flags), flags);\n EXPECT_EQ(ModifierFlag::stripFN(flags | ModifierFlag::FN), flags);\n}\n\nTEST(ModifierFlag, stripCURSOR) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripCURSOR(flags), flags);\n EXPECT_EQ(ModifierFlag::stripCURSOR(flags | ModifierFlag::CURSOR), flags);\n}\n\nTEST(ModifierFlag, stripKEYPAD) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripKEYPAD(flags), flags);\n EXPECT_EQ(ModifierFlag::stripKEYPAD(flags | ModifierFlag::KEYPAD), flags);\n}\n\nTEST(ModifierFlag, stripNONE) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_EQ(ModifierFlag::stripNONE(flags), flags);\n EXPECT_EQ(ModifierFlag::stripNONE(flags | ModifierFlag::NONE), flags);\n}\n\nTEST(ModifierFlag, isOn) {\n unsigned int flags = ModifierFlag::SHIFT_L | ModifierFlag::CONTROL_R | ModifierFlag::COMMAND_R;\n EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_L));\n EXPECT_FALSE(ModifierFlag::isOn(flags, ModifierFlag::SHIFT_R));\n\n flags = ModifierFlag::NONE;\n EXPECT_TRUE(ModifierFlag::isOn(flags, ModifierFlag::NONE));\n}\n\nnamespace {\n unsigned int keypads[][2] = {\n { KeyCode::KEYPAD_0, KeyCode::M },\n { KeyCode::KEYPAD_1, KeyCode::J },\n { KeyCode::KEYPAD_2, KeyCode::K },\n { KeyCode::KEYPAD_3, KeyCode::L },\n { KeyCode::KEYPAD_4, KeyCode::U },\n { KeyCode::KEYPAD_5, KeyCode::I },\n { KeyCode::KEYPAD_6, KeyCode::O },\n { KeyCode::KEYPAD_7, KeyCode::KEY_7 },\n { KeyCode::KEYPAD_8, KeyCode::KEY_8 },\n { KeyCode::KEYPAD_9, KeyCode::KEY_9 },\n { KeyCode::KEYPAD_CLEAR, KeyCode::KEY_6 },\n { KeyCode::KEYPAD_PLUS, KeyCode::SLASH },\n { KeyCode::KEYPAD_MINUS, KeyCode::SEMICOLON },\n { KeyCode::KEYPAD_MULTIPLY, KeyCode::P },\n { KeyCode::KEYPAD_SLASH, KeyCode::KEY_0 },\n { KeyCode::KEYPAD_EQUAL, KeyCode::MINUS },\n { KeyCode::KEYPAD_DOT, KeyCode::DOT },\n };\n\n unsigned int cursors[][2] = {\n { KeyCode::PAGEUP, KeyCode::CURSOR_UP },\n { KeyCode::PAGEDOWN, KeyCode::CURSOR_DOWN },\n { KeyCode::HOME, KeyCode::CURSOR_LEFT },\n { KeyCode::END, KeyCode::CURSOR_RIGHT },\n };\n}\n\n\nTEST(KeyCode, normalizeKey) {\n unsigned int key = 0;\n unsigned int flags = 0;\n unsigned int keyboardType = 0;\n\n \/\/ ENTER_POWERBOOK -> ENTER\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ normal key\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ KEYPAD\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n }\n\n \/\/ ENTER\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ FORWARD_DELETE\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ normal key(+FN)\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ KEYPAD(+FN)\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(keypads[i][1])); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n }\n\n \/\/ PAGEUP(+FN)\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][1]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::CURSOR));\n }\n\n \/\/ ENTER(+FN)\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::RETURN)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ FORWARD_DELETE(+FN)\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n}\n\nTEST(KeyCode, reverseNormalizeKey) {\n unsigned int key = 0;\n unsigned int flags = 0;\n unsigned int keyboardType = 0;\n\n \/\/ ENTER_POWERBOOK -> ENTER\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ ENTER_POWERBOOK(+FN) -> ENTER(+FN) -> RETURN\n key = KeyCode::ENTER_POWERBOOK; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::POWERBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER_POWERBOOK)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ normal key\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ KEYPAD\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, keypads[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n }\n\n \/\/ ENTER\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ FORWARD_DELETE\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L));\n\n \/\/ CURSOR\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][1]; flags = ModifierFlag::CURSOR; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(cursors[i][1])); EXPECT_EQ(flags, static_cast(ModifierFlag::CURSOR));\n }\n\n \/\/ normal key(+FN)\n key = KeyCode::A; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::A)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ KEYPAD(+FN)\n for (size_t i = 0; i < sizeof(keypads) \/ sizeof(keypads[0]); ++i) {\n key = keypads[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(keypads[i][0])); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN | ModifierFlag::KEYPAD));\n }\n\n \/\/ PAGEUP(+FN)\n for (size_t i = 0; i < sizeof(cursors) \/ sizeof(cursors[0]); ++i) {\n key = cursors[i][0]; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, cursors[i][0]); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n }\n\n \/\/ ENTER(+FN)\n key = KeyCode::ENTER; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::ENTER)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n\n \/\/ FORWARD_DELETE(+FN)\n key = KeyCode::FORWARD_DELETE; flags = ModifierFlag::SHIFT_L | ModifierFlag::FN; keyboardType = KeyboardType::MACBOOK;\n KeyCode::normalizeKey(key, flags, keyboardType);\n flags |= ModifierFlag::FN;\n KeyCode::reverseNormalizeKey(key, flags, keyboardType);\n EXPECT_EQ(key, static_cast(KeyCode::FORWARD_DELETE)); EXPECT_EQ(flags, static_cast(ModifierFlag::SHIFT_L | ModifierFlag::FN));\n}\n<|endoftext|>"} {"text":"#include \"core\/physics\/physics_manager.h\"\n#include \"core\/physics\/constraint.h\"\n#include \"core\/rendering\/render_manager.h\"\n#include \n#include \n\nnamespace eversim { namespace core { namespace physics {\n\n\tnamespace {\n\t\ttemplate \n\t\tvoid iterate(Constraints const& c, std::index_sequence, Func&& fun)\n\t\t{\n\t\t\tstd::initializer_list{\n\t\t\t\t(std::forward(fun)(std::get(c), Is), 0)...\n\t\t\t};\n\t\t}\n\t}\n\n\tvoid physics_manager::add_particle(particle const& p)\n\t{\n\t\tparticles.push_back(p);\n\t}\n\n\tvoid physics_manager::integrate(float dt)\n\t{\n\t\tapply_external_forces(dt);\n\t\tdamp_velocities();\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tp.projected_position = p.pos + dt * p.vel;\n\t\t}\n\n\t\tfor (auto i = 0; i < solver_iterations; ++i)\n\t\t{\n\t\t\tproject_constraints();\n\t\t}\n\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tp.vel = (p.projected_position - p.pos) \/ dt;\n\t\t\tp.pos = p.projected_position;\n\t\t}\n\t}\n\n\tvoid physics_manager::atomic_step(float dt)\n\t{\n\t\tswitch (current_state)\n\t\t{\n\t\tcase simulation_state::external:\n\t\t\tapply_external_forces(dt);\n\t\t\tcurrent_state = simulation_state::damp;\n\t\t\tbreak;\n\t\tcase simulation_state::damp:\n\t\t\tdamp_velocities();\n\t\t\tcurrent_state = simulation_state::apply_velocity;\n\t\t\tbreak;\n\t\tcase simulation_state::apply_velocity:\n\t\t\tfor (auto& p : particles)\n\t\t\t{\n\t\t\t\tp.projected_position = p.pos + dt * p.vel;\n\t\t\t}\n\t\t\tcurrent_state = simulation_state::constraint_iteration;\n\t\t\tbreak;\n\t\tcase simulation_state::constraint_iteration:\n\t\t\tif(current_iteration < solver_iterations)\n\t\t\t{\n\t\t\t\tproject_constraints();\n\t\t\t\tcurrent_iteration++;\n\t\t\t}else\n\t\t\t{\n\t\t\t\tcurrent_iteration = 0;\n\t\t\t\tcurrent_state = simulation_state::apply_changes;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase simulation_state::apply_changes:\n\t\t\tfor (auto& p : particles)\n\t\t\t{\n\t\t\t\tp.vel = (p.projected_position - p.pos) \/ dt;\n\t\t\t\tp.pos = p.projected_position;\n\t\t\t}\n\t\t\tcurrent_state = simulation_state::external;\n\t\t\tbreak;\n\t\tdefault: ;\n\t\t\tassert(!\"unknown state!\");\n\t\t}\n\t}\n\n\tvoid physics_manager::draw_constraints(std::bitset to_render)\n\t{\n\t\titerate(constraints, std::make_index_sequence{}, [to_render](auto const& cs, size_t I)\n\t\t{\n\t\t\tif(to_render[I])\n\t\t\t{\n\t\t\t\tfor (auto const& c : cs) {\n\t\t\t\t\tfor (int i = 0; i < c->arity(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int j = 0; j < i; ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto p1 = c->particles[i];\n\t\t\t\t\t\t\tauto p2 = c->particles[j];\n\t\t\t\t\t\t\trendering::draw_line(p1->projected_position, p2->projected_position);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\n\tvoid physics_manager::apply_external_forces(float dt)\n\t{\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tif (p.inv_mass == 0.f)\n\t\t\t\tcontinue;\n\t\t\tp.vel += dt * glm::vec2{0,-1};\n\t\t}\n\t}\n\n\tvoid physics_manager::damp_velocities()\n\t{\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tp.vel *= 0.99; \/\/ TODO: improve\n\t\t}\n\t}\n\n\tnamespace {\n\t\ttemplate \n\t\tvoid project_single_constraint(constraint const& c)\n\t\t{\n\t\t\tconst auto err = c();\n\t\t\tswitch (c.get_type())\n\t\t\t{\n\t\t\tcase constraint_type::equality:\n\t\t\t\t{\n\t\t\t\t\tif (err == 0)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase constraint_type::inequality:\n\t\t\t\t{\n\t\t\t\t\tif (err >= 0)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tassert(!\"Unhandled constraint type!\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto grad = c.grad();\n\n\t\t\tconst auto sum = [&]\n\t\t\t{\n\t\t\t\tauto sum = 0.f;\n\t\t\t\tfor (auto i = 0; i < N; ++i)\n\t\t\t\t{\n\t\t\t\t\tsum += c.particles[i]->inv_mass * length2(grad[i]);\n\t\t\t\t}\n\t\t\t\treturn sum;\n\t\t\t}();\n\t\t\tconst auto scale = err \/ sum;\n\n\t\t\tfor (auto i = 0; i < N; ++i)\n\t\t\t{\n\t\t\t\tauto& p = c.particles[i];\n\t\t\t\tconst auto correction = -scale * p->inv_mass * grad[i];\n\t\t\t\trendering::draw_line(p->projected_position, p->projected_position + correction,60);\n\t\t\t\tp->projected_position += correction;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid physics_manager::project_constraints()\n\t{\n\t\titerate(constraints, std::make_index_sequence{}, [](auto&& cs, auto){\n\t\t\tfor(auto const& c : cs)\n\t\t\t{\n\t\t\t\tproject_single_constraint(*c);\n\t\t\t}\n\t\t});\n\t}\n}}}\nimplemented missing code for stiffness parameter#include \"core\/physics\/physics_manager.h\"\n#include \"core\/physics\/constraint.h\"\n#include \"core\/rendering\/render_manager.h\"\n#include \n#include \n\nnamespace eversim { namespace core { namespace physics {\n\n\tnamespace {\n\t\ttemplate \n\t\tvoid iterate(Constraints const& c, std::index_sequence, Func&& fun)\n\t\t{\n\t\t\tstd::initializer_list{\n\t\t\t\t(std::forward(fun)(std::get(c), Is), 0)...\n\t\t\t};\n\t\t}\n\t}\n\n\tvoid physics_manager::add_particle(particle const& p)\n\t{\n\t\tparticles.push_back(p);\n\t}\n\n\tvoid physics_manager::integrate(float dt)\n\t{\n\t\tapply_external_forces(dt);\n\t\tdamp_velocities();\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tp.projected_position = p.pos + dt * p.vel;\n\t\t}\n\n\t\tfor (auto i = 0; i < solver_iterations; ++i)\n\t\t{\n\t\t\tproject_constraints();\n\t\t}\n\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tp.vel = (p.projected_position - p.pos) \/ dt;\n\t\t\tp.pos = p.projected_position;\n\t\t}\n\t}\n\n\tvoid physics_manager::atomic_step(float dt)\n\t{\n\t\tswitch (current_state)\n\t\t{\n\t\tcase simulation_state::external:\n\t\t\tapply_external_forces(dt);\n\t\t\tcurrent_state = simulation_state::damp;\n\t\t\tbreak;\n\t\tcase simulation_state::damp:\n\t\t\tdamp_velocities();\n\t\t\tcurrent_state = simulation_state::apply_velocity;\n\t\t\tbreak;\n\t\tcase simulation_state::apply_velocity:\n\t\t\tfor (auto& p : particles)\n\t\t\t{\n\t\t\t\tp.projected_position = p.pos + dt * p.vel;\n\t\t\t}\n\t\t\tcurrent_state = simulation_state::constraint_iteration;\n\t\t\tbreak;\n\t\tcase simulation_state::constraint_iteration:\n\t\t\tif(current_iteration < solver_iterations)\n\t\t\t{\n\t\t\t\tproject_constraints();\n\t\t\t\tcurrent_iteration++;\n\t\t\t}else\n\t\t\t{\n\t\t\t\tcurrent_iteration = 0;\n\t\t\t\tcurrent_state = simulation_state::apply_changes;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase simulation_state::apply_changes:\n\t\t\tfor (auto& p : particles)\n\t\t\t{\n\t\t\t\tp.vel = (p.projected_position - p.pos) \/ dt;\n\t\t\t\tp.pos = p.projected_position;\n\t\t\t}\n\t\t\tcurrent_state = simulation_state::external;\n\t\t\tbreak;\n\t\tdefault: ;\n\t\t\tassert(!\"unknown state!\");\n\t\t}\n\t}\n\n\tvoid physics_manager::draw_constraints(std::bitset to_render)\n\t{\n\t\titerate(constraints, std::make_index_sequence{}, [to_render](auto const& cs, size_t I)\n\t\t{\n\t\t\tif(to_render[I])\n\t\t\t{\n\t\t\t\tfor (auto const& c : cs) {\n\t\t\t\t\tfor (int i = 0; i < c->arity(); ++i)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (int j = 0; j < i; ++j)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tauto p1 = c->particles[i];\n\t\t\t\t\t\t\tauto p2 = c->particles[j];\n\t\t\t\t\t\t\trendering::draw_line(p1->projected_position, p2->projected_position);\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\t}\n\n\n\tvoid physics_manager::apply_external_forces(float dt)\n\t{\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tif (p.inv_mass == 0.f)\n\t\t\t\tcontinue;\n\t\t\tp.vel += dt * glm::vec2{0,-1};\n\t\t}\n\t}\n\n\tvoid physics_manager::damp_velocities()\n\t{\n\t\tfor (auto& p : particles)\n\t\t{\n\t\t\tp.vel *= 0.99; \/\/ TODO: improve\n\t\t}\n\t}\n\n\tnamespace {\n\t\ttemplate \n\t\tvoid project_single_constraint(constraint const& c, int solver_iterations)\n\t\t{\n\t\t\tconst auto err = c();\n\t\t\tswitch (c.get_type())\n\t\t\t{\n\t\t\tcase constraint_type::equality:\n\t\t\t\t{\n\t\t\t\t\tif (err == 0)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tcase constraint_type::inequality:\n\t\t\t\t{\n\t\t\t\t\tif (err >= 0)\n\t\t\t\t\t\treturn;\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\tdefault:\n\t\t\t\t{\n\t\t\t\t\tassert(!\"Unhandled constraint type!\");\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto grad = c.grad();\n\n\t\t\tconst auto sum = [&]\n\t\t\t{\n\t\t\t\tauto sum = 0.f;\n\t\t\t\tfor (auto i = 0; i < N; ++i)\n\t\t\t\t{\n\t\t\t\t\tsum += c.particles[i]->inv_mass * length2(grad[i]);\n\t\t\t\t}\n\t\t\t\treturn sum;\n\t\t\t}();\n\t\t\tconst auto scale = err \/ sum;\n\n\t\t\tconst auto k = 1.f - powf(1.f - c.stiffness, 1.f \/ solver_iterations);\n\n\t\t\tfor (auto i = 0; i < N; ++i)\n\t\t\t{\n\t\t\t\tauto& p = c.particles[i];\n\t\t\t\tconst auto correction = -scale * p->inv_mass * grad[i] * k;\n\t\t\t\trendering::draw_line(p->projected_position, p->projected_position + correction,60);\n\t\t\t\tp->projected_position += correction;\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid physics_manager::project_constraints()\n\t{\n\t\titerate(constraints, std::make_index_sequence{}, [this](auto&& cs, auto){\n\t\t\tfor(auto const& c : cs)\n\t\t\t{\n\t\t\t\tproject_single_constraint(*c, solver_iterations);\n\t\t\t}\n\t\t});\n\t}\n}}}\n<|endoftext|>"} {"text":"\/\/\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2013 Project Chrono\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file at the top level of the distribution\n\/\/ and at http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\n\/\/\n\/\/ Demo code about\n\/\/\n\/\/ - FEA for 3D beams of 'cable' type (ANCF gradient-deficient beams)\n\/\/ uses the Chrono MKL module\n\n#include \"chrono\/timestepper\/ChTimestepper.h\"\n#include \"chrono_irrlicht\/ChIrrApp.h\"\n#include \"chrono_mkl\/ChSolverMKL.h\"\n\n#include \"FEAcables.h\"\n\/*\nusing namespace chrono;\nusing namespace fea;\nusing namespace irr;\n*\/\nint main(int argc, char* argv[]) {\n \/\/ Create a Chrono::Engine physical system\n ChSystem my_system;\n\n \/\/ Create the Irrlicht visualization (open the Irrlicht device,\n \/\/ bind a simple user interface, etc. etc.)\n ChIrrApp application(&my_system, L\"Cables FEM (MKL)\", core::dimension2d(800, 600), false, true);\n\n \/\/ Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:\n application.AddTypicalLogo();\n application.AddTypicalSky();\n application.AddTypicalLights();\n application.AddTypicalCamera(core::vector3df(0.f, 0.6f, -1.f));\n\n \/\/ Create a mesh, that is a container for groups of elements and\n \/\/ their referenced nodes.\n auto my_mesh = std::make_shared();\n\n \/\/ Create the model (defined in FEAcables.h)\n model3(my_system, my_mesh);\n\n \/\/ Remember to add the mesh to the system!\n my_system.Add(my_mesh);\n\n \/\/ ==Asset== attach a visualization of the FEM mesh.\n \/\/ This will automatically update a triangle mesh (a ChTriangleMeshShape\n \/\/ asset that is internally managed) by setting proper\n \/\/ coordinates and vertex colours as in the FEM elements.\n \/\/ Such triangle mesh can be rendered by Irrlicht or POVray or whatever\n \/\/ postprocessor that can handle a coloured ChTriangleMeshShape).\n \/\/ Do not forget AddAsset() at the end!\n\n auto mvisualizebeamA = std::make_shared(*(my_mesh.get()));\n mvisualizebeamA->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_ELEM_BEAM_MZ);\n mvisualizebeamA->SetColorscaleMinMax(-0.4, 0.4);\n mvisualizebeamA->SetSmoothFaces(true);\n mvisualizebeamA->SetWireframe(false);\n my_mesh->AddAsset(mvisualizebeamA);\n\n auto mvisualizebeamC = std::make_shared(*(my_mesh.get()));\n mvisualizebeamC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_NODE_CSYS);\n mvisualizebeamC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NONE);\n mvisualizebeamC->SetSymbolsThickness(0.006);\n mvisualizebeamC->SetSymbolsScale(0.01);\n mvisualizebeamC->SetZbufferHide(false);\n my_mesh->AddAsset(mvisualizebeamC);\n\n \/\/ ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items\n \/\/ in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes.\n \/\/ If you need a finer control on which item really needs a visualization proxy in\n \/\/ Irrlicht, just use application.AssetBind(myitem); on a per-item basis.\n application.AssetBindAll();\n\n \/\/ ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets\n \/\/ that you added to the bodies into 3D shapes, they can be visualized by Irrlicht!\n application.AssetUpdateAll();\n\n \/\/ Mark completion of system construction\n my_system.SetupInitial();\n\n \/\/ Change solver to MKL\n ChSolverMKL<>* mkl_solver_stab = new ChSolverMKL<>;\n ChSolverMKL<>* mkl_solver_speed = new ChSolverMKL<>;\n my_system.ChangeSolverStab(mkl_solver_stab);\n my_system.ChangeSolverSpeed(mkl_solver_speed);\n\tmkl_solver_stab->SetSparsityPatternLock(true);\n\tmkl_solver_speed->SetSparsityPatternLock(true);\n application.GetSystem()->Update();\n\n \/\/ Change type of integrator:\n my_system.SetIntegrationType(chrono::ChSystem::INT_EULER_IMPLICIT_LINEARIZED); \/\/ fast, less precise\n \/\/ my_system.SetIntegrationType(chrono::ChSystem::INT_HHT); \/\/ precise,slower, might iterate each step\n\n \/\/ if later you want to change integrator settings:\n if (auto mystepper = std::dynamic_pointer_cast(my_system.GetTimestepper())) {\n mystepper->SetAlpha(-0.2);\n mystepper->SetMaxiters(2);\n mystepper->SetAbsTolerances(1e-6);\n }\n\n \/\/\n \/\/ THE SOFT-REAL-TIME CYCLE\n \/\/\n\n application.SetTimestep(0.01);\n\n while (application.GetDevice()->run()) {\n application.BeginScene();\n application.DrawAll();\n application.DoStep();\n application.EndScene();\n }\n\n return 0;\n}\ndemo_FEAcablesMKL cannot use sparsity pattern lock (Pardiso bug)\/\/\n\/\/ PROJECT CHRONO - http:\/\/projectchrono.org\n\/\/\n\/\/ Copyright (c) 2013 Project Chrono\n\/\/ All rights reserved.\n\/\/\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file at the top level of the distribution\n\/\/ and at http:\/\/projectchrono.org\/license-chrono.txt.\n\/\/\n\n\/\/\n\/\/ Demo code about\n\/\/\n\/\/ - FEA for 3D beams of 'cable' type (ANCF gradient-deficient beams)\n\/\/ uses the Chrono MKL module\n\n#include \"chrono\/timestepper\/ChTimestepper.h\"\n#include \"chrono_irrlicht\/ChIrrApp.h\"\n#include \"chrono_mkl\/ChSolverMKL.h\"\n\n#include \"FEAcables.h\"\n\/*\nusing namespace chrono;\nusing namespace fea;\nusing namespace irr;\n*\/\nint main(int argc, char* argv[]) {\n \/\/ Create a Chrono::Engine physical system\n ChSystem my_system;\n\n \/\/ Create the Irrlicht visualization (open the Irrlicht device,\n \/\/ bind a simple user interface, etc. etc.)\n ChIrrApp application(&my_system, L\"Cables FEM (MKL)\", core::dimension2d(800, 600), false, true);\n\n \/\/ Easy shortcuts to add camera, lights, logo and sky in Irrlicht scene:\n application.AddTypicalLogo();\n application.AddTypicalSky();\n application.AddTypicalLights();\n application.AddTypicalCamera(core::vector3df(0.f, 0.6f, -1.f));\n\n \/\/ Create a mesh, that is a container for groups of elements and\n \/\/ their referenced nodes.\n auto my_mesh = std::make_shared();\n\n \/\/ Create the model (defined in FEAcables.h)\n model3(my_system, my_mesh);\n\n \/\/ Remember to add the mesh to the system!\n my_system.Add(my_mesh);\n\n \/\/ ==Asset== attach a visualization of the FEM mesh.\n \/\/ This will automatically update a triangle mesh (a ChTriangleMeshShape\n \/\/ asset that is internally managed) by setting proper\n \/\/ coordinates and vertex colours as in the FEM elements.\n \/\/ Such triangle mesh can be rendered by Irrlicht or POVray or whatever\n \/\/ postprocessor that can handle a coloured ChTriangleMeshShape).\n \/\/ Do not forget AddAsset() at the end!\n\n auto mvisualizebeamA = std::make_shared(*(my_mesh.get()));\n mvisualizebeamA->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_ELEM_BEAM_MZ);\n mvisualizebeamA->SetColorscaleMinMax(-0.4, 0.4);\n mvisualizebeamA->SetSmoothFaces(true);\n mvisualizebeamA->SetWireframe(false);\n my_mesh->AddAsset(mvisualizebeamA);\n\n auto mvisualizebeamC = std::make_shared(*(my_mesh.get()));\n mvisualizebeamC->SetFEMglyphType(ChVisualizationFEAmesh::E_GLYPH_NODE_CSYS);\n mvisualizebeamC->SetFEMdataType(ChVisualizationFEAmesh::E_PLOT_NONE);\n mvisualizebeamC->SetSymbolsThickness(0.006);\n mvisualizebeamC->SetSymbolsScale(0.01);\n mvisualizebeamC->SetZbufferHide(false);\n my_mesh->AddAsset(mvisualizebeamC);\n\n \/\/ ==IMPORTANT!== Use this function for adding a ChIrrNodeAsset to all items\n \/\/ in the system. These ChIrrNodeAsset assets are 'proxies' to the Irrlicht meshes.\n \/\/ If you need a finer control on which item really needs a visualization proxy in\n \/\/ Irrlicht, just use application.AssetBind(myitem); on a per-item basis.\n application.AssetBindAll();\n\n \/\/ ==IMPORTANT!== Use this function for 'converting' into Irrlicht meshes the assets\n \/\/ that you added to the bodies into 3D shapes, they can be visualized by Irrlicht!\n application.AssetUpdateAll();\n\n \/\/ Mark completion of system construction\n my_system.SetupInitial();\n\n \/\/ Change solver to MKL\n auto mkl_solver_stab = new ChSolverMKL<>;\n auto mkl_solver_speed = new ChSolverMKL<>;\n my_system.ChangeSolverStab(mkl_solver_stab);\n my_system.ChangeSolverSpeed(mkl_solver_speed);\n\tmkl_solver_stab->SetSparsityPatternLock(false);\n\tmkl_solver_speed->SetSparsityPatternLock(false);\n \/\/ WARNING: due to known issues on MKL Pardiso, if CSR matrix is used, sparsity pattern lock should be put OFF\n \/\/ Look at ChCSR3Matrix::SetElement comments to further details.\n application.GetSystem()->Update();\n\n \/\/ Change type of integrator:\n my_system.SetIntegrationType(chrono::ChSystem::INT_EULER_IMPLICIT_LINEARIZED); \/\/ fast, less precise\n \/\/ my_system.SetIntegrationType(chrono::ChSystem::INT_HHT); \/\/ precise,slower, might iterate each step\n\n \/\/ if later you want to change integrator settings:\n if (auto mystepper = std::dynamic_pointer_cast(my_system.GetTimestepper())) {\n mystepper->SetAlpha(-0.2);\n mystepper->SetMaxiters(2);\n mystepper->SetAbsTolerances(1e-6);\n }\n\n \/\/\n \/\/ THE SOFT-REAL-TIME CYCLE\n \/\/\n\n application.SetTimestep(0.01);\n\n while (application.GetDevice()->run()) {\n application.BeginScene();\n application.DrawAll();\n application.DoStep();\n application.EndScene();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: layerupdatehandler.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: rt $ $Date: 2003-04-17 13:17:03 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \"layerupdatehandler.hxx\"\n\n#ifndef CONFIGMGR_BACKEND_LAYERUPDATEMERGER_HXX\n#include \"layerupdatemerger.hxx\"\n#endif\n\n#ifndef CONFIGMGR_API_FACTORY_HXX_\n#include \"confapifactory.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYEXISTEXCEPTION_HPP_\n#include \n#endif\n\n\/\/ -----------------------------------------------------------------------------\n#define OUSTR( str ) OUString( RTL_CONSTASCII_USTRINGPARAM( str ) )\n\/\/ -----------------------------------------------------------------------------\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace backend\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace backenduno = ::com::sun::star::configuration::backend;\n\/\/ -----------------------------------------------------------------------------\n\nuno::Reference< uno::XInterface > SAL_CALL instantiateUpdateMerger\n( CreationContext const& xContext )\n{\n return * new LayerUpdateHandler( xContext );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nLayerUpdateHandler::LayerUpdateHandler(CreationArg _xContext)\n: UpdateService(_xContext)\n, m_aBuilder()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nLayerUpdateHandler::~LayerUpdateHandler()\n{\n}\n\/\/ -----------------------------------------------------------------------------\ninline\nvoid LayerUpdateHandler::checkBuilder(bool _bForProperty)\n{\n if ( m_aBuilder.isEmpty() )\n raiseMalformedDataException(\"LayerUpdateHandler: Illegal operation - no update is in progress\");\n\n if ( !m_aBuilder.isActive() )\n raiseMalformedDataException(\"LayerUpdateHandler: Illegal operation - no context for update available\");\n\n if ( m_aBuilder.isPropertyActive() != _bForProperty )\n raiseMalformedDataException(\"LayerUpdateHandler: Illegal operation - a property is in progress\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raiseMalformedDataException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n throw backenduno::MalformedDataException(sMsg,*this,uno::Any());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raiseNodeChangedBeforeException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n throw backenduno::MalformedDataException(sMsg,*this,uno::Any());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raisePropChangedBeforeException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n throw backenduno::MalformedDataException(sMsg,*this,uno::Any());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raisePropExistsException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n com::sun::star::beans::PropertyExistException e(sMsg,*this);\n\n throw backenduno::MalformedDataException(sMsg,*this, uno::makeAny(e));\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ XUpdateHandler\nvoid SAL_CALL\n LayerUpdateHandler::startUpdate( )\n throw ( MalformedDataException, lang::IllegalAccessException,\n lang::WrappedTargetException, uno::RuntimeException)\n{\n this->checkSourceLayer();\n if (!m_aBuilder.init())\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot start update - update is already in progress\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::endUpdate( )\n throw ( MalformedDataException, lang::IllegalAccessException,\n lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.finish())\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot finish update - a node is still open.\");\n\n uno::Reference< backenduno::XLayer > xMergedLayer( LayerUpdateMerger::getMergedLayer(this->getSourceLayer(), m_aBuilder.result()) );\n\n m_aBuilder.clear();\n\n this->writeUpdatedLayer(xMergedLayer);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::modifyNode( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, sal_Bool bReset )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.modifyNode(aName,aAttributes,aAttributeMask,bReset))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot start node modification - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.replaceNode(aName,aAttributes,NULL))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot start added\/replaced node - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplaceNodeFromTemplate( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aTemplate )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.replaceNode(aName,aAttributes,&aTemplate))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot start added\/replaced node - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::endNode( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.finishNode())\n {\n OSL_ENSURE(m_aBuilder.isPropertyActive() || !m_aBuilder.isActive(), \"LayerUpdateHandler: Unexpected failure mode for finishNode\");\n if (m_aBuilder.isPropertyActive())\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot finish node update - open property has not been ended.\");\n else\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot finish node update - no node has been started.\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::removeNode( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.removeNode(aName))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot remove node - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler:: modifyProperty( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, const uno::Type & aType )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(false);\n\n if (!m_aBuilder.modifyProperty(aName,aAttributes,aAttributeMask, aType))\n raisePropChangedBeforeException(\"LayerUpdateHandler: Cannot start property modification - property has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler:: setPropertyValue( const uno::Any& aValue )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.setPropertyValue(aValue) );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler:: setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.setPropertyValueForLocale(aValue,aLocale) );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::resetPropertyValue( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.resetPropertyValue() );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::resetPropertyValueForLocale( const OUString& aLocale )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.resetPropertyValueForLocale(aLocale) );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::endProperty( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY ( m_aBuilder.finishProperty() );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::resetProperty( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if (!m_aBuilder.resetProperty(aName))\n raisePropChangedBeforeException(\"LayerUpdateHandler: Cannot reset property - property has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplaceProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if (!m_aBuilder.addNullProperty(aName,aAttributes,aType))\n raisePropExistsException(\"LayerUpdateHandler: Cannot add property - property exists (and has already been changed).\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplacePropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if (!m_aBuilder.addProperty(aName,aAttributes,aValue))\n raisePropExistsException(\"LayerUpdateHandler: Cannot add property - property exists (and has already been changed).\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::removeProperty( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n \/\/ treat 'remove' as 'reset'. (Note: does not verify that this actually amounts to dropping the property)\n if (!m_aBuilder.resetProperty(aName))\n raisePropChangedBeforeException(\"LayerUpdateHandler: Cannot remove property - property has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n } \/\/ namespace\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n\nINTEGRATION: CWS ooo19126 (1.9.180); FILE MERGED 2005\/09\/05 17:04:01 rt 1.9.180.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: layerupdatehandler.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 03:31:49 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"layerupdatehandler.hxx\"\n\n#ifndef CONFIGMGR_BACKEND_LAYERUPDATEMERGER_HXX\n#include \"layerupdatemerger.hxx\"\n#endif\n\n#ifndef CONFIGMGR_API_FACTORY_HXX_\n#include \"confapifactory.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYERHANDLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_CONFIGURATION_BACKEND_XLAYER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_BEANS_PROPERTYEXISTEXCEPTION_HPP_\n#include \n#endif\n\n\/\/ -----------------------------------------------------------------------------\n#define OUSTR( str ) OUString( RTL_CONSTASCII_USTRINGPARAM( str ) )\n\/\/ -----------------------------------------------------------------------------\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace backend\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace lang = ::com::sun::star::lang;\n namespace backenduno = ::com::sun::star::configuration::backend;\n\/\/ -----------------------------------------------------------------------------\n\nuno::Reference< uno::XInterface > SAL_CALL instantiateUpdateMerger\n( CreationContext const& xContext )\n{\n return * new LayerUpdateHandler( xContext );\n}\n\n\/\/ -----------------------------------------------------------------------------\n\nLayerUpdateHandler::LayerUpdateHandler(CreationArg _xContext)\n: UpdateService(_xContext)\n, m_aBuilder()\n{\n}\n\/\/ -----------------------------------------------------------------------------\n\nLayerUpdateHandler::~LayerUpdateHandler()\n{\n}\n\/\/ -----------------------------------------------------------------------------\ninline\nvoid LayerUpdateHandler::checkBuilder(bool _bForProperty)\n{\n if ( m_aBuilder.isEmpty() )\n raiseMalformedDataException(\"LayerUpdateHandler: Illegal operation - no update is in progress\");\n\n if ( !m_aBuilder.isActive() )\n raiseMalformedDataException(\"LayerUpdateHandler: Illegal operation - no context for update available\");\n\n if ( m_aBuilder.isPropertyActive() != _bForProperty )\n raiseMalformedDataException(\"LayerUpdateHandler: Illegal operation - a property is in progress\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raiseMalformedDataException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n throw backenduno::MalformedDataException(sMsg,*this,uno::Any());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raiseNodeChangedBeforeException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n throw backenduno::MalformedDataException(sMsg,*this,uno::Any());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raisePropChangedBeforeException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n throw backenduno::MalformedDataException(sMsg,*this,uno::Any());\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid LayerUpdateHandler::raisePropExistsException(sal_Char const * pMsg)\n{\n OUString sMsg = OUString::createFromAscii(pMsg);\n com::sun::star::beans::PropertyExistException e(sMsg,*this);\n\n throw backenduno::MalformedDataException(sMsg,*this, uno::makeAny(e));\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ XUpdateHandler\nvoid SAL_CALL\n LayerUpdateHandler::startUpdate( )\n throw ( MalformedDataException, lang::IllegalAccessException,\n lang::WrappedTargetException, uno::RuntimeException)\n{\n this->checkSourceLayer();\n if (!m_aBuilder.init())\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot start update - update is already in progress\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::endUpdate( )\n throw ( MalformedDataException, lang::IllegalAccessException,\n lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.finish())\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot finish update - a node is still open.\");\n\n uno::Reference< backenduno::XLayer > xMergedLayer( LayerUpdateMerger::getMergedLayer(this->getSourceLayer(), m_aBuilder.result()) );\n\n m_aBuilder.clear();\n\n this->writeUpdatedLayer(xMergedLayer);\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::modifyNode( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, sal_Bool bReset )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.modifyNode(aName,aAttributes,aAttributeMask,bReset))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot start node modification - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplaceNode( const OUString& aName, sal_Int16 aAttributes )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.replaceNode(aName,aAttributes,NULL))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot start added\/replaced node - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplaceNodeFromTemplate( const OUString& aName, sal_Int16 aAttributes, const TemplateIdentifier& aTemplate )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.replaceNode(aName,aAttributes,&aTemplate))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot start added\/replaced node - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::endNode( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.finishNode())\n {\n OSL_ENSURE(m_aBuilder.isPropertyActive() || !m_aBuilder.isActive(), \"LayerUpdateHandler: Unexpected failure mode for finishNode\");\n if (m_aBuilder.isPropertyActive())\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot finish node update - open property has not been ended.\");\n else\n raiseMalformedDataException(\"LayerUpdateHandler: Cannot finish node update - no node has been started.\");\n }\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::removeNode( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder();\n\n if (!m_aBuilder.removeNode(aName))\n raiseNodeChangedBeforeException(\"LayerUpdateHandler: Cannot remove node - node has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler:: modifyProperty( const OUString& aName, sal_Int16 aAttributes, sal_Int16 aAttributeMask, const uno::Type & aType )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(false);\n\n if (!m_aBuilder.modifyProperty(aName,aAttributes,aAttributeMask, aType))\n raisePropChangedBeforeException(\"LayerUpdateHandler: Cannot start property modification - property has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler:: setPropertyValue( const uno::Any& aValue )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.setPropertyValue(aValue) );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler:: setPropertyValueForLocale( const uno::Any& aValue, const OUString& aLocale )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.setPropertyValueForLocale(aValue,aLocale) );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::resetPropertyValue( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.resetPropertyValue() );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::resetPropertyValueForLocale( const OUString& aLocale )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY( m_aBuilder.resetPropertyValueForLocale(aLocale) );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::endProperty( )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n checkBuilder(true); \/\/ already checks for open property\n\n OSL_VERIFY ( m_aBuilder.finishProperty() );\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::resetProperty( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if (!m_aBuilder.resetProperty(aName))\n raisePropChangedBeforeException(\"LayerUpdateHandler: Cannot reset property - property has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplaceProperty( const OUString& aName, sal_Int16 aAttributes, const uno::Type& aType )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if (!m_aBuilder.addNullProperty(aName,aAttributes,aType))\n raisePropExistsException(\"LayerUpdateHandler: Cannot add property - property exists (and has already been changed).\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::addOrReplacePropertyWithValue( const OUString& aName, sal_Int16 aAttributes, const uno::Any& aValue )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n if (!m_aBuilder.addProperty(aName,aAttributes,aValue))\n raisePropExistsException(\"LayerUpdateHandler: Cannot add property - property exists (and has already been changed).\");\n}\n\/\/ -----------------------------------------------------------------------------\n\nvoid SAL_CALL\n LayerUpdateHandler::removeProperty( const OUString& aName )\n throw (MalformedDataException, lang::WrappedTargetException, uno::RuntimeException)\n{\n \/\/ treat 'remove' as 'reset'. (Note: does not verify that this actually amounts to dropping the property)\n if (!m_aBuilder.resetProperty(aName))\n raisePropChangedBeforeException(\"LayerUpdateHandler: Cannot remove property - property has already been changed.\");\n}\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ -----------------------------------------------------------------------------\n } \/\/ namespace\n\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MServices.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: vg $ $Date: 2007-10-15 12:31:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"MDriver.hxx\"\n#ifndef _CPPUHELPER_FACTORY_HXX_\n#include \n#endif\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n#ifndef _COM_SUN_STAR_MOZILLA_XMOZILLABOOTSTRAP_HPP_\n#include \n#endif\n#ifndef CONNECTIVITY_SMOZILLABOOTSTRAP_HXX\n#include \"bootstrap\/MMozillaBootstrap.hxx\"\n#endif\n\nusing namespace connectivity::mozab;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::registry::XRegistryKey;\nusing ::com::sun::star::lang::XSingleServiceFactory;\nusing ::com::sun::star::lang::XMultiServiceFactory;\nusing ::com::sun::star::mozilla::XMozillaBootstrap;\n\ntypedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)\n (\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ::cppu::ComponentInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames,\n rtl_ModuleCount* _pTemp\n );\n\n\/\/***************************************************************************************\n\/\/\n\/\/ Die vorgeschriebene C-Api muss erfuellt werden!\n\/\/ Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.\n\/\/\n\n\/\/---------------------------------------------------------------------------------------\nvoid REGISTER_PROVIDER(\n const OUString& aServiceImplName,\n const Sequence< OUString>& Services,\n const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)\n{\n OUString aMainKeyName;\n aMainKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\"));\n aMainKeyName += aServiceImplName;\n aMainKeyName += OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/UNO\/SERVICES\"));\n\n Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );\n OSL_ENSURE(xNewKey.is(), \"MOZAB::component_writeInfo : could not create a registry key !\");\n\n for (sal_Int32 i=0; icreateKey(Services[i]);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\nstruct ProviderRequest\n{\n Reference< XSingleServiceFactory > xRet;\n Reference< XMultiServiceFactory > const xServiceManager;\n OUString const sImplementationName;\n\n ProviderRequest(\n void* pServiceManager,\n sal_Char const* pImplementationName\n )\n : xServiceManager(reinterpret_cast(pServiceManager))\n , sImplementationName(OUString::createFromAscii(pImplementationName))\n {\n }\n\n inline\n sal_Bool CREATE_PROVIDER(\n const OUString& Implname,\n const Sequence< OUString > & Services,\n ::cppu::ComponentInstantiation Factory,\n createFactoryFunc creator\n )\n {\n if (!xRet.is() && (Implname == sImplementationName))\n try\n {\n xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);\n }\n catch(...)\n {\n }\n return xRet.is();\n }\n\n void* getProvider() const { return xRet.get(); }\n};\n\n\/\/---------------------------------------------------------------------------------------\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char **ppEnvTypeName,\n uno_Environment ** \/*ppEnv*\/\n )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void* \/*pServiceManager*\/,\n void* pRegistryKey\n )\n{\n if (pRegistryKey)\n try\n {\n Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));\n\n\n REGISTER_PROVIDER(\n MozabDriver::getImplementationName_Static(),\n MozabDriver::getSupportedServiceNames_Static(), xKey);\n\n Sequence< ::rtl::OUString > aSNS( 1 );\n aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.mozilla.MozillaBootstrap\"));\n REGISTER_PROVIDER(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.mozilla.MozillaBootstrap\")),\n aSNS, xKey);\n\n return sal_True;\n }\n catch (::com::sun::star::registry::InvalidRegistryException& )\n {\n OSL_ENSURE(sal_False, \"Mozab::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !\");\n }\n\n return sal_False;\n}\ntypedef void* (SAL_CALL * OMozillaBootstrap_CreateInstanceFunction)(const Reference< XMultiServiceFactory >& _rxFactory );\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createMozillaBootstrap(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )\n{\n const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(SAL_MODULENAME( \"mozabdrv2\" ));\n\n \/\/ load the dbtools library\n oslModule s_hModule = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >(&createMozillaBootstrap),\n sModuleName.pData, 0);\n OSL_ENSURE(NULL != s_hModule, \"MozabDriver::registerClient: could not load the dbtools library!\");\n if (NULL != s_hModule)\n {\n\n \/\/ get the symbol for the method creating the factory\n const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"OMozillaBootstrap_CreateInstance\"));\n \/\/ reinterpret_cast removed GNU C\n OMozillaBootstrap_CreateInstanceFunction s_pCreationFunc = (OMozillaBootstrap_CreateInstanceFunction)osl_getFunctionSymbol(s_hModule, sFactoryCreationFunc.pData);\n\n if (NULL == s_pCreationFunc)\n { \/\/ did not find the symbol\n OSL_ENSURE(sal_False, \"MozabDriver::registerClient: could not find the symbol for creating the factory!\");\n osl_unloadModule(s_hModule);\n s_hModule = NULL;\n }\n MozillaBootstrap * pBootstrap = reinterpret_cast((*s_pCreationFunc)(_rxFactory));\n return *pBootstrap;\n }\n return NULL;\n}\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" void* SAL_CALL component_getFactory(\n const sal_Char* pImplementationName,\n void* pServiceManager,\n void* \/*pRegistryKey*\/)\n{\n void* pRet = 0;\n if (pServiceManager)\n {\n OUString aImplName( OUString::createFromAscii( pImplementationName ) );\n ProviderRequest aReq(pServiceManager,pImplementationName);\n if (aImplName.equals( MozabDriver::getImplementationName_Static() ))\n {\n aReq.CREATE_PROVIDER(\n MozabDriver::getImplementationName_Static(),\n MozabDriver::getSupportedServiceNames_Static(),\n MozabDriver_CreateInstance, ::cppu::createSingleFactory);\n }\n else if (aImplName.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.mozilla.MozillaBootstrap\")) ))\n {\n Sequence< ::rtl::OUString > aSNS( 1 );\n aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.mozilla.MozillaBootstrap\"));\n aReq.CREATE_PROVIDER(\n aImplName,\n aSNS,\n createMozillaBootstrap, ::cppu::createSingleFactory);\n }\n if(aReq.xRet.is())\n aReq.xRet->acquire();\n pRet = aReq.getProvider();\n }\n\n return pRet;\n};\n\n\nINTEGRATION: CWS changefileheader (1.7.78); FILE MERGED 2008\/04\/01 15:08:58 thb 1.7.78.3: #i85898# Stripping all external header guards 2008\/04\/01 10:53:11 thb 1.7.78.2: #i85898# Stripping all external header guards 2008\/03\/28 15:23:51 rt 1.7.78.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: MServices.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_connectivity.hxx\"\n\n#include \"MDriver.hxx\"\n#include \n#include \n#include \n#include \"bootstrap\/MMozillaBootstrap.hxx\"\n\nusing namespace connectivity::mozab;\nusing ::rtl::OUString;\nusing ::com::sun::star::uno::Reference;\nusing ::com::sun::star::uno::Sequence;\nusing ::com::sun::star::registry::XRegistryKey;\nusing ::com::sun::star::lang::XSingleServiceFactory;\nusing ::com::sun::star::lang::XMultiServiceFactory;\nusing ::com::sun::star::mozilla::XMozillaBootstrap;\n\ntypedef Reference< XSingleServiceFactory > (SAL_CALL *createFactoryFunc)\n (\n const Reference< XMultiServiceFactory > & rServiceManager,\n const OUString & rComponentName,\n ::cppu::ComponentInstantiation pCreateFunction,\n const Sequence< OUString > & rServiceNames,\n rtl_ModuleCount* _pTemp\n );\n\n\/\/***************************************************************************************\n\/\/\n\/\/ Die vorgeschriebene C-Api muss erfuellt werden!\n\/\/ Sie besteht aus drei Funktionen, die von dem Modul exportiert werden muessen.\n\/\/\n\n\/\/---------------------------------------------------------------------------------------\nvoid REGISTER_PROVIDER(\n const OUString& aServiceImplName,\n const Sequence< OUString>& Services,\n const Reference< ::com::sun::star::registry::XRegistryKey > & xKey)\n{\n OUString aMainKeyName;\n aMainKeyName = OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/\"));\n aMainKeyName += aServiceImplName;\n aMainKeyName += OUString( RTL_CONSTASCII_USTRINGPARAM(\"\/UNO\/SERVICES\"));\n\n Reference< ::com::sun::star::registry::XRegistryKey > xNewKey( xKey->createKey(aMainKeyName) );\n OSL_ENSURE(xNewKey.is(), \"MOZAB::component_writeInfo : could not create a registry key !\");\n\n for (sal_Int32 i=0; icreateKey(Services[i]);\n}\n\n\n\/\/---------------------------------------------------------------------------------------\nstruct ProviderRequest\n{\n Reference< XSingleServiceFactory > xRet;\n Reference< XMultiServiceFactory > const xServiceManager;\n OUString const sImplementationName;\n\n ProviderRequest(\n void* pServiceManager,\n sal_Char const* pImplementationName\n )\n : xServiceManager(reinterpret_cast(pServiceManager))\n , sImplementationName(OUString::createFromAscii(pImplementationName))\n {\n }\n\n inline\n sal_Bool CREATE_PROVIDER(\n const OUString& Implname,\n const Sequence< OUString > & Services,\n ::cppu::ComponentInstantiation Factory,\n createFactoryFunc creator\n )\n {\n if (!xRet.is() && (Implname == sImplementationName))\n try\n {\n xRet = creator( xServiceManager, sImplementationName,Factory, Services,0);\n }\n catch(...)\n {\n }\n return xRet.is();\n }\n\n void* getProvider() const { return xRet.get(); }\n};\n\n\/\/---------------------------------------------------------------------------------------\n\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char **ppEnvTypeName,\n uno_Environment ** \/*ppEnv*\/\n )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void* \/*pServiceManager*\/,\n void* pRegistryKey\n )\n{\n if (pRegistryKey)\n try\n {\n Reference< ::com::sun::star::registry::XRegistryKey > xKey(reinterpret_cast< ::com::sun::star::registry::XRegistryKey*>(pRegistryKey));\n\n\n REGISTER_PROVIDER(\n MozabDriver::getImplementationName_Static(),\n MozabDriver::getSupportedServiceNames_Static(), xKey);\n\n Sequence< ::rtl::OUString > aSNS( 1 );\n aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.mozilla.MozillaBootstrap\"));\n REGISTER_PROVIDER(\n ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.mozilla.MozillaBootstrap\")),\n aSNS, xKey);\n\n return sal_True;\n }\n catch (::com::sun::star::registry::InvalidRegistryException& )\n {\n OSL_ENSURE(sal_False, \"Mozab::component_writeInfo : could not create a registry key ! ## InvalidRegistryException !\");\n }\n\n return sal_False;\n}\ntypedef void* (SAL_CALL * OMozillaBootstrap_CreateInstanceFunction)(const Reference< XMultiServiceFactory >& _rxFactory );\n::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface > SAL_CALL createMozillaBootstrap(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rxFactory) throw( ::com::sun::star::uno::Exception )\n{\n const ::rtl::OUString sModuleName = ::rtl::OUString::createFromAscii(SAL_MODULENAME( \"mozabdrv2\" ));\n\n \/\/ load the dbtools library\n oslModule s_hModule = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >(&createMozillaBootstrap),\n sModuleName.pData, 0);\n OSL_ENSURE(NULL != s_hModule, \"MozabDriver::registerClient: could not load the dbtools library!\");\n if (NULL != s_hModule)\n {\n\n \/\/ get the symbol for the method creating the factory\n const ::rtl::OUString sFactoryCreationFunc = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"OMozillaBootstrap_CreateInstance\"));\n \/\/ reinterpret_cast removed GNU C\n OMozillaBootstrap_CreateInstanceFunction s_pCreationFunc = (OMozillaBootstrap_CreateInstanceFunction)osl_getFunctionSymbol(s_hModule, sFactoryCreationFunc.pData);\n\n if (NULL == s_pCreationFunc)\n { \/\/ did not find the symbol\n OSL_ENSURE(sal_False, \"MozabDriver::registerClient: could not find the symbol for creating the factory!\");\n osl_unloadModule(s_hModule);\n s_hModule = NULL;\n }\n MozillaBootstrap * pBootstrap = reinterpret_cast((*s_pCreationFunc)(_rxFactory));\n return *pBootstrap;\n }\n return NULL;\n}\n\/\/---------------------------------------------------------------------------------------\nextern \"C\" void* SAL_CALL component_getFactory(\n const sal_Char* pImplementationName,\n void* pServiceManager,\n void* \/*pRegistryKey*\/)\n{\n void* pRet = 0;\n if (pServiceManager)\n {\n OUString aImplName( OUString::createFromAscii( pImplementationName ) );\n ProviderRequest aReq(pServiceManager,pImplementationName);\n if (aImplName.equals( MozabDriver::getImplementationName_Static() ))\n {\n aReq.CREATE_PROVIDER(\n MozabDriver::getImplementationName_Static(),\n MozabDriver::getSupportedServiceNames_Static(),\n MozabDriver_CreateInstance, ::cppu::createSingleFactory);\n }\n else if (aImplName.equals( ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.comp.mozilla.MozillaBootstrap\")) ))\n {\n Sequence< ::rtl::OUString > aSNS( 1 );\n aSNS[0] = ::rtl::OUString( RTL_CONSTASCII_USTRINGPARAM(\"com.sun.star.mozilla.MozillaBootstrap\"));\n aReq.CREATE_PROVIDER(\n aImplName,\n aSNS,\n createMozillaBootstrap, ::cppu::createSingleFactory);\n }\n if(aReq.xRet.is())\n aReq.xRet->acquire();\n pRet = aReq.getProvider();\n }\n\n return pRet;\n};\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stringtransfer.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: hr $ $Date: 2007-06-27 21:52:16 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n\n#ifndef _SVTOOLS_STRINGTRANSFER_HXX_\n#include \n#endif\n\n\/\/........................................................................\nnamespace svt\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::datatransfer;\n\n \/\/====================================================================\n \/\/= OStringTransferable\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OStringTransferable::OStringTransferable(const ::rtl::OUString& _rContent)\n :TransferableHelper()\n ,m_sContent( _rContent )\n {\n }\n\n \/\/--------------------------------------------------------------------\n void OStringTransferable::AddSupportedFormats()\n {\n AddFormat(SOT_FORMAT_STRING);\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OStringTransferable::GetData( const DataFlavor& _rFlavor )\n {\n sal_uInt32 nFormat = SotExchange::GetFormat( _rFlavor );\n if (SOT_FORMAT_STRING == nFormat)\n return SetString( m_sContent, _rFlavor );\n\n return sal_False;\n }\n\n \/\/====================================================================\n \/\/= OStringTransfer\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n void OStringTransfer::CopyString( const ::rtl::OUString& _rContent, Window* _pWindow )\n {\n OStringTransferable* pTransferable = new OStringTransferable( _rContent );\n Reference< XTransferable > xTransfer = pTransferable;\n pTransferable->CopyToClipboard( _pWindow );\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OStringTransfer::PasteString( ::rtl::OUString& _rContent, Window* _pWindow )\n {\n TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow );\n\n \/\/ check for a string format\n const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector();\n for ( DataFlavorExVector::const_iterator aSearch = rFormats.begin();\n aSearch != rFormats.end();\n ++aSearch\n )\n {\n if (SOT_FORMAT_STRING == aSearch->mnSotId)\n {\n String sContent;\n sal_Bool bSuccess = aClipboardData.GetString( SOT_FORMAT_STRING, sContent );\n _rContent = sContent;\n return bSuccess;\n }\n }\n\n return sal_False;\n }\n\n \/\/--------------------------------------------------------------------\n void OStringTransfer::StartStringDrag( const ::rtl::OUString& _rContent, Window* _pWindow, sal_Int8 _nDragSourceActions )\n {\n OStringTransferable* pTransferable = new OStringTransferable( _rContent );\n Reference< XTransferable > xTransfer = pTransferable;\n pTransferable->StartDrag(_pWindow, _nDragSourceActions);\n }\n\n\/\/........................................................................\n} \/\/ namespace svt\n\/\/........................................................................\n\nINTEGRATION: CWS changefileheader (1.7.246); FILE MERGED 2008\/04\/01 12:43:48 thb 1.7.246.2: #i85898# Stripping all external header guards 2008\/03\/31 13:02:17 rt 1.7.246.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: stringtransfer.cxx,v $\n * $Revision: 1.8 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svtools.hxx\"\n#include \n\n\/\/........................................................................\nnamespace svt\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::datatransfer;\n\n \/\/====================================================================\n \/\/= OStringTransferable\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OStringTransferable::OStringTransferable(const ::rtl::OUString& _rContent)\n :TransferableHelper()\n ,m_sContent( _rContent )\n {\n }\n\n \/\/--------------------------------------------------------------------\n void OStringTransferable::AddSupportedFormats()\n {\n AddFormat(SOT_FORMAT_STRING);\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OStringTransferable::GetData( const DataFlavor& _rFlavor )\n {\n sal_uInt32 nFormat = SotExchange::GetFormat( _rFlavor );\n if (SOT_FORMAT_STRING == nFormat)\n return SetString( m_sContent, _rFlavor );\n\n return sal_False;\n }\n\n \/\/====================================================================\n \/\/= OStringTransfer\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n void OStringTransfer::CopyString( const ::rtl::OUString& _rContent, Window* _pWindow )\n {\n OStringTransferable* pTransferable = new OStringTransferable( _rContent );\n Reference< XTransferable > xTransfer = pTransferable;\n pTransferable->CopyToClipboard( _pWindow );\n }\n\n \/\/--------------------------------------------------------------------\n sal_Bool OStringTransfer::PasteString( ::rtl::OUString& _rContent, Window* _pWindow )\n {\n TransferableDataHelper aClipboardData = TransferableDataHelper::CreateFromSystemClipboard( _pWindow );\n\n \/\/ check for a string format\n const DataFlavorExVector& rFormats = aClipboardData.GetDataFlavorExVector();\n for ( DataFlavorExVector::const_iterator aSearch = rFormats.begin();\n aSearch != rFormats.end();\n ++aSearch\n )\n {\n if (SOT_FORMAT_STRING == aSearch->mnSotId)\n {\n String sContent;\n sal_Bool bSuccess = aClipboardData.GetString( SOT_FORMAT_STRING, sContent );\n _rContent = sContent;\n return bSuccess;\n }\n }\n\n return sal_False;\n }\n\n \/\/--------------------------------------------------------------------\n void OStringTransfer::StartStringDrag( const ::rtl::OUString& _rContent, Window* _pWindow, sal_Int8 _nDragSourceActions )\n {\n OStringTransferable* pTransferable = new OStringTransferable( _rContent );\n Reference< XTransferable > xTransfer = pTransferable;\n pTransferable->StartDrag(_pWindow, _nDragSourceActions);\n }\n\n\/\/........................................................................\n} \/\/ namespace svt\n\/\/........................................................................\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: displayinfo.cxx,v $\n * $Revision: 1.15 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ALL_GHOSTED_DRAWMODES (DRAWMODE_GHOSTEDLINE|DRAWMODE_GHOSTEDFILL|DRAWMODE_GHOSTEDTEXT|DRAWMODE_GHOSTEDBITMAP|DRAWMODE_GHOSTEDGRADIENT)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace contact\n {\n \/\/ This uses Application::AnyInput() and may change mbContinuePaint\n \/\/ to interrupt the paint\n void DisplayInfo::CheckContinuePaint()\n {\n \/\/ #111111#\n \/\/ INPUT_PAINT and INPUT_TIMER removed again since this leads to\n \/\/ problems under Linux and Solaris when painting slow objects\n \/\/ (e.g. bitmaps)\n\n \/\/ #114335#\n \/\/ INPUT_OTHER removed too, leads to problems with added controls\n \/\/ from the form layer.\n#ifndef SOLARIS\n if(Application::AnyInput(INPUT_KEYBOARD))\n {\n mbContinuePaint = sal_False;\n }\n#endif\n }\n\n DisplayInfo::DisplayInfo(SdrPageView* pPageView)\n : mpPageView(pPageView),\n mpProcessedPage(0L),\n mpLastDisplayInfo(0L),\n maProcessLayers(sal_True), \/\/ init layer info with all bits set to draw everything on default\n mpOutputDevice(0L),\n mpExtOutputDevice(0L),\n mpPaintInfoRec(0L),\n mpRootVOC(0L),\n mbControlLayerPainting(sal_False),\n mbPagePainting(sal_True),\n mbGhostedDrawModeActive(sal_False),\n mbBufferingAllowed(sal_True),\n mbContinuePaint(sal_True),\n mbMasterPagePainting(sal_False)\n {\n }\n\n DisplayInfo::~DisplayInfo()\n {\n SetProcessedPage( 0L );\n }\n\n \/\/ access to ProcessedPage, write for internal use only.\n void DisplayInfo::SetProcessedPage(SdrPage* pNew)\n {\n if(pNew != mpProcessedPage)\n {\n mpProcessedPage = pNew;\n\n if(mpPageView)\n {\n if( pNew == NULL )\n {\n \/\/ DisplayInfo needs to be reset at PageView if set since DisplayInfo is no longer valid\n if(mpPageView && mpPageView->GetCurrentPaintingDisplayInfo())\n {\n DBG_ASSERT( mpPageView->GetCurrentPaintingDisplayInfo() == this, \"DisplayInfo::~DisplayInfo() : stack error!\" );\n\n \/\/ restore remembered DisplayInfo to build a stack, or delete\n mpPageView->SetCurrentPaintingDisplayInfo(mpLastDisplayInfo);\n }\n }\n else\n {\n \/\/ rescue current\n mpLastDisplayInfo = mpPageView->GetCurrentPaintingDisplayInfo();\n\n \/\/ set at PageView when a page is set\n mpPageView->SetCurrentPaintingDisplayInfo(this);\n }\n }\n }\n }\n\n const SdrPage* DisplayInfo::GetProcessedPage() const\n {\n return mpProcessedPage;\n }\n\n \/\/ Access to LayerInfos (which layers to proccess)\n void DisplayInfo::SetProcessLayers(const SetOfByte& rSet)\n {\n maProcessLayers = rSet;\n }\n\n const SetOfByte& DisplayInfo::GetProcessLayers() const\n {\n return maProcessLayers;\n }\n\n \/\/ access to ExtendedOutputDevice\n void DisplayInfo::SetExtendedOutputDevice(XOutputDevice* pExtOut)\n {\n if(mpExtOutputDevice != pExtOut)\n {\n mpExtOutputDevice = pExtOut;\n }\n }\n\n XOutputDevice* DisplayInfo::GetExtendedOutputDevice() const\n {\n return mpExtOutputDevice;\n }\n\n \/\/ access to PaintInfoRec\n void DisplayInfo::SetPaintInfoRec(SdrPaintInfoRec* pInfoRec)\n {\n if(mpPaintInfoRec != pInfoRec)\n {\n mpPaintInfoRec = pInfoRec;\n }\n }\n\n SdrPaintInfoRec* DisplayInfo::GetPaintInfoRec() const\n {\n return mpPaintInfoRec;\n }\n\n \/\/ access to OutputDevice\n void DisplayInfo::SetOutputDevice(OutputDevice* pOutDev)\n {\n if(mpOutputDevice != pOutDev)\n {\n mpOutputDevice = pOutDev;\n }\n }\n\n OutputDevice* DisplayInfo::GetOutputDevice() const\n {\n return mpOutputDevice;\n }\n\n \/\/ access to RedrawArea\n void DisplayInfo::SetRedrawArea(const Region& rRegion)\n {\n maRedrawArea = rRegion;\n }\n\n const Region& DisplayInfo::GetRedrawArea() const\n {\n return maRedrawArea;\n }\n\n \/\/ Is OutDev a printer?\n sal_Bool DisplayInfo::OutputToPrinter() const\n {\n if(mpOutputDevice && OUTDEV_PRINTER == mpOutputDevice->GetOutDevType())\n {\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/ Is OutDev a window?\n sal_Bool DisplayInfo::OutputToWindow() const\n {\n if(mpOutputDevice && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType())\n {\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/ Is OutDev a VirtualDevice?\n sal_Bool DisplayInfo::OutputToVirtualDevice() const\n {\n if(mpOutputDevice && OUTDEV_VIRDEV == mpOutputDevice->GetOutDevType())\n {\n return sal_True;\n }\n\n return sal_False;\n }\n\n \/\/ Is OutDev a recording MetaFile?\n sal_Bool DisplayInfo::OutputToRecordingMetaFile() const\n {\n if(mpOutputDevice)\n {\n GDIMetaFile* pMetaFile = mpOutputDevice->GetConnectMetaFile();\n\n if(pMetaFile)\n {\n sal_Bool bRecording = pMetaFile->IsRecord() && !pMetaFile->IsPause();\n return bRecording;\n }\n }\n\n return sal_False;\n }\n\n void DisplayInfo::SetControlLayerPainting(sal_Bool bDoPaint)\n {\n if(mbControlLayerPainting != bDoPaint)\n {\n mbControlLayerPainting = bDoPaint;\n }\n }\n\n sal_Bool DisplayInfo::GetControlLayerPainting() const\n {\n return mbControlLayerPainting;\n }\n\n void DisplayInfo::SetPagePainting(sal_Bool bDoPaint)\n {\n if(mbPagePainting != bDoPaint)\n {\n mbPagePainting = bDoPaint;\n }\n }\n\n sal_Bool DisplayInfo::GetPagePainting() const\n {\n return mbPagePainting;\n }\n\n \/\/ Access to svtools::ColorConfig\n const svtools::ColorConfig& DisplayInfo::GetColorConfig() const\n {\n return maColorConfig;\n }\n\n sal_uInt32 DisplayInfo::GetOriginalDrawMode() const\n {\n \/\/ return DrawMode without ghosted stuff\n if(mpOutputDevice)\n {\n return (mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES);\n }\n\n return 0L;\n }\n\n sal_uInt32 DisplayInfo::GetCurrentDrawMode() const\n {\n if(mpOutputDevice)\n {\n return mpOutputDevice->GetDrawMode();\n }\n\n return 0L;\n }\n\n void DisplayInfo::ClearGhostedDrawMode()\n {\n if(mpOutputDevice)\n {\n mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() & ~ALL_GHOSTED_DRAWMODES);\n }\n\n mbGhostedDrawModeActive = sal_False;\n }\n\n void DisplayInfo::SetGhostedDrawMode()\n {\n if(mpOutputDevice)\n {\n mpOutputDevice->SetDrawMode(mpOutputDevice->GetDrawMode() | ALL_GHOSTED_DRAWMODES);\n }\n\n mbGhostedDrawModeActive = sal_True;\n }\n\n sal_Bool DisplayInfo::IsGhostedDrawModeActive() const\n {\n return mbGhostedDrawModeActive;\n }\n\n \/\/ access to buffering allowed flag\n void DisplayInfo::SetBufferingAllowed(sal_Bool bNew)\n {\n if(mbBufferingAllowed != bNew)\n {\n mbBufferingAllowed = bNew;\n }\n }\n\n sal_Bool DisplayInfo::IsBufferingAllowed() const\n {\n return mbBufferingAllowed;\n }\n\n \/\/ Check if painting should be continued. If not, return from paint\n \/\/ as soon as possible.\n sal_Bool DisplayInfo::DoContinuePaint()\n {\n if(mbContinuePaint\n && mpOutputDevice\n && OUTDEV_WINDOW == mpOutputDevice->GetOutDevType())\n {\n CheckContinuePaint();\n }\n\n return mbContinuePaint;\n }\n\n sal_Bool DisplayInfo::GetMasterPagePainting() const\n {\n return mbMasterPagePainting;\n }\n\n void DisplayInfo::SetMasterPagePainting(sal_Bool bNew)\n {\n if(mbMasterPagePainting != bNew)\n {\n mbMasterPagePainting = bNew;\n }\n }\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\nINTEGRATION: CWS aw033 (1.8.14); FILE MERGED 2008\/06\/03 13:41:11 aw 1.8.14.12: corrections 2008\/05\/27 14:49:57 aw 1.8.14.11: #i39532# changes DEV300 m12 resync corrections 2008\/05\/14 14:00:23 aw 1.8.14.10: RESYNC: (1.14-1.15); FILE MERGED 2008\/04\/16 05:30:44 aw 1.8.14.9: diverse optimisations and fixes for primitives. Support for LazyInvalidation. 2008\/01\/29 10:27:31 aw 1.8.14.8: updated refresh for ActionChanged(), diverse removals 2008\/01\/22 12:29:29 aw 1.8.14.7: adaptions and 1st stripping 2007\/12\/03 16:39:59 aw 1.8.14.6: RESYNC: (1.13-1.14); FILE MERGED 2007\/08\/13 15:34:32 aw 1.8.14.5: #i39532# changes after resync 2007\/08\/09 18:45:41 aw 1.8.14.4: RESYNC: (1.12-1.13); FILE MERGED 2006\/11\/28 19:24:04 aw 1.8.14.3: RESYNC: (1.10-1.12); FILE MERGED 2006\/09\/26 19:19:49 aw 1.8.14.2: RESYNC: (1.8-1.10); FILE MERGED 2006\/05\/12 12:46:21 aw 1.8.14.1: code changes for primitive support\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: displayinfo.cxx,v $\n * $Revision: 1.16 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_svx.hxx\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#define ALL_GHOSTED_DRAWMODES (DRAWMODE_GHOSTEDLINE|DRAWMODE_GHOSTEDFILL|DRAWMODE_GHOSTEDTEXT|DRAWMODE_GHOSTEDBITMAP|DRAWMODE_GHOSTEDGRADIENT)\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nnamespace sdr\n{\n namespace contact\n {\n DisplayInfo::DisplayInfo()\n : \/\/mpProcessedPage(0),\n maProcessLayers(true), \/\/ init layer info with all bits set to draw everything on default\n maRedrawArea(),\n mbControlLayerProcessingActive(false),\n mbPageProcessingActive(true),\n mbGhostedDrawModeActive(false),\n mbSubContentActive(false)\n {\n }\n\n DisplayInfo::~DisplayInfo()\n {\n \/\/SetProcessedPage(0);\n }\n\n \/\/ access to ProcessedPage, write for internal use only.\n \/\/void DisplayInfo::SetProcessedPage(SdrPage* pNew)\n \/\/{\n \/\/ if(pNew != mpProcessedPage)\n \/\/ {\n \/\/ mpProcessedPage = pNew;\n \/\/ }\n \/\/}\n\n \/\/const SdrPage* DisplayInfo::GetProcessedPage() const\n \/\/{\n \/\/ return mpProcessedPage;\n \/\/}\n\n \/\/ Access to LayerInfos (which layers to proccess)\n void DisplayInfo::SetProcessLayers(const SetOfByte& rSet)\n {\n maProcessLayers = rSet;\n }\n\n const SetOfByte& DisplayInfo::GetProcessLayers() const\n {\n return maProcessLayers;\n }\n\n \/\/ access to RedrawArea\n void DisplayInfo::SetRedrawArea(const Region& rRegion)\n {\n maRedrawArea = rRegion;\n }\n\n const Region& DisplayInfo::GetRedrawArea() const\n {\n return maRedrawArea;\n }\n\n void DisplayInfo::SetControlLayerProcessingActive(bool bDoProcess)\n {\n if((bool)mbControlLayerProcessingActive != bDoProcess)\n {\n mbControlLayerProcessingActive = bDoProcess;\n }\n }\n\n bool DisplayInfo::GetControlLayerProcessingActive() const\n {\n return mbControlLayerProcessingActive;\n }\n\n void DisplayInfo::SetPageProcessingActive(bool bDoProcess)\n {\n if((bool)mbPageProcessingActive != bDoProcess)\n {\n mbPageProcessingActive = bDoProcess;\n }\n }\n\n bool DisplayInfo::GetPageProcessingActive() const\n {\n return mbPageProcessingActive;\n }\n\n void DisplayInfo::ClearGhostedDrawMode()\n {\n mbGhostedDrawModeActive = false;\n }\n\n void DisplayInfo::SetGhostedDrawMode()\n {\n mbGhostedDrawModeActive = true;\n }\n\n bool DisplayInfo::IsGhostedDrawModeActive() const\n {\n return mbGhostedDrawModeActive;\n }\n\n bool DisplayInfo::GetSubContentActive() const\n {\n return mbSubContentActive;\n }\n\n void DisplayInfo::SetSubContentActive(bool bNew)\n {\n if((bool)mbSubContentActive != bNew)\n {\n mbSubContentActive = bNew;\n }\n }\n } \/\/ end of namespace contact\n} \/\/ end of namespace sdr\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ eof\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: SwUndoPageDesc.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: hr $ $Date: 2004-09-08 14:57:59 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nSwUndoPageDesc::SwUndoPageDesc(const SwPageDesc & _aOld,\n const SwPageDesc & _aNew,\n SwDoc * _pDoc)\n : SwUndo(_aOld.GetName() != _aNew.GetName() ?\n UNDO_RENAME_PAGEDESC\n :UNDO_CHANGE_PAGEDESC),\n aOld(_aOld, _pDoc), aNew(_aNew, _pDoc), pDoc(_pDoc)\n{\n ASSERT(0 != pDoc, \"no document?\");\n}\n\nSwUndoPageDesc::~SwUndoPageDesc()\n{\n}\n\nvoid SwUndoPageDesc::Undo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n pDoc->ChgPageDesc(aOld.GetName(), aOld);\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDesc::Redo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n pDoc->ChgPageDesc(aNew.GetName(), aNew);\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDesc::Repeat(SwUndoIter & rIt)\n{\n Redo(rIt);\n}\n\nSwRewriter SwUndoPageDesc::GetRewriter() const\n{\n SwRewriter aResult;\n\n aResult.AddRule(UNDO_ARG1, aOld.GetName());\n aResult.AddRule(UNDO_ARG2, SW_RES(STR_YIELDS));\n aResult.AddRule(UNDO_ARG3, aNew.GetName());\n\n return aResult;\n}\n\n\/\/ #116530#\nSwUndoPageDescCreate::SwUndoPageDescCreate(const SwPageDesc * pNew,\n SwDoc * _pDoc)\n : SwUndo(UNDO_CREATE_PAGEDESC), pDesc(pNew), aNew(*pNew, _pDoc),\n pDoc(_pDoc)\n{\n ASSERT(0 != pDoc, \"no document?\");\n}\n\nSwUndoPageDescCreate::~SwUndoPageDescCreate()\n{\n}\n\nvoid SwUndoPageDescCreate::Undo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n\n \/\/ -> #116530#\n if (pDesc)\n {\n aNew = *pDesc;\n pDesc = NULL;\n }\n \/\/ <- #116530#\n\n pDoc->DelPageDesc(aNew.GetName(), TRUE);\n pDoc->DoUndo(bUndo);\n}\n\n\nvoid SwUndoPageDescCreate::Redo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n\n SwPageDesc aPageDesc = aNew;\n pDoc->MakePageDesc(aNew.GetName(), &aPageDesc, FALSE, TRUE); \/\/ #116530#\n\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDescCreate::Repeat(SwUndoIter & rIt)\n{\n Redo(rIt);\n}\n\nSwRewriter SwUndoPageDescCreate::GetRewriter() const\n{\n SwRewriter aResult;\n\n if (pDesc)\n aResult.AddRule(UNDO_ARG1, pDesc->GetName());\n else\n aResult.AddRule(UNDO_ARG1, aNew.GetName());\n\n\n return aResult;\n}\n\nSwUndoPageDescDelete::SwUndoPageDescDelete(const SwPageDesc & _aOld,\n SwDoc * _pDoc)\n : SwUndo(UNDO_DELETE_PAGEDESC), aOld(_aOld, _pDoc), pDoc(_pDoc)\n{\n ASSERT(0 != pDoc, \"no document?\");\n}\n\nSwUndoPageDescDelete::~SwUndoPageDescDelete()\n{\n}\n\nvoid SwUndoPageDescDelete::Undo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n\n SwPageDesc aPageDesc = aOld;\n pDoc->MakePageDesc(aOld.GetName(), &aPageDesc, FALSE, TRUE); \/\/ #116530#\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDescDelete::Redo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n pDoc->DelPageDesc(aOld.GetName(), TRUE); \/\/ #116530#\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDescDelete::Repeat(SwUndoIter & rIt)\n{\n Redo(rIt);\n}\n\nSwRewriter SwUndoPageDescDelete::GetRewriter() const\n{\n SwRewriter aResult;\n\n aResult.AddRule(UNDO_ARG1, aOld.GetName());\n\n return aResult;\n}\nINTEGRATION: CWS swqcore08 (1.3.320); FILE MERGED 2005\/03\/01 18:06:23 dvo 1.3.320.1: #i43072# undo of header\/footer creation\/deletion\/*************************************************************************\n *\n * $RCSfile: SwUndoPageDesc.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: rt $ $Date: 2005-03-29 14:38:59 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nSwUndoPageDesc::SwUndoPageDesc(const SwPageDesc & _aOld,\n const SwPageDesc & _aNew,\n SwDoc * _pDoc)\n : SwUndo(_aOld.GetName() != _aNew.GetName() ?\n UNDO_RENAME_PAGEDESC\n :UNDO_CHANGE_PAGEDESC),\n aOld(_aOld, _pDoc), aNew(_aNew, _pDoc), pDoc(_pDoc)\n{\n ASSERT(0 != pDoc, \"no document?\");\n\n \/\/ The headers\/footers from the two SwPageDesc saved by this undo\n \/\/ are still in the main document array. In order to preserve the\n \/\/ absolute indices, we need to move them into the undo nodes\n \/\/ array.\n SwNodes& rNodes = * const_cast( pDoc->GetUndoNds() );\n saveHeaderFooterNodes( (SwPageDesc&)aOld, rNodes );\n saveHeaderFooterNodes( (SwPageDesc&)aNew, rNodes );\n}\n\nSwUndoPageDesc::~SwUndoPageDesc()\n{\n}\n\nvoid SwUndoPageDesc::Undo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n pDoc->ChgPageDesc(aOld.GetName(), aOld);\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDesc::Redo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n pDoc->ChgPageDesc(aNew.GetName(), aNew);\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDesc::Repeat(SwUndoIter & rIt)\n{\n Redo(rIt);\n}\n\nSwRewriter SwUndoPageDesc::GetRewriter() const\n{\n SwRewriter aResult;\n\n aResult.AddRule(UNDO_ARG1, aOld.GetName());\n aResult.AddRule(UNDO_ARG2, SW_RES(STR_YIELDS));\n aResult.AddRule(UNDO_ARG3, aNew.GetName());\n\n return aResult;\n}\n\n\/\/ #116530#\nSwUndoPageDescCreate::SwUndoPageDescCreate(const SwPageDesc * pNew,\n SwDoc * _pDoc)\n : SwUndo(UNDO_CREATE_PAGEDESC), pDesc(pNew), aNew(*pNew, _pDoc),\n pDoc(_pDoc)\n{\n ASSERT(0 != pDoc, \"no document?\");\n}\n\nSwUndoPageDescCreate::~SwUndoPageDescCreate()\n{\n}\n\nvoid SwUndoPageDescCreate::Undo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n\n \/\/ -> #116530#\n if (pDesc)\n {\n aNew = *pDesc;\n pDesc = NULL;\n }\n \/\/ <- #116530#\n\n pDoc->DelPageDesc(aNew.GetName(), TRUE);\n pDoc->DoUndo(bUndo);\n}\n\n\nvoid SwUndoPageDescCreate::Redo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n\n SwPageDesc aPageDesc = aNew;\n pDoc->MakePageDesc(aNew.GetName(), &aPageDesc, FALSE, TRUE); \/\/ #116530#\n\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDescCreate::Repeat(SwUndoIter & rIt)\n{\n Redo(rIt);\n}\n\nSwRewriter SwUndoPageDescCreate::GetRewriter() const\n{\n SwRewriter aResult;\n\n if (pDesc)\n aResult.AddRule(UNDO_ARG1, pDesc->GetName());\n else\n aResult.AddRule(UNDO_ARG1, aNew.GetName());\n\n\n return aResult;\n}\n\nSwUndoPageDescDelete::SwUndoPageDescDelete(const SwPageDesc & _aOld,\n SwDoc * _pDoc)\n : SwUndo(UNDO_DELETE_PAGEDESC), aOld(_aOld, _pDoc), pDoc(_pDoc)\n{\n ASSERT(0 != pDoc, \"no document?\");\n}\n\nSwUndoPageDescDelete::~SwUndoPageDescDelete()\n{\n}\n\nvoid SwUndoPageDescDelete::Undo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n\n SwPageDesc aPageDesc = aOld;\n pDoc->MakePageDesc(aOld.GetName(), &aPageDesc, FALSE, TRUE); \/\/ #116530#\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDescDelete::Redo(SwUndoIter & rIt)\n{\n BOOL bUndo = pDoc->DoesUndo();\n\n pDoc->DoUndo(FALSE);\n pDoc->DelPageDesc(aOld.GetName(), TRUE); \/\/ #116530#\n pDoc->DoUndo(bUndo);\n}\n\nvoid SwUndoPageDescDelete::Repeat(SwUndoIter & rIt)\n{\n Redo(rIt);\n}\n\nSwRewriter SwUndoPageDescDelete::GetRewriter() const\n{\n SwRewriter aResult;\n\n aResult.AddRule(UNDO_ARG1, aOld.GetName());\n\n return aResult;\n}\n<|endoftext|>"} {"text":"#include \"Node.h\"\n\nint Node::s_current_id = 0;\n\nNode::Node()\n{\n \/\/ Status\n m_id = ++s_current_id;\n m_show = false;\n\n \/\/ Arrangement\n m_position = Vec2(0.0, 0.0);\n m_anchor = Vec2(0.5, 0.5);\n m_size = Vec2(30.0, 30.0);\n \n \/\/ Texture\n m_texture = NULL;\n m_texture_src = NULL;\n m_texture_dst = NULL;\n}\n\nNode::~Node()\n{\n \/\/SDL_DestroyTexture(m_texture);\n}\n\nint Node::getId()\n{\n return m_id;\n}\n\nvoid Node::show(bool p_show)\n{\n m_show = p_show;\n}\n\nbool Node::show()\n{\n return m_show;\n}\n\nvoid Node::setPosition(Vec2 pos)\n{\n m_position = pos;\n\n m_position.x -= (m_size.x * m_anchor.x);\n m_position.y -= (m_size.y * m_anchor.y);\n\n if(m_texture_dst != NULL)\n {\n m_texture_dst->x = m_position.x;\n m_texture_dst->y = m_position.y;\n }\n}\n\nvoid Node::moveBy(Vec2 p_movement)\n{\n m_position += p_movement;\n\n if(m_texture_dst != NULL)\n {\n m_texture_dst->x += p_movement.x;\n m_texture_dst->y += p_movement.y;\n }\n}\n\nVec2 Node::getPosition()\n{\n return m_position;\n}\n\nvoid Node::setSize(Vec2 p_size)\n{\n \/\/ Arrangement\n m_size = p_size;\n \n \/\/ Texture\n m_texture_dst->w = m_size.x;\n m_texture_dst->h = m_size.y;\n}\n\nVec2 Node::getSize()\n{\n return m_size;\n}\n\nvoid Node::setAnchor(Vec2 p_anchor)\n{\n m_anchor = p_anchor;\n}\n\nVec2 Node::getAnchor()\n{\n return m_anchor;\n}\n\nvoid Node::setTexture(SDL_Texture* p_texture)\n{\n m_texture = p_texture;\n}\n\nSDL_Texture* Node::getTexture()\n{\n return m_texture;\n}\n\nSDL_Rect* Node::getTextureSrc()\n{\n return m_texture_src;\n}\n\nSDL_Rect* Node::getTextureDst()\n{\n return m_texture_dst;\n}Fix texture displacement#include \"Node.h\"\n\nint Node::s_current_id = 0;\n\nNode::Node()\n{\n \/\/ Status\n m_id = ++s_current_id;\n m_show = false;\n\n \/\/ Arrangement\n m_position = Vec2(0.0, 0.0);\n m_anchor = Vec2(0.5, 0.5);\n m_size = Vec2(30.0, 30.0);\n \n \/\/ Texture\n m_texture = NULL;\n m_texture_src = NULL;\n m_texture_dst = NULL;\n}\n\nNode::~Node()\n{\n \/\/SDL_DestroyTexture(m_texture);\n}\n\nint Node::getId()\n{\n return m_id;\n}\n\nvoid Node::show(bool p_show)\n{\n m_show = p_show;\n}\n\nbool Node::show()\n{\n return m_show;\n}\n\nvoid Node::setPosition(Vec2 pos)\n{\n m_position = pos;\n\n m_position.x -= (m_size.x * m_anchor.x);\n m_position.y -= (m_size.y * m_anchor.y);\n\n if(m_texture_dst != NULL)\n {\n m_texture_dst->x = m_position.x;\n m_texture_dst->y = m_position.y;\n }\n}\n\nvoid Node::moveBy(Vec2 p_movement)\n{\n m_position += p_movement;\n\n if(m_texture_dst != NULL)\n {\n m_texture_dst->x = m_position.x;\n m_texture_dst->y = m_position.y;\n }\n}\n\nVec2 Node::getPosition()\n{\n return m_position;\n}\n\nvoid Node::setSize(Vec2 p_size)\n{\n \/\/ Arrangement\n m_size = p_size;\n \n \/\/ Texture\n m_texture_dst->w = m_size.x;\n m_texture_dst->h = m_size.y;\n}\n\nVec2 Node::getSize()\n{\n return m_size;\n}\n\nvoid Node::setAnchor(Vec2 p_anchor)\n{\n m_anchor = p_anchor;\n}\n\nVec2 Node::getAnchor()\n{\n return m_anchor;\n}\n\nvoid Node::setTexture(SDL_Texture* p_texture)\n{\n m_texture = p_texture;\n}\n\nSDL_Texture* Node::getTexture()\n{\n return m_texture;\n}\n\nSDL_Rect* Node::getTextureSrc()\n{\n return m_texture_src;\n}\n\nSDL_Rect* Node::getTextureDst()\n{\n return m_texture_dst;\n}<|endoftext|>"} {"text":"\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2016 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include \n#include \n#include \n#include \n\n#include \"joynr\/MessagingQos.h\"\n#include \"joynr\/JoynrMessage.h\"\n#include \"joynr\/JoynrMessageFactory.h\"\n#include \"joynr\/JoynrMessageSender.h\"\n#include \"joynr\/Request.h\"\n#include \"joynr\/Reply.h\"\n#include \"joynr\/SubscriptionPublication.h\"\n#include \"joynr\/PeriodicSubscriptionQos.h\"\n#include \"joynr\/OnChangeSubscriptionQos.h\"\n#include \"tests\/utils\/MockObjects.h\"\n#include \"joynr\/SingleThreadedIOService.h\"\n\nusing ::testing::A;\nusing ::testing::_;\nusing ::testing::A;\nusing ::testing::Eq;\nusing ::testing::NotNull;\nusing ::testing::AllOf;\nusing ::testing::Property;\nusing namespace joynr;\n\nclass JoynrMessageSenderTest : public ::testing::Test {\npublic:\n JoynrMessageSenderTest() :\n messageFactory(),\n postFix(),\n senderID(),\n receiverID(),\n requestID(),\n qosSettings(),\n mockDispatcher(),\n mockMessagingStub(),\n callBack(),\n singleThreadedIOService()\n {\n singleThreadedIOService.start();\n }\n\n\n void SetUp(){\n postFix = \"_\" + util::createUuid();\n senderID = \"senderId\" + postFix;\n receiverID = \"receiverID\" + postFix;\n requestID = \"requestId\" + postFix;\n qosSettings = MessagingQos(456000);\n }\n\nprotected:\n JoynrMessageFactory messageFactory;\n std::string postFix;\n std::string senderID;\n std::string receiverID;\n std::string requestID;\n MessagingQos qosSettings;\n MockDispatcher mockDispatcher;\n MockMessaging mockMessagingStub;\n std::shared_ptr callBack;\n SingleThreadedIOService singleThreadedIOService;\n};\n\ntypedef JoynrMessageSenderTest JoynrMessageSenderDeathTest;\n\n\nTEST_F(JoynrMessageSenderTest, sendRequest_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n\n Request request;\n request.setMethodName(\"methodName\");\n request.setParams(42, std::string(\"value\"));\n std::vector paramDatatypes;\n paramDatatypes.push_back(\"java.lang.Integer\");\n paramDatatypes.push_back(\"java.lang.String\");\n request.setParamDatatypes(paramDatatypes);\n\n JoynrMessage message = messageFactory.createRequest(\n senderID,\n receiverID,\n qosSettings,\n request\n );\n\n EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, request, callBack);\n}\n\nTEST_F(JoynrMessageSenderTest, sendOneWayRequest_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n\n OneWayRequest oneWayRequest;\n oneWayRequest.setMethodName(\"methodName\");\n oneWayRequest.setParams(42, std::string(\"value\"));\n std::vector paramDatatypes;\n paramDatatypes.push_back(\"java.lang.Integer\");\n paramDatatypes.push_back(\"java.lang.String\");\n oneWayRequest.setParamDatatypes(paramDatatypes);\n\n JoynrMessage message = messageFactory.createOneWayRequest(\n senderID,\n receiverID,\n qosSettings,\n oneWayRequest\n );\n\n EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n joynrMessageSender.sendOneWayRequest(senderID, receiverID, qosSettings, oneWayRequest);\n}\n\n\nTEST_F(JoynrMessageSenderDeathTest, DISABLED_sendRequest_nullPayloadFails_death){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n EXPECT_CALL(*(messagingStub.get()), route(_,_)).Times(0);\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n Request jsonRequest;\n ASSERT_DEATH(joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, jsonRequest, callBack), \"Assertion.*\");\n}\n\n\nTEST_F(JoynrMessageSenderTest, sendReply_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n Reply reply;\n reply.setRequestReplyId(util::createUuid());\n reply.setResponse(std::string(\"response\"));\n\n JoynrMessage message = messageFactory.createReply(\n senderID,\n receiverID,\n qosSettings,\n reply);\n\n\n EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REPLY)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n joynrMessageSender.sendReply(senderID, receiverID, qosSettings, reply);\n}\n\nTEST_F(JoynrMessageSenderTest, sendSubscriptionRequest_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n\n std::int64_t period = 2000;\n std::int64_t validity = 100000;\n std::int64_t alert = 4000;\n auto qos = std::make_shared(validity, period, alert);\n\n SubscriptionRequest subscriptionRequest;\n subscriptionRequest.setSubscriptionId(\"subscriptionId\");\n subscriptionRequest.setSubscribeToName(\"attributeName\");\n subscriptionRequest.setQos(qos);\n\n JoynrMessage message = messageFactory.createSubscriptionRequest(\n senderID,\n receiverID,\n qosSettings,\n subscriptionRequest);\n\n\n EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n joynrMessageSender.sendSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest);\n}\n\nTEST_F(JoynrMessageSenderTest, sendBroadcastSubscriptionRequest_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n\n std::int64_t minInterval = 2000;\n std::int64_t validity = 100000;\n auto qos = std::make_shared(validity, minInterval);\n\n BroadcastSubscriptionRequest subscriptionRequest;\n BroadcastFilterParameters filter;\n filter.setFilterParameter(\"MyParameter\", \"MyValue\");\n subscriptionRequest.setFilterParameters(filter);\n subscriptionRequest.setSubscriptionId(\"subscriptionId\");\n subscriptionRequest.setSubscribeToName(\"broadcastName\");\n subscriptionRequest.setQos(qos);\n\n JoynrMessage message = messageFactory.createBroadcastSubscriptionRequest(\n senderID,\n receiverID,\n qosSettings,\n subscriptionRequest);\n\n\n EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n joynrMessageSender.sendBroadcastSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest);\n}\n\n\n\/\/TODO implement sending a reply to a subscription request!\nTEST_F(JoynrMessageSenderTest, DISABLED_sendSubscriptionReply_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n std::string payload(\"subscriptionReply\");\n EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY)),\n Property(&JoynrMessage::getPayload, Eq(payload))),_));\n\n\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n\/\/ joynrMessageSender.sendSubscriptionReply(util::createUuid(), payload, senderID, receiverID, qosSettings);\n}\n\nTEST_F(JoynrMessageSenderTest, sendPublication_normal){\n\n MockDispatcher mockDispatcher;\n auto messagingStub = std::make_shared(singleThreadedIOService.getIOService());\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n SubscriptionPublication publication;\n publication.setSubscriptionId(\"ignoresubscriptionid\");\n publication.setResponse(std::string(\"publication\"));\n JoynrMessage message = messageFactory.createSubscriptionPublication(\n senderID,\n receiverID,\n qosSettings,\n publication);\n\n EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n joynrMessageSender.sendSubscriptionPublication(senderID, receiverID, qosSettings, std::move(publication));\n}\n[C++] JoynrMessageSenderTest: Move common code into fixture\/*\n * #%L\n * %%\n * Copyright (C) 2011 - 2016 BMW Car IT GmbH\n * %%\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * #L%\n *\/\n#include \n#include \n#include \n#include \n\n#include \"joynr\/MessagingQos.h\"\n#include \"joynr\/JoynrMessage.h\"\n#include \"joynr\/JoynrMessageFactory.h\"\n#include \"joynr\/JoynrMessageSender.h\"\n#include \"joynr\/Request.h\"\n#include \"joynr\/Reply.h\"\n#include \"joynr\/SubscriptionPublication.h\"\n#include \"joynr\/PeriodicSubscriptionQos.h\"\n#include \"joynr\/OnChangeSubscriptionQos.h\"\n#include \"tests\/utils\/MockObjects.h\"\n#include \"joynr\/SingleThreadedIOService.h\"\n\nusing ::testing::A;\nusing ::testing::_;\nusing ::testing::A;\nusing ::testing::Eq;\nusing ::testing::NotNull;\nusing ::testing::AllOf;\nusing ::testing::Property;\nusing namespace joynr;\n\nclass JoynrMessageSenderTest : public ::testing::Test {\npublic:\n JoynrMessageSenderTest() :\n messageFactory(),\n postFix(),\n senderID(),\n receiverID(),\n requestID(),\n qosSettings(),\n mockDispatcher(),\n mockMessagingStub(),\n callBack(),\n singleThreadedIOService(),\n messagingStub(std::make_shared(singleThreadedIOService.getIOService()))\n {\n singleThreadedIOService.start();\n }\n\n\n void SetUp(){\n postFix = \"_\" + util::createUuid();\n senderID = \"senderId\" + postFix;\n receiverID = \"receiverID\" + postFix;\n requestID = \"requestId\" + postFix;\n qosSettings = MessagingQos(456000);\n }\n\nprotected:\n JoynrMessageFactory messageFactory;\n std::string postFix;\n std::string senderID;\n std::string receiverID;\n std::string requestID;\n MessagingQos qosSettings;\n MockDispatcher mockDispatcher;\n MockMessaging mockMessagingStub;\n std::shared_ptr callBack;\n SingleThreadedIOService singleThreadedIOService;\n std::shared_ptr messagingStub;\n};\n\ntypedef JoynrMessageSenderTest JoynrMessageSenderDeathTest;\n\n\nTEST_F(JoynrMessageSenderTest, sendRequest_normal){\n Request request;\n request.setMethodName(\"methodName\");\n request.setParams(42, std::string(\"value\"));\n std::vector paramDatatypes;\n paramDatatypes.push_back(\"java.lang.Integer\");\n paramDatatypes.push_back(\"java.lang.String\");\n request.setParamDatatypes(paramDatatypes);\n\n JoynrMessage message = messageFactory.createRequest(\n senderID,\n receiverID,\n qosSettings,\n request\n );\n\n EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REQUEST)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, request, callBack);\n}\n\nTEST_F(JoynrMessageSenderTest, sendOneWayRequest_normal){\n OneWayRequest oneWayRequest;\n oneWayRequest.setMethodName(\"methodName\");\n oneWayRequest.setParams(42, std::string(\"value\"));\n std::vector paramDatatypes;\n paramDatatypes.push_back(\"java.lang.Integer\");\n paramDatatypes.push_back(\"java.lang.String\");\n oneWayRequest.setParamDatatypes(paramDatatypes);\n\n JoynrMessage message = messageFactory.createOneWayRequest(\n senderID,\n receiverID,\n qosSettings,\n oneWayRequest\n );\n\n EXPECT_CALL( *(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_ONE_WAY)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n joynrMessageSender.sendOneWayRequest(senderID, receiverID, qosSettings, oneWayRequest);\n}\n\n\nTEST_F(JoynrMessageSenderDeathTest, DISABLED_sendRequest_nullPayloadFails_death){\n EXPECT_CALL(*(messagingStub.get()), route(_,_)).Times(0);\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n Request jsonRequest;\n ASSERT_DEATH(joynrMessageSender.sendRequest(senderID, receiverID, qosSettings, jsonRequest, callBack), \"Assertion.*\");\n}\n\n\nTEST_F(JoynrMessageSenderTest, sendReply_normal){\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n Reply reply;\n reply.setRequestReplyId(util::createUuid());\n reply.setResponse(std::string(\"response\"));\n\n JoynrMessage message = messageFactory.createReply(\n senderID,\n receiverID,\n qosSettings,\n reply);\n\n\n EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_REPLY)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n joynrMessageSender.sendReply(senderID, receiverID, qosSettings, reply);\n}\n\nTEST_F(JoynrMessageSenderTest, sendSubscriptionRequest_normal){\n std::int64_t period = 2000;\n std::int64_t validity = 100000;\n std::int64_t alert = 4000;\n auto qos = std::make_shared(validity, period, alert);\n\n SubscriptionRequest subscriptionRequest;\n subscriptionRequest.setSubscriptionId(\"subscriptionId\");\n subscriptionRequest.setSubscribeToName(\"attributeName\");\n subscriptionRequest.setQos(qos);\n\n JoynrMessage message = messageFactory.createSubscriptionRequest(\n senderID,\n receiverID,\n qosSettings,\n subscriptionRequest);\n\n\n EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REQUEST)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n joynrMessageSender.sendSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest);\n}\n\nTEST_F(JoynrMessageSenderTest, sendBroadcastSubscriptionRequest_normal){\n std::int64_t minInterval = 2000;\n std::int64_t validity = 100000;\n auto qos = std::make_shared(validity, minInterval);\n\n BroadcastSubscriptionRequest subscriptionRequest;\n BroadcastFilterParameters filter;\n filter.setFilterParameter(\"MyParameter\", \"MyValue\");\n subscriptionRequest.setFilterParameters(filter);\n subscriptionRequest.setSubscriptionId(\"subscriptionId\");\n subscriptionRequest.setSubscribeToName(\"broadcastName\");\n subscriptionRequest.setQos(qos);\n\n JoynrMessage message = messageFactory.createBroadcastSubscriptionRequest(\n senderID,\n receiverID,\n qosSettings,\n subscriptionRequest);\n\n\n EXPECT_CALL(*messagingStub, route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_BROADCAST_SUBSCRIPTION_REQUEST)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n joynrMessageSender.sendBroadcastSubscriptionRequest(senderID, receiverID, qosSettings, subscriptionRequest);\n}\n\n\n\/\/TODO implement sending a reply to a subscription request!\nTEST_F(JoynrMessageSenderTest, DISABLED_sendSubscriptionReply_normal){\n std::string payload(\"subscriptionReply\");\n EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_SUBSCRIPTION_REPLY)),\n Property(&JoynrMessage::getPayload, Eq(payload))),_));\n\n\n\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n\n\/\/ joynrMessageSender.sendSubscriptionReply(util::createUuid(), payload, senderID, receiverID, qosSettings);\n}\n\nTEST_F(JoynrMessageSenderTest, sendPublication_normal){\n JoynrMessageSender joynrMessageSender(messagingStub);\n joynrMessageSender.registerDispatcher(&mockDispatcher);\n SubscriptionPublication publication;\n publication.setSubscriptionId(\"ignoresubscriptionid\");\n publication.setResponse(std::string(\"publication\"));\n JoynrMessage message = messageFactory.createSubscriptionPublication(\n senderID,\n receiverID,\n qosSettings,\n publication);\n\n EXPECT_CALL(*(messagingStub.get()), route(AllOf(Property(&JoynrMessage::getType, Eq(JoynrMessage::VALUE_MESSAGE_TYPE_PUBLICATION)),\n Property(&JoynrMessage::getPayload, Eq(message.getPayload()))),_));\n\n joynrMessageSender.sendSubscriptionPublication(senderID, receiverID, qosSettings, std::move(publication));\n}\n<|endoftext|>"} {"text":"\/\/ RUN: %clang_cc1 -DSETNODEBUG=0 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=YESINFO\n\/\/ RUN: %clang_cc1 -DSETNODEBUG=1 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=NOINFO\n\n#if SETNODEBUG\n#define NODEBUG __attribute__((nodebug))\n#else\n#define NODEBUG\n#endif\n\n\/\/ Const global variable. Use it so it gets emitted.\nNODEBUG static const int const_global_int_def = 1;\nvoid func1(int);\nvoid func2() { func1(const_global_int_def); }\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"const_global_int_def\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"const_global_int_def\"\n\n\/\/ Global variable with a more involved type.\n\/\/ If the variable has no debug info, the type should not appear either.\nstruct S1 {\n int a;\n int b;\n};\nNODEBUG S1 global_struct = { 2, 3 };\n\/\/ YESINFO-DAG: !DICompositeType({{.*}} name: \"S1\"\n\/\/ NOINFO-NOT: !DICompositeType({{.*}} name: \"S1\"\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"global_struct\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"global_struct\"\n\n\/\/ Static data members. Const member needs a use.\nstruct S2 {\n NODEBUG static int static_member;\n NODEBUG static const int static_const_member = 4;\n};\nint S2::static_member = 5;\nvoid func3() { func1(S2::static_const_member); }\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"static_member\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"static_member\"\n\/\/ YESINFO-DAG: !DIDerivedType({{.*}} name: \"static_const_member\"\n\/\/ NOINFO-NOT: !DIDerivedType({{.*}} name: \"static_const_member\"\n\n\/\/ Function-local static variable.\nvoid func4() {\n NODEBUG static int static_local = 6;\n}\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"static_local\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"static_local\"\nMake the test exercise all paths modified in r267746.\/\/ RUN: %clang_cc1 -DSETNODEBUG=0 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=YESINFO\n\/\/ RUN: %clang_cc1 -DSETNODEBUG=1 -emit-llvm -debug-info-kind=limited %s -o - | FileCheck %s --check-prefix=NOINFO\n\n#if SETNODEBUG\n#define NODEBUG __attribute__((nodebug))\n#else\n#define NODEBUG\n#endif\n\n\/\/ Const global variable. Use it so it gets emitted.\nNODEBUG static const int const_global_int_def = 1;\nvoid func1(int);\nvoid func2() { func1(const_global_int_def); }\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"const_global_int_def\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"const_global_int_def\"\n\n\/\/ Global variable with a more involved type.\n\/\/ If the variable has no debug info, the type should not appear either.\nstruct S1 {\n int a;\n int b;\n};\nNODEBUG S1 global_struct = { 2, 3 };\n\/\/ YESINFO-DAG: !DICompositeType({{.*}} name: \"S1\"\n\/\/ NOINFO-NOT: !DICompositeType({{.*}} name: \"S1\"\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"global_struct\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"global_struct\"\n\n\/\/ Static data members. Const member needs a use.\n\/\/ Also the class as a whole needs a use, so that we produce debug info for\n\/\/ the entire class (iterating over the members, demonstrably skipping those\n\/\/ with 'nodebug').\nstruct S2 {\n NODEBUG static int static_member;\n NODEBUG static const int static_const_member = 4;\n};\nint S2::static_member = 5;\nvoid func3() {\n S2 junk;\n func1(S2::static_const_member);\n}\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"static_member\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"static_member\"\n\/\/ YESINFO-DAG: !DIDerivedType({{.*}} name: \"static_const_member\"\n\/\/ NOINFO-NOT: !DIDerivedType({{.*}} name: \"static_const_member\"\n\n\/\/ Function-local static variable.\nvoid func4() {\n NODEBUG static int static_local = 6;\n}\n\/\/ YESINFO-DAG: !DIGlobalVariable(name: \"static_local\"\n\/\/ NOINFO-NOT: !DIGlobalVariable(name: \"static_local\"\n<|endoftext|>"} {"text":"\/*\n * Copyright 2019 The Open GEE Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"AssetVersion.h\"\n#include \"gee_version.h\"\n#include \"StateUpdater.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ All refs must end with \"?version=X\" or the calls to AssetVersionRef::Bind\n\/\/ will try to load assets from disk. For simplicity, we force everything to\n\/\/ be version 1. When you write additional tests you have to remember to call\n\/\/ this function when working directly with the state updater.\nconst string SUFFIX = \"?version=1\";\nAssetKey fix(AssetKey ref) {\n return ref.toString() + SUFFIX;\n}\n\nclass MockVersion : public AssetVersionImpl {\n public:\n bool stateSet;\n bool loadedMutable;\n vector dependents;\n\n MockVersion() : stateSet(false), loadedMutable(false) {\n type = AssetDefs::Imagery;\n state = AssetDefs::Blocked;\n }\n MockVersion(const AssetKey & ref) : MockVersion() {\n name = fix(ref);\n }\n MockVersion(const MockVersion & that) : MockVersion() {\n name = that.name; \/\/ Don't add the suffix - the other MockVersion already did\n }\n void DependentChildren(vector & d) const {\n for(auto dependent : dependents) {\n d.push_back(dependent);\n }\n }\n bool NeedComputeState() const { return true; }\n AssetDefs::State CalcStateByInputsAndChildren(\n AssetDefs::State stateByInputs,\n AssetDefs::State stateByChildren,\n bool blockersAreOffline,\n uint32 numWaitingFor) const\n {\n return AssetDefs::InProgress;\n }\n void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) {\n stateSet = true;\n }\n \n \/\/ Not used - only included to make MockVersion non-virtual\n string PluginName(void) const { return string(); }\n void GetOutputFilenames(vector &) const {}\n string GetOutputFilename(uint) const { return string(); }\n};\n\nusing VersionMap = map>;\n\nclass MockStorageManager : public StorageManagerInterface {\n private:\n VersionMap versions;\n PointerType GetFromMap(const AssetKey & ref) {\n auto versionIter = versions.find(ref);\n if (versionIter != versions.end()) {\n auto version = dynamic_pointer_cast(versionIter->second);\n assert(version);\n return version;\n }\n assert(false);\n return nullptr;\n }\n public:\n void AddVersion(const AssetKey & key, const MockVersion & v) {\n versions[key] = make_shared(v);\n }\n virtual AssetHandle Get(const AssetKey &ref) {\n return AssetHandle(GetFromMap(ref), nullptr);\n }\n virtual AssetHandle GetMutable(const AssetKey &ref) {\n auto handle = AssetHandle(GetFromMap(ref), nullptr);\n dynamic_cast(handle.operator->())->loadedMutable = true;\n return handle;\n }\n void ResetLoadedMutable() {\n for (auto & v : versions) {\n v.second->loadedMutable = false;\n }\n }\n};\n\nclass StateUpdaterTest : public testing::Test {\n protected:\n MockStorageManager sm;\n StateUpdater updater;\n public:\n StateUpdaterTest() : sm(), updater(&sm) {}\n};\n\nvoid SetVersions(MockStorageManager & sm, vector versions) {\n for (auto & version: versions) {\n sm.AddVersion(version.name, version);\n }\n}\n\n\/\/ This is bad because technically the object could be deleted before you use\n\/\/ it, but it works for unit tests.\nAssetHandle GetVersion(MockStorageManager & sm, const AssetKey & key) {\n return sm.Get(fix(key));\n}\n\nvoid SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) {\n parent = fix(parent);\n child = fix(child);\n sm.GetMutable(parent)->children.push_back(child);\n sm.GetMutable(child)->parents.push_back(parent);\n}\n\nvoid SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) {\n listener = fix(listener);\n input = fix(input);\n sm.GetMutable(listener)->inputs.push_back(input);\n sm.GetMutable(input)->listeners.push_back(listener);\n}\n\nvoid SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) {\n dependee = fix(dependee);\n dependent = fix(dependent);\n AssetHandle dependeeHandle = sm.GetMutable(dependee);\n dependeeHandle->dependents.push_back(dependent);\n}\n\nvoid GetBigTree(MockStorageManager & sm) {\n SetVersions(sm,\n {\n MockVersion(\"gp\"),\n MockVersion(\"p1\"),\n MockVersion(\"p2\"),\n MockVersion(\"gpi\"),\n MockVersion(\"pi1\"),\n MockVersion(\"c1\"),\n MockVersion(\"c2\"),\n MockVersion(\"c3\"),\n MockVersion(\"c4\"),\n MockVersion(\"ci1\"),\n MockVersion(\"ci2\"),\n MockVersion(\"ci3\")\n });\n SetParentChild(sm, \"gp\", \"p1\");\n SetParentChild(sm, \"gp\", \"p2\");\n SetListenerInput(sm, \"gp\", \"gpi\");\n SetListenerInput(sm, \"p1\", \"pi1\");\n SetParentChild(sm, \"p1\", \"c1\");\n SetParentChild(sm, \"p1\", \"c2\");\n SetParentChild(sm, \"p2\", \"c3\");\n SetParentChild(sm, \"p2\", \"c4\");\n SetListenerInput(sm, \"c2\", \"ci3\");\n SetListenerInput(sm, \"c4\", \"ci1\");\n SetListenerInput(sm, \"c4\", \"ci2\");\n SetDependent(sm, \"gp\", \"p1\");\n SetDependent(sm, \"gp\", \"c2\");\n SetDependent(sm, \"p1\", \"c1\");\n}\n\nTEST_F(StateUpdaterTest, SetStateSingleVersion) {\n AssetKey ref1 = \"test1\";\n AssetKey ref2 = \"test2\";\n AssetKey ref3 = \"test3\";\n SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)});\n updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; });\n ASSERT_TRUE(GetVersion(sm, ref1)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; });\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersions) {\n GetBigTree(sm);\n updater.SetStateForRefAndDependents(fix(\"gp\"), AssetDefs::Canceled, [](AssetDefs::State) {return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c2\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) {\n GetBigTree(sm);\n sm.ResetLoadedMutable();\n updater.SetStateForRefAndDependents(fix(\"p1\"), AssetDefs::Canceled, [](AssetDefs::State) {return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n\n ASSERT_TRUE(GetVersion(sm, \"p1\")->loadedMutable);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->loadedMutable);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->loadedMutable);\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc,argv);\n return RUN_ALL_TESTS();\n}\nTest states that do and don't change\/*\n * Copyright 2019 The Open GEE Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"AssetVersion.h\"\n#include \"gee_version.h\"\n#include \"StateUpdater.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ All refs must end with \"?version=X\" or the calls to AssetVersionRef::Bind\n\/\/ will try to load assets from disk. For simplicity, we force everything to\n\/\/ be version 1. When you write additional tests you have to remember to call\n\/\/ this function when working directly with the state updater.\nconst string SUFFIX = \"?version=1\";\nAssetKey fix(AssetKey ref) {\n return ref.toString() + SUFFIX;\n}\n\nclass MockVersion : public AssetVersionImpl {\n public:\n bool stateSet;\n bool loadedMutable;\n vector dependents;\n\n MockVersion() : stateSet(false), loadedMutable(false) {\n type = AssetDefs::Imagery;\n state = AssetDefs::Blocked;\n }\n MockVersion(const AssetKey & ref) : MockVersion() {\n name = fix(ref);\n }\n MockVersion(const MockVersion & that) : MockVersion() {\n name = that.name; \/\/ Don't add the suffix - the other MockVersion already did\n }\n void DependentChildren(vector & d) const {\n for(auto dependent : dependents) {\n d.push_back(dependent);\n }\n }\n bool NeedComputeState() const { return true; }\n AssetDefs::State CalcStateByInputsAndChildren(\n AssetDefs::State stateByInputs,\n AssetDefs::State stateByChildren,\n bool blockersAreOffline,\n uint32 numWaitingFor) const\n {\n return AssetDefs::InProgress;\n }\n void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) {\n stateSet = true;\n }\n \n \/\/ Not used - only included to make MockVersion non-virtual\n string PluginName(void) const { return string(); }\n void GetOutputFilenames(vector &) const {}\n string GetOutputFilename(uint) const { return string(); }\n};\n\nusing VersionMap = map>;\n\nclass MockStorageManager : public StorageManagerInterface {\n private:\n VersionMap versions;\n PointerType GetFromMap(const AssetKey & ref) {\n auto versionIter = versions.find(ref);\n if (versionIter != versions.end()) {\n auto version = dynamic_pointer_cast(versionIter->second);\n assert(version);\n return version;\n }\n assert(false);\n return nullptr;\n }\n public:\n void AddVersion(const AssetKey & key, const MockVersion & v) {\n versions[key] = make_shared(v);\n }\n virtual AssetHandle Get(const AssetKey &ref) {\n return AssetHandle(GetFromMap(ref), nullptr);\n }\n virtual AssetHandle GetMutable(const AssetKey &ref) {\n auto handle = AssetHandle(GetFromMap(ref), nullptr);\n dynamic_cast(handle.operator->())->loadedMutable = true;\n return handle;\n }\n void ResetLoadedMutable() {\n for (auto & v : versions) {\n v.second->loadedMutable = false;\n }\n }\n};\n\nclass StateUpdaterTest : public testing::Test {\n protected:\n MockStorageManager sm;\n StateUpdater updater;\n public:\n StateUpdaterTest() : sm(), updater(&sm) {}\n};\n\nvoid SetVersions(MockStorageManager & sm, vector versions) {\n for (auto & version: versions) {\n sm.AddVersion(version.name, version);\n }\n}\n\n\/\/ This is bad because technically the object could be deleted before you use\n\/\/ it, but it works for unit tests.\nAssetHandle GetVersion(MockStorageManager & sm, const AssetKey & key) {\n return sm.Get(fix(key));\n}\n\nvoid SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) {\n parent = fix(parent);\n child = fix(child);\n sm.GetMutable(parent)->children.push_back(child);\n sm.GetMutable(child)->parents.push_back(parent);\n}\n\nvoid SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) {\n listener = fix(listener);\n input = fix(input);\n sm.GetMutable(listener)->inputs.push_back(input);\n sm.GetMutable(input)->listeners.push_back(listener);\n}\n\nvoid SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) {\n dependee = fix(dependee);\n dependent = fix(dependent);\n AssetHandle dependeeHandle = sm.GetMutable(dependee);\n dependeeHandle->dependents.push_back(dependent);\n}\n\nvoid GetBigTree(MockStorageManager & sm) {\n SetVersions(sm,\n {\n MockVersion(\"gp\"),\n MockVersion(\"p1\"),\n MockVersion(\"p2\"),\n MockVersion(\"gpi\"),\n MockVersion(\"pi1\"),\n MockVersion(\"c1\"),\n MockVersion(\"c2\"),\n MockVersion(\"c3\"),\n MockVersion(\"c4\"),\n MockVersion(\"ci1\"),\n MockVersion(\"ci2\"),\n MockVersion(\"ci3\")\n });\n SetParentChild(sm, \"gp\", \"p1\");\n SetParentChild(sm, \"gp\", \"p2\");\n SetListenerInput(sm, \"gp\", \"gpi\");\n SetListenerInput(sm, \"p1\", \"pi1\");\n SetParentChild(sm, \"p1\", \"c1\");\n SetParentChild(sm, \"p1\", \"c2\");\n SetParentChild(sm, \"p2\", \"c3\");\n SetParentChild(sm, \"p2\", \"c4\");\n SetListenerInput(sm, \"c2\", \"ci3\");\n SetListenerInput(sm, \"c4\", \"ci1\");\n SetListenerInput(sm, \"c4\", \"ci2\");\n SetDependent(sm, \"gp\", \"p1\");\n SetDependent(sm, \"gp\", \"c2\");\n SetDependent(sm, \"p1\", \"c1\");\n}\n\nTEST_F(StateUpdaterTest, SetStateSingleVersion) {\n AssetKey ref1 = \"test1\";\n AssetKey ref2 = \"test2\";\n AssetKey ref3 = \"test3\";\n SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)});\n updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; });\n ASSERT_TRUE(GetVersion(sm, ref1)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; });\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersions) {\n GetBigTree(sm);\n updater.SetStateForRefAndDependents(fix(\"gp\"), AssetDefs::Canceled, [](AssetDefs::State) {return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c2\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) {\n GetBigTree(sm);\n sm.ResetLoadedMutable();\n updater.SetStateForRefAndDependents(fix(\"p1\"), AssetDefs::Canceled, [](AssetDefs::State) { return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n\n ASSERT_TRUE(GetVersion(sm, \"p1\")->loadedMutable);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->loadedMutable);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->loadedMutable);\n}\n\nTEST_F(StateUpdaterTest, SetState_StateDoesAndDoesntChange) {\n const AssetDefs::State SET_TO_STATE = AssetDefs::InProgress;\n const AssetDefs::State STARTING_STATE = AssetDefs::Canceled;\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n sm.GetMutable(fix(\"a\"))->state = SET_TO_STATE;\n sm.GetMutable(fix(\"b\"))->state = STARTING_STATE;\n \n updater.SetStateForRefAndDependents(fix(\"a\"), SET_TO_STATE, [](AssetDefs::State) { return true; });\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n\n updater.SetStateForRefAndDependents(fix(\"b\"), SET_TO_STATE, [](AssetDefs::State) { return true; });\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"b\")->stateSet);\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc,argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2019 The Open GEE Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"AssetVersion.h\"\n#include \"gee_version.h\"\n#include \"StateUpdater.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ All refs must end with \"?version=X\" or the calls to AssetVersionRef::Bind\n\/\/ will try to load assets from disk. For simplicity, we force everything to\n\/\/ be version 1. When you write additional tests you have to remember to call\n\/\/ this function when working directly with the state updater.\nconst string SUFFIX = \"?version=1\";\nAssetKey fix(AssetKey ref) {\n return ref.toString() + SUFFIX;\n}\n\nconst AssetDefs::State STARTING_STATE = AssetDefs::Blocked;\nconst AssetDefs::State CALCULATED_STATE = AssetDefs::InProgress;\n\nclass MockVersion : public AssetVersionImpl {\n public:\n bool stateSet;\n bool loadedMutable;\n bool notificationsSent;\n bool needComputeState;\n vector dependents;\n\n MockVersion() : stateSet(false), loadedMutable(false), notificationsSent(false), needComputeState(true) {\n type = AssetDefs::Imagery;\n state = STARTING_STATE;\n }\n MockVersion(const AssetKey & ref)\n : MockVersion() {\n name = fix(ref);\n }\n MockVersion(const MockVersion & that) : MockVersion() {\n name = that.name; \/\/ Don't add the suffix - the other MockVersion already did\n }\n void DependentChildren(vector & d) const {\n for(auto dependent : dependents) {\n d.push_back(dependent);\n }\n }\n bool NeedComputeState() const { return needComputeState; }\n AssetDefs::State CalcStateByInputsAndChildren(\n AssetDefs::State stateByInputs,\n AssetDefs::State stateByChildren,\n bool blockersAreOffline,\n uint32 numWaitingFor) const {\n return CALCULATED_STATE;\n }\n void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) {\n stateSet = true;\n notificationsSent = sendNotifications;\n }\n \n \/\/ Not used - only included to make MockVersion non-virtual\n string PluginName(void) const { return string(); }\n void GetOutputFilenames(vector &) const {}\n string GetOutputFilename(uint) const { return string(); }\n};\n\nusing VersionMap = map>;\n\nclass MockStorageManager : public StorageManagerInterface {\n private:\n VersionMap versions;\n PointerType GetFromMap(const AssetKey & ref) {\n auto versionIter = versions.find(ref);\n if (versionIter != versions.end()) {\n auto version = dynamic_pointer_cast(versionIter->second);\n assert(version);\n return version;\n }\n assert(false);\n return nullptr;\n }\n public:\n void AddVersion(const AssetKey & key, const MockVersion & v) {\n versions[key] = make_shared(v);\n }\n virtual AssetHandle Get(const AssetKey &ref) {\n return AssetHandle(GetFromMap(ref), nullptr);\n }\n virtual AssetHandle GetMutable(const AssetKey &ref) {\n auto handle = AssetHandle(GetFromMap(ref), nullptr);\n dynamic_cast(handle.operator->())->loadedMutable = true;\n return handle;\n }\n void ResetLoadedMutable() {\n for (auto & v : versions) {\n v.second->loadedMutable = false;\n }\n }\n};\n\nclass StateUpdaterTest : public testing::Test {\n protected:\n MockStorageManager sm;\n StateUpdater updater;\n public:\n StateUpdaterTest() : sm(), updater(&sm) {}\n};\n\nvoid SetVersions(MockStorageManager & sm, vector versions) {\n for (auto & version: versions) {\n sm.AddVersion(version.name, version);\n }\n}\n\nAssetHandle GetVersion(MockStorageManager & sm, const AssetKey & key) {\n return sm.Get(fix(key));\n}\n\nAssetHandle GetMutableVersion(MockStorageManager & sm, const AssetKey & key) {\n return sm.GetMutable(fix(key));\n}\n\nvoid SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) {\n GetMutableVersion(sm, parent)->children.push_back(fix(child));\n GetMutableVersion(sm, child)->parents.push_back(fix(parent));\n}\n\nvoid SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) {\n GetMutableVersion(sm, listener)->inputs.push_back(fix(input));\n GetMutableVersion(sm, input)->listeners.push_back(fix(listener));\n}\n\nvoid SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) {\n GetMutableVersion(sm, dependee)->dependents.push_back(fix(dependent));\n}\n\nvoid GetBigTree(MockStorageManager & sm) {\n SetVersions(sm,\n {\n MockVersion(\"gp\"),\n MockVersion(\"p1\"),\n MockVersion(\"p2\"),\n MockVersion(\"gpi\"),\n MockVersion(\"pi1\"),\n MockVersion(\"c1\"),\n MockVersion(\"c2\"),\n MockVersion(\"c3\"),\n MockVersion(\"c4\"),\n MockVersion(\"ci1\"),\n MockVersion(\"ci2\"),\n MockVersion(\"ci3\")\n });\n SetParentChild(sm, \"gp\", \"p1\");\n SetParentChild(sm, \"gp\", \"p2\");\n SetListenerInput(sm, \"gp\", \"gpi\");\n SetListenerInput(sm, \"p1\", \"pi1\");\n SetParentChild(sm, \"p1\", \"c1\");\n SetParentChild(sm, \"p1\", \"c2\");\n SetParentChild(sm, \"p2\", \"c3\");\n SetParentChild(sm, \"p2\", \"c4\");\n SetListenerInput(sm, \"c2\", \"ci3\");\n SetListenerInput(sm, \"c4\", \"ci1\");\n SetListenerInput(sm, \"c4\", \"ci2\");\n SetDependent(sm, \"gp\", \"p1\");\n SetDependent(sm, \"gp\", \"c2\");\n SetDependent(sm, \"p1\", \"c1\");\n}\n\nTEST_F(StateUpdaterTest, SetStateSingleVersion) {\n AssetKey ref1 = \"test1\";\n AssetKey ref2 = \"test2\";\n AssetKey ref3 = \"test3\";\n SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)});\n updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; });\n ASSERT_TRUE(GetVersion(sm, ref1)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; });\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersions) {\n GetBigTree(sm);\n updater.SetStateForRefAndDependents(fix(\"gp\"), AssetDefs::Canceled, [](AssetDefs::State) {return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c2\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n\n ASSERT_FALSE(GetVersion(sm, \"gp\")->notificationsSent);\n ASSERT_FALSE(GetVersion(sm, \"p1\")->notificationsSent);\n ASSERT_FALSE(GetVersion(sm, \"c1\")->notificationsSent);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->notificationsSent);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) {\n GetBigTree(sm);\n sm.ResetLoadedMutable();\n updater.SetStateForRefAndDependents(fix(\"p1\"), AssetDefs::Canceled, [](AssetDefs::State) { return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n\n ASSERT_TRUE(GetVersion(sm, \"p1\")->loadedMutable);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->loadedMutable);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->loadedMutable);\n}\n\nTEST_F(StateUpdaterTest, SetState_StateDoesAndDoesntChange) {\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n GetMutableVersion(sm, \"a\")->state = CALCULATED_STATE;\n GetMutableVersion(sm, \"b\")->state = STARTING_STATE;\n \n updater.SetStateForRefAndDependents(fix(\"a\"), CALCULATED_STATE, [](AssetDefs::State) { return true; });\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n\n updater.SetStateForRefAndDependents(fix(\"b\"), CALCULATED_STATE, [](AssetDefs::State) { return true; });\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"b\")->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStatePredicate) {\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n GetMutableVersion(sm, \"a\")->state = AssetDefs::Bad;\n GetMutableVersion(sm, \"b\")->state = AssetDefs::Canceled;\n SetDependent(sm, \"a\", \"b\");\n updater.SetStateForRefAndDependents(fix(\"a\"), AssetDefs::Succeeded, [](AssetDefs::State state) {\n return state != AssetDefs::Canceled;\n });\n ASSERT_TRUE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n}\n\nTEST_F(StateUpdaterTest, NeedComputeStateFalse) {\n SetVersions(sm, {MockVersion(\"a\")});\n updater.SetStateForRefAndDependents(fix(\"a\"), AssetDefs::Canceled, [](AssetDefs::State) { return true; });\n GetMutableVersion(sm, \"a\")->needComputeState = false;\n GetMutableVersion(sm, \"a\")->stateSet = false;\n updater.RecalculateAndSaveStates();\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n GetMutableVersion(sm, \"a\")->needComputeState = true;\n updater.RecalculateAndSaveStates();\n ASSERT_TRUE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"a\")->notificationsSent);\n}\n\nTEST_F(StateUpdaterTest, RecalculateState_StateDoesAndDoesntChange) {\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n GetMutableVersion(sm, \"a\")->state = CALCULATED_STATE;\n GetMutableVersion(sm, \"b\")->state = STARTING_STATE;\n SetListenerInput(sm, \"a\", \"b\");\n updater.SetStateForRefAndDependents(fix(\"a\"), CALCULATED_STATE, [](AssetDefs::State) { return false; });\n\n \/\/ Verify that the setup is correct\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n \n updater.RecalculateAndSaveStates();\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"b\")->stateSet);\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc,argv);\n return RUN_ALL_TESTS();\n}\nMake sure assets aren't unnecessarily loaded as mutable\/*\n * Copyright 2019 The Open GEE Contributors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"AssetVersion.h\"\n#include \"gee_version.h\"\n#include \"StateUpdater.h\"\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n\/\/ All refs must end with \"?version=X\" or the calls to AssetVersionRef::Bind\n\/\/ will try to load assets from disk. For simplicity, we force everything to\n\/\/ be version 1. When you write additional tests you have to remember to call\n\/\/ this function when working directly with the state updater.\nconst string SUFFIX = \"?version=1\";\nAssetKey fix(AssetKey ref) {\n return ref.toString() + SUFFIX;\n}\n\nconst AssetDefs::State STARTING_STATE = AssetDefs::Blocked;\nconst AssetDefs::State CALCULATED_STATE = AssetDefs::InProgress;\n\nclass MockVersion : public AssetVersionImpl {\n public:\n bool stateSet;\n bool loadedMutable;\n bool notificationsSent;\n bool needComputeState;\n vector dependents;\n\n MockVersion() : stateSet(false), loadedMutable(false), notificationsSent(false), needComputeState(true) {\n type = AssetDefs::Imagery;\n state = STARTING_STATE;\n }\n MockVersion(const AssetKey & ref)\n : MockVersion() {\n name = fix(ref);\n }\n MockVersion(const MockVersion & that) : MockVersion() {\n name = that.name; \/\/ Don't add the suffix - the other MockVersion already did\n }\n void DependentChildren(vector & d) const {\n for(auto dependent : dependents) {\n d.push_back(dependent);\n }\n }\n bool NeedComputeState() const { return needComputeState; }\n AssetDefs::State CalcStateByInputsAndChildren(\n AssetDefs::State stateByInputs,\n AssetDefs::State stateByChildren,\n bool blockersAreOffline,\n uint32 numWaitingFor) const {\n return CALCULATED_STATE;\n }\n void SetMyStateOnly(AssetDefs::State newState, bool sendNotifications) {\n stateSet = true;\n notificationsSent = sendNotifications;\n }\n \n \/\/ Not used - only included to make MockVersion non-virtual\n string PluginName(void) const { return string(); }\n void GetOutputFilenames(vector &) const {}\n string GetOutputFilename(uint) const { return string(); }\n};\n\nusing VersionMap = map>;\n\nclass MockStorageManager : public StorageManagerInterface {\n private:\n VersionMap versions;\n PointerType GetFromMap(const AssetKey & ref) {\n auto versionIter = versions.find(ref);\n if (versionIter != versions.end()) {\n auto version = dynamic_pointer_cast(versionIter->second);\n assert(version);\n return version;\n }\n assert(false);\n return nullptr;\n }\n public:\n void AddVersion(const AssetKey & key, const MockVersion & v) {\n versions[key] = make_shared(v);\n }\n virtual AssetHandle Get(const AssetKey &ref) {\n return AssetHandle(GetFromMap(ref), nullptr);\n }\n virtual AssetHandle GetMutable(const AssetKey &ref) {\n auto handle = AssetHandle(GetFromMap(ref), nullptr);\n dynamic_cast(handle.operator->())->loadedMutable = true;\n return handle;\n }\n void ResetLoadedMutable() {\n for (auto & v : versions) {\n v.second->loadedMutable = false;\n }\n }\n};\n\nclass StateUpdaterTest : public testing::Test {\n protected:\n MockStorageManager sm;\n StateUpdater updater;\n public:\n StateUpdaterTest() : sm(), updater(&sm) {}\n};\n\nvoid SetVersions(MockStorageManager & sm, vector versions) {\n for (auto & version: versions) {\n sm.AddVersion(version.name, version);\n }\n}\n\nAssetHandle GetVersion(MockStorageManager & sm, const AssetKey & key) {\n return sm.Get(fix(key));\n}\n\nAssetHandle GetMutableVersion(MockStorageManager & sm, const AssetKey & key) {\n return sm.GetMutable(fix(key));\n}\n\nvoid SetParentChild(MockStorageManager & sm, AssetKey parent, AssetKey child) {\n GetMutableVersion(sm, parent)->children.push_back(fix(child));\n GetMutableVersion(sm, child)->parents.push_back(fix(parent));\n}\n\nvoid SetListenerInput(MockStorageManager & sm, AssetKey listener, AssetKey input) {\n GetMutableVersion(sm, listener)->inputs.push_back(fix(input));\n GetMutableVersion(sm, input)->listeners.push_back(fix(listener));\n}\n\nvoid SetDependent(MockStorageManager & sm, AssetKey dependee, AssetKey dependent) {\n GetMutableVersion(sm, dependee)->dependents.push_back(fix(dependent));\n}\n\nvoid GetBigTree(MockStorageManager & sm) {\n SetVersions(sm,\n {\n MockVersion(\"gp\"),\n MockVersion(\"p1\"),\n MockVersion(\"p2\"),\n MockVersion(\"gpi\"),\n MockVersion(\"pi1\"),\n MockVersion(\"c1\"),\n MockVersion(\"c2\"),\n MockVersion(\"c3\"),\n MockVersion(\"c4\"),\n MockVersion(\"ci1\"),\n MockVersion(\"ci2\"),\n MockVersion(\"ci3\")\n });\n SetParentChild(sm, \"gp\", \"p1\");\n SetParentChild(sm, \"gp\", \"p2\");\n SetListenerInput(sm, \"gp\", \"gpi\");\n SetListenerInput(sm, \"p1\", \"pi1\");\n SetParentChild(sm, \"p1\", \"c1\");\n SetParentChild(sm, \"p1\", \"c2\");\n SetParentChild(sm, \"p2\", \"c3\");\n SetParentChild(sm, \"p2\", \"c4\");\n SetListenerInput(sm, \"c2\", \"ci3\");\n SetListenerInput(sm, \"c4\", \"ci1\");\n SetListenerInput(sm, \"c4\", \"ci2\");\n SetDependent(sm, \"gp\", \"p1\");\n SetDependent(sm, \"gp\", \"c2\");\n SetDependent(sm, \"p1\", \"c1\");\n}\n\nTEST_F(StateUpdaterTest, SetStateSingleVersion) {\n AssetKey ref1 = \"test1\";\n AssetKey ref2 = \"test2\";\n AssetKey ref3 = \"test3\";\n SetVersions(sm, {MockVersion(ref1), MockVersion(ref2), MockVersion(ref3)});\n updater.SetStateForRefAndDependents(fix(ref1), AssetDefs::Bad, [](AssetDefs::State) { return true; });\n ASSERT_TRUE(GetVersion(sm, ref1)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n updater.SetStateForRefAndDependents(fix(ref2), AssetDefs::Bad, [](AssetDefs::State) { return false; });\n ASSERT_FALSE(GetVersion(sm, ref2)->stateSet);\n ASSERT_FALSE(GetVersion(sm, ref3)->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersions) {\n GetBigTree(sm);\n updater.SetStateForRefAndDependents(fix(\"gp\"), AssetDefs::Canceled, [](AssetDefs::State) {return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c2\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n\n ASSERT_FALSE(GetVersion(sm, \"gp\")->notificationsSent);\n ASSERT_FALSE(GetVersion(sm, \"p1\")->notificationsSent);\n ASSERT_FALSE(GetVersion(sm, \"c1\")->notificationsSent);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->notificationsSent);\n}\n\nTEST_F(StateUpdaterTest, SetStateMultipleVersionsFromChild) {\n GetBigTree(sm);\n sm.ResetLoadedMutable();\n updater.SetStateForRefAndDependents(fix(\"p1\"), AssetDefs::Canceled, [](AssetDefs::State) { return true; });\n \n ASSERT_TRUE(GetVersion(sm, \"p1\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->stateSet);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->stateSet);\n\n ASSERT_TRUE(GetVersion(sm, \"p1\")->loadedMutable);\n ASSERT_TRUE(GetVersion(sm, \"c1\")->loadedMutable);\n \n ASSERT_FALSE(GetVersion(sm, \"gp\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"gpi\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"pi1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c3\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"c4\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci1\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci2\")->loadedMutable);\n ASSERT_FALSE(GetVersion(sm, \"ci3\")->loadedMutable);\n}\n\nTEST_F(StateUpdaterTest, SetState_StateDoesAndDoesntChange) {\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n GetMutableVersion(sm, \"a\")->state = CALCULATED_STATE;\n GetMutableVersion(sm, \"b\")->state = STARTING_STATE;\n \n updater.SetStateForRefAndDependents(fix(\"a\"), CALCULATED_STATE, [](AssetDefs::State) { return true; });\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n\n updater.SetStateForRefAndDependents(fix(\"b\"), CALCULATED_STATE, [](AssetDefs::State) { return true; });\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"b\")->stateSet);\n}\n\nTEST_F(StateUpdaterTest, SetStatePredicate) {\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n GetMutableVersion(sm, \"a\")->state = AssetDefs::Bad;\n GetMutableVersion(sm, \"b\")->state = AssetDefs::Canceled;\n SetDependent(sm, \"a\", \"b\");\n updater.SetStateForRefAndDependents(fix(\"a\"), AssetDefs::Succeeded, [](AssetDefs::State state) {\n return state != AssetDefs::Canceled;\n });\n ASSERT_TRUE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n}\n\nTEST_F(StateUpdaterTest, NeedComputeStateFalse) {\n SetVersions(sm, {MockVersion(\"a\")});\n updater.SetStateForRefAndDependents(fix(\"a\"), AssetDefs::Canceled, [](AssetDefs::State) { return true; });\n GetMutableVersion(sm, \"a\")->needComputeState = false;\n GetMutableVersion(sm, \"a\")->stateSet = false;\n updater.RecalculateAndSaveStates();\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n GetMutableVersion(sm, \"a\")->needComputeState = true;\n updater.RecalculateAndSaveStates();\n ASSERT_TRUE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"a\")->notificationsSent);\n}\n\nTEST_F(StateUpdaterTest, RecalculateState_StateDoesAndDoesntChange) {\n SetVersions(sm, {MockVersion(\"a\"), MockVersion(\"b\")});\n GetMutableVersion(sm, \"a\")->state = CALCULATED_STATE;\n GetMutableVersion(sm, \"b\")->state = STARTING_STATE;\n SetListenerInput(sm, \"a\", \"b\");\n GetMutableVersion(sm, \"a\")->loadedMutable = false;\n updater.SetStateForRefAndDependents(fix(\"a\"), CALCULATED_STATE, [](AssetDefs::State) { return false; });\n\n \/\/ Verify that the setup is correct\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"b\")->stateSet);\n \n updater.RecalculateAndSaveStates();\n ASSERT_FALSE(GetVersion(sm, \"a\")->stateSet);\n ASSERT_TRUE(GetVersion(sm, \"b\")->stateSet);\n ASSERT_FALSE(GetVersion(sm, \"a\")->loadedMutable);\n}\n\nint main(int argc, char **argv) {\n testing::InitGoogleTest(&argc,argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n\n#include \"MatrixOps.h\"\n#include \"MathUtils.h\"\n\n#include \n#include \n#include \n\nOCIO_NAMESPACE_ENTER\n{\n namespace\n {\n void ApplyClampExponent(float* rgbaBuffer, long numPixels,\n const float* exp4)\n {\n for(long pixelIndex=0; pixelIndex\";\n }\n \n std::string ExponentOp::getCacheID() const\n {\n return m_cacheID;\n }\n \n \/\/ TODO: compute real value for isNoOp\n bool ExponentOp::isNoOp() const\n {\n return false;\n }\n \n void ExponentOp::finalize()\n {\n if(m_direction == TRANSFORM_DIR_UNKNOWN)\n {\n throw Exception(\"Cannot apply ExponentOp op, unspecified transform direction.\");\n }\n \n if(m_direction == TRANSFORM_DIR_INVERSE)\n {\n for(int i=0; i<4; ++i)\n {\n if(!IsScalarEqualToZero(m_exp4[i]))\n {\n m_finalExp4[i] = 1.0f \/ m_exp4[i];\n }\n else\n {\n throw Exception(\"Cannot apply ExponentOp op, Cannot apply 0.0 exponent in the inverse.\");\n }\n }\n }\n else\n {\n memcpy(m_finalExp4, m_exp4, 4*sizeof(float));\n }\n \n \/\/ Create the cacheID\n std::ostringstream cacheIDStream;\n cacheIDStream << \"\";\n m_cacheID = cacheIDStream.str();\n }\n \n void ExponentOp::apply(float* rgbaBuffer, long numPixels) const\n {\n if(!rgbaBuffer) return;\n \n ApplyClampExponent(rgbaBuffer, numPixels, m_finalExp4);\n }\n \n bool ExponentOp::supportsGpuShader() const\n {\n return false;\n }\n \n void ExponentOp::writeGpuShader(std::ostringstream & \/*shader*\/,\n const std::string & \/*pixelName*\/,\n const GpuShaderDesc & \/*shaderDesc*\/) const\n {\n \/\/ TODO: Add Gpu Shader for exponent op\n throw Exception(\"ExponentOp does not support analytical shader generation.\");\n }\n \n bool ExponentOp::definesGpuAllocation() const\n {\n return false;\n }\n \n GpuAllocationData ExponentOp::getGpuAllocation() const\n {\n throw Exception(\"ExponentOp does not define a Gpu Allocation.\");\n }\n \n } \/\/ Anon namespace\n \n \n \n void CreateExponentOp(OpRcPtrVec & ops,\n const float * exp4,\n TransformDirection direction)\n {\n bool expIsIdentity = IsVecEqualToOne(exp4, 4);\n if(expIsIdentity) return;\n \n ops.push_back( OpRcPtr(new ExponentOp(exp4, direction)) );\n }\n}\nOCIO_NAMESPACE_EXIT\nexponentop implements gpu path\/*\nCopyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.\nAll Rights Reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n* Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n* Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n* Neither the name of Sony Pictures Imageworks nor the names of its\n contributors may be used to endorse or promote products derived from\n this software without specific prior written permission.\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n\n#include \"GpuShaderUtils.h\"\n#include \"MatrixOps.h\"\n#include \"MathUtils.h\"\n\nOCIO_NAMESPACE_ENTER\n{\n namespace\n {\n void ApplyClampExponent(float* rgbaBuffer, long numPixels,\n const float* exp4)\n {\n for(long pixelIndex=0; pixelIndex\";\n }\n \n std::string ExponentOp::getCacheID() const\n {\n return m_cacheID;\n }\n \n \/\/ TODO: compute real value for isNoOp\n bool ExponentOp::isNoOp() const\n {\n return false;\n }\n \n void ExponentOp::finalize()\n {\n if(m_direction == TRANSFORM_DIR_UNKNOWN)\n {\n throw Exception(\"Cannot apply ExponentOp op, unspecified transform direction.\");\n }\n \n if(m_direction == TRANSFORM_DIR_INVERSE)\n {\n for(int i=0; i<4; ++i)\n {\n if(!IsScalarEqualToZero(m_exp4[i]))\n {\n m_finalExp4[i] = 1.0f \/ m_exp4[i];\n }\n else\n {\n throw Exception(\"Cannot apply ExponentOp op, Cannot apply 0.0 exponent in the inverse.\");\n }\n }\n }\n else\n {\n memcpy(m_finalExp4, m_exp4, 4*sizeof(float));\n }\n \n \/\/ Create the cacheID\n std::ostringstream cacheIDStream;\n cacheIDStream << \"\";\n m_cacheID = cacheIDStream.str();\n }\n \n void ExponentOp::apply(float* rgbaBuffer, long numPixels) const\n {\n if(!rgbaBuffer) return;\n \n ApplyClampExponent(rgbaBuffer, numPixels, m_finalExp4);\n }\n \n bool ExponentOp::supportsGpuShader() const\n {\n return true;\n }\n \n void ExponentOp::writeGpuShader(std::ostringstream & shader,\n const std::string & pixelName,\n const GpuShaderDesc & shaderDesc) const\n {\n GpuLanguage lang = shaderDesc.getLanguage();\n float zerovec[4] = { 0.0f, 0.0f, 0.0f, 0.0f };\n \n shader << pixelName << \" = pow(\";\n shader << \"max(\" << pixelName << \", \" << GpuTextHalf4(zerovec, lang) << \")\";\n shader << \", \" << GpuTextHalf4(m_finalExp4, lang) << \");\\n\";\n }\n \n bool ExponentOp::definesGpuAllocation() const\n {\n return false;\n }\n \n GpuAllocationData ExponentOp::getGpuAllocation() const\n {\n throw Exception(\"ExponentOp does not define a Gpu Allocation.\");\n }\n \n } \/\/ Anon namespace\n \n \n \n void CreateExponentOp(OpRcPtrVec & ops,\n const float * exp4,\n TransformDirection direction)\n {\n bool expIsIdentity = IsVecEqualToOne(exp4, 4);\n if(expIsIdentity) return;\n \n ops.push_back( OpRcPtr(new ExponentOp(exp4, direction)) );\n }\n}\nOCIO_NAMESPACE_EXIT\n<|endoftext|>"} {"text":"\/**\n * @file rpc_manager.cpp\n *\n * @date Feb 7, 2017\n *\/\n\n#include \n#include \n\n#include \n\nnamespace derecho {\n\nnamespace rpc {\n\nthread_local bool _in_rpc_handler = false;\n\nRPCManager::~RPCManager() {\n thread_shutdown = true;\n if(rpc_thread.joinable()) {\n rpc_thread.join();\n }\n}\n\nvoid RPCManager::create_connections() {\n connections = std::make_unique(sst::P2PParams{nid, {nid}, view_manager.view_max_window_size, view_manager.view_max_payload_size + sizeof(header)});\n}\n\nvoid RPCManager::destroy_remote_invocable_class(uint32_t instance_id) {\n \/\/Delete receiver functions that were added by this class\/subgroup\n for(auto receivers_iterator = receivers->begin();\n receivers_iterator != receivers->end();) {\n if(receivers_iterator->first.subgroup_id == instance_id) {\n receivers_iterator = receivers->erase(receivers_iterator);\n } else {\n receivers_iterator++;\n }\n }\n \/\/Deliver a node_removed_from_shard_exception to the QueryResults for this class\n \/\/Important: This only works because the Replicated destructor runs before the\n \/\/wrapped_this member is destroyed; otherwise the PendingResults we're referencing\n \/\/would already have been deleted.\n std::lock_guard lock(pending_results_mutex);\n while(!pending_results_to_fulfill[instance_id].empty()) {\n pending_results_to_fulfill[instance_id].front().get().set_exception_for_caller_removed();\n pending_results_to_fulfill[instance_id].pop();\n }\n while(!fulfilled_pending_results[instance_id].empty()) {\n fulfilled_pending_results[instance_id].front().get().set_exception_for_caller_removed();\n fulfilled_pending_results[instance_id].pop_front();\n }\n}\n\nvoid RPCManager::start_listening() {\n std::lock_guard lock(thread_start_mutex);\n thread_start = true;\n thread_start_cv.notify_all();\n}\n\nstd::exception_ptr RPCManager::receive_message(\n const Opcode& indx, const node_id_t& received_from, char const* const buf,\n std::size_t payload_size, const std::function& out_alloc) {\n using namespace remote_invocation_utilities;\n assert(payload_size);\n auto receiver_function_entry = receivers->find(indx);\n if(receiver_function_entry == receivers->end()) {\n dbg_default_error(\"Received an RPC message with an invalid RPC opcode! Opcode was ({}, {}, {}, {}).\",\n indx.class_id, indx.subgroup_id, indx.function_id, indx.is_reply);\n \/\/TODO: We should reply with some kind of \"no such method\" error in this case\n return std::exception_ptr{};\n }\n std::size_t reply_header_size = header_space();\n recv_ret reply_return = receiver_function_entry->second(\n &rdv, received_from, buf,\n [&out_alloc, &reply_header_size](std::size_t size) {\n return out_alloc(size + reply_header_size) + reply_header_size;\n });\n auto* reply_buf = reply_return.payload;\n if(reply_buf) {\n reply_buf -= reply_header_size;\n const auto id = reply_return.opcode;\n const auto size = reply_return.size;\n populate_header(reply_buf, size, id, nid, 0);\n }\n return reply_return.possible_exception;\n}\n\nstd::exception_ptr RPCManager::parse_and_receive(char* buf, std::size_t size,\n const std::function& out_alloc) {\n using namespace remote_invocation_utilities;\n assert(size >= header_space());\n std::size_t payload_size = size;\n Opcode indx;\n node_id_t received_from;\n uint32_t flags;\n retrieve_header(&rdv, buf, payload_size, indx, received_from, flags);\n return receive_message(indx, received_from, buf + header_space(),\n payload_size, out_alloc);\n}\n\nvoid RPCManager::rpc_message_handler(subgroup_id_t subgroup_id, node_id_t sender_id,\n char* msg_buf, uint32_t buffer_size) {\n \/\/ WARNING: This assumes the current view doesn't change during execution!\n \/\/ (It accesses curr_view without a lock).\n\n \/\/ set the thread local rpc_handler context\n _in_rpc_handler = true;\n\n \/\/Use the reply-buffer allocation lambda to detect whether parse_and_receive generated a reply\n size_t reply_size = 0;\n char* reply_buf;\n parse_and_receive(msg_buf, buffer_size,\n [this, &reply_buf, &reply_size, &sender_id](size_t size) -> char* {\n reply_size = size;\n if(reply_size <= connections->get_max_p2p_size()) {\n reply_buf = (char*)connections->get_sendbuffer_ptr(\n connections->get_node_rank(sender_id), sst::REQUEST_TYPE::RPC_REPLY);\n return reply_buf;\n } else {\n \/\/ the reply size is too large - not part of the design to handle it\n return nullptr;\n }\n });\n if(sender_id == nid) {\n \/\/This is a self-receive of an RPC message I sent, so I have a reply-map that needs fulfilling\n int my_shard = view_manager.curr_view->multicast_group->get_subgroup_settings().at(subgroup_id).shard_num;\n std::unique_lock lock(pending_results_mutex);\n \/\/ because of a race condition, toFulfillQueue can genuinely be empty\n \/\/ so we shouldn't assert that it is empty\n \/\/ instead we should sleep on a condition variable and let the main thread that called the orderedSend signal us\n \/\/ although the race condition is infinitely rare\n pending_results_cv.wait(lock, [&]() { return !pending_results_to_fulfill[subgroup_id].empty(); });\n \/\/We now know the membership of \"all nodes in my shard of the subgroup\" in the current view\n pending_results_to_fulfill[subgroup_id].front().get().fulfill_map(\n view_manager.curr_view->subgroup_shard_views.at(subgroup_id).at(my_shard).members);\n fulfilled_pending_results[subgroup_id].push_back(\n std::move(pending_results_to_fulfill[subgroup_id].front()));\n pending_results_to_fulfill[subgroup_id].pop();\n if(reply_size > 0) {\n \/\/Since this was a self-receive, the reply also goes to myself\n parse_and_receive(\n reply_buf, reply_size,\n [](size_t size) -> char* { assert_always(false); });\n }\n } else if(reply_size > 0) {\n \/\/Otherwise, the only thing to do is send the reply (if there was one)\n connections->send(connections->get_node_rank(sender_id));\n }\n\n \/\/ clear the thread local rpc_handler context\n _in_rpc_handler = false;\n}\n\nvoid RPCManager::p2p_message_handler(node_id_t sender_id, char* msg_buf, uint32_t buffer_size) {\n using namespace remote_invocation_utilities;\n const std::size_t header_size = header_space();\n std::size_t payload_size;\n Opcode indx;\n node_id_t received_from;\n uint32_t flags;\n retrieve_header(nullptr, msg_buf, payload_size, indx, received_from, flags);\n size_t reply_size = 0;\n if(indx.is_reply) {\n \/\/ REPLYs can be handled here because they do not block.\n receive_message(indx, received_from, msg_buf + header_size, payload_size,\n [this, &msg_buf, &buffer_size, &reply_size, &sender_id](size_t _size) -> char* {\n reply_size = _size;\n if(reply_size <= buffer_size) {\n return (char*)connections->get_sendbuffer_ptr(\n connections->get_node_rank(sender_id), sst::REQUEST_TYPE::P2P_REPLY);\n }\n return nullptr;\n });\n if(reply_size > 0) {\n connections->send(connections->get_node_rank(sender_id));\n }\n } else if(RPC_HEADER_FLAG_TST(flags, CASCADE)) {\n \/\/ TODO: what is the lifetime of msg_buf? discuss with Sagar to make\n \/\/ sure the buffers are safely managed.\n \/\/ for cascading messages, we create a new thread.\n throw derecho::derecho_exception(\"Cascading P2P Send\/Queries to be implemented!\");\n } else {\n \/\/ send to fifo queue.\n std::unique_lock lock(fifo_queue_mutex);\n fifo_queue.emplace(sender_id, msg_buf, buffer_size);\n fifo_queue_cv.notify_one();\n }\n}\n\nvoid RPCManager::new_view_callback(const View& new_view) {\n std::lock_guard connections_lock(p2p_connections_mutex);\n connections = std::make_unique(std::move(*connections), new_view.members);\n dbg_default_debug(\"Created new connections among the new view members\");\n std::lock_guard lock(pending_results_mutex);\n for(auto& fulfilled_pending_results_pair : fulfilled_pending_results) {\n const subgroup_id_t subgroup_id = fulfilled_pending_results_pair.first;\n \/\/For each PendingResults in this subgroup, check the departed list of each shard\n \/\/the subgroup, and call set_exception_for_removed_node for the departed nodes\n for(auto pending_results_iter = fulfilled_pending_results_pair.second.begin();\n pending_results_iter != fulfilled_pending_results_pair.second.end();) {\n \/\/Garbage-collect PendingResults references that are obsolete\n if(pending_results_iter->get().all_responded()) {\n pending_results_iter = fulfilled_pending_results_pair.second.erase(pending_results_iter);\n } else {\n for(uint32_t shard_num = 0;\n shard_num < new_view.subgroup_shard_views[subgroup_id].size();\n ++shard_num) {\n for(auto removed_id : new_view.subgroup_shard_views[subgroup_id][shard_num].departed) {\n \/\/This will do nothing if removed_id was never in the\n \/\/shard this PendingResult corresponds to\n dbg_default_debug(\"Setting exception for removed node {} on PendingResults for subgroup {}, shard {}\", removed_id, subgroup_id, shard_num);\n pending_results_iter->get().set_exception_for_removed_node(removed_id);\n }\n }\n pending_results_iter++;\n }\n }\n }\n}\n\nbool RPCManager::finish_rpc_send(subgroup_id_t subgroup_id, PendingBase& pending_results_handle) {\n std::lock_guard lock(pending_results_mutex);\n pending_results_to_fulfill[subgroup_id].push(pending_results_handle);\n pending_results_cv.notify_all();\n return true;\n}\n\nvolatile char* RPCManager::get_sendbuffer_ptr(uint32_t dest_id, sst::REQUEST_TYPE type) {\n auto dest_rank = connections->get_node_rank(dest_id);\n volatile char* buf;\n do {\n buf = connections->get_sendbuffer_ptr(dest_rank, type);\n } while(!buf);\n return buf;\n}\n\nvoid RPCManager::finish_p2p_send(node_id_t dest_id, subgroup_id_t dest_subgroup_id, PendingBase& pending_results_handle) {\n connections->send(connections->get_node_rank(dest_id));\n pending_results_handle.fulfill_map({dest_id});\n std::lock_guard lock(pending_results_mutex);\n fulfilled_pending_results[dest_subgroup_id].push_back(pending_results_handle);\n}\n\nvoid RPCManager::fifo_worker() {\n pthread_setname_np(pthread_self(), \"fifo_thread\");\n using namespace remote_invocation_utilities;\n const std::size_t header_size = header_space();\n std::size_t payload_size;\n Opcode indx;\n node_id_t received_from;\n uint32_t flags;\n size_t reply_size = 0;\n fifo_req request;\n\n while(!thread_shutdown) {\n {\n std::unique_lock lock(fifo_queue_mutex);\n fifo_queue_cv.wait(lock, [&]() { return !fifo_queue.empty() || thread_shutdown; });\n if(thread_shutdown) {\n break;\n }\n request = fifo_queue.front();\n fifo_queue.pop();\n }\n retrieve_header(nullptr, request.msg_buf, payload_size, indx, received_from, flags);\n if(indx.is_reply || RPC_HEADER_FLAG_TST(flags, CASCADE)) {\n dbg_default_error(\"Invalid rpc message in fifo queue: is_reply={}, is_cascading={}\",\n indx.is_reply, RPC_HEADER_FLAG_TST(flags, CASCADE));\n throw derecho::derecho_exception(\"invalid rpc message in fifo queue...crash.\");\n }\n receive_message(indx, received_from, request.msg_buf + header_size, payload_size,\n [this, &reply_size, &request](size_t _size) -> char* {\n reply_size = _size;\n if(reply_size <= request.buffer_size) {\n return (char*)connections->get_sendbuffer_ptr(\n connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY);\n }\n return nullptr;\n });\n if(reply_size > 0) {\n connections->send(connections->get_node_rank(request.sender_id));\n } else {\n \/\/ hack for now to \"simulate\" a reply for p2p_sends to functions that do not generate a reply\n char* buf = connections->get_sendbuffer_ptr(connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY);\n buf[0] = 0;\n connections->send(connections->get_node_rank(request.sender_id));\n }\n }\n}\n\nvoid RPCManager::p2p_receive_loop() {\n pthread_setname_np(pthread_self(), \"rpc_thread\");\n uint64_t max_payload_size = getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);\n \/\/ set the thread local rpc_handler context\n _in_rpc_handler = true;\n\n while(!thread_start) {\n std::unique_lock lock(thread_start_mutex);\n thread_start_cv.wait(lock, [this]() { return thread_start; });\n }\n dbg_default_debug(\"P2P listening thread started\");\n \/\/ start the fifo worker thread\n fifo_worker_thread = std::thread(&RPCManager::fifo_worker, this);\n \/\/ loop event\n while(!thread_shutdown) {\n std::lock_guard connections_lock(p2p_connections_mutex);\n auto optional_reply_pair = connections->probe_all();\n if(optional_reply_pair) {\n auto reply_pair = optional_reply_pair.value();\n p2p_message_handler(reply_pair.first, (char*)reply_pair.second, max_payload_size);\n }\n }\n \/\/ stop fifo worker.\n fifo_queue_cv.notify_one();\n fifo_worker_thread.join();\n}\n\nbool in_rpc_handler() {\n return _in_rpc_handler;\n}\n} \/\/ namespace rpc\n} \/\/ namespace derecho\nFixed a potential deadlock in rpc_message_handler\/**\n * @file rpc_manager.cpp\n *\n * @date Feb 7, 2017\n *\/\n\n#include \n#include \n\n#include \n\nnamespace derecho {\n\nnamespace rpc {\n\nthread_local bool _in_rpc_handler = false;\n\nRPCManager::~RPCManager() {\n thread_shutdown = true;\n if(rpc_thread.joinable()) {\n rpc_thread.join();\n }\n}\n\nvoid RPCManager::create_connections() {\n connections = std::make_unique(sst::P2PParams{nid, {nid}, view_manager.view_max_window_size, view_manager.view_max_payload_size + sizeof(header)});\n}\n\nvoid RPCManager::destroy_remote_invocable_class(uint32_t instance_id) {\n \/\/Delete receiver functions that were added by this class\/subgroup\n for(auto receivers_iterator = receivers->begin();\n receivers_iterator != receivers->end();) {\n if(receivers_iterator->first.subgroup_id == instance_id) {\n receivers_iterator = receivers->erase(receivers_iterator);\n } else {\n receivers_iterator++;\n }\n }\n \/\/Deliver a node_removed_from_shard_exception to the QueryResults for this class\n \/\/Important: This only works because the Replicated destructor runs before the\n \/\/wrapped_this member is destroyed; otherwise the PendingResults we're referencing\n \/\/would already have been deleted.\n std::lock_guard lock(pending_results_mutex);\n while(!pending_results_to_fulfill[instance_id].empty()) {\n pending_results_to_fulfill[instance_id].front().get().set_exception_for_caller_removed();\n pending_results_to_fulfill[instance_id].pop();\n }\n while(!fulfilled_pending_results[instance_id].empty()) {\n fulfilled_pending_results[instance_id].front().get().set_exception_for_caller_removed();\n fulfilled_pending_results[instance_id].pop_front();\n }\n}\n\nvoid RPCManager::start_listening() {\n std::lock_guard lock(thread_start_mutex);\n thread_start = true;\n thread_start_cv.notify_all();\n}\n\nstd::exception_ptr RPCManager::receive_message(\n const Opcode& indx, const node_id_t& received_from, char const* const buf,\n std::size_t payload_size, const std::function& out_alloc) {\n using namespace remote_invocation_utilities;\n assert(payload_size);\n auto receiver_function_entry = receivers->find(indx);\n if(receiver_function_entry == receivers->end()) {\n dbg_default_error(\"Received an RPC message with an invalid RPC opcode! Opcode was ({}, {}, {}, {}).\",\n indx.class_id, indx.subgroup_id, indx.function_id, indx.is_reply);\n \/\/TODO: We should reply with some kind of \"no such method\" error in this case\n return std::exception_ptr{};\n }\n std::size_t reply_header_size = header_space();\n recv_ret reply_return = receiver_function_entry->second(\n &rdv, received_from, buf,\n [&out_alloc, &reply_header_size](std::size_t size) {\n return out_alloc(size + reply_header_size) + reply_header_size;\n });\n auto* reply_buf = reply_return.payload;\n if(reply_buf) {\n reply_buf -= reply_header_size;\n const auto id = reply_return.opcode;\n const auto size = reply_return.size;\n populate_header(reply_buf, size, id, nid, 0);\n }\n return reply_return.possible_exception;\n}\n\nstd::exception_ptr RPCManager::parse_and_receive(char* buf, std::size_t size,\n const std::function& out_alloc) {\n using namespace remote_invocation_utilities;\n assert(size >= header_space());\n std::size_t payload_size = size;\n Opcode indx;\n node_id_t received_from;\n uint32_t flags;\n retrieve_header(&rdv, buf, payload_size, indx, received_from, flags);\n return receive_message(indx, received_from, buf + header_space(),\n payload_size, out_alloc);\n}\n\nvoid RPCManager::rpc_message_handler(subgroup_id_t subgroup_id, node_id_t sender_id,\n char* msg_buf, uint32_t buffer_size) {\n \/\/ WARNING: This assumes the current view doesn't change during execution!\n \/\/ (It accesses curr_view without a lock).\n\n \/\/ set the thread local rpc_handler context\n _in_rpc_handler = true;\n\n \/\/Use the reply-buffer allocation lambda to detect whether parse_and_receive generated a reply\n size_t reply_size = 0;\n char* reply_buf;\n parse_and_receive(msg_buf, buffer_size,\n [this, &reply_buf, &reply_size, &sender_id](size_t size) -> char* {\n reply_size = size;\n if(reply_size <= connections->get_max_p2p_size()) {\n reply_buf = (char*)connections->get_sendbuffer_ptr(\n connections->get_node_rank(sender_id), sst::REQUEST_TYPE::RPC_REPLY);\n return reply_buf;\n } else {\n \/\/ the reply size is too large - not part of the design to handle it\n return nullptr;\n }\n });\n if(sender_id == nid) {\n \/\/This is a self-receive of an RPC message I sent, so I have a reply-map that needs fulfilling\n const uint32_t my_shard = view_manager.curr_view->my_subgroups.at(subgroup_id);\n {\n std::unique_lock lock(pending_results_mutex);\n \/\/ because of a race condition, pending_results_to_fulfill can genuinely be empty\n \/\/ so before accessing it we should sleep on a condition variable and let the main\n \/\/ thread that called the orderedSend signal us\n \/\/ although the race condition is infinitely rare\n pending_results_cv.wait(lock, [&]() { return !pending_results_to_fulfill[subgroup_id].empty(); });\n \/\/We now know the membership of \"all nodes in my shard of the subgroup\" in the current view\n pending_results_to_fulfill[subgroup_id].front().get().fulfill_map(\n view_manager.curr_view->subgroup_shard_views.at(subgroup_id).at(my_shard).members);\n fulfilled_pending_results[subgroup_id].push_back(\n std::move(pending_results_to_fulfill[subgroup_id].front()));\n pending_results_to_fulfill[subgroup_id].pop();\n } \/\/release pending_results_mutex\n if(reply_size > 0) {\n \/\/Since this was a self-receive, the reply also goes to myself\n parse_and_receive(\n reply_buf, reply_size,\n [](size_t size) -> char* { assert_always(false); });\n }\n } else if(reply_size > 0) {\n \/\/Otherwise, the only thing to do is send the reply (if there was one)\n connections->send(connections->get_node_rank(sender_id));\n }\n\n \/\/ clear the thread local rpc_handler context\n _in_rpc_handler = false;\n}\n\nvoid RPCManager::p2p_message_handler(node_id_t sender_id, char* msg_buf, uint32_t buffer_size) {\n using namespace remote_invocation_utilities;\n const std::size_t header_size = header_space();\n std::size_t payload_size;\n Opcode indx;\n node_id_t received_from;\n uint32_t flags;\n retrieve_header(nullptr, msg_buf, payload_size, indx, received_from, flags);\n size_t reply_size = 0;\n if(indx.is_reply) {\n \/\/ REPLYs can be handled here because they do not block.\n receive_message(indx, received_from, msg_buf + header_size, payload_size,\n [this, &msg_buf, &buffer_size, &reply_size, &sender_id](size_t _size) -> char* {\n reply_size = _size;\n if(reply_size <= buffer_size) {\n return (char*)connections->get_sendbuffer_ptr(\n connections->get_node_rank(sender_id), sst::REQUEST_TYPE::P2P_REPLY);\n }\n return nullptr;\n });\n if(reply_size > 0) {\n connections->send(connections->get_node_rank(sender_id));\n }\n } else if(RPC_HEADER_FLAG_TST(flags, CASCADE)) {\n \/\/ TODO: what is the lifetime of msg_buf? discuss with Sagar to make\n \/\/ sure the buffers are safely managed.\n \/\/ for cascading messages, we create a new thread.\n throw derecho::derecho_exception(\"Cascading P2P Send\/Queries to be implemented!\");\n } else {\n \/\/ send to fifo queue.\n std::unique_lock lock(fifo_queue_mutex);\n fifo_queue.emplace(sender_id, msg_buf, buffer_size);\n fifo_queue_cv.notify_one();\n }\n}\n\nvoid RPCManager::new_view_callback(const View& new_view) {\n std::lock_guard connections_lock(p2p_connections_mutex);\n connections = std::make_unique(std::move(*connections), new_view.members);\n dbg_default_debug(\"Created new connections among the new view members\");\n std::lock_guard lock(pending_results_mutex);\n for(auto& fulfilled_pending_results_pair : fulfilled_pending_results) {\n const subgroup_id_t subgroup_id = fulfilled_pending_results_pair.first;\n \/\/For each PendingResults in this subgroup, check the departed list of each shard\n \/\/the subgroup, and call set_exception_for_removed_node for the departed nodes\n for(auto pending_results_iter = fulfilled_pending_results_pair.second.begin();\n pending_results_iter != fulfilled_pending_results_pair.second.end();) {\n \/\/Garbage-collect PendingResults references that are obsolete\n if(pending_results_iter->get().all_responded()) {\n pending_results_iter = fulfilled_pending_results_pair.second.erase(pending_results_iter);\n } else {\n for(uint32_t shard_num = 0;\n shard_num < new_view.subgroup_shard_views[subgroup_id].size();\n ++shard_num) {\n for(auto removed_id : new_view.subgroup_shard_views[subgroup_id][shard_num].departed) {\n \/\/This will do nothing if removed_id was never in the\n \/\/shard this PendingResult corresponds to\n dbg_default_debug(\"Setting exception for removed node {} on PendingResults for subgroup {}, shard {}\", removed_id, subgroup_id, shard_num);\n pending_results_iter->get().set_exception_for_removed_node(removed_id);\n }\n }\n pending_results_iter++;\n }\n }\n }\n}\n\nbool RPCManager::finish_rpc_send(subgroup_id_t subgroup_id, PendingBase& pending_results_handle) {\n std::lock_guard lock(pending_results_mutex);\n pending_results_to_fulfill[subgroup_id].push(pending_results_handle);\n pending_results_cv.notify_all();\n return true;\n}\n\nvolatile char* RPCManager::get_sendbuffer_ptr(uint32_t dest_id, sst::REQUEST_TYPE type) {\n auto dest_rank = connections->get_node_rank(dest_id);\n volatile char* buf;\n do {\n buf = connections->get_sendbuffer_ptr(dest_rank, type);\n } while(!buf);\n return buf;\n}\n\nvoid RPCManager::finish_p2p_send(node_id_t dest_id, subgroup_id_t dest_subgroup_id, PendingBase& pending_results_handle) {\n connections->send(connections->get_node_rank(dest_id));\n pending_results_handle.fulfill_map({dest_id});\n std::lock_guard lock(pending_results_mutex);\n fulfilled_pending_results[dest_subgroup_id].push_back(pending_results_handle);\n}\n\nvoid RPCManager::fifo_worker() {\n pthread_setname_np(pthread_self(), \"fifo_thread\");\n using namespace remote_invocation_utilities;\n const std::size_t header_size = header_space();\n std::size_t payload_size;\n Opcode indx;\n node_id_t received_from;\n uint32_t flags;\n size_t reply_size = 0;\n fifo_req request;\n\n while(!thread_shutdown) {\n {\n std::unique_lock lock(fifo_queue_mutex);\n fifo_queue_cv.wait(lock, [&]() { return !fifo_queue.empty() || thread_shutdown; });\n if(thread_shutdown) {\n break;\n }\n request = fifo_queue.front();\n fifo_queue.pop();\n }\n retrieve_header(nullptr, request.msg_buf, payload_size, indx, received_from, flags);\n if(indx.is_reply || RPC_HEADER_FLAG_TST(flags, CASCADE)) {\n dbg_default_error(\"Invalid rpc message in fifo queue: is_reply={}, is_cascading={}\",\n indx.is_reply, RPC_HEADER_FLAG_TST(flags, CASCADE));\n throw derecho::derecho_exception(\"invalid rpc message in fifo queue...crash.\");\n }\n receive_message(indx, received_from, request.msg_buf + header_size, payload_size,\n [this, &reply_size, &request](size_t _size) -> char* {\n reply_size = _size;\n if(reply_size <= request.buffer_size) {\n return (char*)connections->get_sendbuffer_ptr(\n connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY);\n }\n return nullptr;\n });\n if(reply_size > 0) {\n connections->send(connections->get_node_rank(request.sender_id));\n } else {\n \/\/ hack for now to \"simulate\" a reply for p2p_sends to functions that do not generate a reply\n char* buf = connections->get_sendbuffer_ptr(connections->get_node_rank(request.sender_id), sst::REQUEST_TYPE::P2P_REPLY);\n buf[0] = 0;\n connections->send(connections->get_node_rank(request.sender_id));\n }\n }\n}\n\nvoid RPCManager::p2p_receive_loop() {\n pthread_setname_np(pthread_self(), \"rpc_thread\");\n uint64_t max_payload_size = getConfUInt64(CONF_SUBGROUP_DEFAULT_MAX_PAYLOAD_SIZE);\n \/\/ set the thread local rpc_handler context\n _in_rpc_handler = true;\n\n while(!thread_start) {\n std::unique_lock lock(thread_start_mutex);\n thread_start_cv.wait(lock, [this]() { return thread_start; });\n }\n dbg_default_debug(\"P2P listening thread started\");\n \/\/ start the fifo worker thread\n fifo_worker_thread = std::thread(&RPCManager::fifo_worker, this);\n \/\/ loop event\n while(!thread_shutdown) {\n std::lock_guard connections_lock(p2p_connections_mutex);\n auto optional_reply_pair = connections->probe_all();\n if(optional_reply_pair) {\n auto reply_pair = optional_reply_pair.value();\n p2p_message_handler(reply_pair.first, (char*)reply_pair.second, max_payload_size);\n }\n }\n \/\/ stop fifo worker.\n fifo_queue_cv.notify_one();\n fifo_worker_thread.join();\n}\n\nbool in_rpc_handler() {\n return _in_rpc_handler;\n}\n} \/\/ namespace rpc\n} \/\/ namespace derecho\n<|endoftext|>"} {"text":"#include \n#include \n\nint main() {\n using namespace dx;\n using namespace std;\n try\n {\n JSON j1(JSON_OBJECT);\n\n std::cout<<\"Eps = \"<(5,5);\n std::map mp;\n mp[\"lala\"] = 12.11e-212;\n mp[\"dsdsd\"] = 1212;\n j3[\"map\"] = mp;\n std::cout<<\"\\nj3 = \"<first] == it->second);\n std::cout<<\"Key = \"<first<<\", Value = \"<second.toString()<first] == it->second);\n std::cout<<\"Key = \"<first<<\", Value = \"<second.toString()< ObjectIterator\n \/\/ObjectIterator it = j4.ObjectBegin();\n \/\/ JSON Iterators (different class);\n\n \/\/for (; it != j4.end(); ++it) {\n\n \/\/ }\n\n \/\/ Check implicit cast operators\n JSON j11(JSON_OBJECT);\n j11[\"1\"] = 1;\n j11[\"2\"] = 12.33;\n j11[\"3\"] = true;\n j11[\"4\"] = 212l;\n j11[\"4.1\"] = \"blahh\";\n j11[\"5\"] = vector(5,0);\n j11[\"6\"] = \"1\";\n\n assert(j11[\"5\"][0.9] == 0);\n assert(j11[\"5\"][j11[\"1\"]] == 0);\n\n assert(j11.has(\"1\"));\n assert(!j11.has(\"random\"));\n assert(j11[\"5\"].has(0));\n assert(j11[\"5\"].has(1));\n assert(j11[\"5\"].has(j11[\"5\"][0]));\n assert(j11.has(j11[\"6\"]) && j11[j11[\"6\"]] == 1);\n assert(j11[\"5\"][j11[\"1\"]] == 0);\n assert(double(j11[\"1\"]) == 1);\n assert(double(j11[\"2\"]) == 12.33);\n assert(bool(j11[\"3\"]) == true);\n assert(j11[\"4.1\"].toString() == \"\\\"blahh\\\"\");\n assert(long(j11[\"4\"]) == 212l);\n assert(double(j11[\"1\"]) < double(j11[\"2\"]));\n\n const JSON j12(j11);\n\n assert(j12[\"5\"][0.9] == 0);\n assert(j12[\"5\"][j11[\"1\"]] == 0);\n\n\n assert(j12[\"5\"][j11[\"1\"]] == 0);\n assert(double(j12[\"1\"]) == 1);\n assert(double(j12[\"2\"]) == 12.33);\n assert(bool(j12[\"3\"]) == true);\n assert(j12[\"4.1\"].toString() == \"\\\"blahh\\\"\");\n assert(long(j12[\"4\"]) == 212l);\n assert(double(j12[\"1\"]) < double(j11[\"2\"]));\n\n JSON j13(JSON_OBJECT);\n j13[\"foo\"] = \"blah\";\n j13[\"foo2\"] = 12;\n j13[\"foo3\"] = 12.32;\n std::string str1 = j13[\"foo\"].get();\n assert(str1 == \"blah\");\n assert(j13[\"foo2\"].get() == 12);\n assert(j13[\"foo3\"].get() == 12.32);\n assert(j13[\"foo3\"].get() == true);\n\n JSON j14(JSON_NULL);\n assert(j14 == JSON_NULL);\n\n std::cout<<\"\\nAll assertions performed succesfully\\n\";\n }\n catch (exception &e)\n {\n std::cout<<\"\\nErrror occured: \\n\"<Made dxjson\/trial.cpp compilable on clang#include \n#include \"dxjson.h\"\n\nint main() {\n using namespace dx;\n using namespace std;\n try\n {\n JSON j1(JSON_OBJECT);\n\n std::cout<<\"Eps = \"<(5,5);\n std::map mp;\n mp[\"lala\"] = 12.11e-212;\n mp[\"dsdsd\"] = 1212;\n j3[\"map\"] = mp;\n std::cout<<\"\\nj3 = \"<first] == it->second);\n std::cout<<\"Key = \"<first<<\", Value = \"<second.toString()<first] == it->second);\n std::cout<<\"Key = \"<first<<\", Value = \"<second.toString()< ObjectIterator\n \/\/ObjectIterator it = j4.ObjectBegin();\n \/\/ JSON Iterators (different class);\n\n \/\/for (; it != j4.end(); ++it) {\n\n \/\/ }\n\n \/\/ Check implicit cast operators\n JSON j11(JSON_OBJECT);\n j11[\"1\"] = 1;\n j11[\"2\"] = 12.33;\n j11[\"3\"] = true;\n j11[\"4\"] = 212l;\n j11[\"4.1\"] = \"blahh\";\n j11[\"5\"] = vector(5,0);\n j11[\"6\"] = \"1\";\n\n assert(j11[\"5\"][0.9].get() == 0);\n assert(j11[\"5\"][j11[\"1\"]].get() == 0);\n\n assert(j11.has(\"1\"));\n assert(!j11.has(\"random\"));\n assert(j11[\"5\"].has(0));\n assert(j11[\"5\"].has(1));\n assert(j11[\"5\"].has(j11[\"5\"][0]));\n assert(j11.has(j11[\"6\"]) && j11[j11[\"6\"]].get() == 1);\n assert(j11[\"5\"][j11[\"1\"]].get() == 0);\n assert(double(j11[\"1\"]) == 1);\n assert(double(j11[\"2\"]) == 12.33);\n assert(bool(j11[\"3\"]) == true);\n assert(j11[\"4.1\"].toString() == \"\\\"blahh\\\"\");\n assert(long(j11[\"4\"]) == 212l);\n assert(double(j11[\"1\"]) < double(j11[\"2\"]));\n\n const JSON j12(j11);\n\n assert(j12[\"5\"][0.9].get() == 0);\n assert(j12[\"5\"][j11[\"1\"]].get() == 0);\n\n\n assert(j12[\"5\"][j11[\"1\"]].get() == 0);\n assert(double(j12[\"1\"]) == 1);\n assert(double(j12[\"2\"]) == 12.33);\n assert(bool(j12[\"3\"]) == true);\n assert(j12[\"4.1\"].toString() == \"\\\"blahh\\\"\");\n assert(long(j12[\"4\"]) == 212l);\n assert(double(j12[\"1\"]) < double(j11[\"2\"]));\n\n JSON j13(JSON_OBJECT);\n j13[\"foo\"] = \"blah\";\n j13[\"foo2\"] = 12;\n j13[\"foo3\"] = 12.32;\n std::string str1 = j13[\"foo\"].get();\n assert(str1 == \"blah\");\n assert(j13[\"foo2\"].get() == 12);\n assert(j13[\"foo3\"].get() == 12.32);\n assert(j13[\"foo3\"].get() == true);\n\n JSON j14(JSON_NULL);\n assert(j14 == JSON(JSON_NULL));\n\n std::cout<<\"\\nAll assertions performed succesfully\\n\";\n }\n catch (exception &e)\n {\n std::cout<<\"\\nErrror occured: \\n\"<"} {"text":"\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 7\/19\/16.\n\/\/\n\n#include \"Preferences.h\"\n\n#include\n\n#include \n\/\/#include \n\n#include \n#include \n\nPreferences::Preferences(const std::string& databaseName, const std::string& tableName)\n\t\t: TABLE_NAME(tableName)\n\t\t, DATABSE_FILE_NAME(databaseName)\n{\n\t\/\/\tPoco::Data::SQLite::Connector::registerConnector();\n\n\trecreate();\n}\n\nPreferences::~Preferences()\n{\n\tif (_session != nullptr)\n\t{\n\t\t_session->close();\n\t}\n\t\/\/\tPoco::Data::SQLite::Connector::unregisterConnector();\n}\n\nvoid Preferences::setValue(const std::string& key, const std::string& value)\n{\n\t_cache[key] = value;\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tPoco::Data::Statement insert(session);\n\tinsert << \"INSERT OR REPLACE INTO \" << TABLE_NAME << \" VALUES(?, ?)\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::useRef(value);\n\tDLOG(\"Preferences: %s\\n(%s)=(%s)\", insert.toString().c_str(), key.c_str(), value.c_str());\n\n\tinsert.execute();\n}\n\nstd::string Preferences::getValue(const std::string& key, const std::string& defaultValue)\n{\n\tauto found = _cache.find(key);\n\tif (found != _cache.end())\n\t{\n\t\treturn found->second;\n\t}\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\t_cache[key] = defaultValue;\n\t\treturn defaultValue;\n\t}\n\n\tstd::string returnedValue = defaultValue;\n\n\tPoco::Data::Session& session = *_session;\n\n\n\t\/\/ a simple query\n\tPoco::Data::Statement select(session);\n\tselect << \"SELECT value FROM \" << TABLE_NAME << \" WHERE key=?\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::into(returnedValue); \/\/ iterate over result set one row at a time\n\n\tDLOG(\"Select: %s\\nkey:%s\", select.toString().c_str(), key.c_str());\n\tselect.execute();\n\n\t_cache[key] = returnedValue;\n\treturn returnedValue;\n}\n\nvoid Preferences::clean()\n{\n\t_cache.clear();\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\t_session->close();\n\n\tif (std::remove(DATABSE_FILE_NAME.c_str()) != 0)\n\t{\n\t\tELOG(\"Can't remove database: %s\", DATABSE_FILE_NAME.c_str());\n\t}\n\trecreate();\n}\n\nvoid Preferences::recreate()\n{\n\ttry\n\t{\n\t\t_session = std::make_unique(\"SQLite\", DATABSE_FILE_NAME.c_str());\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tELOG(\"Can't create session: %s\", ex.what());\n\t}\n\tcatch (...)\n\t{\n\t\tELOG(\"Can't create session\");\n\t}\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tsession << \"CREATE TABLE IF NOT EXISTS `\" << TABLE_NAME << \"`(\"\n\t\t\t\"`key` TEXT NOT NULL UNIQUE,\"\n\t\t\t\"`value` TEXT,\"\n\t\t\t\"PRIMARY KEY(key)\"\n\t\t\t\");\", Poco::Data::Keywords::now;\n}\nFix Preferences (after android changes)\/\/\n\/\/ Created by Dawid Drozd aka Gelldur on 7\/19\/16.\n\/\/\n\n#include \"Preferences.h\"\n\n#include\n\n#include \n#include \n\n#include \n#include \n\nPreferences::Preferences(const std::string& databaseName, const std::string& tableName)\n\t\t: TABLE_NAME(tableName)\n\t\t, DATABSE_FILE_NAME(databaseName)\n{\n\tPoco::Data::SQLite::Connector::registerConnector();\n\n\trecreate();\n}\n\nPreferences::~Preferences()\n{\n\tif (_session != nullptr)\n\t{\n\t\t_session->close();\n\t}\n\tPoco::Data::SQLite::Connector::unregisterConnector();\n}\n\nvoid Preferences::setValue(const std::string& key, const std::string& value)\n{\n\t_cache[key] = value;\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tPoco::Data::Statement insert(session);\n\tinsert << \"INSERT OR REPLACE INTO \" << TABLE_NAME << \" VALUES(?, ?)\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::useRef(value);\n\tDLOG(\"Preferences: %s\\n(%s)=(%s)\", insert.toString().c_str(), key.c_str(), value.c_str());\n\n\tinsert.execute();\n}\n\nstd::string Preferences::getValue(const std::string& key, const std::string& defaultValue)\n{\n\tauto found = _cache.find(key);\n\tif (found != _cache.end())\n\t{\n\t\treturn found->second;\n\t}\n\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\t_cache[key] = defaultValue;\n\t\treturn defaultValue;\n\t}\n\n\tstd::string returnedValue = defaultValue;\n\n\tPoco::Data::Session& session = *_session;\n\n\n\t\/\/ a simple query\n\tPoco::Data::Statement select(session);\n\tselect << \"SELECT value FROM \" << TABLE_NAME << \" WHERE key=?\",\n\t\t\tPoco::Data::Keywords::useRef(key),\n\t\t\tPoco::Data::Keywords::into(returnedValue); \/\/ iterate over result set one row at a time\n\n\tDLOG(\"Select: %s\\nkey:%s\", select.toString().c_str(), key.c_str());\n\tselect.execute();\n\n\t_cache[key] = returnedValue;\n\treturn returnedValue;\n}\n\nvoid Preferences::clean()\n{\n\t_cache.clear();\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\t_session->close();\n\n\tif (std::remove(DATABSE_FILE_NAME.c_str()) != 0)\n\t{\n\t\tELOG(\"Can't remove database: %s\", DATABSE_FILE_NAME.c_str());\n\t}\n\trecreate();\n}\n\nvoid Preferences::recreate()\n{\n\ttry\n\t{\n\t\t_session = std::make_unique(\"SQLite\", DATABSE_FILE_NAME.c_str());\n\t}\n\tcatch (const std::exception& ex)\n\t{\n\t\tELOG(\"Can't create session: %s\", ex.what());\n\t}\n\tcatch (...)\n\t{\n\t\tELOG(\"Can't create session\");\n\t}\n\tif (_session == nullptr)\n\t{\n\t\tELOG(\"Session not created\\nNo storage\");\n\t\treturn;\n\t}\n\n\tPoco::Data::Session& session = *_session;\n\n\tsession << \"CREATE TABLE IF NOT EXISTS `\" << TABLE_NAME << \"`(\"\n\t\t\t\"`key` TEXT NOT NULL UNIQUE,\"\n\t\t\t\"`value` TEXT,\"\n\t\t\t\"PRIMARY KEY(key)\"\n\t\t\t\");\", Poco::Data::Keywords::now;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $\n\n\/\/ mapnik\n#include \n\n#include \n\n\/\/ boost\n#include \n#include \n#include \n\n\/\/ ltdl\n#include \n\n\/\/ stl\n#include \n#include \n\nnamespace mapnik\n{\n using namespace std;\n using namespace boost;\n \n bool is_input_plugin (std::string const& filename)\n {\n return boost::algorithm::ends_with(filename,std::string(\".input\"));\n }\n \n\n datasource_cache::datasource_cache()\n {\n if (lt_dlinit()) throw std::runtime_error(\"lt_dlinit() failed\");\n }\n\n datasource_cache::~datasource_cache()\n {\n lt_dlexit();\n }\n\n std::map > datasource_cache::plugins_;\n bool datasource_cache::registered_=false;\n \n datasource_ptr datasource_cache::create(const parameters& params) \n {\n boost::optional type = params.get(\"type\");\n if ( ! type)\n {\n throw config_error(string(\"Could not create datasource. Required \") +\n \"parameter 'type' is missing\");\n }\n\n datasource_ptr ds;\n map >::iterator itr=plugins_.find(*type);\n if ( itr == plugins_.end() )\n {\n throw config_error(string(\"Could not create datasource. No plugin \") +\n \"found for type '\" + * type + \"'\");\n }\n if ( ! itr->second->handle())\n {\n throw std::runtime_error(string(\"Cannot load library: \") + \n lt_dlerror());\n }\n\n create_ds* create_datasource = \n (create_ds*) lt_dlsym(itr->second->handle(), \"create\");\n\n if ( ! create_datasource)\n {\n throw std::runtime_error(string(\"Cannot load symbols: \") + \n lt_dlerror());\n }\n std::cout << \"size = \" << params.size() << \"\\n\";\n parameters::const_iterator i = params.begin();\n for (;i!=params.end();++i)\n {\n std::cout << i->first << \"=\" << i->second << \"\\n\"; \n }\n ds=datasource_ptr(create_datasource(params), datasource_deleter());\n\n#ifdef MAPNIK_DEBUG\n std::clog<<\"datasource=\"<\n (new PluginInfo(type,module)))).second; \n }\n\n void datasource_cache::register_datasources(const std::string& str)\n {\t\n mutex::scoped_lock lock(mapnik::singleton::mutex_);\n filesystem::path path(str);\n filesystem::directory_iterator end_itr;\n if (exists(path) && is_directory(path))\n {\n for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )\n {\n if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))\n {\n try \n {\n lt_dlhandle module=lt_dlopen(itr->string().c_str());\n if (module)\n {\n datasource_name* ds_name = \n (datasource_name*) lt_dlsym(module, \"datasource_name\");\n if (ds_name && insert(ds_name(),module))\n { \n#ifdef MAPNIK_DEBUG\n std::clog<<\"registered datasource : \"<only print to clog when MAPNIK_DEBUG is defined\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/$Id: datasource_cache.cpp 23 2005-03-22 22:16:34Z pavlenko $\n\n\/\/ mapnik\n#include \n\n#include \n\n\/\/ boost\n#include \n#include \n#include \n\n\/\/ ltdl\n#include \n\n\/\/ stl\n#include \n#include \n\nnamespace mapnik\n{\n using namespace std;\n using namespace boost;\n \n bool is_input_plugin (std::string const& filename)\n {\n return boost::algorithm::ends_with(filename,std::string(\".input\"));\n }\n \n\n datasource_cache::datasource_cache()\n {\n if (lt_dlinit()) throw std::runtime_error(\"lt_dlinit() failed\");\n }\n\n datasource_cache::~datasource_cache()\n {\n lt_dlexit();\n }\n\n std::map > datasource_cache::plugins_;\n bool datasource_cache::registered_=false;\n \n datasource_ptr datasource_cache::create(const parameters& params) \n {\n boost::optional type = params.get(\"type\");\n if ( ! type)\n {\n throw config_error(string(\"Could not create datasource. Required \") +\n \"parameter 'type' is missing\");\n }\n\n datasource_ptr ds;\n map >::iterator itr=plugins_.find(*type);\n if ( itr == plugins_.end() )\n {\n throw config_error(string(\"Could not create datasource. No plugin \") +\n \"found for type '\" + * type + \"'\");\n }\n if ( ! itr->second->handle())\n {\n throw std::runtime_error(string(\"Cannot load library: \") + \n lt_dlerror());\n }\n\n create_ds* create_datasource = \n (create_ds*) lt_dlsym(itr->second->handle(), \"create\");\n\n if ( ! create_datasource)\n {\n throw std::runtime_error(string(\"Cannot load symbols: \") + \n lt_dlerror());\n }\n#ifdef MAPNIK_DEBUG\n std::clog << \"size = \" << params.size() << \"\\n\";\n parameters::const_iterator i = params.begin();\n for (;i!=params.end();++i)\n {\n std::clog << i->first << \"=\" << i->second << \"\\n\"; \n }\n#endif\n ds=datasource_ptr(create_datasource(params), datasource_deleter());\n\n#ifdef MAPNIK_DEBUG\n std::clog<<\"datasource=\"<\n (new PluginInfo(type,module)))).second; \n }\n\n void datasource_cache::register_datasources(const std::string& str)\n {\t\n mutex::scoped_lock lock(mapnik::singleton::mutex_);\n filesystem::path path(str);\n filesystem::directory_iterator end_itr;\n if (exists(path) && is_directory(path))\n {\n for (filesystem::directory_iterator itr(path);itr!=end_itr;++itr )\n {\n if (!is_directory( *itr ) && is_input_plugin(itr->leaf()))\n {\n try \n {\n lt_dlhandle module=lt_dlopen(itr->string().c_str());\n if (module)\n {\n datasource_name* ds_name = \n (datasource_name*) lt_dlsym(module, \"datasource_name\");\n if (ds_name && insert(ds_name(),module))\n { \n#ifdef MAPNIK_DEBUG\n std::clog<<\"registered datasource : \"<"} {"text":"Improve IAS Zone enrollment<|endoftext|>"} {"text":"\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n\nnamespace Tadpole::Compiler {\n\nint FunctionCompiler::resolve_local(const Lex::Token& name, const ErrorFn& errfn) {\n for (int i = locals_count() - 1; i >= 0; --i) {\n const LocalVar& local = locals_[i];\n if (local.name == name && local.depth == -1)\n errfn(Common::from_fmt(\"cannot load local variable `%s` in its own initializer\", name.as_cstring()));\n }\n return -1;\n}\n\nint FunctionCompiler::add_upvalue(u8_t index, bool is_local) {\n for (sz_t i = 0; i < fn_->upvalues_count(); ++i) {\n if (upvalues_[i].is_equal(index, is_local))\n return Common::as_type(i);\n }\n\n upvalues_.push_back({index, is_local});\n return Common::as_type(fn_->inc_upvalues_count());\n}\n\nint FunctionCompiler::resolve_upvalue(const Lex::Token& name, const ErrorFn& errfn) {\n if (enclosing_ == nullptr)\n return -1;\n\n if (int local = enclosing_->resolve_local(name, errfn); local != -1) {\n enclosing_->locals_[local].is_upvalue = true;\n return add_upvalue(Common::as_type(local), true);\n }\n if (int upvalue = enclosing_->resolve_upvalue(name, errfn); upvalue != -1)\n return add_upvalue(Common::as_type(upvalue), false);\n\n return -1;\n}\n\nvoid FunctionCompiler::declare_localvar(const Lex::Token& name, const ErrorFn& errfn) {\n \/\/ TODO:\n}\n\n}\n:construction: chore(function-compiler): finished the implementation of function compiler\/\/ Copyright (c) 2021 ASMlover. All rights reserved.\n\/\/\n\/\/ ______ __ ___\n\/\/ \/\\__ _\\ \/\\ \\ \/\\_ \\\n\/\/ \\\/_\/\\ \\\/ __ \\_\\ \\ _____ ___\\\/\/\\ \\ __\n\/\/ \\ \\ \\ \/'__`\\ \/'_` \\\/\\ '__`\\ \/ __`\\\\ \\ \\ \/'__`\\\n\/\/ \\ \\ \\\/\\ \\L\\.\\_\/\\ \\L\\ \\ \\ \\L\\ \\\/\\ \\L\\ \\\\_\\ \\_\/\\ __\/\n\/\/ \\ \\_\\ \\__\/.\\_\\ \\___,_\\ \\ ,__\/\\ \\____\/\/\\____\\ \\____\\\n\/\/ \\\/_\/\\\/__\/\\\/_\/\\\/__,_ \/\\ \\ \\\/ \\\/___\/ \\\/____\/\\\/____\/\n\/\/ \\ \\_\\\n\/\/ \\\/_\/\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright\n\/\/ notice, this list ofconditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in\n\/\/ the documentation and\/or other materialsprovided with the\n\/\/ distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\n\/\/ LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n\/\/ LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN\n\/\/ ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n#include \n#include \n\nnamespace Tadpole::Compiler {\n\nint FunctionCompiler::resolve_local(const Lex::Token& name, const ErrorFn& errfn) {\n for (int i = locals_count() - 1; i >= 0; --i) {\n const LocalVar& local = locals_[i];\n if (local.name == name && local.depth == -1)\n errfn(Common::from_fmt(\"cannot load local variable `%s` in its own initializer\", name.as_cstring()));\n }\n return -1;\n}\n\nint FunctionCompiler::add_upvalue(u8_t index, bool is_local) {\n for (sz_t i = 0; i < fn_->upvalues_count(); ++i) {\n if (upvalues_[i].is_equal(index, is_local))\n return Common::as_type(i);\n }\n\n upvalues_.push_back({index, is_local});\n return Common::as_type(fn_->inc_upvalues_count());\n}\n\nint FunctionCompiler::resolve_upvalue(const Lex::Token& name, const ErrorFn& errfn) {\n if (enclosing_ == nullptr)\n return -1;\n\n if (int local = enclosing_->resolve_local(name, errfn); local != -1) {\n enclosing_->locals_[local].is_upvalue = true;\n return add_upvalue(Common::as_type(local), true);\n }\n if (int upvalue = enclosing_->resolve_upvalue(name, errfn); upvalue != -1)\n return add_upvalue(Common::as_type(upvalue), false);\n\n return -1;\n}\n\nvoid FunctionCompiler::declare_localvar(const Lex::Token& name, const ErrorFn& errfn) {\n if (scope_depth_ == 0)\n return;\n\n for (auto it = locals_.rbegin(); it != locals_.rend(); ++it) {\n if (it->depth != -1 && it->depth < scope_depth_)\n break;\n\n if (it->name == name)\n errfn(Common::from_fmt(\"name `%s` is redefined\", name.as_cstring()));\n }\n locals_.push_back({name, -1, false});\n}\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/sqlite\/db_sqlite_table.h\"\n\n#include \"src\/trace_processor\/sqlite\/sqlite_utils.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nnamespace {\n\nFilterOp SqliteOpToFilterOp(int sqlite_op) {\n switch (sqlite_op) {\n case SQLITE_INDEX_CONSTRAINT_EQ:\n case SQLITE_INDEX_CONSTRAINT_IS:\n return FilterOp::kEq;\n case SQLITE_INDEX_CONSTRAINT_GT:\n return FilterOp::kGt;\n case SQLITE_INDEX_CONSTRAINT_LT:\n return FilterOp::kLt;\n case SQLITE_INDEX_CONSTRAINT_ISNOT:\n case SQLITE_INDEX_CONSTRAINT_NE:\n return FilterOp::kNe;\n case SQLITE_INDEX_CONSTRAINT_GE:\n return FilterOp::kGe;\n case SQLITE_INDEX_CONSTRAINT_LE:\n return FilterOp::kLe;\n case SQLITE_INDEX_CONSTRAINT_ISNULL:\n return FilterOp::kIsNull;\n case SQLITE_INDEX_CONSTRAINT_ISNOTNULL:\n return FilterOp::kIsNotNull;\n case SQLITE_INDEX_CONSTRAINT_LIKE:\n return FilterOp::kLike;\n default:\n PERFETTO_FATAL(\"Currently unsupported constraint\");\n }\n}\n\nSqlValue SqliteValueToSqlValue(sqlite3_value* sqlite_val) {\n auto col_type = sqlite3_value_type(sqlite_val);\n SqlValue value;\n switch (col_type) {\n case SQLITE_INTEGER:\n value.type = SqlValue::kLong;\n value.long_value = sqlite3_value_int64(sqlite_val);\n break;\n case SQLITE_TEXT:\n value.type = SqlValue::kString;\n value.string_value =\n reinterpret_cast(sqlite3_value_text(sqlite_val));\n break;\n case SQLITE_FLOAT:\n value.type = SqlValue::kDouble;\n value.double_value = sqlite3_value_double(sqlite_val);\n break;\n case SQLITE_BLOB:\n value.type = SqlValue::kBytes;\n value.bytes_value = sqlite3_value_blob(sqlite_val);\n value.bytes_count = static_cast(sqlite3_value_bytes(sqlite_val));\n break;\n case SQLITE_NULL:\n value.type = SqlValue::kNull;\n break;\n }\n return value;\n}\n\n} \/\/ namespace\n\nDbSqliteTable::DbSqliteTable(sqlite3*, const Table* table) : table_(table) {}\nDbSqliteTable::~DbSqliteTable() = default;\n\nvoid DbSqliteTable::RegisterTable(sqlite3* db,\n const Table* table,\n const std::string& name) {\n SqliteTable::Register(db, table, name);\n}\n\nutil::Status DbSqliteTable::Init(int, const char* const*, Schema* schema) {\n std::vector schema_cols;\n for (uint32_t i = 0; i < table_->GetColumnCount(); ++i) {\n const auto& col = table_->GetColumn(i);\n schema_cols.emplace_back(i, col.name(), col.type());\n }\n \/\/ TODO(lalitm): this is hardcoded to be the id column but change this to be\n \/\/ more generic in the future.\n auto opt_idx = table_->FindColumnIdxByName(\"id\");\n if (!opt_idx) {\n PERFETTO_FATAL(\n \"id column not found in %s. Currently all db Tables need to contain an \"\n \"id column; this constraint will be relaxed in the future.\",\n name().c_str());\n }\n\n std::vector primary_keys;\n primary_keys.emplace_back(*opt_idx);\n\n *schema = Schema(std::move(schema_cols), std::move(primary_keys));\n return util::OkStatus();\n}\n\nint DbSqliteTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {\n \/\/ TODO(lalitm): investigate SQLITE_INDEX_SCAN_UNIQUE for id columns.\n auto cost_and_rows = EstimateCost(*table_, qc);\n info->estimated_cost = cost_and_rows.cost;\n info->estimated_rows = cost_and_rows.rows;\n return SQLITE_OK;\n}\n\nint DbSqliteTable::ModifyConstraints(QueryConstraints* qc) {\n using C = QueryConstraints::Constraint;\n\n \/\/ Reorder constraints to consider the constraints on columns which are\n \/\/ cheaper to filter first.\n auto* cs = qc->mutable_constraints();\n std::sort(cs->begin(), cs->end(), [this](const C& a, const C& b) {\n uint32_t a_idx = static_cast(a.column);\n uint32_t b_idx = static_cast(b.column);\n const auto& a_col = table_->GetColumn(a_idx);\n const auto& b_col = table_->GetColumn(b_idx);\n\n \/\/ Id columns are always very cheap to filter on so try and get them\n \/\/ first.\n if (a_col.IsId() && !b_col.IsId())\n return true;\n\n \/\/ Sorted columns are also quite cheap to filter so order them after\n \/\/ any id columns.\n if (a_col.IsSorted() && !b_col.IsSorted())\n return true;\n\n \/\/ TODO(lalitm): introduce more orderings here based on empirical data.\n return false;\n });\n\n \/\/ Remove any order by constraints which also have an equality constraint.\n auto* ob = qc->mutable_order_by();\n {\n auto p = [&cs](const QueryConstraints::OrderBy& o) {\n auto inner_p = [&o](const QueryConstraints::Constraint& c) {\n return c.column == o.iColumn && sqlite_utils::IsOpEq(c.op);\n };\n return std::any_of(cs->begin(), cs->end(), inner_p);\n };\n auto remove_it = std::remove_if(ob->begin(), ob->end(), p);\n ob->erase(remove_it, ob->end());\n }\n\n \/\/ Go through the order by constraints in reverse order and eliminate\n \/\/ constraints until the first non-sorted column or the first order by in\n \/\/ descending order.\n {\n auto p = [this](const QueryConstraints::OrderBy& o) {\n const auto& col = table_->GetColumn(static_cast(o.iColumn));\n return o.desc || !col.IsSorted();\n };\n auto first_non_sorted_it = std::find_if(ob->rbegin(), ob->rend(), p);\n auto pop_count = std::distance(ob->rbegin(), first_non_sorted_it);\n ob->resize(ob->size() - static_cast(pop_count));\n }\n\n return SQLITE_OK;\n}\n\nDbSqliteTable::QueryCost DbSqliteTable::EstimateCost(\n const Table& table,\n const QueryConstraints& qc) {\n \/\/ Currently our cost estimation algorithm is quite simplistic but is good\n \/\/ enough for the simplest cases.\n \/\/ TODO(lalitm): replace hardcoded constants with either more heuristics\n \/\/ based on the exact type of constraint or profiling the queries themselves.\n\n \/\/ We estimate the fixed cost of set-up and tear-down of a query in terms of\n \/\/ the number of rows scanned.\n constexpr double kFixedQueryCost = 1000.0;\n\n \/\/ Setup the variables for estimating the number of rows we will have at the\n \/\/ end of filtering. Note that |current_row_count| should always be at least 1\n \/\/ unless we are absolutely certain that we will return no rows as otherwise\n \/\/ SQLite can make some bad choices.\n uint32_t current_row_count = table.size();\n\n \/\/ If the table is empty, any constraint set only pays the fixed cost. Also we\n \/\/ can return 0 as the row count as we are certain that we will return no\n \/\/ rows.\n if (current_row_count == 0)\n return QueryCost{kFixedQueryCost, 0};\n\n \/\/ Setup the variables for estimating the cost of filtering.\n double filter_cost = 0.0;\n const auto& cs = qc.constraints();\n for (const auto& c : cs) {\n const auto& col = table.GetColumn(static_cast(c.column));\n if (sqlite_utils::IsOpEq(c.op) && col.IsId()) {\n \/\/ If we have an id equality constraint, it's a bit expensive to find\n \/\/ the exact row but it filters down to a single row.\n filter_cost += 100;\n current_row_count = 1;\n } else if (sqlite_utils::IsOpEq(c.op)) {\n \/\/ If there is only a single equality constraint, we have special logic\n \/\/ to sort by that column and then binary search if we see the constraint\n \/\/ set often. Model this by dividing but the log of the number of rows as\n \/\/ a good approximation. Otherwise, we'll need to do a full table scan.\n filter_cost += cs.size() == 1\n ? (2 * current_row_count) \/ log2(current_row_count)\n : current_row_count;\n\n \/\/ We assume that an equalty constraint will cut down the number of rows\n \/\/ by approximate log of the number of rows.\n double estimated_rows = current_row_count \/ log2(current_row_count);\n current_row_count = std::max(static_cast(estimated_rows), 1u);\n } else {\n \/\/ Otherwise, we will need to do a full table scan and we estimate we will\n \/\/ maybe (at best) halve the number of rows.\n filter_cost += current_row_count;\n current_row_count = std::max(current_row_count \/ 2u, 1u);\n }\n }\n\n \/\/ Now, to figure out the cost of sorting, multiply the final row count\n \/\/ by |qc.order_by().size()| * log(row count). This should act as a crude\n \/\/ estimation of the cost.\n double sort_cost =\n qc.order_by().size() * current_row_count * log2(current_row_count);\n\n \/\/ The cost of iterating rows is more expensive than filtering the rows\n \/\/ so multiply by an appropriate factor.\n double iteration_cost = current_row_count * 2.0;\n\n \/\/ To get the final cost, add up all the individual components.\n double final_cost =\n kFixedQueryCost + filter_cost + sort_cost + iteration_cost;\n return QueryCost{final_cost, current_row_count};\n}\n\nstd::unique_ptr DbSqliteTable::CreateCursor() {\n return std::unique_ptr(new Cursor(this));\n}\n\nDbSqliteTable::Cursor::Cursor(DbSqliteTable* table)\n : SqliteTable::Cursor(table), initial_db_table_(table->table_) {}\n\nint DbSqliteTable::Cursor::Filter(const QueryConstraints& qc,\n sqlite3_value** argv,\n FilterHistory history) {\n \/\/ Clear out the iterator before filtering to ensure the destructor is run\n \/\/ before the table's destructor.\n iterator_ = base::nullopt;\n\n if (history == FilterHistory::kSame && qc.constraints().size() == 1 &&\n sqlite_utils::IsOpEq(qc.constraints().front().op)) {\n \/\/ If we've seen the same constraint set with a single equality constraint\n \/\/ more than |kRepeatedThreshold| times, we assume we will see it more\n \/\/ in the future and thus cache a table sorted on the column. That way,\n \/\/ future equality constraints can binary search for the value instead of\n \/\/ doing a full table scan.\n constexpr uint32_t kRepeatedThreshold = 3;\n if (!sorted_cache_table_ && repeated_cache_count_++ > kRepeatedThreshold) {\n const auto& c = qc.constraints().front();\n uint32_t col = static_cast(c.column);\n sorted_cache_table_ = initial_db_table_->Sort({Order{col, false}});\n }\n } else {\n sorted_cache_table_ = base::nullopt;\n repeated_cache_count_ = 0;\n }\n\n \/\/ We reuse this vector to reduce memory allocations on nested subqueries.\n constraints_.resize(qc.constraints().size());\n for (size_t i = 0; i < qc.constraints().size(); ++i) {\n const auto& cs = qc.constraints()[i];\n uint32_t col = static_cast(cs.column);\n\n FilterOp op = SqliteOpToFilterOp(cs.op);\n SqlValue value = SqliteValueToSqlValue(argv[i]);\n\n constraints_[i] = Constraint{col, op, value};\n }\n\n \/\/ We reuse this vector to reduce memory allocations on nested subqueries.\n orders_.resize(qc.order_by().size());\n for (size_t i = 0; i < qc.order_by().size(); ++i) {\n const auto& ob = qc.order_by()[i];\n uint32_t col = static_cast(ob.iColumn);\n orders_[i] = Order{col, static_cast(ob.desc)};\n }\n\n \/\/ Try and use the sorted cache table (if it exists) to speed up the sorting.\n \/\/ Otherwise, just use the original table.\n auto* source =\n sorted_cache_table_ ? &*sorted_cache_table_ : &*initial_db_table_;\n db_table_ = source->Filter(constraints_).Sort(orders_);\n iterator_ = db_table_->IterateRows();\n\n return SQLITE_OK;\n}\n\nint DbSqliteTable::Cursor::Next() {\n iterator_->Next();\n return SQLITE_OK;\n}\n\nint DbSqliteTable::Cursor::Eof() {\n return !*iterator_;\n}\n\nint DbSqliteTable::Cursor::Column(sqlite3_context* ctx, int raw_col) {\n uint32_t column = static_cast(raw_col);\n SqlValue value = iterator_->Get(column);\n switch (value.type) {\n case SqlValue::Type::kLong:\n sqlite3_result_int64(ctx, value.long_value);\n break;\n case SqlValue::Type::kDouble:\n sqlite3_result_double(ctx, value.double_value);\n break;\n case SqlValue::Type::kString: {\n \/\/ We can say kSqliteStatic here because all strings are expected to\n \/\/ come from the string pool and thus will be valid for the lifetime\n \/\/ of trace processor.\n sqlite3_result_text(ctx, value.string_value, -1,\n sqlite_utils::kSqliteStatic);\n break;\n }\n case SqlValue::Type::kBytes: {\n \/\/ We can say kSqliteStatic here because for our iterator will hold\n \/\/ onto the pointer as long as we don't call Next() but that only\n \/\/ happens with Next() is called on the Cursor itself at which point\n \/\/ SQLite no longer cares about the bytes pointer.\n sqlite3_result_blob(ctx, value.bytes_value,\n static_cast(value.bytes_count),\n sqlite_utils::kSqliteStatic);\n break;\n }\n case SqlValue::Type::kNull:\n sqlite3_result_null(ctx);\n break;\n }\n return SQLITE_OK;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\nFix cost estimation for single row am: 9faab56544\/*\n * Copyright (C) 2019 The Android Open Source Project\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"src\/trace_processor\/sqlite\/db_sqlite_table.h\"\n\n#include \"src\/trace_processor\/sqlite\/sqlite_utils.h\"\n\nnamespace perfetto {\nnamespace trace_processor {\n\nnamespace {\n\nFilterOp SqliteOpToFilterOp(int sqlite_op) {\n switch (sqlite_op) {\n case SQLITE_INDEX_CONSTRAINT_EQ:\n case SQLITE_INDEX_CONSTRAINT_IS:\n return FilterOp::kEq;\n case SQLITE_INDEX_CONSTRAINT_GT:\n return FilterOp::kGt;\n case SQLITE_INDEX_CONSTRAINT_LT:\n return FilterOp::kLt;\n case SQLITE_INDEX_CONSTRAINT_ISNOT:\n case SQLITE_INDEX_CONSTRAINT_NE:\n return FilterOp::kNe;\n case SQLITE_INDEX_CONSTRAINT_GE:\n return FilterOp::kGe;\n case SQLITE_INDEX_CONSTRAINT_LE:\n return FilterOp::kLe;\n case SQLITE_INDEX_CONSTRAINT_ISNULL:\n return FilterOp::kIsNull;\n case SQLITE_INDEX_CONSTRAINT_ISNOTNULL:\n return FilterOp::kIsNotNull;\n case SQLITE_INDEX_CONSTRAINT_LIKE:\n return FilterOp::kLike;\n default:\n PERFETTO_FATAL(\"Currently unsupported constraint\");\n }\n}\n\nSqlValue SqliteValueToSqlValue(sqlite3_value* sqlite_val) {\n auto col_type = sqlite3_value_type(sqlite_val);\n SqlValue value;\n switch (col_type) {\n case SQLITE_INTEGER:\n value.type = SqlValue::kLong;\n value.long_value = sqlite3_value_int64(sqlite_val);\n break;\n case SQLITE_TEXT:\n value.type = SqlValue::kString;\n value.string_value =\n reinterpret_cast(sqlite3_value_text(sqlite_val));\n break;\n case SQLITE_FLOAT:\n value.type = SqlValue::kDouble;\n value.double_value = sqlite3_value_double(sqlite_val);\n break;\n case SQLITE_BLOB:\n value.type = SqlValue::kBytes;\n value.bytes_value = sqlite3_value_blob(sqlite_val);\n value.bytes_count = static_cast(sqlite3_value_bytes(sqlite_val));\n break;\n case SQLITE_NULL:\n value.type = SqlValue::kNull;\n break;\n }\n return value;\n}\n\n} \/\/ namespace\n\nDbSqliteTable::DbSqliteTable(sqlite3*, const Table* table) : table_(table) {}\nDbSqliteTable::~DbSqliteTable() = default;\n\nvoid DbSqliteTable::RegisterTable(sqlite3* db,\n const Table* table,\n const std::string& name) {\n SqliteTable::Register(db, table, name);\n}\n\nutil::Status DbSqliteTable::Init(int, const char* const*, Schema* schema) {\n std::vector schema_cols;\n for (uint32_t i = 0; i < table_->GetColumnCount(); ++i) {\n const auto& col = table_->GetColumn(i);\n schema_cols.emplace_back(i, col.name(), col.type());\n }\n \/\/ TODO(lalitm): this is hardcoded to be the id column but change this to be\n \/\/ more generic in the future.\n auto opt_idx = table_->FindColumnIdxByName(\"id\");\n if (!opt_idx) {\n PERFETTO_FATAL(\n \"id column not found in %s. Currently all db Tables need to contain an \"\n \"id column; this constraint will be relaxed in the future.\",\n name().c_str());\n }\n\n std::vector primary_keys;\n primary_keys.emplace_back(*opt_idx);\n\n *schema = Schema(std::move(schema_cols), std::move(primary_keys));\n return util::OkStatus();\n}\n\nint DbSqliteTable::BestIndex(const QueryConstraints& qc, BestIndexInfo* info) {\n \/\/ TODO(lalitm): investigate SQLITE_INDEX_SCAN_UNIQUE for id columns.\n auto cost_and_rows = EstimateCost(*table_, qc);\n info->estimated_cost = cost_and_rows.cost;\n info->estimated_rows = cost_and_rows.rows;\n return SQLITE_OK;\n}\n\nint DbSqliteTable::ModifyConstraints(QueryConstraints* qc) {\n using C = QueryConstraints::Constraint;\n\n \/\/ Reorder constraints to consider the constraints on columns which are\n \/\/ cheaper to filter first.\n auto* cs = qc->mutable_constraints();\n std::sort(cs->begin(), cs->end(), [this](const C& a, const C& b) {\n uint32_t a_idx = static_cast(a.column);\n uint32_t b_idx = static_cast(b.column);\n const auto& a_col = table_->GetColumn(a_idx);\n const auto& b_col = table_->GetColumn(b_idx);\n\n \/\/ Id columns are always very cheap to filter on so try and get them\n \/\/ first.\n if (a_col.IsId() && !b_col.IsId())\n return true;\n\n \/\/ Sorted columns are also quite cheap to filter so order them after\n \/\/ any id columns.\n if (a_col.IsSorted() && !b_col.IsSorted())\n return true;\n\n \/\/ TODO(lalitm): introduce more orderings here based on empirical data.\n return false;\n });\n\n \/\/ Remove any order by constraints which also have an equality constraint.\n auto* ob = qc->mutable_order_by();\n {\n auto p = [&cs](const QueryConstraints::OrderBy& o) {\n auto inner_p = [&o](const QueryConstraints::Constraint& c) {\n return c.column == o.iColumn && sqlite_utils::IsOpEq(c.op);\n };\n return std::any_of(cs->begin(), cs->end(), inner_p);\n };\n auto remove_it = std::remove_if(ob->begin(), ob->end(), p);\n ob->erase(remove_it, ob->end());\n }\n\n \/\/ Go through the order by constraints in reverse order and eliminate\n \/\/ constraints until the first non-sorted column or the first order by in\n \/\/ descending order.\n {\n auto p = [this](const QueryConstraints::OrderBy& o) {\n const auto& col = table_->GetColumn(static_cast(o.iColumn));\n return o.desc || !col.IsSorted();\n };\n auto first_non_sorted_it = std::find_if(ob->rbegin(), ob->rend(), p);\n auto pop_count = std::distance(ob->rbegin(), first_non_sorted_it);\n ob->resize(ob->size() - static_cast(pop_count));\n }\n\n return SQLITE_OK;\n}\n\nDbSqliteTable::QueryCost DbSqliteTable::EstimateCost(\n const Table& table,\n const QueryConstraints& qc) {\n \/\/ Currently our cost estimation algorithm is quite simplistic but is good\n \/\/ enough for the simplest cases.\n \/\/ TODO(lalitm): replace hardcoded constants with either more heuristics\n \/\/ based on the exact type of constraint or profiling the queries themselves.\n\n \/\/ We estimate the fixed cost of set-up and tear-down of a query in terms of\n \/\/ the number of rows scanned.\n constexpr double kFixedQueryCost = 1000.0;\n\n \/\/ Setup the variables for estimating the number of rows we will have at the\n \/\/ end of filtering. Note that |current_row_count| should always be at least 1\n \/\/ unless we are absolutely certain that we will return no rows as otherwise\n \/\/ SQLite can make some bad choices.\n uint32_t current_row_count = table.size();\n\n \/\/ If the table is empty, any constraint set only pays the fixed cost. Also we\n \/\/ can return 0 as the row count as we are certain that we will return no\n \/\/ rows.\n if (current_row_count == 0)\n return QueryCost{kFixedQueryCost, 0};\n\n \/\/ Setup the variables for estimating the cost of filtering.\n double filter_cost = 0.0;\n const auto& cs = qc.constraints();\n for (const auto& c : cs) {\n if (current_row_count < 2)\n break;\n const auto& col = table.GetColumn(static_cast(c.column));\n if (sqlite_utils::IsOpEq(c.op) && col.IsId()) {\n \/\/ If we have an id equality constraint, it's a bit expensive to find\n \/\/ the exact row but it filters down to a single row.\n filter_cost += 100;\n current_row_count = 1;\n } else if (sqlite_utils::IsOpEq(c.op)) {\n \/\/ If there is only a single equality constraint, we have special logic\n \/\/ to sort by that column and then binary search if we see the constraint\n \/\/ set often. Model this by dividing but the log of the number of rows as\n \/\/ a good approximation. Otherwise, we'll need to do a full table scan.\n filter_cost += cs.size() == 1\n ? (2 * current_row_count) \/ log2(current_row_count)\n : current_row_count;\n\n \/\/ We assume that an equalty constraint will cut down the number of rows\n \/\/ by approximate log of the number of rows.\n double estimated_rows = current_row_count \/ log2(current_row_count);\n current_row_count = std::max(static_cast(estimated_rows), 1u);\n } else {\n \/\/ Otherwise, we will need to do a full table scan and we estimate we will\n \/\/ maybe (at best) halve the number of rows.\n filter_cost += current_row_count;\n current_row_count = std::max(current_row_count \/ 2u, 1u);\n }\n }\n\n \/\/ Now, to figure out the cost of sorting, multiply the final row count\n \/\/ by |qc.order_by().size()| * log(row count). This should act as a crude\n \/\/ estimation of the cost.\n double sort_cost =\n qc.order_by().size() * current_row_count * log2(current_row_count);\n\n \/\/ The cost of iterating rows is more expensive than filtering the rows\n \/\/ so multiply by an appropriate factor.\n double iteration_cost = current_row_count * 2.0;\n\n \/\/ To get the final cost, add up all the individual components.\n double final_cost =\n kFixedQueryCost + filter_cost + sort_cost + iteration_cost;\n return QueryCost{final_cost, current_row_count};\n}\n\nstd::unique_ptr DbSqliteTable::CreateCursor() {\n return std::unique_ptr(new Cursor(this));\n}\n\nDbSqliteTable::Cursor::Cursor(DbSqliteTable* table)\n : SqliteTable::Cursor(table), initial_db_table_(table->table_) {}\n\nint DbSqliteTable::Cursor::Filter(const QueryConstraints& qc,\n sqlite3_value** argv,\n FilterHistory history) {\n \/\/ Clear out the iterator before filtering to ensure the destructor is run\n \/\/ before the table's destructor.\n iterator_ = base::nullopt;\n\n if (history == FilterHistory::kSame && qc.constraints().size() == 1 &&\n sqlite_utils::IsOpEq(qc.constraints().front().op)) {\n \/\/ If we've seen the same constraint set with a single equality constraint\n \/\/ more than |kRepeatedThreshold| times, we assume we will see it more\n \/\/ in the future and thus cache a table sorted on the column. That way,\n \/\/ future equality constraints can binary search for the value instead of\n \/\/ doing a full table scan.\n constexpr uint32_t kRepeatedThreshold = 3;\n if (!sorted_cache_table_ && repeated_cache_count_++ > kRepeatedThreshold) {\n const auto& c = qc.constraints().front();\n uint32_t col = static_cast(c.column);\n sorted_cache_table_ = initial_db_table_->Sort({Order{col, false}});\n }\n } else {\n sorted_cache_table_ = base::nullopt;\n repeated_cache_count_ = 0;\n }\n\n \/\/ We reuse this vector to reduce memory allocations on nested subqueries.\n constraints_.resize(qc.constraints().size());\n for (size_t i = 0; i < qc.constraints().size(); ++i) {\n const auto& cs = qc.constraints()[i];\n uint32_t col = static_cast(cs.column);\n\n FilterOp op = SqliteOpToFilterOp(cs.op);\n SqlValue value = SqliteValueToSqlValue(argv[i]);\n\n constraints_[i] = Constraint{col, op, value};\n }\n\n \/\/ We reuse this vector to reduce memory allocations on nested subqueries.\n orders_.resize(qc.order_by().size());\n for (size_t i = 0; i < qc.order_by().size(); ++i) {\n const auto& ob = qc.order_by()[i];\n uint32_t col = static_cast(ob.iColumn);\n orders_[i] = Order{col, static_cast(ob.desc)};\n }\n\n \/\/ Try and use the sorted cache table (if it exists) to speed up the sorting.\n \/\/ Otherwise, just use the original table.\n auto* source =\n sorted_cache_table_ ? &*sorted_cache_table_ : &*initial_db_table_;\n db_table_ = source->Filter(constraints_).Sort(orders_);\n iterator_ = db_table_->IterateRows();\n\n return SQLITE_OK;\n}\n\nint DbSqliteTable::Cursor::Next() {\n iterator_->Next();\n return SQLITE_OK;\n}\n\nint DbSqliteTable::Cursor::Eof() {\n return !*iterator_;\n}\n\nint DbSqliteTable::Cursor::Column(sqlite3_context* ctx, int raw_col) {\n uint32_t column = static_cast(raw_col);\n SqlValue value = iterator_->Get(column);\n switch (value.type) {\n case SqlValue::Type::kLong:\n sqlite3_result_int64(ctx, value.long_value);\n break;\n case SqlValue::Type::kDouble:\n sqlite3_result_double(ctx, value.double_value);\n break;\n case SqlValue::Type::kString: {\n \/\/ We can say kSqliteStatic here because all strings are expected to\n \/\/ come from the string pool and thus will be valid for the lifetime\n \/\/ of trace processor.\n sqlite3_result_text(ctx, value.string_value, -1,\n sqlite_utils::kSqliteStatic);\n break;\n }\n case SqlValue::Type::kBytes: {\n \/\/ We can say kSqliteStatic here because for our iterator will hold\n \/\/ onto the pointer as long as we don't call Next() but that only\n \/\/ happens with Next() is called on the Cursor itself at which point\n \/\/ SQLite no longer cares about the bytes pointer.\n sqlite3_result_blob(ctx, value.bytes_value,\n static_cast(value.bytes_count),\n sqlite_utils::kSqliteStatic);\n break;\n }\n case SqlValue::Type::kNull:\n sqlite3_result_null(ctx);\n break;\n }\n return SQLITE_OK;\n}\n\n} \/\/ namespace trace_processor\n} \/\/ namespace perfetto\n<|endoftext|>"} {"text":"\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2016. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"HAL\/AnalogGyro.h\"\n\n#include \n#include \n\n#include \"AnalogInternal.h\"\n#include \"HAL\/AnalogAccumulator.h\"\n#include \"HAL\/AnalogInput.h\"\n#include \"HAL\/handles\/IndexedHandleResource.h\"\n\nnamespace {\nstruct AnalogGyro {\n HAL_AnalogInputHandle handle;\n double voltsPerDegreePerSecond;\n double offset;\n int32_t center;\n};\n}\n\nstatic constexpr uint32_t kOversampleBits = 10;\nstatic constexpr uint32_t kAverageBits = 0;\nstatic constexpr double kSamplesPerSecond = 50.0;\nstatic constexpr double kCalibrationSampleTime = 5.0;\nstatic constexpr double kDefaultVoltsPerDegreePerSecond = 0.007;\n\nusing namespace hal;\n\nstatic IndexedHandleResource\n analogGyroHandles;\n\nstatic void Wait(double seconds) {\n if (seconds < 0.0) return;\n std::this_thread::sleep_for(std::chrono::duration(seconds));\n}\n\nextern \"C\" {\nHAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analog_handle,\n int32_t* status) {\n if (!HAL_IsAccumulatorChannel(analog_handle, status)) {\n if (*status == 0) {\n *status = HAL_INVALID_ACCUMULATOR_CHANNEL;\n }\n return HAL_kInvalidHandle;\n }\n\n \/\/ handle known to be correct, so no need to type check\n int16_t channel = getHandleIndex(analog_handle);\n\n auto handle = analogGyroHandles.Allocate(channel, status);\n\n if (*status != 0)\n return HAL_kInvalidHandle; \/\/ failed to allocate. Pass error back.\n\n \/\/ Initialize port structure\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) { \/\/ would only error on thread issue\n *status = HAL_HANDLE_ERROR;\n return HAL_kInvalidHandle;\n }\n\n gyro->handle = analog_handle;\n gyro->voltsPerDegreePerSecond = 0;\n gyro->offset = 0;\n gyro->center = 0;\n\n return handle;\n}\n\nvoid HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n gyro->voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond;\n\n HAL_SetAnalogAverageBits(gyro->handle, kAverageBits, status);\n if (*status != 0) return;\n HAL_SetAnalogOversampleBits(gyro->handle, kOversampleBits, status);\n if (*status != 0) return;\n float sampleRate =\n kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits));\n HAL_SetAnalogSampleRate(sampleRate, status);\n if (*status != 0) return;\n Wait(0.1);\n\n HAL_SetAnalogGyroDeadband(handle, 0.0f, status);\n if (*status != 0) return;\n}\n\nvoid HAL_FreeAnalogGyro(HAL_GyroHandle handle) {\n analogGyroHandles.Free(handle);\n}\n\nvoid HAL_SetAnalogGyroParameters(HAL_GyroHandle handle,\n double voltsPerDegreePerSecond, double offset,\n int32_t center, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond;\n gyro->offset = offset;\n gyro->center = center;\n HAL_SetAccumulatorCenter(gyro->handle, center, status);\n}\n\nvoid HAL_SetAnalogGyroVoltsPerDegreePerSecond(HAL_GyroHandle handle,\n double voltsPerDegreePerSecond,\n int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond;\n}\n\nvoid HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n HAL_ResetAccumulator(gyro->handle, status);\n if (*status != 0) return;\n\n const double sampleTime = 1.0 \/ HAL_GetAnalogSampleRate(status);\n const double overSamples =\n 1 << HAL_GetAnalogOversampleBits(gyro->handle, status);\n const double averageSamples =\n 1 << HAL_GetAnalogAverageBits(gyro->handle, status);\n if (*status != 0) return;\n Wait(sampleTime * overSamples * averageSamples);\n}\n\nvoid HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n HAL_InitAccumulator(gyro->handle, status);\n if (*status != 0) return;\n Wait(kCalibrationSampleTime);\n\n int64_t value;\n int64_t count;\n HAL_GetAccumulatorOutput(gyro->handle, &value, &count, status);\n if (*status != 0) return;\n\n gyro->center = static_cast(\n static_cast(value) \/ static_cast(count) + .5);\n\n gyro->offset = static_cast(value) \/ static_cast(count) -\n static_cast(gyro->center);\n HAL_SetAccumulatorCenter(gyro->handle, gyro->center, status);\n if (*status != 0) return;\n HAL_ResetAnalogGyro(handle, status);\n}\n\nvoid HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts,\n int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n int32_t deadband = static_cast(\n volts * 1e9 \/ HAL_GetAnalogLSBWeight(gyro->handle, status) *\n (1 << HAL_GetAnalogOversampleBits(gyro->handle, status)));\n if (*status != 0) return;\n HAL_SetAccumulatorDeadband(gyro->handle, deadband, status);\n}\n\ndouble HAL_GetAnalogGyroAngle(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n int64_t rawValue = 0;\n int64_t count = 0;\n HAL_GetAccumulatorOutput(gyro->handle, &rawValue, &count, status);\n\n int64_t value = rawValue - static_cast(static_cast(count) *\n gyro->offset);\n\n double scaledValue =\n value * 1e-9 *\n static_cast(HAL_GetAnalogLSBWeight(gyro->handle, status)) *\n static_cast(1 << HAL_GetAnalogAverageBits(gyro->handle, status)) \/\n (HAL_GetAnalogSampleRate(status) * gyro->voltsPerDegreePerSecond);\n\n return static_cast(scaledValue);\n}\n\ndouble HAL_GetAnalogGyroRate(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n\n return (HAL_GetAnalogAverageValue(gyro->handle, status) -\n (static_cast(gyro->center) + gyro->offset)) *\n 1e-9 * HAL_GetAnalogLSBWeight(gyro->handle, status) \/\n ((1 << HAL_GetAnalogOversampleBits(gyro->handle, status)) *\n gyro->voltsPerDegreePerSecond);\n}\n\ndouble HAL_GetAnalogGyroOffset(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n return gyro->offset;\n}\n\nint32_t HAL_GetAnalogGyroCenter(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n return gyro->center;\n}\n}\nFixes analog gyro casting to float then returning double (#177)\/*----------------------------------------------------------------------------*\/\n\/* Copyright (c) FIRST 2016. All Rights Reserved. *\/\n\/* Open Source Software - may be modified and shared by FRC teams. The code *\/\n\/* must be accompanied by the FIRST BSD license file in the root directory of *\/\n\/* the project. *\/\n\/*----------------------------------------------------------------------------*\/\n\n#include \"HAL\/AnalogGyro.h\"\n\n#include \n#include \n\n#include \"AnalogInternal.h\"\n#include \"HAL\/AnalogAccumulator.h\"\n#include \"HAL\/AnalogInput.h\"\n#include \"HAL\/handles\/IndexedHandleResource.h\"\n\nnamespace {\nstruct AnalogGyro {\n HAL_AnalogInputHandle handle;\n double voltsPerDegreePerSecond;\n double offset;\n int32_t center;\n};\n}\n\nstatic constexpr uint32_t kOversampleBits = 10;\nstatic constexpr uint32_t kAverageBits = 0;\nstatic constexpr double kSamplesPerSecond = 50.0;\nstatic constexpr double kCalibrationSampleTime = 5.0;\nstatic constexpr double kDefaultVoltsPerDegreePerSecond = 0.007;\n\nusing namespace hal;\n\nstatic IndexedHandleResource\n analogGyroHandles;\n\nstatic void Wait(double seconds) {\n if (seconds < 0.0) return;\n std::this_thread::sleep_for(std::chrono::duration(seconds));\n}\n\nextern \"C\" {\nHAL_GyroHandle HAL_InitializeAnalogGyro(HAL_AnalogInputHandle analog_handle,\n int32_t* status) {\n if (!HAL_IsAccumulatorChannel(analog_handle, status)) {\n if (*status == 0) {\n *status = HAL_INVALID_ACCUMULATOR_CHANNEL;\n }\n return HAL_kInvalidHandle;\n }\n\n \/\/ handle known to be correct, so no need to type check\n int16_t channel = getHandleIndex(analog_handle);\n\n auto handle = analogGyroHandles.Allocate(channel, status);\n\n if (*status != 0)\n return HAL_kInvalidHandle; \/\/ failed to allocate. Pass error back.\n\n \/\/ Initialize port structure\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) { \/\/ would only error on thread issue\n *status = HAL_HANDLE_ERROR;\n return HAL_kInvalidHandle;\n }\n\n gyro->handle = analog_handle;\n gyro->voltsPerDegreePerSecond = 0;\n gyro->offset = 0;\n gyro->center = 0;\n\n return handle;\n}\n\nvoid HAL_SetupAnalogGyro(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n gyro->voltsPerDegreePerSecond = kDefaultVoltsPerDegreePerSecond;\n\n HAL_SetAnalogAverageBits(gyro->handle, kAverageBits, status);\n if (*status != 0) return;\n HAL_SetAnalogOversampleBits(gyro->handle, kOversampleBits, status);\n if (*status != 0) return;\n float sampleRate =\n kSamplesPerSecond * (1 << (kAverageBits + kOversampleBits));\n HAL_SetAnalogSampleRate(sampleRate, status);\n if (*status != 0) return;\n Wait(0.1);\n\n HAL_SetAnalogGyroDeadband(handle, 0.0f, status);\n if (*status != 0) return;\n}\n\nvoid HAL_FreeAnalogGyro(HAL_GyroHandle handle) {\n analogGyroHandles.Free(handle);\n}\n\nvoid HAL_SetAnalogGyroParameters(HAL_GyroHandle handle,\n double voltsPerDegreePerSecond, double offset,\n int32_t center, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond;\n gyro->offset = offset;\n gyro->center = center;\n HAL_SetAccumulatorCenter(gyro->handle, center, status);\n}\n\nvoid HAL_SetAnalogGyroVoltsPerDegreePerSecond(HAL_GyroHandle handle,\n double voltsPerDegreePerSecond,\n int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n gyro->voltsPerDegreePerSecond = voltsPerDegreePerSecond;\n}\n\nvoid HAL_ResetAnalogGyro(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n HAL_ResetAccumulator(gyro->handle, status);\n if (*status != 0) return;\n\n const double sampleTime = 1.0 \/ HAL_GetAnalogSampleRate(status);\n const double overSamples =\n 1 << HAL_GetAnalogOversampleBits(gyro->handle, status);\n const double averageSamples =\n 1 << HAL_GetAnalogAverageBits(gyro->handle, status);\n if (*status != 0) return;\n Wait(sampleTime * overSamples * averageSamples);\n}\n\nvoid HAL_CalibrateAnalogGyro(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n\n HAL_InitAccumulator(gyro->handle, status);\n if (*status != 0) return;\n Wait(kCalibrationSampleTime);\n\n int64_t value;\n int64_t count;\n HAL_GetAccumulatorOutput(gyro->handle, &value, &count, status);\n if (*status != 0) return;\n\n gyro->center = static_cast(\n static_cast(value) \/ static_cast(count) + .5);\n\n gyro->offset = static_cast(value) \/ static_cast(count) -\n static_cast(gyro->center);\n HAL_SetAccumulatorCenter(gyro->handle, gyro->center, status);\n if (*status != 0) return;\n HAL_ResetAnalogGyro(handle, status);\n}\n\nvoid HAL_SetAnalogGyroDeadband(HAL_GyroHandle handle, double volts,\n int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return;\n }\n int32_t deadband = static_cast(\n volts * 1e9 \/ HAL_GetAnalogLSBWeight(gyro->handle, status) *\n (1 << HAL_GetAnalogOversampleBits(gyro->handle, status)));\n if (*status != 0) return;\n HAL_SetAccumulatorDeadband(gyro->handle, deadband, status);\n}\n\ndouble HAL_GetAnalogGyroAngle(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n int64_t rawValue = 0;\n int64_t count = 0;\n HAL_GetAccumulatorOutput(gyro->handle, &rawValue, &count, status);\n\n int64_t value = rawValue - static_cast(static_cast(count) *\n gyro->offset);\n\n double scaledValue =\n value * 1e-9 *\n static_cast(HAL_GetAnalogLSBWeight(gyro->handle, status)) *\n static_cast(1 << HAL_GetAnalogAverageBits(gyro->handle, status)) \/\n (HAL_GetAnalogSampleRate(status) * gyro->voltsPerDegreePerSecond);\n\n return scaledValue;\n}\n\ndouble HAL_GetAnalogGyroRate(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n\n return (HAL_GetAnalogAverageValue(gyro->handle, status) -\n (static_cast(gyro->center) + gyro->offset)) *\n 1e-9 * HAL_GetAnalogLSBWeight(gyro->handle, status) \/\n ((1 << HAL_GetAnalogOversampleBits(gyro->handle, status)) *\n gyro->voltsPerDegreePerSecond);\n}\n\ndouble HAL_GetAnalogGyroOffset(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n return gyro->offset;\n}\n\nint32_t HAL_GetAnalogGyroCenter(HAL_GyroHandle handle, int32_t* status) {\n auto gyro = analogGyroHandles.Get(handle);\n if (gyro == nullptr) {\n *status = HAL_HANDLE_ERROR;\n return 0;\n }\n return gyro->center;\n}\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \"rapidjson\/writer.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"rapidjson\/error\/en.h\"\n#include \"rapidjson\/stringbuffer.h\"\n\n#include \"acmacs-base\/read-file.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate class JsonWriterT : public RW\n{\n public:\n inline JsonWriterT(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {}\n inline operator std::string() const { return mBuffer.GetString(); }\n inline std::string keyword() const { return mKeyword; }\n\n private:\n rapidjson::StringBuffer mBuffer;\n std::string mKeyword;\n};\n\n\/\/ template <> inline JsonWriterT>::JsonWriterT(std::string aKeyword)\n\/\/ : rapidjson::PrettyWriter(mBuffer), mKeyword(aKeyword)\n\/\/ {\n\/\/ SetIndent(' ', 1);\n\/\/ }\n\ntypedef JsonWriterT> JsonWriter;\ntypedef JsonWriterT> JsonPrettyWriter;\n\n\/\/ ----------------------------------------------------------------------\n\nenum _StartArray { StartArray };\nenum _EndArray { EndArray };\nenum _StartObject { StartObject };\nenum _EndObject { EndObject };\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _StartArray) { writer.StartArray(); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _EndArray) { writer.EndArray(); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _StartObject) { writer.StartObject(); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _EndObject) { writer.EndObject(); return writer; }\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, std::string s) { writer.String(s.c_str(), static_cast(s.size())); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, int value) { writer.Int(value); return writer; }\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, const std::vector& list)\n{\n writer << StartArray;\n for (const auto& e: list)\n writer << e;\n return writer << EndArray;\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, const std::vector>& list_list_strings)\n{\n writer << StartArray;\n for (const auto& e: list_list_strings)\n writer << e;\n return writer << EndArray;\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint)\n{\n JsonPrettyWriter writer(keyword);\n writer.SetIndent(' ', static_cast(indent));\n writer << value;\n std::string result = writer;\n if (insert_emacs_indent_hint && result[0] == '{') {\n const std::string ind(indent - 1, ' ');\n result.insert(1, ind + \"\\\"_\\\": \\\"-*- js-indent-level: \" + std::to_string(indent) + \" -*-\\\",\");\n }\n return result;\n}\n\ntemplate inline std::string compact_json(const V& value, std::string keyword)\n{\n JsonWriter writer(keyword);\n return writer << value;\n}\n\ntemplate inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true)\n{\n if (indent)\n return pretty_json(value, keyword, indent, insert_emacs_indent_hint);\n else\n return compact_json(value, keyword);\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true)\n{\n acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint));\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\nsupport for JsonObjectKey#pragma once\n\n#include \n#include \n\n#include \"rapidjson\/writer.h\"\n#include \"rapidjson\/prettywriter.h\"\n#include \"rapidjson\/error\/en.h\"\n#include \"rapidjson\/stringbuffer.h\"\n\n#include \"acmacs-base\/read-file.hh\"\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate class JsonWriterT : public RW\n{\n public:\n inline JsonWriterT(std::string aKeyword) : RW(mBuffer), mKeyword(aKeyword) {}\n inline operator std::string() const { return mBuffer.GetString(); }\n inline std::string keyword() const { return mKeyword; }\n\n private:\n rapidjson::StringBuffer mBuffer;\n std::string mKeyword;\n};\n\n\/\/ template <> inline JsonWriterT>::JsonWriterT(std::string aKeyword)\n\/\/ : rapidjson::PrettyWriter(mBuffer), mKeyword(aKeyword)\n\/\/ {\n\/\/ SetIndent(' ', 1);\n\/\/ }\n\ntypedef JsonWriterT> JsonWriter;\ntypedef JsonWriterT> JsonPrettyWriter;\n\n\/\/ ----------------------------------------------------------------------\n\nenum _StartArray { StartArray };\nenum _EndArray { EndArray };\nenum _StartObject { StartObject };\nenum _EndObject { EndObject };\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _StartArray) { writer.StartArray(); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _EndArray) { writer.EndArray(); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _StartObject) { writer.StartObject(); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, _EndObject) { writer.EndObject(); return writer; }\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, const char* s) { writer.String(s, static_cast(strlen(s))); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, std::string s) { writer.String(s.c_str(), static_cast(s.size())); return writer; }\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, int value) { writer.Int(value); return writer; }\n\nclass JsonObjectKey\n{\n public:\n inline JsonObjectKey(const char* v) : value(v) {}\n inline JsonObjectKey(std::string v) : value(v.c_str()) {}\n inline operator const char*() const { return value; }\n\n private:\n const char* value;\n};\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, JsonObjectKey value) { writer.Key(value); return writer; }\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, const std::vector& list)\n{\n writer << StartArray;\n for (const auto& e: list)\n writer << e;\n return writer << EndArray;\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline JsonWriterT& operator <<(JsonWriterT& writer, const std::vector>& list_list_strings)\n{\n writer << StartArray;\n for (const auto& e: list_list_strings)\n writer << e;\n return writer << EndArray;\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline std::string pretty_json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint)\n{\n JsonPrettyWriter writer(keyword);\n writer.SetIndent(' ', static_cast(indent));\n writer << value;\n std::string result = writer;\n if (insert_emacs_indent_hint && result[0] == '{') {\n const std::string ind(indent - 1, ' ');\n result.insert(1, ind + \"\\\"_\\\": \\\"-*- js-indent-level: \" + std::to_string(indent) + \" -*-\\\",\");\n }\n return result;\n}\n\ntemplate inline std::string compact_json(const V& value, std::string keyword)\n{\n JsonWriter writer(keyword);\n return writer << value;\n}\n\ntemplate inline std::string json(const V& value, std::string keyword, size_t indent, bool insert_emacs_indent_hint = true)\n{\n if (indent)\n return pretty_json(value, keyword, indent, insert_emacs_indent_hint);\n else\n return compact_json(value, keyword);\n}\n\n\/\/ ----------------------------------------------------------------------\n\ntemplate inline void export_to_json(const V& value, std::string keyword, std::string filename, size_t indent, bool insert_emacs_indent_hint = true)\n{\n acmacs_base::write_file(filename, json(value, keyword, indent, insert_emacs_indent_hint));\n}\n\n\/\/ ----------------------------------------------------------------------\n\/\/\/ Local Variables:\n\/\/\/ eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))\n\/\/\/ End:\n<|endoftext|>"} {"text":"\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2020 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/apu\/xaudio2\/xaudio2_audio_driver.h\"\n\n\/\/ Must be included before xaudio2.h so we get the right windows.h include.\n#include \"xenia\/base\/platform_win.h\"\n\n#include \"xenia\/apu\/apu_flags.h\"\n#include \"xenia\/base\/clock.h\"\n#include \"xenia\/base\/logging.h\"\n\nnamespace xe {\nnamespace apu {\nnamespace xaudio2 {\n\nclass XAudio2AudioDriver::VoiceCallback : public api::IXAudio2VoiceCallback {\n public:\n explicit VoiceCallback(xe::threading::Semaphore* semaphore)\n : semaphore_(semaphore) {}\n ~VoiceCallback() {}\n\n void OnStreamEnd() {}\n void OnVoiceProcessingPassEnd() {}\n void OnVoiceProcessingPassStart(uint32_t samples_required) {}\n void OnBufferEnd(void* context) {\n auto ret = semaphore_->Release(1, nullptr);\n assert_true(ret);\n }\n void OnBufferStart(void* context) {}\n void OnLoopEnd(void* context) {}\n void OnVoiceError(void* context, HRESULT result) {}\n\n private:\n xe::threading::Semaphore* semaphore_ = nullptr;\n};\n\nXAudio2AudioDriver::XAudio2AudioDriver(Memory* memory,\n xe::threading::Semaphore* semaphore)\n : AudioDriver(memory), semaphore_(semaphore) {}\n\nXAudio2AudioDriver::~XAudio2AudioDriver() = default;\n\nbool XAudio2AudioDriver::Initialize() {\n HRESULT hr;\n\n voice_callback_ = new VoiceCallback(semaphore_);\n\n \/\/ Load the XAudio2 DLL dynamically. Needed both for 2.7 and for\n \/\/ differentiating between 2.8 and later versions. Windows 8.1 SDK references\n \/\/ XAudio2_8.dll in xaudio2.lib, which is available on Windows 8.1, however,\n \/\/ Windows 10 SDK references XAudio2_9.dll in it, which is only available in\n \/\/ Windows 10, and XAudio2_8.dll is linked through a different .lib -\n \/\/ xaudio2_8.lib, so easier not to link the .lib at all.\n xaudio2_module_ = reinterpret_cast(LoadLibraryW(L\"XAudio2_8.dll\"));\n if (xaudio2_module_) {\n api_minor_version_ = 8;\n } else {\n xaudio2_module_ = reinterpret_cast(LoadLibraryW(L\"XAudio2_7.dll\"));\n if (xaudio2_module_) {\n api_minor_version_ = 7;\n } else {\n XELOGE(\"Failed to load XAudio 2.8 or 2.7 library DLL\");\n assert_always();\n return false;\n }\n }\n\n \/\/ First CPU (2.8 default). XAUDIO2_ANY_PROCESSOR (2.7 default) steals too\n \/\/ much time from other things. Ideally should process audio on what roughly\n \/\/ represents thread 4 (5th) on the Xbox 360 (2.7 default on the console), or\n \/\/ even beyond the 6 guest cores.\n api::XAUDIO2_PROCESSOR processor = 0x00000001;\n if (api_minor_version_ >= 8) {\n union {\n \/\/ clang-format off\n HRESULT (__stdcall* xaudio2_create)(\n api::IXAudio2_8** xaudio2_out, UINT32 flags,\n api::XAUDIO2_PROCESSOR xaudio2_processor);\n \/\/ clang-format on\n FARPROC xaudio2_create_ptr;\n };\n xaudio2_create_ptr = GetProcAddress(\n reinterpret_cast(xaudio2_module_), \"XAudio2Create\");\n if (!xaudio2_create_ptr) {\n XELOGE(\"XAudio2Create not found in XAudio2_8.dll\");\n assert_always();\n return false;\n }\n hr = xaudio2_create(&objects_.api_2_8.audio, 0, processor);\n if (FAILED(hr)) {\n XELOGE(\"XAudio2Create failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n return InitializeObjects(objects_.api_2_8);\n } else {\n hr = CoCreateInstance(__uuidof(api::XAudio2_7), NULL, CLSCTX_INPROC_SERVER,\n IID_PPV_ARGS(&objects_.api_2_7.audio));\n if (FAILED(hr)) {\n XELOGE(\"CoCreateInstance for XAudio2 failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n hr = objects_.api_2_7.audio->Initialize(0, processor);\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2::Initialize failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n return InitializeObjects(objects_.api_2_7);\n }\n}\n\ntemplate \nbool XAudio2AudioDriver::InitializeObjects(Objects& objects) {\n HRESULT hr;\n\n api::XAUDIO2_DEBUG_CONFIGURATION config;\n config.TraceMask = api::XE_XAUDIO2_LOG_ERRORS | api::XE_XAUDIO2_LOG_WARNINGS;\n config.BreakMask = 0;\n config.LogThreadID = FALSE;\n config.LogTiming = TRUE;\n config.LogFunctionName = TRUE;\n config.LogFileline = TRUE;\n objects.audio->SetDebugConfiguration(&config);\n\n hr = objects.audio->CreateMasteringVoice(&objects.mastering_voice);\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2::CreateMasteringVoice failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n\n WAVEFORMATIEEEFLOATEX waveformat;\n\n waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;\n waveformat.Format.nChannels = frame_channels_;\n waveformat.Format.nSamplesPerSec = 48000;\n waveformat.Format.wBitsPerSample = 32;\n waveformat.Format.nBlockAlign =\n (waveformat.Format.nChannels * waveformat.Format.wBitsPerSample) \/ 8;\n waveformat.Format.nAvgBytesPerSec =\n waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;\n waveformat.Format.cbSize =\n sizeof(WAVEFORMATIEEEFLOATEX) - sizeof(WAVEFORMATEX);\n\n waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;\n waveformat.Samples.wValidBitsPerSample = waveformat.Format.wBitsPerSample;\n static const DWORD kChannelMasks[] = {\n 0,\n 0,\n SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT,\n 0,\n 0,\n 0,\n SPEAKER_FRONT_LEFT | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT |\n SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT,\n 0,\n };\n waveformat.dwChannelMask = kChannelMasks[waveformat.Format.nChannels];\n\n hr = objects.audio->CreateSourceVoice(\n &objects.pcm_voice, &waveformat.Format,\n 0, \/\/ api::XE_XAUDIO2_VOICE_NOSRC | api::XE_XAUDIO2_VOICE_NOPITCH,\n api::XE_XAUDIO2_MAX_FREQ_RATIO, voice_callback_);\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2::CreateSourceVoice failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n\n hr = objects.pcm_voice->Start();\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2SourceVoice::Start failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n\n if (cvars::mute) {\n objects.pcm_voice->SetVolume(0.0f);\n }\n\n return true;\n}\n\nvoid XAudio2AudioDriver::SubmitFrame(uint32_t frame_ptr) {\n \/\/ Process samples! They are big-endian floats.\n HRESULT hr;\n\n api::XAUDIO2_VOICE_STATE state;\n if (api_minor_version_ >= 8) {\n objects_.api_2_8.pcm_voice->GetState(&state,\n api::XE_XAUDIO2_VOICE_NOSAMPLESPLAYED);\n } else {\n objects_.api_2_7.pcm_voice->GetState(&state);\n }\n assert_true(state.BuffersQueued < frame_count_);\n\n auto input_frame = memory_->TranslateVirtual(frame_ptr);\n auto output_frame = reinterpret_cast(frames_[current_frame_]);\n auto interleave_channels = frame_channels_;\n\n \/\/ interleave the data\n for (uint32_t index = 0, o = 0; index < channel_samples_; ++index) {\n for (uint32_t channel = 0, table = 0; channel < interleave_channels;\n ++channel, table += channel_samples_) {\n output_frame[o++] = xe::byte_swap(input_frame[table + index]);\n }\n }\n\n api::XAUDIO2_BUFFER buffer;\n buffer.Flags = 0;\n buffer.pAudioData = reinterpret_cast(output_frame);\n buffer.AudioBytes = frame_size_;\n buffer.PlayBegin = 0;\n buffer.PlayLength = channel_samples_;\n buffer.LoopBegin = api::XE_XAUDIO2_NO_LOOP_REGION;\n buffer.LoopLength = 0;\n buffer.LoopCount = 0;\n buffer.pContext = 0;\n if (api_minor_version_ >= 8) {\n hr = objects_.api_2_8.pcm_voice->SubmitSourceBuffer(&buffer);\n } else {\n hr = objects_.api_2_7.pcm_voice->SubmitSourceBuffer(&buffer);\n }\n if (FAILED(hr)) {\n XELOGE(\"SubmitSourceBuffer failed with {:08X}\", hr);\n assert_always();\n return;\n }\n\n current_frame_ = (current_frame_ + 1) % frame_count_;\n\n \/\/ Update playback ratio to our time scalar.\n \/\/ This will keep audio in sync with the game clock.\n float frequency_ratio = static_cast(xe::Clock::guest_time_scalar());\n if (api_minor_version_ >= 8) {\n objects_.api_2_8.pcm_voice->SetFrequencyRatio(frequency_ratio);\n } else {\n objects_.api_2_7.pcm_voice->SetFrequencyRatio(frequency_ratio);\n }\n}\n\nvoid XAudio2AudioDriver::Shutdown() {\n if (api_minor_version_ >= 8) {\n ShutdownObjects(objects_.api_2_8);\n } else {\n ShutdownObjects(objects_.api_2_7);\n }\n\n if (xaudio2_module_) {\n FreeLibrary(reinterpret_cast(xaudio2_module_));\n xaudio2_module_ = nullptr;\n }\n\n if (voice_callback_) {\n delete voice_callback_;\n voice_callback_ = nullptr;\n }\n}\n\ntemplate \nvoid XAudio2AudioDriver::ShutdownObjects(Objects& objects) {\n if (objects.pcm_voice) {\n objects.pcm_voice->Stop();\n objects.pcm_voice->DestroyVoice();\n objects.pcm_voice = nullptr;\n }\n\n if (objects.mastering_voice) {\n objects.mastering_voice->DestroyVoice();\n objects.mastering_voice = nullptr;\n }\n\n if (objects.audio) {\n objects.audio->StopEngine();\n objects.audio->Release();\n objects.audio = nullptr;\n }\n}\n\n} \/\/ namespace xaudio2\n} \/\/ namespace apu\n} \/\/ namespace xe\n[APU] Use vectorized converter in xaudio2 backend\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2020 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \"xenia\/apu\/xaudio2\/xaudio2_audio_driver.h\"\n\n\/\/ Must be included before xaudio2.h so we get the right windows.h include.\n#include \"xenia\/base\/platform_win.h\"\n\n#include \"xenia\/apu\/apu_flags.h\"\n#include \"xenia\/apu\/conversion.h\"\n#include \"xenia\/base\/clock.h\"\n#include \"xenia\/base\/logging.h\"\n\nnamespace xe {\nnamespace apu {\nnamespace xaudio2 {\n\nclass XAudio2AudioDriver::VoiceCallback : public api::IXAudio2VoiceCallback {\n public:\n explicit VoiceCallback(xe::threading::Semaphore* semaphore)\n : semaphore_(semaphore) {}\n ~VoiceCallback() {}\n\n void OnStreamEnd() {}\n void OnVoiceProcessingPassEnd() {}\n void OnVoiceProcessingPassStart(uint32_t samples_required) {}\n void OnBufferEnd(void* context) {\n auto ret = semaphore_->Release(1, nullptr);\n assert_true(ret);\n }\n void OnBufferStart(void* context) {}\n void OnLoopEnd(void* context) {}\n void OnVoiceError(void* context, HRESULT result) {}\n\n private:\n xe::threading::Semaphore* semaphore_ = nullptr;\n};\n\nXAudio2AudioDriver::XAudio2AudioDriver(Memory* memory,\n xe::threading::Semaphore* semaphore)\n : AudioDriver(memory), semaphore_(semaphore) {}\n\nXAudio2AudioDriver::~XAudio2AudioDriver() = default;\n\nbool XAudio2AudioDriver::Initialize() {\n HRESULT hr;\n\n voice_callback_ = new VoiceCallback(semaphore_);\n\n \/\/ Load the XAudio2 DLL dynamically. Needed both for 2.7 and for\n \/\/ differentiating between 2.8 and later versions. Windows 8.1 SDK references\n \/\/ XAudio2_8.dll in xaudio2.lib, which is available on Windows 8.1, however,\n \/\/ Windows 10 SDK references XAudio2_9.dll in it, which is only available in\n \/\/ Windows 10, and XAudio2_8.dll is linked through a different .lib -\n \/\/ xaudio2_8.lib, so easier not to link the .lib at all.\n xaudio2_module_ = reinterpret_cast(LoadLibraryW(L\"XAudio2_8.dll\"));\n if (xaudio2_module_) {\n api_minor_version_ = 8;\n } else {\n xaudio2_module_ = reinterpret_cast(LoadLibraryW(L\"XAudio2_7.dll\"));\n if (xaudio2_module_) {\n api_minor_version_ = 7;\n } else {\n XELOGE(\"Failed to load XAudio 2.8 or 2.7 library DLL\");\n assert_always();\n return false;\n }\n }\n\n \/\/ First CPU (2.8 default). XAUDIO2_ANY_PROCESSOR (2.7 default) steals too\n \/\/ much time from other things. Ideally should process audio on what roughly\n \/\/ represents thread 4 (5th) on the Xbox 360 (2.7 default on the console), or\n \/\/ even beyond the 6 guest cores.\n api::XAUDIO2_PROCESSOR processor = 0x00000001;\n if (api_minor_version_ >= 8) {\n union {\n \/\/ clang-format off\n HRESULT (__stdcall* xaudio2_create)(\n api::IXAudio2_8** xaudio2_out, UINT32 flags,\n api::XAUDIO2_PROCESSOR xaudio2_processor);\n \/\/ clang-format on\n FARPROC xaudio2_create_ptr;\n };\n xaudio2_create_ptr = GetProcAddress(\n reinterpret_cast(xaudio2_module_), \"XAudio2Create\");\n if (!xaudio2_create_ptr) {\n XELOGE(\"XAudio2Create not found in XAudio2_8.dll\");\n assert_always();\n return false;\n }\n hr = xaudio2_create(&objects_.api_2_8.audio, 0, processor);\n if (FAILED(hr)) {\n XELOGE(\"XAudio2Create failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n return InitializeObjects(objects_.api_2_8);\n } else {\n hr = CoCreateInstance(__uuidof(api::XAudio2_7), NULL, CLSCTX_INPROC_SERVER,\n IID_PPV_ARGS(&objects_.api_2_7.audio));\n if (FAILED(hr)) {\n XELOGE(\"CoCreateInstance for XAudio2 failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n hr = objects_.api_2_7.audio->Initialize(0, processor);\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2::Initialize failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n return InitializeObjects(objects_.api_2_7);\n }\n}\n\ntemplate \nbool XAudio2AudioDriver::InitializeObjects(Objects& objects) {\n HRESULT hr;\n\n api::XAUDIO2_DEBUG_CONFIGURATION config;\n config.TraceMask = api::XE_XAUDIO2_LOG_ERRORS | api::XE_XAUDIO2_LOG_WARNINGS;\n config.BreakMask = 0;\n config.LogThreadID = FALSE;\n config.LogTiming = TRUE;\n config.LogFunctionName = TRUE;\n config.LogFileline = TRUE;\n objects.audio->SetDebugConfiguration(&config);\n\n hr = objects.audio->CreateMasteringVoice(&objects.mastering_voice);\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2::CreateMasteringVoice failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n\n WAVEFORMATIEEEFLOATEX waveformat;\n\n waveformat.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;\n waveformat.Format.nChannels = frame_channels_;\n waveformat.Format.nSamplesPerSec = 48000;\n waveformat.Format.wBitsPerSample = 32;\n waveformat.Format.nBlockAlign =\n (waveformat.Format.nChannels * waveformat.Format.wBitsPerSample) \/ 8;\n waveformat.Format.nAvgBytesPerSec =\n waveformat.Format.nSamplesPerSec * waveformat.Format.nBlockAlign;\n waveformat.Format.cbSize =\n sizeof(WAVEFORMATIEEEFLOATEX) - sizeof(WAVEFORMATEX);\n\n waveformat.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;\n waveformat.Samples.wValidBitsPerSample = waveformat.Format.wBitsPerSample;\n static const DWORD kChannelMasks[] = {\n 0,\n 0,\n SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT,\n 0,\n 0,\n 0,\n SPEAKER_FRONT_LEFT | SPEAKER_FRONT_CENTER | SPEAKER_FRONT_RIGHT |\n SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT,\n 0,\n };\n waveformat.dwChannelMask = kChannelMasks[waveformat.Format.nChannels];\n\n hr = objects.audio->CreateSourceVoice(\n &objects.pcm_voice, &waveformat.Format,\n 0, \/\/ api::XE_XAUDIO2_VOICE_NOSRC | api::XE_XAUDIO2_VOICE_NOPITCH,\n api::XE_XAUDIO2_MAX_FREQ_RATIO, voice_callback_);\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2::CreateSourceVoice failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n\n hr = objects.pcm_voice->Start();\n if (FAILED(hr)) {\n XELOGE(\"IXAudio2SourceVoice::Start failed with {:08X}\", hr);\n assert_always();\n return false;\n }\n\n if (cvars::mute) {\n objects.pcm_voice->SetVolume(0.0f);\n }\n\n return true;\n}\n\nvoid XAudio2AudioDriver::SubmitFrame(uint32_t frame_ptr) {\n \/\/ Process samples! They are big-endian floats.\n HRESULT hr;\n\n api::XAUDIO2_VOICE_STATE state;\n if (api_minor_version_ >= 8) {\n objects_.api_2_8.pcm_voice->GetState(&state,\n api::XE_XAUDIO2_VOICE_NOSAMPLESPLAYED);\n } else {\n objects_.api_2_7.pcm_voice->GetState(&state);\n }\n assert_true(state.BuffersQueued < frame_count_);\n\n auto input_frame = memory_->TranslateVirtual(frame_ptr);\n auto output_frame = reinterpret_cast(frames_[current_frame_]);\n auto interleave_channels = frame_channels_;\n\n \/\/ interleave the data\n conversion::sequential_6_BE_to_interleaved_6_LE(output_frame, input_frame,\n channel_samples_);\n\n api::XAUDIO2_BUFFER buffer;\n buffer.Flags = 0;\n buffer.pAudioData = reinterpret_cast(output_frame);\n buffer.AudioBytes = frame_size_;\n buffer.PlayBegin = 0;\n buffer.PlayLength = channel_samples_;\n buffer.LoopBegin = api::XE_XAUDIO2_NO_LOOP_REGION;\n buffer.LoopLength = 0;\n buffer.LoopCount = 0;\n buffer.pContext = 0;\n if (api_minor_version_ >= 8) {\n hr = objects_.api_2_8.pcm_voice->SubmitSourceBuffer(&buffer);\n } else {\n hr = objects_.api_2_7.pcm_voice->SubmitSourceBuffer(&buffer);\n }\n if (FAILED(hr)) {\n XELOGE(\"SubmitSourceBuffer failed with {:08X}\", hr);\n assert_always();\n return;\n }\n\n current_frame_ = (current_frame_ + 1) % frame_count_;\n\n \/\/ Update playback ratio to our time scalar.\n \/\/ This will keep audio in sync with the game clock.\n float frequency_ratio = static_cast(xe::Clock::guest_time_scalar());\n if (api_minor_version_ >= 8) {\n objects_.api_2_8.pcm_voice->SetFrequencyRatio(frequency_ratio);\n } else {\n objects_.api_2_7.pcm_voice->SetFrequencyRatio(frequency_ratio);\n }\n}\n\nvoid XAudio2AudioDriver::Shutdown() {\n if (api_minor_version_ >= 8) {\n ShutdownObjects(objects_.api_2_8);\n } else {\n ShutdownObjects(objects_.api_2_7);\n }\n\n if (xaudio2_module_) {\n FreeLibrary(reinterpret_cast(xaudio2_module_));\n xaudio2_module_ = nullptr;\n }\n\n if (voice_callback_) {\n delete voice_callback_;\n voice_callback_ = nullptr;\n }\n}\n\ntemplate \nvoid XAudio2AudioDriver::ShutdownObjects(Objects& objects) {\n if (objects.pcm_voice) {\n objects.pcm_voice->Stop();\n objects.pcm_voice->DestroyVoice();\n objects.pcm_voice = nullptr;\n }\n\n if (objects.mastering_voice) {\n objects.mastering_voice->DestroyVoice();\n objects.mastering_voice = nullptr;\n }\n\n if (objects.audio) {\n objects.audio->StopEngine();\n objects.audio->Release();\n objects.audio = nullptr;\n }\n}\n\n} \/\/ namespace xaudio2\n} \/\/ namespace apu\n} \/\/ namespace xe\n<|endoftext|>"} {"text":"\/**\n * \\ file OutPointerFilter.cpp\n *\/\n\n#include \n\n#include \n\n#include \n#include \n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include \n\n#define PROCESSSIZE (10)\n\nBOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n \n ATK::InPointerFilter generator(data.data(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n std::array outdata;\n\n ATK::OutPointerFilter output(outdata.data(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n\n output.process(2);\n output.process(PROCESSSIZE - 2);\n \n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( OutPointerDouble_sin1k_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n \n ATK::InPointerFilter generator(data.data(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n \n std::array outdata;\n \n ATK::OutPointerFilter output(outdata.data(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n \n output.process(2);\n output.process(PROCESSSIZE - 2);\n \n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE(OutPointerDouble_check_bound_test)\n{\n std::array data;\n for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i + 1.) \/ 48000 * 1000);\n }\n\n ATK::InPointerFilter generator(data.data(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n std::array outdata;\n std::fill(outdata.begin(), outdata.end(), -1);\n\n ATK::OutPointerFilter output(outdata.data(), 1, 3*PROCESSSIZE\/2, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n\n output.process(2*PROCESSSIZE);\n\n for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n for (ptrdiff_t i = 0; i < PROCESSSIZE \/ 2; ++i)\n {\n BOOST_REQUIRE_EQUAL(0, outdata[PROCESSSIZE + i]); \/\/ check that input is now 0\n }\n for (ptrdiff_t i = 0; i < PROCESSSIZE \/ 2; ++i)\n {\n BOOST_REQUIRE_EQUAL(-1, outdata[3 * PROCESSSIZE \/2 + i]); \/\/ check that we don't write after what we declare was allocated\n }\n}\n\nBOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_interleaved_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[2*i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n data[2*i+1] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 2000);\n }\n \n ATK::InPointerFilter generator(data.data(), PROCESSSIZE, 2, true);\n generator.set_output_sampling_rate(48000);\n\n std::array outdata;\n \n ATK::OutPointerFilter output(outdata.data(), PROCESSSIZE, 2, true);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n output.set_input_port(1, &generator, 1);\n \n output.process(2);\n output.process(PROCESSSIZE);\n output.process(PROCESSSIZE);\n output.process(PROCESSSIZE);\n \n for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_noninterleaved_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i+PROCESSSIZE] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 2000);\n }\n \n ATK::InPointerFilter generator(data.data(), 2, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n \n std::array outdata;\n \n ATK::OutPointerFilter output(outdata.data(), 2, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n output.set_input_port(1, &generator, 1);\n\n output.process(2);\n output.process(PROCESSSIZE - 2);\n \n for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\nFinally found the proper way of testing this line!!!!\/**\n * \\ file OutPointerFilter.cpp\n *\/\n\n#include \n\n#include \n\n#include \n#include \n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include \n\n#define PROCESSSIZE (10)\n\nBOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n \n ATK::InPointerFilter generator(data.data(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n std::array outdata;\n\n ATK::OutPointerFilter output(outdata.data(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n\n output.process(2);\n output.process(PROCESSSIZE - 2);\n \n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( OutPointerDouble_sin1k_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n \n ATK::InPointerFilter generator(data.data(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n \n std::array outdata;\n \n ATK::OutPointerFilter output(outdata.data(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n \n output.process(2);\n output.process(PROCESSSIZE - 2);\n \n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE(OutPointerDouble_check_bound_test)\n{\n std::array data;\n for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i + 1.) \/ 48000 * 1000);\n }\n\n ATK::InPointerFilter generator(data.data(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n std::array outdata;\n std::fill(outdata.begin(), outdata.end(), -1);\n\n ATK::OutPointerFilter output(outdata.data(), 1, 3*PROCESSSIZE\/2, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n\n output.process(2*PROCESSSIZE);\n\n for (ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n for (ptrdiff_t i = 0; i < PROCESSSIZE \/ 2; ++i)\n {\n BOOST_REQUIRE_EQUAL(0, outdata[PROCESSSIZE + i]); \/\/ check that input is now 0\n }\n for (ptrdiff_t i = 0; i < PROCESSSIZE \/ 2; ++i)\n {\n BOOST_REQUIRE_EQUAL(-1, outdata[3 * PROCESSSIZE \/2 + i]); \/\/ check that we don't write after what we declare was allocated\n }\n}\n\nBOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_interleaved_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[2*i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n data[2*i+1] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 2000);\n }\n \n ATK::InPointerFilter generator(data.data(), PROCESSSIZE, 2, true);\n generator.set_output_sampling_rate(48000);\n\n std::array outdata;\n \n ATK::OutPointerFilter output(outdata.data(), PROCESSSIZE, 2, true);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n output.set_input_port(1, &generator, 1);\n \n output.process(2);\n output.process(PROCESSSIZE - 2);\n \n for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( OutPointerFloat_sin1k2k_noninterleaved_test )\n{\n std::array data;\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n for(ptrdiff_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i+PROCESSSIZE] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 2000);\n }\n \n ATK::InPointerFilter generator(data.data(), 2, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n \n std::array outdata;\n \n ATK::OutPointerFilter output(outdata.data(), 2, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &generator, 0);\n output.set_input_port(1, &generator, 1);\n\n output.process(2);\n output.process(PROCESSSIZE);\n output.process(PROCESSSIZE);\n output.process(PROCESSSIZE);\n \n for(ptrdiff_t i = 0; i < 2*PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i], outdata[i]);\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \"client.h\"\n\nClient::Client(ClientArguments *args)\n : _args(args),\n _status(new ClientStatus()),\n _reqTimer(new Timer()),\n _cycleTimer(new Timer()),\n _masterTimer(new Timer()),\n _http(new HTTPClient(_args->_hostname, _args->_port,\n _args->_keepAlive, _args->_headerBenchmarkdataCoverage,\n _args->_extraHeaders, _args->_authority)),\n _reader(new FileReader()),\n _output(),\n _linebufsize(args->_maxLineSize),\n _linebuf(new char[_linebufsize]),\n _stop(false),\n _done(false),\n _thread()\n{\n assert(args != NULL);\n _cycleTimer->SetMax(_args->_cycle);\n}\n\nClient::~Client()\n{\n delete [] _linebuf;\n}\n\nvoid Client::runMe(Client * me) {\n me->run();\n}\n\n\nclass UrlReader {\n FileReader &_reader;\n const ClientArguments &_args;\n int _restarts;\n int _contentbufsize;\n int _leftOversLen;\n char *_contentbuf;\n const char *_leftOvers;\npublic:\n UrlReader(FileReader& reader, const ClientArguments &args)\n : _reader(reader), _args(args), _restarts(0),\n _contentbufsize(0), _leftOversLen(0),\n _contentbuf(0), _leftOvers(0)\n {\n if (_args._usePostMode) {\n _contentbufsize = 16 * _args._maxLineSize;\n _contentbuf = new char[_contentbufsize];\n }\n }\n bool reset();\n int findUrl(char *buf, int buflen);\n int nextUrl(char *buf, int buflen);\n int getContent();\n const char *content() const { return _contentbuf; }\n ~UrlReader() { delete [] _contentbuf; }\n};\n\nbool UrlReader::reset()\n{\n if (_restarts == _args._restartLimit) {\n return false;\n } else if (_args._restartLimit > 0) {\n _restarts++;\n }\n _reader.Reset();\n \/\/ Start reading from offset\n if (_args._singleQueryFile) {\n _reader.SetFilePos(_args._queryfileOffset);\n }\n return true;\n}\n\nint UrlReader::findUrl(char *buf, int buflen)\n{\n while (true) {\n if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) {\n \/\/ reached logical EOF\n return -1;\n }\n int ll = _reader.ReadLine(buf, buflen);\n if (ll < 0) {\n \/\/ reached physical EOF\n return ll;\n }\n if (ll > 0) {\n if (buf[0] == '\/' || !_args._usePostMode) {\n \/\/ found URL\n return ll;\n }\n }\n }\n}\n\nint UrlReader::nextUrl(char *buf, int buflen)\n{\n if (_leftOvers) {\n int sz = std::min(_leftOversLen, buflen-1);\n strncpy(buf, _leftOvers, sz);\n buf[sz] = '\\0';\n _leftOvers = NULL;\n return _leftOversLen;\n }\n int ll = findUrl(buf, buflen);\n if (ll > 0) {\n return ll;\n }\n if (reset()) {\n \/\/ try again\n ll = findUrl(buf, buflen);\n }\n return ll;\n}\n\nint UrlReader::getContent()\n{\n char *buf = _contentbuf;\n int totLen = 0;\n while (totLen < _contentbufsize) {\n int left = _contentbufsize - totLen;\n int len = _reader.ReadLine(buf, left);\n if (len < 0) {\n \/\/ reached EOF\n return totLen;\n }\n if (len > 0 && buf[0] == '\/') {\n \/\/ reached next URL\n _leftOvers = buf;\n _leftOversLen = len;\n return totLen;\n }\n buf += len;\n totLen += len;\n }\n return totLen;\n}\n\n\nvoid\nClient::run()\n{\n char inputFilename[1024];\n char outputFilename[1024];\n char timestr[64];\n int linelen;\n \/\/\/ int reslen;\n\n std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay));\n\n \/\/ open query file\n snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum);\n if (!_reader->Open(inputFilename)) {\n printf(\"Client %d: ERROR: could not open file '%s' [read mode]\\n\",\n _args->_myNum, inputFilename);\n _status->SetError(\"Could not open query file.\");\n return;\n }\n if (_args->_outputPattern != NULL) {\n snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum);\n _output = std::make_unique(outputFilename, std::ofstream::out | std::ofstream::binary);\n if (_output->fail()) {\n printf(\"Client %d: ERROR: could not open file '%s' [write mode]\\n\",\n _args->_myNum, outputFilename);\n _status->SetError(\"Could not open output file.\");\n return;\n }\n }\n if (_output)\n _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);\n\n if (_args->_ignoreCount == 0)\n _masterTimer->Start();\n\n \/\/ Start reading from offset\n if ( _args->_singleQueryFile )\n _reader->SetFilePos(_args->_queryfileOffset);\n\n UrlReader urlSource(*_reader, *_args);\n size_t urlNumber = 0;\n\n \/\/ run queries\n while (!_stop) {\n\n _cycleTimer->Start();\n\n linelen = urlSource.nextUrl(_linebuf, _linebufsize);\n if (linelen > 0) {\n ++urlNumber;\n } else {\n if (urlNumber == 0) {\n fprintf(stderr, \"Client %d: ERROR: could not read any lines from '%s'\\n\",\n _args->_myNum, inputFilename);\n _status->SetError(\"Could not read any lines from query file.\");\n }\n break;\n }\n if (linelen < _linebufsize) {\n if (_output) {\n _output->write(\"URL: \", strlen(\"URL: \"));\n _output->write(_linebuf, linelen);\n _output->write(\"\\n\\n\", 2);\n }\n if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) {\n strcat(_linebuf, _args->_queryStringToAppend.c_str());\n }\n int cLen = _args->_usePostMode ? urlSource.getContent() : 0;\n _reqTimer->Start();\n auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, urlSource.content(), cLen);\n _reqTimer->Stop();\n _status->AddRequestStatus(fetch_status.RequestStatus());\n if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0)\n ++_status->_zeroHitQueries;\n if (_output) {\n if (!fetch_status.Ok()) {\n _output->write(\"\\nFBENCH: URL FETCH FAILED!\\n\",\n strlen(\"\\nFBENCH: URL FETCH FAILED!\\n\"));\n _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);\n } else {\n sprintf(timestr, \"\\nTIME USED: %0.4f s\\n\",\n _reqTimer->GetTimespan() \/ 1000.0);\n _output->write(timestr, strlen(timestr));\n _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);\n }\n }\n if (fetch_status.ResultSize() >= _args->_byteLimit) {\n if (_args->_ignoreCount == 0)\n _status->ResponseTime(_reqTimer->GetTimespan());\n } else {\n if (_args->_ignoreCount == 0)\n _status->RequestFailed();\n }\n } else {\n if (_args->_ignoreCount == 0)\n _status->SkippedRequest();\n }\n _cycleTimer->Stop();\n if (_args->_cycle < 0) {\n std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan())));\n } else {\n if (_cycleTimer->GetRemaining() > 0) {\n std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining())));\n } else {\n if (_args->_ignoreCount == 0)\n _status->OverTime();\n }\n }\n if (_args->_ignoreCount > 0) {\n _args->_ignoreCount--;\n if (_args->_ignoreCount == 0)\n _masterTimer->Start();\n }\n \/\/ Update current time span to calculate Q\/s\n _status->SetRealTime(_masterTimer->GetCurrent());\n }\n _masterTimer->Stop();\n _status->SetRealTime(_masterTimer->GetTimespan());\n _status->SetReuseCount(_http->GetReuseCount());\n printf(\".\");\n fflush(stdout);\n _done = true;\n}\n\nvoid Client::stop() {\n _stop = true;\n}\n\nbool Client::done() {\n return _done;\n}\n\nvoid Client::start() {\n _thread = std::thread(Client::runMe, this);\n}\n\nvoid Client::join() {\n _thread.join();\n}\nput newline between content lines\/\/ Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.\n#include \n#include \n#include \n#include \"client.h\"\n\nClient::Client(ClientArguments *args)\n : _args(args),\n _status(new ClientStatus()),\n _reqTimer(new Timer()),\n _cycleTimer(new Timer()),\n _masterTimer(new Timer()),\n _http(new HTTPClient(_args->_hostname, _args->_port,\n _args->_keepAlive, _args->_headerBenchmarkdataCoverage,\n _args->_extraHeaders, _args->_authority)),\n _reader(new FileReader()),\n _output(),\n _linebufsize(args->_maxLineSize),\n _linebuf(new char[_linebufsize]),\n _stop(false),\n _done(false),\n _thread()\n{\n assert(args != NULL);\n _cycleTimer->SetMax(_args->_cycle);\n}\n\nClient::~Client()\n{\n delete [] _linebuf;\n}\n\nvoid Client::runMe(Client * me) {\n me->run();\n}\n\n\nclass UrlReader {\n FileReader &_reader;\n const ClientArguments &_args;\n int _restarts;\n int _contentbufsize;\n int _leftOversLen;\n char *_contentbuf;\n const char *_leftOvers;\npublic:\n UrlReader(FileReader& reader, const ClientArguments &args)\n : _reader(reader), _args(args), _restarts(0),\n _contentbufsize(0), _leftOversLen(0),\n _contentbuf(0), _leftOvers(0)\n {\n if (_args._usePostMode) {\n _contentbufsize = 16 * _args._maxLineSize;\n _contentbuf = new char[_contentbufsize];\n }\n }\n bool reset();\n int findUrl(char *buf, int buflen);\n int nextUrl(char *buf, int buflen);\n int nextContent();\n const char *content() const { return _contentbuf; }\n ~UrlReader() { delete [] _contentbuf; }\n};\n\nbool UrlReader::reset()\n{\n if (_restarts == _args._restartLimit) {\n return false;\n } else if (_args._restartLimit > 0) {\n _restarts++;\n }\n _reader.Reset();\n \/\/ Start reading from offset\n if (_args._singleQueryFile) {\n _reader.SetFilePos(_args._queryfileOffset);\n }\n return true;\n}\n\nint UrlReader::findUrl(char *buf, int buflen)\n{\n while (true) {\n if ( _args._singleQueryFile && _reader.GetFilePos() >= _args._queryfileEndOffset ) {\n \/\/ reached logical EOF\n return -1;\n }\n int ll = _reader.ReadLine(buf, buflen);\n if (ll < 0) {\n \/\/ reached physical EOF\n return ll;\n }\n if (ll > 0) {\n if (buf[0] == '\/' || !_args._usePostMode) {\n \/\/ found URL\n return ll;\n }\n }\n }\n}\n\nint UrlReader::nextUrl(char *buf, int buflen)\n{\n if (_leftOvers) {\n int sz = std::min(_leftOversLen, buflen-1);\n strncpy(buf, _leftOvers, sz);\n buf[sz] = '\\0';\n _leftOvers = NULL;\n return _leftOversLen;\n }\n int ll = findUrl(buf, buflen);\n if (ll > 0) {\n return ll;\n }\n if (reset()) {\n \/\/ try again\n ll = findUrl(buf, buflen);\n }\n return ll;\n}\n\nint UrlReader::nextContent()\n{\n char *buf = _contentbuf;\n int totLen = 0;\n int nl = 0;\n while (totLen + 1 < _contentbufsize) {\n int left = _contentbufsize - totLen;\n \/\/ allow space for newline:\n int len = _reader.ReadLine(buf, left - 1);\n if (len < 0) {\n \/\/ reached EOF\n return totLen;\n }\n if (len > 0 && buf[0] == '\/') {\n \/\/ reached next URL\n _leftOvers = buf;\n _leftOversLen = len;\n return totLen;\n }\n buf += len;\n *buf++ = '\\n';\n totLen += nl + len;\n nl = 1;\n }\n return totLen;\n}\n\n\nvoid\nClient::run()\n{\n char inputFilename[1024];\n char outputFilename[1024];\n char timestr[64];\n int linelen;\n \/\/\/ int reslen;\n\n std::this_thread::sleep_for(std::chrono::milliseconds(_args->_delay));\n\n \/\/ open query file\n snprintf(inputFilename, 1024, _args->_filenamePattern, _args->_myNum);\n if (!_reader->Open(inputFilename)) {\n printf(\"Client %d: ERROR: could not open file '%s' [read mode]\\n\",\n _args->_myNum, inputFilename);\n _status->SetError(\"Could not open query file.\");\n return;\n }\n if (_args->_outputPattern != NULL) {\n snprintf(outputFilename, 1024, _args->_outputPattern, _args->_myNum);\n _output = std::make_unique(outputFilename, std::ofstream::out | std::ofstream::binary);\n if (_output->fail()) {\n printf(\"Client %d: ERROR: could not open file '%s' [write mode]\\n\",\n _args->_myNum, outputFilename);\n _status->SetError(\"Could not open output file.\");\n return;\n }\n }\n if (_output)\n _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);\n\n if (_args->_ignoreCount == 0)\n _masterTimer->Start();\n\n \/\/ Start reading from offset\n if ( _args->_singleQueryFile )\n _reader->SetFilePos(_args->_queryfileOffset);\n\n UrlReader urlSource(*_reader, *_args);\n size_t urlNumber = 0;\n\n \/\/ run queries\n while (!_stop) {\n\n _cycleTimer->Start();\n\n linelen = urlSource.nextUrl(_linebuf, _linebufsize);\n if (linelen > 0) {\n ++urlNumber;\n } else {\n if (urlNumber == 0) {\n fprintf(stderr, \"Client %d: ERROR: could not read any lines from '%s'\\n\",\n _args->_myNum, inputFilename);\n _status->SetError(\"Could not read any lines from query file.\");\n }\n break;\n }\n if (linelen < _linebufsize) {\n if (_output) {\n _output->write(\"URL: \", strlen(\"URL: \"));\n _output->write(_linebuf, linelen);\n _output->write(\"\\n\\n\", 2);\n }\n if (linelen + (int)_args->_queryStringToAppend.length() < _linebufsize) {\n strcat(_linebuf, _args->_queryStringToAppend.c_str());\n }\n int cLen = _args->_usePostMode ? urlSource.nextContent() : 0;\n _reqTimer->Start();\n auto fetch_status = _http->Fetch(_linebuf, _output.get(), _args->_usePostMode, urlSource.content(), cLen);\n _reqTimer->Stop();\n _status->AddRequestStatus(fetch_status.RequestStatus());\n if (fetch_status.Ok() && fetch_status.TotalHitCount() == 0)\n ++_status->_zeroHitQueries;\n if (_output) {\n if (!fetch_status.Ok()) {\n _output->write(\"\\nFBENCH: URL FETCH FAILED!\\n\",\n strlen(\"\\nFBENCH: URL FETCH FAILED!\\n\"));\n _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);\n } else {\n sprintf(timestr, \"\\nTIME USED: %0.4f s\\n\",\n _reqTimer->GetTimespan() \/ 1000.0);\n _output->write(timestr, strlen(timestr));\n _output->write(FBENCH_DELIMITER + 1, strlen(FBENCH_DELIMITER) - 1);\n }\n }\n if (fetch_status.ResultSize() >= _args->_byteLimit) {\n if (_args->_ignoreCount == 0)\n _status->ResponseTime(_reqTimer->GetTimespan());\n } else {\n if (_args->_ignoreCount == 0)\n _status->RequestFailed();\n }\n } else {\n if (_args->_ignoreCount == 0)\n _status->SkippedRequest();\n }\n _cycleTimer->Stop();\n if (_args->_cycle < 0) {\n std::this_thread::sleep_for(std::chrono::milliseconds(int(_reqTimer->GetTimespan())));\n } else {\n if (_cycleTimer->GetRemaining() > 0) {\n std::this_thread::sleep_for(std::chrono::milliseconds(int(_cycleTimer->GetRemaining())));\n } else {\n if (_args->_ignoreCount == 0)\n _status->OverTime();\n }\n }\n if (_args->_ignoreCount > 0) {\n _args->_ignoreCount--;\n if (_args->_ignoreCount == 0)\n _masterTimer->Start();\n }\n \/\/ Update current time span to calculate Q\/s\n _status->SetRealTime(_masterTimer->GetCurrent());\n }\n _masterTimer->Stop();\n _status->SetRealTime(_masterTimer->GetTimespan());\n _status->SetReuseCount(_http->GetReuseCount());\n printf(\".\");\n fflush(stdout);\n _done = true;\n}\n\nvoid Client::stop() {\n _stop = true;\n}\n\nbool Client::done() {\n return _done;\n}\n\nvoid Client::start() {\n _thread = std::thread(Client::runMe, this);\n}\n\nvoid Client::join() {\n _thread.join();\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP\n#define STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Specialisation for use with combinations of\n * `Eigen::Matrix` and `var_value` inputs.\n * Eigen's binaryExpr framework is used for more efficient indexing of both row-\n * and column-major inputs without separate loops.\n *\n * @tparam T1 Type of first argument to which functor is applied.\n * @tparam T2 Type of second argument to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x First Matrix input to which operation is applied.\n * @param y Second Matrix input to which operation is applied.\n * @param f functor to apply to Matrix inputs.\n * @return `var_value` with result of applying functor to inputs.\n *\/\ntemplate * = nullptr,\n require_all_matrix_t* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n check_matching_dims(\"Binary function\", \"x\", x, \"y\", y);\n return f(x, y);\n}\n\n\/**\n * Specialisation for use with one `var_value` (row or column) and\n * a one-dimensional std::vector of integer types\n *\n * @tparam T1 Type of first argument to which functor is applied.\n * @tparam T2 Type of second argument to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x Matrix input to which operation is applied.\n * @param y Integer std::vector input to which operation is applied.\n * @param f functor to apply to inputs.\n * @return var_value object with result of applying functor to inputs.\n *\/\ntemplate * = nullptr,\n require_any_std_vector_vt* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n check_matching_sizes(\"Binary function\", \"x\", x, \"y\", y);\n return f(x, y);\n}\n\n\/**\n * Specialisation for use with a two-dimensional std::vector of integer types\n * and one `var_value`.\n *\n * @tparam T1 Type of first argument to which functor is applied.\n * @tparam T2 Type of second argument to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x Either a var matrix or nested integer std::vector input to which operation is applied.\n * @param x Either a var matrix or nested integer std::vector input to which operation is applied.\n * @param f functor to apply to inputs.\n * @return Eigen object with result of applying functor to inputs.\n *\/\ntemplate * = nullptr,\n require_any_std_vector_st* = nullptr,\n require_any_var_matrix_t* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n return f(x, y);\n}\n\n\n\/**\n * Specialisation for use when the one input is an `var_value type and\n * the other is a scalar.\n *\n * @tparam T1 Type of either `var_value` or scalar object to which functor is applied.\n * @tparam T2 Type of either `var_value` or scalar object to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x Matrix or Scalar input to which operation is applied.\n * @param x Matrix or Scalar input to which operation is applied.\n * @param f functor to apply to var matrix and scalar inputs.\n * @return `var_value object with result of applying functor to inputs.\n *\n *\/\n template * = nullptr,\n require_any_var_matrix_t* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n return f(x, y);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#ifndef STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP\n#define STAN_MATH_REV_FUNCTOR_APPLY_SCALAR_BINARY_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Specialisation for use with combinations of\n * `Eigen::Matrix` and `var_value` inputs.\n * Eigen's binaryExpr framework is used for more efficient indexing of both row-\n * and column-major inputs without separate loops.\n *\n * @tparam T1 Type of first argument to which functor is applied.\n * @tparam T2 Type of second argument to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x First Matrix input to which operation is applied.\n * @param y Second Matrix input to which operation is applied.\n * @param f functor to apply to Matrix inputs.\n * @return `var_value` with result of applying functor to inputs.\n *\/\ntemplate * = nullptr,\n require_all_matrix_t* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n check_matching_dims(\"Binary function\", \"x\", x, \"y\", y);\n return f(x, y);\n}\n\n\/**\n * Specialisation for use with one `var_value` (row or column) and\n * a one-dimensional std::vector of integer types\n *\n * @tparam T1 Type of first argument to which functor is applied.\n * @tparam T2 Type of second argument to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x Matrix input to which operation is applied.\n * @param y Integer std::vector input to which operation is applied.\n * @param f functor to apply to inputs.\n * @return var_value object with result of applying functor to inputs.\n *\/\ntemplate * = nullptr,\n require_any_std_vector_vt* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n check_matching_sizes(\"Binary function\", \"x\", x, \"y\", y);\n return f(x, y);\n}\n\n\/**\n * Specialisation for use with a two-dimensional std::vector of integer types\n * and one `var_value`.\n *\n * @tparam T1 Type of first argument to which functor is applied.\n * @tparam T2 Type of second argument to which functor is applied.\n * @tparam F Type of functor to apply.\n * @param x Either a var matrix or nested integer std::vector input to which\n * operation is applied.\n * @param x Either a var matrix or nested integer std::vector input to which\n * operation is applied.\n * @param f functor to apply to inputs.\n * @return Eigen object with result of applying functor to inputs.\n *\/\ntemplate * = nullptr,\n require_any_std_vector_st* = nullptr,\n require_any_var_matrix_t* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n return f(x, y);\n}\n\n\/**\n * Specialisation for use when the one input is an `var_value type and\n * the other is a scalar.\n *\n * @tparam T1 Type of either `var_value` or scalar object to which\n * functor is applied.\n * @tparam T2 Type of either `var_value` or scalar object to which\n * functor is applied.\n * @tparam F Type of functor to apply.\n * @param x Matrix or Scalar input to which operation is applied.\n * @param x Matrix or Scalar input to which operation is applied.\n * @param f functor to apply to var matrix and scalar inputs.\n * @return `var_value object with result of applying functor to inputs.\n *\n *\/\ntemplate * = nullptr,\n require_any_var_matrix_t* = nullptr>\ninline auto apply_scalar_binary(const T1& x, const T2& y, const F& f) {\n return f(x, y);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: elementparser.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: kz $ $Date: 2004-08-31 14:59:01 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_XML_ELEMENTPARSER_HXX\n#define CONFIGMGR_XML_ELEMENTPARSER_HXX\n\n#ifndef CONFIGMGR_XML_ELEMENTINFO_HXX\n#include \"elementinfo.hxx\"\n#endif\n\n#ifndef CONFIGMGR_LOGGER_HXX\n#include \"logger.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_\n#include \n#endif\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace sax = ::com::sun::star::xml::sax;\n\n using rtl::OUString;\n\n\/\/ -----------------------------------------------------------------------------\n class ElementParser\n {\n Logger mLogger;\n public:\n typedef uno::Reference< sax::XAttributeList > SaxAttributeList;\n public:\n explicit\n ElementParser(Logger const & xLogger)\n : mLogger(xLogger)\n {}\n\n Logger const & logger() const { return mLogger; }\n\n \/\/\/ reset the parser for a new document\n void reset()\n {}\n\n \/\/\/ retrieve the (almost) complete information for an element\n ElementInfo parseElementInfo(OUString const& _sTag, SaxAttributeList const& _xAttribs) const;\n\n \/\/\/ retrieve the node name for an element\n ElementType::Enum getNodeType(OUString const& _sTag, SaxAttributeList const& xAttribs) const;\n\n \/\/\/ retrieve the node name for an element\n ElementName getName(OUString const& _sTag, SaxAttributeList const& xAttribs, ElementType::Enum eType = ElementType::unknown) const;\n\n \/\/\/ query whether the node has an operation\n Operation::Enum getOperation(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const;\n\n \/\/\/ retrieve the language (if any) stored in the attribute list\n bool getLanguage(SaxAttributeList const& xAttribs, OUString & _rsLanguage) const;\n\n \/\/\/ reads attributes for nodes from the attribute list\n ElementInfo::FlagsType getNodeFlags(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const;\n\n \/\/\/ retrieve element type and associated module name of a set,\n bool getSetElementType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const;\n\n \/\/\/ retrieve the instance type and associated module name of a instance,\n bool getInstanceType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const;\n\n \/\/\/ retrieve the component for an import or uses element,\n bool getImportComponent(SaxAttributeList const& _xAttribs, OUString& _rsComponent) const;\n\n \/\/\/ retrieve element type and associated module name of a set,\n uno::Type getPropertyValueType(SaxAttributeList const& _xAttribs) const;\n\n \/\/\/ reads a value attribute from the attribute list\n bool isNull(SaxAttributeList const& _xAttribs) const;\n\n \/\/\/ reads a value attribute from the attribute list\n OUString getSeparator(SaxAttributeList const& _xAttribs) const;\n\n \/\/ low-level internal methods\n\n \/\/\/ checks for presence of a boolean attribute and assigns its value if it exists (and is a bool)\n bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, bool& _rbAttributeValue) const;\n\n \/\/\/ checks for presence of an attribute and assigns its value if it exists\n bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const;\n\n \/\/\/ assigns an attribute value or an empty string if it doesn't exist\n void alwaysGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const;\n };\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n } \/\/ namespace xml\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n#endif\n\nINTEGRATION: CWS cfglooseends (1.3.12); FILE MERGED 2004\/11\/05 10:25:10 jb 1.3.12.1: #115489# Raise an exception when encountering an invalid value type\/*************************************************************************\n *\n * $RCSfile: elementparser.hxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-11-15 13:38:55 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2002 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef CONFIGMGR_XML_ELEMENTPARSER_HXX\n#define CONFIGMGR_XML_ELEMENTPARSER_HXX\n\n#ifndef CONFIGMGR_XML_ELEMENTINFO_HXX\n#include \"elementinfo.hxx\"\n#endif\n\n#ifndef CONFIGMGR_LOGGER_HXX\n#include \"logger.hxx\"\n#endif\n\n#ifndef _COM_SUN_STAR_XML_SAX_XATTRIBUTELIST_HPP_\n#include \n#endif\n\nnamespace configmgr\n{\n\/\/ -----------------------------------------------------------------------------\n namespace xml\n {\n\/\/ -----------------------------------------------------------------------------\n namespace uno = ::com::sun::star::uno;\n namespace sax = ::com::sun::star::xml::sax;\n\n using rtl::OUString;\n\n\/\/ -----------------------------------------------------------------------------\n class ElementParser\n {\n Logger mLogger;\n public:\n typedef uno::Reference< sax::XAttributeList > SaxAttributeList;\n\n class BadValueType\n {\n OUString mMessage;\n public:\n BadValueType(OUString const & aMessage) : mMessage(aMessage) {}\n\n OUString message() const { return mMessage.getStr(); }\n };\n public:\n explicit\n ElementParser(Logger const & xLogger)\n : mLogger(xLogger)\n {}\n\n Logger const & logger() const { return mLogger; }\n\n \/\/\/ reset the parser for a new document\n void reset()\n {}\n\n \/\/\/ retrieve the (almost) complete information for an element\n ElementInfo parseElementInfo(OUString const& _sTag, SaxAttributeList const& _xAttribs) const;\n\n \/\/\/ retrieve the node name for an element\n ElementType::Enum getNodeType(OUString const& _sTag, SaxAttributeList const& xAttribs) const;\n\n \/\/\/ retrieve the node name for an element\n ElementName getName(OUString const& _sTag, SaxAttributeList const& xAttribs, ElementType::Enum eType = ElementType::unknown) const;\n\n \/\/\/ query whether the node has an operation\n Operation::Enum getOperation(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const;\n\n \/\/\/ retrieve the language (if any) stored in the attribute list\n bool getLanguage(SaxAttributeList const& xAttribs, OUString & _rsLanguage) const;\n\n \/\/\/ reads attributes for nodes from the attribute list\n ElementInfo::FlagsType getNodeFlags(SaxAttributeList const& xAttribs, ElementType::Enum _eType) const;\n\n \/\/\/ retrieve element type and associated module name of a set,\n bool getSetElementType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const;\n\n \/\/\/ retrieve the instance type and associated module name of a instance,\n bool getInstanceType(SaxAttributeList const& _xAttribs, OUString& _rsElementType, OUString& _rsElementTypeModule) const;\n\n \/\/\/ retrieve the component for an import or uses element,\n bool getImportComponent(SaxAttributeList const& _xAttribs, OUString& _rsComponent) const;\n\n \/\/\/ retrieve element type and associated module name of a set,\n uno::Type getPropertyValueType(SaxAttributeList const& _xAttribs) const;\n \/\/ throw( BadValueType )\n\n \/\/\/ reads a value attribute from the attribute list\n bool isNull(SaxAttributeList const& _xAttribs) const;\n\n \/\/\/ reads a value attribute from the attribute list\n OUString getSeparator(SaxAttributeList const& _xAttribs) const;\n\n \/\/ low-level internal methods\n\n \/\/\/ checks for presence of a boolean attribute and assigns its value if it exists (and is a bool)\n bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, bool& _rbAttributeValue) const;\n\n \/\/\/ checks for presence of an attribute and assigns its value if it exists\n bool maybeGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const;\n\n \/\/\/ assigns an attribute value or an empty string if it doesn't exist\n void alwaysGetAttribute(SaxAttributeList const& _xAttribs, OUString const& _aAttributeName, OUString& _rsAttributeValue) const;\n };\n\/\/ -----------------------------------------------------------------------------\n\n\/\/ -----------------------------------------------------------------------------\n } \/\/ namespace xml\n\/\/ -----------------------------------------------------------------------------\n} \/\/ namespace configmgr\n\n#endif\n\n<|endoftext|>"} {"text":"\/\/===--- RuntimeEntrySymbols.cpp - Define symbols for runtime entries --===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines function pointer symbols for runtime entries.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Produce global symbols referencing runtime function implementations only for\n\/\/ those runtime entries that demand it.\n\/\/\n\/\/ Each runtime function definition in RuntimeFunctions.def should\n\/\/ indicate if it requires a global referencing it.\n\/\/\n\/\/ For example, all entries using the RegisterPreservingCC calling convention\n\/\/ need a global, because they are currently always invoked indirectly using a\n\/\/ client-side wrapper.\n\/\/\n\/\/ Runtime entries using the DefaultCC calling convention do not\n\/\/ demand a global symbol by default. But they can optionally ask for it, in\n\/\/ case it is needed. For example, _swift_isDeallocating is required by\n\/\/ Instruments.\n\n#include \"swift\/Runtime\/Config.h\"\n\n\/\/ Entry points using a standard C calling convention or not using the new\n\/\/ calling convention do not need to have global symbols referring to their\n\/\/ implementations.\n#define FOR_CONV_DefaultCC(...)\n#define FOR_CONV_C_CC(...)\n\/\/ Entry points using the new calling convention require global symbols\n\/\/ referring to their implementations.\n#define FOR_CONV_RegisterPreservingCC(x) x\n\ntypedef void (*RuntimeEntry)();\n\n\/\/ Generate a forward declaration of the runtime entry implementation.\n\/\/ Define a global symbol referring to this implementation.\n\n#define DEFINE_SYMBOL(SymbolName, Name, CC) \\\n SWIFT_RT_ENTRY_VISIBILITY extern \"C\" void Name() \\\n SWIFT_CC(CC); \\\n SWIFT_RUNTIME_EXPORT extern \"C\" RuntimeEntry SymbolName = \\\n reinterpret_cast(Name);\n\n#define FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs) \\\n DEFINE_SYMBOL(SWIFT_RT_ENTRY_REF(Name), Name, CC)\n\n#if defined(SWIFT_RT_USE_WRAPPERS)\n\/\/ Automatically generate a global symbol name if it is required by the calling\n\/\/ convention.\n#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs) \\\n FOR_CONV_##CC(FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs))\n#else\n\/\/ No need to generate any global symbols for entries that do not provide their\n\/\/ own symbols.\n#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs)\n#endif\n\/\/ Allow for a custom global symbol name and implementation.\n#define FUNCTION_WITH_GLOBAL_SYMBOL_AND_IMPL(Id, Name, GlobalSymbolName, Impl, \\\n CC, ReturnTys, ArgTys, Attrs) \\\n DEFINE_SYMBOL(GlobalSymbolName, Impl, CC)\n\n\/\/ Indicate that we are going to generate the global symbols for those runtime\n\/\/ functions that require it.\n#define SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS 1\n\nnamespace swift {\n\/\/ Generate global symbols which are function pointers to the actual\n\/\/ implementations of runtime entry points.\n\/\/ This is done only for entry points using a new calling convention or\n\/\/ for those entry points which explicitly require it.\n#include \"swift\/Runtime\/RuntimeFunctions.def\"\n}\n\nSet proper linkage on external declarations of runtime functions implementations.\/\/===--- RuntimeEntrySymbols.cpp - Define symbols for runtime entries --===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file defines function pointer symbols for runtime entries.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n\/\/ Produce global symbols referencing runtime function implementations only for\n\/\/ those runtime entries that demand it.\n\/\/\n\/\/ Each runtime function definition in RuntimeFunctions.def should\n\/\/ indicate if it requires a global referencing it.\n\/\/\n\/\/ For example, all entries using the RegisterPreservingCC calling convention\n\/\/ need a global, because they are currently always invoked indirectly using a\n\/\/ client-side wrapper.\n\/\/\n\/\/ Runtime entries using the DefaultCC calling convention do not\n\/\/ demand a global symbol by default. But they can optionally ask for it, in\n\/\/ case it is needed. For example, _swift_isDeallocating is required by\n\/\/ Instruments.\n\n#include \"swift\/Runtime\/Config.h\"\n\n\/\/ Entry points using a standard C calling convention or not using the new\n\/\/ calling convention do not need to have global symbols referring to their\n\/\/ implementations.\n#define FOR_CONV_DefaultCC(...)\n#define FOR_CONV_C_CC(...)\n\/\/ Entry points using the new calling convention require global symbols\n\/\/ referring to their implementations.\n#define FOR_CONV_RegisterPreservingCC(x) x\n\ntypedef void (*RuntimeEntry)();\n\n\/\/ Generate a forward declaration of the runtime entry implementation.\n\/\/ Define a global symbol referring to this implementation.\n\n#define DEFINE_SYMBOL(SymbolName, Name, CC) \\\n SWIFT_RT_ENTRY_IMPL_VISIBILITY extern \"C\" void Name() \\\n SWIFT_CC(CC); \\\n SWIFT_RUNTIME_EXPORT extern \"C\" RuntimeEntry SymbolName = \\\n reinterpret_cast(Name);\n\n#define FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs) \\\n DEFINE_SYMBOL(SWIFT_RT_ENTRY_REF(Name), Name, CC)\n\n#if defined(SWIFT_RT_USE_WRAPPERS)\n\/\/ Automatically generate a global symbol name if it is required by the calling\n\/\/ convention.\n#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs) \\\n FOR_CONV_##CC(FUNCTION1(Id, Name, CC, ReturnTys, ArgTys, Attrs))\n#else\n\/\/ No need to generate any global symbols for entries that do not provide their\n\/\/ own symbols.\n#define FUNCTION(Id, Name, CC, ReturnTys, ArgTys, Attrs)\n#endif\n\/\/ Allow for a custom global symbol name and implementation.\n#define FUNCTION_WITH_GLOBAL_SYMBOL_AND_IMPL(Id, Name, GlobalSymbolName, Impl, \\\n CC, ReturnTys, ArgTys, Attrs) \\\n DEFINE_SYMBOL(GlobalSymbolName, Impl, CC)\n\n\/\/ Indicate that we are going to generate the global symbols for those runtime\n\/\/ functions that require it.\n#define SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS 1\n\nnamespace swift {\n\/\/ Generate global symbols which are function pointers to the actual\n\/\/ implementations of runtime entry points.\n\/\/ This is done only for entry points using a new calling convention or\n\/\/ for those entry points which explicitly require it.\n#include \"swift\/Runtime\/RuntimeFunctions.def\"\n}\n\n<|endoftext|>"} {"text":"#include \"selectsignaldialog.h\"\n#include \"ui_selectsignaldialog.h\"\n\n#include \"signaldescription.h\"\n#include \"signalhandler.h\"\n#include \"jointnames.h\"\n\n#include \n#include \n\nclass SelectSignalDialog::Internal : public Ui::SelectSignalDialog\n{\npublic:\n\n QList ArrayKeyWidgets;\n\n};\n\nSelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent)\n{\n mInternal = new Internal;\n mInternal->setupUi(this);\n\n QStringList channels;\n channels << \"ATLAS_COMMAND\" << \"ATLAS_FOOT_POS_EST\"\n << \"ATLAS_IMU_PACKET\" << \"ATLAS_IMU_PACKET_FILTERED\"\n << \"ATLAS_STATE\" << \"ATLAS_STATE_FILTERED\" << \"ATLAS_STATE_FILTERED_ALT\" \n << \"ATLAS_STATE_EXTRA\"\n << \"ATLAS_STATUS\" << \"EST_ROBOT_STATE\" \n << \"EST_ROBOT_STATE_KF\" << \"EST_ROBOT_STATE_LP\" << \"EST_ROBOT_STATE_ECHO\" \n << \"FOOT_CONTACT_ESTIMATE\" << \"FOOT_CONTACT_CLASSIFY\" \n << \"FORCE_PLATE_DATA\" \n << \"INS_ERR_UPDATE\" << \"MICROSTRAIN_INS\"\n << \"POSE_BDI\"\n << \"POSE_BODY\" << \"POSE_BODY_ALT\"\n << \"POSE_BODY_FOVIS_VELOCITY\" \n << \"POSE_BODY_LEGODO_VELOCITY\" << \"POSE_BODY_LEGODO_VELOCITY_FAIL\" \n << \"POSE_VICON\"\n << \"SCALED_ROBOT_STATE\" \n << \"SE_INS_POSE_STATE\" << \"SE_MATLAB_DATAFUSION_REQ\"\n << \"STATE_ESTIMATOR_POSE\"\n << \"STATE_ESTIMATOR_STATE\"\n << \"TRUE_ROBOT_STATE\"\n << \"VICON_ATLAS\" << \"CONTROLLER_DEBUG\"\n << \"ROBOTIQ_LEFT_STATUS\" << \"ROBOTIQ_RIGHT_STATUS\" ;\n\n\n QStringList messageTypes = SignalHandlerFactory::instance().messageTypes();\n QStringList messageFields;\n\n mInternal->ChannelListBox->addItems(channels);\n mInternal->MessageTypeListBox->addItems(messageTypes);\n mInternal->MessageFieldListBox->addItems(messageFields);\n\n mInternal->ChannelListBox->setCurrentRow(0);\n mInternal->MessageTypeListBox->setCurrentRow(0);\n mInternal->MessageFieldListBox->setCurrentRow(0);\n\n this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged()));\n this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged()));\n this->onMessageTypeChanged();\n}\n\nvoid SelectSignalDialog::onMessageTypeChanged()\n{\n if (!mInternal->MessageTypeListBox->currentItem())\n {\n return;\n }\n\n QString messageType = mInternal->MessageTypeListBox->currentItem()->text();\n\n QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType);\n fieldNames.sort();\n\n mInternal->MessageFieldListBox->clear();\n mInternal->MessageFieldListBox->addItems(fieldNames);\n mInternal->MessageFieldListBox->setCurrentRow(0);\n this->onFieldNameChanged();\n}\n\n\nvoid SelectSignalDialog::onFieldNameChanged()\n{\n if (!mInternal->MessageFieldListBox->currentItem())\n {\n return;\n }\n\n QString messageType = mInternal->MessageTypeListBox->currentItem()->text();\n QString fieldName = mInternal->MessageFieldListBox->currentItem()->text();\n\n foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)\n {\n delete listWidget;\n }\n mInternal->ArrayKeyWidgets.clear();\n\n const QList >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName);\n\n bool useArrayKeys = !validArrayKeys.empty();\n mInternal->ArrayKeysLabel->setVisible(useArrayKeys);\n mInternal->ArrayKeysContainer->setVisible(useArrayKeys);\n\n foreach (const QList & keys, validArrayKeys)\n {\n assert(keys.size());\n QListWidget* listWidget = new QListWidget;\n listWidget->addItems(keys);\n listWidget->setCurrentRow(0);\n mInternal->ArrayKeyWidgets.append(listWidget);\n mInternal->ArrayKeysContainer->layout()->addWidget(listWidget);\n }\n\n if (mInternal->ArrayKeyWidgets.size())\n {\n mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection);\n }\n\n}\n\n\nSelectSignalDialog::~SelectSignalDialog()\n{\n delete mInternal;\n}\n\nQList SelectSignalDialog::createSignalHandlers() const\n{\n QString channel = mInternal->ChannelListBox->currentItem()->text();\n QString messageType = mInternal->MessageTypeListBox->currentItem()->text();\n QString messageField = mInternal->MessageFieldListBox->currentItem()->text();\n\n\n SignalDescription desc;\n desc.mChannel = channel;\n desc.mMessageType = messageType;\n desc.mFieldName = messageField;\n\n QList descriptions;\n\n if (mInternal->ArrayKeyWidgets.length())\n {\n foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)\n {\n if (listWidget == mInternal->ArrayKeyWidgets.back())\n {\n foreach (QListWidgetItem*\tselectedItem, listWidget->selectedItems())\n {\n QString arrayKey = selectedItem->text();\n SignalDescription descCopy(desc);\n descCopy.mArrayKeys.append(arrayKey);\n descriptions.append(descCopy);\n }\n }\n else\n {\n QString arrayKey = listWidget->currentItem()->text();\n desc.mArrayKeys.append(arrayKey);\n }\n }\n }\n else\n {\n descriptions.append(desc);\n }\n\n QList signalHandlers;\n foreach (const SignalDescription& description, descriptions)\n {\n SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description);\n assert(signalHandler);\n signalHandlers.append(signalHandler);\n }\n\n return signalHandlers;\n}\n\nadding signal#include \"selectsignaldialog.h\"\n#include \"ui_selectsignaldialog.h\"\n\n#include \"signaldescription.h\"\n#include \"signalhandler.h\"\n#include \"jointnames.h\"\n\n#include \n#include \n\nclass SelectSignalDialog::Internal : public Ui::SelectSignalDialog\n{\npublic:\n\n QList ArrayKeyWidgets;\n\n};\n\nSelectSignalDialog::SelectSignalDialog(QWidget* parent) : QDialog(parent)\n{\n mInternal = new Internal;\n mInternal->setupUi(this);\n\n QStringList channels;\n channels << \"ATLAS_COMMAND\" << \"ATLAS_FOOT_POS_EST\"\n << \"ATLAS_IMU_PACKET\" << \"ATLAS_IMU_PACKET_FILTERED\"\n << \"ATLAS_STATE\" << \"ATLAS_STATE_FILTERED\" << \"ATLAS_STATE_FILTERED_ALT\" \n << \"ATLAS_STATE_EXTRA\"\n << \"ATLAS_STATUS\" << \"EST_ROBOT_STATE\" \n << \"EST_ROBOT_STATE_KF\" << \"EST_ROBOT_STATE_LP\" << \"EST_ROBOT_STATE_ECHO\" \n << \"EXPD_ROBOT_STATE\"\n << \"FOOT_CONTACT_ESTIMATE\" << \"FOOT_CONTACT_CLASSIFY\" \n << \"FORCE_PLATE_DATA\" \n << \"INS_ERR_UPDATE\" << \"MICROSTRAIN_INS\"\n << \"POSE_BDI\"\n << \"POSE_BODY\" << \"POSE_BODY_ALT\"\n << \"POSE_BODY_FOVIS_VELOCITY\" \n << \"POSE_BODY_LEGODO_VELOCITY\" << \"POSE_BODY_LEGODO_VELOCITY_FAIL\" \n << \"POSE_VICON\"\n << \"SCALED_ROBOT_STATE\" \n << \"SE_INS_POSE_STATE\" << \"SE_MATLAB_DATAFUSION_REQ\"\n << \"STATE_ESTIMATOR_POSE\"\n << \"STATE_ESTIMATOR_STATE\"\n << \"TRUE_ROBOT_STATE\"\n << \"VICON_ATLAS\" << \"CONTROLLER_DEBUG\"\n << \"ROBOTIQ_LEFT_STATUS\" << \"ROBOTIQ_RIGHT_STATUS\" ;\n\n\n QStringList messageTypes = SignalHandlerFactory::instance().messageTypes();\n QStringList messageFields;\n\n mInternal->ChannelListBox->addItems(channels);\n mInternal->MessageTypeListBox->addItems(messageTypes);\n mInternal->MessageFieldListBox->addItems(messageFields);\n\n mInternal->ChannelListBox->setCurrentRow(0);\n mInternal->MessageTypeListBox->setCurrentRow(0);\n mInternal->MessageFieldListBox->setCurrentRow(0);\n\n this->connect(mInternal->MessageTypeListBox, SIGNAL(currentRowChanged(int)), SLOT(onMessageTypeChanged()));\n this->connect(mInternal->MessageFieldListBox, SIGNAL(currentRowChanged(int)), SLOT(onFieldNameChanged()));\n this->onMessageTypeChanged();\n}\n\nvoid SelectSignalDialog::onMessageTypeChanged()\n{\n if (!mInternal->MessageTypeListBox->currentItem())\n {\n return;\n }\n\n QString messageType = mInternal->MessageTypeListBox->currentItem()->text();\n\n QStringList fieldNames = SignalHandlerFactory::instance().fieldNames(messageType);\n fieldNames.sort();\n\n mInternal->MessageFieldListBox->clear();\n mInternal->MessageFieldListBox->addItems(fieldNames);\n mInternal->MessageFieldListBox->setCurrentRow(0);\n this->onFieldNameChanged();\n}\n\n\nvoid SelectSignalDialog::onFieldNameChanged()\n{\n if (!mInternal->MessageFieldListBox->currentItem())\n {\n return;\n }\n\n QString messageType = mInternal->MessageTypeListBox->currentItem()->text();\n QString fieldName = mInternal->MessageFieldListBox->currentItem()->text();\n\n foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)\n {\n delete listWidget;\n }\n mInternal->ArrayKeyWidgets.clear();\n\n const QList >& validArrayKeys = SignalHandlerFactory::instance().validArrayKeys(messageType, fieldName);\n\n bool useArrayKeys = !validArrayKeys.empty();\n mInternal->ArrayKeysLabel->setVisible(useArrayKeys);\n mInternal->ArrayKeysContainer->setVisible(useArrayKeys);\n\n foreach (const QList & keys, validArrayKeys)\n {\n assert(keys.size());\n QListWidget* listWidget = new QListWidget;\n listWidget->addItems(keys);\n listWidget->setCurrentRow(0);\n mInternal->ArrayKeyWidgets.append(listWidget);\n mInternal->ArrayKeysContainer->layout()->addWidget(listWidget);\n }\n\n if (mInternal->ArrayKeyWidgets.size())\n {\n mInternal->ArrayKeyWidgets.back()->setSelectionMode(QAbstractItemView::ExtendedSelection);\n }\n\n}\n\n\nSelectSignalDialog::~SelectSignalDialog()\n{\n delete mInternal;\n}\n\nQList SelectSignalDialog::createSignalHandlers() const\n{\n QString channel = mInternal->ChannelListBox->currentItem()->text();\n QString messageType = mInternal->MessageTypeListBox->currentItem()->text();\n QString messageField = mInternal->MessageFieldListBox->currentItem()->text();\n\n\n SignalDescription desc;\n desc.mChannel = channel;\n desc.mMessageType = messageType;\n desc.mFieldName = messageField;\n\n QList descriptions;\n\n if (mInternal->ArrayKeyWidgets.length())\n {\n foreach (QListWidget* listWidget, mInternal->ArrayKeyWidgets)\n {\n if (listWidget == mInternal->ArrayKeyWidgets.back())\n {\n foreach (QListWidgetItem*\tselectedItem, listWidget->selectedItems())\n {\n QString arrayKey = selectedItem->text();\n SignalDescription descCopy(desc);\n descCopy.mArrayKeys.append(arrayKey);\n descriptions.append(descCopy);\n }\n }\n else\n {\n QString arrayKey = listWidget->currentItem()->text();\n desc.mArrayKeys.append(arrayKey);\n }\n }\n }\n else\n {\n descriptions.append(desc);\n }\n\n QList signalHandlers;\n foreach (const SignalDescription& description, descriptions)\n {\n SignalHandler* signalHandler = SignalHandlerFactory::instance().createHandler(&description);\n assert(signalHandler);\n signalHandlers.append(signalHandler);\n }\n\n return signalHandlers;\n}\n\n<|endoftext|>"} {"text":"#include \"loader.h\"\n\n#include\n\n\n\nBVS::ModuleMap BVS::Loader::modules;\n\n\n\nBVS::ModuleVector BVS::Loader::masterModules;\n\n\n\nBVS::Loader::Loader(Control& control, Config& config)\n\t: control(control)\n\t, logger(\"Loader\")\n\t, config(config)\n{\n\n}\n\n\n\nvoid BVS::Loader::registerModule(const std::string& id, Module* module)\n{\n\tmodules[id] = std::shared_ptr(new ModuleData{ \\\n\t\t\tid, \\\n\t\t\tstd::string(), \\\n\t\t\tstd::string(), \\\n\t\t\tmodule, \\\n\t\t\tnullptr, \\\n\t\t\tstd::thread(), \\\n\t\t\tfalse, \\\n\t\t\tModuleFlag::WAIT, \\\n\t\t\tStatus::NONE, \\\n\t\t\tConnectorMap()});\n}\n\n\n\nBVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread)\n{\n\t\/* algorithm:\n\t * SEPARATE id(library).options\n\t * CHECK for duplicate ids\n\t * LOAD the library and CHECK errors\n\t * LINK and execute register function, CHECK errors\n\t * SAVE metadata\n\t * MOVE connectors to metadata\n\t * START (un\/)threaded module\n\t *\/\n\tstd::string id;\n\tstd::string library;\n\tstd::string options;\n\n\t\/\/ search for '.' in id and separate id and options\n\tsize_t separator = moduleTraits.find_first_of('.');\n\tif (separator!=std::string::npos)\n\t{\n\t\tid = moduleTraits.substr(0, separator);\n\t\toptions = moduleTraits.substr(separator+1, std::string::npos);\n\t}\n\telse\n\t\tid = moduleTraits;\n\n\t\/\/ search for '(' in id and separate if necessary\n\tseparator = id.find_first_of('(');\n\tif (separator!=std::string::npos)\n\t{\n\t\tlibrary = id.substr(separator+1, std::string::npos);\n\t\tlibrary.erase(library.length()-1);\n\t\tid = id.erase(separator, std::string::npos);\n\t}\n\telse\n\t\tlibrary = id;\n\n\t\/\/ search for duplicate id in modules\n\tif (modules.find(id)!=modules.end())\n\t{\n\t\tLOG(0, \"Duplicate id: \" << id);\n\t\tLOG(0, \"If you try to load a module more than once, use unique ids and the id(library).options syntax!\");\n\t\texit(-1);\n\t}\n\n\t\/\/ prepare path and load the lib\n\tstd::string modulePath = \".\/lib\" + library + \".so\";\n\tLOG(3, id << \" will be loaded from \" << modulePath);\n\tvoid* dlib = dlopen(modulePath.c_str(), RTLD_NOW);\n\n\t\/\/ check for errors\n\tif (dlib == NULL)\n\t{\n\t\tLOG(0, \"While loading \" << modulePath << \", following error occured: \" << dlerror());\n\t\texit(-1);\n\t}\n\n\t\/\/ look for bvsRegisterModule in loaded lib, check for errors and execute register function\n\ttypedef void (*bvsRegisterModule_t)(const std::string& id, const Config& config);\n\tbvsRegisterModule_t bvsRegisterModule;\n\t*reinterpret_cast(&bvsRegisterModule)=dlsym(dlib, \"bvsRegisterModule\");\n\n\t\/\/ check for errors\n\tchar* dlerr = dlerror();\n\tif (dlerr)\n\t{\n\t\tLOG(0, \"Loading function bvsRegisterModule() in \" << modulePath << \" resulted in: \" << dlerr);\n\t\texit(-1);\n\t}\n\n\t\/\/ register\n\tbvsRegisterModule(id, config);\n\tLOG(2, id << \" loaded and registered!\");\n\n\t\/\/ save handle,library name and option string for later use\n\tmodules[id]->dlib = dlib;\n\tmodules[id]->library = library;\n\tmodules[id]->options = options;\n\n\t\/\/ move connectors from temporary to metadata\n\tmodules[id]->connectors = std::move(ConnectorDataCollector::connectors);\n\n\t\/\/ set metadata and start as thread if needed\n\tif (asThread==true)\n\t{\n\t\tLOG(3, id << \" will be started in own thread!\");\n\t\tmodules[id]->asThread = true;\n\t\tmodules[id]->thread = std::thread(&Control::threadController, &control, modules[id]);\n\t\tControl::threadedModules++;\n\t}\n\telse\n\t{\n\t\tLOG(3, id << \" will be executed by Control!\");\n\t\tmodules[id]->asThread = false;\n\t\tmasterModules.push_back(modules[id]);\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::Loader& BVS::Loader::unload(const std::string& id, const bool eraseFromMap)\n{\n\t\/* algorithm:\n\t * CHECK thread, signal exit\n\t * DISCONNECT connectors\n\t * DELETE module instance and connectors\n\t * CHECK library handle\n\t * CLOSE library\n\t * CHECK errors\n\t *\/\n\t\/\/ wait for thread to join, first check if it is still running\n\tif (modules[id]->asThread == true)\n\t{\n\t\tif (modules[id]->thread.joinable())\n\t\t{\n\t\t\tmodules[id]->flag = ModuleFlag::QUIT;\n\t\t\tcontrol.threadCond.notify_all();\n\t\t\tLOG(3, \"joining: \" << id);\n\t\t\tmodules[id]->thread.join();\n\t\t}\n\t}\n\n\t\/\/ disconnect connectors\n\tfor (auto& it: modules)\n\t{\n\t\tfor (auto& con: it.second->connectors)\n\t\t{\n\t\t\tif (con.second->type==ConnectorType::INPUT) continue;\n\n\t\t\t\/\/ find and reset all inputs connected to output\n\t\t\tfor (auto& mods: modules)\n\t\t\t{\n\t\t\t\tfor (auto& modCon: mods.second->connectors)\n\t\t\t\t{\n\t\t\t\t\tif (con.second->pointer==modCon.second->pointer)\n\t\t\t\t\t{\n\t\t\t\t\t\tmodCon.second->pointer = nullptr;\n\t\t\t\t\t\tmodCon.second->active = false;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ delete module and connectors\n\tmodules[id]->connectors.clear();\n\tdelete modules[id]->module;\n\tmodules[id]->module = nullptr;\n\n\t\/\/ close lib and check for errors\n\tstd::string modulePath = \".\/lib\" + modules[id]->library + \".so\";\n\tLOG(3, id << \" will be closed using \" << modulePath);\n\n\t\/\/ get handle from internals\n\tvoid* dlib = modules[id]->dlib;\n\tif (dlib==nullptr)\n\t{\n\t\tLOG(0, \"Requested module \" << id << \" not found!\");\n\t\texit(-1);\n\t}\n\n\t\/\/ close the module\n\tdlclose(dlib);\n\n\t\/\/ check for errors\n\tchar* dlerr = dlerror();\n\tif (dlerr)\n\t{\n\t\tLOG(0, \"While closing \" << modulePath << \" following error occured: \" << dlerror());\n\t\texit(-1);\n\t}\n\tLOG(2, id << \" unloaded and deregistered!\");\n\n\tif (eraseFromMap)\n\t{\n\t\tmodules.erase(id);\n\t\tLOG(2, id << \" erased from map!\");\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::Loader& BVS::Loader::unloadAll()\n{\n\tfor (auto& it: modules)\n\t\tunload(it.second->id, false);\n\n\tmodules.clear();\n\n\treturn *this;\n}\n\n\n\nBVS::Loader& BVS::Loader::connectModules(bool connectorTypeMatching)\n{\n\t\/* algorithm:\n\t * FOR EACH module\n\t * DO\n\t *\t\tSEPARATE input and remove parsed part\n\t *\t\tCHECK input exists\n\t *\t\tCHECK input type\n\t *\t\tSEPARATE module and output\n\t *\t\tCHECK module exists and self reference\n\t *\t\tCHECK output exists\n\t *\t\tCHECK output type\n\t *\t\tCHECK input typeid hash == output typeid hash\n\t *\t\tCHECK input already connected\n\t *\t\tCONNECT\n\t * DONE\n\t *\/\n\n\tstd::string options;\n\tstd::string selection;\n\tstd::string input;\n\tstd::string module;\n\tstd::string output;\n\tsize_t separator;\n\tsize_t separator2;\n\n\t\/\/ check options for each module\n\tfor (auto& it: modules)\n\t{\n\t\toptions = it.second->options;\n\n\t\twhile (!options.empty())\n\t\t{\n\t\t\t\/\/ get input name and selection\n\t\t\tseparator = options.find_first_of('(');\n\t\t\tseparator2 = options.find_first_of(')');\n\t\t\tselection = options.substr(0, separator2+1);\n\t\t\tif (separator!=std::string::npos)\n\t\t\t{\n\t\t\t\tmodule= options.substr(separator+1, separator2-separator-1);\n\t\t\t\tinput = options.substr(0, separator);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLOG(0, \"no input selection found: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ remove parsed part\n\t\t\toptions.erase(0, separator2+1);\n\t\t\tif (options[0] == '.') options.erase(options.begin());\n\n\t\t\t\/\/ check if desired input exists\n\t\t\tif (it.second->connectors.find(input) == it.second->connectors.end())\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input does not exist: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check input type\n\t\t\tif (it.second->connectors[input]->type != ConnectorType::INPUT)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input is not of input type: \" << it.second->id << \".\" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ search for '.' in selection and separate module and output\n\t\t\tseparator = module.find_first_of('.');\n\t\t\tif (separator!=std::string::npos)\n\t\t\t{\n\t\t\t\toutput = module.substr(separator+1, std::string::npos);\n\t\t\t\tmodule = module.substr(0, separator);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLOG(0, \"no module output selected: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check if desired module exists\n\t\t\tif (modules.find(module) == modules.end())\n\t\t\t{\n\t\t\t\tLOG(0, \"could not find module: \" << module);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check for sending data to oneself...\n\t\t\tif (module == it.second->id)\n\t\t\t{\n\t\t\t\tLOG(0, \"can not request data from self: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check if desired output exists\n\t\t\tif (modules[module]->connectors.find(output) == modules[module]->connectors.end())\n\t\t\t{\n\t\t\t\tLOG(0, \"selected output does not exist: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check output type\n\t\t\tif (modules[module]->connectors[output]->type != ConnectorType::OUTPUT)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected output is not of output type: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check input typeid hash == output typeid hash\n\t\t\tif (connectorTypeMatching && it.second->connectors[input]->typeIDHash != modules[module]->connectors[output]->typeIDHash)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input and output connector template instantiations are of different type: \" \\\n\t\t\t\t\t\t<< it.second->id << \".\" << selection << \" -> \" \\\n\t\t\t\t\t\t<< it.second->connectors[input]->typeIDName << \"!=\" << modules[module]->connectors[output]->typeIDName);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check if input is already connected\n\t\t\tif (it.second->connectors[input]->active)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input is alreade connected to another output: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ connect\n\t\t\tit.second->connectors[input]->pointer = modules[module]->connectors[output]->pointer;\n\t\t\tit.second->connectors[input]->active = true;\n\t\t\tit.second->connectors[input]->mutex = modules[module]->connectors[output]->mutex;\n\t\t\tLOG(3, \"connected: \" << it.second->id << \".\" << it.second->connectors[input]->id << \" <- \" << modules[module]->id << \".\" << modules[module]->connectors[output]->id);\n\t\t}\n\t}\n\n\n\n\t\/\/ do maintenance for load\/unload, e.g. remove all connections for unloaded module...\n\treturn *this;\n}\n\nloader: unset mutex when unloading#include \"loader.h\"\n\n#include\n\n\n\nBVS::ModuleMap BVS::Loader::modules;\n\n\n\nBVS::ModuleVector BVS::Loader::masterModules;\n\n\n\nBVS::Loader::Loader(Control& control, Config& config)\n\t: control(control)\n\t, logger(\"Loader\")\n\t, config(config)\n{\n\n}\n\n\n\nvoid BVS::Loader::registerModule(const std::string& id, Module* module)\n{\n\tmodules[id] = std::shared_ptr(new ModuleData{ \\\n\t\t\tid, \\\n\t\t\tstd::string(), \\\n\t\t\tstd::string(), \\\n\t\t\tmodule, \\\n\t\t\tnullptr, \\\n\t\t\tstd::thread(), \\\n\t\t\tfalse, \\\n\t\t\tModuleFlag::WAIT, \\\n\t\t\tStatus::NONE, \\\n\t\t\tConnectorMap()});\n}\n\n\n\nBVS::Loader& BVS::Loader::load(const std::string& moduleTraits, const bool asThread)\n{\n\t\/* algorithm:\n\t * SEPARATE id(library).options\n\t * CHECK for duplicate ids\n\t * LOAD the library and CHECK errors\n\t * LINK and execute register function, CHECK errors\n\t * SAVE metadata\n\t * MOVE connectors to metadata\n\t * START (un\/)threaded module\n\t *\/\n\tstd::string id;\n\tstd::string library;\n\tstd::string options;\n\n\t\/\/ search for '.' in id and separate id and options\n\tsize_t separator = moduleTraits.find_first_of('.');\n\tif (separator!=std::string::npos)\n\t{\n\t\tid = moduleTraits.substr(0, separator);\n\t\toptions = moduleTraits.substr(separator+1, std::string::npos);\n\t}\n\telse\n\t\tid = moduleTraits;\n\n\t\/\/ search for '(' in id and separate if necessary\n\tseparator = id.find_first_of('(');\n\tif (separator!=std::string::npos)\n\t{\n\t\tlibrary = id.substr(separator+1, std::string::npos);\n\t\tlibrary.erase(library.length()-1);\n\t\tid = id.erase(separator, std::string::npos);\n\t}\n\telse\n\t\tlibrary = id;\n\n\t\/\/ search for duplicate id in modules\n\tif (modules.find(id)!=modules.end())\n\t{\n\t\tLOG(0, \"Duplicate id: \" << id);\n\t\tLOG(0, \"If you try to load a module more than once, use unique ids and the id(library).options syntax!\");\n\t\texit(-1);\n\t}\n\n\t\/\/ prepare path and load the lib\n\tstd::string modulePath = \".\/lib\" + library + \".so\";\n\tLOG(3, id << \" will be loaded from \" << modulePath);\n\tvoid* dlib = dlopen(modulePath.c_str(), RTLD_NOW);\n\n\t\/\/ check for errors\n\tif (dlib == NULL)\n\t{\n\t\tLOG(0, \"While loading \" << modulePath << \", following error occured: \" << dlerror());\n\t\texit(-1);\n\t}\n\n\t\/\/ look for bvsRegisterModule in loaded lib, check for errors and execute register function\n\ttypedef void (*bvsRegisterModule_t)(const std::string& id, const Config& config);\n\tbvsRegisterModule_t bvsRegisterModule;\n\t*reinterpret_cast(&bvsRegisterModule)=dlsym(dlib, \"bvsRegisterModule\");\n\n\t\/\/ check for errors\n\tchar* dlerr = dlerror();\n\tif (dlerr)\n\t{\n\t\tLOG(0, \"Loading function bvsRegisterModule() in \" << modulePath << \" resulted in: \" << dlerr);\n\t\texit(-1);\n\t}\n\n\t\/\/ register\n\tbvsRegisterModule(id, config);\n\tLOG(2, id << \" loaded and registered!\");\n\n\t\/\/ save handle,library name and option string for later use\n\tmodules[id]->dlib = dlib;\n\tmodules[id]->library = library;\n\tmodules[id]->options = options;\n\n\t\/\/ move connectors from temporary to metadata\n\tmodules[id]->connectors = std::move(ConnectorDataCollector::connectors);\n\n\t\/\/ set metadata and start as thread if needed\n\tif (asThread==true)\n\t{\n\t\tLOG(3, id << \" will be started in own thread!\");\n\t\tmodules[id]->asThread = true;\n\t\tmodules[id]->thread = std::thread(&Control::threadController, &control, modules[id]);\n\t\tControl::threadedModules++;\n\t}\n\telse\n\t{\n\t\tLOG(3, id << \" will be executed by Control!\");\n\t\tmodules[id]->asThread = false;\n\t\tmasterModules.push_back(modules[id]);\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::Loader& BVS::Loader::unload(const std::string& id, const bool eraseFromMap)\n{\n\t\/* algorithm:\n\t * CHECK thread, signal exit\n\t * DISCONNECT connectors\n\t * DELETE module instance and connectors\n\t * CHECK library handle\n\t * CLOSE library\n\t * CHECK errors\n\t *\/\n\t\/\/ wait for thread to join, first check if it is still running\n\tif (modules[id]->asThread == true)\n\t{\n\t\tif (modules[id]->thread.joinable())\n\t\t{\n\t\t\tmodules[id]->flag = ModuleFlag::QUIT;\n\t\t\tcontrol.threadCond.notify_all();\n\t\t\tLOG(3, \"joining: \" << id);\n\t\t\tmodules[id]->thread.join();\n\t\t}\n\t}\n\n\t\/\/ disconnect connectors\n\tfor (auto& it: modules)\n\t{\n\t\tfor (auto& con: it.second->connectors)\n\t\t{\n\t\t\tif (con.second->type==ConnectorType::INPUT) continue;\n\n\t\t\t\/\/ find and reset all inputs connected to output\n\t\t\tfor (auto& mods: modules)\n\t\t\t{\n\t\t\t\tfor (auto& modCon: mods.second->connectors)\n\t\t\t\t{\n\t\t\t\t\tif (con.second->pointer==modCon.second->pointer)\n\t\t\t\t\t{\n\t\t\t\t\t\tmodCon.second->pointer = nullptr;\n\t\t\t\t\t\tmodCon.second->active = false;\n\t\t\t\t\t\tmodCon.second->mutex = nullptr;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ delete module and connectors\n\tmodules[id]->connectors.clear();\n\tdelete modules[id]->module;\n\tmodules[id]->module = nullptr;\n\n\t\/\/ close lib and check for errors\n\tstd::string modulePath = \".\/lib\" + modules[id]->library + \".so\";\n\tLOG(3, id << \" will be closed using \" << modulePath);\n\n\t\/\/ get handle from internals\n\tvoid* dlib = modules[id]->dlib;\n\tif (dlib==nullptr)\n\t{\n\t\tLOG(0, \"Requested module \" << id << \" not found!\");\n\t\texit(-1);\n\t}\n\n\t\/\/ close the module\n\tdlclose(dlib);\n\n\t\/\/ check for errors\n\tchar* dlerr = dlerror();\n\tif (dlerr)\n\t{\n\t\tLOG(0, \"While closing \" << modulePath << \" following error occured: \" << dlerror());\n\t\texit(-1);\n\t}\n\tLOG(2, id << \" unloaded and deregistered!\");\n\n\tif (eraseFromMap)\n\t{\n\t\tmodules.erase(id);\n\t\tLOG(2, id << \" erased from map!\");\n\t}\n\n\treturn *this;\n}\n\n\n\nBVS::Loader& BVS::Loader::unloadAll()\n{\n\tfor (auto& it: modules)\n\t\tunload(it.second->id, false);\n\n\tmodules.clear();\n\n\treturn *this;\n}\n\n\n\nBVS::Loader& BVS::Loader::connectModules(bool connectorTypeMatching)\n{\n\t\/* algorithm:\n\t * FOR EACH module\n\t * DO\n\t *\t\tSEPARATE input and remove parsed part\n\t *\t\tCHECK input exists\n\t *\t\tCHECK input type\n\t *\t\tSEPARATE module and output\n\t *\t\tCHECK module exists and self reference\n\t *\t\tCHECK output exists\n\t *\t\tCHECK output type\n\t *\t\tCHECK input typeid hash == output typeid hash\n\t *\t\tCHECK input already connected\n\t *\t\tCONNECT\n\t * DONE\n\t *\/\n\n\tstd::string options;\n\tstd::string selection;\n\tstd::string input;\n\tstd::string module;\n\tstd::string output;\n\tsize_t separator;\n\tsize_t separator2;\n\n\t\/\/ check options for each module\n\tfor (auto& it: modules)\n\t{\n\t\toptions = it.second->options;\n\n\t\twhile (!options.empty())\n\t\t{\n\t\t\t\/\/ get input name and selection\n\t\t\tseparator = options.find_first_of('(');\n\t\t\tseparator2 = options.find_first_of(')');\n\t\t\tselection = options.substr(0, separator2+1);\n\t\t\tif (separator!=std::string::npos)\n\t\t\t{\n\t\t\t\tmodule= options.substr(separator+1, separator2-separator-1);\n\t\t\t\tinput = options.substr(0, separator);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLOG(0, \"no input selection found: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ remove parsed part\n\t\t\toptions.erase(0, separator2+1);\n\t\t\tif (options[0] == '.') options.erase(options.begin());\n\n\t\t\t\/\/ check if desired input exists\n\t\t\tif (it.second->connectors.find(input) == it.second->connectors.end())\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input does not exist: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check input type\n\t\t\tif (it.second->connectors[input]->type != ConnectorType::INPUT)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input is not of input type: \" << it.second->id << \".\" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ search for '.' in selection and separate module and output\n\t\t\tseparator = module.find_first_of('.');\n\t\t\tif (separator!=std::string::npos)\n\t\t\t{\n\t\t\t\toutput = module.substr(separator+1, std::string::npos);\n\t\t\t\tmodule = module.substr(0, separator);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tLOG(0, \"no module output selected: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check if desired module exists\n\t\t\tif (modules.find(module) == modules.end())\n\t\t\t{\n\t\t\t\tLOG(0, \"could not find module: \" << module);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check for sending data to oneself...\n\t\t\tif (module == it.second->id)\n\t\t\t{\n\t\t\t\tLOG(0, \"can not request data from self: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check if desired output exists\n\t\t\tif (modules[module]->connectors.find(output) == modules[module]->connectors.end())\n\t\t\t{\n\t\t\t\tLOG(0, \"selected output does not exist: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check output type\n\t\t\tif (modules[module]->connectors[output]->type != ConnectorType::OUTPUT)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected output is not of output type: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check input typeid hash == output typeid hash\n\t\t\tif (connectorTypeMatching && it.second->connectors[input]->typeIDHash != modules[module]->connectors[output]->typeIDHash)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input and output connector template instantiations are of different type: \" \\\n\t\t\t\t\t\t<< it.second->id << \".\" << selection << \" -> \" \\\n\t\t\t\t\t\t<< it.second->connectors[input]->typeIDName << \"!=\" << modules[module]->connectors[output]->typeIDName);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ check if input is already connected\n\t\t\tif (it.second->connectors[input]->active)\n\t\t\t{\n\t\t\t\tLOG(0, \"selected input is alreade connected to another output: \" << selection);\n\t\t\t\texit(1);\n\t\t\t}\n\n\t\t\t\/\/ connect\n\t\t\tit.second->connectors[input]->pointer = modules[module]->connectors[output]->pointer;\n\t\t\tit.second->connectors[input]->active = true;\n\t\t\tit.second->connectors[input]->mutex = modules[module]->connectors[output]->mutex;\n\t\t\tLOG(3, \"connected: \" << it.second->id << \".\" << it.second->connectors[input]->id << \" <- \" << modules[module]->id << \".\" << modules[module]->connectors[output]->id);\n\t\t}\n\t}\n\n\n\n\t\/\/ do maintenance for load\/unload, e.g. remove all connections for unloaded module...\n\treturn *this;\n}\n\n<|endoftext|>"} {"text":"AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *AddTaskStrangenessVsMultiplicityMCRun2( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, Bool_t lSaveCascade = kTRUE, TString lExtraOptions = \"\", const TString lMasterJobSessionFlag = \"\", TString lExtraOutputName = \"\")\n{\n \/\/ Creates, configures and attaches to the train a cascades check task.\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskStrangenessVsMultiplicity\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskStrangenessVsMultiplicity\", \"This task requires an input event handler\");\n return NULL;\n }\n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n \n \/\/ Create and configure the task\n AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *taskAuxiliary = new AliAnalysisTaskStrangenessVsMultiplicityMCRun2(lSaveEventTree, lSaveV0, lSaveCascade, Form(\"taskAuxiliary%s\",lExtraOutputName.Data()), lExtraOptions);\n mgr->AddTask(taskAuxiliary);\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \n outputFileName += \":PWGLF_StrVsMult\";\n if (mgr->GetMCtruthEventHandler()) outputFileName += \"_MC\";\n outputFileName += lExtraOutputName.Data();\n \n Printf(\"Set OutputFileName : \\n %s\\n\", outputFileName.Data() );\n \n TString lC[9];\n lC[0] = \"cList\";\n lC[1] = \"cListV0\";\n lC[2] = \"cListXiMinus\";\n lC[3] = \"cListXiPlus\";\n lC[4] = \"cListOmegaMinus\";\n lC[5] = \"cListOmegaPlus\";\n lC[6] = \"cTreeEvent\";\n lC[7] = \"cTreeV0\";\n lC[8] = \"cTreeCascade\";\n \n for(Int_t iname=0;iname<9;iname++)\n lC[iname] += lExtraOutputName.Data();\n \n AliAnalysisDataContainer *coutputLists[6];\n for(Int_t ilist=0;ilist<6;ilist++){\n coutputLists[ilist] = mgr->CreateContainer(lC[ilist].Data(),\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n }\n \n AliAnalysisDataContainer *coutputTree = 0x0;\n AliAnalysisDataContainer *coutputTreeV0 = 0x0;\n AliAnalysisDataContainer *coutputTreeCascade = 0x0;\n \n if( lSaveEventTree ){\n AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(Form(\"cTreeEvent%s\",lExtraOutputName.Data()),\n TTree::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n coutputTree->SetSpecialOutput();\n }\n if( lSaveV0 ){\n AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer(Form(\"cTreeV0%s\",lExtraOutputName.Data()),\n TTree::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n coutputTreeV0->SetSpecialOutput();\n }\n if (lSaveCascade){\n AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer(Form(\"cTreeCascade%s\",lExtraOutputName.Data()),\n TTree::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n coutputTreeCascade->SetSpecialOutput();\n }\n \/\/This one you should merge in file-resident ways...\n \n \/\/Recommendation: Tree as a single output slot\n mgr->ConnectInput (taskAuxiliary, 0, mgr->GetCommonInputContainer());\n for(Int_t ilist=0;ilist<6;ilist++){\n mgr->ConnectOutput(taskAuxiliary, ilist+1, coutputLists[ilist]);\n \n if ( lSaveEventTree ) mgr->ConnectOutput(taskAuxiliary, 4, coutputTree);\n if ( lSaveV0 ) mgr->ConnectOutput(taskAuxiliary, 5, coutputTreeV0);\n if ( lSaveCascade ) mgr->ConnectOutput(taskAuxiliary, 6, coutputTreeCascade);\n \n return taskAuxiliary;\n} \nFix indicesAliAnalysisTaskStrangenessVsMultiplicityMCRun2 *AddTaskStrangenessVsMultiplicityMCRun2( Bool_t lSaveEventTree = kTRUE, Bool_t lSaveV0 = kTRUE, Bool_t lSaveCascade = kTRUE, TString lExtraOptions = \"\", const TString lMasterJobSessionFlag = \"\", TString lExtraOutputName = \"\")\n{\n \/\/ Creates, configures and attaches to the train a cascades check task.\n \/\/ Get the pointer to the existing analysis manager via the static access method.\n \/\/==============================================================================\n AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();\n if (!mgr) {\n ::Error(\"AddTaskStrangenessVsMultiplicity\", \"No analysis manager to connect to.\");\n return NULL;\n }\n \n \/\/ Check the analysis type using the event handlers connected to the analysis manager.\n \/\/==============================================================================\n if (!mgr->GetInputEventHandler()) {\n ::Error(\"AddTaskStrangenessVsMultiplicity\", \"This task requires an input event handler\");\n return NULL;\n }\n TString type = mgr->GetInputEventHandler()->GetDataType(); \/\/ can be \"ESD\" or \"AOD\"\n \n \/\/ Create and configure the task\n AliAnalysisTaskStrangenessVsMultiplicityMCRun2 *taskAuxiliary = new AliAnalysisTaskStrangenessVsMultiplicityMCRun2(lSaveEventTree, lSaveV0, lSaveCascade, Form(\"taskAuxiliary%s\",lExtraOutputName.Data()), lExtraOptions);\n mgr->AddTask(taskAuxiliary);\n TString outputFileName = AliAnalysisManager::GetCommonFileName();\n \n outputFileName += \":PWGLF_StrVsMult\";\n if (mgr->GetMCtruthEventHandler()) outputFileName += \"_MC\";\n outputFileName += lExtraOutputName.Data();\n \n Printf(\"Set OutputFileName : \\n %s\\n\", outputFileName.Data() );\n \n TString lC[9];\n lC[0] = \"cList\";\n lC[1] = \"cListV0\";\n lC[2] = \"cListXiMinus\";\n lC[3] = \"cListXiPlus\";\n lC[4] = \"cListOmegaMinus\";\n lC[5] = \"cListOmegaPlus\";\n lC[6] = \"cTreeEvent\";\n lC[7] = \"cTreeV0\";\n lC[8] = \"cTreeCascade\";\n \n for(Int_t iname=0;iname<9;iname++)\n lC[iname] += lExtraOutputName.Data();\n \n AliAnalysisDataContainer *coutputLists[6];\n for(Int_t ilist=0;ilist<6;ilist++){\n coutputLists[ilist] = mgr->CreateContainer(lC[ilist].Data(),\n TList::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n }\n \n AliAnalysisDataContainer *coutputTree = 0x0;\n AliAnalysisDataContainer *coutputTreeV0 = 0x0;\n AliAnalysisDataContainer *coutputTreeCascade = 0x0;\n \n if( lSaveEventTree ){\n AliAnalysisDataContainer *coutputTree = mgr->CreateContainer(Form(\"cTreeEvent%s\",lExtraOutputName.Data()),\n TTree::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n coutputTree->SetSpecialOutput();\n }\n if( lSaveV0 ){\n AliAnalysisDataContainer *coutputTreeV0 = mgr->CreateContainer(Form(\"cTreeV0%s\",lExtraOutputName.Data()),\n TTree::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n coutputTreeV0->SetSpecialOutput();\n }\n if (lSaveCascade){\n AliAnalysisDataContainer *coutputTreeCascade = mgr->CreateContainer(Form(\"cTreeCascade%s\",lExtraOutputName.Data()),\n TTree::Class(),\n AliAnalysisManager::kOutputContainer,\n outputFileName );\n coutputTreeCascade->SetSpecialOutput();\n }\n \/\/This one you should merge in file-resident ways...\n \n \/\/Recommendation: Tree as a single output slot\n mgr->ConnectInput (taskAuxiliary, 0, mgr->GetCommonInputContainer());\n for(Int_t ilist=0;ilist<6;ilist++){\n mgr->ConnectOutput(taskAuxiliary, ilist+1, coutputLists[ilist]);\n \n if ( lSaveEventTree ) mgr->ConnectOutput(taskAuxiliary, 7, coutputTree);\n if ( lSaveV0 ) mgr->ConnectOutput(taskAuxiliary, 8, coutputTreeV0);\n if ( lSaveCascade ) mgr->ConnectOutput(taskAuxiliary, 9, coutputTreeCascade);\n \n return taskAuxiliary;\n} \n<|endoftext|>"} {"text":"\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n\n#include \n\n#include \n\nusing namespace mesos;\n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nvoid run(ExecutorDriver* driver, const TaskInfo& task)\n{\n sleep(100);\n\n TaskStatus status;\n status.mutable_task_id()->MergeFrom(task.task_id());\n status.set_state(TASK_FINISHED);\n\n driver->sendStatusUpdate(status);\n}\n\n\nvoid* start(void* arg)\n{\n std::tr1::function* thunk = (std::tr1::function*) arg;\n (*thunk)();\n delete thunk;\n return NULL;\n}\n\n\nclass LongLivedExecutor : public Executor\n{\npublic:\n virtual ~LongLivedExecutor() {}\n\n virtual void registered(ExecutorDriver* driver,\n const ExecutorInfo& executorInfo,\n const FrameworkInfo& frameworkInfo,\n const SlaveInfo& slaveInfo)\n {\n cout << \"Registered executor on \" << slaveInfo.hostname() << endl;\n }\n\n virtual void reregistered(ExecutorDriver* driver,\n const SlaveInfo& slaveInfo)\n {\n cout << \"Re-registered executor on \" << slaveInfo.hostname() << endl;\n }\n\n virtual void disconnected(ExecutorDriver* driver) {}\n\n virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task)\n {\n cout << \"Starting task \" << task.task_id().value() << endl;\n\n std::tr1::function* thunk =\n new std::tr1::function(std::tr1::bind(&run, driver, task));\n\n pthread_t pthread;\n if (pthread_create(&pthread, NULL, &start, thunk) != 0) {\n TaskStatus status;\n status.mutable_task_id()->MergeFrom(task.task_id());\n status.set_state(TASK_FAILED);\n\n driver->sendStatusUpdate(status);\n } else {\n pthread_detach(pthread);\n\n TaskStatus status;\n status.mutable_task_id()->MergeFrom(task.task_id());\n status.set_state(TASK_RUNNING);\n\n driver->sendStatusUpdate(status);\n }\n }\n\n virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {}\n virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {}\n virtual void shutdown(ExecutorDriver* driver) {}\n virtual void error(ExecutorDriver* driver, const string& message) {}\n};\n\n\nint main(int argc, char** argv)\n{\n LongLivedExecutor executor;\n MesosExecutorDriver driver(&executor);\n return driver.run() == DRIVER_STOPPED ? 0 : 1;\n}\nMade tasks of the \"long-lived-framework\" have varying runtimes (https:\/\/reviews.apache.org\/r\/5267).\/**\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \/\/ For random.\n\n#include \n#include \n\n#include \n\n#include \n\nusing namespace mesos;\n\nusing std::cout;\nusing std::endl;\nusing std::string;\n\n\nvoid run(ExecutorDriver* driver, const TaskInfo& task)\n{\n sleep(random() % 10);\n\n TaskStatus status;\n status.mutable_task_id()->MergeFrom(task.task_id());\n status.set_state(TASK_FINISHED);\n\n driver->sendStatusUpdate(status);\n}\n\n\nvoid* start(void* arg)\n{\n std::tr1::function* thunk = (std::tr1::function*) arg;\n (*thunk)();\n delete thunk;\n return NULL;\n}\n\n\nclass LongLivedExecutor : public Executor\n{\npublic:\n virtual ~LongLivedExecutor() {}\n\n virtual void registered(ExecutorDriver* driver,\n const ExecutorInfo& executorInfo,\n const FrameworkInfo& frameworkInfo,\n const SlaveInfo& slaveInfo)\n {\n cout << \"Registered executor on \" << slaveInfo.hostname() << endl;\n }\n\n virtual void reregistered(ExecutorDriver* driver,\n const SlaveInfo& slaveInfo)\n {\n cout << \"Re-registered executor on \" << slaveInfo.hostname() << endl;\n }\n\n virtual void disconnected(ExecutorDriver* driver) {}\n\n virtual void launchTask(ExecutorDriver* driver, const TaskInfo& task)\n {\n cout << \"Starting task \" << task.task_id().value() << endl;\n\n std::tr1::function* thunk =\n new std::tr1::function(std::tr1::bind(&run, driver, task));\n\n pthread_t pthread;\n if (pthread_create(&pthread, NULL, &start, thunk) != 0) {\n TaskStatus status;\n status.mutable_task_id()->MergeFrom(task.task_id());\n status.set_state(TASK_FAILED);\n\n driver->sendStatusUpdate(status);\n } else {\n pthread_detach(pthread);\n\n TaskStatus status;\n status.mutable_task_id()->MergeFrom(task.task_id());\n status.set_state(TASK_RUNNING);\n\n driver->sendStatusUpdate(status);\n }\n }\n\n virtual void killTask(ExecutorDriver* driver, const TaskID& taskId) {}\n virtual void frameworkMessage(ExecutorDriver* driver, const string& data) {}\n virtual void shutdown(ExecutorDriver* driver) {}\n virtual void error(ExecutorDriver* driver, const string& message) {}\n};\n\n\nint main(int argc, char** argv)\n{\n LongLivedExecutor executor;\n MesosExecutorDriver driver(&executor);\n return driver.run() == DRIVER_STOPPED ? 0 : 1;\n}\n<|endoftext|>"} {"text":"#pragma once\n#ifndef DELEGATE_HPP\n# define DELEGATE_HPP\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\ntemplate class delegate;\n\ntemplate\nclass delegate\n{\n template struct is_functora\n : std::false_type { };\n\n template \n struct is_functora::type\n > : std::true_type { };\n\n template struct is_functorb\n : std::false_type { };\n\n template \n struct is_functorb::type\n > : std::true_type { };\n\n template \n struct is_functor\n {\n static constexpr bool const value = is_functora::value\n || is_functorb::value;\n };\n\n typedef R (*stub_ptr_type)(void*, A...);\n\n constexpr delegate(void* const o, stub_ptr_type const m)\n : object_ptr_(o),\n stub_ptr_(m)\n {\n }\n\npublic:\n constexpr delegate() = default;\n\n constexpr delegate(delegate const&) = default;\n\n constexpr delegate(delegate&&) = default;\n\n template \n constexpr delegate(C const* const o)\n : object_ptr_(const_cast(o))\n {\n }\n\n template \n constexpr delegate(C const& o)\n : object_ptr_(const_cast(&o))\n {\n }\n\n delegate(R (* const function_ptr)(A...))\n {\n *this = from(function_ptr);\n }\n\n template \n delegate(C* const object_ptr_, R (C::* const method_ptr)(A...))\n {\n *this = from(object_ptr_, method_ptr);\n }\n\n template \n delegate(C* const object_ptr_, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object_ptr_, method_ptr);\n }\n\n template \n delegate(C& object, R (C::* const method_ptr)(A...))\n {\n *this = from(object, method_ptr);\n }\n\n template \n delegate(C const& object, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object, method_ptr);\n }\n\n template <\n typename T,\n typename = typename std::enable_if<\n !std::is_same::type>::type>::value\n && is_functor::type>::value\n >::type\n >\n delegate(T&& f)\n : store_(operator new(sizeof(T)),\n functor_deleter::type>),\n store_size_(sizeof(T))\n {\n typedef typename std::remove_reference::type functor_type;\n\n object_ptr_ = new (store_.get()) functor_type(std::forward(f));\n\n stub_ptr_ = functor_stub;\n\n deleter_ = destructor_stub;\n }\n\n delegate& operator=(delegate const&) = default;\n\n delegate& operator=(delegate&& rhs) = default;\n\n template \n delegate& operator=(R (C::* const rhs)(A...))\n {\n return *this = from(static_cast(object_ptr_), rhs);\n }\n\n template \n delegate& operator=(R (C::* const rhs)(A...) const)\n {\n return *this = from(static_cast(object_ptr_), rhs);\n }\n\n template <\n typename T,\n typename = typename std::enable_if<\n !std::is_same::type>::type>::value\n && is_functor::type>::value\n >::type\n >\n delegate& operator=(T&& f)\n {\n typedef typename std::remove_reference::type functor_type;\n\n if ((sizeof(T) > store_size_)\n || (decltype(store_.use_count())(1) != store_.use_count()))\n {\n store_.reset(operator new(sizeof(T)),\n functor_deleter);\n\n store_size_ = sizeof(T);\n }\n else\n {\n deleter_(store_.get());\n }\n\n object_ptr_ = new (store_.get()) functor_type(std::forward(f));\n\n stub_ptr_ = functor_stub;\n\n deleter_ = destructor_stub;\n\n return *this;\n }\n\n template \n static constexpr delegate from()\n {\n return { nullptr, function_stub };\n }\n\n template \n static constexpr delegate from(C* const object_ptr_)\n {\n return { object_ptr_, method_stub };\n }\n\n template \n static constexpr delegate from(C const* const object_ptr_)\n {\n return { const_cast(object_ptr_), const_method_stub };\n }\n\n template \n static constexpr delegate from(C& object)\n {\n return { &object, method_stub };\n }\n\n template \n static constexpr delegate from(C const& object)\n {\n return { const_cast(&object), const_method_stub };\n }\n\n template \n static delegate from(T&& f)\n {\n return { std::forward(f) };\n }\n\n static constexpr delegate from(R (* const function_ptr)(A...))\n {\n return { [function_ptr](A const... args){\n return (*function_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C* const object_ptr_,\n R (C::* const method_ptr)(A...))\n {\n return { [object_ptr_, method_ptr](A const... args){\n return (object_ptr_->*method_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C const* const object_ptr_,\n R (C::* const method_ptr)(A...) const)\n {\n return { [object_ptr_, method_ptr](A const... args){\n return (object_ptr_->*method_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C& object,\n R (C::* const method_ptr)(A...))\n {\n return { [&object, method_ptr](A const... args){\n return (object.*method_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C const& object,\n R (C::* const method_ptr)(A...) const)\n {\n return { [&object, method_ptr](A const... args){\n return (object.*method_ptr)(args...); } };\n }\n\n void reset() { stub_ptr_ = nullptr; }\n\n void swap(delegate& other)\n {\n std::swap(object_ptr_, other.object_ptr_);\n std::swap(stub_ptr_, other.stub_ptr_);\n }\n\n constexpr bool operator==(delegate const& rhs) const\n {\n return (stub_ptr_ == rhs.stub_ptr_)\n && (object_ptr_ == rhs.object_ptr_);\n }\n\n constexpr bool operator!=(delegate const& rhs) const\n {\n return !operator==(rhs);\n }\n\n constexpr bool operator<(delegate const& rhs) const\n {\n return (object_ptr_ < rhs.object_ptr_)\n || (stub_ptr_ < rhs.stub_ptr_);\n }\n\n constexpr explicit operator bool() const { return stub_ptr_; }\n\n template \n constexpr R operator()(B&&... args) const\n {\n\/\/ assert(stub_ptr);\n return (*stub_ptr_)(object_ptr_, std::forward(args)...);\n }\n\nprivate:\n friend class ::std::hash;\n\n typedef void (*deleter_type)(void*);\n\n void* object_ptr_{};\n stub_ptr_type stub_ptr_{};\n\n deleter_type deleter_;\n\n std::shared_ptr store_;\n std::size_t store_size_;\n\n template \n static void destructor_stub(void* const p)\n {\n static_cast(p)->~T();\n }\n\n template \n static void functor_deleter(void* const p)\n {\n static_cast(p)->~T();\n\n operator delete(p);\n }\n\n template \n static constexpr R function_stub(void* const,\n A const... args)\n {\n return (*function_ptr)(args...);\n }\n\n template \n static constexpr R method_stub(void* const object_ptr_,\n A const... args)\n {\n return (static_cast(object_ptr_)->*method_ptr)(args...);\n }\n\n template \n static constexpr R const_method_stub(void* const object_ptr_,\n A const... args)\n {\n return (static_cast(object_ptr_)->*method_ptr)(args...);\n }\n\n template \n static constexpr R functor_stub(void* const object_ptr_,\n A const... args)\n {\n return (*static_cast(object_ptr_))(args...);\n }\n};\n\nnamespace std\n{\n template \n struct hash >\n {\n size_t operator()(delegate const& d) const\n {\n auto const seed(hash()(d.object_ptr_) + 0x9e3779b9);\n\n return hash::stub_ptr_type>()(d.stub_ptr_)\n + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n };\n}\n\n#endif \/\/ DELEGATE_HPP\nhash added#pragma once\n#ifndef DELEGATE_HPP\n# define DELEGATE_HPP\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\ntemplate class delegate;\n\ntemplate\nclass delegate\n{\n template struct is_functora\n : std::false_type { };\n\n template \n struct is_functora::type\n > : std::true_type { };\n\n template struct is_functorb\n : std::false_type { };\n\n template \n struct is_functorb::type\n > : std::true_type { };\n\n template \n struct is_functor\n {\n static constexpr bool const value = is_functora::value\n || is_functorb::value;\n };\n\n typedef R (*stub_ptr_type)(void*, A...);\n\n constexpr delegate(void* const o, stub_ptr_type const m)\n : object_ptr_(o),\n stub_ptr_(m)\n {\n }\n\npublic:\n constexpr delegate() = default;\n\n constexpr delegate(delegate const&) = default;\n\n constexpr delegate(delegate&&) = default;\n\n template \n constexpr delegate(C const* const o)\n : object_ptr_(const_cast(o))\n {\n }\n\n template \n constexpr delegate(C const& o)\n : object_ptr_(const_cast(&o))\n {\n }\n\n delegate(R (* const function_ptr)(A...))\n {\n *this = from(function_ptr);\n }\n\n template \n delegate(C* const object_ptr_, R (C::* const method_ptr)(A...))\n {\n *this = from(object_ptr_, method_ptr);\n }\n\n template \n delegate(C* const object_ptr_, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object_ptr_, method_ptr);\n }\n\n template \n delegate(C& object, R (C::* const method_ptr)(A...))\n {\n *this = from(object, method_ptr);\n }\n\n template \n delegate(C const& object, R (C::* const method_ptr)(A...) const)\n {\n *this = from(object, method_ptr);\n }\n\n template <\n typename T,\n typename = typename std::enable_if<\n !std::is_same::type>::type>::value\n && is_functor::type>::value\n >::type\n >\n delegate(T&& f)\n : store_(operator new(sizeof(T)),\n functor_deleter::type>),\n store_size_(sizeof(T))\n {\n typedef typename std::remove_reference::type functor_type;\n\n object_ptr_ = new (store_.get()) functor_type(std::forward(f));\n\n stub_ptr_ = functor_stub;\n\n deleter_ = destructor_stub;\n }\n\n delegate& operator=(delegate const&) = default;\n\n delegate& operator=(delegate&& rhs) = default;\n\n template \n delegate& operator=(R (C::* const rhs)(A...))\n {\n return *this = from(static_cast(object_ptr_), rhs);\n }\n\n template \n delegate& operator=(R (C::* const rhs)(A...) const)\n {\n return *this = from(static_cast(object_ptr_), rhs);\n }\n\n template <\n typename T,\n typename = typename std::enable_if<\n !std::is_same::type>::type>::value\n && is_functor::type>::value\n >::type\n >\n delegate& operator=(T&& f)\n {\n typedef typename std::remove_reference::type functor_type;\n\n if ((sizeof(T) > store_size_)\n || (decltype(store_.use_count())(1) != store_.use_count()))\n {\n store_.reset(operator new(sizeof(T)),\n functor_deleter);\n\n store_size_ = sizeof(T);\n }\n else\n {\n deleter_(store_.get());\n }\n\n object_ptr_ = new (store_.get()) functor_type(std::forward(f));\n\n stub_ptr_ = functor_stub;\n\n deleter_ = destructor_stub;\n\n return *this;\n }\n\n template \n static constexpr delegate from()\n {\n return { nullptr, function_stub };\n }\n\n template \n static constexpr delegate from(C* const object_ptr_)\n {\n return { object_ptr_, method_stub };\n }\n\n template \n static constexpr delegate from(C const* const object_ptr_)\n {\n return { const_cast(object_ptr_), const_method_stub };\n }\n\n template \n static constexpr delegate from(C& object)\n {\n return { &object, method_stub };\n }\n\n template \n static constexpr delegate from(C const& object)\n {\n return { const_cast(&object), const_method_stub };\n }\n\n template \n static delegate from(T&& f)\n {\n return { std::forward(f) };\n }\n\n static constexpr delegate from(R (* const function_ptr)(A...))\n {\n return { [function_ptr](A const... args){\n return (*function_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C* const object_ptr_,\n R (C::* const method_ptr)(A...))\n {\n return { [object_ptr_, method_ptr](A const... args){\n return (object_ptr_->*method_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C const* const object_ptr_,\n R (C::* const method_ptr)(A...) const)\n {\n return { [object_ptr_, method_ptr](A const... args){\n return (object_ptr_->*method_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C& object,\n R (C::* const method_ptr)(A...))\n {\n return { [&object, method_ptr](A const... args){\n return (object.*method_ptr)(args...); } };\n }\n\n template \n static constexpr delegate from(C const& object,\n R (C::* const method_ptr)(A...) const)\n {\n return { [&object, method_ptr](A const... args){\n return (object.*method_ptr)(args...); } };\n }\n\n void reset() { stub_ptr_ = nullptr; }\n\n void swap(delegate& other)\n {\n std::swap(*this, other);\n }\n\n constexpr bool operator==(delegate const& rhs) const\n {\n return (stub_ptr_ == rhs.stub_ptr_)\n && (object_ptr_ == rhs.object_ptr_);\n }\n\n constexpr bool operator!=(delegate const& rhs) const\n {\n return !operator==(rhs);\n }\n\n constexpr bool operator<(delegate const& rhs) const\n {\n return (object_ptr_ < rhs.object_ptr_)\n || (stub_ptr_ < rhs.stub_ptr_);\n }\n\n constexpr explicit operator bool() const { return stub_ptr_; }\n\n template \n constexpr R operator()(B&&... args) const\n {\n\/\/ assert(stub_ptr);\n return (*stub_ptr_)(object_ptr_, std::forward(args)...);\n }\n\nprivate:\n friend class ::std::hash;\n\n typedef void (*deleter_type)(void*);\n\n void* object_ptr_{};\n stub_ptr_type stub_ptr_{};\n\n deleter_type deleter_;\n\n std::shared_ptr store_;\n std::size_t store_size_;\n\n template \n static void destructor_stub(void* const p)\n {\n static_cast(p)->~T();\n }\n\n template \n static void functor_deleter(void* const p)\n {\n static_cast(p)->~T();\n\n operator delete(p);\n }\n\n template \n static constexpr R function_stub(void* const,\n A const... args)\n {\n return (*function_ptr)(args...);\n }\n\n template \n static constexpr R method_stub(void* const object_ptr_,\n A const... args)\n {\n return (static_cast(object_ptr_)->*method_ptr)(args...);\n }\n\n template \n static constexpr R const_method_stub(void* const object_ptr_,\n A const... args)\n {\n return (static_cast(object_ptr_)->*method_ptr)(args...);\n }\n\n template \n static constexpr R functor_stub(void* const object_ptr_,\n A const... args)\n {\n return (*static_cast(object_ptr_))(args...);\n }\n};\n\nnamespace std\n{\n template \n struct hash >\n {\n size_t operator()(delegate const& d) const\n {\n auto const seed(hash()(d.object_ptr_) + 0x9e3779b9);\n\n return hash::stub_ptr_type>()(d.stub_ptr_)\n + 0x9e3779b9 + (seed << 6) + (seed >> 2);\n }\n };\n}\n\n#endif \/\/ DELEGATE_HPP\n<|endoftext|>"} {"text":"#include \n#include \"utTerm.h\"\n\nint main( int argc , char **argv )\n{\n testing :: InitGoogleTest( &argc , argv ) ;\n return RUN_ALL_TESTS( ) ;\n}\nDelete MainTerm.cpp<|endoftext|>"} {"text":"\/***********************************************************************\n filename: ItemViewRenderer.cpp\n created: Mon Jun 02 2014\n author: Timotei Dolean \n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/WindowRendererSets\/Core\/ItemViewRenderer.h\"\n#include \"CEGUI\/falagard\/WidgetLookManager.h\"\n\nnamespace CEGUI\n{\n\n\/\/----------------------------------------------------------------------------\/\/\nItemViewRenderer::ItemViewRenderer(const String& type) :\n WindowRenderer(type)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRectf ItemViewRenderer::getItemRenderingArea(bool hscroll, bool vscroll) const\n{\n const WidgetLookFeel& wlf = getLookNFeel();\n String scroll_suffix;\n\n if (vscroll)\n scroll_suffix += \"V\";\n\n if (hscroll)\n scroll_suffix += \"H\";\n\n if(!scroll_suffix.empty())\n scroll_suffix += \"Scroll\";\n\n const String area_names[] = { \"ItemRenderingArea\", \"ItemRenderArea\" };\n const String suffixes[] = { scroll_suffix, \"\" };\n\n for (size_t suffix_id = 0; suffix_id < 2; suffix_id++)\n {\n const String& suffix = suffixes[suffix_id];\n\n for (size_t area_id = 0; area_id < 2; ++area_id)\n {\n const String& full_area_name = area_names[area_id] + suffix;\n\n if (wlf.isNamedAreaDefined(full_area_name))\n return wlf.getNamedArea(full_area_name).getArea().getPixelRect(*d_window);\n }\n }\n\n CEGUI_THROW(UnknownObjectException(\"There is no item rendering area defined!\"));\n}\n\n}\nFix the instantiating of a string\/***********************************************************************\n filename: ItemViewRenderer.cpp\n created: Mon Jun 02 2014\n author: Timotei Dolean \n*************************************************************************\/\n\/***************************************************************************\n * Copyright (C) 2004 - 2014 Paul D Turner & The CEGUI Development Team\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR\n * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,\n * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR\n * OTHER DEALINGS IN THE SOFTWARE.\n ***************************************************************************\/\n#include \"CEGUI\/WindowRendererSets\/Core\/ItemViewRenderer.h\"\n#include \"CEGUI\/falagard\/WidgetLookManager.h\"\n\nnamespace CEGUI\n{\n\n\/\/----------------------------------------------------------------------------\/\/\nItemViewRenderer::ItemViewRenderer(const String& type) :\n WindowRenderer(type)\n{\n}\n\n\/\/----------------------------------------------------------------------------\/\/\nRectf ItemViewRenderer::getItemRenderingArea(bool hscroll, bool vscroll) const\n{\n const WidgetLookFeel& wlf = getLookNFeel();\n String scroll_suffix;\n\n if (vscroll)\n scroll_suffix += \"V\";\n\n if (hscroll)\n scroll_suffix += \"H\";\n\n if(!scroll_suffix.empty())\n scroll_suffix += \"Scroll\";\n\n const String area_names[] = { \"ItemRenderingArea\", \"ItemRenderArea\" };\n const String suffixes[] = { scroll_suffix, \"\" };\n\n for (size_t suffix_id = 0; suffix_id < 2; suffix_id++)\n {\n const String& suffix = suffixes[suffix_id];\n\n for (size_t area_id = 0; area_id < 2; ++area_id)\n {\n const String full_area_name(area_names[area_id] + suffix);\n\n if (wlf.isNamedAreaDefined(full_area_name))\n return wlf.getNamedArea(full_area_name).getArea().getPixelRect(*d_window);\n }\n }\n\n CEGUI_THROW(UnknownObjectException(\"There is no item rendering area defined!\"));\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(OS_WIN)\n#define MAYBE_Infobars Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n\/\/ Temporarily marked as DISABLED on OSX too. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\nMarking ExtensionApiTest.Infobars as DISABLED on Windows.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(OS_WIN)\n\/\/ Also marking this as disabled on Windows. See http:\/\/crbug.com\/75451.\n#define MAYBE_Infobars DISABLED_Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n\/\/ Temporarily marked as DISABLED on OSX too. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(TOOLKIT_VIEWS)\n#define MAYBE_Infobars Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n\/\/ Temporarily marked as DISABLED on OSX too. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\nMarking ExtensionApiTest, Infobars as DISABLED on everything but Windows.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/command_line.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n\n#if defined(OS_WIN)\n#define MAYBE_Infobars Infobars\n#else\n\/\/ Need to finish port to Linux. See http:\/\/crbug.com\/39916 for details.\n\/\/ Temporarily marked as DISABLED on OSX too. See http:\/\/crbug.com\/60990 for details.\n#define MAYBE_Infobars DISABLED_Infobars\n#endif\n\nIN_PROC_BROWSER_TEST_F(ExtensionApiTest, MAYBE_Infobars) {\n \/\/ TODO(finnur): Remove once infobars are no longer experimental (bug 39511).\n CommandLine::ForCurrentProcess()->AppendSwitch(\n switches::kEnableExperimentalExtensionApis);\n\n ASSERT_TRUE(RunExtensionTest(\"infobars\")) << message_;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_resource_handler.h\"\n\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"content\/common\/resource_response.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request.h\"\n\nnamespace prerender {\n\nnamespace {\n\nbool ShouldPrerenderURL(const GURL& url) {\n if (!url.is_valid())\n return false;\n if (!url.SchemeIs(\"http\")) {\n RecordFinalStatus(FINAL_STATUS_HTTPS);\n return false;\n }\n return true;\n}\n\nbool ValidateAliasURLs(const std::vector& urls) {\n for (std::vector::const_iterator it = urls.begin();\n it != urls.end();\n ++it) {\n if (!ShouldPrerenderURL(*it))\n return false;\n }\n return true;\n}\n\nbool ShouldPrerender(const ResourceResponse* response) {\n if (!response)\n return false;\n const ResourceResponseHead& rrh = response->response_head;\n if (!rrh.headers)\n return false;\n if (rrh.mime_type != \"text\/html\")\n return false;\n if (rrh.headers->response_code() != 200)\n return false;\n return true;\n}\n\n} \/\/ namespace\n\nPrerenderResourceHandler* PrerenderResourceHandler::MaybeCreate(\n const net::URLRequest& request,\n ChromeURLRequestContext* context,\n ResourceHandler* next_handler) {\n if (!context || !context->prerender_manager())\n return NULL;\n if (request.load_flags() & net::LOAD_PRERENDER) {\n RecordFinalStatus(FINAL_STATUS_NESTED);\n return NULL;\n }\n if (!(request.load_flags() & net::LOAD_PREFETCH))\n return NULL;\n if (!ShouldPrerenderURL(request.url()))\n return NULL;\n if (request.method() != \"GET\")\n return NULL;\n return new PrerenderResourceHandler(request,\n next_handler,\n context->prerender_manager());\n}\n\nPrerenderResourceHandler::PrerenderResourceHandler(\n const net::URLRequest& request,\n ResourceHandler* next_handler,\n PrerenderManager* prerender_manager)\n : next_handler_(next_handler),\n prerender_manager_(prerender_manager),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n prerender_callback_(NewCallback(\n this, &PrerenderResourceHandler::StartPrerender))),\n request_(request) {\n DCHECK(next_handler);\n DCHECK(prerender_manager);\n}\n\nPrerenderResourceHandler::PrerenderResourceHandler(\n const net::URLRequest& request,\n ResourceHandler* next_handler,\n PrerenderCallback* callback)\n : next_handler_(next_handler),\n prerender_callback_(callback),\n request_(request) {\n DCHECK(next_handler);\n DCHECK(callback);\n}\n\nPrerenderResourceHandler::~PrerenderResourceHandler() {\n}\n\nbool PrerenderResourceHandler::OnUploadProgress(int request_id,\n uint64 position,\n uint64 size) {\n return next_handler_->OnUploadProgress(request_id, position, size);\n}\n\nbool PrerenderResourceHandler::OnRequestRedirected(int request_id,\n const GURL& url,\n ResourceResponse* response,\n bool* defer) {\n bool will_redirect = next_handler_->OnRequestRedirected(\n request_id, url, response, defer);\n if (will_redirect) {\n if (!ShouldPrerenderURL(url))\n return false;\n alias_urls_.push_back(url);\n url_ = url;\n }\n return will_redirect;\n}\n\nbool PrerenderResourceHandler::OnResponseStarted(int request_id,\n ResourceResponse* response) {\n if (ShouldPrerender(response)) {\n DCHECK(ValidateAliasURLs(alias_urls_));\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &PrerenderResourceHandler::RunCallbackFromUIThread,\n url_,\n alias_urls_,\n GURL(request_.referrer())));\n }\n return next_handler_->OnResponseStarted(request_id, response);\n}\n\nbool PrerenderResourceHandler::OnWillStart(int request_id,\n const GURL& url,\n bool* defer) {\n bool will_start = next_handler_->OnWillStart(request_id, url, defer);\n if (will_start) {\n if (!ShouldPrerenderURL(url))\n return false;\n alias_urls_.push_back(url);\n url_ = url;\n }\n return will_start;\n}\n\nbool PrerenderResourceHandler::OnWillRead(int request_id,\n net::IOBuffer** buf,\n int* buf_size,\n int min_size) {\n return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);\n}\n\nbool PrerenderResourceHandler::OnReadCompleted(int request_id,\n int* bytes_read) {\n return next_handler_->OnReadCompleted(request_id, bytes_read);\n}\n\nbool PrerenderResourceHandler::OnResponseCompleted(\n int request_id,\n const net::URLRequestStatus& status,\n const std::string& security_info) {\n return next_handler_->OnResponseCompleted(request_id, status, security_info);\n}\n\nvoid PrerenderResourceHandler::OnRequestClosed() {\n next_handler_->OnRequestClosed();\n}\n\nvoid PrerenderResourceHandler::RunCallbackFromUIThread(\n const GURL& url,\n const std::vector& alias_urls,\n const GURL& referrer) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n prerender_callback_->Run(url, alias_urls, referrer);\n}\n\nvoid PrerenderResourceHandler::StartPrerender(\n const GURL& url,\n const std::vector& alias_urls,\n const GURL& referrer) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n prerender_manager_->AddPreload(url, alias_urls, referrer);\n}\n\n} \/\/ namespace prerender\nMove FINAL_STATUS_NESTED later so it is not counted too heavily.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/prerender\/prerender_resource_handler.h\"\n\n#include \"chrome\/browser\/net\/chrome_url_request_context.h\"\n#include \"content\/common\/resource_response.h\"\n#include \"net\/base\/load_flags.h\"\n#include \"net\/http\/http_response_headers.h\"\n#include \"net\/url_request\/url_request.h\"\n\nnamespace prerender {\n\nnamespace {\n\nbool ShouldPrerenderURL(const GURL& url) {\n if (!url.is_valid())\n return false;\n if (!url.SchemeIs(\"http\")) {\n RecordFinalStatus(FINAL_STATUS_HTTPS);\n return false;\n }\n return true;\n}\n\nbool ValidateAliasURLs(const std::vector& urls) {\n for (std::vector::const_iterator it = urls.begin();\n it != urls.end();\n ++it) {\n if (!ShouldPrerenderURL(*it))\n return false;\n }\n return true;\n}\n\nbool ShouldPrerender(const ResourceResponse* response) {\n if (!response)\n return false;\n const ResourceResponseHead& rrh = response->response_head;\n if (!rrh.headers)\n return false;\n if (rrh.mime_type != \"text\/html\")\n return false;\n if (rrh.headers->response_code() != 200)\n return false;\n return true;\n}\n\n} \/\/ namespace\n\nPrerenderResourceHandler* PrerenderResourceHandler::MaybeCreate(\n const net::URLRequest& request,\n ChromeURLRequestContext* context,\n ResourceHandler* next_handler) {\n if (!context || !context->prerender_manager())\n return NULL;\n if (!(request.load_flags() & net::LOAD_PREFETCH))\n return NULL;\n if (!ShouldPrerenderURL(request.url()))\n return NULL;\n if (request.method() != \"GET\")\n return NULL;\n if (request.load_flags() & net::LOAD_PRERENDER) {\n RecordFinalStatus(FINAL_STATUS_NESTED);\n return NULL;\n }\n return new PrerenderResourceHandler(request,\n next_handler,\n context->prerender_manager());\n}\n\nPrerenderResourceHandler::PrerenderResourceHandler(\n const net::URLRequest& request,\n ResourceHandler* next_handler,\n PrerenderManager* prerender_manager)\n : next_handler_(next_handler),\n prerender_manager_(prerender_manager),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n prerender_callback_(NewCallback(\n this, &PrerenderResourceHandler::StartPrerender))),\n request_(request) {\n DCHECK(next_handler);\n DCHECK(prerender_manager);\n}\n\nPrerenderResourceHandler::PrerenderResourceHandler(\n const net::URLRequest& request,\n ResourceHandler* next_handler,\n PrerenderCallback* callback)\n : next_handler_(next_handler),\n prerender_callback_(callback),\n request_(request) {\n DCHECK(next_handler);\n DCHECK(callback);\n}\n\nPrerenderResourceHandler::~PrerenderResourceHandler() {\n}\n\nbool PrerenderResourceHandler::OnUploadProgress(int request_id,\n uint64 position,\n uint64 size) {\n return next_handler_->OnUploadProgress(request_id, position, size);\n}\n\nbool PrerenderResourceHandler::OnRequestRedirected(int request_id,\n const GURL& url,\n ResourceResponse* response,\n bool* defer) {\n bool will_redirect = next_handler_->OnRequestRedirected(\n request_id, url, response, defer);\n if (will_redirect) {\n if (!ShouldPrerenderURL(url))\n return false;\n alias_urls_.push_back(url);\n url_ = url;\n }\n return will_redirect;\n}\n\nbool PrerenderResourceHandler::OnResponseStarted(int request_id,\n ResourceResponse* response) {\n if (ShouldPrerender(response)) {\n DCHECK(ValidateAliasURLs(alias_urls_));\n BrowserThread::PostTask(\n BrowserThread::UI,\n FROM_HERE,\n NewRunnableMethod(\n this,\n &PrerenderResourceHandler::RunCallbackFromUIThread,\n url_,\n alias_urls_,\n GURL(request_.referrer())));\n }\n return next_handler_->OnResponseStarted(request_id, response);\n}\n\nbool PrerenderResourceHandler::OnWillStart(int request_id,\n const GURL& url,\n bool* defer) {\n bool will_start = next_handler_->OnWillStart(request_id, url, defer);\n if (will_start) {\n if (!ShouldPrerenderURL(url))\n return false;\n alias_urls_.push_back(url);\n url_ = url;\n }\n return will_start;\n}\n\nbool PrerenderResourceHandler::OnWillRead(int request_id,\n net::IOBuffer** buf,\n int* buf_size,\n int min_size) {\n return next_handler_->OnWillRead(request_id, buf, buf_size, min_size);\n}\n\nbool PrerenderResourceHandler::OnReadCompleted(int request_id,\n int* bytes_read) {\n return next_handler_->OnReadCompleted(request_id, bytes_read);\n}\n\nbool PrerenderResourceHandler::OnResponseCompleted(\n int request_id,\n const net::URLRequestStatus& status,\n const std::string& security_info) {\n return next_handler_->OnResponseCompleted(request_id, status, security_info);\n}\n\nvoid PrerenderResourceHandler::OnRequestClosed() {\n next_handler_->OnRequestClosed();\n}\n\nvoid PrerenderResourceHandler::RunCallbackFromUIThread(\n const GURL& url,\n const std::vector& alias_urls,\n const GURL& referrer) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n prerender_callback_->Run(url, alias_urls, referrer);\n}\n\nvoid PrerenderResourceHandler::StartPrerender(\n const GURL& url,\n const std::vector& alias_urls,\n const GURL& referrer) {\n DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));\n prerender_manager_->AddPreload(url, alias_urls, referrer);\n}\n\n} \/\/ namespace prerender\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/browser_list.h\"\n#include \"chrome\/browser\/defaults.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/tab_restore_service.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/page_transition_types.h\"\n\nnamespace {\n\n\/\/ BrowserList::Observer implementation that waits for a browser to be\n\/\/ removed.\nclass BrowserListObserverImpl : public BrowserList::Observer {\n public:\n BrowserListObserverImpl() : did_remove_(false), running_(false) {\n BrowserList::AddObserver(this);\n }\n\n ~BrowserListObserverImpl() {\n BrowserList::RemoveObserver(this);\n }\n\n \/\/ Returns when a browser has been removed.\n void Run() {\n running_ = true;\n if (!did_remove_)\n ui_test_utils::RunMessageLoop();\n }\n\n \/\/ BrowserList::Observer\n virtual void OnBrowserAdded(const Browser* browser) OVERRIDE {\n }\n virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE {\n did_remove_ = true;\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n private:\n \/\/ Was OnBrowserRemoved invoked?\n bool did_remove_;\n\n \/\/ Was Run invoked?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl);\n};\n\n} \/\/ namespace\n\ntypedef InProcessBrowserTest SessionRestoreTest;\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n\/\/ Crashes on Linux Views: http:\/\/crbug.com\/39476\n#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \\\n DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers\n#else\n#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \\\n RestoreOnNewWindowWithNoTabbedBrowsers\n#endif\n\n\/\/ Makes sure when session restore is triggered in the same process we don't end\n\/\/ up with an extra tab.\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest,\n MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) {\n if (browser_defaults::kRestorePopups)\n return;\n\n const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Turn on session restore.\n SessionStartupPref::SetStartupPref(\n browser()->profile(),\n SessionStartupPref(SessionStartupPref::LAST));\n\n \/\/ Create a new popup.\n Profile* profile = browser()->profile();\n Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile);\n popup->window()->Show();\n\n \/\/ Close the browser.\n browser()->window()->Close();\n\n \/\/ Create a new window, which should trigger session restore.\n popup->NewWindow();\n\n Browser* new_browser = ui_test_utils::WaitForNewBrowser();\n\n ASSERT_TRUE(new_browser != NULL);\n\n \/\/ The browser should only have one tab.\n ASSERT_EQ(1, new_browser->tab_count());\n\n \/\/ And the first url should be url.\n EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());\n}\n\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) {\n GURL url1(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title1.html\"))));\n GURL url2(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title2.html\"))));\n GURL url3(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title3.html\"))));\n\n \/\/ Add and navigate three tabs.\n ui_test_utils::NavigateToURL(browser(), url1);\n browser()->AddSelectedTabWithURL(url2, PageTransition::LINK);\n ui_test_utils::WaitForNavigationInCurrentTab(browser());\n\n browser()->AddSelectedTabWithURL(url3, PageTransition::LINK);\n ui_test_utils::WaitForNavigationInCurrentTab(browser());\n\n TabRestoreService* service = browser()->profile()->GetTabRestoreService();\n service->ClearEntries();\n\n browser()->window()->Close();\n\n \/\/ Expect a window with three tabs.\n EXPECT_EQ(1U, service->entries().size());\n ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);\n const TabRestoreService::Window* window =\n static_cast(service->entries().front());\n EXPECT_EQ(3U, window->tabs.size());\n\n \/\/ Find the SessionID for entry2. Since the session service was destroyed,\n \/\/ there is no guarantee that the SessionID for the tab has remained the same.\n std::vector::const_iterator it = window->tabs.begin();\n for ( ; it != window->tabs.end(); ++it) {\n const TabRestoreService::Tab& tab = *it;\n \/\/ If this tab held url2, then restore this single tab.\n if (tab.navigations[0].virtual_url() == url2) {\n service->RestoreEntryById(NULL, tab.id, false);\n break;\n }\n }\n\n \/\/ Make sure that the Window got updated.\n EXPECT_EQ(1U, service->entries().size());\n ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);\n window = static_cast(service->entries().front());\n EXPECT_EQ(2U, window->tabs.size());\n}\n\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) {\n GURL url(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title1.html\"))));\n\n \/\/ Add a single tab.\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabRestoreService* service = browser()->profile()->GetTabRestoreService();\n service->ClearEntries();\n EXPECT_EQ(0U, service->entries().size());\n\n \/\/ Close the window.\n browser()->window()->Close();\n\n \/\/ Expect the window to be converted to a tab by the TRS.\n EXPECT_EQ(1U, service->entries().size());\n ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type);\n const TabRestoreService::Tab* tab =\n static_cast(service->entries().front());\n\n \/\/ Restore the tab.\n service->RestoreEntryById(NULL, tab->id, false);\n\n \/\/ Make sure the restore was successful.\n EXPECT_EQ(0U, service->entries().size());\n}\n\n\/\/ Verifies we remember the last browser window when closing the last\n\/\/ non-incognito window while an incognito window is open.\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) {\n \/\/ Turn on session restore.\n SessionStartupPref pref(SessionStartupPref::LAST);\n SessionStartupPref::SetStartupPref(browser()->profile(), pref);\n\n GURL url(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title1.html\"))));\n\n \/\/ Add a single tab.\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Create a new incognito window.\n Browser* incognito_browser = CreateIncognitoBrowser();\n incognito_browser->AddBlankTab(true);\n incognito_browser->window()->Show();\n\n \/\/ Close the normal browser. After this we only have the incognito window\n \/\/ open. We wait until the window closes as window closing is async.\n {\n BrowserListObserverImpl observer;\n browser()->window()->Close();\n observer.Run();\n }\n\n \/\/ Create a new window, which should trigger session restore.\n incognito_browser->NewWindow();\n\n \/\/ The first tab should have 'url' as its url.\n Browser* new_browser = ui_test_utils::WaitForNewBrowser();\n ASSERT_TRUE(new_browser);\n EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());\n}\nFix header include for reals.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/file_path.h\"\n#include \"chrome\/browser\/defaults.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/sessions\/tab_restore_service.h\"\n#include \"chrome\/browser\/tabs\/tab_strip_model.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/browser_list.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/test\/in_process_browser_test.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"content\/browser\/tab_contents\/tab_contents.h\"\n#include \"content\/common\/page_transition_types.h\"\n\nnamespace {\n\n\/\/ BrowserList::Observer implementation that waits for a browser to be\n\/\/ removed.\nclass BrowserListObserverImpl : public BrowserList::Observer {\n public:\n BrowserListObserverImpl() : did_remove_(false), running_(false) {\n BrowserList::AddObserver(this);\n }\n\n ~BrowserListObserverImpl() {\n BrowserList::RemoveObserver(this);\n }\n\n \/\/ Returns when a browser has been removed.\n void Run() {\n running_ = true;\n if (!did_remove_)\n ui_test_utils::RunMessageLoop();\n }\n\n \/\/ BrowserList::Observer\n virtual void OnBrowserAdded(const Browser* browser) OVERRIDE {\n }\n virtual void OnBrowserRemoved(const Browser* browser) OVERRIDE {\n did_remove_ = true;\n if (running_)\n MessageLoop::current()->Quit();\n }\n\n private:\n \/\/ Was OnBrowserRemoved invoked?\n bool did_remove_;\n\n \/\/ Was Run invoked?\n bool running_;\n\n DISALLOW_COPY_AND_ASSIGN(BrowserListObserverImpl);\n};\n\n} \/\/ namespace\n\ntypedef InProcessBrowserTest SessionRestoreTest;\n\n#if defined(OS_LINUX) && defined(TOOLKIT_VIEWS)\n\/\/ Crashes on Linux Views: http:\/\/crbug.com\/39476\n#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \\\n DISABLED_RestoreOnNewWindowWithNoTabbedBrowsers\n#else\n#define MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers \\\n RestoreOnNewWindowWithNoTabbedBrowsers\n#endif\n\n\/\/ Makes sure when session restore is triggered in the same process we don't end\n\/\/ up with an extra tab.\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest,\n MAYBE_RestoreOnNewWindowWithNoTabbedBrowsers) {\n if (browser_defaults::kRestorePopups)\n return;\n\n const FilePath::CharType* kTitle1File = FILE_PATH_LITERAL(\"title1.html\");\n GURL url(ui_test_utils::GetTestUrl(FilePath(FilePath::kCurrentDirectory),\n FilePath(kTitle1File)));\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Turn on session restore.\n SessionStartupPref::SetStartupPref(\n browser()->profile(),\n SessionStartupPref(SessionStartupPref::LAST));\n\n \/\/ Create a new popup.\n Profile* profile = browser()->profile();\n Browser* popup = Browser::CreateForType(Browser::TYPE_POPUP, profile);\n popup->window()->Show();\n\n \/\/ Close the browser.\n browser()->window()->Close();\n\n \/\/ Create a new window, which should trigger session restore.\n popup->NewWindow();\n\n Browser* new_browser = ui_test_utils::WaitForNewBrowser();\n\n ASSERT_TRUE(new_browser != NULL);\n\n \/\/ The browser should only have one tab.\n ASSERT_EQ(1, new_browser->tab_count());\n\n \/\/ And the first url should be url.\n EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());\n}\n\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest, RestoreIndividualTabFromWindow) {\n GURL url1(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title1.html\"))));\n GURL url2(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title2.html\"))));\n GURL url3(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title3.html\"))));\n\n \/\/ Add and navigate three tabs.\n ui_test_utils::NavigateToURL(browser(), url1);\n browser()->AddSelectedTabWithURL(url2, PageTransition::LINK);\n ui_test_utils::WaitForNavigationInCurrentTab(browser());\n\n browser()->AddSelectedTabWithURL(url3, PageTransition::LINK);\n ui_test_utils::WaitForNavigationInCurrentTab(browser());\n\n TabRestoreService* service = browser()->profile()->GetTabRestoreService();\n service->ClearEntries();\n\n browser()->window()->Close();\n\n \/\/ Expect a window with three tabs.\n EXPECT_EQ(1U, service->entries().size());\n ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);\n const TabRestoreService::Window* window =\n static_cast(service->entries().front());\n EXPECT_EQ(3U, window->tabs.size());\n\n \/\/ Find the SessionID for entry2. Since the session service was destroyed,\n \/\/ there is no guarantee that the SessionID for the tab has remained the same.\n std::vector::const_iterator it = window->tabs.begin();\n for ( ; it != window->tabs.end(); ++it) {\n const TabRestoreService::Tab& tab = *it;\n \/\/ If this tab held url2, then restore this single tab.\n if (tab.navigations[0].virtual_url() == url2) {\n service->RestoreEntryById(NULL, tab.id, false);\n break;\n }\n }\n\n \/\/ Make sure that the Window got updated.\n EXPECT_EQ(1U, service->entries().size());\n ASSERT_EQ(TabRestoreService::WINDOW, service->entries().front()->type);\n window = static_cast(service->entries().front());\n EXPECT_EQ(2U, window->tabs.size());\n}\n\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest, WindowWithOneTab) {\n GURL url(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title1.html\"))));\n\n \/\/ Add a single tab.\n ui_test_utils::NavigateToURL(browser(), url);\n\n TabRestoreService* service = browser()->profile()->GetTabRestoreService();\n service->ClearEntries();\n EXPECT_EQ(0U, service->entries().size());\n\n \/\/ Close the window.\n browser()->window()->Close();\n\n \/\/ Expect the window to be converted to a tab by the TRS.\n EXPECT_EQ(1U, service->entries().size());\n ASSERT_EQ(TabRestoreService::TAB, service->entries().front()->type);\n const TabRestoreService::Tab* tab =\n static_cast(service->entries().front());\n\n \/\/ Restore the tab.\n service->RestoreEntryById(NULL, tab->id, false);\n\n \/\/ Make sure the restore was successful.\n EXPECT_EQ(0U, service->entries().size());\n}\n\n\/\/ Verifies we remember the last browser window when closing the last\n\/\/ non-incognito window while an incognito window is open.\nIN_PROC_BROWSER_TEST_F(SessionRestoreTest, IncognitotoNonIncognito) {\n \/\/ Turn on session restore.\n SessionStartupPref pref(SessionStartupPref::LAST);\n SessionStartupPref::SetStartupPref(browser()->profile(), pref);\n\n GURL url(ui_test_utils::GetTestUrl(\n FilePath(FilePath::kCurrentDirectory),\n FilePath(FILE_PATH_LITERAL(\"title1.html\"))));\n\n \/\/ Add a single tab.\n ui_test_utils::NavigateToURL(browser(), url);\n\n \/\/ Create a new incognito window.\n Browser* incognito_browser = CreateIncognitoBrowser();\n incognito_browser->AddBlankTab(true);\n incognito_browser->window()->Show();\n\n \/\/ Close the normal browser. After this we only have the incognito window\n \/\/ open. We wait until the window closes as window closing is async.\n {\n BrowserListObserverImpl observer;\n browser()->window()->Close();\n observer.Run();\n }\n\n \/\/ Create a new window, which should trigger session restore.\n incognito_browser->NewWindow();\n\n \/\/ The first tab should have 'url' as its url.\n Browser* new_browser = ui_test_utils::WaitForNewBrowser();\n ASSERT_TRUE(new_browser);\n EXPECT_EQ(url, new_browser->GetTabContentsAt(0)->GetURL());\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/tab_contents_ssl_helper.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/certificate_viewer.h\"\n#include \"chrome\/browser\/ssl\/ssl_add_cert_handler.h\"\n#include \"chrome\/browser\/ssl\/ssl_client_auth_handler.h\"\n#include \"chrome\/browser\/ssl_client_certificate_selector.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"net\/base\/net_errors.h\"\n\nnamespace {\n\nSkBitmap* GetCertIcon() {\n \/\/ TODO(davidben): use a more appropriate icon.\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_SAVE_PASSWORD);\n}\n\nclass SSLCertAddedInfoBarDelegate : public ConfirmInfoBarDelegate {\n public:\n SSLCertAddedInfoBarDelegate(TabContents* tab_contents,\n net::X509Certificate* cert)\n : ConfirmInfoBarDelegate(tab_contents),\n tab_contents_(tab_contents),\n cert_(cert) {\n }\n\n virtual ~SSLCertAddedInfoBarDelegate() {\n }\n\n \/\/ Overridden from ConfirmInfoBarDelegate:\n virtual string16 GetMessageText() const {\n \/\/ TODO(evanm): GetDisplayName should return UTF-16.\n return l10n_util::GetStringFUTF16(\n IDS_ADD_CERT_SUCCESS_INFOBAR_LABEL,\n UTF8ToUTF16(cert_->issuer().GetDisplayName()));\n }\n\n virtual SkBitmap* GetIcon() const {\n return GetCertIcon();\n }\n\n virtual int GetButtons() const {\n return BUTTON_OK;\n }\n\n virtual string16 GetButtonLabel(InfoBarButton button) const {\n switch (button) {\n case BUTTON_OK:\n return l10n_util::GetStringUTF16(IDS_ADD_CERT_SUCCESS_INFOBAR_BUTTON);\n default:\n return string16();\n }\n }\n\n virtual Type GetInfoBarType() {\n return PAGE_ACTION_TYPE;\n }\n\n virtual bool Accept() {\n ShowCertificateViewer(tab_contents_->GetMessageBoxRootWindow(), cert_);\n return false; \/\/ Hiding the infobar just as the dialog opens looks weird.\n }\n\n virtual void InfoBarClosed() {\n \/\/ ConfirmInfoBarDelegate doesn't delete itself.\n delete this;\n }\n\n private:\n \/\/ The TabContents we are attached to\n TabContents* tab_contents_;\n \/\/ The cert we added.\n scoped_refptr cert_;\n};\n\n} \/\/ namespace\n\nclass TabContentsSSLHelper::SSLAddCertData : public NotificationObserver {\n public:\n SSLAddCertData(TabContents* tab, SSLAddCertHandler* handler)\n : tab_(tab),\n handler_(handler),\n infobar_delegate_(NULL) {\n \/\/ Listen for disappearing InfoBars.\n Source tc_source(tab_);\n registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,\n tc_source);\n registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REPLACED,\n tc_source);\n }\n ~SSLAddCertData() {}\n\n \/\/ Displays |delegate| as an infobar in |tab_|, replacing our current one if\n \/\/ still active.\n void ShowInfoBar(InfoBarDelegate* delegate) {\n if (infobar_delegate_) {\n tab_->ReplaceInfoBar(infobar_delegate_, delegate);\n } else {\n tab_->AddInfoBar(delegate);\n }\n infobar_delegate_ = delegate;\n }\n\n void ShowErrorInfoBar(const std::wstring& message) {\n ShowInfoBar(\n new SimpleAlertInfoBarDelegate(tab_,\n WideToUTF16(message),\n GetCertIcon(),\n true));\n }\n\n \/\/ NotificationObserver implementation.\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::TAB_CONTENTS_INFOBAR_REMOVED:\n InfoBarClosed(Details(details).ptr());\n break;\n case NotificationType::TAB_CONTENTS_INFOBAR_REPLACED:\n typedef std::pair\n InfoBarDelegatePair;\n InfoBarClosed(Details(details).ptr()->first);\n break;\n default:\n NOTREACHED();\n break;\n }\n }\n\n private:\n void InfoBarClosed(InfoBarDelegate* delegate) {\n if (infobar_delegate_ == delegate)\n infobar_delegate_ = NULL;\n }\n\n \/\/ The TabContents we are attached to.\n TabContents* tab_;\n \/\/ The handler we call back to.\n scoped_refptr handler_;\n \/\/ The current InfoBarDelegate we're displaying.\n InfoBarDelegate* infobar_delegate_;\n\n NotificationRegistrar registrar_;\n\n DISALLOW_COPY_AND_ASSIGN(SSLAddCertData);\n};\n\nTabContentsSSLHelper::TabContentsSSLHelper(TabContents* tab_contents)\n : tab_contents_(tab_contents) {\n}\n\nTabContentsSSLHelper::~TabContentsSSLHelper() {\n}\n\nvoid TabContentsSSLHelper::ShowClientCertificateRequestDialog(\n scoped_refptr handler) {\n browser::ShowSSLClientCertificateSelector(\n tab_contents_, handler->cert_request_info(), handler);\n}\n\nvoid TabContentsSSLHelper::OnVerifyClientCertificateError(\n scoped_refptr handler, int error_code) {\n SSLAddCertData* add_cert_data = GetAddCertData(handler);\n \/\/ Display an infobar with the error message.\n \/\/ TODO(davidben): Display a more user-friendly error string.\n add_cert_data->ShowErrorInfoBar(\n l10n_util::GetStringF(IDS_ADD_CERT_ERR_INVALID_CERT,\n UTF8ToWide(base::IntToString(-error_code)),\n ASCIIToWide(net::ErrorToString(error_code))));\n}\n\nvoid TabContentsSSLHelper::AskToAddClientCertificate(\n scoped_refptr handler) {\n NOTREACHED(); \/\/ Not implemented yet.\n}\n\nvoid TabContentsSSLHelper::OnAddClientCertificateSuccess(\n scoped_refptr handler) {\n SSLAddCertData* add_cert_data = GetAddCertData(handler);\n \/\/ Display an infobar to inform the user.\n add_cert_data->ShowInfoBar(\n new SSLCertAddedInfoBarDelegate(tab_contents_, handler->cert()));\n}\n\nvoid TabContentsSSLHelper::OnAddClientCertificateError(\n scoped_refptr handler, int error_code) {\n SSLAddCertData* add_cert_data = GetAddCertData(handler);\n \/\/ Display an infobar with the error message.\n \/\/ TODO(davidben): Display a more user-friendly error string.\n add_cert_data->ShowErrorInfoBar(\n l10n_util::GetStringF(IDS_ADD_CERT_ERR_FAILED,\n UTF8ToWide(base::IntToString(-error_code)),\n ASCIIToWide(net::ErrorToString(error_code))));\n}\n\nvoid TabContentsSSLHelper::OnAddClientCertificateFinished(\n scoped_refptr handler) {\n \/\/ Clean up.\n request_id_to_add_cert_data_.erase(handler->network_request_id());\n}\n\nTabContentsSSLHelper::SSLAddCertData* TabContentsSSLHelper::GetAddCertData(\n SSLAddCertHandler* handler) {\n \/\/ Find\/create the slot.\n linked_ptr& ptr_ref =\n request_id_to_add_cert_data_[handler->network_request_id()];\n \/\/ Fill it if necessary.\n if (!ptr_ref.get())\n ptr_ref.reset(new SSLAddCertData(tab_contents_, handler));\n return ptr_ref.get();\n}\nRmeove another wstring from infobar code.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/tab_contents\/tab_contents_ssl_helper.h\"\n\n#include \"app\/l10n_util.h\"\n#include \"app\/resource_bundle.h\"\n#include \"base\/basictypes.h\"\n#include \"base\/string_number_conversions.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/certificate_viewer.h\"\n#include \"chrome\/browser\/ssl\/ssl_add_cert_handler.h\"\n#include \"chrome\/browser\/ssl\/ssl_client_auth_handler.h\"\n#include \"chrome\/browser\/ssl_client_certificate_selector.h\"\n#include \"chrome\/browser\/tab_contents\/infobar_delegate.h\"\n#include \"chrome\/browser\/tab_contents\/tab_contents.h\"\n#include \"chrome\/common\/notification_service.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"net\/base\/net_errors.h\"\n\nnamespace {\n\nSkBitmap* GetCertIcon() {\n \/\/ TODO(davidben): use a more appropriate icon.\n return ResourceBundle::GetSharedInstance().GetBitmapNamed(\n IDR_INFOBAR_SAVE_PASSWORD);\n}\n\nclass SSLCertAddedInfoBarDelegate : public ConfirmInfoBarDelegate {\n public:\n SSLCertAddedInfoBarDelegate(TabContents* tab_contents,\n net::X509Certificate* cert)\n : ConfirmInfoBarDelegate(tab_contents),\n tab_contents_(tab_contents),\n cert_(cert) {\n }\n\n virtual ~SSLCertAddedInfoBarDelegate() {\n }\n\n \/\/ Overridden from ConfirmInfoBarDelegate:\n virtual string16 GetMessageText() const {\n \/\/ TODO(evanm): GetDisplayName should return UTF-16.\n return l10n_util::GetStringFUTF16(\n IDS_ADD_CERT_SUCCESS_INFOBAR_LABEL,\n UTF8ToUTF16(cert_->issuer().GetDisplayName()));\n }\n\n virtual SkBitmap* GetIcon() const {\n return GetCertIcon();\n }\n\n virtual int GetButtons() const {\n return BUTTON_OK;\n }\n\n virtual string16 GetButtonLabel(InfoBarButton button) const {\n switch (button) {\n case BUTTON_OK:\n return l10n_util::GetStringUTF16(IDS_ADD_CERT_SUCCESS_INFOBAR_BUTTON);\n default:\n return string16();\n }\n }\n\n virtual Type GetInfoBarType() {\n return PAGE_ACTION_TYPE;\n }\n\n virtual bool Accept() {\n ShowCertificateViewer(tab_contents_->GetMessageBoxRootWindow(), cert_);\n return false; \/\/ Hiding the infobar just as the dialog opens looks weird.\n }\n\n virtual void InfoBarClosed() {\n \/\/ ConfirmInfoBarDelegate doesn't delete itself.\n delete this;\n }\n\n private:\n \/\/ The TabContents we are attached to\n TabContents* tab_contents_;\n \/\/ The cert we added.\n scoped_refptr cert_;\n};\n\n} \/\/ namespace\n\nclass TabContentsSSLHelper::SSLAddCertData : public NotificationObserver {\n public:\n SSLAddCertData(TabContents* tab, SSLAddCertHandler* handler)\n : tab_(tab),\n handler_(handler),\n infobar_delegate_(NULL) {\n \/\/ Listen for disappearing InfoBars.\n Source tc_source(tab_);\n registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REMOVED,\n tc_source);\n registrar_.Add(this, NotificationType::TAB_CONTENTS_INFOBAR_REPLACED,\n tc_source);\n }\n ~SSLAddCertData() {}\n\n \/\/ Displays |delegate| as an infobar in |tab_|, replacing our current one if\n \/\/ still active.\n void ShowInfoBar(InfoBarDelegate* delegate) {\n if (infobar_delegate_) {\n tab_->ReplaceInfoBar(infobar_delegate_, delegate);\n } else {\n tab_->AddInfoBar(delegate);\n }\n infobar_delegate_ = delegate;\n }\n\n void ShowErrorInfoBar(const string16& message) {\n ShowInfoBar(\n new SimpleAlertInfoBarDelegate(tab_, message, GetCertIcon(), true));\n }\n\n \/\/ NotificationObserver implementation.\n virtual void Observe(NotificationType type,\n const NotificationSource& source,\n const NotificationDetails& details) {\n switch (type.value) {\n case NotificationType::TAB_CONTENTS_INFOBAR_REMOVED:\n InfoBarClosed(Details(details).ptr());\n break;\n case NotificationType::TAB_CONTENTS_INFOBAR_REPLACED:\n typedef std::pair\n InfoBarDelegatePair;\n InfoBarClosed(Details(details).ptr()->first);\n break;\n default:\n NOTREACHED();\n break;\n }\n }\n\n private:\n void InfoBarClosed(InfoBarDelegate* delegate) {\n if (infobar_delegate_ == delegate)\n infobar_delegate_ = NULL;\n }\n\n \/\/ The TabContents we are attached to.\n TabContents* tab_;\n \/\/ The handler we call back to.\n scoped_refptr handler_;\n \/\/ The current InfoBarDelegate we're displaying.\n InfoBarDelegate* infobar_delegate_;\n\n NotificationRegistrar registrar_;\n\n DISALLOW_COPY_AND_ASSIGN(SSLAddCertData);\n};\n\nTabContentsSSLHelper::TabContentsSSLHelper(TabContents* tab_contents)\n : tab_contents_(tab_contents) {\n}\n\nTabContentsSSLHelper::~TabContentsSSLHelper() {\n}\n\nvoid TabContentsSSLHelper::ShowClientCertificateRequestDialog(\n scoped_refptr handler) {\n browser::ShowSSLClientCertificateSelector(\n tab_contents_, handler->cert_request_info(), handler);\n}\n\nvoid TabContentsSSLHelper::OnVerifyClientCertificateError(\n scoped_refptr handler, int error_code) {\n SSLAddCertData* add_cert_data = GetAddCertData(handler);\n \/\/ Display an infobar with the error message.\n \/\/ TODO(davidben): Display a more user-friendly error string.\n add_cert_data->ShowErrorInfoBar(\n l10n_util::GetStringFUTF16(IDS_ADD_CERT_ERR_INVALID_CERT,\n base::IntToString16(-error_code),\n ASCIIToUTF16(net::ErrorToString(error_code))));\n}\n\nvoid TabContentsSSLHelper::AskToAddClientCertificate(\n scoped_refptr handler) {\n NOTREACHED(); \/\/ Not implemented yet.\n}\n\nvoid TabContentsSSLHelper::OnAddClientCertificateSuccess(\n scoped_refptr handler) {\n SSLAddCertData* add_cert_data = GetAddCertData(handler);\n \/\/ Display an infobar to inform the user.\n add_cert_data->ShowInfoBar(\n new SSLCertAddedInfoBarDelegate(tab_contents_, handler->cert()));\n}\n\nvoid TabContentsSSLHelper::OnAddClientCertificateError(\n scoped_refptr handler, int error_code) {\n SSLAddCertData* add_cert_data = GetAddCertData(handler);\n \/\/ Display an infobar with the error message.\n \/\/ TODO(davidben): Display a more user-friendly error string.\n add_cert_data->ShowErrorInfoBar(\n l10n_util::GetStringFUTF16(IDS_ADD_CERT_ERR_FAILED,\n base::IntToString16(-error_code),\n ASCIIToUTF16(net::ErrorToString(error_code))));\n}\n\nvoid TabContentsSSLHelper::OnAddClientCertificateFinished(\n scoped_refptr handler) {\n \/\/ Clean up.\n request_id_to_add_cert_data_.erase(handler->network_request_id());\n}\n\nTabContentsSSLHelper::SSLAddCertData* TabContentsSSLHelper::GetAddCertData(\n SSLAddCertHandler* handler) {\n \/\/ Find\/create the slot.\n linked_ptr& ptr_ref =\n request_id_to_add_cert_data_[handler->network_request_id()];\n \/\/ Fill it if necessary.\n if (!ptr_ref.get())\n ptr_ref.reset(new SSLAddCertData(tab_contents_, handler));\n return ptr_ref.get();\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of the CernVM File System.\n *\n * Fills an internal map of key-value pairs from ASCII files in key=value\n * style. Parameters can be overwritten. Used to read configuration from\n * \/etc\/cvmfs\/...\n *\/\n\n#include \"cvmfs_config.h\"\n#include \"options.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"logging.h\"\n#include \"sanitizer.h\"\n#include \"util.h\"\n\nusing namespace std; \/\/ NOLINT\n\n#ifdef CVMFS_NAMESPACE_GUARD\nnamespace CVMFS_NAMESPACE_GUARD {\n#endif\n\n\nstatic string EscapeShell(const std::string &raw) {\n for (unsigned i = 0, l = raw.length(); i < l; ++i) {\n if (!(((raw[i] >= '0') && (raw[i] <= '9')) ||\n ((raw[i] >= 'A') && (raw[i] <= 'Z')) ||\n ((raw[i] >= 'a') && (raw[i] <= 'z')) ||\n (raw[i] == '\/') || (raw[i] == ':') || (raw[i] == '.') ||\n (raw[i] == '_') || (raw[i] == '-') || (raw[i] == ',')))\n {\n goto escape_shell_quote;\n }\n }\n return raw;\n\n escape_shell_quote:\n string result = \"'\";\n for (unsigned i = 0, l = raw.length(); i < l; ++i) {\n if (raw[i] == '\\'')\n result += \"\\\\\";\n result += raw[i];\n }\n result += \"'\";\n return result;\n}\n\n\nvoid SimpleOptionsParser::ParsePath(const string &config_file,\n const bool external __attribute__((unused))) {\n LogCvmfs(kLogCvmfs, kLogDebug, \"Fast-parsing config file %s\",\n config_file.c_str());\n int retval;\n string line;\n FILE *fconfig = fopen(config_file.c_str(), \"r\");\n if (fconfig == NULL)\n return;\n\n \/\/ Read line by line and extract parameters\n while (GetLineFile(fconfig, &line)) {\n line = Trim(line);\n if (line.empty() || line[0] == '#' || line.find(\" \") < string::npos)\n continue;\n vector tokens = SplitString(line, '=');\n if (tokens.size() < 2 || tokens.size() > 2)\n continue;\n\n ConfigValue value;\n value.source = config_file;\n value.value = tokens[1];\n string parameter = tokens[0];\n config_[parameter] = value;\n retval = setenv(parameter.c_str(), value.value.c_str(), 1);\n assert(retval == 0);\n }\n fclose(fconfig);\n}\n\n\nvoid BashOptionsManager::ParsePath(const string &config_file,\n const bool external) {\n LogCvmfs(kLogCvmfs, kLogDebug, \"Parsing config file %s\", config_file.c_str());\n int retval;\n int pipe_open[2];\n int pipe_quit[2];\n pid_t pid_child = 0;\n if (external) {\n \/\/ cvmfs can run in the process group of automount in which case\n \/\/ autofs won't mount an additional config repository. We create a\n \/\/ short-lived process that detaches from the process group and triggers\n \/\/ autofs to mount the config repository, if necessary. It holds a file\n \/\/ handle to the config file until the main process opened the file, too.\n MakePipe(pipe_open);\n MakePipe(pipe_quit);\n switch (pid_child = fork()) {\n case -1:\n abort();\n case 0: { \/\/ Child\n close(pipe_open[0]);\n close(pipe_quit[1]);\n \/\/ If this is not a process group leader, create a new session\n if (getpgrp() != getpid()) {\n pid_t new_session = setsid();\n assert(new_session != (pid_t)-1);\n }\n (void)open(config_file.c_str(), O_RDONLY);\n char ready = 'R';\n WritePipe(pipe_open[1], &ready, 1);\n read(pipe_quit[0], &ready, 1);\n _exit(0); \/\/ Don't flush shared file descriptors\n }\n }\n \/\/ Parent\n close(pipe_open[1]);\n close(pipe_quit[0]);\n char ready = 0;\n ReadPipe(pipe_open[0], &ready, 1);\n assert(ready == 'R');\n close(pipe_open[0]);\n }\n const string config_path = GetParentPath(config_file);\n FILE *fconfig = fopen(config_file.c_str(), \"r\");\n if (pid_child > 0) {\n char c = 'C';\n WritePipe(pipe_quit[1], &c, 1);\n int statloc;\n waitpid(pid_child, &statloc, 0);\n close(pipe_quit[1]);\n }\n if (!fconfig) {\n if (external && !DirectoryExists(config_path)) {\n LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,\n \"external location for configuration files does not exist: %s\",\n config_path.c_str());\n }\n return;\n }\n\n int fd_stdin;\n int fd_stdout;\n int fd_stderr;\n retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);\n assert(retval);\n\n \/\/ Let the shell read the file\n string line;\n const string newline = \"\\n\";\n const string cd = \"cd \\\"\" + ((config_path == \"\") ? \"\/\" : config_path) + \"\\\"\" +\n newline;\n WritePipe(fd_stdin, cd.data(), cd.length());\n while (GetLineFile(fconfig, &line)) {\n WritePipe(fd_stdin, line.data(), line.length());\n WritePipe(fd_stdin, newline.data(), newline.length());\n }\n rewind(fconfig);\n\n \/\/ Read line by line and extract parameters\n while (GetLineFile(fconfig, &line)) {\n line = Trim(line);\n if (line.empty() || line[0] == '#' || line.find(\"if \") == 0)\n continue;\n vector tokens = SplitString(line, '=');\n if (tokens.size() < 2)\n continue;\n\n ConfigValue value;\n value.source = config_file;\n string parameter = tokens[0];\n \/\/ Strip \"readonly\"\n if (parameter.find(\"readonly\") == 0) {\n parameter = parameter.substr(8);\n parameter = Trim(parameter);\n }\n \/\/ Strip export\n if (parameter.find(\"export\") == 0) {\n parameter = parameter.substr(6);\n parameter = Trim(parameter);\n }\n \/\/ Strip eval\n if (parameter.find(\"eval\") == 0) {\n parameter = parameter.substr(4);\n parameter = Trim(parameter);\n }\n\n const string sh_echo = \"echo $\" + parameter + \"\\n\";\n WritePipe(fd_stdin, sh_echo.data(), sh_echo.length());\n GetLineFd(fd_stdout, &value.value);\n config_[parameter] = value;\n retval = setenv(parameter.c_str(), value.value.c_str(), 1);\n assert(retval == 0);\n }\n\n close(fd_stderr);\n close(fd_stdout);\n close(fd_stdin);\n fclose(fconfig);\n}\n\n\nbool OptionsManager::HasConfigRepository(const string &fqrn,\n string *config_path) {\n string cvmfs_mount_dir;\n if (!GetValue(\"CVMFS_MOUNT_DIR\", &cvmfs_mount_dir)) {\n LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, \"CVMFS_MOUNT_DIR missing\");\n return false;\n }\n\n string config_repository;\n if (GetValue(\"CVMFS_CONFIG_REPOSITORY\", &config_repository)) {\n if (config_repository.empty() || (config_repository == fqrn))\n return false;\n sanitizer::RepositorySanitizer repository_sanitizer;\n if (!repository_sanitizer.IsValid(config_repository)) {\n LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,\n \"invalid CVMFS_CONFIG_REPOSITORY: %s\",\n config_repository.c_str());\n return false;\n }\n *config_path = cvmfs_mount_dir + \"\/\" + config_repository + \"\/etc\/cvmfs\/\";\n return true;\n }\n return false;\n}\n\n\nvoid OptionsManager::ParseDefault(const string &fqrn) {\n int retval = setenv(\"CVMFS_FQRN\", fqrn.c_str(), 1);\n assert(retval == 0);\n\n ParsePath(\"\/etc\/cvmfs\/default.conf\", false);\n vector dist_defaults = FindFiles(\"\/etc\/cvmfs\/default.d\", \".conf\");\n for (unsigned i = 0; i < dist_defaults.size(); ++i) {\n ParsePath(dist_defaults[i], false);\n }\n ParsePath(\"\/etc\/cvmfs\/default.local\", false);\n\n if (fqrn != \"\") {\n string domain;\n vector tokens = SplitString(fqrn, '.');\n assert(tokens.size() > 1);\n tokens.erase(tokens.begin());\n domain = JoinStrings(tokens, \".\");\n\n string external_config_path;\n if (HasConfigRepository(fqrn, &external_config_path))\n ParsePath(external_config_path + \"domain.d\/\" + domain + \".conf\", true);\n ParsePath(\"\/etc\/cvmfs\/domain.d\/\" + domain + \".conf\", false);\n ParsePath(\"\/etc\/cvmfs\/domain.d\/\" + domain + \".local\", false);\n\n if (HasConfigRepository(fqrn, &external_config_path))\n ParsePath(external_config_path + \"config.d\/\" + fqrn + \".conf\", true);\n ParsePath(\"\/etc\/cvmfs\/config.d\/\" + fqrn + \".conf\", false);\n ParsePath(\"\/etc\/cvmfs\/config.d\/\" + fqrn + \".local\", false);\n }\n}\n\n\nvoid OptionsManager::ClearConfig() {\n config_.clear();\n}\n\n\nbool OptionsManager::IsDefined(const std::string &key) {\n map::const_iterator iter = config_.find(key);\n return iter != config_.end();\n}\n\n\nbool OptionsManager::GetValue(const string &key, string *value) {\n map::const_iterator iter = config_.find(key);\n if (iter != config_.end()) {\n *value = iter->second.value;\n return true;\n }\n *value = \"\";\n return false;\n}\n\n\nbool OptionsManager::GetSource(const string &key, string *value) {\n map::const_iterator iter = config_.find(key);\n if (iter != config_.end()) {\n *value = iter->second.source;\n return true;\n }\n *value = \"\";\n return false;\n}\n\n\nbool OptionsManager::IsOn(const std::string ¶m_value) {\n const string uppercase = ToUpper(param_value);\n return ((uppercase == \"YES\") || (uppercase == \"ON\") || (uppercase == \"1\"));\n}\n\n\nvector OptionsManager::GetAllKeys() {\n vector result;\n for (map::const_iterator i = config_.begin(),\n iEnd = config_.end(); i != iEnd; ++i)\n {\n result.push_back(i->first);\n }\n return result;\n}\n\n\nstring OptionsManager::Dump() {\n string result;\n vector keys = GetAllKeys();\n for (unsigned i = 0, l = keys.size(); i < l; ++i) {\n bool retval;\n string value;\n string source;\n\n retval = GetValue(keys[i], &value);\n assert(retval);\n retval = GetSource(keys[i], &source);\n assert(retval);\n result += keys[i] + \"=\" + EscapeShell(value) +\n \" # from \" + source + \"\\n\";\n }\n return result;\n}\n\n#ifdef CVMFS_NAMESPACE_GUARD\n} \/\/ namespace CVMFS_NAMESPACE_GUARD\n#endif\nadd looking for default.conf in config repo\/**\n * This file is part of the CernVM File System.\n *\n * Fills an internal map of key-value pairs from ASCII files in key=value\n * style. Parameters can be overwritten. Used to read configuration from\n * \/etc\/cvmfs\/...\n *\/\n\n#include \"cvmfs_config.h\"\n#include \"options.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"logging.h\"\n#include \"sanitizer.h\"\n#include \"util.h\"\n\nusing namespace std; \/\/ NOLINT\n\n#ifdef CVMFS_NAMESPACE_GUARD\nnamespace CVMFS_NAMESPACE_GUARD {\n#endif\n\n\nstatic string EscapeShell(const std::string &raw) {\n for (unsigned i = 0, l = raw.length(); i < l; ++i) {\n if (!(((raw[i] >= '0') && (raw[i] <= '9')) ||\n ((raw[i] >= 'A') && (raw[i] <= 'Z')) ||\n ((raw[i] >= 'a') && (raw[i] <= 'z')) ||\n (raw[i] == '\/') || (raw[i] == ':') || (raw[i] == '.') ||\n (raw[i] == '_') || (raw[i] == '-') || (raw[i] == ',')))\n {\n goto escape_shell_quote;\n }\n }\n return raw;\n\n escape_shell_quote:\n string result = \"'\";\n for (unsigned i = 0, l = raw.length(); i < l; ++i) {\n if (raw[i] == '\\'')\n result += \"\\\\\";\n result += raw[i];\n }\n result += \"'\";\n return result;\n}\n\n\nvoid SimpleOptionsParser::ParsePath(const string &config_file,\n const bool external __attribute__((unused))) {\n LogCvmfs(kLogCvmfs, kLogDebug, \"Fast-parsing config file %s\",\n config_file.c_str());\n int retval;\n string line;\n FILE *fconfig = fopen(config_file.c_str(), \"r\");\n if (fconfig == NULL)\n return;\n\n \/\/ Read line by line and extract parameters\n while (GetLineFile(fconfig, &line)) {\n line = Trim(line);\n if (line.empty() || line[0] == '#' || line.find(\" \") < string::npos)\n continue;\n vector tokens = SplitString(line, '=');\n if (tokens.size() < 2 || tokens.size() > 2)\n continue;\n\n ConfigValue value;\n value.source = config_file;\n value.value = tokens[1];\n string parameter = tokens[0];\n config_[parameter] = value;\n retval = setenv(parameter.c_str(), value.value.c_str(), 1);\n assert(retval == 0);\n }\n fclose(fconfig);\n}\n\n\nvoid BashOptionsManager::ParsePath(const string &config_file,\n const bool external) {\n LogCvmfs(kLogCvmfs, kLogDebug, \"Parsing config file %s\", config_file.c_str());\n int retval;\n int pipe_open[2];\n int pipe_quit[2];\n pid_t pid_child = 0;\n if (external) {\n \/\/ cvmfs can run in the process group of automount in which case\n \/\/ autofs won't mount an additional config repository. We create a\n \/\/ short-lived process that detaches from the process group and triggers\n \/\/ autofs to mount the config repository, if necessary. It holds a file\n \/\/ handle to the config file until the main process opened the file, too.\n MakePipe(pipe_open);\n MakePipe(pipe_quit);\n switch (pid_child = fork()) {\n case -1:\n abort();\n case 0: { \/\/ Child\n close(pipe_open[0]);\n close(pipe_quit[1]);\n \/\/ If this is not a process group leader, create a new session\n if (getpgrp() != getpid()) {\n pid_t new_session = setsid();\n assert(new_session != (pid_t)-1);\n }\n (void)open(config_file.c_str(), O_RDONLY);\n char ready = 'R';\n WritePipe(pipe_open[1], &ready, 1);\n read(pipe_quit[0], &ready, 1);\n _exit(0); \/\/ Don't flush shared file descriptors\n }\n }\n \/\/ Parent\n close(pipe_open[1]);\n close(pipe_quit[0]);\n char ready = 0;\n ReadPipe(pipe_open[0], &ready, 1);\n assert(ready == 'R');\n close(pipe_open[0]);\n }\n const string config_path = GetParentPath(config_file);\n FILE *fconfig = fopen(config_file.c_str(), \"r\");\n if (pid_child > 0) {\n char c = 'C';\n WritePipe(pipe_quit[1], &c, 1);\n int statloc;\n waitpid(pid_child, &statloc, 0);\n close(pipe_quit[1]);\n }\n if (!fconfig) {\n if (external && !DirectoryExists(config_path)) {\n LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogWarn,\n \"external location for configuration files does not exist: %s\",\n config_path.c_str());\n }\n return;\n }\n\n int fd_stdin;\n int fd_stdout;\n int fd_stderr;\n retval = Shell(&fd_stdin, &fd_stdout, &fd_stderr);\n assert(retval);\n\n \/\/ Let the shell read the file\n string line;\n const string newline = \"\\n\";\n const string cd = \"cd \\\"\" + ((config_path == \"\") ? \"\/\" : config_path) + \"\\\"\" +\n newline;\n WritePipe(fd_stdin, cd.data(), cd.length());\n while (GetLineFile(fconfig, &line)) {\n WritePipe(fd_stdin, line.data(), line.length());\n WritePipe(fd_stdin, newline.data(), newline.length());\n }\n rewind(fconfig);\n\n \/\/ Read line by line and extract parameters\n while (GetLineFile(fconfig, &line)) {\n line = Trim(line);\n if (line.empty() || line[0] == '#' || line.find(\"if \") == 0)\n continue;\n vector tokens = SplitString(line, '=');\n if (tokens.size() < 2)\n continue;\n\n ConfigValue value;\n value.source = config_file;\n string parameter = tokens[0];\n \/\/ Strip \"readonly\"\n if (parameter.find(\"readonly\") == 0) {\n parameter = parameter.substr(8);\n parameter = Trim(parameter);\n }\n \/\/ Strip export\n if (parameter.find(\"export\") == 0) {\n parameter = parameter.substr(6);\n parameter = Trim(parameter);\n }\n \/\/ Strip eval\n if (parameter.find(\"eval\") == 0) {\n parameter = parameter.substr(4);\n parameter = Trim(parameter);\n }\n\n const string sh_echo = \"echo $\" + parameter + \"\\n\";\n WritePipe(fd_stdin, sh_echo.data(), sh_echo.length());\n GetLineFd(fd_stdout, &value.value);\n config_[parameter] = value;\n retval = setenv(parameter.c_str(), value.value.c_str(), 1);\n assert(retval == 0);\n }\n\n close(fd_stderr);\n close(fd_stdout);\n close(fd_stdin);\n fclose(fconfig);\n}\n\n\nbool OptionsManager::HasConfigRepository(const string &fqrn,\n string *config_path) {\n string cvmfs_mount_dir;\n if (!GetValue(\"CVMFS_MOUNT_DIR\", &cvmfs_mount_dir)) {\n LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr, \"CVMFS_MOUNT_DIR missing\");\n return false;\n }\n\n string config_repository;\n if (GetValue(\"CVMFS_CONFIG_REPOSITORY\", &config_repository)) {\n if (config_repository.empty() || (config_repository == fqrn))\n return false;\n sanitizer::RepositorySanitizer repository_sanitizer;\n if (!repository_sanitizer.IsValid(config_repository)) {\n LogCvmfs(kLogCvmfs, kLogDebug | kLogSyslogErr,\n \"invalid CVMFS_CONFIG_REPOSITORY: %s\",\n config_repository.c_str());\n return false;\n }\n *config_path = cvmfs_mount_dir + \"\/\" + config_repository + \"\/etc\/cvmfs\/\";\n return true;\n }\n return false;\n}\n\n\nvoid OptionsManager::ParseDefault(const string &fqrn) {\n int retval = setenv(\"CVMFS_FQRN\", fqrn.c_str(), 1);\n assert(retval == 0);\n\n ParsePath(\"\/etc\/cvmfs\/default.conf\", false);\n vector dist_defaults = FindFiles(\"\/etc\/cvmfs\/default.d\", \".conf\");\n for (unsigned i = 0; i < dist_defaults.size(); ++i) {\n ParsePath(dist_defaults[i], false);\n }\n string external_config_path;\n if ((fqrn != \"\") && HasConfigRepository(fqrn, &external_config_path))\n ParsePath(external_config_path + \"default.conf\", true);\n ParsePath(\"\/etc\/cvmfs\/default.local\", false);\n\n if (fqrn != \"\") {\n string domain;\n vector tokens = SplitString(fqrn, '.');\n assert(tokens.size() > 1);\n tokens.erase(tokens.begin());\n domain = JoinStrings(tokens, \".\");\n\n if (HasConfigRepository(fqrn, &external_config_path))\n ParsePath(external_config_path + \"domain.d\/\" + domain + \".conf\", true);\n ParsePath(\"\/etc\/cvmfs\/domain.d\/\" + domain + \".conf\", false);\n ParsePath(\"\/etc\/cvmfs\/domain.d\/\" + domain + \".local\", false);\n\n if (HasConfigRepository(fqrn, &external_config_path))\n ParsePath(external_config_path + \"config.d\/\" + fqrn + \".conf\", true);\n ParsePath(\"\/etc\/cvmfs\/config.d\/\" + fqrn + \".conf\", false);\n ParsePath(\"\/etc\/cvmfs\/config.d\/\" + fqrn + \".local\", false);\n }\n}\n\n\nvoid OptionsManager::ClearConfig() {\n config_.clear();\n}\n\n\nbool OptionsManager::IsDefined(const std::string &key) {\n map::const_iterator iter = config_.find(key);\n return iter != config_.end();\n}\n\n\nbool OptionsManager::GetValue(const string &key, string *value) {\n map::const_iterator iter = config_.find(key);\n if (iter != config_.end()) {\n *value = iter->second.value;\n return true;\n }\n *value = \"\";\n return false;\n}\n\n\nbool OptionsManager::GetSource(const string &key, string *value) {\n map::const_iterator iter = config_.find(key);\n if (iter != config_.end()) {\n *value = iter->second.source;\n return true;\n }\n *value = \"\";\n return false;\n}\n\n\nbool OptionsManager::IsOn(const std::string ¶m_value) {\n const string uppercase = ToUpper(param_value);\n return ((uppercase == \"YES\") || (uppercase == \"ON\") || (uppercase == \"1\"));\n}\n\n\nvector OptionsManager::GetAllKeys() {\n vector result;\n for (map::const_iterator i = config_.begin(),\n iEnd = config_.end(); i != iEnd; ++i)\n {\n result.push_back(i->first);\n }\n return result;\n}\n\n\nstring OptionsManager::Dump() {\n string result;\n vector keys = GetAllKeys();\n for (unsigned i = 0, l = keys.size(); i < l; ++i) {\n bool retval;\n string value;\n string source;\n\n retval = GetValue(keys[i], &value);\n assert(retval);\n retval = GetSource(keys[i], &source);\n assert(retval);\n result += keys[i] + \"=\" + EscapeShell(value) +\n \" # from \" + source + \"\\n\";\n }\n return result;\n}\n\n#ifdef CVMFS_NAMESPACE_GUARD\n} \/\/ namespace CVMFS_NAMESPACE_GUARD\n#endif\n<|endoftext|>"} {"text":"#include \"StdAfxUnitTests.h\"\r\n#include \"DnsUnitTests.h\"\r\n\r\nCPPUNIT_TEST_SUITE_REGISTRATION(AppSecInc::UnitTests::TcpIp::DNS::DnsUnitTests);\r\n\r\nusing namespace AppSecInc::UnitTests::TcpIp::DNS;\r\n\r\nvoid DnsUnitTests::testGetHostByAddress()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR ip;\r\n\t\tLPCSTR host;\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"65.55.11.218\", \"*.codeplex.com\" }\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string host = AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i].ip);\r\n\t\tstd::cout << std::endl << testdata[i].ip << \" -> \" << host;\r\n\t\tCPPUNIT_ASSERT(host == testdata[i].host);\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostByInvalidAddress()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tLPCSTR testdata[] =\r\n\t{\r\n\t\t{ \"abcdefgh\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\r\n\t\ttry\r\n\t\t{\r\n\t\t\tAppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i]);\r\n\t\t\tthrow \"Expected std::exception\";\r\n\t\t}\r\n\t\tcatch(std::exception& ex)\r\n\t\t{\r\n\t\t\tstd::cout << std::endl << \"Expected exception for \" << testdata[i] << \": \" << ex.what();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostByName()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR ip;\r\n\t\tLPCSTR host;\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"65.55.11.218\", \"*.codeplex.com\" },\r\n\t\t{ \"www.codeplex.com\", \"lb.codeplex.com.microsoft.akadns.net\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string host = AppSecInc::TcpIp::DNS::GetHostByName(testdata[i].ip);\r\n\t\tstd::cout << std::endl << testdata[i].ip << \" -> \" << host;\r\n\t\tCPPUNIT_ASSERT(host == testdata[i].host);\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostIpAddresses()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR host;\r\n\t\tLPCSTR ip;\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"65.55.11.218\", \"65.55.11.218\" },\r\n\t\t{ \"www.codeplex.com\", \"65.55.11.218\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string ip = AppSecInc::TcpIp::DNS::GetHostIpAddresses(testdata[i].ip)[0];\r\n\t\tstd::cout << std::endl << testdata[i].host << \" -> \" << ip;\r\n\t\tCPPUNIT_ASSERT(ip == testdata[i].ip);\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostInfo()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR host;\r\n\t\tLPCSTR hostname; \/\/ expected host name\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"www.codeplex.com\", \"lb.codeplex.com.microsoft.akadns.net\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string hostname;\r\n\t\tstd::vector aliases;\r\n\t\tstd::vector addresses;\r\n\t\tAppSecInc::TcpIp::DNS::GetHostInfo(testdata[i].host, hostname, aliases, addresses);\r\n\r\n\t\tstd::cout << std::endl << testdata[i].host << \" -> \" << hostname;\r\n\t\tCPPUNIT_ASSERT(hostname == testdata[i].hostname);\r\n\r\n\t\tfor each (const std::string& alias in aliases)\r\n\t\t\tstd::cout << std::endl << \" alias: \" << alias;\r\n\r\n\t\tfor each (const std::string& address in addresses)\r\n\t\t\tstd::cout << std::endl << \" address: \" << address;\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetLocal()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tchar computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };\r\n\tDWORD size = MAX_COMPUTERNAME_LENGTH;\r\n\tCPPUNIT_ASSERT(::GetComputerNameA(computername, & size));\r\n\tstd::cout << std::endl << \"Host: \" << computername;\r\n\r\n\tstd::string tcpaddress = AppSecInc::TcpIp::DNS::GetHostIpAddresses(computername)[0];\r\n\tstd::cout << std::endl << \"Ip: \" << tcpaddress;\r\n\tCPPUNIT_ASSERT(! tcpaddress.empty());\r\n\r\n\tstd::string host = AppSecInc::TcpIp::DNS::GetHostByName(computername);\r\n\tstd::cout << std::endl << \"Host: \" << host;\r\n\tCPPUNIT_ASSERT(! host.empty());\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostName()\r\n{\r\n\twchar_t computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };\r\n\tDWORD size = MAX_COMPUTERNAME_LENGTH;\r\n\tCPPUNIT_ASSERT(::GetComputerNameW(computername, & size));\r\n\tstd::wcout << std::endl << L\"Computer: \" << computername;\r\n std::wstring hostname = AppSecInc::TcpIp::DNS::GetHostNameW();\r\n\tstd::wcout << std::endl << L\"Host: \" << hostname; \r\n CPPUNIT_ASSERT(0 == ::_wcsicmp(computername, hostname.c_str()));\r\n}\r\n\r\nvoid DnsUnitTests::testIsIpAddress()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR ip;\r\n\t\tbool isIp; \/\/ expected true\/false\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"\", false },\r\n\t\t{ \"127.0.0.1\", true },\r\n\t\t{ \"localhost\", false },\r\n\t\t{ \"0\", false },\r\n\t\t{ \"192.168.0.1\", true },\r\n\t\t{ \"10.10.10.10\", true },\r\n\t\t{ \"fe80::8081:ade5:e522:4a3c%14\", false }, \/\/ IPv6 is not supported by this function\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tbool ip = AppSecInc::TcpIp::DNS::IsIpAddress(testdata[i].ip);\r\n\t\tstd::cout << std::endl << testdata[i].ip << \" -> \" << (ip ? \"ip\" : \"not ip\");\r\n\t\tCPPUNIT_ASSERT(ip == testdata[i].isIp);\r\n\t}\r\n}Changed sample IPs in test.#include \"StdAfxUnitTests.h\"\r\n#include \"DnsUnitTests.h\"\r\n\r\nCPPUNIT_TEST_SUITE_REGISTRATION(AppSecInc::UnitTests::TcpIp::DNS::DnsUnitTests);\r\n\r\nusing namespace AppSecInc::UnitTests::TcpIp::DNS;\r\n\r\nvoid DnsUnitTests::testGetHostByAddress()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR ip;\r\n\t\tLPCSTR host;\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"207.97.227.239\", \"github.com\" }\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string host = AppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i].ip);\r\n\t\tstd::cout << std::endl << testdata[i].ip << \" -> \" << host;\r\n\t\tCPPUNIT_ASSERT(host == testdata[i].host);\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostByInvalidAddress()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tLPCSTR testdata[] =\r\n\t{\r\n\t\t{ \"abcdefgh\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\r\n\t\ttry\r\n\t\t{\r\n\t\t\tAppSecInc::TcpIp::DNS::GetHostByAddress(testdata[i]);\r\n\t\t\tthrow \"Expected std::exception\";\r\n\t\t}\r\n\t\tcatch(std::exception& ex)\r\n\t\t{\r\n\t\t\tstd::cout << std::endl << \"Expected exception for \" << testdata[i] << \": \" << ex.what();\r\n\t\t}\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostByName()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR ip;\r\n\t\tLPCSTR host;\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"207.97.227.239\", \"github.com\" },\r\n\t\t{ \"www.codeplex.com\", \"lb.codeplex.com.microsoft.akadns.net\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string host = AppSecInc::TcpIp::DNS::GetHostByName(testdata[i].ip);\r\n\t\tstd::cout << std::endl << testdata[i].ip << \" -> \" << host;\r\n\t\tCPPUNIT_ASSERT(host == testdata[i].host);\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostIpAddresses()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR host;\r\n\t\tLPCSTR ip;\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"207.97.227.239\", \"207.97.227.239\" },\r\n\t\t{ \"www.github.com\", \"207.97.227.239\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string ip = AppSecInc::TcpIp::DNS::GetHostIpAddresses(testdata[i].ip)[0];\r\n\t\tstd::cout << std::endl << testdata[i].host << \" -> \" << ip;\r\n\t\tCPPUNIT_ASSERT(ip == testdata[i].ip);\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostInfo()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR host;\r\n\t\tLPCSTR hostname; \/\/ expected host name\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"www.codeplex.com\", \"lb.codeplex.com.microsoft.akadns.net\" },\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tstd::string hostname;\r\n\t\tstd::vector aliases;\r\n\t\tstd::vector addresses;\r\n\t\tAppSecInc::TcpIp::DNS::GetHostInfo(testdata[i].host, hostname, aliases, addresses);\r\n\r\n\t\tstd::cout << std::endl << testdata[i].host << \" -> \" << hostname;\r\n\t\tCPPUNIT_ASSERT(hostname == testdata[i].hostname);\r\n\r\n\t\tfor each (const std::string& alias in aliases)\r\n\t\t\tstd::cout << std::endl << \" alias: \" << alias;\r\n\r\n\t\tfor each (const std::string& address in addresses)\r\n\t\t\tstd::cout << std::endl << \" address: \" << address;\r\n\t}\r\n}\r\n\r\nvoid DnsUnitTests::testGetLocal()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tchar computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };\r\n\tDWORD size = MAX_COMPUTERNAME_LENGTH;\r\n\tCPPUNIT_ASSERT(::GetComputerNameA(computername, & size));\r\n\tstd::cout << std::endl << \"Host: \" << computername;\r\n\r\n\tstd::string tcpaddress = AppSecInc::TcpIp::DNS::GetHostIpAddresses(computername)[0];\r\n\tstd::cout << std::endl << \"Ip: \" << tcpaddress;\r\n\tCPPUNIT_ASSERT(! tcpaddress.empty());\r\n\r\n\tstd::string host = AppSecInc::TcpIp::DNS::GetHostByName(computername);\r\n\tstd::cout << std::endl << \"Host: \" << host;\r\n\tCPPUNIT_ASSERT(! host.empty());\r\n}\r\n\r\nvoid DnsUnitTests::testGetHostName()\r\n{\r\n\twchar_t computername[MAX_COMPUTERNAME_LENGTH + 1] = { 0 };\r\n\tDWORD size = MAX_COMPUTERNAME_LENGTH;\r\n\tCPPUNIT_ASSERT(::GetComputerNameW(computername, & size));\r\n\tstd::wcout << std::endl << L\"Computer: \" << computername;\r\n std::wstring hostname = AppSecInc::TcpIp::DNS::GetHostNameW();\r\n\tstd::wcout << std::endl << L\"Host: \" << hostname; \r\n CPPUNIT_ASSERT(0 == ::_wcsicmp(computername, hostname.c_str()));\r\n}\r\n\r\nvoid DnsUnitTests::testIsIpAddress()\r\n{\r\n\tAppSecInc::TcpIp::CWSAStartup wsa;\r\n\r\n\tstruct TestData\r\n\t{\r\n\t\tLPCSTR ip;\r\n\t\tbool isIp; \/\/ expected true\/false\r\n\t};\r\n\r\n\tTestData testdata[] = \r\n\t{\r\n\t\t{ \"\", false },\r\n\t\t{ \"127.0.0.1\", true },\r\n\t\t{ \"localhost\", false },\r\n\t\t{ \"0\", false },\r\n\t\t{ \"192.168.0.1\", true },\r\n\t\t{ \"10.10.10.10\", true },\r\n\t\t{ \"fe80::8081:ade5:e522:4a3c%14\", false }, \/\/ IPv6 is not supported by this function\r\n\t};\r\n\r\n\tfor (int i = 0; i < ARRAYSIZE(testdata); i++)\r\n\t{\t\t\r\n\t\tbool ip = AppSecInc::TcpIp::DNS::IsIpAddress(testdata[i].ip);\r\n\t\tstd::cout << std::endl << testdata[i].ip << \" -> \" << (ip ? \"ip\" : \"not ip\");\r\n\t\tCPPUNIT_ASSERT(ip == testdata[i].isIp);\r\n\t}\r\n}<|endoftext|>"} {"text":"#undef isnan\n#undef isfinite\n\n#include \"kfusion.h\"\n#include \"helpers.h\"\n\n#include \n#include \n#include \n\n#include \n#include \"perfstats.h\"\n\nusing namespace std;\nusing namespace TooN;\n\n#include \n\nfreenect_context *f_ctx;\nfreenect_device *f_dev;\nbool gotDepth;\n\nvoid depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp)\n{\n gotDepth = true;\n}\n\nint InitKinect( uint16_t * buffer ){\n if (freenect_init(&f_ctx, NULL) < 0) {\n cout << \"freenect_init() failed\" << endl;\n return 1;\n }\n\n freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING);\n freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));\n\n int nr_devices = freenect_num_devices (f_ctx);\n cout << \"Number of devices found: \" << nr_devices << endl;\n\n if (nr_devices < 1)\n return 1;\n\n if (freenect_open_device(f_ctx, &f_dev, 0) < 0) {\n cout << \"Could not open device\" << endl;\n return 1;\n }\n\n freenect_set_depth_callback(f_dev, depth_cb);\n freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT));\n freenect_set_depth_buffer(f_dev, buffer);\n freenect_start_depth(f_dev);\n\n gotDepth = false;\n\n return 0;\n}\n\nvoid CloseKinect(){\n freenect_stop_depth(f_dev);\n freenect_close_device(f_dev);\n freenect_shutdown(f_ctx);\n}\n\nvoid DepthFrameKinect() {\n while (!gotDepth && freenect_process_events(f_ctx) >= 0){\n }\n gotDepth = false;\n}\n\nint main(int argc, char ** argv) {\n const float size = (argc > 1) ? atof(argv[1]) : 2.f;\n\n KFusionConfig config;\n\n \/\/ it is enough now to set the volume resolution once.\n \/\/ everything else is derived from that.\n \/\/ config.volumeSize = make_uint3(64);\n config.volumeSize = make_uint3(128);\n \/\/ config.volumeSize = make_uint3(256);\n\n \/\/ these are physical dimensions in meters\n config.volumeDimensions = make_float3(size);\n config.nearPlane = 0.4f;\n config.farPlane = 5.0f;\n config.mu = 0.1;\n config.combinedTrackAndReduce = false;\n\n config.camera = make_float4(297.12732, 296.24240, 169.89365, 121.25151);\n\n config.iterations[0] = 10;\n config.iterations[1] = 5;\n config.iterations[2] = 4;\n\n config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold;\n config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold;\n\n const uint2 imageSize = config.renderSize();\n\n CVD::GLWindow window(CVD::ImageRef(imageSize.x * 2, imageSize.y * 2));\n CVD::GLWindow::EventSummary events;\n glDisable(GL_DEPTH_TEST);\n\n KFusion kfusion;\n kfusion.Init(config);\n if(printCUDAError()){\n kfusion.Clear();\n cudaDeviceReset();\n return 1;\n }\n\n Image lightScene(imageSize), depth(imageSize), lightModel(imageSize);\n Image depthImage(make_uint2(640, 480));\n\n const float3 light = make_float3(1.0, -2, 1.0);\n const float3 ambient = make_float3(0.1, 0.1, 0.1);\n const float4 renderCamera = make_float4(297.12732, 296.24240, 169.89365+160, 121.25151);\n\n SE3 initPose(makeVector(size\/2, size\/2, 0, 0, 0, 0));\n\n kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));\n\n if(InitKinect(depthImage.data()))\n return 1;\n\n bool integrate = true;\n bool reset = true;\n\n int counter = 0;\n while(!events.should_quit()){\n glClear( GL_COLOR_BUFFER_BIT );\n const double startFrame = Stats.start();\n ++counter;\n\n DepthFrameKinect();\n const double startProcessing = Stats.sample(\"kinect\");\n\n kfusion.setKinectDeviceDepth(depthImage.getDeviceImage());\n Stats.sample(\"raw to cooked\");\n\n integrate = kfusion.Track();\n Stats.sample(\"track\");\n\n if(integrate || reset ){\n kfusion.Integrate();\n Stats.sample(\"integrate\");\n reset = false;\n }\n\n renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient);\n renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient );\n renderTrackResult( depth.getDeviceImage(), kfusion.reduction );\n cudaDeviceSynchronize();\n\n Stats.sample(\"render\");\n\n glClear( GL_COLOR_BUFFER_BIT );\n glRasterPos2i(0,imageSize.y * 0);\n glDrawPixels(lightScene);\n glRasterPos2i(imageSize.x, imageSize.y * 0);\n glDrawPixels(depth);\n glRasterPos2i(0,imageSize.y * 1);\n glDrawPixels(lightModel);\n Stats.sample(\"draw\");\n\n window.swap_buffers();\n events.clear();\n window.get_events(events);\n\n if(events.key_up.count('c')){\n kfusion.Reset();\n kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));\n reset = true;\n }\n\n if(counter % 50 == 0){\n Stats.print();\n Stats.reset();\n cout << endl;\n }\n\n if(printCUDAError())\n break;\n\n const double endProcessing = Stats.sample(\"events\");\n Stats.sample(\"total\", endProcessing - startFrame, PerfStats::TIME);\n Stats.sample(\"total_proc\", endProcessing - startProcessing, PerfStats::TIME);\n }\n\n CloseKinect();\n kfusion.Clear();\n\n cudaDeviceReset();\n return 0;\n}\nvectors instead of arrays, to make config copyable etc and everything more flexible, missed a file#undef isnan\n#undef isfinite\n\n#include \"kfusion.h\"\n#include \"helpers.h\"\n\n#include \n#include \n#include \n\n#include \n#include \"perfstats.h\"\n\nusing namespace std;\nusing namespace TooN;\n\n#include \n\nfreenect_context *f_ctx;\nfreenect_device *f_dev;\nbool gotDepth;\n\nvoid depth_cb(freenect_device *dev, void *v_depth, uint32_t timestamp)\n{\n gotDepth = true;\n}\n\nint InitKinect( uint16_t * buffer ){\n if (freenect_init(&f_ctx, NULL) < 0) {\n cout << \"freenect_init() failed\" << endl;\n return 1;\n }\n\n freenect_set_log_level(f_ctx, FREENECT_LOG_WARNING);\n freenect_select_subdevices(f_ctx, (freenect_device_flags)(FREENECT_DEVICE_MOTOR | FREENECT_DEVICE_CAMERA));\n\n int nr_devices = freenect_num_devices (f_ctx);\n cout << \"Number of devices found: \" << nr_devices << endl;\n\n if (nr_devices < 1)\n return 1;\n\n if (freenect_open_device(f_ctx, &f_dev, 0) < 0) {\n cout << \"Could not open device\" << endl;\n return 1;\n }\n\n freenect_set_depth_callback(f_dev, depth_cb);\n freenect_set_depth_mode(f_dev, freenect_find_depth_mode(FREENECT_RESOLUTION_MEDIUM, FREENECT_DEPTH_11BIT));\n freenect_set_depth_buffer(f_dev, buffer);\n freenect_start_depth(f_dev);\n\n gotDepth = false;\n\n return 0;\n}\n\nvoid CloseKinect(){\n freenect_stop_depth(f_dev);\n freenect_close_device(f_dev);\n freenect_shutdown(f_ctx);\n}\n\nvoid DepthFrameKinect() {\n while (!gotDepth && freenect_process_events(f_ctx) >= 0){\n }\n gotDepth = false;\n}\n\nint main(int argc, char ** argv) {\n const float size = (argc > 1) ? atof(argv[1]) : 2.f;\n\n KFusionConfig config;\n\n \/\/ it is enough now to set the volume resolution once.\n \/\/ everything else is derived from that.\n \/\/ config.volumeSize = make_uint3(64);\n config.volumeSize = make_uint3(128);\n \/\/ config.volumeSize = make_uint3(256);\n\n \/\/ these are physical dimensions in meters\n config.volumeDimensions = make_float3(size);\n config.nearPlane = 0.4f;\n config.farPlane = 5.0f;\n config.mu = 0.1;\n config.combinedTrackAndReduce = false;\n\n config.camera = make_float4(297.12732, 296.24240, 169.89365, 121.25151);\n\n \/\/ config.iterations is a vector, the length determines\n \/\/ the number of levels to be used in tracking\n \/\/ push back more then 3 iteraton numbers to get more levels.\n config.iterations[0] = 10;\n config.iterations[1] = 5;\n config.iterations[2] = 4;\n\n config.dist_threshold = (argc > 2 ) ? atof(argv[2]) : config.dist_threshold;\n config.normal_threshold = (argc > 3 ) ? atof(argv[3]) : config.normal_threshold;\n\n const uint2 imageSize = config.renderSize();\n\n CVD::GLWindow window(CVD::ImageRef(imageSize.x * 2, imageSize.y * 2));\n CVD::GLWindow::EventSummary events;\n glDisable(GL_DEPTH_TEST);\n\n KFusion kfusion;\n kfusion.Init(config);\n if(printCUDAError()){\n kfusion.Clear();\n cudaDeviceReset();\n return 1;\n }\n\n Image lightScene(imageSize), depth(imageSize), lightModel(imageSize);\n Image depthImage(make_uint2(640, 480));\n\n const float3 light = make_float3(1.0, -2, 1.0);\n const float3 ambient = make_float3(0.1, 0.1, 0.1);\n const float4 renderCamera = make_float4(297.12732, 296.24240, 169.89365+160, 121.25151);\n\n SE3 initPose(makeVector(size\/2, size\/2, 0, 0, 0, 0));\n\n kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));\n\n if(InitKinect(depthImage.data()))\n return 1;\n\n bool integrate = true;\n bool reset = true;\n\n int counter = 0;\n while(!events.should_quit()){\n glClear( GL_COLOR_BUFFER_BIT );\n const double startFrame = Stats.start();\n ++counter;\n\n DepthFrameKinect();\n const double startProcessing = Stats.sample(\"kinect\");\n\n kfusion.setKinectDeviceDepth(depthImage.getDeviceImage());\n Stats.sample(\"raw to cooked\");\n\n integrate = kfusion.Track();\n Stats.sample(\"track\");\n\n if(integrate || reset ){\n kfusion.Integrate();\n Stats.sample(\"integrate\");\n reset = false;\n }\n\n renderLight( lightModel.getDeviceImage(), kfusion.vertex, kfusion.normal, light, ambient);\n renderLight( lightScene.getDeviceImage(), kfusion.inputVertex[0], kfusion.inputNormal[0], light, ambient );\n renderTrackResult( depth.getDeviceImage(), kfusion.reduction );\n cudaDeviceSynchronize();\n\n Stats.sample(\"render\");\n\n glClear( GL_COLOR_BUFFER_BIT );\n glRasterPos2i(0,imageSize.y * 0);\n glDrawPixels(lightScene);\n glRasterPos2i(imageSize.x, imageSize.y * 0);\n glDrawPixels(depth);\n glRasterPos2i(0,imageSize.y * 1);\n glDrawPixels(lightModel);\n Stats.sample(\"draw\");\n\n window.swap_buffers();\n events.clear();\n window.get_events(events);\n\n if(events.key_up.count('c')){\n kfusion.Reset();\n kfusion.setPose(toMatrix4(initPose), toMatrix4(initPose.inverse()));\n reset = true;\n }\n\n if(counter % 50 == 0){\n Stats.print();\n Stats.reset();\n cout << endl;\n }\n\n if(printCUDAError())\n break;\n\n const double endProcessing = Stats.sample(\"events\");\n Stats.sample(\"total\", endProcessing - startFrame, PerfStats::TIME);\n Stats.sample(\"total_proc\", endProcessing - startProcessing, PerfStats::TIME);\n }\n\n CloseKinect();\n kfusion.Clear();\n\n cudaDeviceReset();\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (C) \n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\n*\/\n\n#include \"componentprivate.h\"\n\nusing namespace Gluon;\n\nComponentPrivate::ComponentPrivate()\n{\n}\n\nComponentPrivate::ComponentPrivate(const ComponentPrivate &other)\n : QSharedData(other)\n{\n}\n\nComponentPrivate::~ComponentPrivate()\n{\n}\nInitialize variables\/*\n\nCopyright (C) \n\nThis program is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program. If not, see .\n\n*\/\n\n#include \"componentprivate.h\"\n\nusing namespace Gluon;\n\nComponentPrivate::ComponentPrivate()\n{\n enabled = true;\n gameObject = 0;\n}\n\nComponentPrivate::ComponentPrivate(const ComponentPrivate &other)\n : QSharedData(other)\n , enabled(other.enabled)\n , gameObject(other.gameObject)\n{\n}\n\nComponentPrivate::~ComponentPrivate()\n{\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2017 Rene Herthel\n *\n * This file is subject to the terms and conditions of the MIT License.\n * See the file LICENSE in the top level directory for more details.\n *\/\n\n\/**\n * @ingroup error_handler\n * @{\n *\n * @brief Function declaration of the ErrorHandler.\n *\n * @author Rene Herthel \n *\/\n\n#include \"ErrorHandler.h\"\n\n#include \"DistanceObservable.h\"\n#include \"DistanceEnum.h\"\n#include \"Signals.h\"\n#include \"CodeDefinition.h\"\n#include \"SerialProtocoll.h\"\n#include \"Signals.h\"\n\n#include \nusing namespace std;\nusing namespace HAL;\n\nErrorHandler::ErrorHandler( int chid,\n ConveyorBeltService *conveyorBeltService,\n LightSystemService *lightSystemService,\n SerialService *serialService,\n PuckManager *puckManager)\n : m_hasError(false)\n , m_resetPressed(false)\n , m_conveyorBeltService(conveyorBeltService)\n , m_lightSystemService(lightSystemService)\n\t, \t m_serialService(serialService)\n\t, \t m_puckManager(puckManager)\n{\n m_lightSystemService->setWarningLevel(Level::OPERATING);\n}\n\nErrorHandler::~ErrorHandler()\n{\n \/\/ Nothing todo so far.\n}\n\nvoid ErrorHandler::process(PuckManager::ManagerReturn &manager)\n{\n\tLOG_DEBUG << \"[ErrorHandler] Demux Manager return \\n\";\n\tLOG_DEBUG << \"[ErrorHandler] Actor Flag \" << manager.actorFlag << \" actorSignal \" << (int)manager.actorSignal << \"\\n\";\n\n\t\/\/if slide full return a warning\n\tif (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_FULL){\n\t\t m_lightSystemService->setWarningLevel(Level::WARNING_OCCURED);\n\t\t LOG_DEBUG << \"[ErrorHandler] Slide is full \\n\";\n\t}\n\tif (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_EMPTY){\n\t\t m_lightSystemService->setWarningLevel(Level::CLEAR_WARNING);\n\t\t m_lightSystemService->setWarningLevel(Level::OPERATING);\n\t\t LOG_DEBUG << \"[ErrorHandler] Slide is empty \\n\";\n\t}\n\n\t\/\/Only handle when error code\n if (manager.errorFlag) {\n\t\tm_hasError = true;\n\n\t\tm_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);\n\n\t\tDistanceObservable &distO = DistanceObservable::getInstance();\n\t\tdistO.updateSpeed(DistanceSpeed::STOP);\n\n\t\tm_conveyorBeltService->changeState(ConveyorBeltState::STOP);\n\t\tm_serialService->sendMsg(Serial_n::ser_proto_msg::STOP_SER);\n\n\t\tswitch (manager.errorSignal) {\n\n\t\t\tcase PuckManager::ErrorSignal::PUCK_LOST:\n\t\t\t\tcout << \"[ErrorHandler] PUCK_LOST - Late Timer\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] PUCK_LOST - Late Timer\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::PUCK_MOVED:\n\t\t\t\tcout << \"[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::UNEXPECTED_SIGNAL:\n\t\t\t\tcout << \"[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::MULTIPLE_ACCEPT:\n\t\t\t\tcout << \"[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::MULTIPLE_WARNING:\n\t\t\t\tcout << \"[ErrorHandler] MULTIPLE_WARNING\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] MULTIPLE_WARNING\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::BOTH_SLIDES_FULL:\n\t\t\t\tcout << \"[ErrorHandler] BOTH_SLIDES_FULL\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] BOTH_SLIDES_FULL\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\t LOG_DEBUG << \"[ErrorHandler] Unkown Error !!!\" << endl;\n\t\t\t\tbreak;\n\t\t}\n }\n}\n\n\nbool ErrorHandler::hasError()\n{\n\tLOG_DEBUG << \"[ErrorHandler] Error: \" << m_hasError << \"\\n\";\n return m_hasError;\n}\n\nvoid ErrorHandler::handleEvent(rcv::msg_t event)\n{\n\tLOG_DEBUG << \"[ErrorHandler] Trying to demux \" << event.code << \" \" << event.value << \"\\n\";\n\tswitch(event.code){\n\t\tcase CodeDefinition::SER_IN :\n\t\t\tif( event.value == Serial_n::ser_proto_msg::ESTOP_SER ||\n\t\t\t\tevent.value == Serial_n::ser_proto_msg::ERROR_SER ||\n\t\t\t\tevent.value == Serial_n::ser_proto_msg::NO_CON_SER ){\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] Got error from serial \\n\";\n\t\t\t\tm_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);\n\t\t\t\tm_conveyorBeltService->changeState(ConveyorBeltState::STOP);\n\t\t\t\tm_hasError = true;\n\t\t\t\tm_resetPressed = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CodeDefinition::ISR :\n\t\t\tif(event.value == interrupts::BUTTON_ESTOP_IN){\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] Got Estop from ISR \\n\";\n\t\t\t\tm_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);\n\t\t\t\tm_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER);\n\t\t\t\tm_conveyorBeltService->changeState(ConveyorBeltState::STOP);\n\t\t\t\tm_hasError = true;\n\t\t\t\tm_resetPressed = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault :\n\t\t\t\/\/Nothing to do\n\t\t\tbreak;\n\t}\n\n\tif(m_hasError){\n\t\t \t bool buttonReset = false;\n\t\t bool buttonStart = false;\n\n\t\t if (event.code != 5) { \/\/ 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine\n\t\t return; \/\/ Do not do anything without code 5!\n\t\t }\n\n\t\t switch(event.value) {\n\n\t\t case interrupts::BUTTON_RESET:\n\t\t buttonReset = true;\n\t\t break;\n\n\t\t case interrupts::BUTTON_START:\n\t\t buttonStart = true;\n\t\t break;\n\n\t\t default:\n\t\t \/\/ Nothing todo so far.\n\t\t break;\n\t\t }\n\n\t\t if (buttonReset && m_hasError) {\n\t\t m_resetPressed = true;\n\t\t cout << \"Error acknowledged\" << endl;\n\t\t m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED);\n\t\t } else if (buttonStart && m_resetPressed && m_hasError) { \/\/ Only go further when reset was pressed before.\n\t\t \tm_puckManager->reset();\n\t\t\t\tcout << \"Clear error\" << endl;\n\t\t\t\tm_lightSystemService->setWarningLevel(Level::OPERATING);\n\t\t\t\tm_resetPressed = false;\n\t\t\t\tm_hasError = false;\n\t\t }\n\t}\n}\n\n\/** @} *\/\nErrorHandler Distributes signals now\/*\n * Copyright (C) 2017 Rene Herthel\n *\n * This file is subject to the terms and conditions of the MIT License.\n * See the file LICENSE in the top level directory for more details.\n *\/\n\n\/**\n * @ingroup error_handler\n * @{\n *\n * @brief Function declaration of the ErrorHandler.\n *\n * @author Rene Herthel \n *\/\n\n#include \"ErrorHandler.h\"\n\n#include \"DistanceObservable.h\"\n#include \"DistanceEnum.h\"\n#include \"Signals.h\"\n#include \"CodeDefinition.h\"\n#include \"SerialProtocoll.h\"\n#include \"Signals.h\"\n\n#include \nusing namespace std;\nusing namespace HAL;\n\nErrorHandler::ErrorHandler( int chid,\n ConveyorBeltService *conveyorBeltService,\n LightSystemService *lightSystemService,\n SerialService *serialService,\n PuckManager *puckManager)\n : m_hasError(false)\n , m_resetPressed(false)\n , m_conveyorBeltService(conveyorBeltService)\n , m_lightSystemService(lightSystemService)\n\t, \t m_serialService(serialService)\n\t, \t m_puckManager(puckManager)\n{\n m_lightSystemService->setWarningLevel(Level::OPERATING);\n}\n\nErrorHandler::~ErrorHandler()\n{\n \/\/ Nothing todo so far.\n}\n\nvoid ErrorHandler::process(PuckManager::ManagerReturn &manager)\n{\n\tLOG_DEBUG << \"[ErrorHandler] Demux Manager return \\n\";\n\tLOG_DEBUG << \"[ErrorHandler] Actor Flag \" << manager.actorFlag << \" actorSignal \" << (int)manager.actorSignal << \"\\n\";\n\n\t\/\/if slide full return a warning\n\tif (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_FULL){\n\t\t m_lightSystemService->setWarningLevel(Level::WARNING_OCCURED);\n\t\t LOG_DEBUG << \"[ErrorHandler] Slide is full \\n\";\n\t}\n\tif (manager.actorFlag && manager.actorSignal == PuckManager::ActorSignal::SEND_SLIDE_EMPTY){\n\t\t m_lightSystemService->setWarningLevel(Level::CLEAR_WARNING);\n\t\t m_lightSystemService->setWarningLevel(Level::OPERATING);\n\t\t LOG_DEBUG << \"[ErrorHandler] Slide is empty \\n\";\n\t}\n\n\t\/\/Only handle when error code\n if (manager.errorFlag) {\n\t\tm_hasError = true;\n\n\t\tm_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);\n\n\t\tDistanceObservable &distO = DistanceObservable::getInstance();\n\t\tdistO.updateSpeed(DistanceSpeed::STOP);\n\n\t\tm_conveyorBeltService->changeState(ConveyorBeltState::STOP);\n\t\tm_serialService->sendMsg(Serial_n::ser_proto_msg::STOP_SER);\n\n\t\tswitch (manager.errorSignal) {\n\n\t\t\tcase PuckManager::ErrorSignal::PUCK_LOST:\n\t\t\t\tcout << \"[ErrorHandler] PUCK_LOST - Late Timer\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] PUCK_LOST - Late Timer\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::PUCK_MOVED:\n\t\t\t\tcout << \"[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] PUCK_MOVED - Puck triggered light barrier before early timer\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::UNEXPECTED_SIGNAL:\n\t\t\t\tcout << \"[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] UNEXPECTED_SIGNAL - Signal could not be processed\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::MULTIPLE_ACCEPT:\n\t\t\t\tcout << \"[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] MULTIPLE_ACCEPT - Shouldn't happen - multiple pucks were triggered\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tcase PuckManager::ErrorSignal::MULTIPLE_WARNING:\n\t\t\t\tcout << \"[ErrorHandler] MULTIPLE_WARNING\" << endl;\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] MULTIPLE_WARNING\" << endl;\n\t\t\t\tbreak;\n\n\t\t\tdefault:\n\t\t\t\t LOG_DEBUG << \"[ErrorHandler] Unkown Error !!!\" << endl;\n\t\t\t\tbreak;\n\t\t}\n }\n}\n\n\nbool ErrorHandler::hasError()\n{\n\tLOG_DEBUG << \"[ErrorHandler] Error: \" << m_hasError << \"\\n\";\n return m_hasError;\n}\n\nvoid ErrorHandler::handleEvent(rcv::msg_t event)\n{\n\tLOG_DEBUG << \"[ErrorHandler] Trying to demux \" << event.code << \" \" << event.value << \"\\n\";\n\tswitch(event.code){\n\t\tcase CodeDefinition::SER_IN :\n\t\t\tif( event.value == Serial_n::ser_proto_msg::ESTOP_SER ||\n\t\t\t\tevent.value == Serial_n::ser_proto_msg::ERROR_SER ||\n\t\t\t\tevent.value == Serial_n::ser_proto_msg::NO_CON_SER ){\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] Got error from serial \\n\";\n\t\t\t\tm_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);\n\t\t\t\tm_conveyorBeltService->changeState(ConveyorBeltState::STOP);\n\t\t\t\tm_hasError = true;\n\t\t\t\tm_resetPressed = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tcase CodeDefinition::ISR :\n\t\t\tif(event.value == interrupts::BUTTON_ESTOP_IN){\n\t\t\t\tLOG_DEBUG << \"[ErrorHandler] Got Estop from ISR \\n\";\n\t\t\t\tm_lightSystemService->setWarningLevel(Level::ERROR_OCCURED);\n\t\t\t\tm_serialService->sendMsg(Serial_n::ser_proto_msg::ESTOP_SER);\n\t\t\t\tm_conveyorBeltService->changeState(ConveyorBeltState::STOP);\n\t\t\t\tm_hasError = true;\n\t\t\t\tm_resetPressed = false;\n\t\t\t}\n\t\t\tbreak;\n\t\tdefault :\n\t\t\t\/\/Nothing to do\n\t\t\tbreak;\n\t}\n\n\tif(m_hasError){\n\t\t \tbool buttonReset = false;\n\t\t bool buttonStart = false;\n\n\t\t if (event.code != 5) { \/\/ 5 is hardcoded in the ISR. TODO Serial signal needs to get through when error is acknowledged on other machine\n\t\t return; \/\/ Do not do anything without code 5!\n\t\t }\n\n\t\t switch(event.value) {\n\n\t\t case interrupts::BUTTON_RESET:\n\t\t buttonReset = true;\n\t\t break;\n\n\t\t case interrupts::BUTTON_START:\n\t\t buttonStart = true;\n\t\t break;\n\n\t\t case interrupts::SLIDE_OUT:\n\t\t \tPuckSignal::Signal signal;\n\t\t \tsignal.signalType = PuckSignal::SignalType::INTERRUPT_SIGNAL;\n\t\t \tsignal.interruptSignal = event.value;\n\t\t \tm_puckManager->process(signal);\n\t\t \tbreak;\n\t\t default:\n\t\t \/\/ Nothing todo so far.\n\t\t break;\n\t\t }\n\n\t\t if (buttonReset && m_hasError) {\n\t\t m_resetPressed = true;\n\t\t cout << \"Error acknowledged\" << endl;\n\t\t m_lightSystemService->setWarningLevel(Level::ERROR_ACKNOWLEDGED);\n\t\t } else if (buttonStart && m_resetPressed && m_hasError) { \/\/ Only go further when reset was pressed before.\n\t\t \tm_puckManager->reset();\n\t\t\t\tcout << \"Clear error\" << endl;\n\t\t\t\tm_lightSystemService->setWarningLevel(Level::OPERATING);\n\t\t\t\tm_resetPressed = false;\n\t\t\t\tm_hasError = false;\n\t\t }\n\t}\n}\n\n\/** @} *\/\n<|endoftext|>"} {"text":"\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkColorMatrixFilter.h\"\n#include \"SkColorMatrix.h\"\n#include \"SkColorPriv.h\"\n#include \"SkUnPreMultiply.h\"\n\nstatic int32_t rowmul4(const int32_t array[], unsigned r, unsigned g,\n unsigned b, unsigned a) {\n return array[0] * r + array[1] * g + array[2] * b + array[3] * a + array[4];\n}\n\nstatic int32_t rowmul3(const int32_t array[], unsigned r, unsigned g,\n unsigned b) {\n return array[0] * r + array[1] * g + array[2] * b + array[4];\n}\n\nstatic void General(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul4(&array[0], r, g, b, a) >> shift;\n result[1] = rowmul4(&array[5], r, g, b, a) >> shift;\n result[2] = rowmul4(&array[10], r, g, b, a) >> shift;\n result[3] = rowmul4(&array[15], r, g, b, a) >> shift;\n}\n\nstatic void General16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul4(&array[0], r, g, b, a) >> 16;\n result[1] = rowmul4(&array[5], r, g, b, a) >> 16;\n result[2] = rowmul4(&array[10], r, g, b, a) >> 16;\n result[3] = rowmul4(&array[15], r, g, b, a) >> 16;\n}\n\nstatic void AffineAdd(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul3(&array[0], r, g, b) >> shift;\n result[1] = rowmul3(&array[5], r, g, b) >> shift;\n result[2] = rowmul3(&array[10], r, g, b) >> shift;\n result[3] = a;\n}\n\nstatic void AffineAdd16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul3(&array[0], r, g, b) >> 16;\n result[1] = rowmul3(&array[5], r, g, b) >> 16;\n result[2] = rowmul3(&array[10], r, g, b) >> 16;\n result[3] = a;\n}\n\nstatic void ScaleAdd(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n \/\/ cast to (int) to keep the expression signed for the shift\n result[0] = (array[0] * (int)r + array[4]) >> shift;\n result[1] = (array[6] * (int)g + array[9]) >> shift;\n result[2] = (array[12] * (int)b + array[14]) >> shift;\n result[3] = a;\n}\n\nstatic void ScaleAdd16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n \/\/ cast to (int) to keep the expression signed for the shift\n result[0] = (array[0] * (int)r + array[4]) >> 16;\n result[1] = (array[6] * (int)g + array[9]) >> 16;\n result[2] = (array[12] * (int)b + array[14]) >> 16;\n result[3] = a;\n}\n\nstatic void Add(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = r + (array[4] >> shift);\n result[1] = g + (array[9] >> shift);\n result[2] = b + (array[14] >> shift);\n result[3] = a;\n}\n\nstatic void Add16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = r + (array[4] >> 16);\n result[1] = g + (array[9] >> 16);\n result[2] = b + (array[14] >> 16);\n result[3] = a;\n}\n\n#define kNO_ALPHA_FLAGS (SkColorFilter::kAlphaUnchanged_Flag | \\\n SkColorFilter::kHasFilter16_Flag)\n\n\/\/ src is [20] but some compilers won't accept __restrict__ on anything\n\/\/ but an raw pointer or reference\nvoid SkColorMatrixFilter::setup(const SkScalar* SK_RESTRICT src) {\n if (NULL == src) {\n fProc = NULL; \/\/ signals identity\n fFlags = kNO_ALPHA_FLAGS;\n \/\/ fState is undefined, but that is OK, since we shouldn't look at it\n return;\n }\n\n int32_t* SK_RESTRICT array = fState.fArray;\n\n int i;\n SkFixed max = 0;\n\n for (int i = 0; i < 20; i++) {\n SkFixed value = SkScalarToFixed(src[i]);\n array[i] = value;\n value = SkAbs32(value);\n max = SkMax32(max, value);\n }\n\n \/* All of fArray[] values must fit in 23 bits, to safely allow me to\n multiply them by 8bit unsigned values, and get a signed answer without\n overflow. This means clz needs to be 9 or bigger\n *\/\n int bits = SkCLZ(max);\n int32_t one = SK_Fixed1;\n\n fState.fShift = 16; \/\/ we are starting out as fixed 16.16\n if (bits < 9) {\n bits = 9 - bits;\n fState.fShift -= bits;\n for (i = 0; i < 20; i++) {\n array[i] >>= bits;\n }\n one >>= bits;\n }\n\n \/\/ check if we have to munge Alpha\n int32_t changesAlpha = (array[15] | array[16] | array[17] |\n (array[18] - one) | array[19]);\n int32_t usesAlpha = (array[3] | array[8] | array[13]);\n bool shiftIs16 = (16 == fState.fShift);\n\n if (changesAlpha | usesAlpha) {\n fProc = shiftIs16 ? General16 : General;\n fFlags = changesAlpha ? 0 : SkColorFilter::kAlphaUnchanged_Flag;\n } else {\n fFlags = kNO_ALPHA_FLAGS;\n\n int32_t needsScale = (array[0] - one) | \/\/ red axis\n (array[6] - one) | \/\/ green axis\n (array[12] - one); \/\/ blue axis\n\n int32_t needs3x3 = array[1] | array[2] | \/\/ red off-axis\n array[5] | array[7] | \/\/ green off-axis\n array[10] | array[11]; \/\/ blue off-axis\n\n if (needs3x3) {\n fProc = shiftIs16 ? AffineAdd16 : AffineAdd;\n } else if (needsScale) {\n fProc = shiftIs16 ? ScaleAdd16 : ScaleAdd;\n } else if (array[4] | array[9] | array[14]) { \/\/ needs add\n fProc = shiftIs16 ? Add16 : Add;\n } else {\n fProc = NULL; \/\/ identity\n }\n }\n\n \/* preround our add values so we get a rounded shift. We do this after we\n analyze the array, so we don't miss the case where the caller has zeros\n which could make us accidentally take the General or Add case.\n *\/\n if (NULL != fProc) {\n int32_t add = 1 << (fState.fShift - 1);\n array[4] += add;\n array[9] += add;\n array[14] += add;\n array[19] += add;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int32_t pin(int32_t value, int32_t max) {\n if (value < 0) {\n value = 0;\n }\n if (value > max) {\n value = max;\n }\n return value;\n}\n\nSkColorMatrixFilter::SkColorMatrixFilter() {\n this->setup(NULL);\n}\n\nSkColorMatrixFilter::SkColorMatrixFilter(const SkColorMatrix& cm) {\n this->setup(cm.fMat);\n}\n\nSkColorMatrixFilter::SkColorMatrixFilter(const SkScalar array[20]) {\n this->setup(array);\n}\n\nuint32_t SkColorMatrixFilter::getFlags() {\n return this->INHERITED::getFlags() | fFlags;\n}\n\nvoid SkColorMatrixFilter::filterSpan(const SkPMColor src[], int count,\n SkPMColor dst[]) {\n Proc proc = fProc;\n State* state = &fState;\n int32_t* SK_RESTRICT result = state->fResult;\n\n if (NULL == proc) {\n if (src != dst) {\n memcpy(dst, src, count * sizeof(SkPMColor));\n }\n return;\n }\n\n const SkUnPreMultiply::Scale* table = SkUnPreMultiply::GetScaleTable();\n\n for (int i = 0; i < count; i++) {\n SkPMColor c = src[i];\n\n unsigned r = SkGetPackedR32(c);\n unsigned g = SkGetPackedG32(c);\n unsigned b = SkGetPackedB32(c);\n unsigned a = SkGetPackedA32(c);\n\n \/\/ need our components to be un-premultiplied\n if (255 != a) {\n SkUnPreMultiply::Scale scale = table[a];\n r = SkUnPreMultiply::ApplyScale(scale, r);\n g = SkUnPreMultiply::ApplyScale(scale, g);\n b = SkUnPreMultiply::ApplyScale(scale, b);\n\n SkASSERT(r <= 255);\n SkASSERT(g <= 255);\n SkASSERT(b <= 255);\n }\n\n proc(state, r, g, b, a);\n\n r = pin(result[0], SK_R32_MASK);\n g = pin(result[1], SK_G32_MASK);\n b = pin(result[2], SK_B32_MASK);\n a = pin(result[3], SK_A32_MASK);\n \/\/ re-prepremultiply if needed\n if (255 != a) {\n int scale = SkAlpha255To256(a);\n r = SkAlphaMul(r, scale);\n g = SkAlphaMul(g, scale);\n b = SkAlphaMul(b, scale);\n }\n dst[i] = SkPackARGB32(a, r, g, b);\n }\n}\n\nvoid SkColorMatrixFilter::filterSpan16(const uint16_t src[], int count,\n uint16_t dst[]) {\n SkASSERT(fFlags & SkColorFilter::kHasFilter16_Flag);\n\n Proc proc = fProc;\n State* state = &fState;\n int32_t* SK_RESTRICT result = state->fResult;\n\n if (NULL == proc) {\n if (src != dst) {\n memcpy(dst, src, count * sizeof(uint16_t));\n }\n return;\n }\n\n for (int i = 0; i < count; i++) {\n uint16_t c = src[i];\n\n \/\/ expand to 8bit components (since our matrix translate is 8bit biased\n unsigned r = SkPacked16ToR32(c);\n unsigned g = SkPacked16ToG32(c);\n unsigned b = SkPacked16ToB32(c);\n\n proc(state, r, g, b, 0);\n\n r = pin(result[0], SK_R32_MASK);\n g = pin(result[1], SK_G32_MASK);\n b = pin(result[2], SK_B32_MASK);\n\n \/\/ now packed it back down to 16bits (hmmm, could dither...)\n dst[i] = SkPack888ToRGB16(r, g, b);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkColorMatrixFilter::flatten(SkFlattenableWriteBuffer& buffer) {\n this->INHERITED::flatten(buffer);\n\n buffer.writeFunctionPtr((void*)fProc);\n buffer.writeMul4(&fState, sizeof(fState));\n buffer.write32(fFlags);\n}\n\nSkFlattenable::Factory SkColorMatrixFilter::getFactory() { return CreateProc; }\n\nSkColorMatrixFilter::SkColorMatrixFilter(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer) {\n fProc = (Proc)buffer.readFunctionPtr();\n buffer.read(&fState, sizeof(fState));\n fFlags = buffer.readU32();\n}\n\nbool SkColorMatrixFilter::asColorMatrix(SkScalar matrix[20]) {\n int32_t* SK_RESTRICT array = fState.fArray;\n int unshift = 16 - fState.fShift;\n for (int i = 0; i < 20; i++) {\n matrix[i] = SkFixedToScalar(array[i] << unshift);\n }\n if (NULL != fProc) {\n \/\/ Undo the offset applied to the constant column in setup().\n SkFixed offset = 1 << (fState.fShift - 1);\n matrix[4] = SkFixedToScalar((array[4] - offset) << unshift);\n matrix[9] = SkFixedToScalar((array[9] - offset) << unshift);\n matrix[14] = SkFixedToScalar((array[14] - offset) << unshift);\n matrix[19] = SkFixedToScalar((array[19] - offset) << unshift);\n }\n return true;\n}\n\nSkFlattenable* SkColorMatrixFilter::CreateProc(SkFlattenableReadBuffer& buf) {\n return SkNEW_ARGS(SkColorMatrixFilter, (buf));\n}\n\nvoid SkColorMatrixFilter::setMatrix(const SkColorMatrix& matrix) {\n setup(matrix.fMat);\n}\n\nvoid SkColorMatrixFilter::setArray(const SkScalar array[20]) {\n setup(array);\n}\n\nSK_DEFINE_FLATTENABLE_REGISTRAR(SkColorMatrixFilter)\nImprove the quality of color matrix filters by using SkPremultiplyARGBInline. This is closer (but not exactly the same as) WebKit's implementation.\n\/*\n * Copyright 2011 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n#include \"SkColorMatrixFilter.h\"\n#include \"SkColorMatrix.h\"\n#include \"SkColorPriv.h\"\n#include \"SkUnPreMultiply.h\"\n\nstatic int32_t rowmul4(const int32_t array[], unsigned r, unsigned g,\n unsigned b, unsigned a) {\n return array[0] * r + array[1] * g + array[2] * b + array[3] * a + array[4];\n}\n\nstatic int32_t rowmul3(const int32_t array[], unsigned r, unsigned g,\n unsigned b) {\n return array[0] * r + array[1] * g + array[2] * b + array[4];\n}\n\nstatic void General(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul4(&array[0], r, g, b, a) >> shift;\n result[1] = rowmul4(&array[5], r, g, b, a) >> shift;\n result[2] = rowmul4(&array[10], r, g, b, a) >> shift;\n result[3] = rowmul4(&array[15], r, g, b, a) >> shift;\n}\n\nstatic void General16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul4(&array[0], r, g, b, a) >> 16;\n result[1] = rowmul4(&array[5], r, g, b, a) >> 16;\n result[2] = rowmul4(&array[10], r, g, b, a) >> 16;\n result[3] = rowmul4(&array[15], r, g, b, a) >> 16;\n}\n\nstatic void AffineAdd(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul3(&array[0], r, g, b) >> shift;\n result[1] = rowmul3(&array[5], r, g, b) >> shift;\n result[2] = rowmul3(&array[10], r, g, b) >> shift;\n result[3] = a;\n}\n\nstatic void AffineAdd16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = rowmul3(&array[0], r, g, b) >> 16;\n result[1] = rowmul3(&array[5], r, g, b) >> 16;\n result[2] = rowmul3(&array[10], r, g, b) >> 16;\n result[3] = a;\n}\n\nstatic void ScaleAdd(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n \/\/ cast to (int) to keep the expression signed for the shift\n result[0] = (array[0] * (int)r + array[4]) >> shift;\n result[1] = (array[6] * (int)g + array[9]) >> shift;\n result[2] = (array[12] * (int)b + array[14]) >> shift;\n result[3] = a;\n}\n\nstatic void ScaleAdd16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n \/\/ cast to (int) to keep the expression signed for the shift\n result[0] = (array[0] * (int)r + array[4]) >> 16;\n result[1] = (array[6] * (int)g + array[9]) >> 16;\n result[2] = (array[12] * (int)b + array[14]) >> 16;\n result[3] = a;\n}\n\nstatic void Add(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n const int shift = state->fShift;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = r + (array[4] >> shift);\n result[1] = g + (array[9] >> shift);\n result[2] = b + (array[14] >> shift);\n result[3] = a;\n}\n\nstatic void Add16(SkColorMatrixFilter::State* state,\n unsigned r, unsigned g, unsigned b, unsigned a) {\n const int32_t* SK_RESTRICT array = state->fArray;\n int32_t* SK_RESTRICT result = state->fResult;\n\n result[0] = r + (array[4] >> 16);\n result[1] = g + (array[9] >> 16);\n result[2] = b + (array[14] >> 16);\n result[3] = a;\n}\n\n#define kNO_ALPHA_FLAGS (SkColorFilter::kAlphaUnchanged_Flag | \\\n SkColorFilter::kHasFilter16_Flag)\n\n\/\/ src is [20] but some compilers won't accept __restrict__ on anything\n\/\/ but an raw pointer or reference\nvoid SkColorMatrixFilter::setup(const SkScalar* SK_RESTRICT src) {\n if (NULL == src) {\n fProc = NULL; \/\/ signals identity\n fFlags = kNO_ALPHA_FLAGS;\n \/\/ fState is undefined, but that is OK, since we shouldn't look at it\n return;\n }\n\n int32_t* SK_RESTRICT array = fState.fArray;\n\n int i;\n SkFixed max = 0;\n\n for (int i = 0; i < 20; i++) {\n SkFixed value = SkScalarToFixed(src[i]);\n array[i] = value;\n value = SkAbs32(value);\n max = SkMax32(max, value);\n }\n\n \/* All of fArray[] values must fit in 23 bits, to safely allow me to\n multiply them by 8bit unsigned values, and get a signed answer without\n overflow. This means clz needs to be 9 or bigger\n *\/\n int bits = SkCLZ(max);\n int32_t one = SK_Fixed1;\n\n fState.fShift = 16; \/\/ we are starting out as fixed 16.16\n if (bits < 9) {\n bits = 9 - bits;\n fState.fShift -= bits;\n for (i = 0; i < 20; i++) {\n array[i] >>= bits;\n }\n one >>= bits;\n }\n\n \/\/ check if we have to munge Alpha\n int32_t changesAlpha = (array[15] | array[16] | array[17] |\n (array[18] - one) | array[19]);\n int32_t usesAlpha = (array[3] | array[8] | array[13]);\n bool shiftIs16 = (16 == fState.fShift);\n\n if (changesAlpha | usesAlpha) {\n fProc = shiftIs16 ? General16 : General;\n fFlags = changesAlpha ? 0 : SkColorFilter::kAlphaUnchanged_Flag;\n } else {\n fFlags = kNO_ALPHA_FLAGS;\n\n int32_t needsScale = (array[0] - one) | \/\/ red axis\n (array[6] - one) | \/\/ green axis\n (array[12] - one); \/\/ blue axis\n\n int32_t needs3x3 = array[1] | array[2] | \/\/ red off-axis\n array[5] | array[7] | \/\/ green off-axis\n array[10] | array[11]; \/\/ blue off-axis\n\n if (needs3x3) {\n fProc = shiftIs16 ? AffineAdd16 : AffineAdd;\n } else if (needsScale) {\n fProc = shiftIs16 ? ScaleAdd16 : ScaleAdd;\n } else if (array[4] | array[9] | array[14]) { \/\/ needs add\n fProc = shiftIs16 ? Add16 : Add;\n } else {\n fProc = NULL; \/\/ identity\n }\n }\n\n \/* preround our add values so we get a rounded shift. We do this after we\n analyze the array, so we don't miss the case where the caller has zeros\n which could make us accidentally take the General or Add case.\n *\/\n if (NULL != fProc) {\n int32_t add = 1 << (fState.fShift - 1);\n array[4] += add;\n array[9] += add;\n array[14] += add;\n array[19] += add;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstatic int32_t pin(int32_t value, int32_t max) {\n if (value < 0) {\n value = 0;\n }\n if (value > max) {\n value = max;\n }\n return value;\n}\n\nSkColorMatrixFilter::SkColorMatrixFilter() {\n this->setup(NULL);\n}\n\nSkColorMatrixFilter::SkColorMatrixFilter(const SkColorMatrix& cm) {\n this->setup(cm.fMat);\n}\n\nSkColorMatrixFilter::SkColorMatrixFilter(const SkScalar array[20]) {\n this->setup(array);\n}\n\nuint32_t SkColorMatrixFilter::getFlags() {\n return this->INHERITED::getFlags() | fFlags;\n}\n\nvoid SkColorMatrixFilter::filterSpan(const SkPMColor src[], int count,\n SkPMColor dst[]) {\n Proc proc = fProc;\n State* state = &fState;\n int32_t* SK_RESTRICT result = state->fResult;\n\n if (NULL == proc) {\n if (src != dst) {\n memcpy(dst, src, count * sizeof(SkPMColor));\n }\n return;\n }\n\n const SkUnPreMultiply::Scale* table = SkUnPreMultiply::GetScaleTable();\n\n for (int i = 0; i < count; i++) {\n SkPMColor c = src[i];\n\n unsigned r = SkGetPackedR32(c);\n unsigned g = SkGetPackedG32(c);\n unsigned b = SkGetPackedB32(c);\n unsigned a = SkGetPackedA32(c);\n\n \/\/ need our components to be un-premultiplied\n if (255 != a) {\n SkUnPreMultiply::Scale scale = table[a];\n r = SkUnPreMultiply::ApplyScale(scale, r);\n g = SkUnPreMultiply::ApplyScale(scale, g);\n b = SkUnPreMultiply::ApplyScale(scale, b);\n\n SkASSERT(r <= 255);\n SkASSERT(g <= 255);\n SkASSERT(b <= 255);\n }\n\n proc(state, r, g, b, a);\n\n r = pin(result[0], SK_R32_MASK);\n g = pin(result[1], SK_G32_MASK);\n b = pin(result[2], SK_B32_MASK);\n a = pin(result[3], SK_A32_MASK);\n \/\/ re-prepremultiply if needed\n dst[i] = SkPremultiplyARGBInline(a, r, g, b);\n }\n}\n\nvoid SkColorMatrixFilter::filterSpan16(const uint16_t src[], int count,\n uint16_t dst[]) {\n SkASSERT(fFlags & SkColorFilter::kHasFilter16_Flag);\n\n Proc proc = fProc;\n State* state = &fState;\n int32_t* SK_RESTRICT result = state->fResult;\n\n if (NULL == proc) {\n if (src != dst) {\n memcpy(dst, src, count * sizeof(uint16_t));\n }\n return;\n }\n\n for (int i = 0; i < count; i++) {\n uint16_t c = src[i];\n\n \/\/ expand to 8bit components (since our matrix translate is 8bit biased\n unsigned r = SkPacked16ToR32(c);\n unsigned g = SkPacked16ToG32(c);\n unsigned b = SkPacked16ToB32(c);\n\n proc(state, r, g, b, 0);\n\n r = pin(result[0], SK_R32_MASK);\n g = pin(result[1], SK_G32_MASK);\n b = pin(result[2], SK_B32_MASK);\n\n \/\/ now packed it back down to 16bits (hmmm, could dither...)\n dst[i] = SkPack888ToRGB16(r, g, b);\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkColorMatrixFilter::flatten(SkFlattenableWriteBuffer& buffer) {\n this->INHERITED::flatten(buffer);\n\n buffer.writeFunctionPtr((void*)fProc);\n buffer.writeMul4(&fState, sizeof(fState));\n buffer.write32(fFlags);\n}\n\nSkFlattenable::Factory SkColorMatrixFilter::getFactory() { return CreateProc; }\n\nSkColorMatrixFilter::SkColorMatrixFilter(SkFlattenableReadBuffer& buffer)\n : INHERITED(buffer) {\n fProc = (Proc)buffer.readFunctionPtr();\n buffer.read(&fState, sizeof(fState));\n fFlags = buffer.readU32();\n}\n\nbool SkColorMatrixFilter::asColorMatrix(SkScalar matrix[20]) {\n int32_t* SK_RESTRICT array = fState.fArray;\n int unshift = 16 - fState.fShift;\n for (int i = 0; i < 20; i++) {\n matrix[i] = SkFixedToScalar(array[i] << unshift);\n }\n if (NULL != fProc) {\n \/\/ Undo the offset applied to the constant column in setup().\n SkFixed offset = 1 << (fState.fShift - 1);\n matrix[4] = SkFixedToScalar((array[4] - offset) << unshift);\n matrix[9] = SkFixedToScalar((array[9] - offset) << unshift);\n matrix[14] = SkFixedToScalar((array[14] - offset) << unshift);\n matrix[19] = SkFixedToScalar((array[19] - offset) << unshift);\n }\n return true;\n}\n\nSkFlattenable* SkColorMatrixFilter::CreateProc(SkFlattenableReadBuffer& buf) {\n return SkNEW_ARGS(SkColorMatrixFilter, (buf));\n}\n\nvoid SkColorMatrixFilter::setMatrix(const SkColorMatrix& matrix) {\n setup(matrix.fMat);\n}\n\nvoid SkColorMatrixFilter::setArray(const SkScalar array[20]) {\n setup(array);\n}\n\nSK_DEFINE_FLATTENABLE_REGISTRAR(SkColorMatrixFilter)\n<|endoftext|>"} {"text":"\/*\n * ARMEmulator.cpp\n *\n * Created on: Oct 10, 2015\n * Author: anon\n *\/\n\n#include \"debug.h\"\n#include \"ARMEmulator.h\"\n#include \"ARMDisassembler.h\"\n\nusing namespace std;\nusing namespace Register;\nusing namespace Disassembler;\n\nnamespace Emulator {\n ARMEmulator::ARMEmulator(ARMContext *context, Memory::AbstractMemory *memory, ARMMode mode, ARMVariants variant) :\n\t\tm_mode{mode}, m_contex{context}, m_memory{memory} {\n\t\t\tm_dis = new ARMDisassembler(variant);\n\t\t\tm_interpreter = new ARMInterpreter(*m_contex);\n }\n\n ARMEmulator::~ARMEmulator() {\n }\n\n void ARMEmulator::start(unsigned count) {\n \tbool stop = false;\n \tunsigned n_executed = 0;\n\n \tuint32_t cur_pc = 0;\n \tuint32_t cur_opcode = 0;\n \tARMMode cur_mode = m_mode;\n\n \tm_contex->getRegister(ARM_REG_PC, cur_pc);\n\n\t\twhile (!stop && n_executed < count) {\n\t\t \/\/ 1. Fetch an instruction from main memory.\n\t\t\tm_memory->read_value(cur_pc, cur_opcode);\n\n\t\t\t\/\/ 2. Decode it.\n\t\t\tARMInstruction ins = m_dis->disassemble(cur_opcode, cur_mode);\n\t\t\tLOG_INFO(\"Emulating instruction @ cur_pc=0x%.8x cur_opcode=0x%.8x string='%s' size=%d decoder='%s'\",\n\t\t\t cur_pc, cur_opcode, ins.toString().c_str(), ins.ins_size, ins.m_decoded_by.c_str());\n\n\t\t\t\/\/ 3. Execute the instruction.\n\t\t\tm_interpreter->execute(ins);\n\n\t\t\t\/\/ 4. Print the status of the registers.\n\t\t\tm_contex->dump();\n\n\t\t\tif (cur_pc == m_contex->PC()) {\n\t\t\t\tcur_pc += ins.ins_size \/ 8;\n\t\t\t\tm_contex->PC(cur_pc);\n\t\t\t}\n\n\t\t\tn_executed++;\n\t\t}\n }\n}\nRemoves overly verbose debug print\/*\n * ARMEmulator.cpp\n *\n * Created on: Oct 10, 2015\n * Author: anon\n *\/\n\n#include \"debug.h\"\n#include \"ARMEmulator.h\"\n#include \"ARMDisassembler.h\"\n\nusing namespace std;\nusing namespace Register;\nusing namespace Disassembler;\n\nnamespace Emulator {\n ARMEmulator::ARMEmulator(ARMContext *context, Memory::AbstractMemory *memory, ARMMode mode, ARMVariants variant) :\n\t\tm_mode{mode}, m_contex{context}, m_memory{memory} {\n\t\t\tm_dis = new ARMDisassembler(variant);\n\t\t\tm_interpreter = new ARMInterpreter(*m_contex);\n }\n\n ARMEmulator::~ARMEmulator() {\n }\n\n void ARMEmulator::start(unsigned count) {\n \tbool stop = false;\n \tunsigned n_executed = 0;\n\n \tuint32_t cur_pc = 0;\n \tuint32_t cur_opcode = 0;\n \tARMMode cur_mode = m_mode;\n\n \tm_contex->getRegister(ARM_REG_PC, cur_pc);\n\n\t\twhile (!stop && n_executed < count) {\n\t\t \/\/ 1. Fetch an instruction from main memory.\n\t\t\tm_memory->read_value(cur_pc, cur_opcode);\n\n\t\t\t\/\/ 2. Decode it.\n\t\t\tARMInstruction ins = m_dis->disassemble(cur_opcode, cur_mode);\n\n\t\t\t\/\/ 3. Execute the instruction.\n\t\t\tm_interpreter->execute(ins);\n\n\t\t\t\/\/ 4. Print the status of the registers.\n\t\t\tm_contex->dump();\n\n\t\t\tif (cur_pc == m_contex->PC()) {\n\t\t\t\tcur_pc += ins.ins_size \/ 8;\n\t\t\t\tm_contex->PC(cur_pc);\n\t\t\t}\n\n\t\t\tn_executed++;\n\t\t}\n }\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n\n#include \"qmljsscopeastpath.h\"\n\n#include \"parser\/qmljsast_p.h\"\n\nusing namespace QmlJS;\nusing namespace AST;\n\nScopeAstPath::ScopeAstPath(Document::Ptr doc)\n : _doc(doc)\n{\n}\n\nQList ScopeAstPath::operator()(quint32 offset)\n{\n _result.clear();\n _offset = offset;\n if (_doc)\n Node::accept(_doc->ast(), this);\n return _result;\n}\n\nvoid ScopeAstPath::accept(Node *node)\n{ Node::acceptChild(node, this); }\n\nbool ScopeAstPath::preVisit(Node *node)\n{\n if (Statement *stmt = node->statementCast()) {\n return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation());\n } else if (ExpressionNode *exp = node->expressionCast()) {\n return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation());\n } else if (UiObjectMember *ui = node->uiObjectMemberCast()) {\n return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation());\n }\n return true;\n}\n\nbool ScopeAstPath::visit(UiPublicMember *node)\n{\n if (node && node->statement && node->statement->kind == node->Kind_Block\n && containsOffset(node->statement->firstSourceLocation(),\n node->statement->lastSourceLocation())) {\n _result.append(node);\n Node::accept(node->statement, this);\n return false;\n }\n return true;\n}\n\nbool ScopeAstPath::visit(UiScriptBinding *node)\n{\n if (node && node->statement && node->statement->kind == node->Kind_Block\n && containsOffset(node->statement->firstSourceLocation(),\n node->statement->lastSourceLocation()))\n {\n _result.append(node);\n Node::accept(node->statement, this);\n return false;\n }\n return true;\n}\n\nbool ScopeAstPath::visit(UiObjectDefinition *node)\n{\n _result.append(node);\n Node::accept(node->initializer, this);\n return false;\n}\n\nbool ScopeAstPath::visit(UiObjectBinding *node)\n{\n _result.append(node);\n Node::accept(node->initializer, this);\n return false;\n}\n\nbool ScopeAstPath::visit(FunctionDeclaration *node)\n{\n return visit(static_cast(node));\n}\n\nbool ScopeAstPath::visit(FunctionExpression *node)\n{\n Node::accept(node->formals, this);\n _result.append(node);\n Node::accept(node->body, this);\n return false;\n}\n\nbool ScopeAstPath::containsOffset(SourceLocation start, SourceLocation end)\n{\n return _offset >= start.begin() && _offset <= end.end();\n}\nQmlJS: Clean up ScopeAstPath visitor.\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n\n#include \"qmljsscopeastpath.h\"\n\n#include \"parser\/qmljsast_p.h\"\n\nusing namespace QmlJS;\nusing namespace AST;\n\nScopeAstPath::ScopeAstPath(Document::Ptr doc)\n : _doc(doc)\n{\n}\n\nQList ScopeAstPath::operator()(quint32 offset)\n{\n _result.clear();\n _offset = offset;\n if (_doc)\n accept(_doc->ast());\n return _result;\n}\n\nvoid ScopeAstPath::accept(Node *node)\n{\n Node::accept(node, this);\n}\n\nbool ScopeAstPath::preVisit(Node *node)\n{\n if (Statement *stmt = node->statementCast()) {\n return containsOffset(stmt->firstSourceLocation(), stmt->lastSourceLocation());\n } else if (ExpressionNode *exp = node->expressionCast()) {\n return containsOffset(exp->firstSourceLocation(), exp->lastSourceLocation());\n } else if (UiObjectMember *ui = node->uiObjectMemberCast()) {\n return containsOffset(ui->firstSourceLocation(), ui->lastSourceLocation());\n }\n return true;\n}\n\nbool ScopeAstPath::visit(UiPublicMember *node)\n{\n if (node && node->statement && node->statement->kind == node->Kind_Block\n && containsOffset(node->statement->firstSourceLocation(),\n node->statement->lastSourceLocation())) {\n _result.append(node);\n accept(node->statement);\n return false;\n }\n return true;\n}\n\nbool ScopeAstPath::visit(UiScriptBinding *node)\n{\n if (node && node->statement && node->statement->kind == node->Kind_Block\n && containsOffset(node->statement->firstSourceLocation(),\n node->statement->lastSourceLocation()))\n {\n _result.append(node);\n accept(node->statement);\n return false;\n }\n return true;\n}\n\nbool ScopeAstPath::visit(UiObjectDefinition *node)\n{\n _result.append(node);\n accept(node->initializer);\n return false;\n}\n\nbool ScopeAstPath::visit(UiObjectBinding *node)\n{\n _result.append(node);\n accept(node->initializer);\n return false;\n}\n\nbool ScopeAstPath::visit(FunctionDeclaration *node)\n{\n return visit(static_cast(node));\n}\n\nbool ScopeAstPath::visit(FunctionExpression *node)\n{\n accept(node->formals);\n _result.append(node);\n accept(node->body);\n return false;\n}\n\nbool ScopeAstPath::containsOffset(SourceLocation start, SourceLocation end)\n{\n return _offset >= start.begin() && _offset <= end.end();\n}\n<|endoftext|>"} {"text":"#include \"change_map.h\"\n\n#include \"logconsole.h\"\n#include \"entity_system.h\"\n#include \"cli_normal_chat.h\"\n#include \"srv_normal_chat.h\"\n#include \"components\/basic_info.h\"\n#include \"whisper_char.h\"\n\nusing namespace RoseCommon;\nusing namespace RoseCommon::Packet;\n\nvoid Map::change_map_request(EntitySystem& entitySystem, Entity entity, const CliChangeMapReq&) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Map::change_map_request\");\n logger->trace(\"entity {}\", entity);\n entitySystem.send_to(entity, SrvChangeMapReply::create());\n const auto& basicInfo = entitySystem.get_component(entity);\n Chat::send_whisper(entitySystem, entity, fmt::format(\"You are client {}\", basicInfo.id));\n entitySystem.send_nearby_except_me(SrvPlayerChar::create());\n const auto& nearby_entities = entitySystem.get_nearby(entity);\n for (auto e : nearby_entities) {\n if (e != entity) {\n entitySystem.send_to(entity, SrvPlayerChar::create());\n }\n }\n if (const auto client_ptr = registry.try_get(entity)) {\n if (auto client = client_ptr->client.lock()) {\n client->set_logged_in();\n }\n }\n}\nUpdate change_map.cpp#include \"change_map.h\"\n\n#include \"logconsole.h\"\n#include \"entity_system.h\"\n#include \"cli_normal_chat.h\"\n#include \"srv_normal_chat.h\"\n#include \"cli_change_map_req.h\"\n#include \"components\/basic_info.h\"\n#include \"whisper_char.h\"\n\nusing namespace RoseCommon;\nusing namespace RoseCommon::Packet;\n\nvoid Map::change_map_request(EntitySystem& entitySystem, Entity entity, const CliChangeMapReq&) {\n auto logger = Core::CLog::GetLogger(Core::log_type::GENERAL).lock();\n logger->trace(\"Map::change_map_request\");\n logger->trace(\"entity {}\", entity);\n entitySystem.send_to(entity, SrvChangeMapReply::create());\n const auto& basicInfo = entitySystem.get_component(entity);\n Chat::send_whisper(entitySystem, entity, fmt::format(\"You are client {}\", basicInfo.id));\n entitySystem.send_nearby_except_me(SrvPlayerChar::create());\n const auto& nearby_entities = entitySystem.get_nearby(entity);\n for (auto e : nearby_entities) {\n if (e != entity) {\n entitySystem.send_to(entity, SrvPlayerChar::create());\n }\n }\n if (const auto client_ptr = registry.try_get(entity)) {\n if (auto client = client_ptr->client.lock()) {\n client->set_logged_in();\n }\n }\n}\n<|endoftext|>"} {"text":"#include \"Ext.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"RuntimeManager.h\"\n#include \"Memory.h\"\n#include \"Type.h\"\n#include \"Endianness.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nExt::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):\n\tRuntimeHelper(_runtimeManager),\n\tm_memoryMan(_memoryMan)\n{\n\tm_funcs = decltype(m_funcs)();\n\tm_argAllocas = decltype(m_argAllocas)();\n\tm_size = m_builder.CreateAlloca(Type::Size, nullptr, \"env.size\");\n}\n\n\nusing FuncDesc = std::tuple;\n\nllvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list const& _argsTypes)\n{\n\treturn llvm::FunctionType::get(_returnType, llvm::ArrayRef{_argsTypes.begin(), _argsTypes.size()}, false);\n}\n\nstd::array::value> const& getEnvFuncDescs()\n{\n\tstatic std::array::value> descs{{\n\t\tFuncDesc{\"env_sload\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sstore\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sha3\", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_balance\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_create\", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_call\", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_log\", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_blockhash\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_extcode\", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},\n\t}};\n\n\treturn descs;\n}\n\nllvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)\n{\n\tauto&& desc = getEnvFuncDescs()[static_cast(_id)];\n\treturn llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);\n}\n\nllvm::Value* Ext::getArgAlloca()\n{\n\tauto& a = m_argAllocas[m_argCounter];\n\tif (!a)\n\t{\n\t\tInsertPointGuard g{getBuilder()};\n\t\tauto allocaIt = getMainFunction()->front().begin();\n\t\tstd::advance(allocaIt, m_argCounter); \/\/ Skip already created allocas\n\t\tgetBuilder().SetInsertPoint(allocaIt);\n\t\ta = getBuilder().CreateAlloca(Type::Word, nullptr, {\"a.\", std::to_string(m_argCounter)});\n\t}\n\t++m_argCounter;\n\treturn a;\n}\n\nllvm::Value* Ext::byPtr(llvm::Value* _value)\n{\n\tauto a = getArgAlloca();\n\tgetBuilder().CreateStore(_value, a);\n\treturn a;\n}\n\nllvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list const& _args)\n{\n\tauto& func = m_funcs[static_cast(_funcId)];\n\tif (!func)\n\t\tfunc = createFunc(_funcId, getModule());\n\n\tm_argCounter = 0;\n\treturn getBuilder().CreateCall(func, {_args.begin(), _args.size()});\n}\n\nllvm::Value* Ext::sload(llvm::Value* _index)\n{\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); \/\/ Uses native endianness\n\treturn m_builder.CreateLoad(ret);\n}\n\nvoid Ext::sstore(llvm::Value* _index, llvm::Value* _value)\n{\n\tcreateCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); \/\/ Uses native endianness\n}\n\nllvm::Value* Ext::calldataload(llvm::Value* _idx)\n{\n\tauto ret = getArgAlloca();\n\tauto result = m_builder.CreateBitCast(ret, Type::BytePtr);\n\n\tauto callDataSize = getRuntimeManager().getCallDataSize();\n\tauto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size);\n\tauto idxValid = m_builder.CreateICmpULT(_idx, callDataSize);\n\tauto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, \"idx\");\n\n\tauto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32));\n\tend = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64);\n\tauto copySize = m_builder.CreateNUWSub(end, idx);\n\tauto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize);\n\tauto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx);\n\tm_builder.CreateMemCpy(result, dataBegin, copySize, 1);\n\tauto pad = m_builder.CreateGEP(Type::Byte, result, copySize);\n\tm_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1);\n\n\treturn Endianness::toNative(m_builder, m_builder.CreateLoad(ret));\n}\n\nllvm::Value* Ext::balance(llvm::Value* _address)\n{\n\tauto address = Endianness::toBE(m_builder, _address);\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});\n\treturn m_builder.CreateLoad(ret);\n}\n\nllvm::Value* Ext::blockhash(llvm::Value* _number)\n{\n\tauto hash = getArgAlloca();\n\tcreateCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});\n\thash = m_builder.CreateLoad(hash);\n\treturn Endianness::toNative(getBuilder(), hash);\n}\n\nllvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)\n{\n\tauto ret = getArgAlloca();\n\tauto begin = m_memoryMan.getBytePtr(_initOff);\n\tauto size = m_builder.CreateTrunc(_initSize, Type::Size, \"size\");\n\tcreateCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret});\n\tllvm::Value* address = m_builder.CreateLoad(ret);\n\taddress = Endianness::toNative(m_builder, address);\n\treturn address;\n}\n\nllvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress)\n{\n\tauto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);\n\tauto inBeg = m_memoryMan.getBytePtr(_inOff);\n\tauto inSize = m_builder.CreateTrunc(_inSize, Type::Size, \"in.size\");\n\tauto outBeg = m_memoryMan.getBytePtr(_outOff);\n\tauto outSize = m_builder.CreateTrunc(_outSize, Type::Size, \"out.size\");\n\tauto codeAddress = Endianness::toBE(m_builder, _codeAddress);\n\tauto callGas = m_builder.CreateSelect(\n\t\t\tm_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)),\n\t\t\tm_builder.CreateTrunc(_callGas, Type::Gas),\n\t\t\tConstant::gasMax);\n\tauto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)});\n\treturn m_builder.CreateZExt(ret, Type::Word, \"ret\");\n}\n\nllvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)\n{\n\tauto begin = m_memoryMan.getBytePtr(_inOff);\n\tauto size = m_builder.CreateTrunc(_inSize, Type::Size, \"size\");\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sha3, {begin, size, ret});\n\tllvm::Value* hash = m_builder.CreateLoad(ret);\n\thash = Endianness::toNative(m_builder, hash);\n\treturn hash;\n}\n\nMemoryRef Ext::extcode(llvm::Value* _addr)\n{\n\tauto addr = Endianness::toBE(m_builder, _addr);\n\tauto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});\n\tauto codeSize = m_builder.CreateLoad(m_size);\n\tauto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);\n\treturn {code, codeSize256};\n}\n\nvoid Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array const& _topics)\n{\n\tauto begin = m_memoryMan.getBytePtr(_memIdx);\n\tauto size = m_builder.CreateTrunc(_numBytes, Type::Size, \"size\");\n\tllvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};\n\n\tauto topicArgPtr = &args[3];\n\tfor (auto&& topic : _topics)\n\t{\n\t\tif (topic)\n\t\t\tm_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);\n\t\telse\n\t\t\t*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);\n\t\t++topicArgPtr;\n\t}\n\n\tcreateCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); \/\/ TODO: use std::initializer_list<>\n}\n\n}\n}\n}\nRelease aquired arg allocas in Ext::calldataload.#include \"Ext.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"RuntimeManager.h\"\n#include \"Memory.h\"\n#include \"Type.h\"\n#include \"Endianness.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nExt::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):\n\tRuntimeHelper(_runtimeManager),\n\tm_memoryMan(_memoryMan)\n{\n\tm_funcs = decltype(m_funcs)();\n\tm_argAllocas = decltype(m_argAllocas)();\n\tm_size = m_builder.CreateAlloca(Type::Size, nullptr, \"env.size\");\n}\n\n\nusing FuncDesc = std::tuple;\n\nllvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list const& _argsTypes)\n{\n\treturn llvm::FunctionType::get(_returnType, llvm::ArrayRef{_argsTypes.begin(), _argsTypes.size()}, false);\n}\n\nstd::array::value> const& getEnvFuncDescs()\n{\n\tstatic std::array::value> descs{{\n\t\tFuncDesc{\"env_sload\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sstore\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sha3\", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_balance\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_create\", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_call\", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_log\", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_blockhash\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_extcode\", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},\n\t}};\n\n\treturn descs;\n}\n\nllvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)\n{\n\tauto&& desc = getEnvFuncDescs()[static_cast(_id)];\n\treturn llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);\n}\n\nllvm::Value* Ext::getArgAlloca()\n{\n\tauto& a = m_argAllocas[m_argCounter];\n\tif (!a)\n\t{\n\t\tInsertPointGuard g{getBuilder()};\n\t\tauto allocaIt = getMainFunction()->front().begin();\n\t\tstd::advance(allocaIt, m_argCounter); \/\/ Skip already created allocas\n\t\tgetBuilder().SetInsertPoint(allocaIt);\n\t\ta = getBuilder().CreateAlloca(Type::Word, nullptr, {\"a.\", std::to_string(m_argCounter)});\n\t}\n\t++m_argCounter;\n\treturn a;\n}\n\nllvm::Value* Ext::byPtr(llvm::Value* _value)\n{\n\tauto a = getArgAlloca();\n\tgetBuilder().CreateStore(_value, a);\n\treturn a;\n}\n\nllvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list const& _args)\n{\n\tauto& func = m_funcs[static_cast(_funcId)];\n\tif (!func)\n\t\tfunc = createFunc(_funcId, getModule());\n\n\tm_argCounter = 0;\n\treturn getBuilder().CreateCall(func, {_args.begin(), _args.size()});\n}\n\nllvm::Value* Ext::sload(llvm::Value* _index)\n{\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); \/\/ Uses native endianness\n\treturn m_builder.CreateLoad(ret);\n}\n\nvoid Ext::sstore(llvm::Value* _index, llvm::Value* _value)\n{\n\tcreateCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); \/\/ Uses native endianness\n}\n\nllvm::Value* Ext::calldataload(llvm::Value* _idx)\n{\n\tauto ret = getArgAlloca();\n\tauto result = m_builder.CreateBitCast(ret, Type::BytePtr);\n\n\tauto callDataSize = getRuntimeManager().getCallDataSize();\n\tauto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size);\n\tauto idxValid = m_builder.CreateICmpULT(_idx, callDataSize);\n\tauto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, \"idx\");\n\n\tauto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32));\n\tend = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64);\n\tauto copySize = m_builder.CreateNUWSub(end, idx);\n\tauto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize);\n\tauto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx);\n\tm_builder.CreateMemCpy(result, dataBegin, copySize, 1);\n\tauto pad = m_builder.CreateGEP(Type::Byte, result, copySize);\n\tm_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1);\n\n\tm_argCounter = 0; \/\/ Release args allocas. TODO: This is a bad design\n\treturn Endianness::toNative(m_builder, m_builder.CreateLoad(ret));\n}\n\nllvm::Value* Ext::balance(llvm::Value* _address)\n{\n\tauto address = Endianness::toBE(m_builder, _address);\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});\n\treturn m_builder.CreateLoad(ret);\n}\n\nllvm::Value* Ext::blockhash(llvm::Value* _number)\n{\n\tauto hash = getArgAlloca();\n\tcreateCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});\n\thash = m_builder.CreateLoad(hash);\n\treturn Endianness::toNative(getBuilder(), hash);\n}\n\nllvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)\n{\n\tauto ret = getArgAlloca();\n\tauto begin = m_memoryMan.getBytePtr(_initOff);\n\tauto size = m_builder.CreateTrunc(_initSize, Type::Size, \"size\");\n\tcreateCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret});\n\tllvm::Value* address = m_builder.CreateLoad(ret);\n\taddress = Endianness::toNative(m_builder, address);\n\treturn address;\n}\n\nllvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress)\n{\n\tauto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);\n\tauto inBeg = m_memoryMan.getBytePtr(_inOff);\n\tauto inSize = m_builder.CreateTrunc(_inSize, Type::Size, \"in.size\");\n\tauto outBeg = m_memoryMan.getBytePtr(_outOff);\n\tauto outSize = m_builder.CreateTrunc(_outSize, Type::Size, \"out.size\");\n\tauto codeAddress = Endianness::toBE(m_builder, _codeAddress);\n\tauto callGas = m_builder.CreateSelect(\n\t\t\tm_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)),\n\t\t\tm_builder.CreateTrunc(_callGas, Type::Gas),\n\t\t\tConstant::gasMax);\n\tauto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)});\n\treturn m_builder.CreateZExt(ret, Type::Word, \"ret\");\n}\n\nllvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)\n{\n\tauto begin = m_memoryMan.getBytePtr(_inOff);\n\tauto size = m_builder.CreateTrunc(_inSize, Type::Size, \"size\");\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sha3, {begin, size, ret});\n\tllvm::Value* hash = m_builder.CreateLoad(ret);\n\thash = Endianness::toNative(m_builder, hash);\n\treturn hash;\n}\n\nMemoryRef Ext::extcode(llvm::Value* _addr)\n{\n\tauto addr = Endianness::toBE(m_builder, _addr);\n\tauto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});\n\tauto codeSize = m_builder.CreateLoad(m_size);\n\tauto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);\n\treturn {code, codeSize256};\n}\n\nvoid Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array const& _topics)\n{\n\tauto begin = m_memoryMan.getBytePtr(_memIdx);\n\tauto size = m_builder.CreateTrunc(_numBytes, Type::Size, \"size\");\n\tllvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};\n\n\tauto topicArgPtr = &args[3];\n\tfor (auto&& topic : _topics)\n\t{\n\t\tif (topic)\n\t\t\tm_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);\n\t\telse\n\t\t\t*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);\n\t\t++topicArgPtr;\n\t}\n\n\tcreateCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); \/\/ TODO: use std::initializer_list<>\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"#include \"Ext.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"RuntimeManager.h\"\n#include \"Memory.h\"\n#include \"Type.h\"\n#include \"Endianness.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nExt::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):\n\tRuntimeHelper(_runtimeManager),\n\tm_memoryMan(_memoryMan)\n{\n\tm_funcs = decltype(m_funcs)();\n\tm_argAllocas = decltype(m_argAllocas)();\n\tm_size = m_builder.CreateAlloca(Type::Size, nullptr, \"env.size\");\n}\n\n\nusing FuncDesc = std::tuple;\n\nllvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list const& _argsTypes)\n{\n\treturn llvm::FunctionType::get(_returnType, llvm::ArrayRef{_argsTypes.begin(), _argsTypes.size()}, false);\n}\n\nstd::array::value> const& getEnvFuncDescs()\n{\n\tstatic std::array::value> descs{{\n\t\tFuncDesc{\"env_sload\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sstore\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sha3\", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_balance\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_create\", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_call\", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_log\", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_blockhash\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_extcode\", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},\n\t}};\n\n\treturn descs;\n}\n\nllvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)\n{\n\tauto&& desc = getEnvFuncDescs()[static_cast(_id)];\n\treturn llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);\n}\n\nllvm::Value* Ext::getArgAlloca()\n{\n\tauto& a = m_argAllocas[m_argCounter];\n\tif (!a)\n\t{\n\t\tInsertPointGuard g{getBuilder()};\n\t\tauto allocaIt = getMainFunction()->front().begin();\n\t\tstd::advance(allocaIt, m_argCounter); \/\/ Skip already created allocas\n\t\tgetBuilder().SetInsertPoint(allocaIt);\n\t\ta = getBuilder().CreateAlloca(Type::Word, nullptr, {\"a.\", std::to_string(m_argCounter)});\n\t}\n\t++m_argCounter;\n\treturn a;\n}\n\nllvm::Value* Ext::byPtr(llvm::Value* _value)\n{\n\tauto a = getArgAlloca();\n\tgetBuilder().CreateStore(_value, a);\n\treturn a;\n}\n\nllvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list const& _args)\n{\n\tauto& func = m_funcs[static_cast(_funcId)];\n\tif (!func)\n\t\tfunc = createFunc(_funcId, getModule());\n\n\tm_argCounter = 0;\n\treturn getBuilder().CreateCall(func, {_args.begin(), _args.size()});\n}\n\nllvm::Value* Ext::sload(llvm::Value* _index)\n{\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); \/\/ Uses native endianness\n\treturn m_builder.CreateLoad(ret);\n}\n\nvoid Ext::sstore(llvm::Value* _index, llvm::Value* _value)\n{\n\tcreateCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); \/\/ Uses native endianness\n}\n\nllvm::Value* Ext::calldataload(llvm::Value* _idx)\n{\n\tauto ret = getArgAlloca();\n\tauto result = m_builder.CreateBitCast(ret, Type::BytePtr);\n\n\tauto callDataSize = getRuntimeManager().getCallDataSize();\n\tauto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size);\n\tauto idxValid = m_builder.CreateICmpULT(_idx, callDataSize);\n\tauto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, \"idx\");\n\n\tauto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32));\n\tend = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64);\n\tauto copySize = m_builder.CreateNUWSub(end, idx);\n\tauto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize);\n\tauto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx);\n\tm_builder.CreateMemCpy(result, dataBegin, copySize, 1);\n\tauto pad = m_builder.CreateGEP(Type::Byte, result, copySize);\n\tm_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1);\n\n\treturn Endianness::toNative(m_builder, m_builder.CreateLoad(ret));\n}\n\nllvm::Value* Ext::balance(llvm::Value* _address)\n{\n\tauto address = Endianness::toBE(m_builder, _address);\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});\n\treturn m_builder.CreateLoad(ret);\n}\n\nllvm::Value* Ext::blockhash(llvm::Value* _number)\n{\n\tauto hash = getArgAlloca();\n\tcreateCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});\n\thash = m_builder.CreateLoad(hash);\n\treturn Endianness::toNative(getBuilder(), hash);\n}\n\nllvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)\n{\n\tauto ret = getArgAlloca();\n\tauto begin = m_memoryMan.getBytePtr(_initOff);\n\tauto size = m_builder.CreateTrunc(_initSize, Type::Size, \"size\");\n\tcreateCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret});\n\tllvm::Value* address = m_builder.CreateLoad(ret);\n\taddress = Endianness::toNative(m_builder, address);\n\treturn address;\n}\n\nllvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress)\n{\n\tauto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);\n\tauto inBeg = m_memoryMan.getBytePtr(_inOff);\n\tauto inSize = m_builder.CreateTrunc(_inSize, Type::Size, \"in.size\");\n\tauto outBeg = m_memoryMan.getBytePtr(_outOff);\n\tauto outSize = m_builder.CreateTrunc(_outSize, Type::Size, \"out.size\");\n\tauto codeAddress = Endianness::toBE(m_builder, _codeAddress);\n\tauto callGas = m_builder.CreateSelect(\n\t\t\tm_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)),\n\t\t\tm_builder.CreateTrunc(_callGas, Type::Gas),\n\t\t\tConstant::gasMax);\n\tauto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)});\n\treturn m_builder.CreateZExt(ret, Type::Word, \"ret\");\n}\n\nllvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)\n{\n\tauto begin = m_memoryMan.getBytePtr(_inOff);\n\tauto size = m_builder.CreateTrunc(_inSize, Type::Size, \"size\");\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sha3, {begin, size, ret});\n\tllvm::Value* hash = m_builder.CreateLoad(ret);\n\thash = Endianness::toNative(m_builder, hash);\n\treturn hash;\n}\n\nMemoryRef Ext::extcode(llvm::Value* _addr)\n{\n\tauto addr = Endianness::toBE(m_builder, _addr);\n\tauto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});\n\tauto codeSize = m_builder.CreateLoad(m_size);\n\tauto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);\n\treturn {code, codeSize256};\n}\n\nvoid Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array const& _topics)\n{\n\tauto begin = m_memoryMan.getBytePtr(_memIdx);\n\tauto size = m_builder.CreateTrunc(_numBytes, Type::Size, \"size\");\n\tllvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};\n\n\tauto topicArgPtr = &args[3];\n\tfor (auto&& topic : _topics)\n\t{\n\t\tif (topic)\n\t\t\tm_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);\n\t\telse\n\t\t\t*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);\n\t\t++topicArgPtr;\n\t}\n\n\tcreateCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); \/\/ TODO: use std::initializer_list<>\n}\n\n}\n}\n}\nRelease aquired arg allocas in Ext::calldataload.#include \"Ext.h\"\n\n#include \"preprocessor\/llvm_includes_start.h\"\n#include \n#include \"preprocessor\/llvm_includes_end.h\"\n\n#include \"RuntimeManager.h\"\n#include \"Memory.h\"\n#include \"Type.h\"\n#include \"Endianness.h\"\n\nnamespace dev\n{\nnamespace eth\n{\nnamespace jit\n{\n\nExt::Ext(RuntimeManager& _runtimeManager, Memory& _memoryMan):\n\tRuntimeHelper(_runtimeManager),\n\tm_memoryMan(_memoryMan)\n{\n\tm_funcs = decltype(m_funcs)();\n\tm_argAllocas = decltype(m_argAllocas)();\n\tm_size = m_builder.CreateAlloca(Type::Size, nullptr, \"env.size\");\n}\n\n\nusing FuncDesc = std::tuple;\n\nllvm::FunctionType* getFunctionType(llvm::Type* _returnType, std::initializer_list const& _argsTypes)\n{\n\treturn llvm::FunctionType::get(_returnType, llvm::ArrayRef{_argsTypes.begin(), _argsTypes.size()}, false);\n}\n\nstd::array::value> const& getEnvFuncDescs()\n{\n\tstatic std::array::value> descs{{\n\t\tFuncDesc{\"env_sload\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sstore\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_sha3\", getFunctionType(Type::Void, {Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_balance\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_create\", getFunctionType(Type::Void, {Type::EnvPtr, Type::GasPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_call\", getFunctionType(Type::Bool, {Type::EnvPtr, Type::GasPtr, Type::Gas, Type::WordPtr, Type::WordPtr, Type::BytePtr, Type::Size, Type::BytePtr, Type::Size, Type::WordPtr})},\n\t\tFuncDesc{\"env_log\", getFunctionType(Type::Void, {Type::EnvPtr, Type::BytePtr, Type::Size, Type::WordPtr, Type::WordPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_blockhash\", getFunctionType(Type::Void, {Type::EnvPtr, Type::WordPtr, Type::WordPtr})},\n\t\tFuncDesc{\"env_extcode\", getFunctionType(Type::BytePtr, {Type::EnvPtr, Type::WordPtr, Type::Size->getPointerTo()})},\n\t}};\n\n\treturn descs;\n}\n\nllvm::Function* createFunc(EnvFunc _id, llvm::Module* _module)\n{\n\tauto&& desc = getEnvFuncDescs()[static_cast(_id)];\n\treturn llvm::Function::Create(std::get<1>(desc), llvm::Function::ExternalLinkage, std::get<0>(desc), _module);\n}\n\nllvm::Value* Ext::getArgAlloca()\n{\n\tauto& a = m_argAllocas[m_argCounter];\n\tif (!a)\n\t{\n\t\tInsertPointGuard g{getBuilder()};\n\t\tauto allocaIt = getMainFunction()->front().begin();\n\t\tstd::advance(allocaIt, m_argCounter); \/\/ Skip already created allocas\n\t\tgetBuilder().SetInsertPoint(allocaIt);\n\t\ta = getBuilder().CreateAlloca(Type::Word, nullptr, {\"a.\", std::to_string(m_argCounter)});\n\t}\n\t++m_argCounter;\n\treturn a;\n}\n\nllvm::Value* Ext::byPtr(llvm::Value* _value)\n{\n\tauto a = getArgAlloca();\n\tgetBuilder().CreateStore(_value, a);\n\treturn a;\n}\n\nllvm::CallInst* Ext::createCall(EnvFunc _funcId, std::initializer_list const& _args)\n{\n\tauto& func = m_funcs[static_cast(_funcId)];\n\tif (!func)\n\t\tfunc = createFunc(_funcId, getModule());\n\n\tm_argCounter = 0;\n\treturn getBuilder().CreateCall(func, {_args.begin(), _args.size()});\n}\n\nllvm::Value* Ext::sload(llvm::Value* _index)\n{\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sload, {getRuntimeManager().getEnvPtr(), byPtr(_index), ret}); \/\/ Uses native endianness\n\treturn m_builder.CreateLoad(ret);\n}\n\nvoid Ext::sstore(llvm::Value* _index, llvm::Value* _value)\n{\n\tcreateCall(EnvFunc::sstore, {getRuntimeManager().getEnvPtr(), byPtr(_index), byPtr(_value)}); \/\/ Uses native endianness\n}\n\nllvm::Value* Ext::calldataload(llvm::Value* _idx)\n{\n\tauto ret = getArgAlloca();\n\tauto result = m_builder.CreateBitCast(ret, Type::BytePtr);\n\n\tauto callDataSize = getRuntimeManager().getCallDataSize();\n\tauto callDataSize64 = m_builder.CreateTrunc(callDataSize, Type::Size);\n\tauto idxValid = m_builder.CreateICmpULT(_idx, callDataSize);\n\tauto idx = m_builder.CreateTrunc(m_builder.CreateSelect(idxValid, _idx, callDataSize), Type::Size, \"idx\");\n\n\tauto end = m_builder.CreateNUWAdd(idx, m_builder.getInt64(32));\n\tend = m_builder.CreateSelect(m_builder.CreateICmpULE(end, callDataSize64), end, callDataSize64);\n\tauto copySize = m_builder.CreateNUWSub(end, idx);\n\tauto padSize = m_builder.CreateNUWSub(m_builder.getInt64(32), copySize);\n\tauto dataBegin = m_builder.CreateGEP(Type::Byte, getRuntimeManager().getCallData(), idx);\n\tm_builder.CreateMemCpy(result, dataBegin, copySize, 1);\n\tauto pad = m_builder.CreateGEP(Type::Byte, result, copySize);\n\tm_builder.CreateMemSet(pad, m_builder.getInt8(0), padSize, 1);\n\n\tm_argCounter = 0; \/\/ Release args allocas. TODO: This is a bad design\n\treturn Endianness::toNative(m_builder, m_builder.CreateLoad(ret));\n}\n\nllvm::Value* Ext::balance(llvm::Value* _address)\n{\n\tauto address = Endianness::toBE(m_builder, _address);\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::balance, {getRuntimeManager().getEnvPtr(), byPtr(address), ret});\n\treturn m_builder.CreateLoad(ret);\n}\n\nllvm::Value* Ext::blockhash(llvm::Value* _number)\n{\n\tauto hash = getArgAlloca();\n\tcreateCall(EnvFunc::blockhash, {getRuntimeManager().getEnvPtr(), byPtr(_number), hash});\n\thash = m_builder.CreateLoad(hash);\n\treturn Endianness::toNative(getBuilder(), hash);\n}\n\nllvm::Value* Ext::create(llvm::Value* _endowment, llvm::Value* _initOff, llvm::Value* _initSize)\n{\n\tauto ret = getArgAlloca();\n\tauto begin = m_memoryMan.getBytePtr(_initOff);\n\tauto size = m_builder.CreateTrunc(_initSize, Type::Size, \"size\");\n\tcreateCall(EnvFunc::create, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), byPtr(_endowment), begin, size, ret});\n\tllvm::Value* address = m_builder.CreateLoad(ret);\n\taddress = Endianness::toNative(m_builder, address);\n\treturn address;\n}\n\nllvm::Value* Ext::call(llvm::Value* _callGas, llvm::Value* _receiveAddress, llvm::Value* _value, llvm::Value* _inOff, llvm::Value* _inSize, llvm::Value* _outOff, llvm::Value* _outSize, llvm::Value* _codeAddress)\n{\n\tauto receiveAddress = Endianness::toBE(m_builder, _receiveAddress);\n\tauto inBeg = m_memoryMan.getBytePtr(_inOff);\n\tauto inSize = m_builder.CreateTrunc(_inSize, Type::Size, \"in.size\");\n\tauto outBeg = m_memoryMan.getBytePtr(_outOff);\n\tauto outSize = m_builder.CreateTrunc(_outSize, Type::Size, \"out.size\");\n\tauto codeAddress = Endianness::toBE(m_builder, _codeAddress);\n\tauto callGas = m_builder.CreateSelect(\n\t\t\tm_builder.CreateICmpULE(_callGas, m_builder.CreateZExt(Constant::gasMax, Type::Word)),\n\t\t\tm_builder.CreateTrunc(_callGas, Type::Gas),\n\t\t\tConstant::gasMax);\n\tauto ret = createCall(EnvFunc::call, {getRuntimeManager().getEnvPtr(), getRuntimeManager().getGasPtr(), callGas, byPtr(receiveAddress), byPtr(_value), inBeg, inSize, outBeg, outSize, byPtr(codeAddress)});\n\treturn m_builder.CreateZExt(ret, Type::Word, \"ret\");\n}\n\nllvm::Value* Ext::sha3(llvm::Value* _inOff, llvm::Value* _inSize)\n{\n\tauto begin = m_memoryMan.getBytePtr(_inOff);\n\tauto size = m_builder.CreateTrunc(_inSize, Type::Size, \"size\");\n\tauto ret = getArgAlloca();\n\tcreateCall(EnvFunc::sha3, {begin, size, ret});\n\tllvm::Value* hash = m_builder.CreateLoad(ret);\n\thash = Endianness::toNative(m_builder, hash);\n\treturn hash;\n}\n\nMemoryRef Ext::extcode(llvm::Value* _addr)\n{\n\tauto addr = Endianness::toBE(m_builder, _addr);\n\tauto code = createCall(EnvFunc::extcode, {getRuntimeManager().getEnvPtr(), byPtr(addr), m_size});\n\tauto codeSize = m_builder.CreateLoad(m_size);\n\tauto codeSize256 = m_builder.CreateZExt(codeSize, Type::Word);\n\treturn {code, codeSize256};\n}\n\nvoid Ext::log(llvm::Value* _memIdx, llvm::Value* _numBytes, std::array const& _topics)\n{\n\tauto begin = m_memoryMan.getBytePtr(_memIdx);\n\tauto size = m_builder.CreateTrunc(_numBytes, Type::Size, \"size\");\n\tllvm::Value* args[] = {getRuntimeManager().getEnvPtr(), begin, size, getArgAlloca(), getArgAlloca(), getArgAlloca(), getArgAlloca()};\n\n\tauto topicArgPtr = &args[3];\n\tfor (auto&& topic : _topics)\n\t{\n\t\tif (topic)\n\t\t\tm_builder.CreateStore(Endianness::toBE(m_builder, topic), *topicArgPtr);\n\t\telse\n\t\t\t*topicArgPtr = llvm::ConstantPointerNull::get(Type::WordPtr);\n\t\t++topicArgPtr;\n\t}\n\n\tcreateCall(EnvFunc::log, {args[0], args[1], args[2], args[3], args[4], args[5], args[6]}); \/\/ TODO: use std::initializer_list<>\n}\n\n}\n}\n}\n<|endoftext|>"} {"text":"#include \"Node.h\"\r\n#include \"NodePart.h\"\r\n#include \"Animation.h\"\r\n#include \"NodeAnimation.h\"\r\n#include \"Keyframe.h\"\r\n#include \"Material.h\"\r\n#include \"Attributes.h\"\r\n#include \"MeshPart.h\"\r\n#include \"Mesh.h\"\r\n#include \"Model.h\"\r\n#include \"Reference.h\"\r\n#include \"FileIO.h\"\r\n #include \"Reference.h\"\r\nnamespace fbxconv {\r\nnamespace modeldata {\r\n static const char* getTextureUseString(const Material::Texture::Usage &textureUse) {\r\n\tswitch(textureUse){\r\n\tcase Material::Texture::Ambient:\r\n\t\treturn \"AMBIENT\";\r\n\tcase Material::Texture::Bump:\r\n\t\treturn \"BUMP\";\r\n\tcase Material::Texture::Diffuse:\r\n\t\treturn \"DIFFUSE\";\r\n\tcase Material::Texture::Emissive:\r\n\t\treturn \"EMISSIVE\";\r\n\tcase Material::Texture::None:\r\n\t\treturn \"NONE\";\r\n\tcase Material::Texture::Normal:\r\n\t\treturn \"NORMAL\";\r\n\tcase Material::Texture::Reflection:\r\n\t\treturn \"REFLECTION\";\r\n\tcase Material::Texture::Shininess:\r\n\t\treturn \"SHININESS\";\r\n\tcase Material::Texture::Specular:\r\n\t\treturn \"SPECULAR\";\r\n\tcase Material::Texture::Transparency:\r\n\t\treturn \"TRANSPARENCY\";\r\n\tdefault:\r\n\t\treturn \"UNKNOWN\";\r\n\t}\r\n}\r\n static const char* getWrapModeUseString(const FbxFileTexture::EWrapMode &textureUse)\r\n {\r\n switch(textureUse){\r\n case FbxFileTexture::eRepeat:\r\n return \"REPEAT\";\r\n case FbxFileTexture::eClamp:\r\n return \"CLAMP\";\r\n default:\r\n return \"UNKNOWN\";\r\n }\r\n }\r\n\tvoid Model::writeBinary(FILE* file)\r\n\t{\r\n std::list _bonenames;\r\n for (std::vector::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr)\r\n {\r\n (*itr)->loadBoneNames(_bonenames);\r\n }\r\n for (std::vector::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr)\r\n {\r\n bool skeleton=false;\r\n (*itr)->checkIsSkeleton(skeleton,_bonenames);\r\n (*itr)->setSkeleton(skeleton);\r\n }\r\n\t\tunsigned int size = meshes.size();\r\n if(size>0)\r\n {\r\n meshes[0]->object.fPosition = ftell(file);\t\r\n }\r\n\t\twrite(size, file);\r\n \/\/ write mesh\r\n\t\tfor(auto itr = meshes.begin(); itr != meshes.end(); itr++)\r\n\t\t{\r\n\t\t\t(*itr)->writeBinary(file);\r\n\t\t}\r\n\t\t\r\n\t\t\/\/ write material\r\n\t size = materials.size();\r\n if(size>0)\r\n {\r\n materials[0]->object.fPosition = ftell(file);\t\r\n }\r\n\t\twrite(size, file);\r\n\t\tfor(auto itr = materials.begin(); itr != materials.end(); itr++)\r\n\t\t{\r\n\t\t\t(*itr)->writeBinary(file);\r\n\t\t}\r\n\t\t\/\/ node num\r\n size = nodes.size();\r\n if(size>0)\r\n {\r\n nodes[0]->object.fPosition = ftell(file);\t\r\n }\r\n write(size, file);\r\n for(auto itr = nodes.begin(); itr != nodes.end(); itr++)\r\n {\r\n (*itr)->writeBinary(file);\r\n }\r\n\r\n\t\t\/\/ animations\r\n write(size, file);\r\n for(auto itr : animations)\r\n {\r\n itr->object.fPosition = ftell(file);\r\n itr->writeBinary(file);\r\n }\r\n\t}\r\n\r\n\tvoid Mesh::writeBinary(FILE* file)\r\n\t{\r\n\t\t\/\/ attribute\r\n\t\tattributes.writeBinary(file);\r\n\t\t\r\n\t\t\/\/ write vertices\r\n\t\tif(vertices.size() > 0)\r\n\t\t{\r\n\t\t\tunsigned int size = vertices.size();\r\n\t\t\twrite(size, file);\r\n\t\t\twrite(&vertices[0],size,file);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\twrite((unsigned int)0, file);\r\n\t\t}\r\n\r\n\t\t\/\/ write parts.\r\n\t\tunsigned int size = parts.size();\r\n\t\twrite(size, file);\r\n\t\tfor(auto itr = parts.begin(); itr != parts.end(); itr++)\r\n\t\t{\r\n (*itr)->writeBinary(file);\r\n \r\n\r\n\t\t}\r\n\t}\r\n void MeshPart::writeBinary(FILE* file)\r\n {\r\n write(id, file);\r\n \/\/aabb\r\n write((unsigned int)6, file);\r\n write(aabb, 6, file);\r\n \/\/ indices size\r\n unsigned int size = indices.size();\r\n write(size, file);\r\n \/\/ indices.\r\n for(auto itr1 = indices.begin(); itr1 != indices.end(); itr1++)\r\n write(*itr1,file);\r\n }\r\n\tvoid Attributes::writeBinary(FILE* file)\r\n\t{\r\n\r\n\t\tstd::vector attribs;\r\n\t\tMeshVertexAttrib attrib;\r\n for (unsigned int i = 0; i < length(); i++)\r\n {\r\n std::string key = name(i);\r\n attrib = attributemap.find(key)->second;\r\n attribs.push_back(attrib);\r\n if(key == \"VERTEX_ATTRIB_BLEND_INDEX\")\r\n {\r\n break;\r\n }\r\n }\r\n\t\tunsigned int size = attribs.size();\r\n write(size, file);\r\n for( int i = 0 ; i < size ; i++ )\r\n {\r\n write(attribs[i].size, file);\r\n write(attribs[i].type, file);\r\n write(attribs[i].name, file);\r\n }\r\n\t}\r\n\t\r\n\tvoid Material::writeBinary(FILE* file)\r\n\t{\r\n\t\twrite(id, file);\r\n write(diffuse.value, 3, file);\r\n write(ambient.value, 3, file);\r\n write(emissive.value, 3, file);\r\n write(opacity.value,file);\r\n write(specular.value, 3, file);\r\n write(shininess.value,file);\r\n unsigned int size = textures.size();\r\n write(size, file);\r\n for(auto itr = textures.begin(); itr != textures.end(); itr++)\r\n {\r\n write((*itr)->id, file);\r\n write((*itr)->path, file);\r\n write((*itr)->uvTranslation, 2, file);\r\n write((*itr)->uvScale, 2, file);\r\n std::string wrapModeU=getWrapModeUseString((*itr)->wrapModeU);\r\n std::string wrapModeV=getWrapModeUseString((*itr)->wrapModeV);\r\n std::string type= getTextureUseString((*itr)->usage);\r\n write(type,file);\r\n write(wrapModeU,file);\r\n write(wrapModeV,file);\r\n }\r\n\t}\r\n\t\r\n\tvoid Node::writeBinary(FILE* file)\r\n\t{\r\n\t\twrite(id, file);\r\n write(_skeleton, file);\r\n \/\/ rotation scale translation\r\n write(transforms, 16, file);\r\n\t\t\/\/write(transform.scale, 3, file);\r\n\t\t\/\/write(transform.translation, 3, file);\r\n \/\/ node part\r\n unsigned int partsSize = parts.size();\r\n\t\twrite(partsSize,file);\r\n\t\tif(parts.size()>0)\r\n\t\t{\r\n for(int i = 0 ; i < parts.size() ; i++ )\r\n {\r\n NodePart* nodepart = parts[i];\r\n if(nodepart)\r\n {\r\n if(nodepart->meshPart)\r\n {\r\n \/\/meshpartid\r\n write(nodepart->meshPart->id, file);\r\n }\r\n else\r\n {\r\n write(\"null\", file);\r\n }\r\n \/\/materialid\r\n if(nodepart->material)\r\n {\r\n write(nodepart->material->id, file);\r\n }\r\n else\r\n {\r\n write(\"null\", file);\r\n }\r\n \/\/ bone num\r\n unsigned int size = nodepart->bones.size();\r\n write(size, file);\r\n for(auto itr = nodepart->bones.begin(); itr != nodepart->bones.end(); itr++)\r\n {\r\n \/\/ write name\r\n write(itr->first->id, file);\r\n \/\/ write transform\r\n float tmp[16];\r\n for(int i = 0; i < 4; i++)\r\n {\r\n for(int j = 0; j < 4; j++)\r\n {\r\n tmp[i*4 + j] = itr->second.Double44()[i][j];\r\n }\r\n }\r\n write(tmp, 16, file);\r\n }\r\n \/\/ uvMapping\r\n size = nodepart->uvMapping.size();\r\n write(size, file);\r\n for(auto itr = nodepart->uvMapping.begin(); itr != nodepart->uvMapping.end(); itr++)\r\n {\r\n unsigned int size = itr->size();\r\n write(size, file);\r\n \/\/TextureIndex\r\n for (auto tt = (*itr).begin(); tt != (*itr).end(); ++tt)\r\n {\r\n unsigned int index = nodepart->material->getTextureIndex(*tt);\r\n write(index, file);\r\n }\r\n }\r\n }\r\n }\r\n\t\t}\r\n \/\/ children\r\n unsigned int childrenSize = children.size();\r\n write(childrenSize,file);\r\n\t\tfor(auto itr = children.begin(); itr != children.end(); itr++)\r\n\t\t{\r\n\t\t\tNode* node = *itr;\r\n if(node)\r\n {\r\n node->writeBinary(file);\r\n }\r\n\t\t}\r\n\t}\r\n\tvoid Animation::writeBinary(FILE* file)\r\n\t{\r\n\t write(id, file);\r\n\t\twrite(length, file);\r\n\t\twrite(static_cast(nodeAnimations.size()), file);\r\n\r\n\t\tfor(auto itr = nodeAnimations.begin(); itr != nodeAnimations.end(); itr++)\r\n\t\t{\r\n\t\t\tNodeAnimation* nodeanim = *itr;\r\n\t\t\twrite(nodeanim->node->id, file);\r\n\t\t\t\r\n\t\t\twrite(static_cast(nodeanim->keyframes.size()), file);\r\n\t\t\t\r\n\t\t\tfor(auto itr1 = nodeanim->keyframes.begin(); itr1 != nodeanim->keyframes.end(); itr1++)\r\n\t\t\t{\r\n\t\t\t\tKeyframe* keyframe = *itr1;\r\n \r\n\t\t\t\t\/\/ write time\r\n\t\t\t\twrite(keyframe->time, file);\r\n \r\n \/\/ write transform flag\r\n unsigned char transformflag(0);\r\n if (keyframe->hasRotation)\r\n transformflag |= 0x01;\r\n if (keyframe->hasScale)\r\n transformflag |= (0x01 << 1);\r\n if (keyframe->hasTranslation)\r\n transformflag |= (0x01 << 2);\r\n \r\n write(transformflag, file);\r\n \r\n \/\/ write rotation val\r\n if (keyframe->hasRotation)\r\n write(keyframe->rotation, 4, file);\r\n \r\n \/\/ write scale val\r\n if (keyframe->hasScale)\r\n write(keyframe->scale, 3, file);\r\n \r\n \/\/ write translation val\r\n if (keyframe->hasTranslation)\r\n write(keyframe->translation, 3, file);\r\n\t\t\t}\r\n\t\t}\r\n }\r\n} \r\n}change AABB write order#include \"Node.h\"\r\n#include \"NodePart.h\"\r\n#include \"Animation.h\"\r\n#include \"NodeAnimation.h\"\r\n#include \"Keyframe.h\"\r\n#include \"Material.h\"\r\n#include \"Attributes.h\"\r\n#include \"MeshPart.h\"\r\n#include \"Mesh.h\"\r\n#include \"Model.h\"\r\n#include \"Reference.h\"\r\n#include \"FileIO.h\"\r\n #include \"Reference.h\"\r\nnamespace fbxconv {\r\nnamespace modeldata {\r\n static const char* getTextureUseString(const Material::Texture::Usage &textureUse) {\r\n\tswitch(textureUse){\r\n\tcase Material::Texture::Ambient:\r\n\t\treturn \"AMBIENT\";\r\n\tcase Material::Texture::Bump:\r\n\t\treturn \"BUMP\";\r\n\tcase Material::Texture::Diffuse:\r\n\t\treturn \"DIFFUSE\";\r\n\tcase Material::Texture::Emissive:\r\n\t\treturn \"EMISSIVE\";\r\n\tcase Material::Texture::None:\r\n\t\treturn \"NONE\";\r\n\tcase Material::Texture::Normal:\r\n\t\treturn \"NORMAL\";\r\n\tcase Material::Texture::Reflection:\r\n\t\treturn \"REFLECTION\";\r\n\tcase Material::Texture::Shininess:\r\n\t\treturn \"SHININESS\";\r\n\tcase Material::Texture::Specular:\r\n\t\treturn \"SPECULAR\";\r\n\tcase Material::Texture::Transparency:\r\n\t\treturn \"TRANSPARENCY\";\r\n\tdefault:\r\n\t\treturn \"UNKNOWN\";\r\n\t}\r\n}\r\n static const char* getWrapModeUseString(const FbxFileTexture::EWrapMode &textureUse)\r\n {\r\n switch(textureUse){\r\n case FbxFileTexture::eRepeat:\r\n return \"REPEAT\";\r\n case FbxFileTexture::eClamp:\r\n return \"CLAMP\";\r\n default:\r\n return \"UNKNOWN\";\r\n }\r\n }\r\n\tvoid Model::writeBinary(FILE* file)\r\n\t{\r\n std::list _bonenames;\r\n for (std::vector::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr)\r\n {\r\n (*itr)->loadBoneNames(_bonenames);\r\n }\r\n for (std::vector::const_iterator itr = nodes.begin(); itr != nodes.end(); ++itr)\r\n {\r\n bool skeleton=false;\r\n (*itr)->checkIsSkeleton(skeleton,_bonenames);\r\n (*itr)->setSkeleton(skeleton);\r\n }\r\n\t\tunsigned int size = meshes.size();\r\n if(size>0)\r\n {\r\n meshes[0]->object.fPosition = ftell(file);\t\r\n }\r\n\t\twrite(size, file);\r\n \/\/ write mesh\r\n\t\tfor(auto itr = meshes.begin(); itr != meshes.end(); itr++)\r\n\t\t{\r\n\t\t\t(*itr)->writeBinary(file);\r\n\t\t}\r\n\t\t\r\n\t\t\/\/ write material\r\n\t size = materials.size();\r\n if(size>0)\r\n {\r\n materials[0]->object.fPosition = ftell(file);\t\r\n }\r\n\t\twrite(size, file);\r\n\t\tfor(auto itr = materials.begin(); itr != materials.end(); itr++)\r\n\t\t{\r\n\t\t\t(*itr)->writeBinary(file);\r\n\t\t}\r\n\t\t\/\/ node num\r\n size = nodes.size();\r\n if(size>0)\r\n {\r\n nodes[0]->object.fPosition = ftell(file);\t\r\n }\r\n write(size, file);\r\n for(auto itr = nodes.begin(); itr != nodes.end(); itr++)\r\n {\r\n (*itr)->writeBinary(file);\r\n }\r\n\r\n\t\t\/\/ animations\r\n write(size, file);\r\n for(auto itr : animations)\r\n {\r\n itr->object.fPosition = ftell(file);\r\n itr->writeBinary(file);\r\n }\r\n\t}\r\n\r\n\tvoid Mesh::writeBinary(FILE* file)\r\n\t{\r\n\t\t\/\/ attribute\r\n\t\tattributes.writeBinary(file);\r\n\t\t\r\n\t\t\/\/ write vertices\r\n\t\tif(vertices.size() > 0)\r\n\t\t{\r\n\t\t\tunsigned int size = vertices.size();\r\n\t\t\twrite(size, file);\r\n\t\t\twrite(&vertices[0],size,file);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\twrite((unsigned int)0, file);\r\n\t\t}\r\n\r\n\t\t\/\/ write parts.\r\n\t\tunsigned int size = parts.size();\r\n\t\twrite(size, file);\r\n\t\tfor(auto itr = parts.begin(); itr != parts.end(); itr++)\r\n\t\t{\r\n (*itr)->writeBinary(file);\r\n \r\n\r\n\t\t}\r\n\t}\r\n void MeshPart::writeBinary(FILE* file)\r\n {\r\n write(id, file);\r\n \/\/ indices size\r\n unsigned int size = indices.size();\r\n write(size, file);\r\n \/\/ indices.\r\n for(auto itr1 = indices.begin(); itr1 != indices.end(); itr1++)\r\n write(*itr1,file);\r\n \/\/aabb\r\n write(aabb, 6, file);\r\n }\r\n\tvoid Attributes::writeBinary(FILE* file)\r\n\t{\r\n\r\n\t\tstd::vector attribs;\r\n\t\tMeshVertexAttrib attrib;\r\n for (unsigned int i = 0; i < length(); i++)\r\n {\r\n std::string key = name(i);\r\n attrib = attributemap.find(key)->second;\r\n attribs.push_back(attrib);\r\n if(key == \"VERTEX_ATTRIB_BLEND_INDEX\")\r\n {\r\n break;\r\n }\r\n }\r\n\t\tunsigned int size = attribs.size();\r\n write(size, file);\r\n for( int i = 0 ; i < size ; i++ )\r\n {\r\n write(attribs[i].size, file);\r\n write(attribs[i].type, file);\r\n write(attribs[i].name, file);\r\n }\r\n\t}\r\n\t\r\n\tvoid Material::writeBinary(FILE* file)\r\n\t{\r\n\t\twrite(id, file);\r\n write(diffuse.value, 3, file);\r\n write(ambient.value, 3, file);\r\n write(emissive.value, 3, file);\r\n write(opacity.value,file);\r\n write(specular.value, 3, file);\r\n write(shininess.value,file);\r\n unsigned int size = textures.size();\r\n write(size, file);\r\n for(auto itr = textures.begin(); itr != textures.end(); itr++)\r\n {\r\n write((*itr)->id, file);\r\n write((*itr)->path, file);\r\n write((*itr)->uvTranslation, 2, file);\r\n write((*itr)->uvScale, 2, file);\r\n std::string wrapModeU=getWrapModeUseString((*itr)->wrapModeU);\r\n std::string wrapModeV=getWrapModeUseString((*itr)->wrapModeV);\r\n std::string type= getTextureUseString((*itr)->usage);\r\n write(type,file);\r\n write(wrapModeU,file);\r\n write(wrapModeV,file);\r\n }\r\n\t}\r\n\t\r\n\tvoid Node::writeBinary(FILE* file)\r\n\t{\r\n\t\twrite(id, file);\r\n write(_skeleton, file);\r\n \/\/ rotation scale translation\r\n write(transforms, 16, file);\r\n\t\t\/\/write(transform.scale, 3, file);\r\n\t\t\/\/write(transform.translation, 3, file);\r\n \/\/ node part\r\n unsigned int partsSize = parts.size();\r\n\t\twrite(partsSize,file);\r\n\t\tif(parts.size()>0)\r\n\t\t{\r\n for(int i = 0 ; i < parts.size() ; i++ )\r\n {\r\n NodePart* nodepart = parts[i];\r\n if(nodepart)\r\n {\r\n if(nodepart->meshPart)\r\n {\r\n \/\/meshpartid\r\n write(nodepart->meshPart->id, file);\r\n }\r\n else\r\n {\r\n write(\"null\", file);\r\n }\r\n \/\/materialid\r\n if(nodepart->material)\r\n {\r\n write(nodepart->material->id, file);\r\n }\r\n else\r\n {\r\n write(\"null\", file);\r\n }\r\n \/\/ bone num\r\n unsigned int size = nodepart->bones.size();\r\n write(size, file);\r\n for(auto itr = nodepart->bones.begin(); itr != nodepart->bones.end(); itr++)\r\n {\r\n \/\/ write name\r\n write(itr->first->id, file);\r\n \/\/ write transform\r\n float tmp[16];\r\n for(int i = 0; i < 4; i++)\r\n {\r\n for(int j = 0; j < 4; j++)\r\n {\r\n tmp[i*4 + j] = itr->second.Double44()[i][j];\r\n }\r\n }\r\n write(tmp, 16, file);\r\n }\r\n \/\/ uvMapping\r\n size = nodepart->uvMapping.size();\r\n write(size, file);\r\n for(auto itr = nodepart->uvMapping.begin(); itr != nodepart->uvMapping.end(); itr++)\r\n {\r\n unsigned int size = itr->size();\r\n write(size, file);\r\n \/\/TextureIndex\r\n for (auto tt = (*itr).begin(); tt != (*itr).end(); ++tt)\r\n {\r\n unsigned int index = nodepart->material->getTextureIndex(*tt);\r\n write(index, file);\r\n }\r\n }\r\n }\r\n }\r\n\t\t}\r\n \/\/ children\r\n unsigned int childrenSize = children.size();\r\n write(childrenSize,file);\r\n\t\tfor(auto itr = children.begin(); itr != children.end(); itr++)\r\n\t\t{\r\n\t\t\tNode* node = *itr;\r\n if(node)\r\n {\r\n node->writeBinary(file);\r\n }\r\n\t\t}\r\n\t}\r\n\tvoid Animation::writeBinary(FILE* file)\r\n\t{\r\n\t write(id, file);\r\n\t\twrite(length, file);\r\n\t\twrite(static_cast(nodeAnimations.size()), file);\r\n\r\n\t\tfor(auto itr = nodeAnimations.begin(); itr != nodeAnimations.end(); itr++)\r\n\t\t{\r\n\t\t\tNodeAnimation* nodeanim = *itr;\r\n\t\t\twrite(nodeanim->node->id, file);\r\n\t\t\t\r\n\t\t\twrite(static_cast(nodeanim->keyframes.size()), file);\r\n\t\t\t\r\n\t\t\tfor(auto itr1 = nodeanim->keyframes.begin(); itr1 != nodeanim->keyframes.end(); itr1++)\r\n\t\t\t{\r\n\t\t\t\tKeyframe* keyframe = *itr1;\r\n \r\n\t\t\t\t\/\/ write time\r\n\t\t\t\twrite(keyframe->time, file);\r\n \r\n \/\/ write transform flag\r\n unsigned char transformflag(0);\r\n if (keyframe->hasRotation)\r\n transformflag |= 0x01;\r\n if (keyframe->hasScale)\r\n transformflag |= (0x01 << 1);\r\n if (keyframe->hasTranslation)\r\n transformflag |= (0x01 << 2);\r\n \r\n write(transformflag, file);\r\n \r\n \/\/ write rotation val\r\n if (keyframe->hasRotation)\r\n write(keyframe->rotation, 4, file);\r\n \r\n \/\/ write scale val\r\n if (keyframe->hasScale)\r\n write(keyframe->scale, 3, file);\r\n \r\n \/\/ write translation val\r\n if (keyframe->hasTranslation)\r\n write(keyframe->translation, 3, file);\r\n\t\t\t}\r\n\t\t}\r\n }\r\n} \r\n}<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 Ratcoin dev-team\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"processNetwork.h\"\n\n#include \"common\/nodesManager.h\"\n#include \"common\/communicationProtocol.h\"\n#include \"common\/actionHandler.h\"\n\n#include \"common\/nodeMedium.h\"\n\n#include \"configureMonitorActionHandler.h\"\n#include \"monitor\/connectNodeAction.h\"\n#include \"monitor\/reputationTracer.h\"\n#include \"monitor\/monitorNodeMedium.h\"\n\nnamespace monitor\n{\n\nCProcessNetwork * CProcessNetwork::ms_instance = NULL;\n\nCProcessNetwork*\nCProcessNetwork::getInstance()\n{\n\tif ( !ms_instance )\n\t{\n\t\tms_instance = new CProcessNetwork();\n\t};\n\treturn ms_instance;\n}\n\nbool\nCProcessNetwork::processMessage(common::CSelfNode* pfrom, CDataStream& vRecv)\n{\n\tstd::vector< common::CMessage > messages;\n\tvRecv >> messages;\n\n\/\/ it is stupid to call this over and over again\n\tif ( !CReputationTracker::getInstance()->getMediumForNode( pfrom ) )\n\t{\n\t\tCReputationTracker::getInstance()->addNode( new CMonitorNodeMedium( pfrom ) );\n\t}\n\n\tBOOST_FOREACH( common::CMessage const & message, messages )\n\t{\n\n\n\t\tif (\n\t\t\t\t message.m_header.m_payloadKind == common::CPayloadKind::RoleInfo\n\t\t\t\t|| message.m_header.m_payloadKind == common::CPayloadKind::Result\n\t\t\t\t|| message.m_header.m_payloadKind == common::CPayloadKind::NetworkInfo\n\t\t\t\t|| message.m_header.m_payloadKind == common::CPayloadKind::NetworkInfo\n\t\t\t\t)\n\t\t{\n\t\t\tcommon::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom );\n\n\t\t\tif ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) )\n\t\t\t{\n\t\t\t\tnodeMedium->setResponse( message.m_header.m_actionKey, common::CMessageResult( message, convertToInt( nodeMedium->getNode() ) ) );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t}\n\t\t}\n\t\t\/*\t{\n\t\tCPubKey pubKey;\n\t\t\tif( !CTrackerNodesManager::getInstance()->getPublicKey( pfrom->addr, pubKey ) )\n\t\t\t{\n\t\t\t\tassert( !\"for now assert this\" );\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}*\/\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::InfoReq )\n\t\t{\n\t\t\t\/\/\n\t\t}\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::IntroductionReq )\n\t\t{\n\t\t\tcommon::CIdentifyMessage identifyMessage;\n\t\t\tconvertPayload( message, identifyMessage );\n\n\t\t\tcommon::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom );\n\n\t\t\tif ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) )\n\t\t\t{\n\t\t\t\tnodeMedium->setResponse( message.m_header.m_actionKey, common::CIdentificationResult( identifyMessage.m_payload, identifyMessage.m_signed, identifyMessage.m_key, pfrom->addr ) );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCConnectNodeAction * connectNodeAction= new CConnectNodeAction(\n\t\t\t\t\t\t\t nodeMedium->getNode()->addr\n\t\t\t\t\t\t\t, message.m_header.m_actionKey\n\t\t\t\t\t\t\t, identifyMessage.m_payload\n\t\t\t\t\t\t\t, convertToInt( nodeMedium->getNode() ) );\n\n\t\t\t\tcommon::CActionHandler< MonitorResponses >::getInstance()->executeAction( connectNodeAction );\n\t\t\t}\n\n\t\t}\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::Ack )\n\t\t{\n\t\t\tcommon::CAck ack;\n\n\t\t\tcommon::convertPayload( message, ack );\n\n\t\t\tcommon::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom );\n\n\t\t\tif ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) )\n\t\t\t{\n\t\t\t\tnodeMedium->setResponse( message.m_header.m_actionKey, common::CAckResult( convertToInt( nodeMedium->getNode() ) ) );\n\t\t\t}\n\t\t}\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::Uninitiated )\n\t\t{\n\t\t\t\/\/\n\t\t}\n\t}\n\t\/*\n\n\n*\/\n\treturn true;\n}\n\n\nbool\nCProcessNetwork::sendMessages(common::CSelfNode* pto, bool fSendTrickle)\n{\n\tpto->sendMessages();\n\n\treturn true;\n}\n\n}\n\ninfo exchange\/\/ Copyright (c) 2014 Ratcoin dev-team\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"processNetwork.h\"\n\n#include \"common\/nodesManager.h\"\n#include \"common\/communicationProtocol.h\"\n#include \"common\/actionHandler.h\"\n\n#include \"common\/nodeMedium.h\"\n\n#include \"configureMonitorActionHandler.h\"\n#include \"monitor\/connectNodeAction.h\"\n#include \"monitor\/reputationTracer.h\"\n#include \"monitor\/monitorNodeMedium.h\"\n\nnamespace monitor\n{\n\nCProcessNetwork * CProcessNetwork::ms_instance = NULL;\n\nCProcessNetwork*\nCProcessNetwork::getInstance()\n{\n\tif ( !ms_instance )\n\t{\n\t\tms_instance = new CProcessNetwork();\n\t};\n\treturn ms_instance;\n}\n\nbool\nCProcessNetwork::processMessage(common::CSelfNode* pfrom, CDataStream& vRecv)\n{\n\tstd::vector< common::CMessage > messages;\n\tvRecv >> messages;\n\n\/\/ it is stupid to call this over and over again\n\tif ( !CReputationTracker::getInstance()->getMediumForNode( pfrom ) )\n\t{\n\t\tCReputationTracker::getInstance()->addNode( new CMonitorNodeMedium( pfrom ) );\n\t}\n\n\tBOOST_FOREACH( common::CMessage const & message, messages )\n\t{\n\n\n\t\tif (\n\t\t\t\t message.m_header.m_payloadKind == common::CPayloadKind::RoleInfo\n\t\t\t\t|| message.m_header.m_payloadKind == common::CPayloadKind::Result\n\t\t\t\t|| message.m_header.m_payloadKind == common::CPayloadKind::NetworkInfo\n\t\t\t\t|| message.m_header.m_payloadKind == common::CPayloadKind::InfoRes\n\t\t\t\t)\n\t\t{\n\t\t\tcommon::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom );\n\n\t\t\tif ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) )\n\t\t\t{\n\t\t\t\tnodeMedium->setResponse( message.m_header.m_actionKey, common::CMessageResult( message, convertToInt( nodeMedium->getNode() ) ) );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t}\n\t\t}\n\t\t\/*\t{\n\t\tCPubKey pubKey;\n\t\t\tif( !CTrackerNodesManager::getInstance()->getPublicKey( pfrom->addr, pubKey ) )\n\t\t\t{\n\t\t\t\tassert( !\"for now assert this\" );\n\t\t\t\treturn true;\n\t\t\t}\n\t\t}*\/\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::InfoReq )\n\t\t{\n\t\t\t\/\/\n\t\t}\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::IntroductionReq )\n\t\t{\n\t\t\tcommon::CIdentifyMessage identifyMessage;\n\t\t\tconvertPayload( message, identifyMessage );\n\n\t\t\tcommon::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom );\n\n\t\t\tif ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) )\n\t\t\t{\n\t\t\t\tnodeMedium->setResponse( message.m_header.m_actionKey, common::CIdentificationResult( identifyMessage.m_payload, identifyMessage.m_signed, identifyMessage.m_key, pfrom->addr ) );\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tCConnectNodeAction * connectNodeAction= new CConnectNodeAction(\n\t\t\t\t\t\t\t nodeMedium->getNode()->addr\n\t\t\t\t\t\t\t, message.m_header.m_actionKey\n\t\t\t\t\t\t\t, identifyMessage.m_payload\n\t\t\t\t\t\t\t, convertToInt( nodeMedium->getNode() ) );\n\n\t\t\t\tcommon::CActionHandler< MonitorResponses >::getInstance()->executeAction( connectNodeAction );\n\t\t\t}\n\n\t\t}\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::Ack )\n\t\t{\n\t\t\tcommon::CAck ack;\n\n\t\t\tcommon::convertPayload( message, ack );\n\n\t\t\tcommon::CNodeMedium< MonitorResponses > * nodeMedium = CReputationTracker::getInstance()->getMediumForNode( pfrom );\n\n\t\t\tif ( common::CNetworkActionRegister::getInstance()->isServicedByAction( message.m_header.m_actionKey ) )\n\t\t\t{\n\t\t\t\tnodeMedium->setResponse( message.m_header.m_actionKey, common::CAckResult( convertToInt( nodeMedium->getNode() ) ) );\n\t\t\t}\n\t\t}\n\t\telse if ( message.m_header.m_payloadKind == common::CPayloadKind::Uninitiated )\n\t\t{\n\t\t\t\/\/\n\t\t}\n\t}\n\t\/*\n\n\n*\/\n\treturn true;\n}\n\n\nbool\nCProcessNetwork::sendMessages(common::CSelfNode* pto, bool fSendTrickle)\n{\n\tpto->sendMessages();\n\n\treturn true;\n}\n\n}\n\n<|endoftext|>"} {"text":"\/* $Id: middlewareTimerTests.cpp,v 1.1.2.5 2012\/11\/30 17:32:33 matthewmulhern Exp $\n *\n * OpenMAMA: The open middleware agnostic messaging API\n * Copyright (C) 2011 NYSE Technologies, Inc.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \n#include \"mama\/mama.h\"\n#include \"MainUnitTestC.h\"\n#include \n#include \"bridge.h\"\n#include \"mama\/types.h\"\n\nusing std::cout;\nusing std::endl;\n\n\nclass MiddlewareTimerTests : public ::testing::Test\n{\nprotected:\n MiddlewareTimerTests(void);\n virtual ~MiddlewareTimerTests(void);\n\n virtual void SetUp(void);\n virtual void TearDown(void);\n\n mamaBridge mBridge;\n};\n\nMiddlewareTimerTests::MiddlewareTimerTests(void)\n{\n}\n\nMiddlewareTimerTests::~MiddlewareTimerTests(void)\n{\n}\n\nvoid MiddlewareTimerTests::SetUp(void)\n{\n\tmama_loadBridge (&mBridge,getMiddleware());\n}\n\nvoid MiddlewareTimerTests::TearDown(void)\n{\n}\n\nstatic void MAMACALLTYPE onTick(mamaTimer timer, void* closure)\n{\n}\n\nstatic void MAMACALLTYPE onTimerDestroy(mamaTimer timer, void* closure)\n{\n}\n\/*===================================================================\n = mamaTimer bridge functions =\n ====================================================================*\/\n\nTEST_F (MiddlewareTimerTests, create)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n \n}\n\nTEST_F (MiddlewareTimerTests, createInvalidResult)\n{\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(NULL, nativeQueueHandle,\n action, onTimerDestroyed,\n interval, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidNativeQueueHandle)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, NULL,\n action, onTimerDestroyed,\n interval, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidActionCB)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n NULL, onTimerDestroyed,\n interval, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidDestroyCB)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n action, NULL,\n interval, parent, closure));\n}\n\n\/* TODO: Determine if interval maybe a NULL value *\/\nTEST_F (MiddlewareTimerTests, DISABLED_createInvalidInterval)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n action, onTimerDestroyed,\n NULL, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidParent)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n action, onTimerDestroyed,\n interval, NULL, closure));\n}\n\nTEST_F (MiddlewareTimerTests, destroy)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge, &mDefaultQueue));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerDestroy(timer));\n \n}\n\nTEST_F (MiddlewareTimerTests, destroyInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerDestroy(NULL));\n}\n\nTEST_F (MiddlewareTimerTests, reset)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerReset(timer));\n \n}\n\nTEST_F (MiddlewareTimerTests, resetInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerReset(NULL));\n}\n\nTEST_F (MiddlewareTimerTests, setInterval)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n mama_f64_t newInterval = 10;\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerSetInterval(timer,newInterval));\n \n}\n\nTEST_F (MiddlewareTimerTests, setIntervalInvalidTimerBridge)\n{\n mama_f64_t interval = 500;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerSetInterval(NULL,interval));\n}\n\n\/* TODO: Determine if interval can be set to a NULL value (0.0 in this case) *\/\nTEST_F (MiddlewareTimerTests, DISABLED_setIntervalInvalidInterval)\n{\n timerBridge timer = (timerBridge) NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerSetInterval(timer,NULL));\n}\n\nTEST_F (MiddlewareTimerTests, getInterval)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n mama_f64_t newInterval = 10;\n mama_f64_t testInterval = 5;\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerSetInterval(timer,newInterval));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerGetInterval(timer,&testInterval));\n\n ASSERT_EQ(testInterval, newInterval);\n \n}\n\nTEST_F (MiddlewareTimerTests, getIntervalInvalidTimerBridge)\n{\n mama_f64_t interval = 500;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaTimerGetInterval(NULL,&interval));\n}\n\nTEST_F (MiddlewareTimerTests, getIntervalInvalidInterval)\n{\n timerBridge timer = (timerBridge) NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerGetInterval(timer,NULL));\n}\nUNIT TESTS: Disabling the invalid timer destroy callback test.\/* $Id: middlewareTimerTests.cpp,v 1.1.2.5 2012\/11\/30 17:32:33 matthewmulhern Exp $\n *\n * OpenMAMA: The open middleware agnostic messaging API\n * Copyright (C) 2011 NYSE Technologies, Inc.\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA\n * 02110-1301 USA\n *\/\n\n#include \n#include \"mama\/mama.h\"\n#include \"MainUnitTestC.h\"\n#include \n#include \"bridge.h\"\n#include \"mama\/types.h\"\n\nusing std::cout;\nusing std::endl;\n\n\nclass MiddlewareTimerTests : public ::testing::Test\n{\nprotected:\n MiddlewareTimerTests(void);\n virtual ~MiddlewareTimerTests(void);\n\n virtual void SetUp(void);\n virtual void TearDown(void);\n\n mamaBridge mBridge;\n};\n\nMiddlewareTimerTests::MiddlewareTimerTests(void)\n{\n}\n\nMiddlewareTimerTests::~MiddlewareTimerTests(void)\n{\n}\n\nvoid MiddlewareTimerTests::SetUp(void)\n{\n\tmama_loadBridge (&mBridge,getMiddleware());\n}\n\nvoid MiddlewareTimerTests::TearDown(void)\n{\n}\n\nstatic void MAMACALLTYPE onTick(mamaTimer timer, void* closure)\n{\n}\n\nstatic void MAMACALLTYPE onTimerDestroy(mamaTimer timer, void* closure)\n{\n}\n\/*===================================================================\n = mamaTimer bridge functions =\n ====================================================================*\/\n\nTEST_F (MiddlewareTimerTests, create)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n \n}\n\nTEST_F (MiddlewareTimerTests, createInvalidResult)\n{\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(NULL, nativeQueueHandle,\n action, onTimerDestroyed,\n interval, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidNativeQueueHandle)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, NULL,\n action, onTimerDestroyed,\n interval, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidActionCB)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n NULL, onTimerDestroyed,\n interval, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, DISABLED_createInvalidDestroyCB)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n action, NULL,\n interval, parent, closure));\n}\n\n\/* TODO: Determine if interval maybe a NULL value *\/\nTEST_F (MiddlewareTimerTests, DISABLED_createInvalidInterval)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n mamaTimer parent = (mamaTimer) NOT_NULL;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n action, onTimerDestroyed,\n NULL, parent, closure));\n}\n\nTEST_F (MiddlewareTimerTests, createInvalidParent)\n{\n timerBridge result = (timerBridge) NOT_NULL;\n void* nativeQueueHandle = NOT_NULL;\n mamaTimerCb action = (mamaTimerCb) NOT_NULL;\n mamaTimerCb onTimerDestroyed = (mamaTimerCb) NOT_NULL;\n double interval = 0.0;\n void* closure = NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerCreate(&result, nativeQueueHandle,\n action, onTimerDestroyed,\n interval, NULL, closure));\n}\n\nTEST_F (MiddlewareTimerTests, destroy)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge, &mDefaultQueue));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerDestroy(timer));\n \n}\n\nTEST_F (MiddlewareTimerTests, destroyInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerDestroy(NULL));\n}\n\nTEST_F (MiddlewareTimerTests, reset)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n\n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerReset(timer));\n \n}\n\nTEST_F (MiddlewareTimerTests, resetInvalid)\n{\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, mBridge->bridgeMamaTimerReset(NULL));\n}\n\nTEST_F (MiddlewareTimerTests, setInterval)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n mama_f64_t newInterval = 10;\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerSetInterval(timer,newInterval));\n \n}\n\nTEST_F (MiddlewareTimerTests, setIntervalInvalidTimerBridge)\n{\n mama_f64_t interval = 500;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerSetInterval(NULL,interval));\n}\n\n\/* TODO: Determine if interval can be set to a NULL value (0.0 in this case) *\/\nTEST_F (MiddlewareTimerTests, DISABLED_setIntervalInvalidInterval)\n{\n timerBridge timer = (timerBridge) NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerSetInterval(timer,NULL));\n}\n\nTEST_F (MiddlewareTimerTests, getInterval)\n{\n timerBridge timer = NULL;\n double interval = 1;\n mamaTimer fakeParent = (mamaTimer) NOT_NULL;\n void* closure = NULL;\n void* handle = NULL;\n mamaQueue mDefaultQueue = NULL;\n mama_f64_t newInterval = 10;\n mama_f64_t testInterval = 5;\n \n ASSERT_EQ(MAMA_STATUS_OK,\n mama_getDefaultEventQueue(mBridge,&mDefaultQueue));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mamaQueue_getNativeHandle(mDefaultQueue, &handle));\n \n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerCreate(&timer, handle, onTick,\n onTimerDestroy, interval,\n fakeParent, closure));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerSetInterval(timer,newInterval));\n\n ASSERT_EQ(MAMA_STATUS_OK, \n mBridge->bridgeMamaTimerGetInterval(timer,&testInterval));\n\n ASSERT_EQ(testInterval, newInterval);\n \n}\n\nTEST_F (MiddlewareTimerTests, getIntervalInvalidTimerBridge)\n{\n mama_f64_t interval = 500;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG,\n mBridge->bridgeMamaTimerGetInterval(NULL,&interval));\n}\n\nTEST_F (MiddlewareTimerTests, getIntervalInvalidInterval)\n{\n timerBridge timer = (timerBridge) NOT_NULL;\n\n ASSERT_EQ (MAMA_STATUS_NULL_ARG, \n mBridge->bridgeMamaTimerGetInterval(timer,NULL));\n}\n<|endoftext|>"} {"text":"\/****************************************************************\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* All contents are licensed under LGPL V2.1 *\/\n\/* See LICENSE for full restrictions *\/\n\/****************************************************************\/\n#include \"EulerAngleProvider2RGBAux.h\"\n#include \"GrainTracker.h\"\n#include \"EulerAngleProvider.h\"\n#include \"Euler2RGB.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addClassDescription(\"Output RGB representation of crystal orientation from user object to an AuxVariable. The entire domain must have the same crystal structure.\");\n MooseEnum sd_enum = MooseEnum(\"100=1 010=2 001=3\", \"001\");\n params.addParam(\"sd\", sd_enum, \"Reference sample direction\");\n MooseEnum structure_enum = MooseEnum(\"cubic=43 hexagonal=62 tetragonal=42 trigonal=32 orthorhombic=22 monoclinic=2 triclinic=1\");\n params.addRequiredParam(\"crystal_structure\",structure_enum,\"Crystal structure of the material\");\n MooseEnum output_types = MooseEnum(\"red green blue scalar\", \"scalar\");\n params.addParam(\"output_type\", output_types, \"Type of value that will be outputted\");\n params.addRequiredParam(\"euler_angle_provider\", \"Name of Euler angle provider user object\");\n params.addRequiredParam(\"grain_tracker\", \"The GrainTracker UserObject to get values from.\");\n params.addParam(\"no_grain_color\", Point(0, 0, 0), \"RGB value of color used to represent area with no grains, defaults to black\");\n return params;\n}\n\nEulerAngleProvider2RGBAux::EulerAngleProvider2RGBAux(const InputParameters & parameters) :\n AuxKernel(parameters),\n _sd(getParam(\"sd\")),\n _xtal_class(getParam(\"crystal_structure\")),\n _output_type(getParam(\"output_type\")),\n _euler(getUserObject(\"euler_angle_provider\")),\n _grain_tracker(getUserObject(\"grain_tracker\")),\n _no_grain_color(getParam(\"no_grain_color\"))\n{\n}\n\nvoid\nEulerAngleProvider2RGBAux::precalculateValue()\n{\n \/\/ ID of unique grain at current point\n const int grain_id = _grain_tracker.getEntityValue((isNodal() ? _current_node->id() : _current_elem->id()),\n FeatureFloodCount::FieldType::UNIQUE_REGION, 0);\n \/\/ Recover euler angles for current grain\n RealVectorValue angles;\n if (grain_id >= 0)\n angles = _euler.getEulerAngles(grain_id);\n\n \/\/ Assign correct RGB value either from euler2RGB or from _no_grain_color\n Point RGB;\n if (grain_id < 0) \/\/If not in a grain, return _no_grain_color\n RGB = _no_grain_color;\n else\n RGB = euler2RGB(_sd, angles(0) \/ 180.0 * libMesh::pi, angles(1) \/ 180.0 * libMesh::pi, angles(2) \/ 180.0 * libMesh::pi, 1.0, _xtal_class);\n\n \/\/ Create correct scalar output\n if (_output_type < 3)\n _value = RGB(_output_type);\n else if (_output_type == 3)\n {\n Real RGBint = 0.0;\n for (unsigned int i = 0; i < 3; ++i)\n RGBint = 256 * RGBint + (RGB(i) >= 1 ? 255 : std::floor(RGB(i) * 256.0));\n\n _value = RGBint;\n }\n else\n mooseError(\"Incorrect value for output_type in EulerAngleProvider2RGBAux\");\n}\n\nReal\nEulerAngleProvider2RGBAux::computeValue()\n{\n return _value;\n}\nCheck grain id validity (#8402)\/****************************************************************\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* All contents are licensed under LGPL V2.1 *\/\n\/* See LICENSE for full restrictions *\/\n\/****************************************************************\/\n#include \"EulerAngleProvider2RGBAux.h\"\n#include \"GrainTracker.h\"\n#include \"EulerAngleProvider.h\"\n#include \"Euler2RGB.h\"\n\ntemplate<>\nInputParameters validParams()\n{\n InputParameters params = validParams();\n params.addClassDescription(\"Output RGB representation of crystal orientation from user object to an AuxVariable. The entire domain must have the same crystal structure.\");\n MooseEnum sd_enum = MooseEnum(\"100=1 010=2 001=3\", \"001\");\n params.addParam(\"sd\", sd_enum, \"Reference sample direction\");\n MooseEnum structure_enum = MooseEnum(\"cubic=43 hexagonal=62 tetragonal=42 trigonal=32 orthorhombic=22 monoclinic=2 triclinic=1\");\n params.addRequiredParam(\"crystal_structure\",structure_enum,\"Crystal structure of the material\");\n MooseEnum output_types = MooseEnum(\"red green blue scalar\", \"scalar\");\n params.addParam(\"output_type\", output_types, \"Type of value that will be outputted\");\n params.addRequiredParam(\"euler_angle_provider\", \"Name of Euler angle provider user object\");\n params.addRequiredParam(\"grain_tracker\", \"The GrainTracker UserObject to get values from.\");\n params.addParam(\"no_grain_color\", Point(0, 0, 0), \"RGB value of color used to represent area with no grains, defaults to black\");\n return params;\n}\n\nEulerAngleProvider2RGBAux::EulerAngleProvider2RGBAux(const InputParameters & parameters) :\n AuxKernel(parameters),\n _sd(getParam(\"sd\")),\n _xtal_class(getParam(\"crystal_structure\")),\n _output_type(getParam(\"output_type\")),\n _euler(getUserObject(\"euler_angle_provider\")),\n _grain_tracker(getUserObject(\"grain_tracker\")),\n _no_grain_color(getParam(\"no_grain_color\"))\n{\n}\n\nvoid\nEulerAngleProvider2RGBAux::precalculateValue()\n{\n \/\/ ID of unique grain at current point\n const int grain_id = _grain_tracker.getEntityValue((isNodal() ? _current_node->id() : _current_elem->id()),\n FeatureFloodCount::FieldType::UNIQUE_REGION, 0);\n\n \/\/ Recover Euler angles for current grain and assign correct\n \/\/ RGB value either from euler2RGB or from _no_grain_color\n Point RGB;\n if (grain_id >= 0 && grain_id < _euler.getGrainNum())\n {\n const RealVectorValue & angles = _euler.getEulerAngles(grain_id);\n RGB = euler2RGB(_sd, angles(0) \/ 180.0 * libMesh::pi, angles(1) \/ 180.0 * libMesh::pi, angles(2) \/ 180.0 * libMesh::pi, 1.0, _xtal_class);\n }\n else\n RGB = _no_grain_color;\n\n \/\/ Create correct scalar output\n if (_output_type < 3)\n _value = RGB(_output_type);\n else if (_output_type == 3)\n {\n Real RGBint = 0.0;\n for (unsigned int i = 0; i < 3; ++i)\n RGBint = 256 * RGBint + (RGB(i) >= 1 ? 255 : std::floor(RGB(i) * 256.0));\n\n _value = RGBint;\n }\n else\n mooseError(\"Incorrect value for output_type in EulerAngleProvider2RGBAux\");\n}\n\nReal\nEulerAngleProvider2RGBAux::computeValue()\n{\n return _value;\n}\n<|endoftext|>"} {"text":"\/\/---------------------------------------------------------------------------\/\/\n\/*\n Copyright (c) 2014, Stuart R. Slattery\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n *: Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n *: Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n *: Neither the name of the Oak Ridge National Laboratory nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\file consistent_interpolation.cpp\n * \\author Stuart Slattery\n * \\brief STK file-based consistent interpolation example.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"DTK_STKMeshDOFVector.hpp\"\n#include \"DTK_STKMeshHelpers.hpp\"\n#include \"DTK_STKMeshManager.hpp\"\n#include \"DTK_ConsistentInterpolationOperator.hpp\"\n\n#include \n#include \"Teuchos_CommandLineProcessor.hpp\"\n#include \"Teuchos_XMLParameterListCoreHelpers.hpp\"\n#include \"Teuchos_ParameterList.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Example driver.\n\/\/---------------------------------------------------------------------------\/\/\nint main(int argc, char* argv[])\n{\n \/\/ INITIALIZATION\n \/\/ --------------\n\n \/\/ Setup communication.\n Teuchos::GlobalMPISession mpiSession(&argc,&argv);\n\n Teuchos::RCP > comm = \n\tTeuchos::DefaultComm::getComm();\n\n \/\/ Read in command line options.\n std::string xml_input_filename;\n Teuchos::CommandLineProcessor clp(false);\n clp.setOption( \"xml-in-file\",\n\t\t &xml_input_filename,\n\t\t \"The XML file to read into a parameter list\" );\n clp.parse(argc,argv);\n\n \/\/ Build the parameter list from the xml input.\n Teuchos::RCP plist =\n\tTeuchos::rcp( new Teuchos::ParameterList() );\n Teuchos::updateParametersFromXmlFile(\n\txml_input_filename, Teuchos::inoutArg(*plist) );\n\n \/\/ Read command-line options\n std::string source_mesh_input_file = \n\tplist->get(\"Source Mesh Input File\");\n std::string source_mesh_output_file = \n\tplist->get(\"Source Mesh Output File\");\n std::string source_mesh_part_name = \n\tplist->get(\"Source Mesh Part\");\n std::string target_mesh_input_file = \n\tplist->get(\"Target Mesh Input File\");\n std::string target_mesh_output_file = \n\tplist->get(\"Target Mesh Output File\");\n std::string target_mesh_part_name = \n\tplist->get(\"Target Mesh Part\");\n\n \/\/ Get the raw mpi communicator (basic typedef in STK).\n Teuchos::RCP > mpi_comm = \n\tTeuchos::rcp_dynamic_cast >( comm );\n Teuchos::RCP > opaque_comm = \n\tmpi_comm->getRawMpiComm();\n stk::ParallelMachine parallel_machine = (*opaque_comm)();\n\n \n \/\/ SOURCE MESH READ\n \/\/ ----------------\n\n \/\/ Load the source mesh.\n stk::io::StkMeshIoBroker src_broker( parallel_machine );\n std::size_t src_input_index = src_broker.add_mesh_database(\n\tsource_mesh_input_file, \"exodus\", stk::io::READ_MESH );\n src_broker.set_active_mesh( src_input_index );\n src_broker.create_input_mesh();\n\n \/\/ Add a nodal field to the source part.\n stk::mesh::Field& source_field = \n\tsrc_broker.meta_data().declare_field >( \n\t stk::topology::NODE_RANK, \"u_src\" );\n stk::mesh::Part* src_part = \n\tsrc_broker.meta_data().get_part( source_mesh_part_name );\n stk::mesh::put_field( source_field, *src_part );\n\n \/\/ Create the source bulk data.\n src_broker.populate_bulk_data();\n Teuchos::RCP src_bulk_data = \n\tTeuchos::rcpFromRef( src_broker.bulk_data() );\n\n \/\/ Put some data in the source field. We will use the distance of the node\n \/\/ from the origin as the data.\n stk::mesh::Selector src_stk_selector( *src_part );\n stk::mesh::BucketVector src_part_buckets = \n\tsrc_stk_selector.get_buckets( stk::topology::NODE_RANK );\n std::vector src_part_nodes;\n stk::mesh::get_selected_entities( \n\tsrc_stk_selector, src_part_buckets, src_part_nodes );\n Intrepid::FieldContainer src_node_coords =\n\tDataTransferKit::STKMeshHelpers::getEntityNodeCoordinates(\n\t Teuchos::Array(src_part_nodes), *src_bulk_data );\n double* src_field_data;\n int num_src_part_nodes = src_part_nodes.size();\n for ( int n = 0; n < num_src_part_nodes; ++n )\n {\n\tsrc_field_data = stk::mesh::field_data( source_field, src_part_nodes[n] );\n\tsrc_field_data[0] = src_node_coords(n,0,0)*src_node_coords(n,0,0) +\n\t\t\t src_node_coords(n,0,1)*src_node_coords(n,0,1) +\n\t\t\t src_node_coords(n,0,2)*src_node_coords(n,0,2);\n }\n\n\n \/\/ TARGET MESH READ\n \/\/ ----------------\n\n \/\/ Load the target mesh.\n stk::io::StkMeshIoBroker tgt_broker( parallel_machine );\n std::size_t tgt_input_index = tgt_broker.add_mesh_database(\n \ttarget_mesh_input_file, \"exodus\", stk::io::READ_MESH );\n tgt_broker.set_active_mesh( tgt_input_index );\n tgt_broker.create_input_mesh();\n\n \/\/ Add a nodal field to the target part.\n stk::mesh::Field& target_field = \n \ttgt_broker.meta_data().declare_field >( \n \t stk::topology::NODE_RANK, \"u_tgt\" );\n stk::mesh::Part* tgt_part = \n\ttgt_broker.meta_data().get_part( target_mesh_part_name );\n stk::mesh::put_field( target_field, *tgt_part );\n\n \/\/ Create the target bulk data.\n tgt_broker.populate_bulk_data();\n Teuchos::RCP tgt_bulk_data = \n \tTeuchos::rcpFromRef( tgt_broker.bulk_data() );\n\n \n \/\/ SOLUTION TRANSFER SETUP\n \/\/ -----------------------\n \n \/\/ Solution transfer parameters.\n Teuchos::RCP parameters = Teuchos::parameterList();\n\n \/\/ Create a manager for the source part elements.\n DataTransferKit::STKMeshManager src_manager( \n\tsrc_bulk_data, src_stk_selector, DataTransferKit::ENTITY_TYPE_VOLUME );\n\n \/\/ Create a manager for the target part nodes.\n stk::mesh::Selector tgt_stk_selector( *tgt_part );\n DataTransferKit::STKMeshManager tgt_manager( \n\ttgt_bulk_data, tgt_stk_selector, DataTransferKit::ENTITY_TYPE_NODE );\n\n \/\/ Create a solution vector for the source.\n Teuchos::RCP > src_vector =\n \tDataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField(\n \t *src_bulk_data, source_field, 1 );\t\n \n \/\/ Create a solution vector for the target.\n Teuchos::RCP > tgt_vector =\n \tDataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField(\n \t *tgt_bulk_data, target_field, 1 );\n\n\n \/\/ SOLUTION TRANSFER\n \/\/ -----------------\n\n \/\/ Create a consistent interpolation operator.\n DataTransferKit::ConsistentInterpolationOperator interpolation_operator;\n\n \/\/ Setup the consistent interpolation operator.\n interpolation_operator.setup( src_vector->getMap(),\n\t\t\t\t src_manager.functionSpace(),\n\t\t\t\t tgt_vector->getMap(),\n\t\t\t\t tgt_manager.functionSpace(),\n\t\t\t\t parameters );\n\n \/\/ Apply the consistent interpolation operator.\n interpolation_operator.apply( *src_vector, *tgt_vector );\n\n \/\/ Push the target vector onto the target mesh.\n DataTransferKit::STKMeshDOFVector::pushTpetraMultiVectorToSTKField(\n \t*tgt_vector, *tgt_bulk_data, target_field );\n\n\n \/\/ SOURCE MESH WRITE\n \/\/ -----------------\n\n std::size_t src_output_index = src_broker.create_output_mesh(\n\tsource_mesh_output_file, stk::io::WRITE_RESULTS );\n src_broker.add_field( src_output_index, source_field );\n src_broker.begin_output_step( src_output_index, 0.0 );\n src_broker.write_defined_output_fields( src_output_index );\n src_broker.end_output_step( src_output_index );\n\n\n \/\/ TARGET MESH WRITE\n \/\/ -----------------\n\n std::size_t tgt_output_index = tgt_broker.create_output_mesh(\n \ttarget_mesh_output_file, stk::io::WRITE_RESULTS );\n tgt_broker.add_field( tgt_output_index, target_field );\n tgt_broker.begin_output_step( tgt_output_index, 0.0 );\n tgt_broker.write_defined_output_fields( tgt_output_index );\n tgt_broker.end_output_step( tgt_output_index );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end tstSTK_Mesh.cpp\n\/\/---------------------------------------------------------------------------\/\/\nadding error calculation to interpolation\/\/---------------------------------------------------------------------------\/\/\n\/*\n Copyright (c) 2014, Stuart R. Slattery\n All rights reserved.\n\n Redistribution and use in source and binary forms, with or without\n modification, are permitted provided that the following conditions are\n met:\n\n *: Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n\n *: Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in the\n documentation and\/or other materials provided with the distribution.\n\n *: Neither the name of the Oak Ridge National Laboratory nor the\n names of its contributors may be used to endorse or promote products\n derived from this software without specific prior written permission.\n\n THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\/\/---------------------------------------------------------------------------\/\/\n\/*!\n * \\file consistent_interpolation.cpp\n * \\author Stuart Slattery\n * \\brief STK file-based consistent interpolation example.\n *\/\n\/\/---------------------------------------------------------------------------\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"DTK_STKMeshDOFVector.hpp\"\n#include \"DTK_STKMeshHelpers.hpp\"\n#include \"DTK_STKMeshManager.hpp\"\n#include \"DTK_ConsistentInterpolationOperator.hpp\"\n\n#include \n#include \"Teuchos_CommandLineProcessor.hpp\"\n#include \"Teuchos_XMLParameterListCoreHelpers.hpp\"\n#include \"Teuchos_ParameterList.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Data field function.\n\/\/---------------------------------------------------------------------------\/\/\ndouble dataFunction( double x, double y, double z )\n{\n return std::abs(x) + std::abs(y) + std::abs(z) + 1.0;\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ Example driver.\n\/\/---------------------------------------------------------------------------\/\/\nint main(int argc, char* argv[])\n{\n \/\/ INITIALIZATION\n \/\/ --------------\n\n \/\/ Setup communication.\n Teuchos::GlobalMPISession mpiSession(&argc,&argv);\n\n Teuchos::RCP > comm = \n\tTeuchos::DefaultComm::getComm();\n\n \/\/ Read in command line options.\n std::string xml_input_filename;\n Teuchos::CommandLineProcessor clp(false);\n clp.setOption( \"xml-in-file\",\n\t\t &xml_input_filename,\n\t\t \"The XML file to read into a parameter list\" );\n clp.parse(argc,argv);\n\n \/\/ Build the parameter list from the xml input.\n Teuchos::RCP plist =\n\tTeuchos::rcp( new Teuchos::ParameterList() );\n Teuchos::updateParametersFromXmlFile(\n\txml_input_filename, Teuchos::inoutArg(*plist) );\n\n \/\/ Read command-line options\n std::string source_mesh_input_file = \n\tplist->get(\"Source Mesh Input File\");\n std::string source_mesh_output_file = \n\tplist->get(\"Source Mesh Output File\");\n std::string source_mesh_part_name = \n\tplist->get(\"Source Mesh Part\");\n std::string target_mesh_input_file = \n\tplist->get(\"Target Mesh Input File\");\n std::string target_mesh_output_file = \n\tplist->get(\"Target Mesh Output File\");\n std::string target_mesh_part_name = \n\tplist->get(\"Target Mesh Part\");\n\n \/\/ Get the raw mpi communicator (basic typedef in STK).\n Teuchos::RCP > mpi_comm = \n\tTeuchos::rcp_dynamic_cast >( comm );\n Teuchos::RCP > opaque_comm = \n\tmpi_comm->getRawMpiComm();\n stk::ParallelMachine parallel_machine = (*opaque_comm)();\n\n \n \/\/ SOURCE MESH READ\n \/\/ ----------------\n\n \/\/ Load the source mesh.\n stk::io::StkMeshIoBroker src_broker( parallel_machine );\n std::size_t src_input_index = src_broker.add_mesh_database(\n\tsource_mesh_input_file, \"exodus\", stk::io::READ_MESH );\n src_broker.set_active_mesh( src_input_index );\n src_broker.create_input_mesh();\n\n \/\/ Add a nodal field to the source part.\n stk::mesh::Field& source_field = \n\tsrc_broker.meta_data().declare_field >( \n\t stk::topology::NODE_RANK, \"u_src\" );\n stk::mesh::Part* src_part = \n\tsrc_broker.meta_data().get_part( source_mesh_part_name );\n stk::mesh::put_field( source_field, *src_part );\n\n \/\/ Create the source bulk data.\n src_broker.populate_bulk_data();\n Teuchos::RCP src_bulk_data = \n\tTeuchos::rcpFromRef( src_broker.bulk_data() );\n\n \/\/ Put some data in the source field. We will use the distance of the node\n \/\/ from the origin as the data.\n stk::mesh::Selector src_stk_selector( *src_part );\n stk::mesh::BucketVector src_part_buckets = \n\tsrc_stk_selector.get_buckets( stk::topology::NODE_RANK );\n std::vector src_part_nodes;\n stk::mesh::get_selected_entities( \n\tsrc_stk_selector, src_part_buckets, src_part_nodes );\n Intrepid::FieldContainer src_node_coords =\n\tDataTransferKit::STKMeshHelpers::getEntityNodeCoordinates(\n\t Teuchos::Array(src_part_nodes), *src_bulk_data );\n double* src_field_data;\n int num_src_part_nodes = src_part_nodes.size();\n for ( int n = 0; n < num_src_part_nodes; ++n )\n {\n\tsrc_field_data = stk::mesh::field_data( source_field, src_part_nodes[n] );\n\tsrc_field_data[0] = dataFunction( src_node_coords(n,0,0),\n\t\t\t\t\t src_node_coords(n,0,1),\n\t\t\t\t\t src_node_coords(n,0,2) );\n }\n\n\n \/\/ TARGET MESH READ\n \/\/ ----------------\n\n \/\/ Load the target mesh.\n stk::io::StkMeshIoBroker tgt_broker( parallel_machine );\n std::size_t tgt_input_index = tgt_broker.add_mesh_database(\n \ttarget_mesh_input_file, \"exodus\", stk::io::READ_MESH );\n tgt_broker.set_active_mesh( tgt_input_index );\n tgt_broker.create_input_mesh();\n\n \/\/ Add a nodal field to the target part.\n stk::mesh::Field& target_field = \n \ttgt_broker.meta_data().declare_field >( \n \t stk::topology::NODE_RANK, \"u_tgt\" );\n stk::mesh::Part* tgt_part = \n\ttgt_broker.meta_data().get_part( target_mesh_part_name );\n stk::mesh::put_field( target_field, *tgt_part );\n\n \/\/ Add an error nodal field to the target part.\n stk::mesh::Field& target_error_field = \n \ttgt_broker.meta_data().declare_field >( \n \t stk::topology::NODE_RANK, \"u_err\" );\n stk::mesh::put_field( target_error_field, *tgt_part );\n\n \/\/ Create the target bulk data.\n tgt_broker.populate_bulk_data();\n Teuchos::RCP tgt_bulk_data = \n \tTeuchos::rcpFromRef( tgt_broker.bulk_data() );\n\n \n \/\/ SOLUTION TRANSFER SETUP\n \/\/ -----------------------\n \n \/\/ Solution transfer parameters.\n Teuchos::RCP parameters = Teuchos::parameterList();\n\n \/\/ Create a manager for the source part elements.\n DataTransferKit::STKMeshManager src_manager( \n\tsrc_bulk_data, src_stk_selector, DataTransferKit::ENTITY_TYPE_VOLUME );\n\n \/\/ Create a manager for the target part nodes.\n stk::mesh::Selector tgt_stk_selector( *tgt_part );\n DataTransferKit::STKMeshManager tgt_manager( \n\ttgt_bulk_data, tgt_stk_selector, DataTransferKit::ENTITY_TYPE_NODE );\n\n \/\/ Create a solution vector for the source.\n Teuchos::RCP > src_vector =\n \tDataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField(\n \t *src_bulk_data, source_field, 1 );\t\n \n \/\/ Create a solution vector for the target.\n Teuchos::RCP > tgt_vector =\n \tDataTransferKit::STKMeshDOFVector::pullTpetraMultiVectorFromSTKField(\n \t *tgt_bulk_data, target_field, 1 );\n\n\n \/\/ SOLUTION TRANSFER\n \/\/ -----------------\n\n \/\/ Create a consistent interpolation operator.\n DataTransferKit::ConsistentInterpolationOperator interpolation_operator;\n\n \/\/ Setup the consistent interpolation operator.\n interpolation_operator.setup( src_vector->getMap(),\n\t\t\t\t src_manager.functionSpace(),\n\t\t\t\t tgt_vector->getMap(),\n\t\t\t\t tgt_manager.functionSpace(),\n\t\t\t\t parameters );\n\n \/\/ Apply the consistent interpolation operator.\n interpolation_operator.apply( *src_vector, *tgt_vector );\n\n \/\/ Push the target vector onto the target mesh.\n DataTransferKit::STKMeshDOFVector::pushTpetraMultiVectorToSTKField(\n \t*tgt_vector, *tgt_bulk_data, target_field );\n\n\n \/\/ COMPUTE THE SOLUTION ERROR\n \/\/ --------------------------\n\n stk::mesh::BucketVector tgt_part_buckets = \n\ttgt_stk_selector.get_buckets( stk::topology::NODE_RANK );\n std::vector tgt_part_nodes;\n stk::mesh::get_selected_entities( \n\ttgt_stk_selector, tgt_part_buckets, tgt_part_nodes );\n Intrepid::FieldContainer tgt_node_coords =\n\tDataTransferKit::STKMeshHelpers::getEntityNodeCoordinates(\n\t Teuchos::Array(tgt_part_nodes), *tgt_bulk_data );\n double* tgt_field_data;\n double* err_field_data;\n int num_tgt_part_nodes = tgt_part_nodes.size();\n double error_l2_norm = 0.0;\n double field_l2_norm = 0.0;\n for ( int n = 0; n < num_tgt_part_nodes; ++n )\n {\n\tdouble gold_value = dataFunction( tgt_node_coords(n,0,0),\n\t\t\t\t\t tgt_node_coords(n,0,1),\n\t\t\t\t\t tgt_node_coords(n,0,2) );\n\ttgt_field_data = stk::mesh::field_data( target_field, tgt_part_nodes[n] );\n\terr_field_data = stk::mesh::field_data( target_error_field, tgt_part_nodes[n] );\n\terr_field_data[0] = tgt_field_data[0] - gold_value;\n\terror_l2_norm += err_field_data[0] * err_field_data[0];\n\tfield_l2_norm += tgt_field_data[0] * tgt_field_data[0];\n\terr_field_data[0] \/= gold_value;\n }\n error_l2_norm = std::sqrt( error_l2_norm );\n field_l2_norm = std::sqrt( field_l2_norm );\n std::cout << \"|e|_2 \/ |f|_2: \" << error_l2_norm \/ field_l2_norm << std::endl;\n\n\n \/\/ SOURCE MESH WRITE\n \/\/ -----------------\n\n std::size_t src_output_index = src_broker.create_output_mesh(\n\tsource_mesh_output_file, stk::io::WRITE_RESULTS );\n src_broker.add_field( src_output_index, source_field );\n src_broker.begin_output_step( src_output_index, 0.0 );\n src_broker.write_defined_output_fields( src_output_index );\n src_broker.end_output_step( src_output_index );\n\n\n \/\/ TARGET MESH WRITE\n \/\/ -----------------\n\n std::size_t tgt_output_index = tgt_broker.create_output_mesh(\n \ttarget_mesh_output_file, stk::io::WRITE_RESULTS );\n tgt_broker.add_field( tgt_output_index, target_field );\n tgt_broker.add_field( tgt_output_index, target_error_field );\n tgt_broker.begin_output_step( tgt_output_index, 0.0 );\n tgt_broker.write_defined_output_fields( tgt_output_index );\n tgt_broker.end_output_step( tgt_output_index );\n}\n\n\/\/---------------------------------------------------------------------------\/\/\n\/\/ end tstSTK_Mesh.cpp\n\/\/---------------------------------------------------------------------------\/\/\n<|endoftext|>"} {"text":"#include \"thruster_tortuga.h\"\n\nThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){\n ros::Rate loop_rate(rate);\n subscriber = n.subscribe(\"\/qubo\/thruster_input\", 1000, &ThrusterTortugaNode::thrusterCallBack, this);\n \n\n ROS_DEBUG(\"Opening sensorboard\");\n sensor_file = \"\/dev\/sensor\";\n fd = openSensorBoard(sensor_file.c_str());\n ROS_DEBUG(\"Opened sensorboard with fd %d.\", fd);\n checkError(syncBoard(fd));\n ROS_DEBUG(\"Synced with the Board\");\n\n \/\/GH: This is not the correct use of checkError.\n \/\/It should be called on the return value of a function call, not on the file descriptor.\n \/\/checkError(fd);\n\n \/\/ Unsafe all the thrusters\n ROS_DEBUG(\"Unsafing all thrusters\");\n for (int i = 6; i <= 11; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n\n ROS_DEBUG(\"Unsafed all thrusters\");\n \n for(int i = 0; i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = 0;\n }\n\n}\n\nThrusterTortugaNode::~ThrusterTortugaNode(){\n \/\/Stop all the thrusters\n ROS_DEBUG(\"Stopping thrusters\");\n readSpeedResponses(fd);\n setSpeeds(fd, 0, 0, 0, 0, 0, 0);\n ROS_DEBUG(\"Safing thrusters\");\n \/\/ Safe all the thrusters\n for (int i = 0; i <= 5; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n ROS_DEBUG(\"Safed thrusters\");\n \/\/Close the sensorboard\n close(fd);\n}\n\nvoid ThrusterTortugaNode::update(){\n \/\/I think we need to initialize thrusters and stuff before this will work \n ros::spinOnce();\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n \/\/ ROS_DEBUG(\"fd = %x\",fd); \n \n ROS_DEBUG(\"Setting thruster speeds\");\n int retR = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed before: %x\", retR);\n int retS = setSpeeds(fd, 128, 128, 128, 128, 128, 128);\n ROS_DEBUG(\"Set speed status: %x\", retS);\n usleep(20*1000);\n int retA = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed after: %x\", retA);\n \n ROS_DEBUG(\"thruster state = %x\", readThrusterState(fd)); \n ROS_DEBUG(\"set speed returns %x\", retS);\n ROS_DEBUG(\"read speed returns %x\", retR);\n}\n\nvoid ThrusterTortugaNode::publish(){\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n}\n\nvoid ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){\n \/\/SG: TODO change this shit\n for(int i = 0 ;i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = new_powers.data[i];\n }\n}\n\n\/\/ssh robot@192.168.10.12\nwe now actually use the values we subscribe to.. also added some more debug output#include \"thruster_tortuga.h\"\n\nThrusterTortugaNode::ThrusterTortugaNode(int argc, char **argv, int rate): TortugaNode(){\n ros::Rate loop_rate(rate);\n subscriber = n.subscribe(\"\/qubo\/thruster_input\", 1000, &ThrusterTortugaNode::thrusterCallBack, this);\n \n\n ROS_DEBUG(\"Opening sensorboard\");\n sensor_file = \"\/dev\/sensor\";\n fd = openSensorBoard(sensor_file.c_str());\n ROS_DEBUG(\"Opened sensorboard with fd %d.\", fd);\n checkError(syncBoard(fd));\n ROS_DEBUG(\"Synced with the Board\");\n\n \/\/GH: This is not the correct use of checkError.\n \/\/It should be called on the return value of a function call, not on the file descriptor.\n \/\/checkError(fd);\n\n \/\/ Unsafe all the thrusters\n ROS_DEBUG(\"Unsafing all thrusters\");\n for (int i = 6; i <= 11; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n\n ROS_DEBUG(\"Unsafed all thrusters\");\n \n for(int i = 0; i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = 0;\n }\n\n}\n\nThrusterTortugaNode::~ThrusterTortugaNode(){\n \/\/Stop all the thrusters\n ROS_DEBUG(\"Stopping thrusters\");\n readSpeedResponses(fd);\n setSpeeds(fd, 0, 0, 0, 0, 0, 0);\n ROS_DEBUG(\"Safing thrusters\");\n \/\/ Safe all the thrusters\n for (int i = 0; i <= 5; i++) {\n checkError(setThrusterSafety(fd, i));\n }\n ROS_DEBUG(\"Safed thrusters\");\n \/\/Close the sensorboard\n close(fd);\n}\n\nvoid ThrusterTortugaNode::update(){\n \/\/I think we need to initialize thrusters and stuff before this will work \n ros::spinOnce();\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n \/\/ ROS_DEBUG(\"fd = %x\",fd); \n \n ROS_DEBUG(\"Setting thruster speeds\");\n int retR = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed before: %x\", retR);\n for(int i = 0 ;i < NUM_THRUSTERS; i++){\n ROS_DEBUG(\"thruster value %i = %i\\n\" i, thruster_powers.data[i])\n }\n int retS = setSpeeds(fd, thruster_powers.data[0], , thruster_powers.data[1], thruster_powers.data[2], thruster_powers[3], thruster_powers[4]);\n ROS_DEBUG(\"Set speed status: %x\", retS);\n usleep(20*1000);\n int retA = readSpeedResponses(fd);\n ROS_DEBUG(\"Read speed after: %x\", retA);\n \n ROS_DEBUG(\"thruster state = %x\", readThrusterState(fd)); \n ROS_DEBUG(\"set speed returns %x\", retS);\n ROS_DEBUG(\"read speed returns %x\", retR);\n \n}\n\nvoid ThrusterTortugaNode::publish(){\n \/\/ setSpeeds(fd, msg.data[0], msg.data[1], msg.data[2], msg.data[3], msg.data[4], msg.data[5]);\n}\n\nvoid ThrusterTortugaNode::thrusterCallBack(const std_msgs::Int64MultiArray new_powers){\n for(int i = 0 ;i < NUM_THRUSTERS; i++){\n thruster_powers.data[i] = new_powers.data[i];\n }\n}\n\n\/\/ssh robot@192.168.10.12\n<|endoftext|>"} {"text":"#include \"ClientSocket.hh\"\n#include \"Server.hh\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nServer server;\n\nvoid handleExitSignal( int \/* signal *\/ )\n{\n server.close();\n}\n\nvoid unescapeQuote( std::string& quote )\n{\n std::size_t position = 0;\n std::string target = \"\\\\n\";\n std::string replacement = \"\\n\";\n while( ( position = quote.find( target, position ) ) != std::string::npos )\n {\n quote.replace( position, target.length(), replacement );\n position += replacement.length();\n }\n}\n\nstd::vector readQuotes( const std::string& filename )\n{\n std::ifstream in( filename );\n if( !in )\n return {};\n\n std::vector quotes;\n std::string line;\n\n while( std::getline( in, line ) )\n {\n unescapeQuote( line );\n quotes.push_back( line );\n }\n\n return quotes;\n}\n\nint main( int argc, char** argv )\n{\n std::vector quotes;\n\n if( argc > 1 )\n quotes = readQuotes( argv[1] );\n else\n quotes = { \"Sorry, no quote today, mate.\\n\" };\n\n std::random_device rd;\n std::mt19937 rng( rd() );\n std::uniform_int_distribution distribution( 0, quotes.size() - 1 );\n\n signal( SIGINT, handleExitSignal );\n\n server.setPort( 2048 );\n\n server.onAccept( [&] ( std::unique_ptr socket )\n {\n socket->write( quotes.at( distribution( rng ) ) );\n socket->close();\n } );\n\n server.listen();\n\n return 0;\n}\nChanged QOTD port#include \"ClientSocket.hh\"\n#include \"Server.hh\"\n\n#include \n\n#include \n#include \n#include \n#include \n\nServer server;\n\nvoid handleExitSignal( int \/* signal *\/ )\n{\n server.close();\n}\n\nvoid unescapeQuote( std::string& quote )\n{\n std::size_t position = 0;\n std::string target = \"\\\\n\";\n std::string replacement = \"\\n\";\n while( ( position = quote.find( target, position ) ) != std::string::npos )\n {\n quote.replace( position, target.length(), replacement );\n position += replacement.length();\n }\n}\n\nstd::vector readQuotes( const std::string& filename )\n{\n std::ifstream in( filename );\n if( !in )\n return {};\n\n std::vector quotes;\n std::string line;\n\n while( std::getline( in, line ) )\n {\n unescapeQuote( line );\n quotes.push_back( line );\n }\n\n return quotes;\n}\n\nint main( int argc, char** argv )\n{\n std::vector quotes;\n\n if( argc > 1 )\n quotes = readQuotes( argv[1] );\n else\n quotes = { \"Sorry, no quote today, mate.\\n\" };\n\n std::random_device rd;\n std::mt19937 rng( rd() );\n std::uniform_int_distribution distribution( 0, quotes.size() - 1 );\n\n signal( SIGINT, handleExitSignal );\n\n server.setPort( 1041 );\n\n server.onAccept( [&] ( std::unique_ptr socket )\n {\n socket->write( quotes.at( distribution( rng ) ) );\n socket->close();\n } );\n\n server.listen();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2010 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n\n\/** @file\n * Implementiation of a PL390 GIC\n *\/\n\n#ifndef __DEV_ARM_GIC_PL390_H__\n#define __DEV_ARM_GIC_PL390_H__\n\n#include \"base\/bitunion.hh\"\n#include \"cpu\/intr_control.hh\"\n#include \"dev\/arm\/base_gic.hh\"\n#include \"dev\/io_device.hh\"\n#include \"dev\/platform.hh\"\n#include \"params\/Pl390.hh\"\n\n\/** @todo this code only assumes one processor for now. Low word\n * of intEnabled and pendingInt need to be replicated per CPU.\n * bottom 31 interrupts (7 words) need to be replicated for\n * for interrupt priority register, processor target registers\n * interrupt config registers *\/\n\nclass Pl390 : public BaseGic\n{\n protected:\n \/\/ distributor memory addresses\n static const int ICDDCR = 0x000; \/\/ control register\n static const int ICDICTR = 0x004; \/\/ controller type\n static const int ICDIIDR = 0x008; \/\/ implementer id\n static const int ICDISER_ST = 0x100; \/\/ interrupt set enable\n static const int ICDISER_ED = 0x17c;\n static const int ICDICER_ST = 0x180; \/\/ interrupt clear enable\n static const int ICDICER_ED = 0x1fc;\n static const int ICDISPR_ST = 0x200; \/\/ set pending interrupt\n static const int ICDISPR_ED = 0x27c;\n static const int ICDICPR_ST = 0x280; \/\/ clear pending interrupt\n static const int ICDICPR_ED = 0x2fc;\n static const int ICDABR_ST = 0x300; \/\/ active bit registers\n static const int ICDABR_ED = 0x37c;\n static const int ICDIPR_ST = 0x400; \/\/ interrupt priority registers\n static const int ICDIPR_ED = 0x7f8;\n static const int ICDIPTR_ST = 0x800; \/\/ processor target registers\n static const int ICDIPTR_ED = 0xbf8;\n static const int ICDICFR_ST = 0xc00; \/\/ interrupt config registers\n static const int ICDICFR_ED = 0xcfc;\n static const int ICDSGIR = 0xf00; \/\/ software generated interrupt\n static const int DIST_SIZE = 0xfff;\n\n \/\/ cpu memory addressesa\n static const int ICCICR = 0x00; \/\/ CPU control register\n static const int ICCPMR = 0x04; \/\/ Interrupt priority mask\n static const int ICCBPR = 0x08; \/\/ binary point register\n static const int ICCIAR = 0x0C; \/\/ interrupt ack register\n static const int ICCEOIR = 0x10; \/\/ end of interrupt\n static const int ICCRPR = 0x14; \/\/ runing priority\n static const int ICCHPIR = 0x18; \/\/ highest pending interrupt\n static const int ICCABPR = 0x1c; \/\/ aliased binary point\n static const int ICCIIDR = 0xfc; \/\/ cpu interface id register\n static const int CPU_SIZE = 0xff;\n\n static const int SGI_MAX = 16; \/\/ Number of Software Gen Interrupts\n static const int PPI_MAX = 16; \/\/ Number of Private Peripheral Interrupts\n\n \/** Mask off SGI's when setting\/clearing pending bits *\/\n static const int SGI_MASK = 0xFFFF0000;\n\n \/** Mask for bits that config N:N mode in ICDICFR's *\/\n static const int NN_CONFIG_MASK = 0x55555555;\n\n static const int CPU_MAX = 8; \/\/ Max number of supported CPU interfaces\n static const int SPURIOUS_INT = 1023;\n static const int INT_BITS_MAX = 32;\n static const int INT_LINES_MAX = 1020;\n\n BitUnion32(SWI)\n Bitfield<3,0> sgi_id;\n Bitfield<23,16> cpu_list;\n Bitfield<25,24> list_type;\n EndBitUnion(SWI)\n\n BitUnion32(IAR)\n Bitfield<9,0> ack_id;\n Bitfield<12,10> cpu_id;\n EndBitUnion(IAR)\n\n \/** Distributor address GIC listens at *\/\n Addr distAddr;\n\n \/** CPU address GIC listens at *\/\n \/** @todo is this one per cpu? *\/\n Addr cpuAddr;\n\n \/** Latency for a distributor operation *\/\n Tick distPioDelay;\n\n \/** Latency for a cpu operation *\/\n Tick cpuPioDelay;\n\n \/** Latency for a interrupt to get to CPU *\/\n Tick intLatency;\n\n \/** Gic enabled *\/\n bool enabled;\n\n \/** Number of itLines enabled *\/\n uint32_t itLines;\n\n uint32_t itLinesLog2;\n\n \/** interrupt enable bits for all possible 1020 interupts.\n * one bit per interrupt, 32 bit per word = 32 words *\/\n uint32_t intEnabled[INT_BITS_MAX];\n\n \/** interrupt pending bits for all possible 1020 interupts.\n * one bit per interrupt, 32 bit per word = 32 words *\/\n uint32_t pendingInt[INT_BITS_MAX];\n\n \/** interrupt active bits for all possible 1020 interupts.\n * one bit per interrupt, 32 bit per word = 32 words *\/\n uint32_t activeInt[INT_BITS_MAX];\n\n \/** read only running priroity register, 1 per cpu*\/\n uint32_t iccrpr[CPU_MAX];\n\n \/** an 8 bit priority (lower is higher priority) for each\n * of the 1020 possible supported interrupts.\n *\/\n uint8_t intPriority[INT_LINES_MAX];\n\n \/** an 8 bit cpu target id for each shared peripheral interrupt\n * of the 1020 possible supported interrupts.\n *\/\n uint8_t cpuTarget[INT_LINES_MAX];\n\n \/** 2 bit per interrupt signaling if it's level or edge sensitive\n * and if it is 1:N or N:N *\/\n uint32_t intConfig[INT_BITS_MAX*2];\n\n \/** CPU enabled *\/\n bool cpuEnabled[CPU_MAX];\n\n \/** CPU priority *\/\n uint8_t cpuPriority[CPU_MAX];\n\n \/** Binary point registers *\/\n uint8_t cpuBpr[CPU_MAX];\n\n \/** highest interrupt that is interrupting CPU *\/\n uint32_t cpuHighestInt[CPU_MAX];\n\n \/** One bit per cpu per software interrupt that is pending for each possible\n * sgi source. Indexed by SGI number. Each byte in generating cpu id and\n * bits in position is destination id. e.g. 0x4 = CPU 0 generated interrupt\n * for CPU 2. *\/\n uint64_t cpuSgiPending[SGI_MAX];\n uint64_t cpuSgiActive[SGI_MAX];\n\n \/** One bit per private peripheral interrupt. Only upper 16 bits\n * will be used since PPI interrupts are numberred from 16 to 32 *\/\n uint32_t cpuPpiPending[CPU_MAX];\n uint32_t cpuPpiActive[CPU_MAX];\n\n \/** Banked interrupt prioirty registers for SGIs and PPIs *\/\n uint8_t bankedIntPriority[CPU_MAX][SGI_MAX + PPI_MAX];\n\n \/** IRQ Enable Used for debug *\/\n bool irqEnable;\n\n \/** software generated interrupt\n * @param data data to decode that indicates which cpus to interrupt\n *\/\n void softInt(int ctx_id, SWI swi);\n\n \/** See if some processor interrupt flags need to be enabled\/disabled\n * @param hint which set of interrupts needs to be checked\n *\/\n void updateIntState(int hint);\n\n \/** Update the register that records priority of the highest priority\n * active interrupt*\/\n void updateRunPri();\n\n \/** generate a bit mask to check cpuSgi for an interrupt. *\/\n uint64_t genSwiMask(int cpu);\n\n int intNumToWord(int num) const { return num >> 5; }\n int intNumToBit(int num) const { return num % 32; }\n\n \/** Post an interrupt to a CPU\n *\/\n void postInt(uint32_t cpu, Tick when);\n\n \/** Event definition to post interrupt to CPU after a delay\n *\/\n class PostIntEvent : public Event\n {\n private:\n uint32_t cpu;\n Platform *platform;\n public:\n PostIntEvent( uint32_t c, Platform* p)\n : cpu(c), platform(p)\n { }\n void process() { platform->intrctrl->post(cpu, ArmISA::INT_IRQ, 0);}\n const char *description() const { return \"Post Interrupt to CPU\"; }\n };\n PostIntEvent *postIntEvent[CPU_MAX];\n\n public:\n typedef Pl390Params Params;\n const Params *\n params() const\n {\n return dynamic_cast(_params);\n }\n Pl390(const Params *p);\n\n \/** Return the address ranges used by the Gic\n * This is the distributor address + all cpu addresses\n *\/\n virtual AddrRangeList getAddrRanges() const;\n\n \/** A PIO read to the device, immediately split up into\n * readDistributor() or readCpu()\n *\/\n virtual Tick read(PacketPtr pkt);\n\n \/** A PIO read to the device, immediately split up into\n * writeDistributor() or writeCpu()\n *\/\n virtual Tick write(PacketPtr pkt);\n\n \/** Handle a read to the distributor poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick readDistributor(PacketPtr pkt);\n\n \/** Handle a read to the cpu poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick readCpu(PacketPtr pkt);\n\n \/** Handle a write to the distributor poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick writeDistributor(PacketPtr pkt);\n\n \/** Handle a write to the cpu poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick writeCpu(PacketPtr pkt);\n\n \/** Post an interrupt from a device that is connected to the Gic.\n * Depending on the configuration, the gic will pass this interrupt\n * on through to a CPU.\n * @param number number of interrupt to send *\/\n void sendInt(uint32_t number);\n\n \/** Interface call for private peripheral interrupts *\/\n void sendPPInt(uint32_t num, uint32_t cpu);\n\n \/** Clear an interrupt from a device that is connected to the Gic\n * Depending on the configuration, the gic may de-assert it's cpu line\n * @param number number of interrupt to send *\/\n void clearInt(uint32_t number);\n\n \/* Various functions fer testing and debugging *\/\n void driveSPI(uint32_t spi);\n void driveLegIRQ(bool state);\n void driveLegFIQ(bool state);\n void driveIrqEn(bool state);\n\n virtual void serialize(std::ostream &os);\n virtual void unserialize(Checkpoint *cp, const std::string §ion);\n\n};\n\n#endif \/\/__DEV_ARM_GIC_H__\narm: Don't export private GIC methods\/*\n * Copyright (c) 2010 ARM Limited\n * All rights reserved\n *\n * The license below extends only to copyright in the software and shall\n * not be construed as granting a license to any other intellectual\n * property including but not limited to intellectual property relating\n * to a hardware implementation of the functionality of the software\n * licensed hereunder. You may use the software subject to the license\n * terms below provided that you ensure that this notice is replicated\n * unmodified and in its entirety in all distributions of the software,\n * modified or unmodified, in source code or in binary form.\n *\n * Copyright (c) 2005 The Regents of The University of Michigan\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met: redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer;\n * redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the distribution;\n * neither the name of the copyright holders nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Ali Saidi\n *\/\n\n\n\/** @file\n * Implementiation of a PL390 GIC\n *\/\n\n#ifndef __DEV_ARM_GIC_PL390_H__\n#define __DEV_ARM_GIC_PL390_H__\n\n#include \"base\/bitunion.hh\"\n#include \"cpu\/intr_control.hh\"\n#include \"dev\/arm\/base_gic.hh\"\n#include \"dev\/io_device.hh\"\n#include \"dev\/platform.hh\"\n#include \"params\/Pl390.hh\"\n\n\/** @todo this code only assumes one processor for now. Low word\n * of intEnabled and pendingInt need to be replicated per CPU.\n * bottom 31 interrupts (7 words) need to be replicated for\n * for interrupt priority register, processor target registers\n * interrupt config registers *\/\n\nclass Pl390 : public BaseGic\n{\n protected:\n \/\/ distributor memory addresses\n static const int ICDDCR = 0x000; \/\/ control register\n static const int ICDICTR = 0x004; \/\/ controller type\n static const int ICDIIDR = 0x008; \/\/ implementer id\n static const int ICDISER_ST = 0x100; \/\/ interrupt set enable\n static const int ICDISER_ED = 0x17c;\n static const int ICDICER_ST = 0x180; \/\/ interrupt clear enable\n static const int ICDICER_ED = 0x1fc;\n static const int ICDISPR_ST = 0x200; \/\/ set pending interrupt\n static const int ICDISPR_ED = 0x27c;\n static const int ICDICPR_ST = 0x280; \/\/ clear pending interrupt\n static const int ICDICPR_ED = 0x2fc;\n static const int ICDABR_ST = 0x300; \/\/ active bit registers\n static const int ICDABR_ED = 0x37c;\n static const int ICDIPR_ST = 0x400; \/\/ interrupt priority registers\n static const int ICDIPR_ED = 0x7f8;\n static const int ICDIPTR_ST = 0x800; \/\/ processor target registers\n static const int ICDIPTR_ED = 0xbf8;\n static const int ICDICFR_ST = 0xc00; \/\/ interrupt config registers\n static const int ICDICFR_ED = 0xcfc;\n static const int ICDSGIR = 0xf00; \/\/ software generated interrupt\n static const int DIST_SIZE = 0xfff;\n\n \/\/ cpu memory addressesa\n static const int ICCICR = 0x00; \/\/ CPU control register\n static const int ICCPMR = 0x04; \/\/ Interrupt priority mask\n static const int ICCBPR = 0x08; \/\/ binary point register\n static const int ICCIAR = 0x0C; \/\/ interrupt ack register\n static const int ICCEOIR = 0x10; \/\/ end of interrupt\n static const int ICCRPR = 0x14; \/\/ runing priority\n static const int ICCHPIR = 0x18; \/\/ highest pending interrupt\n static const int ICCABPR = 0x1c; \/\/ aliased binary point\n static const int ICCIIDR = 0xfc; \/\/ cpu interface id register\n static const int CPU_SIZE = 0xff;\n\n static const int SGI_MAX = 16; \/\/ Number of Software Gen Interrupts\n static const int PPI_MAX = 16; \/\/ Number of Private Peripheral Interrupts\n\n \/** Mask off SGI's when setting\/clearing pending bits *\/\n static const int SGI_MASK = 0xFFFF0000;\n\n \/** Mask for bits that config N:N mode in ICDICFR's *\/\n static const int NN_CONFIG_MASK = 0x55555555;\n\n static const int CPU_MAX = 8; \/\/ Max number of supported CPU interfaces\n static const int SPURIOUS_INT = 1023;\n static const int INT_BITS_MAX = 32;\n static const int INT_LINES_MAX = 1020;\n\n BitUnion32(SWI)\n Bitfield<3,0> sgi_id;\n Bitfield<23,16> cpu_list;\n Bitfield<25,24> list_type;\n EndBitUnion(SWI)\n\n BitUnion32(IAR)\n Bitfield<9,0> ack_id;\n Bitfield<12,10> cpu_id;\n EndBitUnion(IAR)\n\n \/** Distributor address GIC listens at *\/\n Addr distAddr;\n\n \/** CPU address GIC listens at *\/\n \/** @todo is this one per cpu? *\/\n Addr cpuAddr;\n\n \/** Latency for a distributor operation *\/\n Tick distPioDelay;\n\n \/** Latency for a cpu operation *\/\n Tick cpuPioDelay;\n\n \/** Latency for a interrupt to get to CPU *\/\n Tick intLatency;\n\n \/** Gic enabled *\/\n bool enabled;\n\n \/** Number of itLines enabled *\/\n uint32_t itLines;\n\n uint32_t itLinesLog2;\n\n \/** interrupt enable bits for all possible 1020 interupts.\n * one bit per interrupt, 32 bit per word = 32 words *\/\n uint32_t intEnabled[INT_BITS_MAX];\n\n \/** interrupt pending bits for all possible 1020 interupts.\n * one bit per interrupt, 32 bit per word = 32 words *\/\n uint32_t pendingInt[INT_BITS_MAX];\n\n \/** interrupt active bits for all possible 1020 interupts.\n * one bit per interrupt, 32 bit per word = 32 words *\/\n uint32_t activeInt[INT_BITS_MAX];\n\n \/** read only running priroity register, 1 per cpu*\/\n uint32_t iccrpr[CPU_MAX];\n\n \/** an 8 bit priority (lower is higher priority) for each\n * of the 1020 possible supported interrupts.\n *\/\n uint8_t intPriority[INT_LINES_MAX];\n\n \/** an 8 bit cpu target id for each shared peripheral interrupt\n * of the 1020 possible supported interrupts.\n *\/\n uint8_t cpuTarget[INT_LINES_MAX];\n\n \/** 2 bit per interrupt signaling if it's level or edge sensitive\n * and if it is 1:N or N:N *\/\n uint32_t intConfig[INT_BITS_MAX*2];\n\n \/** CPU enabled *\/\n bool cpuEnabled[CPU_MAX];\n\n \/** CPU priority *\/\n uint8_t cpuPriority[CPU_MAX];\n\n \/** Binary point registers *\/\n uint8_t cpuBpr[CPU_MAX];\n\n \/** highest interrupt that is interrupting CPU *\/\n uint32_t cpuHighestInt[CPU_MAX];\n\n \/** One bit per cpu per software interrupt that is pending for each possible\n * sgi source. Indexed by SGI number. Each byte in generating cpu id and\n * bits in position is destination id. e.g. 0x4 = CPU 0 generated interrupt\n * for CPU 2. *\/\n uint64_t cpuSgiPending[SGI_MAX];\n uint64_t cpuSgiActive[SGI_MAX];\n\n \/** One bit per private peripheral interrupt. Only upper 16 bits\n * will be used since PPI interrupts are numberred from 16 to 32 *\/\n uint32_t cpuPpiPending[CPU_MAX];\n uint32_t cpuPpiActive[CPU_MAX];\n\n \/** Banked interrupt prioirty registers for SGIs and PPIs *\/\n uint8_t bankedIntPriority[CPU_MAX][SGI_MAX + PPI_MAX];\n\n \/** IRQ Enable Used for debug *\/\n bool irqEnable;\n\n \/** software generated interrupt\n * @param data data to decode that indicates which cpus to interrupt\n *\/\n void softInt(int ctx_id, SWI swi);\n\n \/** See if some processor interrupt flags need to be enabled\/disabled\n * @param hint which set of interrupts needs to be checked\n *\/\n void updateIntState(int hint);\n\n \/** Update the register that records priority of the highest priority\n * active interrupt*\/\n void updateRunPri();\n\n \/** generate a bit mask to check cpuSgi for an interrupt. *\/\n uint64_t genSwiMask(int cpu);\n\n int intNumToWord(int num) const { return num >> 5; }\n int intNumToBit(int num) const { return num % 32; }\n\n \/** Post an interrupt to a CPU\n *\/\n void postInt(uint32_t cpu, Tick when);\n\n \/** Event definition to post interrupt to CPU after a delay\n *\/\n class PostIntEvent : public Event\n {\n private:\n uint32_t cpu;\n Platform *platform;\n public:\n PostIntEvent( uint32_t c, Platform* p)\n : cpu(c), platform(p)\n { }\n void process() { platform->intrctrl->post(cpu, ArmISA::INT_IRQ, 0);}\n const char *description() const { return \"Post Interrupt to CPU\"; }\n };\n PostIntEvent *postIntEvent[CPU_MAX];\n\n public:\n typedef Pl390Params Params;\n const Params *\n params() const\n {\n return dynamic_cast(_params);\n }\n Pl390(const Params *p);\n\n \/** @{ *\/\n \/** Return the address ranges used by the Gic\n * This is the distributor address + all cpu addresses\n *\/\n virtual AddrRangeList getAddrRanges() const;\n\n \/** A PIO read to the device, immediately split up into\n * readDistributor() or readCpu()\n *\/\n virtual Tick read(PacketPtr pkt);\n\n \/** A PIO read to the device, immediately split up into\n * writeDistributor() or writeCpu()\n *\/\n virtual Tick write(PacketPtr pkt);\n \/** @} *\/\n\n \/** @{ *\/\n \/** Post an interrupt from a device that is connected to the Gic.\n * Depending on the configuration, the gic will pass this interrupt\n * on through to a CPU.\n * @param number number of interrupt to send *\/\n void sendInt(uint32_t number);\n\n \/** Interface call for private peripheral interrupts *\/\n void sendPPInt(uint32_t num, uint32_t cpu);\n\n \/** Clear an interrupt from a device that is connected to the Gic\n * Depending on the configuration, the gic may de-assert it's cpu line\n * @param number number of interrupt to send *\/\n void clearInt(uint32_t number);\n \/** @} *\/\n\n \/** @{ *\/\n \/* Various functions fer testing and debugging *\/\n void driveSPI(uint32_t spi);\n void driveLegIRQ(bool state);\n void driveLegFIQ(bool state);\n void driveIrqEn(bool state);\n \/** @} *\/\n\n virtual void serialize(std::ostream &os);\n virtual void unserialize(Checkpoint *cp, const std::string §ion);\n\n protected:\n \/** Handle a read to the distributor poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick readDistributor(PacketPtr pkt);\n\n \/** Handle a read to the cpu poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick readCpu(PacketPtr pkt);\n\n \/** Handle a write to the distributor poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick writeDistributor(PacketPtr pkt);\n\n \/** Handle a write to the cpu poriton of the GIC\n * @param pkt packet to respond to\n *\/\n Tick writeCpu(PacketPtr pkt);\n};\n\n#endif \/\/__DEV_ARM_GIC_H__\n<|endoftext|>"} {"text":"\/\/ LaminaFS is Copyright (c) 2016 Brett Lajzer\n\/\/ See LICENSE for license information.\n\n#include \"Directory.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _WIN32\n#define UNICODE 1\n#define _UNICODE 1\n#define _CRT_SECURE_NO_WARNINGS 1\n#include \n#include \n#else\n#include \n#include \n#endif\n\nusing namespace laminaFS;\n\nnamespace {\n#ifdef _WIN32\nconstexpr uint32_t MAX_PATH_LEN = 1024;\n\nint widen(const char *inStr, WCHAR *outStr, size_t outStrLen) {\n\treturn MultiByteToWideChar(CP_UTF8, 0, inStr, -1, outStr, (int)outStrLen);\n}\n\nErrorCode convertError(DWORD error) {\n\tErrorCode result = LFS_GENERIC_ERROR;\n\n\tswitch (error) {\n\tcase ERROR_FILE_NOT_FOUND:\n\tcase ERROR_PATH_NOT_FOUND:\n\t\tresult = LFS_NOT_FOUND;\n\t\tbreak;\n\tcase ERROR_ACCESS_DENIED:\n\t\tresult = LFS_PERMISSIONS_ERROR;\n\t\tbreak;\n\t};\n\n\treturn result;\n}\n\n#else\nErrorCode convertError(int error) {\n\tErrorCode result = LFS_GENERIC_ERROR;\n\n\tswitch (error) {\n\tcase EEXIST:\n\t\tresult = LFS_ALREADY_EXISTS;\n\t\tbreak;\n\tcase EPERM:\n\tcase EACCES:\n\t\tresult = LFS_PERMISSIONS_ERROR;\n\t\tbreak;\n\tcase EROFS:\n\t\tresult = LFS_UNSUPPORTED;\n\t\tbreak;\n\tcase ENOENT:\n\t\tresult = LFS_NOT_FOUND;\n\t\tbreak;\n\t}\n\n\treturn result;\n}\n#endif\n}\n\nDirectoryDevice::DirectoryDevice(Allocator *allocator, const char *path) {\n\t_alloc = allocator;\n\n\t\/\/ TODO: realpath()\n\t_pathLen = static_cast(strlen(path));\n\t_devicePath = reinterpret_cast(_alloc->alloc(_alloc->allocator, sizeof(char) * (_pathLen + 1), alignof(char)));\n\tstrcpy(_devicePath, path);\n}\n\nDirectoryDevice::~DirectoryDevice() {\n\t_alloc->free(_alloc->allocator, _devicePath);\n}\n\nErrorCode DirectoryDevice::create(Allocator *alloc, const char *path, void **device) {\n\tErrorCode returnCode = LFS_OK;\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(path, &windowsPath[0], MAX_PATH_LEN);\n\n\tDWORD result = GetFileAttributesW(&windowsPath[0]);\n\n\tif (result != INVALID_FILE_ATTRIBUTES && (result & FILE_ATTRIBUTE_DIRECTORY)) {\n\t\t*device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path);\n\t} else {\n\t\treturnCode = LFS_NOT_FOUND;\n\t}\n#else\n\tstruct stat statInfo;\n\tint result = stat(path, &statInfo);\n\n\tif (result == 0 && S_ISDIR(statInfo.st_mode)) {\n\t\t*device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path);\n\t} else {\n\t\t*device = nullptr;\n\t\treturnCode = LFS_NOT_FOUND;\n\t}\n#endif\n\n\treturn returnCode;\n}\n\nvoid DirectoryDevice::destroy(void *device) {\n\tDirectoryDevice *dir = static_cast(device);\n\tdir->~DirectoryDevice();\n\tdir->_alloc->free(dir->_alloc->allocator, device);\n}\n\n#ifdef _WIN32\nvoid *DirectoryDevice::openFile(const char *filePath, uint32_t accessMode, uint32_t createMode) {\n\tchar *diskPath = getDevicePath(filePath);\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\tfreeDevicePath(diskPath);\n\n\tHANDLE file = CreateFileW(\n\t\t&windowsPath[0],\n\t\taccessMode,\n\t\tFILE_SHARE_READ | FILE_SHARE_WRITE,\n\t\tnullptr,\n\t\tcreateMode,\n\t\tFILE_ATTRIBUTE_NORMAL,\n\t\tnullptr);\n\n\treturn file;\n}\n#else\nFILE *DirectoryDevice::openFile(const char *filePath, const char *modeString) {\n\tchar *diskPath = getDevicePath(filePath);\n\tFILE *file = fopen(diskPath, modeString);\n\tfreeDevicePath(diskPath);\n\treturn file;\n}\n#endif\n\nchar *DirectoryDevice::getDevicePath(const char *filePath) {\n\tuint32_t diskPathLen = static_cast(_pathLen + strlen(filePath) + 1);\n\tchar *diskPath = reinterpret_cast(_alloc->alloc(_alloc->allocator, sizeof(char) * diskPathLen, alignof(char)));\n\tstrcpy(diskPath, _devicePath);\n\tstrcpy(diskPath + _pathLen, filePath);\n\n\t\/\/ replace forward slashes with backslashes on windows\n#ifdef _WIN32\n\tfor (uint32_t i = 0; i < diskPathLen; ++i) {\n\t\tif (diskPath[i] == '\/')\n\t\t\tdiskPath[i] = '\\\\';\n\t}\n#endif\n\n\treturn diskPath;\n}\n\nvoid DirectoryDevice::freeDevicePath(char *path) {\n\t_alloc->free(_alloc->allocator, path);\n}\n\nbool DirectoryDevice::fileExists(void *device, const char *filePath) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(filePath);\n\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\tdev->freeDevicePath(diskPath);\n\n\tDWORD result = GetFileAttributesW(&windowsPath[0]);\n\n\treturn result != INVALID_FILE_ATTRIBUTES && !(result & FILE_ATTRIBUTE_DIRECTORY);\n#else\n\tstruct stat statInfo;\n\tint result = stat(diskPath, &statInfo);\n\n\tdev->freeDevicePath(diskPath);\n\treturn result == 0 && S_ISREG(statInfo.st_mode);\n#endif\n}\n\nsize_t DirectoryDevice::fileSize(void *device, const char *filePath, ErrorCode *outError) {\n\tDirectoryDevice *dev = static_cast(device);\n\tsize_t size = 0;\n\n#ifdef _WIN32\n\tHANDLE file = dev->openFile(filePath, GENERIC_READ, OPEN_EXISTING);\n\n\tif (file) {\n\t\tLARGE_INTEGER result;\n\t\tif(!GetFileSizeEx(file, &result)) {\n\t\t\tprintf(\"error code %lu\\n\", GetLastError());\n\t\t} else {\n\t\t\tsize = result.QuadPart;\n\t\t}\n\t\tCloseHandle(file);\n\t} else {\n\t\t*outError = convertError(GetLastError());\n\t}\n#else\n\tchar *diskPath = dev->getDevicePath(filePath);\n\tstruct stat statInfo;\n\tint result = stat(diskPath, &statInfo);\n\tdev->freeDevicePath(diskPath);\n\n\tif (result == 0 && S_ISREG(statInfo.st_mode)) {\n\t\t*outError = LFS_OK;\n\t\tsize = statInfo.st_size;\n\t} else if (result != 0) {\n\t\t*outError = convertError(errno);\n\t} else {\n\t *outError = LFS_UNSUPPORTED;\n\t}\n#endif\n\treturn size;\n}\n\nsize_t DirectoryDevice::readFile(void *device, const char *filePath, Allocator *alloc, void **buffer, bool nullTerminate, ErrorCode *outError) {\n\tsize_t bytesRead = 0;\n\tDirectoryDevice *dir = static_cast(device);\n#ifdef _WIN32\n\tHANDLE file = dir->openFile(filePath, GENERIC_READ, OPEN_EXISTING);\n\n\tif (file) {\n\t\tLARGE_INTEGER result;\n\t\tGetFileSizeEx(file, &result);\n\t\tsize_t fileSize = result.QuadPart;\n\n\t\tif (fileSize) {\n\t\t\t*buffer = dir->_alloc->alloc(dir->_alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1);\n\n\t\t\tDWORD bytesReadTemp = 0;\n\t\t\tif (!ReadFile(file, *buffer, (DWORD)fileSize, &bytesReadTemp, nullptr)) {\n\t\t\t\t*outError = convertError(GetLastError());\n\t\t\t} else if (nullTerminate) {\n\t\t\t\t(*(char**)buffer)[bytesRead] = 0;\n\t\t\t}\n\n\t\t\tbytesRead = bytesReadTemp;\n\t\t}\n\n\t\tCloseHandle(file);\n\t} else {\n\t\t*outError = LFS_NOT_FOUND;\n\t}\n#else\n\tFILE *file = dir->openFile(filePath, \"rb\");\n\n\tif (file) {\n\t\tsize_t fileSize = 0;\n\t\tif (fseek(file, 0L, SEEK_END) == 0) {\n\t\t\tfileSize = ftell(file);\n\t\t}\n\n\t\tif (fileSize && fseek(file, 0L, SEEK_SET) == 0) {\n\t\t\t*buffer = dir->_alloc->alloc(dir->_alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1);\n\t\t\tif (*buffer) {\n\t\t\t\tbytesRead = fread(*buffer, 1, fileSize, file);\n\n\t\t\t\tif (nullTerminate) {\n\t\t\t\t\t(*(char**)buffer)[bytesRead] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t*outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK;\n\n\t\tfclose(file);\n\t} else {\n\t\t*outError = LFS_NOT_FOUND;\n\t}\n#endif\n\treturn bytesRead;\n}\n\nsize_t DirectoryDevice::writeFile(void *device, const char *filePath, void *buffer, size_t bytesToWrite, bool append, ErrorCode *outError) {\n\tsize_t bytesWritten = 0;\n\tDirectoryDevice *dev = static_cast(device);\n\n#ifdef _WIN32\n\tHANDLE file = dev->openFile(filePath, GENERIC_WRITE, append ? OPEN_ALWAYS : CREATE_ALWAYS);\n\n\tif (file) {\n\t\tif (append) {\n\t\t\tif (SetFilePointer(file, 0, nullptr, FILE_END) == INVALID_SET_FILE_POINTER) {\n\t\t\t\t*outError = LFS_GENERIC_ERROR;\n\t\t\t\tCloseHandle(file);\n\t\t\t\treturn bytesWritten;\n\t\t\t}\n\t\t}\n\n\t\tDWORD temp = 0;\n\t\tif (!WriteFile(file, buffer, (DWORD)bytesToWrite, &temp, nullptr)) {\n\t\t\t\t*outError = LFS_GENERIC_ERROR;\n\t\t} else {\n\t\t\tbytesWritten = temp;\n\t\t}\n\t} else {\n\t\t*outError = convertError(GetLastError());\n\t}\n\n\tCloseHandle(file);\n#else\n\tFILE *file = dev->openFile(filePath, append ? \"ab\" : \"wb\");\n\n\tif (file) {\n\t\tbytesWritten = fwrite(buffer, 1, bytesToWrite, file);\n\t\t*outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK;\n\t\tfclose(file);\n\t} else {\n\t\t*outError = LFS_PERMISSIONS_ERROR;\n\t}\n#endif\n\treturn bytesWritten;\n}\n\nErrorCode DirectoryDevice::deleteFile(void *device, const char *filePath) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(filePath);\n\n\tErrorCode resultCode = LFS_OK;\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\n\tif (!DeleteFileW(&windowsPath[0])) {\n\t\tresultCode = convertError(GetLastError());\n\t}\n#else\n\tif (unlink(diskPath) != 0) {\n\t\tresultCode = convertError(errno);\n\t}\n#endif\n\n\tdev->freeDevicePath(diskPath);\n\treturn resultCode;\n}\n\nErrorCode DirectoryDevice::createDir(void *device, const char *path) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(path);\n\n\tErrorCode resultCode = LFS_OK;\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\n\tif (!CreateDirectoryW(&windowsPath[0], nullptr)) {\n\t\tresultCode = convertError(GetLastError());\n\t}\n#else\n\tint result = mkdir(diskPath, DEFFILEMODE | S_IXUSR | S_IXGRP | S_IRWXO);\n\n\tif (result != 0) {\n\t\tresultCode = convertError(errno);\n\t}\n#endif\n\n\tdev->freeDevicePath(diskPath);\n\treturn resultCode;\n}\n\nErrorCode DirectoryDevice::deleteDir(void *device, const char *path) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(path);\n\n\tErrorCode resultCode = LFS_OK;\n\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\tint len = widen(diskPath, &windowsPath[0], MAX_PATH_LEN - 1); \/\/ XXX: ensure one space for double-null\n\twindowsPath[len] = 0;\n\n\t\/\/ just use the shell API to delete the directory.\n\t\/\/ requires path to be double null-terminated.\n\t\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb762164(v=vs.85).aspx\n\tSHFILEOPSTRUCTW shOp;\n\tshOp.hwnd = nullptr;\n\tshOp.wFunc = FO_DELETE;\n\tshOp.pFrom = &windowsPath[0];\n\tshOp.pTo = nullptr;\n\tshOp.fFlags = FOF_NO_UI;\n\tshOp.fAnyOperationsAborted = FALSE;\n\tshOp.hNameMappings = nullptr;\n\tshOp.lpszProgressTitle = nullptr;\n\n\tint result = SHFileOperationW(&shOp);\n\n\tswitch (result) {\n\tcase 0:\n\t\tbreak;\n\tcase 0x7C: \/\/ DE_INVALIDFILES\n\t\tresultCode = LFS_NOT_FOUND;\n\t\tbreak;\n\tcase 0x78: \/\/ DE_ACCESSDENIEDSRC\n\tcase 0x86: \/\/ DE_SRC_IS_CDROM\n\tcase 0x87: \/\/ DE_SRC_IS_DVD\n\t\tresultCode = LFS_PERMISSIONS_ERROR;\n\t\tbreak;\n\tdefault:\n\t\tresultCode = LFS_GENERIC_ERROR;\n\t\tbreak;\n\t};\n#else\n\tFTS *fts = nullptr;\n\tchar *fileList[] = {diskPath, nullptr};\n\tbool error = false;\n\n\tif ((fts = fts_open(fileList, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {\n\t\tFTSENT *ent = fts_read(fts);\n\t\twhile (!error && ent) {\n\t\t\tswitch (ent->fts_info) {\n\t\t\t\/\/ ignore directories until post-traversal (FTS_DP)\n\t\t\tcase FTS_D:\n\t\t\t\tbreak;\n\n\t\t\t\/\/ normal stuff we want to delete\n\t\t\tcase FTS_DEFAULT:\n\t\t\tcase FTS_DP:\n\t\t\tcase FTS_F:\n\t\t\tcase FTS_SL:\n\t\t\tcase FTS_SLNONE:\n\t\t\t\tif (remove(ent->fts_accpath) == -1) {\n\t\t\t\t\terror = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\/\/ shouldn't ever hit these\n\t\t\tcase FTS_DC:\n\t\t\tcase FTS_DOT:\n\t\t\tcase FTS_NSOK:\n\t\t\t\tbreak;\n\n\t\t\t\/\/ errors\n\t\t\tcase FTS_NS:\n\t\t\tcase FTS_DNR:\n\t\t\tcase FTS_ERR:\n\t\t\t\terror = true;\n\t\t\t\terrno = ent->fts_errno;\n\t\t\t\tbreak;\n\t\t\t};\n\n\t\t\tif (!error)\n\t\t\t\tent = fts_read(fts);\n\t\t}\n\n\t\terror = error || errno != 0;\n\t\tfts_close(fts);\n\t}\n\n\tif (error) {\n\t\tresultCode = convertError(errno);\n\t}\n#endif\n\n\tdev->freeDevicePath(diskPath);\n\treturn resultCode;\n}\nUse the correct allocator when reading files.\/\/ LaminaFS is Copyright (c) 2016 Brett Lajzer\n\/\/ See LICENSE for license information.\n\n#include \"Directory.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\n#ifdef _WIN32\n#define UNICODE 1\n#define _UNICODE 1\n#define _CRT_SECURE_NO_WARNINGS 1\n#include \n#include \n#else\n#include \n#include \n#endif\n\nusing namespace laminaFS;\n\nnamespace {\n#ifdef _WIN32\nconstexpr uint32_t MAX_PATH_LEN = 1024;\n\nint widen(const char *inStr, WCHAR *outStr, size_t outStrLen) {\n\treturn MultiByteToWideChar(CP_UTF8, 0, inStr, -1, outStr, (int)outStrLen);\n}\n\nErrorCode convertError(DWORD error) {\n\tErrorCode result = LFS_GENERIC_ERROR;\n\n\tswitch (error) {\n\tcase ERROR_FILE_NOT_FOUND:\n\tcase ERROR_PATH_NOT_FOUND:\n\t\tresult = LFS_NOT_FOUND;\n\t\tbreak;\n\tcase ERROR_ACCESS_DENIED:\n\t\tresult = LFS_PERMISSIONS_ERROR;\n\t\tbreak;\n\t};\n\n\treturn result;\n}\n\n#else\nErrorCode convertError(int error) {\n\tErrorCode result = LFS_GENERIC_ERROR;\n\n\tswitch (error) {\n\tcase EEXIST:\n\t\tresult = LFS_ALREADY_EXISTS;\n\t\tbreak;\n\tcase EPERM:\n\tcase EACCES:\n\t\tresult = LFS_PERMISSIONS_ERROR;\n\t\tbreak;\n\tcase EROFS:\n\t\tresult = LFS_UNSUPPORTED;\n\t\tbreak;\n\tcase ENOENT:\n\t\tresult = LFS_NOT_FOUND;\n\t\tbreak;\n\t}\n\n\treturn result;\n}\n#endif\n}\n\nDirectoryDevice::DirectoryDevice(Allocator *allocator, const char *path) {\n\t_alloc = allocator;\n\n\t\/\/ TODO: realpath()\n\t_pathLen = static_cast(strlen(path));\n\t_devicePath = reinterpret_cast(_alloc->alloc(_alloc->allocator, sizeof(char) * (_pathLen + 1), alignof(char)));\n\tstrcpy(_devicePath, path);\n}\n\nDirectoryDevice::~DirectoryDevice() {\n\t_alloc->free(_alloc->allocator, _devicePath);\n}\n\nErrorCode DirectoryDevice::create(Allocator *alloc, const char *path, void **device) {\n\tErrorCode returnCode = LFS_OK;\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(path, &windowsPath[0], MAX_PATH_LEN);\n\n\tDWORD result = GetFileAttributesW(&windowsPath[0]);\n\n\tif (result != INVALID_FILE_ATTRIBUTES && (result & FILE_ATTRIBUTE_DIRECTORY)) {\n\t\t*device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path);\n\t} else {\n\t\treturnCode = LFS_NOT_FOUND;\n\t}\n#else\n\tstruct stat statInfo;\n\tint result = stat(path, &statInfo);\n\n\tif (result == 0 && S_ISDIR(statInfo.st_mode)) {\n\t\t*device = new(alloc->alloc(alloc->allocator, sizeof(DirectoryDevice), alignof(DirectoryDevice))) DirectoryDevice(alloc, path);\n\t} else {\n\t\t*device = nullptr;\n\t\treturnCode = LFS_NOT_FOUND;\n\t}\n#endif\n\n\treturn returnCode;\n}\n\nvoid DirectoryDevice::destroy(void *device) {\n\tDirectoryDevice *dir = static_cast(device);\n\tdir->~DirectoryDevice();\n\tdir->_alloc->free(dir->_alloc->allocator, device);\n}\n\n#ifdef _WIN32\nvoid *DirectoryDevice::openFile(const char *filePath, uint32_t accessMode, uint32_t createMode) {\n\tchar *diskPath = getDevicePath(filePath);\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\tfreeDevicePath(diskPath);\n\n\tHANDLE file = CreateFileW(\n\t\t&windowsPath[0],\n\t\taccessMode,\n\t\tFILE_SHARE_READ | FILE_SHARE_WRITE,\n\t\tnullptr,\n\t\tcreateMode,\n\t\tFILE_ATTRIBUTE_NORMAL,\n\t\tnullptr);\n\n\treturn file;\n}\n#else\nFILE *DirectoryDevice::openFile(const char *filePath, const char *modeString) {\n\tchar *diskPath = getDevicePath(filePath);\n\tFILE *file = fopen(diskPath, modeString);\n\tfreeDevicePath(diskPath);\n\treturn file;\n}\n#endif\n\nchar *DirectoryDevice::getDevicePath(const char *filePath) {\n\tuint32_t diskPathLen = static_cast(_pathLen + strlen(filePath) + 1);\n\tchar *diskPath = reinterpret_cast(_alloc->alloc(_alloc->allocator, sizeof(char) * diskPathLen, alignof(char)));\n\tstrcpy(diskPath, _devicePath);\n\tstrcpy(diskPath + _pathLen, filePath);\n\n\t\/\/ replace forward slashes with backslashes on windows\n#ifdef _WIN32\n\tfor (uint32_t i = 0; i < diskPathLen; ++i) {\n\t\tif (diskPath[i] == '\/')\n\t\t\tdiskPath[i] = '\\\\';\n\t}\n#endif\n\n\treturn diskPath;\n}\n\nvoid DirectoryDevice::freeDevicePath(char *path) {\n\t_alloc->free(_alloc->allocator, path);\n}\n\nbool DirectoryDevice::fileExists(void *device, const char *filePath) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(filePath);\n\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\tdev->freeDevicePath(diskPath);\n\n\tDWORD result = GetFileAttributesW(&windowsPath[0]);\n\n\treturn result != INVALID_FILE_ATTRIBUTES && !(result & FILE_ATTRIBUTE_DIRECTORY);\n#else\n\tstruct stat statInfo;\n\tint result = stat(diskPath, &statInfo);\n\n\tdev->freeDevicePath(diskPath);\n\treturn result == 0 && S_ISREG(statInfo.st_mode);\n#endif\n}\n\nsize_t DirectoryDevice::fileSize(void *device, const char *filePath, ErrorCode *outError) {\n\tDirectoryDevice *dev = static_cast(device);\n\tsize_t size = 0;\n\n#ifdef _WIN32\n\tHANDLE file = dev->openFile(filePath, GENERIC_READ, OPEN_EXISTING);\n\n\tif (file) {\n\t\tLARGE_INTEGER result;\n\t\tif(!GetFileSizeEx(file, &result)) {\n\t\t\tprintf(\"error code %lu\\n\", GetLastError());\n\t\t} else {\n\t\t\tsize = result.QuadPart;\n\t\t}\n\t\tCloseHandle(file);\n\t} else {\n\t\t*outError = convertError(GetLastError());\n\t}\n#else\n\tchar *diskPath = dev->getDevicePath(filePath);\n\tstruct stat statInfo;\n\tint result = stat(diskPath, &statInfo);\n\tdev->freeDevicePath(diskPath);\n\n\tif (result == 0 && S_ISREG(statInfo.st_mode)) {\n\t\t*outError = LFS_OK;\n\t\tsize = statInfo.st_size;\n\t} else if (result != 0) {\n\t\t*outError = convertError(errno);\n\t} else {\n\t *outError = LFS_UNSUPPORTED;\n\t}\n#endif\n\treturn size;\n}\n\nsize_t DirectoryDevice::readFile(void *device, const char *filePath, Allocator *alloc, void **buffer, bool nullTerminate, ErrorCode *outError) {\n\tsize_t bytesRead = 0;\n\tDirectoryDevice *dir = static_cast(device);\n#ifdef _WIN32\n\tHANDLE file = dir->openFile(filePath, GENERIC_READ, OPEN_EXISTING);\n\n\tif (file) {\n\t\tLARGE_INTEGER result;\n\t\tGetFileSizeEx(file, &result);\n\t\tsize_t fileSize = result.QuadPart;\n\n\t\tif (fileSize) {\n\t\t\t*buffer = alloc->alloc(alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1);\n\n\t\t\tDWORD bytesReadTemp = 0;\n\t\t\tif (!ReadFile(file, *buffer, (DWORD)fileSize, &bytesReadTemp, nullptr)) {\n\t\t\t\t*outError = convertError(GetLastError());\n\t\t\t} else if (nullTerminate) {\n\t\t\t\t(*(char**)buffer)[bytesRead] = 0;\n\t\t\t}\n\n\t\t\tbytesRead = bytesReadTemp;\n\t\t}\n\n\t\tCloseHandle(file);\n\t} else {\n\t\t*outError = LFS_NOT_FOUND;\n\t}\n#else\n\tFILE *file = dir->openFile(filePath, \"rb\");\n\n\tif (file) {\n\t\tsize_t fileSize = 0;\n\t\tif (fseek(file, 0L, SEEK_END) == 0) {\n\t\t\tfileSize = ftell(file);\n\t\t}\n\n\t\tif (fileSize && fseek(file, 0L, SEEK_SET) == 0) {\n\t\t\t*buffer = alloc->alloc(alloc->allocator, fileSize + (nullTerminate ? 1 : 0), 1);\n\t\t\tif (*buffer) {\n\t\t\t\tbytesRead = fread(*buffer, 1, fileSize, file);\n\n\t\t\t\tif (nullTerminate) {\n\t\t\t\t\t(*(char**)buffer)[bytesRead] = 0;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t*outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK;\n\n\t\tfclose(file);\n\t} else {\n\t\t*outError = LFS_NOT_FOUND;\n\t}\n#endif\n\treturn bytesRead;\n}\n\nsize_t DirectoryDevice::writeFile(void *device, const char *filePath, void *buffer, size_t bytesToWrite, bool append, ErrorCode *outError) {\n\tsize_t bytesWritten = 0;\n\tDirectoryDevice *dev = static_cast(device);\n\n#ifdef _WIN32\n\tHANDLE file = dev->openFile(filePath, GENERIC_WRITE, append ? OPEN_ALWAYS : CREATE_ALWAYS);\n\n\tif (file) {\n\t\tif (append) {\n\t\t\tif (SetFilePointer(file, 0, nullptr, FILE_END) == INVALID_SET_FILE_POINTER) {\n\t\t\t\t*outError = LFS_GENERIC_ERROR;\n\t\t\t\tCloseHandle(file);\n\t\t\t\treturn bytesWritten;\n\t\t\t}\n\t\t}\n\n\t\tDWORD temp = 0;\n\t\tif (!WriteFile(file, buffer, (DWORD)bytesToWrite, &temp, nullptr)) {\n\t\t\t\t*outError = LFS_GENERIC_ERROR;\n\t\t} else {\n\t\t\tbytesWritten = temp;\n\t\t}\n\t} else {\n\t\t*outError = convertError(GetLastError());\n\t}\n\n\tCloseHandle(file);\n#else\n\tFILE *file = dev->openFile(filePath, append ? \"ab\" : \"wb\");\n\n\tif (file) {\n\t\tbytesWritten = fwrite(buffer, 1, bytesToWrite, file);\n\t\t*outError = ferror(file) ? LFS_GENERIC_ERROR : LFS_OK;\n\t\tfclose(file);\n\t} else {\n\t\t*outError = LFS_PERMISSIONS_ERROR;\n\t}\n#endif\n\treturn bytesWritten;\n}\n\nErrorCode DirectoryDevice::deleteFile(void *device, const char *filePath) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(filePath);\n\n\tErrorCode resultCode = LFS_OK;\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\n\tif (!DeleteFileW(&windowsPath[0])) {\n\t\tresultCode = convertError(GetLastError());\n\t}\n#else\n\tif (unlink(diskPath) != 0) {\n\t\tresultCode = convertError(errno);\n\t}\n#endif\n\n\tdev->freeDevicePath(diskPath);\n\treturn resultCode;\n}\n\nErrorCode DirectoryDevice::createDir(void *device, const char *path) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(path);\n\n\tErrorCode resultCode = LFS_OK;\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\twiden(diskPath, &windowsPath[0], MAX_PATH_LEN);\n\n\tif (!CreateDirectoryW(&windowsPath[0], nullptr)) {\n\t\tresultCode = convertError(GetLastError());\n\t}\n#else\n\tint result = mkdir(diskPath, DEFFILEMODE | S_IXUSR | S_IXGRP | S_IRWXO);\n\n\tif (result != 0) {\n\t\tresultCode = convertError(errno);\n\t}\n#endif\n\n\tdev->freeDevicePath(diskPath);\n\treturn resultCode;\n}\n\nErrorCode DirectoryDevice::deleteDir(void *device, const char *path) {\n\tDirectoryDevice *dev = static_cast(device);\n\tchar *diskPath = dev->getDevicePath(path);\n\n\tErrorCode resultCode = LFS_OK;\n\n#ifdef _WIN32\n\tWCHAR windowsPath[MAX_PATH_LEN];\n\tint len = widen(diskPath, &windowsPath[0], MAX_PATH_LEN - 1); \/\/ XXX: ensure one space for double-null\n\twindowsPath[len] = 0;\n\n\t\/\/ just use the shell API to delete the directory.\n\t\/\/ requires path to be double null-terminated.\n\t\/\/ https:\/\/msdn.microsoft.com\/en-us\/library\/windows\/desktop\/bb762164(v=vs.85).aspx\n\tSHFILEOPSTRUCTW shOp;\n\tshOp.hwnd = nullptr;\n\tshOp.wFunc = FO_DELETE;\n\tshOp.pFrom = &windowsPath[0];\n\tshOp.pTo = nullptr;\n\tshOp.fFlags = FOF_NO_UI;\n\tshOp.fAnyOperationsAborted = FALSE;\n\tshOp.hNameMappings = nullptr;\n\tshOp.lpszProgressTitle = nullptr;\n\n\tint result = SHFileOperationW(&shOp);\n\n\tswitch (result) {\n\tcase 0:\n\t\tbreak;\n\tcase 0x7C: \/\/ DE_INVALIDFILES\n\t\tresultCode = LFS_NOT_FOUND;\n\t\tbreak;\n\tcase 0x78: \/\/ DE_ACCESSDENIEDSRC\n\tcase 0x86: \/\/ DE_SRC_IS_CDROM\n\tcase 0x87: \/\/ DE_SRC_IS_DVD\n\t\tresultCode = LFS_PERMISSIONS_ERROR;\n\t\tbreak;\n\tdefault:\n\t\tresultCode = LFS_GENERIC_ERROR;\n\t\tbreak;\n\t};\n#else\n\tFTS *fts = nullptr;\n\tchar *fileList[] = {diskPath, nullptr};\n\tbool error = false;\n\n\tif ((fts = fts_open(fileList, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {\n\t\tFTSENT *ent = fts_read(fts);\n\t\twhile (!error && ent) {\n\t\t\tswitch (ent->fts_info) {\n\t\t\t\/\/ ignore directories until post-traversal (FTS_DP)\n\t\t\tcase FTS_D:\n\t\t\t\tbreak;\n\n\t\t\t\/\/ normal stuff we want to delete\n\t\t\tcase FTS_DEFAULT:\n\t\t\tcase FTS_DP:\n\t\t\tcase FTS_F:\n\t\t\tcase FTS_SL:\n\t\t\tcase FTS_SLNONE:\n\t\t\t\tif (remove(ent->fts_accpath) == -1) {\n\t\t\t\t\terror = true;\n\t\t\t\t}\n\t\t\t\tbreak;\n\n\t\t\t\/\/ shouldn't ever hit these\n\t\t\tcase FTS_DC:\n\t\t\tcase FTS_DOT:\n\t\t\tcase FTS_NSOK:\n\t\t\t\tbreak;\n\n\t\t\t\/\/ errors\n\t\t\tcase FTS_NS:\n\t\t\tcase FTS_DNR:\n\t\t\tcase FTS_ERR:\n\t\t\t\terror = true;\n\t\t\t\terrno = ent->fts_errno;\n\t\t\t\tbreak;\n\t\t\t};\n\n\t\t\tif (!error)\n\t\t\t\tent = fts_read(fts);\n\t\t}\n\n\t\terror = error || errno != 0;\n\t\tfts_close(fts);\n\t}\n\n\tif (error) {\n\t\tresultCode = convertError(errno);\n\t}\n#endif\n\n\tdev->freeDevicePath(diskPath);\n\treturn resultCode;\n}\n<|endoftext|>"} {"text":"#include \n\nvoid SetAliEnSettings()\n{\n \/\/ Routine to load settings from an AliEn environment file.\n\n ifstream fileIn;\n fileIn.open(Form(\"%s\/gclient_env_%d\", gSystem->TempDirectory(), gSystem->GetUid()));\n if (gDebug>0) {printf(\"P010_TAlien.C: parsing %s\/gclient_env_$UID\\n\", gSystem->TempDirectory());}\n TString lineS,tmp;\n char line[4096];\n\n while (fileIn.good()){\n fileIn.getline(line,4096,'\\n');\n lineS = line;\n if (lineS.IsNull()) continue;\n if (lineS.Contains(\"export \")) {\n lineS.ReplaceAll(\"export \",\"\");\n\n TObjArray* array = lineS.Tokenize(\"=\");\n\n if (array->GetEntries() == 2) {\n TObjString *strVar = (TObjString *) array->At(0);\n TObjString *strVal = (TObjString *) array->At(1);\n\n if ((strVar)&&(strVal)) {\n tmp = strVal->GetString();\n tmp.ReplaceAll(\"\\\"\",\"\");\n tmp.ReplaceAll(\"$LD_LIBRARY_PATH\",gSystem->Getenv(\"LD_LIBRARY_PATH\"));\n tmp.ReplaceAll(\"$DYLD_LIBRARY_PATH\",gSystem->Getenv(\"DYLD_LIBRARY_PATH\"));\n tmp.ReplaceAll(\" \",\"\");\n gSystem->Unsetenv(strVar->GetString());\n gSystem->Setenv(strVar->GetString(), tmp);\n if (gDebug>0) {\n Info(\"P010_TAlien\", \"setting environment %s=\\\"%s\\\"\", strVar->GetString().Data(), tmp.Data());\n }\n if (!strVar->GetString().CompareTo(\"GCLIENT_SERVER_LIST\")) {\n gSystem->Unsetenv(\"alien_API_SERVER_LIST\");\n gSystem->Setenv(\"alien_API_SERVER_LIST\", tmp);\n }\n }\n if (array) {\n delete array;\n array = 0 ;\n }\n } else {\n \/\/ parse the MONA_ stuff\n TObjArray* array = lineS.Tokenize(\"\\\" \");\n TString key=\"\";\n TString val=\"\";\n for (int i=0; i< array->GetEntries(); i++) {\n if ( ((TObjString*) array->At(i))->GetString().Contains(\"=\")) {\n if (key.Length() && val.Length()) {\n val.Resize(val.Length()-1);\n if (gDebug>0) {\n Info(\"P010_TAlien\", \"setting environment %s=\\\"%s\\\"\", key.Data(), val.Data());\n }\n gSystem->Unsetenv(key);\n gSystem->Setenv(key, val);\n key=\"\";\n val=\"\";\n }\n key = ((TObjString*) array->At(i))->GetString();\n key.ReplaceAll(\"=\",\"\");\n } else {\n val+=((TObjString*) array->At(i))->GetString();\n val+=\" \";\n }\n }\n if (key.Length() && val.Length()) {\n if (gDebug>0) {\n Info(\"P010_TAlien\", \"setting environment %s=\\\"%s\\\"\", key.Data(), val.Data());\n }\n gSystem->Unsetenv(key);\n gSystem->Setenv(key, val);\n }\n }\n }\n }\n}\n\nvoid P010_TAlien()\n{\n TString configfeatures = gROOT->GetConfigFeatures();\n TString ralienpath = gSystem->Getenv(\"ROOTSYS\");\n ralienpath += \"\/lib\/\"; ralienpath += \"libRAliEn.so\";\n\n \/\/ only if ROOT was compiled with enable-alien we do library setup and configure a handler\n if ((!gSystem->AccessPathName(ralienpath)) || (configfeatures.contains(\"alien\"))) {\n \/\/ you can enforce\n if ((!gSystem->Getenv(\"GBBOX_ENVFILE\")) ||\n ( gSystem->Getenv(\"ALIEN_SOURCE_GCLIENT_ENV\")) ||\n (!gSystem->Getenv(\"ALIEN_SKIP_GCLIENT_ENV\")) ) {\n SetAliEnSettings();\n }\n\n if ( ((gSystem->Load(\"libgapiUI.so\")>=0) && (gSystem->Load(\"libRAliEn.so\")>=0))) {\n gPluginMgr->AddHandler(\"TGrid\", \"^alien\", \"TAlien\",\n \"RAliEn\", \"TAlien(const char*,const char*,const char*,const char*)\");\n } else {\n Error(\"P010_TAlien\",\"Please fix your loader path environment variable to be able to load libRAliEn.so\");\n }\n }\n}\nFix typo.#include \n\nvoid SetAliEnSettings()\n{\n \/\/ Routine to load settings from an AliEn environment file.\n\n ifstream fileIn;\n fileIn.open(Form(\"%s\/gclient_env_%d\", gSystem->TempDirectory(), gSystem->GetUid()));\n if (gDebug>0) {printf(\"P010_TAlien.C: parsing %s\/gclient_env_$UID\\n\", gSystem->TempDirectory());}\n TString lineS,tmp;\n char line[4096];\n\n while (fileIn.good()){\n fileIn.getline(line,4096,'\\n');\n lineS = line;\n if (lineS.IsNull()) continue;\n if (lineS.Contains(\"export \")) {\n lineS.ReplaceAll(\"export \",\"\");\n\n TObjArray* array = lineS.Tokenize(\"=\");\n\n if (array->GetEntries() == 2) {\n TObjString *strVar = (TObjString *) array->At(0);\n TObjString *strVal = (TObjString *) array->At(1);\n\n if ((strVar)&&(strVal)) {\n tmp = strVal->GetString();\n tmp.ReplaceAll(\"\\\"\",\"\");\n tmp.ReplaceAll(\"$LD_LIBRARY_PATH\",gSystem->Getenv(\"LD_LIBRARY_PATH\"));\n tmp.ReplaceAll(\"$DYLD_LIBRARY_PATH\",gSystem->Getenv(\"DYLD_LIBRARY_PATH\"));\n tmp.ReplaceAll(\" \",\"\");\n gSystem->Unsetenv(strVar->GetString());\n gSystem->Setenv(strVar->GetString(), tmp);\n if (gDebug>0) {\n Info(\"P010_TAlien\", \"setting environment %s=\\\"%s\\\"\", strVar->GetString().Data(), tmp.Data());\n }\n if (!strVar->GetString().CompareTo(\"GCLIENT_SERVER_LIST\")) {\n gSystem->Unsetenv(\"alien_API_SERVER_LIST\");\n gSystem->Setenv(\"alien_API_SERVER_LIST\", tmp);\n }\n }\n if (array) {\n delete array;\n array = 0 ;\n }\n } else {\n \/\/ parse the MONA_ stuff\n TObjArray* array = lineS.Tokenize(\"\\\" \");\n TString key=\"\";\n TString val=\"\";\n for (int i=0; i< array->GetEntries(); i++) {\n if ( ((TObjString*) array->At(i))->GetString().Contains(\"=\")) {\n if (key.Length() && val.Length()) {\n val.Resize(val.Length()-1);\n if (gDebug>0) {\n Info(\"P010_TAlien\", \"setting environment %s=\\\"%s\\\"\", key.Data(), val.Data());\n }\n gSystem->Unsetenv(key);\n gSystem->Setenv(key, val);\n key=\"\";\n val=\"\";\n }\n key = ((TObjString*) array->At(i))->GetString();\n key.ReplaceAll(\"=\",\"\");\n } else {\n val+=((TObjString*) array->At(i))->GetString();\n val+=\" \";\n }\n }\n if (key.Length() && val.Length()) {\n if (gDebug>0) {\n Info(\"P010_TAlien\", \"setting environment %s=\\\"%s\\\"\", key.Data(), val.Data());\n }\n gSystem->Unsetenv(key);\n gSystem->Setenv(key, val);\n }\n }\n }\n }\n}\n\nvoid P010_TAlien()\n{\n TString configfeatures = gROOT->GetConfigFeatures();\n TString ralienpath = gSystem->Getenv(\"ROOTSYS\");\n ralienpath += \"\/lib\/\"; ralienpath += \"libRAliEn.so\";\n\n \/\/ only if ROOT was compiled with enable-alien we do library setup and configure a handler\n if ((!gSystem->AccessPathName(ralienpath)) || (configfeatures.Contains(\"alien\"))) {\n \/\/ you can enforce\n if ((!gSystem->Getenv(\"GBBOX_ENVFILE\")) ||\n ( gSystem->Getenv(\"ALIEN_SOURCE_GCLIENT_ENV\")) ||\n (!gSystem->Getenv(\"ALIEN_SKIP_GCLIENT_ENV\")) ) {\n SetAliEnSettings();\n }\n\n if ( ((gSystem->Load(\"libgapiUI.so\")>=0) && (gSystem->Load(\"libRAliEn.so\")>=0))) {\n gPluginMgr->AddHandler(\"TGrid\", \"^alien\", \"TAlien\",\n \"RAliEn\", \"TAlien(const char*,const char*,const char*,const char*)\");\n } else {\n Error(\"P010_TAlien\",\"Please fix your loader path environment variable to be able to load libRAliEn.so\");\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/public\/browser\/browser_main_runner.h\"\n\n#include \"base\/allocator\/allocator_shim.h\"\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/metrics\/statistics_recorder.h\"\n#include \"content\/browser\/browser_main_loop.h\"\n#include \"content\/browser\/notification_service_impl.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/main_function_params.h\"\n#include \"ui\/base\/ime\/input_method_initializer.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win\/metro.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"ui\/base\/win\/scoped_ole_initializer.h\"\n#endif\n\nbool g_exited_main_message_loop = false;\n\nnamespace content {\n\nclass BrowserMainRunnerImpl : public BrowserMainRunner {\n public:\n BrowserMainRunnerImpl()\n : is_initialized_(false),\n is_shutdown_(false),\n created_threads_(false) {\n }\n\n virtual ~BrowserMainRunnerImpl() {\n if (is_initialized_ && !is_shutdown_)\n Shutdown();\n }\n\n virtual int Initialize(const MainFunctionParams& parameters)\n OVERRIDE {\n TRACE_EVENT0(\"startup\", \"BrowserMainRunnerImpl::Initialize\")\n is_initialized_ = true;\n\n#if defined(OS_WIN)\n if (parameters.command_line.HasSwitch(\n switches::kEnableTextServicesFramework)) {\n base::win::SetForceToUseTSF();\n } else if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n \/\/ When \"Extend support of advanced text services to all programs\"\n \/\/ (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on\n \/\/ Windows XP and handwriting modules shipped with Office 2003 are\n \/\/ installed, \"penjpn.dll\" and \"skchui.dll\" will be loaded and then crash\n \/\/ unless a user installs Office 2003 SP3. To prevent these modules from\n \/\/ being loaded, disable TSF entirely. crbug\/160914.\n \/\/ TODO(yukawa): Add a high-level wrapper for this instead of calling\n \/\/ Win32 API here directly.\n ImmDisableTextFrameService(static_cast(-1));\n }\n#endif \/\/ OS_WIN\n\n base::StatisticsRecorder::Initialize();\n\n notification_service_.reset(new NotificationServiceImpl);\n\n#if defined(OS_WIN)\n \/\/ Ole must be initialized before starting message pump, so that TSF\n \/\/ (Text Services Framework) module can interact with the message pump\n \/\/ on Windows 8 Metro mode.\n ole_initializer_.reset(new ui::ScopedOleInitializer);\n#endif \/\/ OS_WIN\n\n main_loop_.reset(new BrowserMainLoop(parameters));\n\n main_loop_->Init();\n\n main_loop_->EarlyInitialization();\n\n \/\/ Must happen before we try to use a message loop or display any UI.\n main_loop_->InitializeToolkit();\n\n main_loop_->MainMessageLoopStart();\n\n \/\/ WARNING: If we get a WM_ENDSESSION, objects created on the stack here\n \/\/ are NOT deleted. If you need something to run during WM_ENDSESSION add it\n \/\/ to browser_shutdown::Shutdown or BrowserProcess::EndSession.\n\n#if defined(OS_WIN) && !defined(NO_TCMALLOC)\n \/\/ When linking shared libraries, NO_TCMALLOC is defined, and dynamic\n \/\/ allocator selection is not supported.\n\n \/\/ Make this call before going multithreaded, or spawning any subprocesses.\n base::allocator::SetupSubprocessAllocator();\n#endif\n ui::InitializeInputMethod();\n\n main_loop_->CreateThreads();\n int result_code = main_loop_->GetResultCode();\n if (result_code > 0)\n return result_code;\n created_threads_ = true;\n\n \/\/ Return -1 to indicate no early termination.\n return -1;\n }\n\n virtual int Run() OVERRIDE {\n DCHECK(is_initialized_);\n DCHECK(!is_shutdown_);\n main_loop_->RunMainMessageLoopParts();\n return main_loop_->GetResultCode();\n }\n\n virtual void Shutdown() OVERRIDE {\n DCHECK(is_initialized_);\n DCHECK(!is_shutdown_);\n g_exited_main_message_loop = true;\n\n if (created_threads_)\n main_loop_->ShutdownThreadsAndCleanUp();\n\n ui::ShutdownInputMethod();\n#if defined(OS_WIN)\n ole_initializer_.reset(NULL);\n#endif\n\n main_loop_.reset(NULL);\n\n notification_service_.reset(NULL);\n\n is_shutdown_ = true;\n }\n\n protected:\n \/\/ True if the runner has been initialized.\n bool is_initialized_;\n\n \/\/ True if the runner has been shut down.\n bool is_shutdown_;\n\n \/\/ True if the non-UI threads were created.\n bool created_threads_;\n\n scoped_ptr notification_service_;\n scoped_ptr main_loop_;\n#if defined(OS_WIN)\n scoped_ptr ole_initializer_;\n#endif\n\n DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);\n};\n\n\/\/ static\nBrowserMainRunner* BrowserMainRunner::Create() {\n return new BrowserMainRunnerImpl();\n}\n\n} \/\/ namespace content\nFix --wait-for-debugger.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/public\/browser\/browser_main_runner.h\"\n\n#include \"base\/allocator\/allocator_shim.h\"\n#include \"base\/base_switches.h\"\n#include \"base\/command_line.h\"\n#include \"base\/debug\/trace_event.h\"\n#include \"base\/logging.h\"\n#include \"base\/metrics\/histogram.h\"\n#include \"base\/metrics\/statistics_recorder.h\"\n#include \"content\/browser\/browser_main_loop.h\"\n#include \"content\/browser\/notification_service_impl.h\"\n#include \"content\/public\/common\/content_switches.h\"\n#include \"content\/public\/common\/main_function_params.h\"\n#include \"ui\/base\/ime\/input_method_initializer.h\"\n\n#if defined(OS_WIN)\n#include \"base\/win\/metro.h\"\n#include \"base\/win\/windows_version.h\"\n#include \"ui\/base\/win\/scoped_ole_initializer.h\"\n#endif\n\nbool g_exited_main_message_loop = false;\n\nnamespace content {\n\nclass BrowserMainRunnerImpl : public BrowserMainRunner {\n public:\n BrowserMainRunnerImpl()\n : is_initialized_(false),\n is_shutdown_(false),\n created_threads_(false) {\n }\n\n virtual ~BrowserMainRunnerImpl() {\n if (is_initialized_ && !is_shutdown_)\n Shutdown();\n }\n\n virtual int Initialize(const MainFunctionParams& parameters)\n OVERRIDE {\n TRACE_EVENT0(\"startup\", \"BrowserMainRunnerImpl::Initialize\")\n is_initialized_ = true;\n\n#if !defined(OS_IOS)\n if (parameters.command_line.HasSwitch(switches::kWaitForDebugger))\n base::debug::WaitForDebugger(60, true);\n#endif\n\n#if defined(OS_WIN)\n if (parameters.command_line.HasSwitch(\n switches::kEnableTextServicesFramework)) {\n base::win::SetForceToUseTSF();\n } else if (base::win::GetVersion() < base::win::VERSION_VISTA) {\n \/\/ When \"Extend support of advanced text services to all programs\"\n \/\/ (a.k.a. Cicero Unaware Application Support; CUAS) is enabled on\n \/\/ Windows XP and handwriting modules shipped with Office 2003 are\n \/\/ installed, \"penjpn.dll\" and \"skchui.dll\" will be loaded and then crash\n \/\/ unless a user installs Office 2003 SP3. To prevent these modules from\n \/\/ being loaded, disable TSF entirely. crbug\/160914.\n \/\/ TODO(yukawa): Add a high-level wrapper for this instead of calling\n \/\/ Win32 API here directly.\n ImmDisableTextFrameService(static_cast(-1));\n }\n#endif \/\/ OS_WIN\n\n base::StatisticsRecorder::Initialize();\n\n notification_service_.reset(new NotificationServiceImpl);\n\n#if defined(OS_WIN)\n \/\/ Ole must be initialized before starting message pump, so that TSF\n \/\/ (Text Services Framework) module can interact with the message pump\n \/\/ on Windows 8 Metro mode.\n ole_initializer_.reset(new ui::ScopedOleInitializer);\n#endif \/\/ OS_WIN\n\n main_loop_.reset(new BrowserMainLoop(parameters));\n\n main_loop_->Init();\n\n main_loop_->EarlyInitialization();\n\n \/\/ Must happen before we try to use a message loop or display any UI.\n main_loop_->InitializeToolkit();\n\n main_loop_->MainMessageLoopStart();\n\n \/\/ WARNING: If we get a WM_ENDSESSION, objects created on the stack here\n \/\/ are NOT deleted. If you need something to run during WM_ENDSESSION add it\n \/\/ to browser_shutdown::Shutdown or BrowserProcess::EndSession.\n\n#if defined(OS_WIN) && !defined(NO_TCMALLOC)\n \/\/ When linking shared libraries, NO_TCMALLOC is defined, and dynamic\n \/\/ allocator selection is not supported.\n\n \/\/ Make this call before going multithreaded, or spawning any subprocesses.\n base::allocator::SetupSubprocessAllocator();\n#endif\n ui::InitializeInputMethod();\n\n main_loop_->CreateThreads();\n int result_code = main_loop_->GetResultCode();\n if (result_code > 0)\n return result_code;\n created_threads_ = true;\n\n \/\/ Return -1 to indicate no early termination.\n return -1;\n }\n\n virtual int Run() OVERRIDE {\n DCHECK(is_initialized_);\n DCHECK(!is_shutdown_);\n main_loop_->RunMainMessageLoopParts();\n return main_loop_->GetResultCode();\n }\n\n virtual void Shutdown() OVERRIDE {\n DCHECK(is_initialized_);\n DCHECK(!is_shutdown_);\n g_exited_main_message_loop = true;\n\n if (created_threads_)\n main_loop_->ShutdownThreadsAndCleanUp();\n\n ui::ShutdownInputMethod();\n#if defined(OS_WIN)\n ole_initializer_.reset(NULL);\n#endif\n\n main_loop_.reset(NULL);\n\n notification_service_.reset(NULL);\n\n is_shutdown_ = true;\n }\n\n protected:\n \/\/ True if the runner has been initialized.\n bool is_initialized_;\n\n \/\/ True if the runner has been shut down.\n bool is_shutdown_;\n\n \/\/ True if the non-UI threads were created.\n bool created_threads_;\n\n scoped_ptr notification_service_;\n scoped_ptr main_loop_;\n#if defined(OS_WIN)\n scoped_ptr ole_initializer_;\n#endif\n\n DISALLOW_COPY_AND_ASSIGN(BrowserMainRunnerImpl);\n};\n\n\/\/ static\nBrowserMainRunner* BrowserMainRunner::Create() {\n return new BrowserMainRunnerImpl();\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"#define BOOST_TEST_MODULE RDOTriangularTest\r\n#include \r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"simulator\/runtime\/rdo_random_distribution.h\"\r\n\r\nBOOST_AUTO_TEST_CASE(RDOTriangularTest)\r\n{\r\n\r\n}* reverted changes from rev.4925\/*!\r\n \\copyright (c) RDO-Team, 2011\r\n \\file main.cpp\r\n \\author (rdo@rk9.bmstu.ru)\r\n \\authors (impus@hotbox.ru)\r\n \\date 12.09.2011\r\n \\brief \r\n \\indent 4T\r\n*\/\r\n\r\n\/\/ ---------------------------------------------------------------------------- PCH\r\n\/\/ ----------------------------------------------------------------------- INCLUDES\r\n#include \"stdafx.h\"\r\n#define BOOST_TEST_MODULE RDOTriangularTest\r\n#include \r\n\/\/ ----------------------------------------------------------------------- SYNOPSIS\r\n#include \"simulator\/runtime\/rdo_random_distribution.h\"\r\n\/\/ --------------------------------------------------------------------------------\r\n\r\nBOOST_AUTO_TEST_CASE(RDOTriangularTest)\r\n{\r\n\r\n}\r\n\r\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright (c) 2016 Charles R. Allen\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n ******************************************************************************\n * lepton.cpp\n *\n * Created on: Mar 7, 2016\n * Author: Charles Allen\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace cv;\nusing namespace std;\n\nstatic const char *dev_name = \"\/dev\/lepton\";\nvoid sig_handler(int signum);\nstatic sig_atomic_t volatile isrunning = 1;\nuint32_t frame_counter = 0;\n#define exitIfMRAAError(x) exitIfMRAAError_internal(x, __FILE__, __LINE__)\n\nstatic void exitIfMRAAError_internal(mraa_result_t result, const char *filename,\n\t\tunsigned int linenum) {\n\tif (__builtin_expect(result != MRAA_SUCCESS, 0)) {\n\t\tconst char *errMsg = NULL;\n\t\tswitch (result) {\n\t\tcase MRAA_ERROR_FEATURE_NOT_IMPLEMENTED:\n\t\t\terrMsg = \"MRAA_ERROR_FEATURE_NOT_IMPLEMENTED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_FEATURE_NOT_SUPPORTED:\n\t\t\terrMsg = \"MRAA_ERROR_FEATURE_NOT_SUPPORTED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_VERBOSITY_LEVEL:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_VERBOSITY_LEVEL\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_PARAMETER:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_PARAMETER\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_HANDLE:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_HANDLE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_NO_RESOURCES:\n\t\t\terrMsg = \"MRAA_ERROR_NO_RESOURCES\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_RESOURCE:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_RESOURCE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_QUEUE_TYPE:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_QUEUE_TYPE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_NO_DATA_AVAILABLE:\n\t\t\terrMsg = \"MRAA_ERROR_NO_DATA_AVAILABLE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_PLATFORM:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_PLATFORM\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_PLATFORM_NOT_INITIALISED:\n\t\t\terrMsg = \"MRAA_ERROR_PLATFORM_NOT_INITIALISED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_PLATFORM_ALREADY_INITIALISED:\n\t\t\terrMsg = \"MRAA_ERROR_PLATFORM_ALREADY_INITIALISED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_UNSPECIFIED:\n\t\t\terrMsg = \"MRAA_ERROR_UNSPECIFIED\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrMsg = \"Completely unknown error in MRAA\";\n\t\t}\n\t\terror_at_line(result, errno, filename, linenum, \"Error %d in MRAA: %s\",\n\t\t\t\t(int) result, errMsg);\n\t}\n}\n\nstatic int captureImage(uint16_t *image, mraa_gpio_context cs, int fd) {\n\tconst int line_len = 164;\n\tint result, i = 0, retval = 0;\n\tuint8_t buff[line_len * 60];\n\twhile (i < 60 && isrunning) {\n\t\tuint8_t *line = &buff[i * line_len];\n\t\tuint16_t *line16 = (uint16_t *) line;\n\t\tmemset(line, 0, line_len);\n\t\tresult = read(fd, line, line_len);\n\t\tif (__builtin_expect(result == -1, 0)) {\n\t\t\terror(0, errno, \"Error reading from [%s]\", dev_name);\n\t\t\tbreak;\n\t\t} else if (__builtin_expect(result != line_len, 0)) {\n\t\t\terror(0, errno, \"Size did not match, read %d, expected %d\",\n\t\t\t\t\t(int) result, line_len);\n\t\t\tbreak;\n\t\t}\n\t\tline[0] &= 0x0F;\n\t\tif (__builtin_expect(line[0] != 0x0F, 0)) {\n\t\t\tuint16_t lineNum = ntohs(line16[0]);\n\t\t\tif (__builtin_expect(i != lineNum, 0)) {\n\t\t\t\tprintf(\"Unexpected line. Expected %d found %d\\n\", (int) i,\n\t\t\t\t\t\t(int) lineNum);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t}\n\tretval = i - 60;\n\tif (__builtin_expect(retval, 0)) {\n\t\treturn retval;\n\t}\n\tfor (i = 0; i < 60; ++i) {\n\t\tuint8_t *line = &buff[i * line_len];\n\t\tmemcpy(&image[i * 80], &line[4], 160);\n\t}\n\n\treturn retval;\n}\n\n#define BOUNDARY \"hfihuuhf782hf4278fh2h4f7842hfh87942h\"\n\nstatic const char boundary_end_str[] = \"\\r\\n--\" BOUNDARY \"\\r\\n\";\n\nstatic int safe_write(int fd, uint8_t *ptr, ssize_t len) {\n\tfor (ssize_t write_remaining = len, my_write = 0; write_remaining > 0;\n\t\t\twrite_remaining -= my_write) {\n\t\tmy_write = write(fd, ptr, write_remaining);\n\t\tif (__builtin_expect(-1 == my_write, 0)) {\n\t\t\t\/\/ Skip things like EAGAIN for now\n\t\t\terror(0, errno, \"Error writing image data\");\n\t\t\treturn -1;\n\t\t}\n\t\tptr = &ptr[my_write];\n\t}\n\treturn len;\n}\n\n\/\/ image is still BigEndian when it gets here\nstatic int printImg(uint16_t *image, int out_fd) {\n\tuint16_t min_v = (uint16_t) -1;\n\tuint16_t max_v = 0;\n\tfor (int i = 0; i < 60; ++i) {\n\t\tuint16_t *line = &image[i * 80];\n\t\tfor (int j = 0; j < 78\/*80*\/; ++j) {\n\t\t\tuint16_t v = line[j] = ntohs(line[j]);\n\t\t\tif (__builtin_expect(v > max_v, 0)) {\n\t\t\t\tmax_v = v;\n\t\t\t}\n\t\t\tif (__builtin_expect(v < min_v, 0)) {\n\t\t\t\tmin_v = v;\n\t\t\t}\n\t\t}\n\t}\n\n\tuint16_t scale = max_v - min_v;\n\tMat grayScaleImage(60, 80, CV_8UC1);\n\tuint8_t *img_out = (uint8_t *) &grayScaleImage.data[0];\n\tfor (int i = 0; i < 60; ++i) {\n\t\tconst int idex = i * 80;\n\t\tuint16_t *line = &image[idex];\n\t\tuint8_t *line_out = &img_out[idex];\n\t\tfor (int j = 0; j < 78\/*80*\/; ++j) {\n\t\t\tline_out[j] = (((line[j] - min_v) << 8) \/ scale) & 0xFF;\n\t\t}\n\t\tline_out[78] = line_out[79] = 0;\n\t}\n\n\tuint8_t strbuff[1024];\n\n\tstd::vector buff;\n\ttry {\n\t\tif (!imencode(\".jpeg\", grayScaleImage, buff)) {\n\t\t\terror(0, 0, \"Error writing jpeg image to buffer\");\n\t\t\treturn -1;\n\t\t}\n\t} catch (cv::Exception &ex) {\n\t\tstd::cout << \"Error writing image: \" <Remove specific IP address.\/******************************************************************************\n * Copyright (c) 2016 Charles R. Allen\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to\n * deal in the Software without restriction, including without limitation\n * the rights to use, copy, modify, merge, publish, distribute, sublicense,\n * and\/or sell copies of the Software, and to permit persons to whom the\n * Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n ******************************************************************************\n * lepton.cpp\n *\n * Created on: Mar 7, 2016\n * Author: Charles Allen\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace cv;\nusing namespace std;\n\nstatic const char *dev_name = \"\/dev\/lepton\";\nvoid sig_handler(int signum);\nstatic sig_atomic_t volatile isrunning = 1;\nuint32_t frame_counter = 0;\n#define exitIfMRAAError(x) exitIfMRAAError_internal(x, __FILE__, __LINE__)\n\nstatic void exitIfMRAAError_internal(mraa_result_t result, const char *filename,\n\t\tunsigned int linenum) {\n\tif (__builtin_expect(result != MRAA_SUCCESS, 0)) {\n\t\tconst char *errMsg = NULL;\n\t\tswitch (result) {\n\t\tcase MRAA_ERROR_FEATURE_NOT_IMPLEMENTED:\n\t\t\terrMsg = \"MRAA_ERROR_FEATURE_NOT_IMPLEMENTED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_FEATURE_NOT_SUPPORTED:\n\t\t\terrMsg = \"MRAA_ERROR_FEATURE_NOT_SUPPORTED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_VERBOSITY_LEVEL:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_VERBOSITY_LEVEL\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_PARAMETER:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_PARAMETER\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_HANDLE:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_HANDLE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_NO_RESOURCES:\n\t\t\terrMsg = \"MRAA_ERROR_NO_RESOURCES\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_RESOURCE:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_RESOURCE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_QUEUE_TYPE:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_QUEUE_TYPE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_NO_DATA_AVAILABLE:\n\t\t\terrMsg = \"MRAA_ERROR_NO_DATA_AVAILABLE\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_INVALID_PLATFORM:\n\t\t\terrMsg = \"MRAA_ERROR_INVALID_PLATFORM\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_PLATFORM_NOT_INITIALISED:\n\t\t\terrMsg = \"MRAA_ERROR_PLATFORM_NOT_INITIALISED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_PLATFORM_ALREADY_INITIALISED:\n\t\t\terrMsg = \"MRAA_ERROR_PLATFORM_ALREADY_INITIALISED\";\n\t\t\tbreak;\n\t\tcase MRAA_ERROR_UNSPECIFIED:\n\t\t\terrMsg = \"MRAA_ERROR_UNSPECIFIED\";\n\t\t\tbreak;\n\t\tdefault:\n\t\t\terrMsg = \"Completely unknown error in MRAA\";\n\t\t}\n\t\terror_at_line(result, errno, filename, linenum, \"Error %d in MRAA: %s\",\n\t\t\t\t(int) result, errMsg);\n\t}\n}\n\nstatic int captureImage(uint16_t *image, mraa_gpio_context cs, int fd) {\n\tconst int line_len = 164;\n\tint result, i = 0, retval = 0;\n\tuint8_t buff[line_len * 60];\n\twhile (i < 60 && isrunning) {\n\t\tuint8_t *line = &buff[i * line_len];\n\t\tuint16_t *line16 = (uint16_t *) line;\n\t\tmemset(line, 0, line_len);\n\t\tresult = read(fd, line, line_len);\n\t\tif (__builtin_expect(result == -1, 0)) {\n\t\t\terror(0, errno, \"Error reading from [%s]\", dev_name);\n\t\t\tbreak;\n\t\t} else if (__builtin_expect(result != line_len, 0)) {\n\t\t\terror(0, errno, \"Size did not match, read %d, expected %d\",\n\t\t\t\t\t(int) result, line_len);\n\t\t\tbreak;\n\t\t}\n\t\tline[0] &= 0x0F;\n\t\tif (__builtin_expect(line[0] != 0x0F, 0)) {\n\t\t\tuint16_t lineNum = ntohs(line16[0]);\n\t\t\tif (__builtin_expect(i != lineNum, 0)) {\n\t\t\t\tprintf(\"Unexpected line. Expected %d found %d\\n\", (int) i,\n\t\t\t\t\t\t(int) lineNum);\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\t}\n\tretval = i - 60;\n\tif (__builtin_expect(retval, 0)) {\n\t\treturn retval;\n\t}\n\tfor (i = 0; i < 60; ++i) {\n\t\tuint8_t *line = &buff[i * line_len];\n\t\tmemcpy(&image[i * 80], &line[4], 160);\n\t}\n\n\treturn retval;\n}\n\n#define BOUNDARY \"hfihuuhf782hf4278fh2h4f7842hfh87942h\"\n\nstatic const char boundary_end_str[] = \"\\r\\n--\" BOUNDARY \"\\r\\n\";\n\nstatic int safe_write(int fd, uint8_t *ptr, ssize_t len) {\n\tfor (ssize_t write_remaining = len, my_write = 0; write_remaining > 0;\n\t\t\twrite_remaining -= my_write) {\n\t\tmy_write = write(fd, ptr, write_remaining);\n\t\tif (__builtin_expect(-1 == my_write, 0)) {\n\t\t\t\/\/ Skip things like EAGAIN for now\n\t\t\terror(0, errno, \"Error writing image data\");\n\t\t\treturn -1;\n\t\t}\n\t\tptr = &ptr[my_write];\n\t}\n\treturn len;\n}\n\n\/\/ image is still BigEndian when it gets here\nstatic int printImg(uint16_t *image, int out_fd) {\n\tuint16_t min_v = (uint16_t) -1;\n\tuint16_t max_v = 0;\n\tfor (int i = 0; i < 60; ++i) {\n\t\tuint16_t *line = &image[i * 80];\n\t\tfor (int j = 0; j < 78\/*80*\/; ++j) {\n\t\t\tuint16_t v = line[j] = ntohs(line[j]);\n\t\t\tif (__builtin_expect(v > max_v, 0)) {\n\t\t\t\tmax_v = v;\n\t\t\t}\n\t\t\tif (__builtin_expect(v < min_v, 0)) {\n\t\t\t\tmin_v = v;\n\t\t\t}\n\t\t}\n\t}\n\n\tuint16_t scale = max_v - min_v;\n\tMat grayScaleImage(60, 80, CV_8UC1);\n\tuint8_t *img_out = (uint8_t *) &grayScaleImage.data[0];\n\tfor (int i = 0; i < 60; ++i) {\n\t\tconst int idex = i * 80;\n\t\tuint16_t *line = &image[idex];\n\t\tuint8_t *line_out = &img_out[idex];\n\t\tfor (int j = 0; j < 78\/*80*\/; ++j) {\n\t\t\tline_out[j] = (((line[j] - min_v) << 8) \/ scale) & 0xFF;\n\t\t}\n\t\tline_out[78] = line_out[79] = 0;\n\t}\n\n\tuint8_t strbuff[1024];\n\n\tstd::vector buff;\n\ttry {\n\t\tif (!imencode(\".jpeg\", grayScaleImage, buff)) {\n\t\t\terror(0, 0, \"Error writing jpeg image to buffer\");\n\t\t\treturn -1;\n\t\t}\n\t} catch (cv::Exception &ex) {\n\t\tstd::cout << \"Error writing image: \" <"} {"text":"\/\/ Copyright 2012 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"syzygy\/agent\/profiler\/return_thunk_factory.h\"\n\n#include \"syzygy\/agent\/profiler\/scoped_last_error_keeper.h\"\n\nnamespace {\n\n\/\/ Static assembly function called by all thunks. It ends up calling to\n\/\/ ReturnThunkFactory::ThunkMain.\nextern \"C\" void __declspec(naked) thunk_main_asm() {\n __asm {\n \/\/ Stash volatile registers.\n push eax\n push ecx\n push edx\n pushfd\n\n \/\/ Get the current cycle time.\n rdtsc\n push edx\n push eax\n\n \/\/ Calculate a pointer to the start of the thunk object as\n \/\/ the return address pushed by the caller, subtracting 5 (the\n \/\/ size of the E8 call instruction) to get a pointer to the\n \/\/ start of the thunk object.\n mov eax, DWORD PTR[esp + 0x18]\n sub eax, 5\n push eax\n\n call agent::client::ReturnThunkFactory::ThunkMain\n\n \/\/ Restore volatile registers, except eax.\n popfd\n pop edx\n pop ecx\n\n \/\/ We start with:\n \/\/ EAX: real ret-address\n \/\/ stack:\n \/\/ pushed EAX\n \/\/ ret-address to thunk\n \/\/\n \/\/ We end with:\n \/\/ EAX: pushed EAX\n \/\/ stack:\n \/\/ ret-address to thunk\n \/\/ real ret-address\n xchg eax, DWORD PTR[esp + 0x4]\n xchg eax, DWORD PTR[esp]\n\n \/\/ Return to the thunk, which will in turn return to the real\n \/\/ return address.\n ret\n }\n}\n\n} \/\/ namespace\n\nnamespace agent {\nnamespace client {\n\nReturnThunkFactory::ReturnThunkFactory(Delegate* delegate)\n : delegate_(delegate),\n first_free_thunk_(NULL) {\n DCHECK(delegate_ != NULL);\n AddPage();\n}\n\nReturnThunkFactory::~ReturnThunkFactory() {\n \/\/ Walk to the head of the page list, then release to the tail.\n Page* current_page = PageFromThunk(first_free_thunk_);\n\n while (current_page->previous_page)\n current_page = current_page->previous_page;\n\n while (current_page->next_page) {\n Page* page_to_free = current_page;\n current_page = current_page->next_page;\n\n \/\/ Notify the delegate of the release. We do this before freeing the memory\n \/\/ to make sure we don't open a race where a new thread could sneak a stack\n \/\/ into the page allocation.\n delegate_->OnPageRemoved(page_to_free);\n\n ::VirtualFree(page_to_free, 0, MEM_RELEASE);\n }\n}\n\nReturnThunkFactory::Thunk* ReturnThunkFactory::MakeThunk(RetAddr real_ret) {\n Thunk* thunk = first_free_thunk_;\n thunk->caller = real_ret;\n\n Page* current_page = PageFromThunk(first_free_thunk_);\n if (first_free_thunk_ != LastThunk(current_page)) {\n first_free_thunk_++;\n } else if (current_page->next_page) {\n first_free_thunk_ = ¤t_page->next_page->thunks[0];\n } else {\n AddPage();\n }\n\n return thunk;\n}\n\nvoid ReturnThunkFactory::AddPage() {\n Page* previous_page = PageFromThunk(first_free_thunk_);\n DCHECK(previous_page == NULL || previous_page->next_page == NULL);\n\n \/\/ TODO(joi): This may be consuming 64K of memory, in which case it would\n \/\/ be more efficient to reserve a larger block at a time if we think we\n \/\/ normally need more than 4K of thunks.\n Page* new_page = reinterpret_cast(::VirtualAlloc(\n NULL, kPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));\n CHECK(new_page);\n new_page->previous_page = previous_page;\n new_page->next_page = NULL;\n new_page->factory = this;\n\n if (previous_page)\n previous_page->next_page = new_page;\n\n \/\/ Since thunks get reused a lot, we optimize a bit by filling in the\n \/\/ static part of all thunks when each page is allocated.\n for (size_t i= 0; i < kNumThunksPerPage; ++i) {\n Thunk* thunk = &new_page->thunks[i];\n thunk->call = 0xE8; \/\/ call\n thunk->func_addr = reinterpret_cast(thunk_main_asm) -\n reinterpret_cast(&thunk->ret);\n thunk->ret = 0xC3;\n }\n\n first_free_thunk_ = &new_page->thunks[0];\n\n \/\/ Notify the delegate that the page has been allocated.\n delegate_->OnPageAdded(new_page);\n}\n\n\/\/ static\nReturnThunkFactory::Page* ReturnThunkFactory::PageFromThunk(Thunk* thunk) {\n return reinterpret_cast(reinterpret_cast(thunk) & kPageMask);\n}\n\n\/\/ static\nReturnThunkFactory::Thunk* ReturnThunkFactory::LastThunk(Page* page) {\n return &page->thunks[kNumThunksPerPage - 1];\n}\n\n\/\/ static\nRetAddr WINAPI ReturnThunkFactory::ThunkMain(Thunk* thunk, uint64 cycles) {\n DCHECK(*reinterpret_cast(thunk) == 0xE8);\n\n ScopedLastErrorKeeper keep_last_error;\n\n ReturnThunkFactory* factory = PageFromThunk(thunk)->factory;\n factory->first_free_thunk_ = thunk;\n\n factory->delegate_->OnFunctionExit(thunk, cycles);\n\n return thunk->caller;\n}\n\n} \/\/ namespace client\n} \/\/ namespace agent\nTweak return thunk assembly.\/\/ Copyright 2012 Google Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"syzygy\/agent\/profiler\/return_thunk_factory.h\"\n\n#include \"syzygy\/agent\/profiler\/scoped_last_error_keeper.h\"\n\nnamespace {\n\n\/\/ Static assembly function called by all thunks. It ends up calling to\n\/\/ ReturnThunkFactory::ThunkMain.\nextern \"C\" void __declspec(naked) thunk_main_asm() {\n __asm {\n \/\/ Stash volatile registers.\n push eax\n push edx\n\n \/\/ Get the current cycle time ASAP.\n rdtsc\n\n push ecx\n pushfd\n\n \/\/ Push the cycle time arg for the ThunkMain function.\n push edx\n push eax\n\n \/\/ Calculate a pointer to the start of the thunk object as\n \/\/ the return address pushed by the caller, subtracting 5 (the\n \/\/ size of the E8 call instruction) to get a pointer to the\n \/\/ start of the thunk object.\n mov eax, DWORD PTR[esp + 0x18]\n sub eax, 5\n push eax\n\n call agent::client::ReturnThunkFactory::ThunkMain\n\n \/\/ Restore volatile registers, except eax.\n popfd\n pop ecx\n pop edx\n\n \/\/ At this point we have:\n \/\/ EAX: real ret-address\n \/\/ stack:\n \/\/ pushed EAX\n \/\/ ret-address to thunk\n push eax\n mov eax, DWORD PTR[esp+4]\n\n \/\/ Return and discard the stored eax and discarded return address.\n ret 8\n }\n}\n\n} \/\/ namespace\n\nnamespace agent {\nnamespace client {\n\nReturnThunkFactory::ReturnThunkFactory(Delegate* delegate)\n : delegate_(delegate),\n first_free_thunk_(NULL) {\n DCHECK(delegate_ != NULL);\n AddPage();\n}\n\nReturnThunkFactory::~ReturnThunkFactory() {\n \/\/ Walk to the head of the page list, then release to the tail.\n Page* current_page = PageFromThunk(first_free_thunk_);\n\n while (current_page->previous_page)\n current_page = current_page->previous_page;\n\n while (current_page->next_page) {\n Page* page_to_free = current_page;\n current_page = current_page->next_page;\n\n \/\/ Notify the delegate of the release. We do this before freeing the memory\n \/\/ to make sure we don't open a race where a new thread could sneak a stack\n \/\/ into the page allocation.\n delegate_->OnPageRemoved(page_to_free);\n\n ::VirtualFree(page_to_free, 0, MEM_RELEASE);\n }\n}\n\nReturnThunkFactory::Thunk* ReturnThunkFactory::MakeThunk(RetAddr real_ret) {\n Thunk* thunk = first_free_thunk_;\n thunk->caller = real_ret;\n\n Page* current_page = PageFromThunk(first_free_thunk_);\n if (first_free_thunk_ != LastThunk(current_page)) {\n first_free_thunk_++;\n } else if (current_page->next_page) {\n first_free_thunk_ = ¤t_page->next_page->thunks[0];\n } else {\n AddPage();\n }\n\n return thunk;\n}\n\nvoid ReturnThunkFactory::AddPage() {\n Page* previous_page = PageFromThunk(first_free_thunk_);\n DCHECK(previous_page == NULL || previous_page->next_page == NULL);\n\n \/\/ TODO(joi): This may be consuming 64K of memory, in which case it would\n \/\/ be more efficient to reserve a larger block at a time if we think we\n \/\/ normally need more than 4K of thunks.\n Page* new_page = reinterpret_cast(::VirtualAlloc(\n NULL, kPageSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE));\n CHECK(new_page);\n new_page->previous_page = previous_page;\n new_page->next_page = NULL;\n new_page->factory = this;\n\n if (previous_page)\n previous_page->next_page = new_page;\n\n \/\/ Since thunks get reused a lot, we optimize a bit by filling in the\n \/\/ static part of all thunks when each page is allocated.\n for (size_t i= 0; i < kNumThunksPerPage; ++i) {\n Thunk* thunk = &new_page->thunks[i];\n thunk->call = 0xE8; \/\/ call\n thunk->func_addr = reinterpret_cast(thunk_main_asm) -\n reinterpret_cast(&thunk->caller);\n }\n\n first_free_thunk_ = &new_page->thunks[0];\n\n \/\/ Notify the delegate that the page has been allocated.\n delegate_->OnPageAdded(new_page);\n}\n\n\/\/ static\nReturnThunkFactory::Page* ReturnThunkFactory::PageFromThunk(Thunk* thunk) {\n return reinterpret_cast(reinterpret_cast(thunk) & kPageMask);\n}\n\n\/\/ static\nReturnThunkFactory::Thunk* ReturnThunkFactory::LastThunk(Page* page) {\n return &page->thunks[kNumThunksPerPage - 1];\n}\n\n\/\/ static\nRetAddr WINAPI ReturnThunkFactory::ThunkMain(Thunk* thunk, uint64 cycles) {\n DCHECK(*reinterpret_cast(thunk) == 0xE8);\n\n ScopedLastErrorKeeper keep_last_error;\n\n ReturnThunkFactory* factory = PageFromThunk(thunk)->factory;\n factory->first_free_thunk_ = thunk;\n\n factory->delegate_->OnFunctionExit(thunk, cycles);\n\n return thunk->caller;\n}\n\n} \/\/ namespace client\n} \/\/ namespace agent\n<|endoftext|>"} {"text":"#include \"engine\/polyline_compressor.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace \/*detail*\/ \/\/ anonymous to keep TU local\n{\n\nstd::string encode(int number_to_encode)\n{\n std::string output;\n while (number_to_encode >= 0x20)\n {\n const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63;\n output += static_cast(next_value);\n number_to_encode >>= 5;\n }\n\n number_to_encode += 63;\n output += static_cast(number_to_encode);\n return output;\n}\n\nstd::string encode(std::vector &numbers)\n{\n std::string output;\n for (auto &number : numbers)\n {\n bool isNegative = number < 0;\n\n if (isNegative)\n {\n const unsigned binary = std::llabs(number);\n const unsigned twos = (~binary) + 1u;\n number = twos;\n }\n\n number <<= 1u;\n\n if (isNegative)\n {\n number = ~number;\n }\n }\n for (const int number : numbers)\n {\n output += encode(number);\n }\n return output;\n}\n} \/\/ anonymous ns\n\nstd::string encodePolyline(CoordVectorForwardIter begin, CoordVectorForwardIter end)\n{\n auto size = std::distance(begin, end);\n if (size == 0)\n {\n return {};\n }\n\n std::vector delta_numbers;\n BOOST_ASSERT(size > 0);\n delta_numbers.reserve((size - 1) * 2);\n util::Coordinate previous_coordinate{util::FixedLongitude(0), util::FixedLatitude(0)};\n std::for_each(begin, end, [&delta_numbers, &previous_coordinate](const util::Coordinate loc)\n {\n const int lat_diff = static_cast(loc.lat - previous_coordinate.lat) *\n detail::COORDINATE_TO_POLYLINE;\n const int lon_diff = static_cast(loc.lon - previous_coordinate.lon) *\n detail::COORDINATE_TO_POLYLINE;\n delta_numbers.emplace_back(lat_diff);\n delta_numbers.emplace_back(lon_diff);\n previous_coordinate = loc;\n });\n return encode(delta_numbers);\n}\nstd::vector decodePolyline(const std::string &geometry_string)\n{\n std::vector new_coordinates;\n int index = 0, len = geometry_string.size();\n int lat = 0, lng = 0;\n\n while (index < len)\n {\n int b, shift = 0, result = 0;\n do\n {\n b = geometry_string.at(index++) - 63;\n result |= (b & 0x1f) << shift;\n shift += 5;\n } while (b >= 0x20);\n int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));\n lat += dlat;\n\n shift = 0;\n result = 0;\n do\n {\n b = geometry_string.at(index++) - 63;\n result |= (b & 0x1f) << shift;\n shift += 5;\n } while (b >= 0x20);\n int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));\n lng += dlng;\n\n util::Coordinate p;\n p.lat = util::FixedLatitude(lat * detail::POLYLINE_TO_COORDINATE);\n p.lon = util::FixedLongitude(lng * detail::POLYLINE_TO_COORDINATE);\n new_coordinates.push_back(p);\n }\n\n return new_coordinates;\n}\n}\n}\nFix numerical problems with polyline#include \"engine\/polyline_compressor.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace osrm\n{\nnamespace engine\n{\nnamespace \/*detail*\/ \/\/ anonymous to keep TU local\n{\n\nstd::string encode(int number_to_encode)\n{\n std::string output;\n while (number_to_encode >= 0x20)\n {\n const int next_value = (0x20 | (number_to_encode & 0x1f)) + 63;\n output += static_cast(next_value);\n number_to_encode >>= 5;\n }\n\n number_to_encode += 63;\n output += static_cast(number_to_encode);\n return output;\n}\n\nstd::string encode(std::vector &numbers)\n{\n std::string output;\n for (auto &number : numbers)\n {\n bool isNegative = number < 0;\n\n if (isNegative)\n {\n const unsigned binary = std::llabs(number);\n const unsigned twos = (~binary) + 1u;\n number = twos;\n }\n\n number <<= 1u;\n\n if (isNegative)\n {\n number = ~number;\n }\n }\n for (const int number : numbers)\n {\n output += encode(number);\n }\n return output;\n}\n} \/\/ anonymous ns\n\nstd::string encodePolyline(CoordVectorForwardIter begin, CoordVectorForwardIter end)\n{\n auto size = std::distance(begin, end);\n if (size == 0)\n {\n return {};\n }\n\n std::vector delta_numbers;\n BOOST_ASSERT(size > 0);\n delta_numbers.reserve((size - 1) * 2);\n int current_lat = 0;\n int current_lon = 0;\n std::for_each(begin, end, [&delta_numbers, ¤t_lat, ¤t_lon](const util::Coordinate loc)\n {\n const int lat_diff = std::round(static_cast(loc.lat) * detail::COORDINATE_TO_POLYLINE) - current_lat;\n const int lon_diff = std::round(static_cast(loc.lon) * detail::COORDINATE_TO_POLYLINE) - current_lon;\n delta_numbers.emplace_back(lat_diff);\n delta_numbers.emplace_back(lon_diff);\n current_lat += lat_diff;\n current_lon += lon_diff;\n });\n return encode(delta_numbers);\n}\nstd::vector decodePolyline(const std::string &geometry_string)\n{\n std::vector new_coordinates;\n int index = 0, len = geometry_string.size();\n int lat = 0, lng = 0;\n\n while (index < len)\n {\n int b, shift = 0, result = 0;\n do\n {\n b = geometry_string.at(index++) - 63;\n result |= (b & 0x1f) << shift;\n shift += 5;\n } while (b >= 0x20);\n int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));\n lat += dlat;\n\n shift = 0;\n result = 0;\n do\n {\n b = geometry_string.at(index++) - 63;\n result |= (b & 0x1f) << shift;\n shift += 5;\n } while (b >= 0x20);\n int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));\n lng += dlng;\n\n util::Coordinate p;\n p.lat = util::FixedLatitude(lat * detail::POLYLINE_TO_COORDINATE);\n p.lon = util::FixedLongitude(lng * detail::POLYLINE_TO_COORDINATE);\n new_coordinates.push_back(p);\n }\n\n return new_coordinates;\n}\n}\n}\n<|endoftext|>"} {"text":"\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 2012 Unvanquished Developers\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see .\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n\nextern \"C\"\n{\n#include \"q_shared.h\"\n#include \"qcommon.h\"\n#include \"..\/..\/libs\/findlocale\/findlocale.h\"\n}\n\n#include \"..\/..\/libs\/tinygettext\/tinygettext.hpp\"\n#include \n#include \n\nusing namespace tinygettext;\n\/\/ Ugly char buffer\nstatic char gettextbuffer[ MAX_STRING_CHARS ];\n\nDictionaryManager trans_manager;\nDictionaryManager trans_managergame;\nDictionary trans_dict;\nDictionary trans_dictgame;\n\ncvar_t *language;\ncvar_t *language_debug;\ncvar_t *trans_encodings;\ncvar_t *trans_languages;\nbool enabled = false;\nint modificationCount=0;\n\n#define _(x) Trans_Gettext(x)\n#define C_(x, y) Trans_Pgettext(x, y)\n\n\/*\n====================\nTrans_ReturnLanguage\n\nReturn a loaded language. If desired language is not found, return closest match. \nIf no languages are close, force English.\n====================\n*\/\nLanguage Trans_ReturnLanguage( const char *lang )\n{\n\tint bestScore = 0;\n\tLanguage bestLang, language = Language::from_env( std::string( lang ) );\n\t\n\tstd::set langs = trans_manager.get_languages();\n\tfor( std::set::iterator i = langs.begin(); i != langs.end(); i++ )\n\t{\n\t\tint score = Language::match( language, *i );\n\t\t\n\t\tif( score > bestScore )\n\t\t{\n\t\t\tbestScore = score;\n\t\t\tbestLang = *i;\n\t\t}\n\t}\n\t\n\t\/\/ Return \"en\" if language not found\n\tif( !bestLang )\n\t{\n\t\tCom_Printf( _(\"^3WARNING:^7 Language \\\"%s\\\" (%s) not found. Default to \\\"English\\\" (en)\\n\"),\n\t\t\t\t\tlanguage.get_name().empty() ? _(\"Unknown Language\") : language.get_name().c_str(),\n\t\t\t\t\tlang );\n\t\tbestLang = Language::from_env( \"en\" );\n\t}\n\t\n\treturn bestLang;\n}\n\nextern \"C\" void Trans_UpdateLanguage_f( void )\n{\n\tif( !enabled ) { return; }\n\tLanguage lang = Trans_ReturnLanguage( language->string );\n\ttrans_dict = trans_manager.get_dictionary( lang );\n\ttrans_dictgame = trans_managergame.get_dictionary( lang );\n\tCom_Printf(_( \"Switched language to %s\\n\"), lang.get_name().c_str() );\n\n#ifndef DEDICATED\n\t\/\/ update the default console keys string\n\textern cvar_t *cl_consoleKeys; \/\/ should really #include client.h\n\tZ_Free( cl_consoleKeys->resetString );\n\tcl_consoleKeys->resetString = CopyString( _(\"~ ` 0x7e 0x60\") );\n#endif\n}\n\n\/*\n============\nTrans_Init\n============\n*\/\nextern \"C\" void Trans_Init( void )\n{\n\tchar **poFiles, langList[ MAX_TOKEN_CHARS ] = \"\", encList[ MAX_TOKEN_CHARS ] = \"\";\n\tint numPoFiles, i;\n\tFL_Locale *locale;\n\tstd::set langs;\n\tLanguage lang;\n\t\n\tlanguage = Cvar_Get( \"language\", \"\", CVAR_ARCHIVE );\n\tlanguage_debug = Cvar_Get( \"language_debug\", \"0\", CVAR_ARCHIVE );\n\ttrans_languages = Cvar_Get( \"trans_languages\", \"\", CVAR_ROM );\n\ttrans_encodings = Cvar_Get( \"trans_languages\", \"\", CVAR_ROM );\n\t\n\t\/\/ Only detect locale if no previous language set.\n\tif( !language->string[0] )\n\t{\n\t\tFL_FindLocale( &locale, FL_MESSAGES );\n\t\t\n\t\t\/\/ Invalid or not found. Just use builtin language.\n\t\tif( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] ) \n\t\t{\n\t\t\tCvar_Set( \"language\", \"en\" );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCvar_Set( \"language\", va( \"%s%s%s\", locale->lang, \n\t\t\t\t\t\t\t\t\t locale->country[0] ? \"_\" : \"\",\n\t\t\t\t\t\t\t\t\t locale->country ) );\n\t\t}\n\t}\n\t\n\tpoFiles = FS_ListFiles( \"translation\/client\", \".po\", &numPoFiles );\n\t\n\t\/\/ This assumes that the filenames in both folders are the same\n\tfor( i = 0; i < numPoFiles; i++ )\n\t{\n\t\tint ret;\n\t\tchar *buffer, language[ 6 ];\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/client\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf(_( \"^1ERROR: Could not open client translation: %s\\n\"), poFiles[ i ] );\n\t\t}\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/game\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf(_( \"^1ERROR: Could not open game translation: %s\\n\"), poFiles[ i ] );\n\t\t}\n\t}\n\tFS_FreeFileList( poFiles );\n\tlangs = trans_manager.get_languages();\n\tfor( std::set::iterator p = langs.begin(); p != langs.end(); p++ )\n\t{\n\t\tQ_strcat( langList, sizeof( langList ), va( \"\\\"%s\\\" \", p->get_name().c_str() ) );\n\t\tQ_strcat( encList, sizeof( encList ), va( \"\\\"%s%s%s\\\" \", p->get_language().c_str(), \n\t\t\t\t\t\t\t\t\t\t\t\t p->get_country().c_str()[0] ? \"_\" : \"\",\n\t\t\t\t\t\t\t\t\t\t\t\t p->get_country().c_str() ) );\n\t}\n\tCvar_Set( \"trans_languages\", langList );\n\tCvar_Set( \"trans_encodings\", encList );\n\tCom_Printf(_( \"Loaded %lu language(s)\\n\"), langs.size() );\n\tCmd_AddCommand( \"updatelanguage\", Trans_UpdateLanguage_f );\n\tif( langs.size() )\n\t{\n\t\tlang = Trans_ReturnLanguage( language->string );\n\t\ttrans_dict = trans_manager.get_dictionary( lang );\n\t\ttrans_dictgame = trans_managergame.get_dictionary( lang );\n\t\tenabled = true;\n\t}\n}\n\nextern \"C\" const char* Trans_Gettext( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\tQ_strncpyz( gettextbuffer, trans_dict.translate( msgid ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_Pgettext( const char *ctxt, const char *msgid )\n{\n\tif ( !enabled ) { return msgid; }\n\tQ_strncpyz( gettextbuffer, trans_dict.translate_ctxt( ctxt, msgid ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_GettextGame( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\tQ_strncpyz( gettextbuffer, trans_dictgame.translate( msgid ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_PgettextGame( const char *ctxt, const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\treturn trans_dictgame.translate_ctxt( std::string( ctxt ), std::string( msgid ) ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\tQ_strncpyz( gettextbuffer, trans_dict.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\tQ_strncpyz( gettextbuffer, trans_dictgame.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\nFix some unused variable warnings\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 2012 Unvanquished Developers\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see .\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n\nextern \"C\"\n{\n#include \"q_shared.h\"\n#include \"qcommon.h\"\n#include \"..\/..\/libs\/findlocale\/findlocale.h\"\n}\n\n#include \"..\/..\/libs\/tinygettext\/tinygettext.hpp\"\n#include \n#include \n\nusing namespace tinygettext;\n\/\/ Ugly char buffer\nstatic char gettextbuffer[ MAX_STRING_CHARS ];\n\nDictionaryManager trans_manager;\nDictionaryManager trans_managergame;\nDictionary trans_dict;\nDictionary trans_dictgame;\n\ncvar_t *language;\ncvar_t *language_debug;\ncvar_t *trans_encodings;\ncvar_t *trans_languages;\nbool enabled = false;\nint modificationCount=0;\n\n#define _(x) Trans_Gettext(x)\n#define C_(x, y) Trans_Pgettext(x, y)\n\n\/*\n====================\nTrans_ReturnLanguage\n\nReturn a loaded language. If desired language is not found, return closest match. \nIf no languages are close, force English.\n====================\n*\/\nLanguage Trans_ReturnLanguage( const char *lang )\n{\n\tint bestScore = 0;\n\tLanguage bestLang, language = Language::from_env( std::string( lang ) );\n\t\n\tstd::set langs = trans_manager.get_languages();\n\tfor( std::set::iterator i = langs.begin(); i != langs.end(); i++ )\n\t{\n\t\tint score = Language::match( language, *i );\n\t\t\n\t\tif( score > bestScore )\n\t\t{\n\t\t\tbestScore = score;\n\t\t\tbestLang = *i;\n\t\t}\n\t}\n\t\n\t\/\/ Return \"en\" if language not found\n\tif( !bestLang )\n\t{\n\t\tCom_Printf( _(\"^3WARNING:^7 Language \\\"%s\\\" (%s) not found. Default to \\\"English\\\" (en)\\n\"),\n\t\t\t\t\tlanguage.get_name().empty() ? _(\"Unknown Language\") : language.get_name().c_str(),\n\t\t\t\t\tlang );\n\t\tbestLang = Language::from_env( \"en\" );\n\t}\n\t\n\treturn bestLang;\n}\n\nextern \"C\" void Trans_UpdateLanguage_f( void )\n{\n\tif( !enabled ) { return; }\n\tLanguage lang = Trans_ReturnLanguage( language->string );\n\ttrans_dict = trans_manager.get_dictionary( lang );\n\ttrans_dictgame = trans_managergame.get_dictionary( lang );\n\tCom_Printf(_( \"Switched language to %s\\n\"), lang.get_name().c_str() );\n\n#ifndef DEDICATED\n\t\/\/ update the default console keys string\n\textern cvar_t *cl_consoleKeys; \/\/ should really #include client.h\n\tZ_Free( cl_consoleKeys->resetString );\n\tcl_consoleKeys->resetString = CopyString( _(\"~ ` 0x7e 0x60\") );\n#endif\n}\n\n\/*\n============\nTrans_Init\n============\n*\/\nextern \"C\" void Trans_Init( void )\n{\n\tchar **poFiles, langList[ MAX_TOKEN_CHARS ] = \"\", encList[ MAX_TOKEN_CHARS ] = \"\";\n\tint numPoFiles, i;\n\tFL_Locale *locale;\n\tstd::set langs;\n\tLanguage lang;\n\t\n\tlanguage = Cvar_Get( \"language\", \"\", CVAR_ARCHIVE );\n\tlanguage_debug = Cvar_Get( \"language_debug\", \"0\", CVAR_ARCHIVE );\n\ttrans_languages = Cvar_Get( \"trans_languages\", \"\", CVAR_ROM );\n\ttrans_encodings = Cvar_Get( \"trans_languages\", \"\", CVAR_ROM );\n\t\n\t\/\/ Only detect locale if no previous language set.\n\tif( !language->string[0] )\n\t{\n\t\tFL_FindLocale( &locale, FL_MESSAGES );\n\t\t\n\t\t\/\/ Invalid or not found. Just use builtin language.\n\t\tif( !locale->lang || !locale->lang[0] || !locale->country || !locale->country[0] ) \n\t\t{\n\t\t\tCvar_Set( \"language\", \"en\" );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCvar_Set( \"language\", va( \"%s%s%s\", locale->lang, \n\t\t\t\t\t\t\t\t\t locale->country[0] ? \"_\" : \"\",\n\t\t\t\t\t\t\t\t\t locale->country ) );\n\t\t}\n\t}\n\t\n\tpoFiles = FS_ListFiles( \"translation\/client\", \".po\", &numPoFiles );\n\t\n\t\/\/ This assumes that the filenames in both folders are the same\n\tfor( i = 0; i < numPoFiles; i++ )\n\t{\n\t\tchar *buffer, language[ 6 ];\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/client\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_manager.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf(_( \"^1ERROR: Could not open client translation: %s\\n\"), poFiles[ i ] );\n\t\t}\n\t\t\n\t\tif( FS_ReadFile( va( \"translation\/game\/%s\", poFiles[ i ] ), ( void ** ) &buffer ) > 0 )\n\t\t{\n\t\t\tCOM_StripExtension2( poFiles[ i ], language, sizeof( language ) );\n\t\t\tstd::stringstream ss( buffer );\n\t\t\ttrans_managergame.add_po( poFiles[ i ], ss, Language::from_env( std::string( language ) ) );\n\t\t\tFS_FreeFile( buffer );\n\t\t}\n\t\telse\n\t\t{\n\t\t\tCom_Printf(_( \"^1ERROR: Could not open game translation: %s\\n\"), poFiles[ i ] );\n\t\t}\n\t}\n\tFS_FreeFileList( poFiles );\n\tlangs = trans_manager.get_languages();\n\tfor( std::set::iterator p = langs.begin(); p != langs.end(); p++ )\n\t{\n\t\tQ_strcat( langList, sizeof( langList ), va( \"\\\"%s\\\" \", p->get_name().c_str() ) );\n\t\tQ_strcat( encList, sizeof( encList ), va( \"\\\"%s%s%s\\\" \", p->get_language().c_str(), \n\t\t\t\t\t\t\t\t\t\t\t\t p->get_country().c_str()[0] ? \"_\" : \"\",\n\t\t\t\t\t\t\t\t\t\t\t\t p->get_country().c_str() ) );\n\t}\n\tCvar_Set( \"trans_languages\", langList );\n\tCvar_Set( \"trans_encodings\", encList );\n\tCom_Printf(_( \"Loaded %lu language(s)\\n\"), langs.size() );\n\tCmd_AddCommand( \"updatelanguage\", Trans_UpdateLanguage_f );\n\tif( langs.size() )\n\t{\n\t\tlang = Trans_ReturnLanguage( language->string );\n\t\ttrans_dict = trans_manager.get_dictionary( lang );\n\t\ttrans_dictgame = trans_managergame.get_dictionary( lang );\n\t\tenabled = true;\n\t}\n}\n\nextern \"C\" const char* Trans_Gettext( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\tQ_strncpyz( gettextbuffer, trans_dict.translate( msgid ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_Pgettext( const char *ctxt, const char *msgid )\n{\n\tif ( !enabled ) { return msgid; }\n\tQ_strncpyz( gettextbuffer, trans_dict.translate_ctxt( ctxt, msgid ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_GettextGame( const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\tQ_strncpyz( gettextbuffer, trans_dictgame.translate( msgid ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_PgettextGame( const char *ctxt, const char *msgid )\n{\n\tif( !enabled ) { return msgid; }\n\treturn trans_dictgame.translate_ctxt( std::string( ctxt ), std::string( msgid ) ).c_str();\n}\n\nextern \"C\" const char* Trans_GettextPlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\tQ_strncpyz( gettextbuffer, trans_dict.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n\nextern \"C\" const char* Trans_GettextGamePlural( const char *msgid, const char *msgid_plural, int num )\n{\n\tif( !enabled ) { return num == 1 ? msgid : msgid_plural; }\n\tQ_strncpyz( gettextbuffer, trans_dictgame.translate_plural( msgid, msgid_plural, num ).c_str(), sizeof( gettextbuffer ) );\n\treturn gettextbuffer;\n}\n<|endoftext|>"} {"text":"\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifndef __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__\n#define __MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__\n\n#include \"mitkDiffusionImageSource.h\"\n#include \"mitkDiffusionImage.h\"\n\ntemplate\nmitk::DiffusionImageSource::DiffusionImageSource()\n{\n \/\/ Create the output. We use static_cast<> here because we know the default\n \/\/ output must be of type DiffusionImage\n typename mitk::DiffusionImage::Pointer output\n = static_cast*>(this->MakeOutput(0).GetPointer());\n\n Superclass::SetNumberOfRequiredOutputs(1);\n Superclass::SetNthOutput(0, output.GetPointer());\n}\n\ntemplate\nmitk::DiffusionImageSource::~DiffusionImageSource()\n{\n}\n\ntemplate\nitk::DataObject::Pointer mitk::DiffusionImageSource::MakeOutput ( DataObjectPointerArraySizeType \/*idx*\/ )\n{\n return OutputType::New().GetPointer();\n}\n\n\ntemplate\nitk::DataObject::Pointer mitk::DiffusionImageSource::MakeOutput( const DataObjectIdentifierType & name )\n{\n itkDebugMacro(\"MakeOutput(\" << name << \")\");\n if( this->IsIndexedOutputName(name) )\n {\n return this->MakeOutput( this->MakeIndexFromOutputName(name) );\n }\n return static_cast(OutputType::New().GetPointer());\n}\n\ntemplate\ntypename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(void)\n{\n return itkDynamicCastInDebugMode( this->GetPrimaryOutput() );\n}\n\ntemplate\nconst typename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(void) const\n{\n return itkDynamicCastInDebugMode( this->GetPrimaryOutput() );\n}\n\ntemplate\ntypename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(DataObjectPointerArraySizeType idx)\n{\n OutputType* out = dynamic_cast( this->ProcessObject::GetOutput(idx) );\n if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )\n {\n itkWarningMacro (<< \"Unable to convert output number \" << idx << \" to type \" << typeid( OutputType ).name () );\n }\n return out;\n}\n\ntemplate\nconst typename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(DataObjectPointerArraySizeType idx) const\n{\n const OutputType* out = dynamic_cast( this->ProcessObject::GetOutput(idx) );\n if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )\n {\n itkWarningMacro (<< \"Unable to convert output number \" << idx << \" to type \" << typeid( OutputType ).name () );\n }\n return out;\n}\n\n#endif \/\/__MITK_NRRD_DIFFUSION_VOULMES_IO_FACTORY_CPP__\nFixed pre-processor macro name\/*===================================================================\n\nThe Medical Imaging Interaction Toolkit (MITK)\n\nCopyright (c) German Cancer Research Center,\nDivision of Medical and Biological Informatics.\nAll rights reserved.\n\nThis software is distributed WITHOUT ANY WARRANTY; without\neven the implied warranty of MERCHANTABILITY or FITNESS FOR\nA PARTICULAR PURPOSE.\n\nSee LICENSE.txt or http:\/\/www.mitk.org for details.\n\n===================================================================*\/\n\n#ifndef __MITK_DIFFUSIONIMAGE_SOURCE_CPP__\n#define __MITK_DIFFUSIONIMAGE_SOURCE_CPP__\n\n#include \"mitkDiffusionImageSource.h\"\n#include \"mitkDiffusionImage.h\"\n\ntemplate\nmitk::DiffusionImageSource::DiffusionImageSource()\n{\n \/\/ Create the output. We use static_cast<> here because we know the default\n \/\/ output must be of type DiffusionImage\n typename mitk::DiffusionImage::Pointer output\n = static_cast*>(this->MakeOutput(0).GetPointer());\n\n Superclass::SetNumberOfRequiredOutputs(1);\n Superclass::SetNthOutput(0, output.GetPointer());\n}\n\ntemplate\nmitk::DiffusionImageSource::~DiffusionImageSource()\n{\n}\n\ntemplate\nitk::DataObject::Pointer mitk::DiffusionImageSource::MakeOutput ( DataObjectPointerArraySizeType \/*idx*\/ )\n{\n return OutputType::New().GetPointer();\n}\n\n\ntemplate\nitk::DataObject::Pointer mitk::DiffusionImageSource::MakeOutput( const DataObjectIdentifierType & name )\n{\n itkDebugMacro(\"MakeOutput(\" << name << \")\");\n if( this->IsIndexedOutputName(name) )\n {\n return this->MakeOutput( this->MakeIndexFromOutputName(name) );\n }\n return static_cast(OutputType::New().GetPointer());\n}\n\ntemplate\ntypename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(void)\n{\n return itkDynamicCastInDebugMode( this->GetPrimaryOutput() );\n}\n\ntemplate\nconst typename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(void) const\n{\n return itkDynamicCastInDebugMode( this->GetPrimaryOutput() );\n}\n\ntemplate\ntypename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(DataObjectPointerArraySizeType idx)\n{\n OutputType* out = dynamic_cast( this->ProcessObject::GetOutput(idx) );\n if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )\n {\n itkWarningMacro (<< \"Unable to convert output number \" << idx << \" to type \" << typeid( OutputType ).name () );\n }\n return out;\n}\n\ntemplate\nconst typename mitk::DiffusionImageSource::OutputType*\nmitk::DiffusionImageSource::GetOutput(DataObjectPointerArraySizeType idx) const\n{\n const OutputType* out = dynamic_cast( this->ProcessObject::GetOutput(idx) );\n if ( out == NULL && this->ProcessObject::GetOutput(idx) != NULL )\n {\n itkWarningMacro (<< \"Unable to convert output number \" << idx << \" to type \" << typeid( OutputType ).name () );\n }\n return out;\n}\n\n#endif \/\/__MITK_DIFFUSIONIMAGE_SOURCE_CPP__\n<|endoftext|>"} {"text":"\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \"Magnum\/Context.h\"\n#include \"Magnum\/Extensions.h\"\n#include \"Magnum\/Test\/AbstractOpenGLTester.h\"\n\nnamespace Magnum { namespace Test {\n\nstruct ContextGLTest: AbstractOpenGLTester {\n explicit ContextGLTest();\n\n void constructCopyMove();\n\n void isVersionSupported();\n void supportedVersion();\n void isExtensionSupported();\n void isExtensionDisabled();\n};\n\nContextGLTest::ContextGLTest() {\n addTests({&ContextGLTest::constructCopyMove,\n\n &ContextGLTest::isVersionSupported,\n &ContextGLTest::supportedVersion,\n &ContextGLTest::isExtensionSupported,\n &ContextGLTest::isExtensionDisabled});\n}\n\nvoid ContextGLTest::constructCopyMove() {\n \/* Only move-construction allowed *\/\n CORRADE_VERIFY(!(std::is_constructible{}));\n CORRADE_VERIFY((std::is_constructible{}));\n CORRADE_VERIFY(!(std::is_assignable{}));\n CORRADE_VERIFY(!(std::is_assignable{}));\n}\n\nvoid ContextGLTest::isVersionSupported() {\n const Version v = Context::current()->version();\n CORRADE_VERIFY(Context::current()->isVersionSupported(v));\n CORRADE_VERIFY(Context::current()->isVersionSupported(Version(Int(v)-1)));\n CORRADE_VERIFY(!Context::current()->isVersionSupported(Version(Int(v)+1)));\n\n \/* No assertions should be fired *\/\n MAGNUM_ASSERT_VERSION_SUPPORTED(v);\n MAGNUM_ASSERT_VERSION_SUPPORTED(Version(Int(v)-1));\n}\n\nvoid ContextGLTest::supportedVersion() {\n const Version v = Context::current()->version();\n\n \/* Selects first supported version (thus not necessarily the highest) *\/\n CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), v, Version(Int(v)-1)}) == v);\n CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), Version(Int(v)-1), v}) == Version(Int(v)-1));\n}\n\nvoid ContextGLTest::isExtensionSupported() {\n #ifndef MAGNUM_TARGET_GLES\n if(Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::GREMEDY::string_marker::string() + std::string(\" extension should not be supported, can't test\"));\n\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::EXT::texture_filter_anisotropic::string() + std::string(\" extension should be supported, can't test\"));\n\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(\" extension should be supported, can't test\"));\n\n \/* Test that we have proper extension list parser *\/\n std::string extensions(reinterpret_cast(glGetString(GL_EXTENSIONS)));\n CORRADE_VERIFY(extensions.find(Extensions::GL::EXT::texture_filter_anisotropic::string()) != std::string::npos);\n CORRADE_VERIFY(extensions.find(Extensions::GL::GREMEDY::string_marker::string()) == std::string::npos);\n\n \/* This is disabled in GL < 3.2 to work around GLSL compiler bugs *\/\n CORRADE_VERIFY(!Context::current()->isExtensionSupported(Version::GL310));\n CORRADE_VERIFY(Context::current()->isExtensionSupported(Version::GL320));\n #else\n CORRADE_SKIP(\"No useful extensions to test on OpenGL ES\");\n #endif\n}\n\nvoid ContextGLTest::isExtensionDisabled() {\n #ifndef MAGNUM_TARGET_GLES\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::ARB::vertex_array_object::string() + std::string(\" extension should be supported, can't test\"));\n\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(\" extension should be supported, can't test\"));\n\n \/* This is not disabled anywhere *\/\n CORRADE_VERIFY(!Context::current()->isExtensionDisabled());\n\n \/* This is disabled in GL < 3.2 to work around GLSL compiler bugs *\/\n CORRADE_VERIFY(Context::current()->isExtensionDisabled(Version::GL310));\n CORRADE_VERIFY(!Context::current()->isExtensionDisabled(Version::GL320));\n #else\n CORRADE_SKIP(\"No useful extensions to test on OpenGL ES\");\n #endif\n}\n\n}}\n\nMAGNUM_GL_TEST_MAIN(Magnum::Test::ContextGLTest)\nDon't use raw GL calls (that are even deprecated) in tests.\/*\n This file is part of Magnum.\n\n Copyright © 2010, 2011, 2012, 2013, 2014, 2015\n Vladimír Vondruš \n\n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n*\/\n\n#include \n\n#include \"Magnum\/Context.h\"\n#include \"Magnum\/Extensions.h\"\n#include \"Magnum\/Test\/AbstractOpenGLTester.h\"\n\nnamespace Magnum { namespace Test {\n\nstruct ContextGLTest: AbstractOpenGLTester {\n explicit ContextGLTest();\n\n void constructCopyMove();\n\n void isVersionSupported();\n void supportedVersion();\n void isExtensionSupported();\n void isExtensionDisabled();\n};\n\nContextGLTest::ContextGLTest() {\n addTests({&ContextGLTest::constructCopyMove,\n\n &ContextGLTest::isVersionSupported,\n &ContextGLTest::supportedVersion,\n &ContextGLTest::isExtensionSupported,\n &ContextGLTest::isExtensionDisabled});\n}\n\nvoid ContextGLTest::constructCopyMove() {\n \/* Only move-construction allowed *\/\n CORRADE_VERIFY(!(std::is_constructible{}));\n CORRADE_VERIFY((std::is_constructible{}));\n CORRADE_VERIFY(!(std::is_assignable{}));\n CORRADE_VERIFY(!(std::is_assignable{}));\n}\n\nvoid ContextGLTest::isVersionSupported() {\n const Version v = Context::current()->version();\n CORRADE_VERIFY(Context::current()->isVersionSupported(v));\n CORRADE_VERIFY(Context::current()->isVersionSupported(Version(Int(v)-1)));\n CORRADE_VERIFY(!Context::current()->isVersionSupported(Version(Int(v)+1)));\n\n \/* No assertions should be fired *\/\n MAGNUM_ASSERT_VERSION_SUPPORTED(v);\n MAGNUM_ASSERT_VERSION_SUPPORTED(Version(Int(v)-1));\n}\n\nvoid ContextGLTest::supportedVersion() {\n const Version v = Context::current()->version();\n\n \/* Selects first supported version (thus not necessarily the highest) *\/\n CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), v, Version(Int(v)-1)}) == v);\n CORRADE_VERIFY(Context::current()->supportedVersion({Version(Int(v)+1), Version(Int(v)-1), v}) == Version(Int(v)-1));\n}\n\nvoid ContextGLTest::isExtensionSupported() {\n #ifndef MAGNUM_TARGET_GLES\n if(Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::GREMEDY::string_marker::string() + std::string(\" extension should not be supported, can't test\"));\n\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::EXT::texture_filter_anisotropic::string() + std::string(\" extension should be supported, can't test\"));\n\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(\" extension should be supported, can't test\"));\n\n \/* Test that we have proper extension list parser *\/\n std::vector extensions = Context::current()->extensionStrings();\n CORRADE_VERIFY(std::find(extensions.begin(), extensions.end(),\n Extensions::GL::EXT::texture_filter_anisotropic::string()) != extensions.end());\n CORRADE_VERIFY(std::find(extensions.begin(), extensions.end(),\n Extensions::GL::GREMEDY::string_marker::string()) == extensions.end());\n\n \/* This is disabled in GL < 3.2 to work around GLSL compiler bugs *\/\n CORRADE_VERIFY(!Context::current()->isExtensionSupported(Version::GL310));\n CORRADE_VERIFY(Context::current()->isExtensionSupported(Version::GL320));\n #else\n CORRADE_SKIP(\"No useful extensions to test on OpenGL ES\");\n #endif\n}\n\nvoid ContextGLTest::isExtensionDisabled() {\n #ifndef MAGNUM_TARGET_GLES\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::ARB::vertex_array_object::string() + std::string(\" extension should be supported, can't test\"));\n\n if(!Context::current()->isExtensionSupported())\n CORRADE_SKIP(Extensions::GL::ARB::explicit_attrib_location::string() + std::string(\" extension should be supported, can't test\"));\n\n \/* This is not disabled anywhere *\/\n CORRADE_VERIFY(!Context::current()->isExtensionDisabled());\n\n \/* This is disabled in GL < 3.2 to work around GLSL compiler bugs *\/\n CORRADE_VERIFY(Context::current()->isExtensionDisabled(Version::GL310));\n CORRADE_VERIFY(!Context::current()->isExtensionDisabled(Version::GL320));\n #else\n CORRADE_SKIP(\"No useful extensions to test on OpenGL ES\");\n #endif\n}\n\n}}\n\nMAGNUM_GL_TEST_MAIN(Magnum::Test::ContextGLTest)\n<|endoftext|>"} {"text":"Planning: some minor bug fixes.<|endoftext|>"} {"text":"\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include \n\nnamespace ox::ptrarith {\n\ntemplate\nclass Ptr {\n\n\tprivate:\n\t\tuint8_t *m_dataStart = nullptr;\n\t\tsize_t m_itemOffset = 0;\n\t\tsize_t m_itemSize = 0;\n\t\t\/\/ this should be removed later on, but the excessive validation is\n\t\t\/\/ desirable during during heavy development\n\t\tmutable uint8_t m_validated = false;\n\n\tpublic:\n\t\tinline Ptr() = default;\n\n\t\tinline Ptr(std::nullptr_t);\n\n\t\tinline Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize = sizeof(T));\n\n\t\tinline bool valid() const;\n\n\t\tinline size_t size() const;\n\n\t\tinline size_t offset() const;\n\n\t\tinline size_t end();\n\n\t\tinline const T *get() const;\n\n\t\tinline T *get();\n\n\t\tinline const T *operator->() const;\n\n\t\tinline T *operator->();\n\n\t\tinline operator const T*() const;\n\n\t\tinline operator T*();\n\n\t\tinline const T &operator*() const;\n\n\t\tinline T &operator*();\n\n\t\tinline operator size_t() const;\n\n\t\tinline bool operator==(const Ptr &other) const;\n\n\t\tinline bool operator!=(const Ptr &other) const;\n\n\t\ttemplate\n\t\tinline const Ptr subPtr(size_t offset, size_t size) const;\n\n\t\ttemplate\n\t\tinline const Ptr subPtr(size_t offset) const;\n\n\t\ttemplate\n\t\tinline Ptr subPtr(size_t offset, size_t size);\n\n\t\ttemplate\n\t\tinline Ptr subPtr(size_t offset);\n\n};\n\ntemplate\ninline Ptr::Ptr(std::nullptr_t) {\n}\n\ntemplate\ninline Ptr::Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize) {\n\t\/\/ do some sanity checks before assuming this is valid\n\tif (itemSize >= sizeof(T) and\n\t dataStart and\n\t itemStart >= minOffset and\n\t itemStart + itemSize <= dataSize) {\n\t\tm_dataStart = reinterpret_cast(dataStart);\n\t\tm_itemOffset = itemStart;\n\t\tm_itemSize = itemSize;\n\t}\n}\n\ntemplate\ninline bool Ptr::valid() const {\n\tm_validated = m_dataStart != nullptr;\n\treturn m_validated;\n}\n\ntemplate\ninline size_t Ptr::size() const {\n\treturn m_itemSize;\n}\n\ntemplate\ninline size_t Ptr::offset() const {\n\treturn m_itemOffset;\n}\n\ntemplate\ninline size_t Ptr::end() {\n\treturn m_itemOffset + m_itemSize;\n}\n\ntemplate\ninline const T *Ptr::get() const {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::get())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::get())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline T *Ptr::get() {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::get())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::get())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline const T *Ptr::operator->() const {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::operator->())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::operator->())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline T *Ptr::operator->() {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::operator->())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::operator->())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline Ptr::operator const T*() const {\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline Ptr::operator T*() {\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline const T &Ptr::operator*() const {\n\toxAssert(m_validated, \"Unvalidated pointer dereference. (ox::fs::Ptr::operator*())\");\n\toxAssert(valid(), \"Invalid pointer dereference. (ox::fs::Ptr::operator*())\");\n\treturn *reinterpret_cast(this);\n}\n\ntemplate\ninline T &Ptr::operator*() {\n\toxAssert(m_validated, \"Unvalidated pointer dereference. (ox::fs::Ptr::operator*())\");\n\toxAssert(valid(), \"Invalid pointer dereference. (ox::fs::Ptr::operator*())\");\n\treturn *reinterpret_cast(this);\n}\n\ntemplate\ninline Ptr::operator size_t() const {\n\tif (m_dataStart and m_itemOffset) {\n\t\treturn m_itemOffset;\n\t}\n\treturn 0;\n}\n\ntemplate\ninline bool Ptr::operator==(const Ptr &other) const {\n\treturn m_dataStart == other.m_dataStart &&\n\t m_itemOffset == other.m_itemOffset &&\n\t m_itemSize == other.m_itemSize;\n}\n\ntemplate\ninline bool Ptr::operator!=(const Ptr &other) const {\n\treturn m_dataStart != other.m_dataStart ||\n\t m_itemOffset != other.m_itemOffset ||\n\t m_itemSize != other.m_itemSize;\n}\n\ntemplate\ntemplate\ninline const Ptr Ptr::subPtr(size_t offset, size_t size) const {\n\tauto out = Ptr(get(), this->size(), offset, size);\n\treturn out;\n}\n\ntemplate\ntemplate\ninline const Ptr Ptr::subPtr(size_t offset) const {\n\toxTrace(\"ox::fs::Ptr::subPtr\") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);\n\treturn subPtr(offset, m_itemSize - offset);\n}\n\ntemplate\ntemplate\ninline Ptr Ptr::subPtr(size_t offset, size_t size) {\n\tauto out = Ptr(get(), this->size(), offset, size);\n\treturn out;\n}\n\ntemplate\ntemplate\ninline Ptr Ptr::subPtr(size_t offset) {\n\toxTrace(\"ox::fs::Ptr::subPtr\") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);\n\treturn subPtr(offset, m_itemSize - offset);\n}\n\n}\n[ox\/buffer] Add to to Ptr\/*\n * Copyright 2015 - 2018 gtalent2@gmail.com\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#pragma once\n\n#include \n\nnamespace ox::ptrarith {\n\ntemplate\nclass Ptr {\n\n\tprivate:\n\t\tuint8_t *m_dataStart = nullptr;\n\t\tsize_t m_dataSize = 0;\n\t\tsize_t m_itemOffset = 0;\n\t\tsize_t m_itemSize = 0;\n\t\t\/\/ this should be removed later on, but the excessive validation is\n\t\t\/\/ desirable during during heavy development\n\t\tmutable uint8_t m_validated = false;\n\n\tpublic:\n\t\tinline Ptr() = default;\n\n\t\tinline Ptr(std::nullptr_t);\n\n\t\tinline Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize = sizeof(T));\n\n\t\tinline bool valid() const;\n\n\t\tinline size_t size() const;\n\n\t\tinline size_t offset() const;\n\n\t\tinline size_t end();\n\n\t\tinline const T *get() const;\n\n\t\tinline T *get();\n\n\t\tinline const T *operator->() const;\n\n\t\tinline T *operator->();\n\n\t\tinline operator const T*() const;\n\n\t\tinline operator T*();\n\n\t\tinline const T &operator*() const;\n\n\t\tinline T &operator*();\n\n\t\tinline operator size_t() const;\n\n\t\tinline bool operator==(const Ptr &other) const;\n\n\t\tinline bool operator!=(const Ptr &other) const;\n\n\t\ttemplate\n\t\tinline const Ptr subPtr(size_t offset, size_t size) const;\n\n\t\ttemplate\n\t\tinline const Ptr subPtr(size_t offset) const;\n\n\t\ttemplate\n\t\tinline Ptr subPtr(size_t offset, size_t size);\n\n\t\ttemplate\n\t\tinline Ptr subPtr(size_t offset);\n\n\t\ttemplate\n\t\tinline const Ptr to() const;\n\n};\n\ntemplate\ninline Ptr::Ptr(std::nullptr_t) {\n}\n\ntemplate\ninline Ptr::Ptr(void *dataStart, size_t dataSize, size_t itemStart, size_t itemSize) {\n\t\/\/ do some sanity checks before assuming this is valid\n\tif (itemSize >= sizeof(T) and\n\t dataStart and\n\t itemStart >= minOffset and\n\t itemStart + itemSize <= dataSize) {\n\t\tm_dataStart = reinterpret_cast(dataStart);\n\t\tm_dataSize = dataSize;\n\t\tm_itemOffset = itemStart;\n\t\tm_itemSize = itemSize;\n\t}\n}\n\ntemplate\ninline bool Ptr::valid() const {\n\tm_validated = m_dataStart != nullptr;\n\treturn m_validated;\n}\n\ntemplate\ninline size_t Ptr::size() const {\n\treturn m_itemSize;\n}\n\ntemplate\ninline size_t Ptr::offset() const {\n\treturn m_itemOffset;\n}\n\ntemplate\ninline size_t Ptr::end() {\n\treturn m_itemOffset + m_itemSize;\n}\n\ntemplate\ninline const T *Ptr::get() const {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::get())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::get())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline T *Ptr::get() {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::get())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::get())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline const T *Ptr::operator->() const {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::operator->())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::operator->())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline T *Ptr::operator->() {\n\toxAssert(m_validated, \"Unvalidated pointer access. (ox::fs::Ptr::operator->())\");\n\toxAssert(valid(), \"Invalid pointer access. (ox::fs::Ptr::operator->())\");\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline Ptr::operator const T*() const {\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline Ptr::operator T*() {\n\treturn reinterpret_cast(m_dataStart + m_itemOffset);\n}\n\ntemplate\ninline const T &Ptr::operator*() const {\n\toxAssert(m_validated, \"Unvalidated pointer dereference. (ox::fs::Ptr::operator*())\");\n\toxAssert(valid(), \"Invalid pointer dereference. (ox::fs::Ptr::operator*())\");\n\treturn *reinterpret_cast(this);\n}\n\ntemplate\ninline T &Ptr::operator*() {\n\toxAssert(m_validated, \"Unvalidated pointer dereference. (ox::fs::Ptr::operator*())\");\n\toxAssert(valid(), \"Invalid pointer dereference. (ox::fs::Ptr::operator*())\");\n\treturn *reinterpret_cast(this);\n}\n\ntemplate\ninline Ptr::operator size_t() const {\n\tif (m_dataStart and m_itemOffset) {\n\t\treturn m_itemOffset;\n\t}\n\treturn 0;\n}\n\ntemplate\ninline bool Ptr::operator==(const Ptr &other) const {\n\treturn m_dataStart == other.m_dataStart &&\n\t m_itemOffset == other.m_itemOffset &&\n\t m_itemSize == other.m_itemSize;\n}\n\ntemplate\ninline bool Ptr::operator!=(const Ptr &other) const {\n\treturn m_dataStart != other.m_dataStart ||\n\t m_itemOffset != other.m_itemOffset ||\n\t m_itemSize != other.m_itemSize;\n}\n\ntemplate\ntemplate\ninline const Ptr Ptr::subPtr(size_t offset, size_t size) const {\n\treturn Ptr(get(), this->size(), offset, size);\n}\n\ntemplate\ntemplate\ninline const Ptr Ptr::subPtr(size_t offset) const {\n\toxTrace(\"ox::fs::Ptr::subPtr\") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);\n\treturn subPtr(offset, m_itemSize - offset);\n}\n\ntemplate\ntemplate\ninline Ptr Ptr::subPtr(size_t offset, size_t size) {\n\treturn Ptr(get(), this->size(), offset, size);\n}\n\ntemplate\ntemplate\ninline Ptr Ptr::subPtr(size_t offset) {\n\toxTrace(\"ox::fs::Ptr::subPtr\") << m_itemOffset << this->size() << offset << m_itemSize << (m_itemSize - offset);\n\treturn subPtr(offset, m_itemSize - offset);\n}\n\ntemplate\ntemplate\ninline const Ptr Ptr::to() const {\n\treturn Ptr(m_dataStart, m_dataSize, m_itemOffset, m_itemSize);\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2018 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/fml\/file.h\"\n\n#include \n\n#include \n\n#include \"flutter\/fml\/platform\/win\/wstring_conversion.h\"\n\nnamespace fml {\n\nfml::UniqueFD OpenFile(const std::wstring& path,\n OpenPermission permission,\n bool is_directory) {\n if (path.size() == 0) {\n return fml::UniqueFD{};\n }\n\n DWORD desired_access = 0;\n\n switch (permission) {\n case OpenPermission::kRead:\n desired_access = GENERIC_READ;\n break;\n case OpenPermission::kWrite:\n desired_access = GENERIC_WRITE;\n break;\n case OpenPermission::kReadWrite:\n desired_access = GENERIC_WRITE | GENERIC_READ;\n break;\n case OpenPermission::kExecute:\n desired_access = GENERIC_READ | GENERIC_EXECUTE;\n break;\n }\n\n return fml::UniqueFD{::CreateFile(\n path.c_str(), \/\/ lpFileName\n desired_access, \/\/ dwDesiredAccess\n FILE_SHARE_READ, \/\/ dwShareMode\n 0, \/\/ lpSecurityAttributes\n OPEN_EXISTING, \/\/ dwCreationDisposition\n FILE_ATTRIBUTE_NORMAL, \/\/ dwFlagsAndAttributes\n 0 \/\/ hTemplateFile\n )};\n}\n\nfml::UniqueFD OpenFile(const char* path,\n OpenPermission permission,\n bool is_directory) {\n return OpenFile(ConvertToWString(path), permission, is_directory);\n}\n\nstatic std::wstring GetFullHandlePath(const fml::UniqueFD& handle) {\n wchar_t buffer[MAX_PATH];\n\n DWORD returned = ::GetFinalPathNameByHandle(handle.get(), buffer, MAX_PATH,\n FILE_NAME_NORMALIZED);\n if (returned == 0 || returned > MAX_PATH) {\n return {};\n }\n\n return {buffer};\n}\n\nfml::UniqueFD OpenFile(const fml::UniqueFD& base_directory,\n const char* path,\n OpenPermission permission,\n bool is_directory) {\n \/\/ If the base directory is invalid or the path is absolute, use the generic\n \/\/ open file variant.\n if (!base_directory.is_valid()) {\n return OpenFile(path, permission, is_directory);\n }\n\n const auto wpath = ConvertToWString(path);\n\n if (!::PathIsRelative(wpath.c_str())) {\n return OpenFile(path, permission, is_directory);\n }\n\n std::wstringstream stream;\n stream << GetFullHandlePath(base_directory) << \"\\\\\" << path;\n return OpenFile(stream.str(), permission, is_directory);\n}\n\nfml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor) {\n if (descriptor == INVALID_HANDLE_VALUE) {\n return fml::UniqueFD{};\n }\n\n HANDLE duplicated = INVALID_HANDLE_VALUE;\n\n if (!::DuplicateHandle(\n GetCurrentProcess(), \/\/ source process\n descriptor, \/\/ source handle\n GetCurrentProcess(), \/\/ target process\n &duplicated, \/\/ target handle\n 0, \/\/ desired access (ignored because DUPLICATE_SAME_ACCESS)\n FALSE, \/\/ inheritable\n DUPLICATE_SAME_ACCESS) \/\/ options\n ) {\n return fml::UniqueFD{};\n }\n\n return fml::UniqueFD{duplicated};\n}\n\nbool IsDirectory(const fml::UniqueFD& directory) {\n BY_HANDLE_FILE_INFORMATION info;\n if (!::GetFileInformationByHandle(directory.get(), &info)) {\n return false;\n }\n return info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;\n}\n\n} \/\/ namespace fml\nFix file flags for directories and backslashes on Windows. (#5387)\/\/ Copyright 2018 The Flutter Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"flutter\/fml\/file.h\"\n\n#include \n\n#include \n#include \n\n#include \"flutter\/fml\/platform\/win\/wstring_conversion.h\"\n\nnamespace fml {\n\nstatic fml::UniqueFD OpenFile(std::wstring path,\n OpenPermission permission,\n bool is_directory) {\n if (path.size() == 0) {\n return fml::UniqueFD{};\n }\n\n DWORD desired_access = 0;\n\n switch (permission) {\n case OpenPermission::kRead:\n desired_access = GENERIC_READ;\n break;\n case OpenPermission::kWrite:\n desired_access = GENERIC_WRITE;\n break;\n case OpenPermission::kReadWrite:\n desired_access = GENERIC_WRITE | GENERIC_READ;\n break;\n case OpenPermission::kExecute:\n desired_access = GENERIC_READ | GENERIC_EXECUTE;\n break;\n }\n\n DWORD flags = FILE_ATTRIBUTE_NORMAL;\n\n if (is_directory) {\n flags |= FILE_FLAG_BACKUP_SEMANTICS;\n }\n\n std::replace(path.begin(), path.end(), '\/', '\\\\');\n\n return fml::UniqueFD{::CreateFile(path.c_str(), \/\/ lpFileName\n desired_access, \/\/ dwDesiredAccess\n FILE_SHARE_READ, \/\/ dwShareMode\n 0, \/\/ lpSecurityAttributes\n OPEN_EXISTING, \/\/ dwCreationDisposition\n flags, \/\/ dwFlagsAndAttributes\n 0 \/\/ hTemplateFile\n )};\n}\n\nfml::UniqueFD OpenFile(const char* path,\n OpenPermission permission,\n bool is_directory) {\n return OpenFile(ConvertToWString(path), permission, is_directory);\n}\n\nstatic std::wstring GetFullHandlePath(const fml::UniqueFD& handle) {\n wchar_t buffer[MAX_PATH];\n\n DWORD returned = ::GetFinalPathNameByHandle(handle.get(), buffer, MAX_PATH,\n FILE_NAME_NORMALIZED);\n if (returned == 0 || returned > MAX_PATH) {\n return {};\n }\n\n return {buffer};\n}\n\nfml::UniqueFD OpenFile(const fml::UniqueFD& base_directory,\n const char* path,\n OpenPermission permission,\n bool is_directory) {\n \/\/ If the base directory is invalid or the path is absolute, use the generic\n \/\/ open file variant.\n if (!base_directory.is_valid()) {\n return OpenFile(path, permission, is_directory);\n }\n\n const auto wpath = ConvertToWString(path);\n\n if (!::PathIsRelative(wpath.c_str())) {\n return OpenFile(path, permission, is_directory);\n }\n\n std::wstringstream stream;\n stream << GetFullHandlePath(base_directory) << \"\\\\\" << path;\n return OpenFile(stream.str(), permission, is_directory);\n}\n\nfml::UniqueFD Duplicate(fml::UniqueFD::element_type descriptor) {\n if (descriptor == INVALID_HANDLE_VALUE) {\n return fml::UniqueFD{};\n }\n\n HANDLE duplicated = INVALID_HANDLE_VALUE;\n\n if (!::DuplicateHandle(\n GetCurrentProcess(), \/\/ source process\n descriptor, \/\/ source handle\n GetCurrentProcess(), \/\/ target process\n &duplicated, \/\/ target handle\n 0, \/\/ desired access (ignored because DUPLICATE_SAME_ACCESS)\n FALSE, \/\/ inheritable\n DUPLICATE_SAME_ACCESS) \/\/ options\n ) {\n return fml::UniqueFD{};\n }\n\n return fml::UniqueFD{duplicated};\n}\n\nbool IsDirectory(const fml::UniqueFD& directory) {\n BY_HANDLE_FILE_INFORMATION info;\n if (!::GetFileInformationByHandle(directory.get(), &info)) {\n return false;\n }\n return info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY;\n}\n\n} \/\/ namespace fml\n<|endoftext|>"} {"text":"\/\/\n\/\/\n\/\/ Description: This file is part of FET\n\/\/\n\/\/\n\/\/ Author: Lalescu Liviu \n\/\/ Copyright (C) 2005 Liviu Lalescu \n\/\/\n\/***************************************************************************\n * *\n * This program is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"timetable_defs.h\"\n#include \"timetable.h\"\n#include \"fet.h\"\n#include \"activitytagsform.h\"\n#include \"studentsset.h\"\n#include \"teacher.h\"\n#include \"subject.h\"\n#include \"activitytag.h\"\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nextern const QString COMPANY;\nextern const QString PROGRAM;\n\nActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)\n{\n\tsetupUi(this);\n\t\n\tcurrentActivityTagTextEdit->setReadOnly(true);\n\n\trenameActivityTagPushButton->setDefault(true);\n\n\tactivityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\tconnect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));\n\tconnect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));\n\tconnect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));\n\tconnect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));\n\n\tconnect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));\n\tconnect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));\n\n\tconnect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));\n\tconnect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));\n\tconnect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));\n\tconnect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));\n\tconnect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));\n\tconnect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));\n\n\tconnect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));\n\tconnect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));\n\n\tconnect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));\n\n\tcenterWidgetOnScreen(this);\n\trestoreFETDialogGeometry(this);\n\t\/\/restore splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tif(settings.contains(this->metaObject()->className()+QString(\"\/splitter-state\")))\n\t\tsplitter->restoreState(settings.value(this->metaObject()->className()+QString(\"\/splitter-state\")).toByteArray());\n\t\t\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; iaddItem(sbt->name);\n\t}\n\t\t\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\n\nActivityTagsForm::~ActivityTagsForm()\n{\n\tsaveFETDialogGeometry(this);\n\t\/\/save splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tsettings.setValue(this->metaObject()->className()+QString(\"\/splitter-state\"), splitter->saveState());\n}\n\nvoid ActivityTagsForm::addActivityTag()\n{\n\tbool ok = false;\n\tActivityTag* sbt=new ActivityTag();\n\tsbt->name = QInputDialog::getText( this, tr(\"Add activity tag\"), tr(\"Please enter activity tag's name\") ,\n\t QLineEdit::Normal, QString(), &ok );\n\n\tif ( ok && !((sbt->name).isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(!gt.rules.addActivityTag(sbt)){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not insert item. Must be a duplicate\"));\n\t\t\tdelete sbt;\n\t\t}\n\t\telse{\n\t\t\tactivityTagsListWidget->addItem(sbt->name);\n\t\t\tactivityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);\n\t\t}\n\t}\n\telse{\n\t\tif(ok){ \/\/the user entered nothing\n\t\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Incorrect name\"));\n\t\t}\n\t\tdelete sbt;\/\/ user entered nothing or pressed Cancel\n\t}\n}\n\nvoid ActivityTagsForm::removeActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint activity_tag_ID=gt.rules.searchActivityTag(text);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tif(QMessageBox::warning( this, tr(\"FET\"),\n\t\ttr(\"Are you sure you want to delete this activity tag?\"),\n\t\ttr(\"Yes\"), tr(\"No\"), 0, 0, 1 ) == 1)\n\t\treturn;\n\n\tint tmp=gt.rules.removeActivityTag(text);\n\tif(tmp){\n\t\tactivityTagsListWidget->setCurrentRow(-1);\n\t\tQListWidgetItem* item;\n\t\titem=activityTagsListWidget->takeItem(i);\n\t\tdelete item;\n\t\t\n\t\tif(i>=activityTagsListWidget->count())\n\t\t\ti=activityTagsListWidget->count()-1;\n\t\tif(i>=0)\n\t\t\tactivityTagsListWidget->setCurrentRow(i);\n\t\telse\n\t\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t}\n}\n\nvoid ActivityTagsForm::renameActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tQString initialActivityTagName=activityTagsListWidget->currentItem()->text();\n\n\tint activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tbool ok = false;\n\tQString finalActivityTagName;\n\tfinalActivityTagName = QInputDialog::getText( this, tr(\"Rename activity tag\"), tr(\"Please enter new activity tag's name\") ,\n\t QLineEdit::Normal, initialActivityTagName, &ok );\n\n\tif ( ok && !(finalActivityTagName.isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(gt.rules.searchActivityTag(finalActivityTagName)>=0){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not modify item. New name must be a duplicate\"));\n\t\t}\n\t\telse{\n\t\t\tgt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);\n\t\t\tactivityTagsListWidget->item(i)->setText(finalActivityTagName);\n\t\t\tactivityTagChanged(activityTagsListWidget->currentRow());\n\t\t}\n\t}\n}\n\nvoid ActivityTagsForm::moveActivityTagUp()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==0)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i-1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i-1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i-1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i-1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i-1);\n\tactivityTagChanged(i-1);\n}\n\nvoid ActivityTagsForm::moveActivityTagDown()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==activityTagsListWidget->count()-1)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i+1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i+1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i+1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i+1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i+1);\n\tactivityTagChanged(i+1);\n}\n\nvoid ActivityTagsForm::sortActivityTags()\n{\n\tgt.rules.sortActivityTagsAlphabetically();\n\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; iaddItem(sbt->name);\n\t}\n\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\nvoid ActivityTagsForm::activityTagChanged(int index)\n{\n\tif(index<0){\n\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* st=gt.rules.activityTagsList.at(index);\n\tassert(st);\n\tQString s=st->getDetailedDescriptionWithConstraints(gt.rules);\n\tcurrentActivityTagTextEdit->setPlainText(s);\n}\n\nvoid ActivityTagsForm::activateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.activateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::deactivateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.deactivateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"De-activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::printableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::notPrintableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagNotPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::help()\n{\n\tQMessageBox::information(this, tr(\"FET help on activity tags\"), \n\t tr(\"Activity tag is a field which can be used or not, depending on your wish (optional field).\"\n\t \" It is designed to help you with some constraints. Each activity has a possible empty list of activity tags\"\n\t \" (if you don't use activity tags, the list will be empty)\"));\n}\n\nvoid ActivityTagsForm::comments()\n{\n\tint ind=activityTagsListWidget->currentRow();\n\tif(ind<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* at=gt.rules.activityTagsList[ind];\n\tassert(at!=NULL);\n\n\tQDialog getCommentsDialog(this);\n\t\n\tgetCommentsDialog.setWindowTitle(tr(\"Activity tag comments\"));\n\t\n\tQPushButton* okPB=new QPushButton(tr(\"OK\"));\n\tokPB->setDefault(true);\n\tQPushButton* cancelPB=new QPushButton(tr(\"Cancel\"));\n\t\n\tconnect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));\n\tconnect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));\n\n\tQHBoxLayout* hl=new QHBoxLayout();\n\thl->addStretch();\n\thl->addWidget(okPB);\n\thl->addWidget(cancelPB);\n\t\n\tQVBoxLayout* vl=new QVBoxLayout();\n\t\n\tQPlainTextEdit* commentsPT=new QPlainTextEdit();\n\tcommentsPT->setPlainText(at->comments);\n\tcommentsPT->selectAll();\n\tcommentsPT->setFocus();\n\t\n\tvl->addWidget(commentsPT);\n\tvl->addLayout(hl);\n\t\n\tgetCommentsDialog.setLayout(vl);\n\t\n\tconst QString settingsName=QString(\"ActivityTagCommentsDialog\");\n\t\n\tgetCommentsDialog.resize(500, 320);\n\tcenterWidgetOnScreen(&getCommentsDialog);\n\trestoreFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tint t=getCommentsDialog.exec();\n\tsaveFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tif(t==QDialog::Accepted){\n\t\tat->comments=commentsPT->toPlainText();\n\t\n\t\tgt.rules.internalStructureComputed=false;\n\t\tsetRulesModifiedAndOtherThings(>.rules);\n\n\t\tactivityTagChanged(ind);\n\t}\n}\n\nremove empty line\/\/\n\/\/\n\/\/ Description: This file is part of FET\n\/\/\n\/\/\n\/\/ Author: Lalescu Liviu \n\/\/ Copyright (C) 2005 Liviu Lalescu \n\/\/\n\/***************************************************************************\n * *\n * This program is free software: you can redistribute it and\/or modify *\n * it under the terms of the GNU Affero General Public License as *\n * published by the Free Software Foundation, either version 3 of the *\n * License, or (at your option) any later version. *\n * *\n ***************************************************************************\/\n\n#include \"timetable_defs.h\"\n#include \"timetable.h\"\n#include \"fet.h\"\n#include \"activitytagsform.h\"\n#include \"studentsset.h\"\n#include \"teacher.h\"\n#include \"subject.h\"\n#include \"activitytag.h\"\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nextern const QString COMPANY;\nextern const QString PROGRAM;\n\nActivityTagsForm::ActivityTagsForm(QWidget* parent): QDialog(parent)\n{\n\tsetupUi(this);\n\t\n\tcurrentActivityTagTextEdit->setReadOnly(true);\n\n\trenameActivityTagPushButton->setDefault(true);\n\n\tactivityTagsListWidget->setSelectionMode(QAbstractItemView::SingleSelection);\n\n\tconnect(closePushButton, SIGNAL(clicked()), this, SLOT(close()));\n\tconnect(addActivityTagPushButton, SIGNAL(clicked()), this, SLOT(addActivityTag()));\n\tconnect(removeActivityTagPushButton, SIGNAL(clicked()), this, SLOT(removeActivityTag()));\n\tconnect(renameActivityTagPushButton, SIGNAL(clicked()), this, SLOT(renameActivityTag()));\n\n\tconnect(moveActivityTagUpPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagUp()));\n\tconnect(moveActivityTagDownPushButton, SIGNAL(clicked()), this, SLOT(moveActivityTagDown()));\n\n\tconnect(sortActivityTagsPushButton, SIGNAL(clicked()), this, SLOT(sortActivityTags()));\n\tconnect(activityTagsListWidget, SIGNAL(currentRowChanged(int)), this, SLOT(activityTagChanged(int)));\n\tconnect(activateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(activateActivityTag()));\n\tconnect(deactivateActivityTagPushButton, SIGNAL(clicked()), this, SLOT(deactivateActivityTag()));\n\tconnect(activityTagsListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(renameActivityTag()));\n\tconnect(helpPushButton, SIGNAL(clicked()), this, SLOT(help()));\n\n\tconnect(printablePushButton, SIGNAL(clicked()), this, SLOT(printableActivityTag()));\n\tconnect(notPrintablePushButton, SIGNAL(clicked()), this, SLOT(notPrintableActivityTag()));\n\n\tconnect(commentsPushButton, SIGNAL(clicked()), this, SLOT(comments()));\n\n\tcenterWidgetOnScreen(this);\n\trestoreFETDialogGeometry(this);\n\t\/\/restore splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tif(settings.contains(this->metaObject()->className()+QString(\"\/splitter-state\")))\n\t\tsplitter->restoreState(settings.value(this->metaObject()->className()+QString(\"\/splitter-state\")).toByteArray());\n\t\t\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; iaddItem(sbt->name);\n\t}\n\t\t\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\n\nActivityTagsForm::~ActivityTagsForm()\n{\n\tsaveFETDialogGeometry(this);\n\t\/\/save splitter state\n\tQSettings settings(COMPANY, PROGRAM);\n\tsettings.setValue(this->metaObject()->className()+QString(\"\/splitter-state\"), splitter->saveState());\n}\n\nvoid ActivityTagsForm::addActivityTag()\n{\n\tbool ok = false;\n\tActivityTag* sbt=new ActivityTag();\n\tsbt->name = QInputDialog::getText( this, tr(\"Add activity tag\"), tr(\"Please enter activity tag's name\") ,\n\t QLineEdit::Normal, QString(), &ok );\n\n\tif ( ok && !((sbt->name).isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(!gt.rules.addActivityTag(sbt)){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not insert item. Must be a duplicate\"));\n\t\t\tdelete sbt;\n\t\t}\n\t\telse{\n\t\t\tactivityTagsListWidget->addItem(sbt->name);\n\t\t\tactivityTagsListWidget->setCurrentRow(activityTagsListWidget->count()-1);\n\t\t}\n\t}\n\telse{\n\t\tif(ok){ \/\/the user entered nothing\n\t\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Incorrect name\"));\n\t\t}\n\t\tdelete sbt;\/\/ user entered nothing or pressed Cancel\n\t}\n}\n\nvoid ActivityTagsForm::removeActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint activity_tag_ID=gt.rules.searchActivityTag(text);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tif(QMessageBox::warning( this, tr(\"FET\"),\n\t\ttr(\"Are you sure you want to delete this activity tag?\"),\n\t\ttr(\"Yes\"), tr(\"No\"), 0, 0, 1 ) == 1)\n\t\treturn;\n\n\tint tmp=gt.rules.removeActivityTag(text);\n\tif(tmp){\n\t\tactivityTagsListWidget->setCurrentRow(-1);\n\t\tQListWidgetItem* item;\n\t\titem=activityTagsListWidget->takeItem(i);\n\t\tdelete item;\n\t\t\n\t\tif(i>=activityTagsListWidget->count())\n\t\t\ti=activityTagsListWidget->count()-1;\n\t\tif(i>=0)\n\t\t\tactivityTagsListWidget->setCurrentRow(i);\n\t\telse\n\t\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t}\n}\n\nvoid ActivityTagsForm::renameActivityTag()\n{\n\tint i=activityTagsListWidget->currentRow();\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tQString initialActivityTagName=activityTagsListWidget->currentItem()->text();\n\n\tint activity_tag_ID=gt.rules.searchActivityTag(initialActivityTagName);\n\tif(activity_tag_ID<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tbool ok = false;\n\tQString finalActivityTagName;\n\tfinalActivityTagName = QInputDialog::getText( this, tr(\"Rename activity tag\"), tr(\"Please enter new activity tag's name\") ,\n\t QLineEdit::Normal, initialActivityTagName, &ok );\n\n\tif ( ok && !(finalActivityTagName.isEmpty()) ){\n\t\t\/\/ user entered something and pressed OK\n\t\tif(gt.rules.searchActivityTag(finalActivityTagName)>=0){\n\t\t\tQMessageBox::information( this, tr(\"Activity tag insertion dialog\"),\n\t\t\t\ttr(\"Could not modify item. New name must be a duplicate\"));\n\t\t}\n\t\telse{\n\t\t\tgt.rules.modifyActivityTag(initialActivityTagName, finalActivityTagName);\n\t\t\tactivityTagsListWidget->item(i)->setText(finalActivityTagName);\n\t\t\tactivityTagChanged(activityTagsListWidget->currentRow());\n\t\t}\n\t}\n}\n\nvoid ActivityTagsForm::moveActivityTagUp()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==0)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i-1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i-1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i-1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i-1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i-1);\n\tactivityTagChanged(i-1);\n}\n\nvoid ActivityTagsForm::moveActivityTagDown()\n{\n\tif(activityTagsListWidget->count()<=1)\n\t\treturn;\n\tint i=activityTagsListWidget->currentRow();\n\tif(i<0 || i>=activityTagsListWidget->count())\n\t\treturn;\n\tif(i==activityTagsListWidget->count()-1)\n\t\treturn;\n\t\t\n\tQString s1=activityTagsListWidget->item(i)->text();\n\tQString s2=activityTagsListWidget->item(i+1)->text();\n\t\n\tActivityTag* at1=gt.rules.activityTagsList.at(i);\n\tActivityTag* at2=gt.rules.activityTagsList.at(i+1);\n\t\n\tgt.rules.internalStructureComputed=false;\n\tsetRulesModifiedAndOtherThings(>.rules);\n\t\n\tactivityTagsListWidget->item(i)->setText(s2);\n\tactivityTagsListWidget->item(i+1)->setText(s1);\n\t\n\tgt.rules.activityTagsList[i]=at2;\n\tgt.rules.activityTagsList[i+1]=at1;\n\t\n\tactivityTagsListWidget->setCurrentRow(i+1);\n\tactivityTagChanged(i+1);\n}\n\nvoid ActivityTagsForm::sortActivityTags()\n{\n\tgt.rules.sortActivityTagsAlphabetically();\n\n\tactivityTagsListWidget->clear();\n\tfor(int i=0; iaddItem(sbt->name);\n\t}\n\n\tif(activityTagsListWidget->count()>0)\n\t\tactivityTagsListWidget->setCurrentRow(0);\n}\n\nvoid ActivityTagsForm::activityTagChanged(int index)\n{\n\tif(index<0){\n\t\tcurrentActivityTagTextEdit->setPlainText(QString(\"\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* st=gt.rules.activityTagsList.at(index);\n\tassert(st);\n\tQString s=st->getDetailedDescriptionWithConstraints(gt.rules);\n\tcurrentActivityTagTextEdit->setPlainText(s);\n}\n\nvoid ActivityTagsForm::activateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.activateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::deactivateActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\tint count=gt.rules.deactivateActivityTag(text);\n\tQMessageBox::information(this, tr(\"FET information\"), tr(\"De-activated a number of %1 activities\").arg(count));\n}\n\nvoid ActivityTagsForm::printableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::notPrintableActivityTag()\n{\n\tif(activityTagsListWidget->currentRow()<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\n\tQString text=activityTagsListWidget->currentItem()->text();\n\t\n\tgt.rules.makeActivityTagNotPrintable(text);\n\n\tactivityTagChanged(activityTagsListWidget->currentRow());\n}\n\nvoid ActivityTagsForm::help()\n{\n\tQMessageBox::information(this, tr(\"FET help on activity tags\"), \n\t tr(\"Activity tag is a field which can be used or not, depending on your wish (optional field).\"\n\t \" It is designed to help you with some constraints. Each activity has a possible empty list of activity tags\"\n\t \" (if you don't use activity tags, the list will be empty)\"));\n}\n\nvoid ActivityTagsForm::comments()\n{\n\tint ind=activityTagsListWidget->currentRow();\n\tif(ind<0){\n\t\tQMessageBox::information(this, tr(\"FET information\"), tr(\"Invalid selected activity tag\"));\n\t\treturn;\n\t}\n\t\n\tActivityTag* at=gt.rules.activityTagsList[ind];\n\tassert(at!=NULL);\n\n\tQDialog getCommentsDialog(this);\n\t\n\tgetCommentsDialog.setWindowTitle(tr(\"Activity tag comments\"));\n\t\n\tQPushButton* okPB=new QPushButton(tr(\"OK\"));\n\tokPB->setDefault(true);\n\tQPushButton* cancelPB=new QPushButton(tr(\"Cancel\"));\n\t\n\tconnect(okPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(accept()));\n\tconnect(cancelPB, SIGNAL(clicked()), &getCommentsDialog, SLOT(reject()));\n\n\tQHBoxLayout* hl=new QHBoxLayout();\n\thl->addStretch();\n\thl->addWidget(okPB);\n\thl->addWidget(cancelPB);\n\t\n\tQVBoxLayout* vl=new QVBoxLayout();\n\t\n\tQPlainTextEdit* commentsPT=new QPlainTextEdit();\n\tcommentsPT->setPlainText(at->comments);\n\tcommentsPT->selectAll();\n\tcommentsPT->setFocus();\n\t\n\tvl->addWidget(commentsPT);\n\tvl->addLayout(hl);\n\t\n\tgetCommentsDialog.setLayout(vl);\n\t\n\tconst QString settingsName=QString(\"ActivityTagCommentsDialog\");\n\t\n\tgetCommentsDialog.resize(500, 320);\n\tcenterWidgetOnScreen(&getCommentsDialog);\n\trestoreFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tint t=getCommentsDialog.exec();\n\tsaveFETDialogGeometry(&getCommentsDialog, settingsName);\n\t\n\tif(t==QDialog::Accepted){\n\t\tat->comments=commentsPT->toPlainText();\n\t\n\t\tgt.rules.internalStructureComputed=false;\n\t\tsetRulesModifiedAndOtherThings(>.rules);\n\n\t\tactivityTagChanged(ind);\n\t}\n}\n<|endoftext|>"} {"text":"\/\/IBM_PROLOG_BEGIN_TAG\n\/\/IBM_PROLOG_END_TAG\n\n\n\/\/--------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef OTHER_USE\n#include \nextern OutputLite out;\n#else\n#include \n#endif\n\nstd::string InstructionTypeToString(Instruction::InstructionType i_type) {\n switch (i_type) {\n case Instruction::NOINSTRUCTION:\n return \"NOINSTRUCTION\";\n case Instruction::FSI:\n return \"FSI\";\n case Instruction::JTAG:\n return \"JTAG\";\n case Instruction::MULTIPLEJTAG:\n return \"MULTIPLEJTAG\";\n case Instruction::PSI:\n return \"PSI\";\n case Instruction::GPIO:\n return \"GPIO\";\n case Instruction::I2C:\n return \"I2C\";\n case Instruction::VPD:\n return \"VPD\";\n case Instruction::DMA:\n return \"DMA\";\n case Instruction::CONTROL:\n return \"CONTROL\";\n case Instruction::DMAEXER:\n return \"DMAEXER\";\n case Instruction::POWR:\n return \"POWR\";\n case Instruction::FSISTREAM:\n return \"FSISTREAM\";\n case Instruction::SBEFIFO:\n return \"SBEFIFO\";\n case Instruction::GSD2PIB:\n return \"GSD2PIB\";\n case Instruction::FSIMEMPROC:\n return \"FSIMEMPROC\";\n case Instruction::PNOR:\n return \"PNOR\";\n }\n return \"\";\n}\n\nstd::string InstructionCommandToString(Instruction::InstructionCommand i_command) {\n switch (i_command) {\n case Instruction::NOCOMMAND:\n return \"NOCOMMAND\";\n case Instruction::SENDCMD:\n return \"SENDCMD\";\n case Instruction::READ:\n return \"READ\";\n case Instruction::WRITE:\n return \"WRITE\";\n case Instruction::LONGIN:\n return \"LONGIN\";\n case Instruction::LONGOUT:\n return \"LONGOUT\";\n case Instruction::READ_WRITE:\n return \"READ_WRITE\";\n case Instruction::SHIFTOUT:\n return \"SHIFTOUT\";\n case Instruction::DMAIN:\n return \"DMAIN\";\n case Instruction::DMAOUT:\n return \"DMAOUT\";\n case Instruction::MISC:\n return \"MISC\";\n case Instruction::TOTAP:\n return \"TOTAP\";\n case Instruction::READVPD:\n return \"READVPD\";\n case Instruction::READSPMEM:\n return \"READSPMEM\";\n case Instruction::WRITESPMEM:\n return \"WRITESPMEM\";\n case Instruction::SCOMIN:\n return \"SCOMIN\";\n case Instruction::SCOMOUT:\n return \"SCOMOUT\";\n case Instruction::WRITEVPD:\n return \"WRITEVPD\";\n case Instruction::PSI_RESET:\n return \"PSI_RESET\";\n case Instruction::PSI_LINK_CALIB:\n return \"PSI_LINK_CALIB\";\n case Instruction::PSI_EI_REG_READ:\n return \"PSI_EI_REG_READ\";\n case Instruction::PSI_EI_REG_WRITE:\n return \"PSI_EI_REG_WRITE\";\n case Instruction::PSI_VERIFY:\n return \"PSI_VERIFY\";\n case Instruction::PSI_SCOM_READ:\n return \"PSI_SCOM_READ\";\n case Instruction::PSI_SCOM_WRITE:\n return \"PSI_SCOM_WRITE\";\n case Instruction::PSI_READ:\n return \"PSI_READ\";\n case Instruction::PSI_WRITE:\n return \"PSI_WRITE\";\n case Instruction::PSI_INIT:\n return \"PSI_INIT\";\n case Instruction::PSI_LINK_ENABLE:\n return \"PSI_LINK_ENABLE\";\n case Instruction::PSI_SET_SPEED:\n return \"PSI_SET_SPEED\";\n case Instruction::PSI_LINK_VERIFY:\n return \"PSI_LINK_VERIFY\";\n case Instruction::I2CWRITE:\n return \"I2CWRITE\";\n case Instruction::I2CREAD:\n return \"I2CREAD\";\n case Instruction::GPIO_CONFIGPIN:\n return \"GPIO_CONFIGPIN\";\n case Instruction::GPIO_READPIN:\n return \"GPIO_READPIN\";\n case Instruction::GPIO_READPINS:\n return \"GPIO_READPINS\";\n case Instruction::GPIO_READLATCH:\n return \"GPIO_READLATCH\";\n case Instruction::GPIO_WRITELATCH:\n return \"GPIO_WRITELATCH\";\n case Instruction::GPIO_WRITELATCHES:\n return \"GPIO_WRITELATCHES\";\n case Instruction::GPIO_READCONFIG:\n return \"GPIO_READCONFIG\";\n case Instruction::GPIO_WRITECONFIG:\n return \"GPIO_WRITECONFIG\";\n case Instruction::GPIO_WRITECNFGSET:\n return \"GPIO_WRITECNFGSET\";\n case Instruction::GPIO_WRITECNFGCLR:\n return \"GPIO_WRITECNFGCLR\";\n case Instruction::DMAEXER_START:\n return \"DMAEXER_START\";\n case Instruction::DMAEXER_REPORT:\n return \"DMAEXER_REPORT\";\n case Instruction::DMAEXER_STOP:\n return \"DMAEXER_STOP\";\n case Instruction::INFO:\n return \"INFO\";\n case Instruction::RUN_CMD:\n return \"RUN_CMD\";\n case Instruction::MULTI_ENABLE:\n return \"MULTI_ENABLE\";\n case Instruction::AUTH:\n return \"AUTH\";\n case Instruction::ADDAUTH:\n return \"ADDAUTH\";\n case Instruction::CLEARAUTH:\n return \"CLEARAUTH\";\n case Instruction::VERSION:\n return \"VERSION\";\n case Instruction::FLIGHTRECORDER:\n return \"FLIGHTRECORDER\";\n case Instruction::EXIT:\n return \"EXIT\";\n case Instruction::SCOMIN_MASK:\n return \"SCOMIN_MASK\";\n case Instruction::MASK_PERSISTENT:\n return \"MASK_PERSISTENT\";\n case Instruction::SET_PERSISTENT:\n return \"SET_PERSISTENT\";\n case Instruction::GET_PERSISTENT:\n return \"GET_PERSISTENT\";\n case Instruction::READKEYWORD:\n return \"READKEYWORD\";\n case Instruction::WRITEKEYWORD:\n return \"WRITEKEYWORD\";\n case Instruction::FRUSTATUS:\n return \"FRUSTATUS\";\n case Instruction::CHICDOIPL:\n return \"CHICDOIPL\";\n case Instruction::ENABLE_MEM_VOLTAGES:\n return \"ENABLE_MEM_VOLTAGES\";\n case Instruction::DISABLE_MEM_VOLTAGES:\n return \"DISABLE_MEM_VOLTAGES\";\n case Instruction::SNDISTEPMSG:\n return \"SNDISTEPMSG\";\n case Instruction::MBXTRACEENABLE:\n return \"MBXTRACEENABLE\";\n case Instruction::MBXTRACEDISABLE:\n return \"MBXTRACEDISABLE\";\n case Instruction::MBXTRACEREAD:\n return \"MBXTRACEREAD\";\n case Instruction::PUTMEMPBA:\n return \"PUTMEMPBA\";\n case Instruction::GETMEMPBA:\n return \"GETMEMPBA\";\n case Instruction::BULK_SCOMIN:\n return \"BULK_SCOMIN\";\n case Instruction::BULK_SCOMOUT:\n return \"BULK_SCOMOUT\";\n case Instruction::STREAM_SETUP:\n return \"STREAM_SETUP\";\n case Instruction::STREAM_FINISH:\n return \"STREAM_FINISH\";\n case Instruction::FSPDMAIN:\n return \"FSPDMAIN\";\n case Instruction::FSPDMAOUT:\n return \"FSPDMAOUT\";\n case Instruction::SUBMIT:\n return \"SUBMIT\";\n case Instruction::REQUEST_RESET:\n return \"REQUEST_RESET\";\n case Instruction::SEND_TAPI_CMD:\n return \"SEND_TAPI_CMD\";\n case Instruction::PUTMEMPROC:\n return \"PUTMEMPROC\";\n case Instruction::GETMEMPROC:\n return \"GETMEMPROC\";\n case Instruction::PNORGETLIST:\n return \"PNORGETLIST\";\n case Instruction::PNORGET:\n return \"PNORGET\";\n case Instruction::PNORPUT:\n return \"PNORPUT\";\n case Instruction::QUERYSP:\n return \"QUERYSP\";\n }\n return \"\";\n}\n\n\n\/*****************************************************************************\/\n\/* Instruction Implementation ************************************************\/\n\/*****************************************************************************\/\nInstruction::Instruction(void) : version(0x1), command(NOCOMMAND), type(NOINSTRUCTION), error(0){\n}\n\n\/* for all of these methods check if we are of a different type *\/\nuint32_t Instruction::execute(ecmdDataBuffer & o_data, InstructionStatus & o_status, Handle ** io_handle) {\n uint32_t rc = 0;\n\n \/* set the version of this instruction in the status *\/\n o_status.instructionVersion = version;\n\n o_status.errorMessage.append(\"Instruction::execute Unknown Instruction specified. New FSP server may be required.\");\n o_status.rc = SERVER_UNKNOWN_INSTRUCTION;\n\n return rc;\n}\n\nuint32_t Instruction::decrementVersion(void) {\n if (version > 0x1) {\n version--;\n return 0;\n }\n \/\/ return an error if we can not decrement\n return 1;\n}\n\nuint32_t Instruction::flatten(uint8_t * o_data, uint32_t i_len) const {\n uint32_t rc = 0;\n\n uint32_t * o_ptr = (uint32_t *) o_data;\n if (i_len < flattenSize()) {\n out.error(\"Instruction::flatten\", \"i_len %d bytes is too small to flatten\\n\", i_len);\n rc = 1;\n } else {\n \/\/ clear memory\n memset(o_data, 0, flattenSize());\n o_ptr[0] = htonl(version);\n o_ptr[1] = htonl(command);\n o_ptr[2] = htonl(flags);\n }\n\n return rc;\n}\n\nuint32_t Instruction::unflatten(const uint8_t * i_data, uint32_t i_len) {\n uint32_t rc = 0;\n\n uint32_t * i_ptr = (uint32_t *) i_data;\n version = ntohl(i_ptr[0]);\n if(version == 0x1) {\n command = (InstructionCommand) ntohl(i_ptr[1]);\n flags = ntohl(i_ptr[2]);\n } else {\n error = rc = SERVER_UNKNOWN_INSTRUCTION_VERSION;\n }\n\n return rc;\n}\n\nuint32_t Instruction::flattenSize(void) const {\n return (3 * sizeof(uint32_t));\n}\n\nstd::string Instruction::dumpInstruction(void) const {\n std::ostringstream oss;\n\n oss << \"Instruction\" << std::endl;\n\n return oss.str();\n}\n\nuint64_t Instruction::getHash(void) const {\n return ((0x0000000F & type) << 28);\n}\n\nuint32_t Instruction::closeHandle(Handle ** i_handle) {\n uint32_t rc = 0;\n\n *i_handle = NULL;\n\n return rc;\n}\n\nstd::string Instruction::getInstructionVars(const InstructionStatus & i_status) const {\n std::ostringstream oss;\n\n oss << std::hex << std::setfill('0');\n oss << \"rc: \" << std::setw(8) << i_status.rc;\n\n return oss.str();\n}\n\nInstruction::InstructionType Instruction::getType(void) const { return type; }\nInstruction::InstructionCommand Instruction::getCommand(void) const { return command; }\nuint32_t Instruction::getFlags(void) const { return flags; }\nuint32_t Instruction::getVersion(void) const { return version; }\n\nint Instruction::genWords(const ecmdDataBuffer &data, std::string &words) const {\n \/\/ copied from Debug.C\n int rc = 0;\n\n if (data.getBitLength() == 0) {\n words = \"\"; \/\/ This will kill the genHexLeftStr error if we have no data \n } else if (data.getBitLength() <= 128) {\n words = data.genHexLeftStr(0, data.getBitLength());\n } else {\n words = data.genHexLeftStr(0, 128);\n }\n\n return rc;\n}\n\nstd::ostream& operator<<(std::ostream& io_stream, const Instruction& i_instruction ) {\n io_stream << i_instruction.dumpInstruction() << std::endl;\n return io_stream;\n}\n\nuint32_t devicestring_genhash(const std::string & i_string, uint32_t & o_hash)\n{\n int length = i_string.length();\n const char * data = i_string.c_str();\n int found = 0;\n int type = 0; \/\/ 3 bits\n int fsi = 0; \/\/ 6 bits\n int cfam = 0; \/\/ 2 bits\n int engine = 0; \/\/ 5 bits\n int subfsi = 0; \/\/ 3 bits\n int subcfam = 0; \/\/ 2 bits\n int subengine = 0; \/\/ 5 bits\n int subsubfsi = 0; \/\/ 3 bits\n int subsubcfam = 0; \/\/ 2 bits\n o_hash = 0x0;\n if (length == 5)\n {\n type = 1;\n found = sscanf(data, \"L%02dC%d\", &fsi, &cfam);\n if (found != 2)\n {\n \/\/std::cout << \"ERROR reading data from \" << i_string << std::endl;\n return 1;\n }\n }\n else if (length == 13)\n {\n type = 2;\n found = sscanf(data, \"L%02dC%dE%02d:L%dC%d\", &fsi, &cfam, &engine, &subfsi, &subcfam);\n if (found != 5)\n {\n \/\/std::cout << \"ERROR reading data from \" << i_string << std::endl;\n return 2;\n }\n }\n else if (length == 21)\n {\n type = 3;\n found = sscanf(data, \"L%02dC%dE%02d:L%dC%dE%02d:L%dC%d\", &fsi, &cfam, &engine, &subfsi, &subcfam,\n &subengine, &subsubfsi, &subsubcfam);\n if (found != 8)\n {\n \/\/std::cout << \"ERROR reading data from \" << i_string << std::endl;\n return 3;\n }\n }\n else\n {\n \/\/ error\n \/\/std::cout << \"ERROR unknown format for device \" << i_string << std::endl;\n return 4;\n }\n o_hash |= ((0x07 & type) << 0); \/\/0x00000007\n o_hash |= ((0x3F & fsi) << 3); \/\/0x000001F8\n o_hash |= ((0x03 & cfam) << 9); \/\/0x00000600\n o_hash |= ((0x1F & engine) << 11); \/\/0x0000F800\n o_hash |= ((0x07 & subfsi) << 16); \/\/0x00070000\n o_hash |= ((0x03 & subcfam) << 19); \/\/0x00180000\n o_hash |= ((0x1F & subengine) << 21); \/\/0x03E00000\n o_hash |= ((0x07 & subsubfsi) << 26); \/\/0x1C000000\n o_hash |= ((0x03 & subsubcfam) << 29); \/\/0x60000000\n return 0;\n}\nfix hash generation for bmc device strings\/\/IBM_PROLOG_BEGIN_TAG\n\/\/IBM_PROLOG_END_TAG\n\n\n\/\/--------------------------------------------------------------------\n\/\/ Includes\n\/\/--------------------------------------------------------------------\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef OTHER_USE\n#include \nextern OutputLite out;\n#else\n#include \n#endif\n\nstd::string InstructionTypeToString(Instruction::InstructionType i_type) {\n switch (i_type) {\n case Instruction::NOINSTRUCTION:\n return \"NOINSTRUCTION\";\n case Instruction::FSI:\n return \"FSI\";\n case Instruction::JTAG:\n return \"JTAG\";\n case Instruction::MULTIPLEJTAG:\n return \"MULTIPLEJTAG\";\n case Instruction::PSI:\n return \"PSI\";\n case Instruction::GPIO:\n return \"GPIO\";\n case Instruction::I2C:\n return \"I2C\";\n case Instruction::VPD:\n return \"VPD\";\n case Instruction::DMA:\n return \"DMA\";\n case Instruction::CONTROL:\n return \"CONTROL\";\n case Instruction::DMAEXER:\n return \"DMAEXER\";\n case Instruction::POWR:\n return \"POWR\";\n case Instruction::FSISTREAM:\n return \"FSISTREAM\";\n case Instruction::SBEFIFO:\n return \"SBEFIFO\";\n case Instruction::GSD2PIB:\n return \"GSD2PIB\";\n case Instruction::FSIMEMPROC:\n return \"FSIMEMPROC\";\n case Instruction::PNOR:\n return \"PNOR\";\n }\n return \"\";\n}\n\nstd::string InstructionCommandToString(Instruction::InstructionCommand i_command) {\n switch (i_command) {\n case Instruction::NOCOMMAND:\n return \"NOCOMMAND\";\n case Instruction::SENDCMD:\n return \"SENDCMD\";\n case Instruction::READ:\n return \"READ\";\n case Instruction::WRITE:\n return \"WRITE\";\n case Instruction::LONGIN:\n return \"LONGIN\";\n case Instruction::LONGOUT:\n return \"LONGOUT\";\n case Instruction::READ_WRITE:\n return \"READ_WRITE\";\n case Instruction::SHIFTOUT:\n return \"SHIFTOUT\";\n case Instruction::DMAIN:\n return \"DMAIN\";\n case Instruction::DMAOUT:\n return \"DMAOUT\";\n case Instruction::MISC:\n return \"MISC\";\n case Instruction::TOTAP:\n return \"TOTAP\";\n case Instruction::READVPD:\n return \"READVPD\";\n case Instruction::READSPMEM:\n return \"READSPMEM\";\n case Instruction::WRITESPMEM:\n return \"WRITESPMEM\";\n case Instruction::SCOMIN:\n return \"SCOMIN\";\n case Instruction::SCOMOUT:\n return \"SCOMOUT\";\n case Instruction::WRITEVPD:\n return \"WRITEVPD\";\n case Instruction::PSI_RESET:\n return \"PSI_RESET\";\n case Instruction::PSI_LINK_CALIB:\n return \"PSI_LINK_CALIB\";\n case Instruction::PSI_EI_REG_READ:\n return \"PSI_EI_REG_READ\";\n case Instruction::PSI_EI_REG_WRITE:\n return \"PSI_EI_REG_WRITE\";\n case Instruction::PSI_VERIFY:\n return \"PSI_VERIFY\";\n case Instruction::PSI_SCOM_READ:\n return \"PSI_SCOM_READ\";\n case Instruction::PSI_SCOM_WRITE:\n return \"PSI_SCOM_WRITE\";\n case Instruction::PSI_READ:\n return \"PSI_READ\";\n case Instruction::PSI_WRITE:\n return \"PSI_WRITE\";\n case Instruction::PSI_INIT:\n return \"PSI_INIT\";\n case Instruction::PSI_LINK_ENABLE:\n return \"PSI_LINK_ENABLE\";\n case Instruction::PSI_SET_SPEED:\n return \"PSI_SET_SPEED\";\n case Instruction::PSI_LINK_VERIFY:\n return \"PSI_LINK_VERIFY\";\n case Instruction::I2CWRITE:\n return \"I2CWRITE\";\n case Instruction::I2CREAD:\n return \"I2CREAD\";\n case Instruction::GPIO_CONFIGPIN:\n return \"GPIO_CONFIGPIN\";\n case Instruction::GPIO_READPIN:\n return \"GPIO_READPIN\";\n case Instruction::GPIO_READPINS:\n return \"GPIO_READPINS\";\n case Instruction::GPIO_READLATCH:\n return \"GPIO_READLATCH\";\n case Instruction::GPIO_WRITELATCH:\n return \"GPIO_WRITELATCH\";\n case Instruction::GPIO_WRITELATCHES:\n return \"GPIO_WRITELATCHES\";\n case Instruction::GPIO_READCONFIG:\n return \"GPIO_READCONFIG\";\n case Instruction::GPIO_WRITECONFIG:\n return \"GPIO_WRITECONFIG\";\n case Instruction::GPIO_WRITECNFGSET:\n return \"GPIO_WRITECNFGSET\";\n case Instruction::GPIO_WRITECNFGCLR:\n return \"GPIO_WRITECNFGCLR\";\n case Instruction::DMAEXER_START:\n return \"DMAEXER_START\";\n case Instruction::DMAEXER_REPORT:\n return \"DMAEXER_REPORT\";\n case Instruction::DMAEXER_STOP:\n return \"DMAEXER_STOP\";\n case Instruction::INFO:\n return \"INFO\";\n case Instruction::RUN_CMD:\n return \"RUN_CMD\";\n case Instruction::MULTI_ENABLE:\n return \"MULTI_ENABLE\";\n case Instruction::AUTH:\n return \"AUTH\";\n case Instruction::ADDAUTH:\n return \"ADDAUTH\";\n case Instruction::CLEARAUTH:\n return \"CLEARAUTH\";\n case Instruction::VERSION:\n return \"VERSION\";\n case Instruction::FLIGHTRECORDER:\n return \"FLIGHTRECORDER\";\n case Instruction::EXIT:\n return \"EXIT\";\n case Instruction::SCOMIN_MASK:\n return \"SCOMIN_MASK\";\n case Instruction::MASK_PERSISTENT:\n return \"MASK_PERSISTENT\";\n case Instruction::SET_PERSISTENT:\n return \"SET_PERSISTENT\";\n case Instruction::GET_PERSISTENT:\n return \"GET_PERSISTENT\";\n case Instruction::READKEYWORD:\n return \"READKEYWORD\";\n case Instruction::WRITEKEYWORD:\n return \"WRITEKEYWORD\";\n case Instruction::FRUSTATUS:\n return \"FRUSTATUS\";\n case Instruction::CHICDOIPL:\n return \"CHICDOIPL\";\n case Instruction::ENABLE_MEM_VOLTAGES:\n return \"ENABLE_MEM_VOLTAGES\";\n case Instruction::DISABLE_MEM_VOLTAGES:\n return \"DISABLE_MEM_VOLTAGES\";\n case Instruction::SNDISTEPMSG:\n return \"SNDISTEPMSG\";\n case Instruction::MBXTRACEENABLE:\n return \"MBXTRACEENABLE\";\n case Instruction::MBXTRACEDISABLE:\n return \"MBXTRACEDISABLE\";\n case Instruction::MBXTRACEREAD:\n return \"MBXTRACEREAD\";\n case Instruction::PUTMEMPBA:\n return \"PUTMEMPBA\";\n case Instruction::GETMEMPBA:\n return \"GETMEMPBA\";\n case Instruction::BULK_SCOMIN:\n return \"BULK_SCOMIN\";\n case Instruction::BULK_SCOMOUT:\n return \"BULK_SCOMOUT\";\n case Instruction::STREAM_SETUP:\n return \"STREAM_SETUP\";\n case Instruction::STREAM_FINISH:\n return \"STREAM_FINISH\";\n case Instruction::FSPDMAIN:\n return \"FSPDMAIN\";\n case Instruction::FSPDMAOUT:\n return \"FSPDMAOUT\";\n case Instruction::SUBMIT:\n return \"SUBMIT\";\n case Instruction::REQUEST_RESET:\n return \"REQUEST_RESET\";\n case Instruction::SEND_TAPI_CMD:\n return \"SEND_TAPI_CMD\";\n case Instruction::PUTMEMPROC:\n return \"PUTMEMPROC\";\n case Instruction::GETMEMPROC:\n return \"GETMEMPROC\";\n case Instruction::PNORGETLIST:\n return \"PNORGETLIST\";\n case Instruction::PNORGET:\n return \"PNORGET\";\n case Instruction::PNORPUT:\n return \"PNORPUT\";\n case Instruction::QUERYSP:\n return \"QUERYSP\";\n }\n return \"\";\n}\n\n\n\/*****************************************************************************\/\n\/* Instruction Implementation ************************************************\/\n\/*****************************************************************************\/\nInstruction::Instruction(void) : version(0x1), command(NOCOMMAND), type(NOINSTRUCTION), error(0){\n}\n\n\/* for all of these methods check if we are of a different type *\/\nuint32_t Instruction::execute(ecmdDataBuffer & o_data, InstructionStatus & o_status, Handle ** io_handle) {\n uint32_t rc = 0;\n\n \/* set the version of this instruction in the status *\/\n o_status.instructionVersion = version;\n\n o_status.errorMessage.append(\"Instruction::execute Unknown Instruction specified. New FSP server may be required.\");\n o_status.rc = SERVER_UNKNOWN_INSTRUCTION;\n\n return rc;\n}\n\nuint32_t Instruction::decrementVersion(void) {\n if (version > 0x1) {\n version--;\n return 0;\n }\n \/\/ return an error if we can not decrement\n return 1;\n}\n\nuint32_t Instruction::flatten(uint8_t * o_data, uint32_t i_len) const {\n uint32_t rc = 0;\n\n uint32_t * o_ptr = (uint32_t *) o_data;\n if (i_len < flattenSize()) {\n out.error(\"Instruction::flatten\", \"i_len %d bytes is too small to flatten\\n\", i_len);\n rc = 1;\n } else {\n \/\/ clear memory\n memset(o_data, 0, flattenSize());\n o_ptr[0] = htonl(version);\n o_ptr[1] = htonl(command);\n o_ptr[2] = htonl(flags);\n }\n\n return rc;\n}\n\nuint32_t Instruction::unflatten(const uint8_t * i_data, uint32_t i_len) {\n uint32_t rc = 0;\n\n uint32_t * i_ptr = (uint32_t *) i_data;\n version = ntohl(i_ptr[0]);\n if(version == 0x1) {\n command = (InstructionCommand) ntohl(i_ptr[1]);\n flags = ntohl(i_ptr[2]);\n } else {\n error = rc = SERVER_UNKNOWN_INSTRUCTION_VERSION;\n }\n\n return rc;\n}\n\nuint32_t Instruction::flattenSize(void) const {\n return (3 * sizeof(uint32_t));\n}\n\nstd::string Instruction::dumpInstruction(void) const {\n std::ostringstream oss;\n\n oss << \"Instruction\" << std::endl;\n\n return oss.str();\n}\n\nuint64_t Instruction::getHash(void) const {\n return ((0x0000000F & type) << 28);\n}\n\nuint32_t Instruction::closeHandle(Handle ** i_handle) {\n uint32_t rc = 0;\n\n *i_handle = NULL;\n\n return rc;\n}\n\nstd::string Instruction::getInstructionVars(const InstructionStatus & i_status) const {\n std::ostringstream oss;\n\n oss << std::hex << std::setfill('0');\n oss << \"rc: \" << std::setw(8) << i_status.rc;\n\n return oss.str();\n}\n\nInstruction::InstructionType Instruction::getType(void) const { return type; }\nInstruction::InstructionCommand Instruction::getCommand(void) const { return command; }\nuint32_t Instruction::getFlags(void) const { return flags; }\nuint32_t Instruction::getVersion(void) const { return version; }\n\nint Instruction::genWords(const ecmdDataBuffer &data, std::string &words) const {\n \/\/ copied from Debug.C\n int rc = 0;\n\n if (data.getBitLength() == 0) {\n words = \"\"; \/\/ This will kill the genHexLeftStr error if we have no data \n } else if (data.getBitLength() <= 128) {\n words = data.genHexLeftStr(0, data.getBitLength());\n } else {\n words = data.genHexLeftStr(0, 128);\n }\n\n return rc;\n}\n\nstd::ostream& operator<<(std::ostream& io_stream, const Instruction& i_instruction ) {\n io_stream << i_instruction.dumpInstruction() << std::endl;\n return io_stream;\n}\n\nuint32_t devicestring_genhash(const std::string & i_string, uint32_t & o_hash)\n{\n uint32_t rc = 0;\n int length = i_string.length();\n const char * data = i_string.c_str();\n int found = 0;\n int type = 0; \/\/ 3 bits\n int fsi = 0; \/\/ 6 bits\n int cfam = 0; \/\/ 2 bits\n int engine = 0; \/\/ 5 bits\n int subfsi = 0; \/\/ 3 bits\n int subcfam = 0; \/\/ 2 bits\n int subengine = 0; \/\/ 5 bits\n int subsubfsi = 0; \/\/ 3 bits\n int subsubcfam = 0; \/\/ 2 bits\n o_hash = 0x0;\n if (length == 5)\n {\n type = 1;\n found = sscanf(data, \"L%02dC%d\", &fsi, &cfam);\n if (found != 2)\n {\n rc = 1;\n }\n }\n else if (length == 13)\n {\n type = 2;\n found = sscanf(data, \"L%02dC%dE%02d:L%dC%d\", &fsi, &cfam, &engine, &subfsi, &subcfam);\n if (found != 5)\n {\n rc = 2;\n }\n }\n else if (length == 21)\n {\n type = 3;\n found = sscanf(data, \"L%02dC%dE%02d:L%dC%dE%02d:L%dC%d\", &fsi, &cfam, &engine, &subfsi, &subcfam,\n &subengine, &subsubfsi, &subsubcfam);\n if (found != 8)\n {\n rc = 3;\n }\n }\n else\n {\n \/\/ BMC device case\n char * endptr = NULL;\n errno = 0;\n fsi = strtol(data, &endptr, 10);\n if (((errno == ERANGE) && ((fsi == LONG_MAX) || (fsi == LONG_MIN))) ||\n ((errno != 0) && (fsi == 0)))\n {\n rc = 5;\n }\n else if (endptr == data)\n {\n rc = 6;\n }\n else if (*endptr != '\\0')\n {\n rc = 4;\n }\n }\n\n if (rc)\n {\n \/\/ error\n std::cout << \"ERROR unknown format for device \" << i_string << \" rc = \" << rc << std::endl;\n }\n else\n {\n o_hash |= ((0x07 & type) << 0); \/\/0x00000007\n o_hash |= ((0x3F & fsi) << 3); \/\/0x000001F8\n o_hash |= ((0x03 & cfam) << 9); \/\/0x00000600\n o_hash |= ((0x1F & engine) << 11); \/\/0x0000F800\n o_hash |= ((0x07 & subfsi) << 16); \/\/0x00070000\n o_hash |= ((0x03 & subcfam) << 19); \/\/0x00180000\n o_hash |= ((0x1F & subengine) << 21); \/\/0x03E00000\n o_hash |= ((0x07 & subsubfsi) << 26); \/\/0x1C000000\n o_hash |= ((0x03 & subsubcfam) << 29); \/\/0x60000000\n }\n return rc;\n}\n<|endoftext|>"} {"text":"#include \"geodrawer_plugin.h\"\n#include \"geodrawer.h\"\n\n#include \n\n#include \"geometries.h\"\n#include \"iooptions.h\"\n#include \"drawerfactory.h\"\n#include \"selectiondrawer.h\"\n\nvoid GeodrawerPlugin::registerTypes(const char *uri)\n{\n \/\/ @uri n52.org.ilwisobjects\n qmlRegisterType(uri, 1, 0, \"GeoDrawer\");\n\n Ilwis::Geodrawer::DrawerFactory::registerDrawer(\"SelectionDrawer\", Ilwis::Geodrawer::SelectionDrawer::create);\n\n\n}\n\n\nrenamed GeoDrawer to LayerView#include \"geodrawer_plugin.h\"\n#include \"visualizationmanager.h\"\n\/\/#include \"geodrawer.h\"\n\n#include \n\n#include \"geometries.h\"\n#include \"iooptions.h\"\n#include \"drawerfactory.h\"\n#include \"selectiondrawer.h\"\n#include \"layersview.h\"\n\nvoid GeodrawerPlugin::registerTypes(const char *uri)\n{\n \/\/ @uri n52.org.ilwisobjects\n qmlRegisterType(uri, 1, 0, \"LayersView\");\n\n Ilwis::Geodrawer::DrawerFactory::registerDrawer(\"SelectionDrawer\", Ilwis::Geodrawer::SelectionDrawer::create);\n\n\n}\n\n\n<|endoftext|>"} {"text":"\/** @date 2015\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2015 Vuzix Corporation.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"DriverWrapper.h\"\n#include \"InterfaceTraits.h\"\n#include \"OSVRViveTracker.h\"\n#include \"PropertyHelper.h\"\n#include \n#include \n\n\/\/ Library\/third-party includes\n#include \n#include \n\n\/\/ Standard includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Anonymous namespace to avoid symbol collision\nnamespace {\n\nstatic const auto PREFIX = \"[OSVR-Vive] \";\n\nclass HardwareDetection {\n\n public:\n HardwareDetection() {}\n OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {\n if (m_driverHost) {\n \/\/ Already found a Vive.\n \/\/\/ @todo what are the semantics of the return value from a hardware\n \/\/\/ detect?\n return OSVR_RETURN_SUCCESS;\n }\n\n {\n osvr::vive::DriverHostPtr host(new osvr::vive::ViveDriverHost);\n\n auto vive = osvr::vive::DriverWrapper(host.get());\n\n if (vive.foundDriver()) {\n std::cout << PREFIX << \"Found the Vive driver at \"\n << vive.getDriverFileLocation() << std::endl;\n }\n\n if (!vive.haveDriverLoaded()) {\n std::cout << PREFIX << \"Could not open driver.\" << std::endl;\n return OSVR_RETURN_FAILURE;\n }\n\n if (vive.foundConfigDirs()) {\n std::cout << PREFIX << \"Driver config dir is: \"\n << vive.getDriverConfigDir() << std::endl;\n }\n\n if (!vive) {\n std::cerr << PREFIX\n << \"Error in first-stage Vive driver startup. Exiting\"\n << std::endl;\n return OSVR_RETURN_FAILURE;\n }\n\n if (!vive.isHMDPresent()) {\n std::cerr << PREFIX\n << \"Driver loaded, but no Vive is connected. Exiting\"\n << std::endl;\n return OSVR_RETURN_FAILURE;\n }\n\n std::cout << PREFIX << \"Vive is connected.\" << std::endl;\n\n \/\/\/ Hand the Vive object off to the OSVR driver.\n auto startResult = host->start(ctx, std::move(vive));\n if (startResult) {\n \/\/\/ and it started up the rest of the way just fine!\n \/\/\/ We'll keep the driver around!\n m_driverHost = std::move(host);\n std::cout << PREFIX\n << \"Vive driver finished startup successfully!\"\n << std::endl;\n return OSVR_RETURN_SUCCESS;\n }\n }\n\n std::cout << PREFIX << \"Vive driver startup failed somewhere, \"\n \"unloading to perhaps try again later.\"\n << std::endl;\n return OSVR_RETURN_FAILURE;\n }\n\n private:\n std::vector m_deviceTypes;\n \/\/\/ This is the OSVR driver object, which also serves as the \"SteamVR\"\n \/\/\/ driver host. We can only run one Vive at a time.\n osvr::vive::DriverHostPtr m_driverHost;\n};\n} \/\/ namespace\n\nOSVR_PLUGIN(com_osvr_Vive) {\n osvr::pluginkit::PluginContext context(ctx);\n\n \/\/\/ Register a detection callback function object.\n context.registerHardwareDetectCallback(new HardwareDetection());\n\n return OSVR_RETURN_SUCCESS;\n}\nAdjust hardware detection so we don't unload the DLL so much, for faster detection callbacks.\/** @date 2015\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2015 Vuzix Corporation.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"DriverWrapper.h\"\n#include \"InterfaceTraits.h\"\n#include \"OSVRViveTracker.h\"\n#include \"PropertyHelper.h\"\n#include \n#include \n\n\/\/ Library\/third-party includes\n#include \n#include \n\n\/\/ Standard includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Anonymous namespace to avoid symbol collision\nnamespace {\n\nstatic const auto PREFIX = \"[OSVR-Vive] \";\n\nclass HardwareDetection {\n\n public:\n HardwareDetection()\n : m_inactiveDriverHost(new osvr::vive::ViveDriverHost) {}\n OSVR_ReturnCode operator()(OSVR_PluginRegContext ctx) {\n if (m_driverHost) {\n \/\/ Already found a Vive.\n \/\/\/ @todo what are the semantics of the return value from a hardware\n \/\/\/ detect?\n return OSVR_RETURN_SUCCESS;\n }\n if (!m_shouldAttemptDetection) {\n \/\/\/ We said we shouldn't and wouldn't try again.\n return OSVR_RETURN_FAILURE;\n }\n\n auto vivePtr = startupAndGetVive();\n if (!vivePtr) {\n \/\/\/ There was trouble in early startup\n return OSVR_RETURN_FAILURE;\n }\n\n if (!vivePtr->isHMDPresent()) {\n \/\/\/ Didn't detect anything - leave the driver DLL loaded,\n \/\/\/ though, to make things faster next time around.\n \/\/\/ Silent failure, to avoid annoying users.\n return OSVR_RETURN_FAILURE;\n }\n\n std::cout << PREFIX << \"Vive is connected.\" << std::endl;\n\n \/\/\/ Hand the Vive object off to the OSVR driver.\n auto startResult = finishViveStartup(ctx);\n if (startResult) {\n \/\/\/ and it started up the rest of the way just fine!\n \/\/\/ We'll keep the driver around!\n std::cout << PREFIX << \"Vive driver finished startup successfully!\"\n << std::endl;\n return OSVR_RETURN_SUCCESS;\n }\n\n std::cout << PREFIX << \"Vive driver startup failed somewhere, \"\n \"unloading to perhaps try again later.\"\n << std::endl;\n\n unloadTemporaries();\n return OSVR_RETURN_FAILURE;\n }\n\n bool finishViveStartup(OSVR_PluginRegContext ctx) {\n auto startResult =\n m_inactiveDriverHost->start(ctx, std::move(*m_viveWrapper));\n m_viveWrapper.reset();\n if (startResult) {\n m_driverHost = std::move(m_inactiveDriverHost);\n }\n return startResult;\n }\n\n \/\/\/ Attempts the first part of startup, if required.\n osvr::vive::DriverWrapper *startupAndGetVive() {\n if (!m_viveWrapper) {\n m_viveWrapper.reset(\n new osvr::vive::DriverWrapper(&getInactiveHost()));\n\n if (m_viveWrapper->foundDriver()) {\n std::cout << PREFIX << \"Found the Vive driver at \"\n << m_viveWrapper->getDriverFileLocation()\n << std::endl;\n }\n\n if (!m_viveWrapper->haveDriverLoaded()) {\n std::cout << PREFIX << \"Could not open driver.\" << std::endl;\n stopAttemptingDetection();\n return nullptr;\n }\n\n if (m_viveWrapper->foundConfigDirs()) {\n std::cout << PREFIX << \"Driver config dir is: \"\n << m_viveWrapper->getDriverConfigDir() << std::endl;\n }\n\n if (!(*m_viveWrapper)) {\n std::cerr << PREFIX\n << \"Error in first-stage Vive driver startup.\"\n << std::endl;\n m_viveWrapper.reset();\n return nullptr;\n }\n }\n return m_viveWrapper.get();\n }\n\n \/\/\/ returns a reference because it will never be null.\n \/\/\/ Creates one if needed.\n osvr::vive::ViveDriverHost &getInactiveHost() {\n if (m_driverHost) {\n throw std::logic_error(\"Can't get an inactive host - we already \"\n \"have a live device driver!\");\n }\n if (!m_inactiveDriverHost) {\n m_inactiveDriverHost.reset(new osvr::vive::ViveDriverHost);\n }\n return *m_inactiveDriverHost.get();\n }\n\n void stopAttemptingDetection() {\n std::cerr << PREFIX << \"Will not re-attempt detecting Vive.\"\n << std::endl;\n m_shouldAttemptDetection = false;\n unloadTemporaries();\n m_driverHost.reset();\n }\n\n void unloadTemporaries() {\n m_viveWrapper.reset();\n m_inactiveDriverHost.reset();\n }\n\n private:\n \/\/\/ This is the OSVR driver object, which also serves as the \"SteamVR\"\n \/\/\/ driver host. We can only run one Vive at a time.\n osvr::vive::DriverHostPtr m_driverHost;\n\n \/\/\/ A Vive object that we hang on to if we don't have a fully-started-up\n \/\/\/ device, to save time in hardware detection.\n std::unique_ptr m_viveWrapper;\n \/\/\/ Populated only when we don't have an active driver - we keep it around\n \/\/\/ so we don't have to re-load the full driver every time we get hit with a\n \/\/\/ hardware detect request.\n osvr::vive::DriverHostPtr m_inactiveDriverHost;\n\n bool m_shouldAttemptDetection = true;\n};\n} \/\/ namespace\n\nOSVR_PLUGIN(com_osvr_Vive) {\n osvr::pluginkit::PluginContext context(ctx);\n\n \/\/\/ Register a detection callback function object.\n context.registerHardwareDetectCallback(new HardwareDetection());\n\n return OSVR_RETURN_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Script Generator project on Qt Labs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"shellgenerator.h\"\n#include \"reporthandler.h\"\n\n#include \"metaqtscript.h\"\n\nbool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const\n{\n uint cg = meta_class->typeEntry()->codeGeneration();\n if (meta_class->name().startsWith(\"QtScript\")) return false;\n if (meta_class->name().startsWith(\"QFuture\")) return false;\n if (meta_class->name().startsWith(\"Global\")) return false;\n if (meta_class->name().startsWith(\"QStyleOptionComplex\")) return false;\n if (meta_class->name().startsWith(\"QTextLayout\")) return false;\n \/\/if (meta_class->name().startsWith(\"QTextStream\")) return false; \/\/ because of >> operators\n \/\/if (meta_class->name().startsWith(\"QDataStream\")) return false; \/\/ \"\n return ((cg & TypeEntry::GenerateCode) != 0);\n}\n\nvoid ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)\n{\n if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {\n s << type->originalTypeDescription();\n return;\n }\n\n if (type->isArray()) {\n writeTypeInfo(s, type->arrayElementType(), options);\n if (options & ArrayAsPointer) {\n s << \"*\";\n } else {\n s << \"[\" << type->arrayElementCount() << \"]\";\n }\n return;\n }\n\n const TypeEntry *te = type->typeEntry();\n\n if (type->isConstant() && !(options & ExcludeConst))\n s << \"const \";\n\n if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {\n s << \"int\";\n } else if (te->isFlags()) {\n s << ((FlagsTypeEntry *) te)->originalName();\n } else {\n s << fixCppTypeName(te->qualifiedCppName());\n }\n\n if (type->instantiations().size() > 0\n && (!type->isContainer() \n || (static_cast(te))->type() != ContainerTypeEntry::StringListContainer)) {\n s << '<';\n QList args = type->instantiations();\n bool nested_template = false;\n for (int i=0; iisContainer();\n writeTypeInfo(s, args.at(i));\n }\n if (nested_template)\n s << ' ';\n s << '>';\n }\n\n s << QString(type->indirections(), '*');\n\n if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))\n s << \"&\";\n \n if (type->isReference() && (options & ConvertReferenceToPtr)) {\n s << \"*\";\n }\n \n\n if (!(options & SkipName))\n s << ' ';\n}\n\n\nvoid ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,\n const AbstractMetaArgumentList &arguments,\n Option option,\n int numArguments)\n{\n if (numArguments < 0) numArguments = arguments.size();\n\n for (int i=0; itype(), option);\n if (!(option & SkipName))\n s << \" \" << arg->argumentName();\n if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) {\n s << \" = \"; \n\n QString expr = arg->originalDefaultValueExpression();\n if (expr != \"0\") {\n QString qualifier;\n if (arg->type()->typeEntry()->isEnum() && expr.indexOf(\"::\") < 0) {\n qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();\n } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf(\"::\") < 0) {\n qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();\n }\n if (!qualifier.isEmpty()) {\n s << qualifier << \"::\";\n }\n }\n if (expr.contains(\"defaultConnection\")) {\n expr.replace(\"defaultConnection\",\"QSqlDatabase::defaultConnection\");\n }\n if (expr == \"MediaSource()\") {\n expr = \"Phonon::MediaSource()\";\n }\n s << expr; \n }\n }\n}\n\n\/*!\n * Writes the function \\a meta_function signature to the textstream \\a s.\n *\n * The \\a name_prefix can be used to give the function name a prefix,\n * like \"__public_\" or \"__override_\" and \\a classname_prefix can\n * be used to give the class name a prefix.\n *\n * The \\a option flags can be used to tweak various parameters, such as\n * showing static, original vs renamed name, underscores for space etc.\n *\n * The \\a extra_arguments list is a list of extra arguments on the\n * form \"bool static_call\".\n *\/\n\nvoid ShellGenerator::writeFunctionSignature(QTextStream &s,\n const AbstractMetaFunction *meta_function,\n const AbstractMetaClass *implementor,\n const QString &name_prefix,\n Option option,\n const QString &classname_prefix,\n const QStringList &extra_arguments,\n int numArguments)\n{\n\/\/ ### remove the implementor\n AbstractMetaType *function_type = meta_function->type();\n\n\n if ((option & SkipReturnType) == 0) {\n if (function_type) {\n writeTypeInfo(s, function_type, option);\n s << \" \";\n } else if (!meta_function->isConstructor()) {\n s << \"void \";\n }\n }\n\n if (implementor) {\n if (classname_prefix.isEmpty())\n s << wrapperClassName(implementor) << \"::\";\n else\n s << classname_prefix << implementor->name() << \"::\";\n }\n\n\n QString function_name;\n if (option & OriginalName)\n function_name = meta_function->originalName();\n else\n function_name = meta_function->name();\n\n if (option & UnderscoreSpaces)\n function_name = function_name.replace(' ', '_');\n\n if (meta_function->isConstructor())\n function_name = meta_function->ownerClass()->name();\n\n if (meta_function->isStatic() && (option & ShowStatic)) {\n function_name = \"static_\" + meta_function->ownerClass()->name() + \"_\" + function_name;\n }\n \n if (function_name.startsWith(\"operator\")) {\n function_name = meta_function->name();\n }\n\n s << name_prefix << function_name;\n\n if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)\n s << \"_setter\";\n else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)\n s << \"_getter\";\n\n s << \"(\";\n\n if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {\n s << meta_function->ownerClass()->qualifiedCppName() << \"* theWrappedObject\"; \n if (meta_function->arguments().size() != 0) {\n s << \", \";\n }\n }\n \n writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);\n\n \/\/ The extra arguments...\n for (int i=0; i 0 || meta_function->arguments().size() != 0)\n s << \", \";\n s << extra_arguments.at(i);\n }\n\n s << \")\";\n if (meta_function->isConstant())\n s << \" const\";\n}\n\nAbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)\n{\n AbstractMetaFunctionList functions = meta_class->queryFunctions( \n AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic\n | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements\n );\n AbstractMetaFunctionList functions2 = meta_class->queryFunctions( \n AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible\n | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements\n );\n QSet set1 = QSet::fromList(functions);\n foreach(AbstractMetaFunction* func, functions2) {\n set1.insert(func);\n }\n\n AbstractMetaFunctionList resultFunctions;\n\n foreach(AbstractMetaFunction* func, set1.toList()) {\n if (!func->isAbstract() && func->implementingClass()==meta_class) {\n resultFunctions << func;\n }\n }\n return resultFunctions;\n}\n\nAbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)\n{\n AbstractMetaFunctionList functions = meta_class->queryFunctions( \n AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible\n\/\/ | AbstractMetaClass::NotRemovedFromTargetLang\n );\n return functions;\n}\n\nAbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)\n{\n AbstractMetaFunctionList functions; \n AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class); \n foreach(AbstractMetaFunction* func, functions1) {\n if (!func->isPublic() || func->isVirtual()) {\n functions << func;\n }\n }\n return functions;\n}\n\n\/*!\nWrites the include defined by \\a inc to \\a stream.\n*\/\nvoid ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)\n{\n if (inc.name.isEmpty())\n return;\n if (inc.type == Include::TargetLangImport)\n return;\n stream << \"#include \";\n if (inc.type == Include::IncludePath)\n stream << \"<\";\n else\n stream << \"\\\"\";\n stream << inc.name;\n if (inc.type == Include::IncludePath)\n stream << \">\";\n else\n stream << \"\\\"\";\n stream << endl;\n}\n\n\/*!\nReturns true if the given function \\a fun is operator>>() or\noperator<<() that streams from\/to a Q{Data,Text}Stream, false\notherwise.\n*\/\nbool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)\n{\n return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)\n && (fun->arguments().size() == 1)\n && (((fun->originalName() == \"operator>>\") && (fun->modifiedName() == \"readFrom\"))\n || ((fun->originalName() == \"operator<<\") && (fun->modifiedName() == \"writeTo\"))));\n}\n\nbool ShellGenerator::isBuiltIn(const QString& name) {\n\n static QSet builtIn;\n if (builtIn.isEmpty()) {\n builtIn.insert(\"Qt\");\n builtIn.insert(\"QFont\");\n builtIn.insert(\"QPixmap\");\n builtIn.insert(\"QBrush\");\n builtIn.insert(\"QBitArray\");\n builtIn.insert(\"QPalette\");\n builtIn.insert(\"QPen\");\n builtIn.insert(\"QIcon\");\n builtIn.insert(\"QImage\");\n builtIn.insert(\"QPolygon\");\n builtIn.insert(\"QRegion\");\n builtIn.insert(\"QBitmap\");\n builtIn.insert(\"QCursor\");\n builtIn.insert(\"QColor\");\n builtIn.insert(\"QSizePolicy\");\n builtIn.insert(\"QKeySequence\");\n builtIn.insert(\"QTextLength\");\n builtIn.insert(\"QTextFormat\");\n builtIn.insert(\"QMatrix\");\n builtIn.insert(\"QDate\");\n builtIn.insert(\"QTime\");\n builtIn.insert(\"QDateTime\");\n builtIn.insert(\"QUrl\");\n builtIn.insert(\"QLocale\");\n builtIn.insert(\"QRect\");\n builtIn.insert(\"QRectF\");\n builtIn.insert(\"QSize\");\n builtIn.insert(\"QSizeF\");\n builtIn.insert(\"QLine\");\n builtIn.insert(\"QLineF\");\n builtIn.insert(\"QPoint\");\n builtIn.insert(\"QPointF\");\n builtIn.insert(\"QRegExp\");\n }\n return builtIn.contains(name);\n}\n\nadded alphabetic sorting\/****************************************************************************\n**\n** Copyright (C) 2008-2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Script Generator project on Qt Labs.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"shellgenerator.h\"\n#include \"reporthandler.h\"\n\n#include \"metaqtscript.h\"\n\nbool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const\n{\n uint cg = meta_class->typeEntry()->codeGeneration();\n if (meta_class->name().startsWith(\"QtScript\")) return false;\n if (meta_class->name().startsWith(\"QFuture\")) return false;\n if (meta_class->name().startsWith(\"Global\")) return false;\n if (meta_class->name().startsWith(\"QStyleOptionComplex\")) return false;\n if (meta_class->name().startsWith(\"QTextLayout\")) return false;\n \/\/if (meta_class->name().startsWith(\"QTextStream\")) return false; \/\/ because of >> operators\n \/\/if (meta_class->name().startsWith(\"QDataStream\")) return false; \/\/ \"\n return ((cg & TypeEntry::GenerateCode) != 0);\n}\n\nvoid ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)\n{\n if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {\n s << type->originalTypeDescription();\n return;\n }\n\n if (type->isArray()) {\n writeTypeInfo(s, type->arrayElementType(), options);\n if (options & ArrayAsPointer) {\n s << \"*\";\n } else {\n s << \"[\" << type->arrayElementCount() << \"]\";\n }\n return;\n }\n\n const TypeEntry *te = type->typeEntry();\n\n if (type->isConstant() && !(options & ExcludeConst))\n s << \"const \";\n\n if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {\n s << \"int\";\n } else if (te->isFlags()) {\n s << ((FlagsTypeEntry *) te)->originalName();\n } else {\n s << fixCppTypeName(te->qualifiedCppName());\n }\n\n if (type->instantiations().size() > 0\n && (!type->isContainer() \n || (static_cast(te))->type() != ContainerTypeEntry::StringListContainer)) {\n s << '<';\n QList args = type->instantiations();\n bool nested_template = false;\n for (int i=0; iisContainer();\n writeTypeInfo(s, args.at(i));\n }\n if (nested_template)\n s << ' ';\n s << '>';\n }\n\n s << QString(type->indirections(), '*');\n\n if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))\n s << \"&\";\n \n if (type->isReference() && (options & ConvertReferenceToPtr)) {\n s << \"*\";\n }\n \n\n if (!(options & SkipName))\n s << ' ';\n}\n\n\nvoid ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,\n const AbstractMetaArgumentList &arguments,\n Option option,\n int numArguments)\n{\n if (numArguments < 0) numArguments = arguments.size();\n\n for (int i=0; itype(), option);\n if (!(option & SkipName))\n s << \" \" << arg->argumentName();\n if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) {\n s << \" = \"; \n\n QString expr = arg->originalDefaultValueExpression();\n if (expr != \"0\") {\n QString qualifier;\n if (arg->type()->typeEntry()->isEnum() && expr.indexOf(\"::\") < 0) {\n qualifier = ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();\n } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf(\"::\") < 0) {\n qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();\n }\n if (!qualifier.isEmpty()) {\n s << qualifier << \"::\";\n }\n }\n if (expr.contains(\"defaultConnection\")) {\n expr.replace(\"defaultConnection\",\"QSqlDatabase::defaultConnection\");\n }\n if (expr == \"MediaSource()\") {\n expr = \"Phonon::MediaSource()\";\n }\n s << expr; \n }\n }\n}\n\n\/*!\n * Writes the function \\a meta_function signature to the textstream \\a s.\n *\n * The \\a name_prefix can be used to give the function name a prefix,\n * like \"__public_\" or \"__override_\" and \\a classname_prefix can\n * be used to give the class name a prefix.\n *\n * The \\a option flags can be used to tweak various parameters, such as\n * showing static, original vs renamed name, underscores for space etc.\n *\n * The \\a extra_arguments list is a list of extra arguments on the\n * form \"bool static_call\".\n *\/\n\nvoid ShellGenerator::writeFunctionSignature(QTextStream &s,\n const AbstractMetaFunction *meta_function,\n const AbstractMetaClass *implementor,\n const QString &name_prefix,\n Option option,\n const QString &classname_prefix,\n const QStringList &extra_arguments,\n int numArguments)\n{\n\/\/ ### remove the implementor\n AbstractMetaType *function_type = meta_function->type();\n\n\n if ((option & SkipReturnType) == 0) {\n if (function_type) {\n writeTypeInfo(s, function_type, option);\n s << \" \";\n } else if (!meta_function->isConstructor()) {\n s << \"void \";\n }\n }\n\n if (implementor) {\n if (classname_prefix.isEmpty())\n s << wrapperClassName(implementor) << \"::\";\n else\n s << classname_prefix << implementor->name() << \"::\";\n }\n\n\n QString function_name;\n if (option & OriginalName)\n function_name = meta_function->originalName();\n else\n function_name = meta_function->name();\n\n if (option & UnderscoreSpaces)\n function_name = function_name.replace(' ', '_');\n\n if (meta_function->isConstructor())\n function_name = meta_function->ownerClass()->name();\n\n if (meta_function->isStatic() && (option & ShowStatic)) {\n function_name = \"static_\" + meta_function->ownerClass()->name() + \"_\" + function_name;\n }\n \n if (function_name.startsWith(\"operator\")) {\n function_name = meta_function->name();\n }\n\n s << name_prefix << function_name;\n\n if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)\n s << \"_setter\";\n else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)\n s << \"_getter\";\n\n s << \"(\";\n\n if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {\n s << meta_function->ownerClass()->qualifiedCppName() << \"* theWrappedObject\"; \n if (meta_function->arguments().size() != 0) {\n s << \", \";\n }\n }\n \n writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);\n\n \/\/ The extra arguments...\n for (int i=0; i 0 || meta_function->arguments().size() != 0)\n s << \", \";\n s << extra_arguments.at(i);\n }\n\n s << \")\";\n if (meta_function->isConstant())\n s << \" const\";\n}\n\nAbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)\n{\n AbstractMetaFunctionList functions = meta_class->queryFunctions( \n AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic\n | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements\n );\n AbstractMetaFunctionList functions2 = meta_class->queryFunctions( \n AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible\n | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements\n );\n QSet set1 = QSet::fromList(functions);\n foreach(AbstractMetaFunction* func, functions2) {\n set1.insert(func);\n }\n\n AbstractMetaFunctionList resultFunctions;\n\n foreach(AbstractMetaFunction* func, set1.toList()) {\n if (!func->isAbstract() && func->implementingClass()==meta_class) {\n resultFunctions << func;\n }\n }\n qStableSort(resultFunctions);\n return resultFunctions;\n}\n\nAbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)\n{\n AbstractMetaFunctionList functions = meta_class->queryFunctions( \n AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible\n\/\/ | AbstractMetaClass::NotRemovedFromTargetLang\n );\n qStableSort(functions);\n return functions;\n}\n\nAbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)\n{\n AbstractMetaFunctionList functions; \n AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class); \n foreach(AbstractMetaFunction* func, functions1) {\n if (!func->isPublic() || func->isVirtual()) {\n functions << func;\n }\n }\n qStableSort(functions);\n return functions;\n}\n\n\/*!\nWrites the include defined by \\a inc to \\a stream.\n*\/\nvoid ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)\n{\n if (inc.name.isEmpty())\n return;\n if (inc.type == Include::TargetLangImport)\n return;\n stream << \"#include \";\n if (inc.type == Include::IncludePath)\n stream << \"<\";\n else\n stream << \"\\\"\";\n stream << inc.name;\n if (inc.type == Include::IncludePath)\n stream << \">\";\n else\n stream << \"\\\"\";\n stream << endl;\n}\n\n\/*!\nReturns true if the given function \\a fun is operator>>() or\noperator<<() that streams from\/to a Q{Data,Text}Stream, false\notherwise.\n*\/\nbool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)\n{\n return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)\n && (fun->arguments().size() == 1)\n && (((fun->originalName() == \"operator>>\") && (fun->modifiedName() == \"readFrom\"))\n || ((fun->originalName() == \"operator<<\") && (fun->modifiedName() == \"writeTo\"))));\n}\n\nbool ShellGenerator::isBuiltIn(const QString& name) {\n\n static QSet builtIn;\n if (builtIn.isEmpty()) {\n builtIn.insert(\"Qt\");\n builtIn.insert(\"QFont\");\n builtIn.insert(\"QPixmap\");\n builtIn.insert(\"QBrush\");\n builtIn.insert(\"QBitArray\");\n builtIn.insert(\"QPalette\");\n builtIn.insert(\"QPen\");\n builtIn.insert(\"QIcon\");\n builtIn.insert(\"QImage\");\n builtIn.insert(\"QPolygon\");\n builtIn.insert(\"QRegion\");\n builtIn.insert(\"QBitmap\");\n builtIn.insert(\"QCursor\");\n builtIn.insert(\"QColor\");\n builtIn.insert(\"QSizePolicy\");\n builtIn.insert(\"QKeySequence\");\n builtIn.insert(\"QTextLength\");\n builtIn.insert(\"QTextFormat\");\n builtIn.insert(\"QMatrix\");\n builtIn.insert(\"QDate\");\n builtIn.insert(\"QTime\");\n builtIn.insert(\"QDateTime\");\n builtIn.insert(\"QUrl\");\n builtIn.insert(\"QLocale\");\n builtIn.insert(\"QRect\");\n builtIn.insert(\"QRectF\");\n builtIn.insert(\"QSize\");\n builtIn.insert(\"QSizeF\");\n builtIn.insert(\"QLine\");\n builtIn.insert(\"QLineF\");\n builtIn.insert(\"QPoint\");\n builtIn.insert(\"QPointF\");\n builtIn.insert(\"QRegExp\");\n }\n return builtIn.contains(name);\n}\n\n<|endoftext|>"} {"text":"Add the initial template of the first part of question 3.7<|endoftext|>"} {"text":"#include \"Logging.h\"\n#include \"WebInterface.h\"\n#include \n#include \n#include \n#include \n#include \"JSON.h\"\n#include \n\nusing namespace Dumais::WebServer;\n\nWebInterface::WebInterface(int port,RESTInterface *pRESTInterface, WebNotificationEngine *pWebNotificationEngine)\n{\n mpRESTInterface = pRESTInterface;\n\/\/ mpWebNotificationEngine = pWebNotificationEngine;\n mPort = port;\n mpWebServer = 0;\n mpThread = 0;\n}\n\nWebInterface::~WebInterface()\n{\n if (mpWebServer) delete mpWebServer;\n mpWebServer = 0;\n}\n\n\nvoid WebInterface::configure(Dumais::JSON::JSON& config)\n{\n this->mPasswdFile = config[\"passwd\"].str();\n}\n\nvoid WebInterface::stop()\n{\n if (mpWebServer)\n {\n Logging::log(\"Attempting to shutdown Web server\");\n mpWebServer->stop();\n }\n if (mpThread) mpThread->join();\n}\n\nvoid WebInterface::onConnectionOpen()\n{\n\/\/ Logging::log(\"WebInterface::onConnectionOpen(%i)\",sock);\n if (mpWebServer->getConnectionCount()>10) Logging::log(\"WARNING: There are %i connections opened on web server\",mpWebServer->getConnectionCount());\n}\n\nvoid WebInterface::onConnectionClosed()\n{\n \/\/ Logging::log(\"WebInterface::onConnectionClosed(%i)\",sock);\n\/\/ mpWebNotificationEngine->unsubscribe(sock);\n}\n\nvoid WebInterface::onResponseSent()\n{\n\/\/ mpWebNotificationEngine->activateSubscription(sock);\n}\n\nHTTPResponse* WebInterface::processHTTPRequest(HTTPRequest* request)\n{\n HTTPResponse *resp;\n\n Dumais::JSON::JSON json;\n std::string method = request->getMethod();\n if (method != \"GET\")\n {\n resp = HTTPProtocol::buildBufferedResponse(NotImplemented,\"\",\"\");\n }\n else\n {\n std::string url = request->getURL();\n \/\/ We will not support SSE anymore because we don't use it. I removed\n \/\/ the code from dumaislib to support persistant connections. There is a backup\n \/\/ in a \"backup-server-sent-events\" folder with that code\n \/*if (request->accepts(\"text\/event-stream\") && url==\"\/subscribe\")\n {\n mpWebNotificationEngine->subscribe(id);\n resp = HTTPProtocol::buildBufferedResponse(OK,\"\",\"text\/event-stream\",\"keep-alive\",\"chunked\");\n }\n else\n {*\/\n std::string responseType = \"application\/json\";\n bool queryProcessed = mpRESTInterface->processQuery(json,url);\n if (queryProcessed)\n {\n resp = HTTPProtocol::buildBufferedResponse(OK,json.stringify(false),responseType);\n }\n else\n {\n resp = HTTPProtocol::buildBufferedResponse(NotFound,\"\",\"\");\n } \n \/\/}\n }\n return resp;\n}\n\n\/\/ This server accepts one connection at a time only. So sockets are blocking\nvoid WebInterface::start()\n{\n mpWebServer = new WebServer(mPort, \"0.0.0.0\",100);\n mpWebServer->requireAuth(this->mPasswdFile.c_str(), 10);\n mpWebServer->setListener(this);\n this->mpWebServer->start();\n}\n\nadded logging for web server#include \"Logging.h\"\n#include \"WebInterface.h\"\n#include \n#include \n#include \n#include \n#include \"JSON.h\"\n#include \n#include \"WebServerLogging.h\"\n\nusing namespace Dumais::WebServer;\n\nclass WebServerInterfaceLogger: public Dumais::WebServer::IWebServerLogger\n{\n virtual void log(const std::string& ss)\n {\n Logging::log(\"%s\",ss.c_str());\n }\n};\n\n\nWebInterface::WebInterface(int port,RESTInterface *pRESTInterface, WebNotificationEngine *pWebNotificationEngine)\n{\n mpRESTInterface = pRESTInterface;\n Dumais::WebServer::WebServerLogging::logger = new WebServerInterfaceLogger();\n\/\/ mpWebNotificationEngine = pWebNotificationEngine;\n mPort = port;\n mpWebServer = 0;\n mpThread = 0;\n}\n\nWebInterface::~WebInterface()\n{\n if (mpWebServer) delete mpWebServer;\n mpWebServer = 0;\n}\n\n\nvoid WebInterface::configure(Dumais::JSON::JSON& config)\n{\n this->mPasswdFile = config[\"passwd\"].str();\n}\n\nvoid WebInterface::stop()\n{\n if (mpWebServer)\n {\n Logging::log(\"Attempting to shutdown Web server\");\n mpWebServer->stop();\n }\n if (mpThread) mpThread->join();\n}\n\nvoid WebInterface::onConnectionOpen()\n{\n\/\/ Logging::log(\"WebInterface::onConnectionOpen(%i)\",sock);\n if (mpWebServer->getConnectionCount()>10) Logging::log(\"WARNING: There are %i connections opened on web server\",mpWebServer->getConnectionCount());\n}\n\nvoid WebInterface::onConnectionClosed()\n{\n \/\/ Logging::log(\"WebInterface::onConnectionClosed(%i)\",sock);\n\/\/ mpWebNotificationEngine->unsubscribe(sock);\n}\n\nvoid WebInterface::onResponseSent()\n{\n\/\/ mpWebNotificationEngine->activateSubscription(sock);\n}\n\nHTTPResponse* WebInterface::processHTTPRequest(HTTPRequest* request)\n{\n HTTPResponse *resp;\n\n Dumais::JSON::JSON json;\n std::string method = request->getMethod();\n if (method != \"GET\")\n {\n resp = HTTPProtocol::buildBufferedResponse(NotImplemented,\"\",\"\");\n }\n else\n {\n std::string url = request->getURL();\n \/\/ We will not support SSE anymore because we don't use it. I removed\n \/\/ the code from dumaislib to support persistant connections. There is a backup\n \/\/ in a \"backup-server-sent-events\" folder with that code\n \/*if (request->accepts(\"text\/event-stream\") && url==\"\/subscribe\")\n {\n mpWebNotificationEngine->subscribe(id);\n resp = HTTPProtocol::buildBufferedResponse(OK,\"\",\"text\/event-stream\",\"keep-alive\",\"chunked\");\n }\n else\n {*\/\n std::string responseType = \"application\/json\";\n bool queryProcessed = mpRESTInterface->processQuery(json,url);\n if (queryProcessed)\n {\n resp = HTTPProtocol::buildBufferedResponse(OK,json.stringify(false),responseType);\n }\n else\n {\n resp = HTTPProtocol::buildBufferedResponse(NotFound,\"\",\"\");\n } \n \/\/}\n }\n return resp;\n}\n\n\/\/ This server accepts one connection at a time only. So sockets are blocking\nvoid WebInterface::start()\n{\n mpWebServer = new WebServer(mPort, \"0.0.0.0\",100);\n mpWebServer->requireAuth(this->mPasswdFile.c_str(), 10);\n mpWebServer->setListener(this);\n this->mpWebServer->start();\n}\n\n<|endoftext|>"} {"text":"\/* Copyright (c) 2016, the Cap authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n *\/\n\n#define BOOST_TEST_MODULE EnergyStorageDevice\n\n#include \"main.cc\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ list of valid inputs to build an EnergyStorageDevice\n\/\/ These are meant as example\nstd::list const valid_device_input = {\n \"series_rc.info\", \"parallel_rc.info\",\n#ifdef WITH_DEAL_II\n \"super_capacitor.info\",\n#endif\n};\n\nBOOST_AUTO_TEST_CASE(test_energy_storage_device_builders)\n{\n boost::mpi::communicator world;\n int const size = world.size();\n int const rank = world.rank();\n std::cout << \"hello world from rank \" << rank << \" of size \" << size << \"\\n\";\n for (auto const &filename : valid_device_input)\n {\n boost::property_tree::ptree ptree;\n boost::property_tree::info_parser::read_info(filename, ptree);\n BOOST_CHECK_NO_THROW(cap::EnergyStorageDevice::build(world, ptree));\n }\n\n \/\/ invalid type must throw an exception\n boost::property_tree::ptree ptree;\n ptree.put(\"type\", \"InvalidDeviceType\");\n BOOST_CHECK_THROW(cap::EnergyStorageDevice::build(world, ptree),\n std::runtime_error);\n}\n\nclass ExampleInspector : public cap::EnergyStorageDeviceInspector\n{\npublic:\n \/\/ get the device type and set the voltage to 1.4 volt\n void inspect(cap::EnergyStorageDevice *device)\n {\n \/\/ use dynamic_cast to find out the actual type\n if (dynamic_cast(device) != nullptr)\n _type = \"SeriesRC\";\n else if (dynamic_cast(device) != nullptr)\n _type = \"ParallelRC\";\n else\n throw std::runtime_error(\"not an equivalent circuit model\");\n \/\/ if we make ExampleInspector friend of the derived\n \/\/ class for the EnergyStorageDevice we could virtually\n \/\/ do anything\n device->evolve_one_time_step_constant_voltage(1.0, 1.4);\n }\n \/\/ the type of the device last inspected\n std::string _type;\n};\n\nBOOST_AUTO_TEST_CASE(test_energy_storage_device_inspectors)\n{\n std::string const filename = \"series_rc.info\";\n boost::mpi::communicator world;\n boost::property_tree::ptree ptree;\n boost::property_tree::info_parser::read_info(filename, ptree);\n auto device = cap::EnergyStorageDevice::build(world, ptree);\n double voltage;\n device->get_voltage(voltage);\n BOOST_TEST(voltage != 1.4);\n ExampleInspector inspector;\n device->inspect(&inspector);\n BOOST_TEST((inspector._type).compare(\"SeriesRC\") == 0);\n device->get_voltage(voltage);\n BOOST_TEST(voltage == 1.4);\n}\n\n\/\/ TODO: won't work for SuperCapacitor\n#ifdef WITH_DEAL_II\nBOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(test_serialization, 1)\n#endif\n\nBOOST_AUTO_TEST_CASE(test_serialization)\n{\n for (auto const &filename : valid_device_input)\n {\n boost::property_tree::ptree ptree;\n boost::property_tree::info_parser::read_info(filename, ptree);\n std::shared_ptr original_device =\n cap::EnergyStorageDevice::build(boost::mpi::communicator(), ptree);\n\n original_device->evolve_one_time_step_constant_voltage(0.1, 2.1);\n double original_voltage;\n double original_current;\n original_device->get_voltage(original_voltage);\n original_device->get_current(original_current);\n\n try\n {\n std::stringstream ss;\n \/\/ save device\n boost::archive::text_oarchive oa(ss);\n oa.register_type();\n oa.register_type();\n oa << original_device;\n \/\/ print the content of the stream to the screen\n std::cout << ss.str() << \"\\n\";\n BOOST_CHECK(!ss.str().empty());\n\n \/\/ restore device\n boost::archive::text_iarchive ia(ss);\n ia.register_type();\n ia.register_type();\n std::shared_ptr restored_device;\n ia >> restored_device;\n double restored_voltage;\n double restored_current;\n restored_device->get_voltage(restored_voltage);\n restored_device->get_current(restored_current);\n BOOST_CHECK_EQUAL(original_voltage, restored_voltage);\n BOOST_CHECK_EQUAL(original_current, restored_current);\n }\n catch (boost::archive::archive_exception e)\n {\n BOOST_TEST_MESSAGE(\"unable to serialize the device\");\n BOOST_TEST(false);\n }\n catch (...)\n {\n throw std::runtime_error(\"unexpected exception occured\");\n }\n }\n}\nImprove test_energy_storage_device.\/* Copyright (c) 2016, the Cap authors.\n *\n * This file is subject to the Modified BSD License and may not be distributed\n * without copyright and license information. Please refer to the file LICENSE\n * for the text and further information on this license.\n *\/\n\n#define BOOST_TEST_MODULE EnergyStorageDevice\n\n#include \"main.cc\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ list of valid inputs to build an EnergyStorageDevice\n\/\/ These are meant as example\nstd::list const valid_device_input = {\n \"series_rc.info\", \"parallel_rc.info\",\n#ifdef WITH_DEAL_II\n \"super_capacitor.info\",\n#endif\n};\n\nBOOST_AUTO_TEST_CASE(test_energy_storage_device_builders)\n{\n boost::mpi::communicator world;\n int const size = world.size();\n int const rank = world.rank();\n std::cout << \"hello world from rank \" << rank << \" of size \" << size << \"\\n\";\n for (auto const &filename : valid_device_input)\n {\n boost::property_tree::ptree ptree;\n boost::property_tree::info_parser::read_info(filename, ptree);\n BOOST_CHECK_NO_THROW(cap::EnergyStorageDevice::build(world, ptree));\n }\n\n \/\/ invalid type must throw an exception\n boost::property_tree::ptree ptree;\n ptree.put(\"type\", \"InvalidDeviceType\");\n BOOST_CHECK_THROW(cap::EnergyStorageDevice::build(world, ptree),\n std::runtime_error);\n}\n\nclass ExampleInspector : public cap::EnergyStorageDeviceInspector\n{\npublic:\n \/\/ get the device type and set the voltage to 1.4 volt\n void inspect(cap::EnergyStorageDevice *device)\n {\n \/\/ use dynamic_cast to find out the actual type\n if (dynamic_cast(device) != nullptr)\n _type = \"SeriesRC\";\n else if (dynamic_cast(device) != nullptr)\n _type = \"ParallelRC\";\n else\n throw std::runtime_error(\"not an equivalent circuit model\");\n \/\/ if we make ExampleInspector friend of the derived\n \/\/ class for the EnergyStorageDevice we could virtually\n \/\/ do anything\n device->evolve_one_time_step_constant_voltage(1.0, 1.4);\n }\n \/\/ the type of the device last inspected\n std::string _type;\n};\n\nBOOST_AUTO_TEST_CASE(test_energy_storage_device_inspectors)\n{\n std::vector filename(2);\n filename[0] = \"series_rc.info\";\n filename[1] = \"parallel_rc.info\";\n std::vector RC_type(2);\n RC_type[0] = \"SeriesRC\";\n RC_type[1] = \"ParallelRC\";\n for (unsigned int i = 0; i < 2; ++i)\n {\n boost::mpi::communicator world;\n boost::property_tree::ptree ptree;\n boost::property_tree::info_parser::read_info(filename[i], ptree);\n auto device = cap::EnergyStorageDevice::build(world, ptree);\n double voltage;\n device->get_voltage(voltage);\n BOOST_TEST(voltage != 1.4);\n ExampleInspector inspector;\n device->inspect(&inspector);\n BOOST_TEST((inspector._type).compare(RC_type[i]) == 0);\n device->get_voltage(voltage);\n BOOST_TEST(voltage == 1.4);\n }\n}\n\n\/\/ TODO: won't work for SuperCapacitor\n#ifdef WITH_DEAL_II\nBOOST_AUTO_TEST_CASE_EXPECTED_FAILURES(test_serialization, 1)\n#endif\n\nBOOST_AUTO_TEST_CASE(test_serialization)\n{\n for (auto const &filename : valid_device_input)\n {\n boost::property_tree::ptree ptree;\n boost::property_tree::info_parser::read_info(filename, ptree);\n std::shared_ptr original_device =\n cap::EnergyStorageDevice::build(boost::mpi::communicator(), ptree);\n\n original_device->evolve_one_time_step_constant_voltage(0.1, 2.1);\n double original_voltage;\n double original_current;\n original_device->get_voltage(original_voltage);\n original_device->get_current(original_current);\n\n try\n {\n std::stringstream ss;\n \/\/ save device\n boost::archive::text_oarchive oa(ss);\n oa.register_type();\n oa.register_type();\n oa << original_device;\n \/\/ print the content of the stream to the screen\n std::cout << ss.str() << \"\\n\";\n BOOST_CHECK(!ss.str().empty());\n\n \/\/ restore device\n boost::archive::text_iarchive ia(ss);\n ia.register_type();\n ia.register_type();\n std::shared_ptr restored_device;\n ia >> restored_device;\n double restored_voltage;\n double restored_current;\n restored_device->get_voltage(restored_voltage);\n restored_device->get_current(restored_current);\n BOOST_CHECK_EQUAL(original_voltage, restored_voltage);\n BOOST_CHECK_EQUAL(original_current, restored_current);\n }\n catch (boost::archive::archive_exception e)\n {\n BOOST_TEST_MESSAGE(\"unable to serialize the device\");\n BOOST_TEST(false);\n }\n catch (...)\n {\n throw std::runtime_error(\"unexpected exception occured\");\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2010-2016, MIT Probabilistic Computing Project\n*\n* Lead Developers: Dan Lovell and Jay Baxter\n* Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka\n* Research Leads: Vikash Mansinghka, Patrick Shafto\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#define __STDC_CONSTANT_MACROS \/\/ Make define UINT64_C &c.\n\n#include \n#include \n#include \n#include \n\n#include \"RandomNumberGenerator.h\"\n\nstatic inline unsigned bitcount64(uint64_t x) {\n \/\/ Count two-bit groups.\n x -= ((x >> 1) & UINT64_C(0x5555555555555555));\n\n \/\/ Add to four-bit groups, carefully masking carries and garbage.\n x = ((x >> 2) & UINT64_C(0x3333333333333333)) +\n (x & UINT64_C(0x3333333333333333));\n\n \/\/ Add to eight-bit groups.\n x = (((x >> 4) + x) & UINT64_C(0x0f0f0f0f0f0f0f0f));\n\n \/\/ Add all eight-bit groups in the leftmost column of a multiply.\n \/\/ Bit counts are small enough no other columns will carry.\n return (x * UINT64_C(0x0101010101010101)) >> 56;\n}\n\nstatic inline unsigned clz64(uint64_t x) {\n \/\/ Round up to a power of two minus one.\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x |= x >> 32;\n\n \/\/ Count the bits thus set, and subtract from 64 to count leading\n \/\/ zeros.\n return 64 - bitcount64(x);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ return a random real between\n\/\/ 0 and 1 with uniform dist\ndouble RandomNumberGenerator::next() {\n int e = -64;\n uint64_t s;\n unsigned d;\n\n \/\/ Draw a significand from an infinite stream of bits.\n while ((s = crypto_weakprng_64(&_weakprng)) == 0) {\n e -= 64;\n \/\/ Just return zero if the exponent is so small there are no\n \/\/ floating-point numbers that tiny.\n if (e < -1074)\n return 0;\n }\n\n \/\/ Shift leading zeros into the exponent and fill trailing bits of\n \/\/ significand uniformly at random.\n if ((d = clz64(s)) != 0) {\n e -= d;\n s <<= d;\n s |= crypto_weakprng_64(&_weakprng) >> (64 - d);\n }\n\n \/\/ Set sticky bit, since there is (almost surely) another 1 in the\n \/\/ bit stream, to avoid a bias toward `even'.\n s |= 1;\n\n \/\/ Return s * 2^e.\n return ldexp(static_cast(s), e);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ return a random int bewteen\n\/\/ zero and max - 1 with uniform\n\/\/ dist if called with same max\nint RandomNumberGenerator::nexti(int bound) {\n assert(0 < bound);\n return crypto_weakprng_below(&_weakprng, bound);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ standard normal samples\n\/\/ via Box-Muller transform\ndouble RandomNumberGenerator::stdnormal() {\n double u, v;\n\n u = next();\n v = next();\n\n return sqrt(-2*log(u)) * sin(2*M_PI*v);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ standard Gamma samples\n\/\/\n\/\/ George Marsaglia & Wai Wan Tsang, `A simple method for\n\/\/ generating gamma variables', ACM Transactions on Mathematical\n\/\/ Software 26(3), September 2000. DOI: 10.1145\/358407.358414\n\/\/ URI: https:\/\/dl.acm.org\/citation.cfm?doid=358407.358414\ndouble RandomNumberGenerator::stdgamma(double alpha) {\n const double d = alpha - (double)1\/3;\n const double c = 1\/sqrt(9*d);\n double x, u, v;\n\n assert(1 <= alpha);\n\n for (;;) {\n x = stdnormal();\n v = 1 + x*c;\n if (v <= 0)\n continue;\n v = v*v*v;\n\n u = next();\n if (u < 1 - 0.0331*((x*x)*(x*x)) ||\n log(u) < x*x\/2 + d - d*v + d*log(v))\n return d*v;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ chi^2 samples\ndouble RandomNumberGenerator::chisquare(double nu) {\n double shape = nu\/2;\n double scale = 2;\n\n return scale*stdgamma(shape);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Student's t-distribution samples\ndouble RandomNumberGenerator::student_t(double nu) {\n return stdnormal() * sqrt(nu\/chisquare(nu));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ control the seed\nvoid RandomNumberGenerator::set_seed(std::time_t seed) {\n uint8_t seedbuf[crypto_weakprng_SEEDBYTES] = {0};\n size_t i;\n\n for (i = 0; i < std::min(sizeof seedbuf, sizeof seed); i++)\n seedbuf[i] = seed >> (8*i);\n crypto_weakprng_seed(&_weakprng, seedbuf);\n}\nProphylactically grab the alpha boosting note from Marsaglia and Tsang.\/*\n* Copyright (c) 2010-2016, MIT Probabilistic Computing Project\n*\n* Lead Developers: Dan Lovell and Jay Baxter\n* Authors: Dan Lovell, Baxter Eaves, Jay Baxter, Vikash Mansinghka\n* Research Leads: Vikash Mansinghka, Patrick Shafto\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#define __STDC_CONSTANT_MACROS \/\/ Make define UINT64_C &c.\n\n#include \n#include \n#include \n#include \n\n#include \"RandomNumberGenerator.h\"\n\nstatic inline unsigned bitcount64(uint64_t x) {\n \/\/ Count two-bit groups.\n x -= ((x >> 1) & UINT64_C(0x5555555555555555));\n\n \/\/ Add to four-bit groups, carefully masking carries and garbage.\n x = ((x >> 2) & UINT64_C(0x3333333333333333)) +\n (x & UINT64_C(0x3333333333333333));\n\n \/\/ Add to eight-bit groups.\n x = (((x >> 4) + x) & UINT64_C(0x0f0f0f0f0f0f0f0f));\n\n \/\/ Add all eight-bit groups in the leftmost column of a multiply.\n \/\/ Bit counts are small enough no other columns will carry.\n return (x * UINT64_C(0x0101010101010101)) >> 56;\n}\n\nstatic inline unsigned clz64(uint64_t x) {\n \/\/ Round up to a power of two minus one.\n x |= x >> 1;\n x |= x >> 2;\n x |= x >> 4;\n x |= x >> 8;\n x |= x >> 16;\n x |= x >> 32;\n\n \/\/ Count the bits thus set, and subtract from 64 to count leading\n \/\/ zeros.\n return 64 - bitcount64(x);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ return a random real between\n\/\/ 0 and 1 with uniform dist\ndouble RandomNumberGenerator::next() {\n int e = -64;\n uint64_t s;\n unsigned d;\n\n \/\/ Draw a significand from an infinite stream of bits.\n while ((s = crypto_weakprng_64(&_weakprng)) == 0) {\n e -= 64;\n \/\/ Just return zero if the exponent is so small there are no\n \/\/ floating-point numbers that tiny.\n if (e < -1074)\n return 0;\n }\n\n \/\/ Shift leading zeros into the exponent and fill trailing bits of\n \/\/ significand uniformly at random.\n if ((d = clz64(s)) != 0) {\n e -= d;\n s <<= d;\n s |= crypto_weakprng_64(&_weakprng) >> (64 - d);\n }\n\n \/\/ Set sticky bit, since there is (almost surely) another 1 in the\n \/\/ bit stream, to avoid a bias toward `even'.\n s |= 1;\n\n \/\/ Return s * 2^e.\n return ldexp(static_cast(s), e);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ return a random int bewteen\n\/\/ zero and max - 1 with uniform\n\/\/ dist if called with same max\nint RandomNumberGenerator::nexti(int bound) {\n assert(0 < bound);\n return crypto_weakprng_below(&_weakprng, bound);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ standard normal samples\n\/\/ via Box-Muller transform\ndouble RandomNumberGenerator::stdnormal() {\n double u, v;\n\n u = next();\n v = next();\n\n return sqrt(-2*log(u)) * sin(2*M_PI*v);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ standard Gamma samples\n\/\/\n\/\/ George Marsaglia & Wai Wan Tsang, `A simple method for\n\/\/ generating gamma variables', ACM Transactions on Mathematical\n\/\/ Software 26(3), September 2000. DOI: 10.1145\/358407.358414\n\/\/ URI: https:\/\/dl.acm.org\/citation.cfm?doid=358407.358414\ndouble RandomNumberGenerator::stdgamma(double alpha) {\n const double d = alpha - (double)1\/3;\n const double c = 1\/sqrt(9*d);\n double x, u, v;\n\n \/\/ The clients currently do not need alpha < 1. Should they, the\n \/\/ reference contains a note (at the end of Section 6) on how to\n \/\/ boost the alpha parameter:\n \/\/ stdgamma(alpha) = stdgamma(alpha+1) * (uniform() ** (1\/alpha))\n assert(1 <= alpha);\n\n for (;;) {\n x = stdnormal();\n v = 1 + x*c;\n if (v <= 0)\n continue;\n v = v*v*v;\n\n u = next();\n if (u < 1 - 0.0331*((x*x)*(x*x)) ||\n log(u) < x*x\/2 + d - d*v + d*log(v))\n return d*v;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ chi^2 samples\ndouble RandomNumberGenerator::chisquare(double nu) {\n double shape = nu\/2;\n double scale = 2;\n\n return scale*stdgamma(shape);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Student's t-distribution samples\ndouble RandomNumberGenerator::student_t(double nu) {\n return stdnormal() * sqrt(nu\/chisquare(nu));\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ control the seed\nvoid RandomNumberGenerator::set_seed(std::time_t seed) {\n uint8_t seedbuf[crypto_weakprng_SEEDBYTES] = {0};\n size_t i;\n\n for (i = 0; i < std::min(sizeof seedbuf, sizeof seed); i++)\n seedbuf[i] = seed >> (8*i);\n crypto_weakprng_seed(&_weakprng, seedbuf);\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2009 Dan Leinir Turthra Jensen \n * Copyright (c) 2010 Arjen Hiemstra <>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"propertywidget.h\"\n\nusing namespace GluonCreator;\n\n#include \"propertywidget.h\"\n#include \"propertywidgetitem.h\"\n#include \"propertywidgetitemfactory.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nclass PropertyWidget::PropertyWidgetPrivate\n{\n public:\n PropertyWidgetPrivate()\n {\n object = 0;\n layout = 0;\n }\n GluonCore::GluonObject *object;\n QVBoxLayout *layout;\n\n void appendMetaObject(QWidget* parent, QObject* object, QGridLayout* layout);\n};\n\n\nPropertyWidget::PropertyWidget(QWidget* parent): QScrollArea(parent), d(new PropertyWidgetPrivate)\n{\n}\n\nPropertyWidget::~PropertyWidget()\n{\n delete d;\n}\n\nGluonCore::GluonObject *PropertyWidget::object() const\n{\n return d->object;\n}\n\nvoid PropertyWidget::setObject(GluonCore::GluonObject * object)\n{\n if (object)\n {\n d->object = object;\n d->layout = new QVBoxLayout(this);\n d->layout->setSpacing(0);\n d->layout->setContentsMargins(0, 0, 0, 0);\n d->layout->setAlignment(Qt::AlignTop);\n\n appendObject(object, true);\n for (int i = 0; i < object->children().count(); i++)\n {\n appendObject(object->child(i));\n }\n d->layout->addStretch();\n\n QWidget * containerWidget = new QWidget(this);\n containerWidget->setLayout(d->layout);\n\n setWidget(containerWidget);\n setWidgetResizable(true);\n }\n}\n\nvoid PropertyWidget::clear()\n{\n delete widget();\n}\n\nvoid PropertyWidget::appendObject(GluonCore::GluonObject *obj, bool first)\n{\n if (!first && obj->metaObject()->className() == QString(\"GluonEngine::GameObject\"))\n {\n return;\n }\n\n QString classname = obj->metaObject()->className();\n classname = classname.right(classname.length() - classname.lastIndexOf(':') - 1);\n #ifdef __GNUC__\n #warning We will need to replace the group box with a custom widget of some type, as we cannot collapse it. Unfortunate, but such is life ;)\n #endif\n QGroupBox* objectBox = new QGroupBox(classname, this);\n\n objectBox->setFlat(true);\n objectBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n if (first)\n {\n long addr = reinterpret_cast(obj);\n QColor color;\n color.setHsv(addr % 255, 255, 192);\n objectBox->setPalette(QPalette(color));\n }\n\n d->layout->addWidget(objectBox);\n\n QGridLayout* boxLayout = new QGridLayout(objectBox);\n boxLayout->setSpacing(0);\n boxLayout->setContentsMargins(0, 0, 0, 0);\n objectBox->setLayout(boxLayout);\n\n d->appendMetaObject(this, obj, boxLayout);\n}\n\nvoid PropertyWidget::PropertyWidgetPrivate::appendMetaObject(QWidget *parent, QObject *object, QGridLayout* layout)\n{\n QString propertyName;\n QString propertyDescription;\n QVariant propertyValue;\n\n const QMetaObject *metaObject = object->metaObject();\n QMetaProperty metaProperty;\n\n int row;\n int count = metaObject->propertyCount();\n for (int i = 0; i < count; ++i)\n {\n row = layout->rowCount();\n metaProperty = metaObject->property(i);\n\n if (metaProperty.name() == QString(\"objectName\"))\n continue;\n\n QLabel * nameLabel = new QLabel(parent);\n nameLabel->setText(metaProperty.name());\n nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n layout->addWidget(nameLabel, row, 0);\n\n PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, metaProperty.typeName(), parent);\n editWidget->setEditObject(object);\n editWidget->setEditProperty(metaProperty.name());\n connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)));\n editWidget->setMinimumWidth(250);\n editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n layout->addWidget(editWidget, row, 1);\n }\n\n foreach(const QByteArray &propName, object->dynamicPropertyNames())\n {\n QString thePropName(propName);\n row = layout->rowCount();\n QLabel * nameLabel = new QLabel(parent);\n nameLabel->setText(thePropName);\n nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n layout->addWidget(nameLabel, row, 0);\n\n PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, object->property(propName).typeName(), parent);\n editWidget->setEditObject(object);\n editWidget->setEditProperty(thePropName);\n connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)));\n editWidget->setMinimumWidth(250);\n editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n layout->addWidget(editWidget);\n }\n}\n\n#include \"propertywidget.moc\"\nRemove the obsolete colouring code\/******************************************************************************\n * This file is part of the Gluon Development Platform\n * Copyright (c) 2009 Dan Leinir Turthra Jensen \n * Copyright (c) 2010 Arjen Hiemstra <>\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \"propertywidget.h\"\n\nusing namespace GluonCreator;\n\n#include \"propertywidget.h\"\n#include \"propertywidgetitem.h\"\n#include \"propertywidgetitemfactory.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nclass PropertyWidget::PropertyWidgetPrivate\n{\n public:\n PropertyWidgetPrivate()\n {\n object = 0;\n layout = 0;\n }\n GluonCore::GluonObject *object;\n QVBoxLayout *layout;\n\n void appendMetaObject(QWidget* parent, QObject* object, QGridLayout* layout);\n};\n\n\nPropertyWidget::PropertyWidget(QWidget* parent): QScrollArea(parent), d(new PropertyWidgetPrivate)\n{\n}\n\nPropertyWidget::~PropertyWidget()\n{\n delete d;\n}\n\nGluonCore::GluonObject *PropertyWidget::object() const\n{\n return d->object;\n}\n\nvoid PropertyWidget::setObject(GluonCore::GluonObject * object)\n{\n if (object)\n {\n d->object = object;\n d->layout = new QVBoxLayout(this);\n d->layout->setSpacing(0);\n d->layout->setContentsMargins(0, 0, 0, 0);\n d->layout->setAlignment(Qt::AlignTop);\n\n appendObject(object, true);\n for (int i = 0; i < object->children().count(); i++)\n {\n appendObject(object->child(i));\n }\n d->layout->addStretch();\n\n QWidget * containerWidget = new QWidget(this);\n containerWidget->setLayout(d->layout);\n\n setWidget(containerWidget);\n setWidgetResizable(true);\n }\n}\n\nvoid PropertyWidget::clear()\n{\n delete widget();\n}\n\nvoid PropertyWidget::appendObject(GluonCore::GluonObject *obj, bool first)\n{\n if (!first && obj->metaObject()->className() == QString(\"GluonEngine::GameObject\"))\n {\n return;\n }\n\n QString classname = obj->metaObject()->className();\n classname = classname.right(classname.length() - classname.lastIndexOf(':') - 1);\n #ifdef __GNUC__\n #warning We will need to replace the group box with a custom widget of some type, as we cannot collapse it. Unfortunate, but such is life ;)\n #endif\n QGroupBox* objectBox = new QGroupBox(classname, this);\n\n objectBox->setFlat(true);\n objectBox->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);\n\n d->layout->addWidget(objectBox);\n\n QGridLayout* boxLayout = new QGridLayout(objectBox);\n boxLayout->setSpacing(0);\n boxLayout->setContentsMargins(0, 0, 0, 0);\n objectBox->setLayout(boxLayout);\n\n d->appendMetaObject(this, obj, boxLayout);\n}\n\nvoid PropertyWidget::PropertyWidgetPrivate::appendMetaObject(QWidget *parent, QObject *object, QGridLayout* layout)\n{\n QString propertyName;\n QString propertyDescription;\n QVariant propertyValue;\n\n const QMetaObject *metaObject = object->metaObject();\n QMetaProperty metaProperty;\n\n int row;\n int count = metaObject->propertyCount();\n for (int i = 0; i < count; ++i)\n {\n row = layout->rowCount();\n metaProperty = metaObject->property(i);\n\n if (metaProperty.name() == QString(\"objectName\"))\n continue;\n\n QLabel * nameLabel = new QLabel(parent);\n nameLabel->setText(metaProperty.name());\n nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n layout->addWidget(nameLabel, row, 0);\n\n PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, metaProperty.typeName(), parent);\n editWidget->setEditObject(object);\n editWidget->setEditProperty(metaProperty.name());\n connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)));\n editWidget->setMinimumWidth(250);\n editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n layout->addWidget(editWidget, row, 1);\n }\n\n foreach(const QByteArray &propName, object->dynamicPropertyNames())\n {\n QString thePropName(propName);\n row = layout->rowCount();\n QLabel * nameLabel = new QLabel(parent);\n nameLabel->setText(thePropName);\n nameLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter);\n layout->addWidget(nameLabel, row, 0);\n\n PropertyWidgetItem *editWidget = PropertyWidgetItemFactory::instance()->create(object, object->property(propName).typeName(), parent);\n editWidget->setEditObject(object);\n editWidget->setEditProperty(thePropName);\n connect(editWidget, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)), parent, SIGNAL(propertyChanged(QObject*, QString, QVariant, QVariant)));\n editWidget->setMinimumWidth(250);\n editWidget->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);\n layout->addWidget(editWidget, row, 1);\n }\n}\n\n#include \"propertywidget.moc\"\n<|endoftext|>"} {"text":"\/* This file is part of Zanshin\n\n Copyright 2014 Kevin Ottens \n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"akonaditagqueries.h\"\n\n\n#include \"akonadicollectionfetchjobinterface.h\"\n#include \"akonadiitemfetchjobinterface.h\"\n#include \"akonaditagfetchjobinterface.h\"\n\n#include \"akonadimonitorimpl.h\"\n#include \"akonadiserializer.h\"\n#include \"akonadistorage.h\"\n\n#include \"utils\/jobhandler.h\"\n\nusing namespace Akonadi;\n\nTagQueries::TagQueries(QObject *parent)\n : QObject(parent),\n m_storage(new Storage),\n m_serializer(new Serializer),\n m_monitor(new MonitorImpl),\n m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes),\n m_ownInterfaces(true)\n{\n connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag)));\n\n connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item)));\n connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item)));\n connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item)));\n}\n\nTagQueries::TagQueries(StorageInterface *storage, SerializerInterface *serializer, MonitorInterface *monitor)\n : m_storage(storage),\n m_serializer(serializer),\n m_monitor(monitor),\n m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes),\n m_ownInterfaces(false)\n{\n connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag)));\n\n connect(monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item)));\n connect(monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item)));\n connect(monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item)));\n}\n\nTagQueries::~TagQueries()\n{\n if (m_ownInterfaces) {\n delete m_storage;\n delete m_serializer;\n delete m_monitor;\n }\n}\n\nvoid TagQueries::setApplicationMode(TagQueries::ApplicationMode mode)\n{\n if (mode == TasksOnly) {\n m_fetchContentTypeFilter = StorageInterface::Tasks;\n } else if (mode == NotesOnly) {\n m_fetchContentTypeFilter = StorageInterface::Notes;\n }\n}\n\nTagQueries::TagResult::Ptr TagQueries::findAll() const\n{\n if (!m_findAll) {\n {\n TagQueries *self = const_cast(this);\n self->m_findAll = self->createTagQuery();\n }\n\n m_findAll->setFetchFunction([this] (const TagQuery::AddFunction &add) {\n TagFetchJobInterface *job = m_storage->fetchTags();\n Utils::JobHandler::install(job->kjob(), [this, job, add] {\n for (Akonadi::Tag tag : job->tags())\n add(tag);\n });\n });\n\n m_findAll->setConvertFunction([this] (const Akonadi::Tag &tag) {\n return m_serializer->createTagFromAkonadiTag(tag);\n });\n\n m_findAll->setUpdateFunction([this] (const Akonadi::Tag &akonadiTag, Domain::Tag::Ptr &tag) {\n m_serializer->updateTagFromAkonadiTag(tag, akonadiTag);\n });\n m_findAll->setPredicateFunction([this] (const Akonadi::Tag &akonadiTag) {\n return akonadiTag.type() == Akonadi::Tag::PLAIN;\n });\n m_findAll->setRepresentsFunction([this] (const Akonadi::Tag &akonadiTag, const Domain::Tag::Ptr &tag) {\n return m_serializer->representsAkonadiTag(tag, akonadiTag);\n });\n }\n\n return m_findAll->result();\n}\n\nTagQueries::ArtifactResult::Ptr TagQueries::findTopLevelArtifacts(Domain::Tag::Ptr tag) const\n{\n Akonadi::Tag akonadiTag = m_serializer->createAkonadiTagFromTag(tag);\n if (!m_findTopLevel.contains(akonadiTag.id())) {\n ArtifactQuery::Ptr query;\n {\n TagQueries *self = const_cast(this);\n query = self->createArtifactQuery();\n self->m_findTopLevel.insert(akonadiTag.id(), query);\n }\n\n query->setFetchFunction([this, akonadiTag] (const ArtifactQuery::AddFunction &add) {\n CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(),\n StorageInterface::Recursive,\n m_fetchContentTypeFilter);\n Utils::JobHandler::install(job->kjob(), [this, job, add] {\n if (job->kjob()->error() != KJob::NoError)\n return;\n\n for (auto collection : job->collections()) {\n ItemFetchJobInterface *job = m_storage->fetchItems(collection);\n Utils::JobHandler::install(job->kjob(), [this, job, add] {\n if (job->kjob()->error() != KJob::NoError)\n return;\n\n for (auto item : job->items())\n add(item);\n });\n }\n });\n });\n query->setConvertFunction([this] (const Akonadi::Item &item) {\n if (m_serializer->isTaskItem(item)) {\n auto task = m_serializer->createTaskFromItem(item);\n return Domain::Artifact::Ptr(task);\n\n } else if (m_serializer->isNoteItem(item)) {\n auto note = m_serializer->createNoteFromItem(item);\n return Domain::Artifact::Ptr(note);\n\n } else {\n return Domain::Artifact::Ptr();\n }\n });\n query->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Artifact::Ptr &artifact) {\n if (auto task = artifact.dynamicCast()) {\n m_serializer->updateTaskFromItem(task, item);\n } else if (auto note = artifact.dynamicCast()) {\n m_serializer->updateNoteFromItem(note, item);\n }\n });\n query->setPredicateFunction([this, tag] (const Akonadi::Item &item) {\n return m_serializer->isTagChild(tag, item);\n });\n query->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Artifact::Ptr &artifact) {\n return m_serializer->representsItem(artifact, item);\n });\n }\n\n return m_findTopLevel.value(akonadiTag.id())->result();\n}\n\nvoid TagQueries::onTagAdded(const Tag &tag)\n{\n foreach (const TagQuery::Ptr &query, m_tagQueries)\n query->onAdded(tag);\n}\n\nvoid TagQueries::onTagRemoved(const Tag &tag)\n{\n foreach (const TagQuery::Ptr &query, m_tagQueries)\n query->onRemoved(tag);\n}\n\nvoid TagQueries::onTagChanged(const Tag &tag)\n{\n foreach (const TagQuery::Ptr &query, m_tagQueries)\n query->onChanged(tag);\n}\n\nvoid TagQueries::onItemAdded(const Item &item)\n{\n foreach (const ArtifactQuery::Ptr &query, m_artifactQueries)\n query->onAdded(item);\n}\n\nvoid TagQueries::onItemRemoved(const Item &item)\n{\n Q_UNUSED(item);\n}\n\nvoid TagQueries::onItemChanged(const Item &item)\n{\n foreach (const ArtifactQuery::Ptr &query, m_artifactQueries)\n query->onChanged(item);\n}\n\nTagQueries::TagQuery::Ptr TagQueries::createTagQuery()\n{\n auto query = TagQueries::TagQuery::Ptr::create();\n m_tagQueries << query;\n return query;\n}\n\nTagQueries::ArtifactQuery::Ptr TagQueries::createArtifactQuery()\n{\n auto query = TagQueries::ArtifactQuery::Ptr::create();\n m_artifactQueries << query;\n return query;\n}\nAvoid an endless loop in tagqueries.\/* This file is part of Zanshin\n\n Copyright 2014 Kevin Ottens \n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n USA.\n*\/\n\n#include \"akonaditagqueries.h\"\n\n\n#include \"akonadicollectionfetchjobinterface.h\"\n#include \"akonadiitemfetchjobinterface.h\"\n#include \"akonaditagfetchjobinterface.h\"\n\n#include \"akonadimonitorimpl.h\"\n#include \"akonadiserializer.h\"\n#include \"akonadistorage.h\"\n\n#include \"utils\/jobhandler.h\"\n\nusing namespace Akonadi;\n\nTagQueries::TagQueries(QObject *parent)\n : QObject(parent),\n m_storage(new Storage),\n m_serializer(new Serializer),\n m_monitor(new MonitorImpl),\n m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes),\n m_ownInterfaces(true)\n{\n connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag)));\n\n connect(m_monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item)));\n connect(m_monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item)));\n connect(m_monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item)));\n}\n\nTagQueries::TagQueries(StorageInterface *storage, SerializerInterface *serializer, MonitorInterface *monitor)\n : m_storage(storage),\n m_serializer(serializer),\n m_monitor(monitor),\n m_fetchContentTypeFilter(StorageInterface::Tasks|StorageInterface::Notes),\n m_ownInterfaces(false)\n{\n connect(m_monitor, SIGNAL(tagAdded(Akonadi::Tag)), this, SLOT(onTagAdded(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagRemoved(Akonadi::Tag)), this, SLOT(onTagRemoved(Akonadi::Tag)));\n connect(m_monitor, SIGNAL(tagChanged(Akonadi::Tag)), this, SLOT(onTagChanged(Akonadi::Tag)));\n\n connect(monitor, SIGNAL(itemAdded(Akonadi::Item)), this, SLOT(onItemAdded(Akonadi::Item)));\n connect(monitor, SIGNAL(itemRemoved(Akonadi::Item)), this, SLOT(onItemRemoved(Akonadi::Item)));\n connect(monitor, SIGNAL(itemChanged(Akonadi::Item)), this, SLOT(onItemChanged(Akonadi::Item)));\n}\n\nTagQueries::~TagQueries()\n{\n if (m_ownInterfaces) {\n delete m_storage;\n delete m_serializer;\n delete m_monitor;\n }\n}\n\nvoid TagQueries::setApplicationMode(TagQueries::ApplicationMode mode)\n{\n if (mode == TasksOnly) {\n m_fetchContentTypeFilter = StorageInterface::Tasks;\n } else if (mode == NotesOnly) {\n m_fetchContentTypeFilter = StorageInterface::Notes;\n }\n}\n\nTagQueries::TagResult::Ptr TagQueries::findAll() const\n{\n if (!m_findAll) {\n {\n TagQueries *self = const_cast(this);\n self->m_findAll = self->createTagQuery();\n }\n\n m_findAll->setFetchFunction([this] (const TagQuery::AddFunction &add) {\n TagFetchJobInterface *job = m_storage->fetchTags();\n Utils::JobHandler::install(job->kjob(), [this, job, add] {\n for (Akonadi::Tag tag : job->tags())\n add(tag);\n });\n });\n\n m_findAll->setConvertFunction([this] (const Akonadi::Tag &tag) {\n return m_serializer->createTagFromAkonadiTag(tag);\n });\n\n m_findAll->setUpdateFunction([this] (const Akonadi::Tag &akonadiTag, Domain::Tag::Ptr &tag) {\n m_serializer->updateTagFromAkonadiTag(tag, akonadiTag);\n });\n m_findAll->setPredicateFunction([this] (const Akonadi::Tag &akonadiTag) {\n return akonadiTag.type() == Akonadi::Tag::PLAIN;\n });\n m_findAll->setRepresentsFunction([this] (const Akonadi::Tag &akonadiTag, const Domain::Tag::Ptr &tag) {\n return m_serializer->representsAkonadiTag(tag, akonadiTag);\n });\n }\n\n return m_findAll->result();\n}\n\nTagQueries::ArtifactResult::Ptr TagQueries::findTopLevelArtifacts(Domain::Tag::Ptr tag) const\n{\n Akonadi::Tag akonadiTag = m_serializer->createAkonadiTagFromTag(tag);\n if (!m_findTopLevel.contains(akonadiTag.id())) {\n ArtifactQuery::Ptr query;\n {\n TagQueries *self = const_cast(this);\n query = self->createArtifactQuery();\n self->m_findTopLevel.insert(akonadiTag.id(), query);\n }\n\n query->setFetchFunction([this, akonadiTag] (const ArtifactQuery::AddFunction &add) {\n CollectionFetchJobInterface *job = m_storage->fetchCollections(Akonadi::Collection::root(),\n StorageInterface::Recursive,\n m_fetchContentTypeFilter);\n Utils::JobHandler::install(job->kjob(), [this, job, add] {\n if (job->kjob()->error() != KJob::NoError)\n return;\n\n for (auto collection : job->collections()) {\n ItemFetchJobInterface *job = m_storage->fetchItems(collection);\n Utils::JobHandler::install(job->kjob(), [this, job, add] {\n if (job->kjob()->error() != KJob::NoError)\n return;\n\n for (auto item : job->items())\n add(item);\n });\n }\n });\n });\n query->setConvertFunction([this] (const Akonadi::Item &item) {\n if (m_serializer->isTaskItem(item)) {\n auto task = m_serializer->createTaskFromItem(item);\n return Domain::Artifact::Ptr(task);\n\n } else if (m_serializer->isNoteItem(item)) {\n auto note = m_serializer->createNoteFromItem(item);\n return Domain::Artifact::Ptr(note);\n\n }\n \/\/The conversion must never fail, otherwise we create an endless loop (child of invalid node is invalid).\n \/\/We therefore catch this case in the predicate.\n Q_ASSERT(false);\n return Domain::Artifact::Ptr();\n });\n query->setUpdateFunction([this] (const Akonadi::Item &item, Domain::Artifact::Ptr &artifact) {\n if (auto task = artifact.dynamicCast()) {\n m_serializer->updateTaskFromItem(task, item);\n } else if (auto note = artifact.dynamicCast()) {\n m_serializer->updateNoteFromItem(note, item);\n }\n });\n query->setPredicateFunction([this, tag] (const Akonadi::Item &item) {\n if (m_serializer->isTaskItem(item)) {\n return false;\n }\n if (!m_serializer->isNoteItem(item)) {\n return false;\n }\n return m_serializer->isTagChild(tag, item);\n });\n query->setRepresentsFunction([this] (const Akonadi::Item &item, const Domain::Artifact::Ptr &artifact) {\n return m_serializer->representsItem(artifact, item);\n });\n }\n\n return m_findTopLevel.value(akonadiTag.id())->result();\n}\n\nvoid TagQueries::onTagAdded(const Tag &tag)\n{\n foreach (const TagQuery::Ptr &query, m_tagQueries)\n query->onAdded(tag);\n}\n\nvoid TagQueries::onTagRemoved(const Tag &tag)\n{\n foreach (const TagQuery::Ptr &query, m_tagQueries)\n query->onRemoved(tag);\n}\n\nvoid TagQueries::onTagChanged(const Tag &tag)\n{\n foreach (const TagQuery::Ptr &query, m_tagQueries)\n query->onChanged(tag);\n}\n\nvoid TagQueries::onItemAdded(const Item &item)\n{\n foreach (const ArtifactQuery::Ptr &query, m_artifactQueries)\n query->onAdded(item);\n}\n\nvoid TagQueries::onItemRemoved(const Item &item)\n{\n Q_UNUSED(item);\n}\n\nvoid TagQueries::onItemChanged(const Item &item)\n{\n foreach (const ArtifactQuery::Ptr &query, m_artifactQueries)\n query->onChanged(item);\n}\n\nTagQueries::TagQuery::Ptr TagQueries::createTagQuery()\n{\n auto query = TagQueries::TagQuery::Ptr::create();\n m_tagQueries << query;\n return query;\n}\n\nTagQueries::ArtifactQuery::Ptr TagQueries::createArtifactQuery()\n{\n auto query = TagQueries::ArtifactQuery::Ptr::create();\n m_artifactQueries << query;\n return query;\n}\n<|endoftext|>"} {"text":"\/*\r\n * This file is part of `et engine`\r\n * Copyright 2009-2013 by Sergey Reznik\r\n * Please, do not modify content without approval.\r\n *\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace et;\r\n\r\nclass et::TextureFactoryPrivate\r\n{\r\npublic:\r\n\tstruct Loader : public ObjectLoader\r\n\t{\r\n\t\tTextureFactory* owner;\r\n\r\n\t\tLoader(TextureFactory* aOwner) : \r\n\t\t\towner(aOwner) { }\r\n\r\n\t\tvoid reloadObject(LoadableObject::Pointer o, ObjectsCache& c)\r\n\t\t\t{ owner->reloadObject(o, c); }\r\n\t};\r\n\r\n\tIntrusivePtr loader;\r\n\r\n\tTextureFactoryPrivate(TextureFactory* owner) : \r\n\t\tloader(new Loader(owner)) { } \r\n};\r\n\r\nTextureFactory::TextureFactory(RenderContext* rc) :\r\n\tAPIObjectFactory(rc)\r\n{\r\n\t_private = new TextureFactoryPrivate(this);\r\n\t_loadingThread = new TextureLoadingThread(this);\r\n}\r\n\r\nTextureFactory::~TextureFactory()\r\n{\r\n\t_loadingThread->stop();\r\n\t_loadingThread->waitForTermination();\r\n\r\n\tdelete _private;\r\n}\r\n\r\nObjectLoader::Pointer TextureFactory::objectLoader()\r\n{\r\n\treturn _private->loader;\r\n}\r\n\r\nTexture TextureFactory::loadTexture(const std::string& fileName, ObjectsCache& cache,\r\n\tbool async, TextureLoaderDelegate* delegate)\r\n{\r\n\tif (fileName.length() == 0)\r\n\t\treturn Texture();\r\n\t\r\n\tCriticalSectionScope lock(_csTextureLoading);\r\n\t\r\n\tstd::string file = application().environment().resolveScalableFileName(fileName,\r\n\t\trenderContext()->screenScaleFactor());\r\n\t\r\n\tif (!fileExists(file))\r\n\t{\r\n\t\tlog::error(\"Unable to find texture file: %s\", file.c_str());\r\n\t\treturn Texture();\r\n\t}\r\n\t\r\n\tuint64_t cachedFileProperty = 0;\r\n Texture texture = cache.findAnyObject(file, &cachedFileProperty);\r\n\tif (texture.invalid())\r\n\t{\r\n\t\tTextureDescription::Pointer desc =\r\n\t\t\tasync ? et::loadTextureDescription(file, false) : et::loadTexture(file);\r\n\r\n\t\tif (desc.valid())\r\n\t\t{\r\n\t\t\tbool calledFromAnotherThread = Threading::currentThread() != threading().renderingThread();\r\n\t\t\t\r\n\t\t\ttexture = Texture(new TextureData(renderContext(), desc, desc->origin(), async || calledFromAnotherThread));\r\n\t\t\tcache.manage(texture, _private->loader);\r\n\t\t\t\r\n\t\t\tif (async)\r\n\t\t\t\t_loadingThread->addRequest(desc->origin(), texture, delegate);\r\n\t\t\telse if (calledFromAnotherThread)\r\n\t\t\t\tassert(false && \"ERROR: Unable to load texture synchronously from non-rendering thread.\");\r\n\t\t}\r\n\t\t\r\n\t}\r\n\telse\r\n\t{\r\n\t\tauto newProperty = cache.getFileProperty(file);\r\n\t\tif (cachedFileProperty != newProperty)\r\n\t\t\treloadObject(texture, cache);\r\n\t\r\n\t\tif (async)\r\n\t\t{\r\n\t\t\ttextureDidStartLoading.invokeInMainRunLoop(texture);\r\n\t\t\tif (delegate != nullptr)\r\n\t\t\t{\r\n\t\t\t\tInvocation1 i;\r\n\t\t\t\ti.setTarget(delegate, &TextureLoaderDelegate::textureDidStartLoading, texture);\r\n\t\t\t\ti.invokeInMainRunLoop();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttextureDidLoad.invokeInMainRunLoop(texture);\r\n\t\t\tif (delegate != nullptr)\r\n\t\t\t{\r\n\t\t\t\tInvocation1 i;\r\n\t\t\t\ti.setTarget(delegate, &TextureLoaderDelegate::textureDidLoad, texture);\r\n\t\t\t\ti.invokeInMainRunLoop();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n \r\n\treturn texture;\r\n}\r\n\r\nTexture TextureFactory::genTexture(uint32_t target, int32_t internalformat, const vec2i& size,\r\n\tuint32_t format, uint32_t type, const BinaryDataStorage& data, const std::string& id)\r\n{\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\t\r\n\tdesc->target = target;\r\n\t\r\n\tdesc->format = format;\r\n\tdesc->internalformat = internalformat;\r\n\tdesc->type = type;\r\n\t\r\n\tdesc->size = size;\r\n\t\r\n\tdesc->mipMapCount = 1;\r\n\tdesc->layersCount = 1;\r\n\tdesc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type);\r\n\t\r\n\tdesc->data = data;\r\n\t\r\n\treturn Texture(new TextureData(renderContext(), desc, id, false));\r\n}\r\n\r\nTexture TextureFactory::genCubeTexture(int32_t internalformat, GLsizei size, uint32_t format, uint32_t type,\r\n\tconst std::string& id)\r\n{\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\t\r\n\tdesc->target = GL_TEXTURE_CUBE_MAP;\r\n\t\r\n\tdesc->format = format;\r\n\tdesc->internalformat = internalformat;\r\n\tdesc->type = type;\r\n\t\r\n\tdesc->size = vec2i(size);\r\n\t\r\n\tdesc->mipMapCount = 1;\r\n\tdesc->layersCount = 6;\r\n\tdesc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type);\r\n\t\r\n\tdesc->data = BinaryDataStorage(desc->layersCount * desc->dataSizeForAllMipLevels(), 0);\r\n\t\r\n\treturn Texture(new TextureData(renderContext(), desc, id, false));\r\n}\r\n\r\nTexture TextureFactory::genTexture(TextureDescription::Pointer desc)\r\n{\r\n\treturn Texture(new TextureData(renderContext(), desc, desc->origin(), false));\r\n}\r\n\r\nTexture TextureFactory::genNoiseTexture(const vec2i& size, bool norm, const std::string& id)\r\n{\r\n\tDataStorage randata(size.square());\r\n\tfor (size_t i = 0; i < randata.size(); ++i)\r\n\t{\r\n\t\tvec4 rand_f = vec4(randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f),\r\n\t\t\trandomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f));\r\n\t\t\r\n\t\trandata[i] = vec4f_to_4ub(norm ? vec4(rand_f.xyz().normalized(), rand_f.w) : rand_f);\r\n\t}\r\n\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\tdesc->data = BinaryDataStorage(4 * size.square());\r\n\tdesc->target = GL_TEXTURE_2D;\r\n\tdesc->format = GL_RGBA;\r\n\tdesc->internalformat = GL_RGBA;\r\n\tdesc->type = GL_UNSIGNED_BYTE;\r\n\tdesc->size = size;\r\n\tdesc->mipMapCount = 1;\r\n\tdesc->layersCount = 1;\r\n desc->bitsPerPixel = 32;\r\n \r\n\tetCopyMemory(desc->data.data(), randata.data(), randata.dataSize());\r\n\r\n\treturn Texture(new TextureData(renderContext(), desc, id, false));\r\n}\r\n\r\nvoid TextureFactory::textureLoadingThreadDidLoadTextureData(TextureLoadingRequest* request)\r\n{\r\n\tCriticalSectionScope lock(_csTextureLoading);\r\n\r\n\trequest->texture->updateData(renderContext(), request->textureDescription);\r\n\ttextureDidLoad.invoke(request->texture);\r\n\r\n\tif (request->delegate)\r\n\t\trequest->delegate->textureDidLoad(request->texture);\r\n\r\n\tdelete request;\r\n}\r\n\r\nTexture TextureFactory::loadTexturesToCubemap(const std::string& posx, const std::string& negx,\r\n\tconst std::string& posy, const std::string& negy, const std::string& posz, const std::string& negz,\r\n\tObjectsCache& cache)\r\n{\r\n\tTextureDescription::Pointer layers[6] = \r\n\t{\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(posx, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(negx, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(negy, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(posy, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(posz, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(negz, renderContext()->screenScaleFactor()))\r\n\t};\r\n\r\n\tint maxCubemapSize = static_cast(openGLCapabilites().maxCubemapTextureSize());\r\n\t\r\n\tfor (size_t l = 0; l < 6; ++l)\r\n\t{\r\n\t\tif (layers[l].valid())\r\n\t\t{\r\n\t\t\tif ((layers[l]->size.x > maxCubemapSize) || (layers[l]->size.y > maxCubemapSize))\r\n\t\t\t{\r\n\t\t\t\tlog::error(\"Cubemap %s size of (%d x %d) is larger than allowed %dx%d\",\r\n\t\t\t\t\tlayers[l]->origin().c_str(), layers[l]->size.x, layers[l]->size.y, maxCubemapSize, maxCubemapSize);\r\n\t\t\t\treturn Texture();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tlog::error(\"Unable to load cubemap face.\");\r\n\t\t\treturn Texture();\r\n\t\t}\r\n\t}\r\n\r\n\tstd::string texId = layers[0]->origin() + \";\";\r\n\tfor (size_t l = 1; l < 6; ++l)\r\n\t{\r\n\t\ttexId += (l < 5) ? layers[l]->origin() + \";\" : layers[l]->origin();\r\n\t\tif ((layers[l-1]->size != layers[l]->size) || \r\n\t\t\t(layers[l-1]->format != layers[l]->format) ||\r\n\t\t\t(layers[l-1]->internalformat != layers[l]->internalformat) || \r\n\t\t\t(layers[l-1]->type != layers[l]->type) || \r\n\t\t\t(layers[l-1]->mipMapCount != layers[l]->mipMapCount) || \r\n\t\t\t(layers[l-1]->compressed != layers[l]->compressed) ||\r\n\t\t\t(layers[l-1]->data.size() != layers[l]->data.size()))\r\n\t\t{\r\n\t\t\tlog::error(\"Failed to load cubemap textures. Textures `%s` and `%s` aren't identical\",\r\n\t\t\t\tlayers[l-1]->origin().c_str(), layers[l]->origin().c_str());\r\n\t\t\treturn Texture();\r\n\t\t}\r\n\t}\r\n\r\n\tsize_t layerSize = layers[0]->dataSizeForAllMipLevels();\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\tdesc->target = GL_TEXTURE_CUBE_MAP;\r\n\tdesc->layersCount = 6;\r\n\tdesc->bitsPerPixel = layers[0]->bitsPerPixel;\r\n\tdesc->channels = layers[0]->channels;\r\n\tdesc->compressed = layers[0]->compressed;\r\n\tdesc->format = layers[0]->format;\r\n\tdesc->internalformat = layers[0]->internalformat;\r\n\tdesc->mipMapCount= layers[0]->mipMapCount;\r\n\tdesc->size = layers[0]->size;\r\n\tdesc->type = layers[0]->type;\r\n\tdesc->data.resize(desc->layersCount * layerSize);\r\n\tfor (size_t l = 0; l < desc->layersCount; ++l)\r\n\t\tetCopyMemory(desc->data.element_ptr(l * layerSize), layers[l]->data.element_ptr(0), layerSize);\r\n\r\n\tTexture result(new TextureData(renderContext(), desc, texId, false));\r\n\t\r\n\tfor (size_t i = 0; i < 6; ++i)\r\n\t\tresult->addOrigin(layers[i]->origin());\r\n\t\r\n\tcache.manage(result, _private->loader);\r\n\t\r\n\treturn result;\r\n}\r\n\r\nTexture TextureFactory::createTextureWrapper(uint32_t texture, const vec2i& size, const std::string& name)\r\n{\r\n\treturn Texture(new TextureData(renderContext(), texture, size, name));\r\n}\r\n\r\nvoid TextureFactory::reloadObject(LoadableObject::Pointer object, ObjectsCache&)\r\n{\r\n\tTextureDescription::Pointer newData = et::loadTexture(object->origin());\r\n\tif (newData.valid())\r\n\t\tTexture(object)->updateData(renderContext(), newData);\r\n}\r\nassert replaced with ET_FAIL in texture factory\/*\r\n * This file is part of `et engine`\r\n * Copyright 2009-2013 by Sergey Reznik\r\n * Please, do not modify content without approval.\r\n *\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nusing namespace et;\r\n\r\nclass et::TextureFactoryPrivate\r\n{\r\npublic:\r\n\tstruct Loader : public ObjectLoader\r\n\t{\r\n\t\tTextureFactory* owner;\r\n\r\n\t\tLoader(TextureFactory* aOwner) : \r\n\t\t\towner(aOwner) { }\r\n\r\n\t\tvoid reloadObject(LoadableObject::Pointer o, ObjectsCache& c)\r\n\t\t\t{ owner->reloadObject(o, c); }\r\n\t};\r\n\r\n\tIntrusivePtr loader;\r\n\r\n\tTextureFactoryPrivate(TextureFactory* owner) : \r\n\t\tloader(new Loader(owner)) { } \r\n};\r\n\r\nTextureFactory::TextureFactory(RenderContext* rc) :\r\n\tAPIObjectFactory(rc)\r\n{\r\n\t_private = new TextureFactoryPrivate(this);\r\n\t_loadingThread = new TextureLoadingThread(this);\r\n}\r\n\r\nTextureFactory::~TextureFactory()\r\n{\r\n\t_loadingThread->stop();\r\n\t_loadingThread->waitForTermination();\r\n\r\n\tdelete _private;\r\n}\r\n\r\nObjectLoader::Pointer TextureFactory::objectLoader()\r\n{\r\n\treturn _private->loader;\r\n}\r\n\r\nTexture TextureFactory::loadTexture(const std::string& fileName, ObjectsCache& cache,\r\n\tbool async, TextureLoaderDelegate* delegate)\r\n{\r\n\tif (fileName.length() == 0)\r\n\t\treturn Texture();\r\n\t\r\n\tCriticalSectionScope lock(_csTextureLoading);\r\n\t\r\n\tstd::string file = application().environment().resolveScalableFileName(fileName,\r\n\t\trenderContext()->screenScaleFactor());\r\n\t\r\n\tif (!fileExists(file))\r\n\t{\r\n\t\tlog::error(\"Unable to find texture file: %s\", file.c_str());\r\n\t\treturn Texture();\r\n\t}\r\n\t\r\n\tuint64_t cachedFileProperty = 0;\r\n Texture texture = cache.findAnyObject(file, &cachedFileProperty);\r\n\tif (texture.invalid())\r\n\t{\r\n\t\tTextureDescription::Pointer desc =\r\n\t\t\tasync ? et::loadTextureDescription(file, false) : et::loadTexture(file);\r\n\r\n\t\tif (desc.valid())\r\n\t\t{\r\n\t\t\tbool calledFromAnotherThread = Threading::currentThread() != threading().renderingThread();\r\n\t\t\t\r\n\t\t\ttexture = Texture(new TextureData(renderContext(), desc, desc->origin(), async || calledFromAnotherThread));\r\n\t\t\tcache.manage(texture, _private->loader);\r\n\t\t\t\r\n\t\t\tif (async)\r\n\t\t\t\t_loadingThread->addRequest(desc->origin(), texture, delegate);\r\n\t\t\telse if (calledFromAnotherThread)\r\n\t\t\t\tET_FAIL(\"ERROR: Unable to load texture synchronously from non-rendering thread.\");\r\n\t\t}\r\n\t\t\r\n\t}\r\n\telse\r\n\t{\r\n\t\tauto newProperty = cache.getFileProperty(file);\r\n\t\tif (cachedFileProperty != newProperty)\r\n\t\t\treloadObject(texture, cache);\r\n\t\r\n\t\tif (async)\r\n\t\t{\r\n\t\t\ttextureDidStartLoading.invokeInMainRunLoop(texture);\r\n\t\t\tif (delegate != nullptr)\r\n\t\t\t{\r\n\t\t\t\tInvocation1 i;\r\n\t\t\t\ti.setTarget(delegate, &TextureLoaderDelegate::textureDidStartLoading, texture);\r\n\t\t\t\ti.invokeInMainRunLoop();\r\n\t\t\t}\r\n\t\t\t\r\n\t\t\ttextureDidLoad.invokeInMainRunLoop(texture);\r\n\t\t\tif (delegate != nullptr)\r\n\t\t\t{\r\n\t\t\t\tInvocation1 i;\r\n\t\t\t\ti.setTarget(delegate, &TextureLoaderDelegate::textureDidLoad, texture);\r\n\t\t\t\ti.invokeInMainRunLoop();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t}\r\n \r\n\treturn texture;\r\n}\r\n\r\nTexture TextureFactory::genTexture(uint32_t target, int32_t internalformat, const vec2i& size,\r\n\tuint32_t format, uint32_t type, const BinaryDataStorage& data, const std::string& id)\r\n{\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\t\r\n\tdesc->target = target;\r\n\t\r\n\tdesc->format = format;\r\n\tdesc->internalformat = internalformat;\r\n\tdesc->type = type;\r\n\t\r\n\tdesc->size = size;\r\n\t\r\n\tdesc->mipMapCount = 1;\r\n\tdesc->layersCount = 1;\r\n\tdesc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type);\r\n\t\r\n\tdesc->data = data;\r\n\t\r\n\treturn Texture(new TextureData(renderContext(), desc, id, false));\r\n}\r\n\r\nTexture TextureFactory::genCubeTexture(int32_t internalformat, GLsizei size, uint32_t format, uint32_t type,\r\n\tconst std::string& id)\r\n{\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\t\r\n\tdesc->target = GL_TEXTURE_CUBE_MAP;\r\n\t\r\n\tdesc->format = format;\r\n\tdesc->internalformat = internalformat;\r\n\tdesc->type = type;\r\n\t\r\n\tdesc->size = vec2i(size);\r\n\t\r\n\tdesc->mipMapCount = 1;\r\n\tdesc->layersCount = 6;\r\n\tdesc->bitsPerPixel = bitsPerPixelForTextureFormat(internalformat, type);\r\n\t\r\n\tdesc->data = BinaryDataStorage(desc->layersCount * desc->dataSizeForAllMipLevels(), 0);\r\n\t\r\n\treturn Texture(new TextureData(renderContext(), desc, id, false));\r\n}\r\n\r\nTexture TextureFactory::genTexture(TextureDescription::Pointer desc)\r\n{\r\n\treturn Texture(new TextureData(renderContext(), desc, desc->origin(), false));\r\n}\r\n\r\nTexture TextureFactory::genNoiseTexture(const vec2i& size, bool norm, const std::string& id)\r\n{\r\n\tDataStorage randata(size.square());\r\n\tfor (size_t i = 0; i < randata.size(); ++i)\r\n\t{\r\n\t\tvec4 rand_f = vec4(randomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f),\r\n\t\t\trandomFloat(-1.0f, 1.0f), randomFloat(-1.0f, 1.0f));\r\n\t\t\r\n\t\trandata[i] = vec4f_to_4ub(norm ? vec4(rand_f.xyz().normalized(), rand_f.w) : rand_f);\r\n\t}\r\n\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\tdesc->data = BinaryDataStorage(4 * size.square());\r\n\tdesc->target = GL_TEXTURE_2D;\r\n\tdesc->format = GL_RGBA;\r\n\tdesc->internalformat = GL_RGBA;\r\n\tdesc->type = GL_UNSIGNED_BYTE;\r\n\tdesc->size = size;\r\n\tdesc->mipMapCount = 1;\r\n\tdesc->layersCount = 1;\r\n desc->bitsPerPixel = 32;\r\n \r\n\tetCopyMemory(desc->data.data(), randata.data(), randata.dataSize());\r\n\r\n\treturn Texture(new TextureData(renderContext(), desc, id, false));\r\n}\r\n\r\nvoid TextureFactory::textureLoadingThreadDidLoadTextureData(TextureLoadingRequest* request)\r\n{\r\n\tCriticalSectionScope lock(_csTextureLoading);\r\n\r\n\trequest->texture->updateData(renderContext(), request->textureDescription);\r\n\ttextureDidLoad.invoke(request->texture);\r\n\r\n\tif (request->delegate)\r\n\t\trequest->delegate->textureDidLoad(request->texture);\r\n\r\n\tdelete request;\r\n}\r\n\r\nTexture TextureFactory::loadTexturesToCubemap(const std::string& posx, const std::string& negx,\r\n\tconst std::string& posy, const std::string& negy, const std::string& posz, const std::string& negz,\r\n\tObjectsCache& cache)\r\n{\r\n\tTextureDescription::Pointer layers[6] = \r\n\t{\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(posx, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(negx, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(negy, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(posy, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(posz, renderContext()->screenScaleFactor())),\r\n\t\tet::loadTexture(application().environment().resolveScalableFileName(negz, renderContext()->screenScaleFactor()))\r\n\t};\r\n\r\n\tint maxCubemapSize = static_cast(openGLCapabilites().maxCubemapTextureSize());\r\n\t\r\n\tfor (size_t l = 0; l < 6; ++l)\r\n\t{\r\n\t\tif (layers[l].valid())\r\n\t\t{\r\n\t\t\tif ((layers[l]->size.x > maxCubemapSize) || (layers[l]->size.y > maxCubemapSize))\r\n\t\t\t{\r\n\t\t\t\tlog::error(\"Cubemap %s size of (%d x %d) is larger than allowed %dx%d\",\r\n\t\t\t\t\tlayers[l]->origin().c_str(), layers[l]->size.x, layers[l]->size.y, maxCubemapSize, maxCubemapSize);\r\n\t\t\t\treturn Texture();\r\n\t\t\t}\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tlog::error(\"Unable to load cubemap face.\");\r\n\t\t\treturn Texture();\r\n\t\t}\r\n\t}\r\n\r\n\tstd::string texId = layers[0]->origin() + \";\";\r\n\tfor (size_t l = 1; l < 6; ++l)\r\n\t{\r\n\t\ttexId += (l < 5) ? layers[l]->origin() + \";\" : layers[l]->origin();\r\n\t\tif ((layers[l-1]->size != layers[l]->size) || \r\n\t\t\t(layers[l-1]->format != layers[l]->format) ||\r\n\t\t\t(layers[l-1]->internalformat != layers[l]->internalformat) || \r\n\t\t\t(layers[l-1]->type != layers[l]->type) || \r\n\t\t\t(layers[l-1]->mipMapCount != layers[l]->mipMapCount) || \r\n\t\t\t(layers[l-1]->compressed != layers[l]->compressed) ||\r\n\t\t\t(layers[l-1]->data.size() != layers[l]->data.size()))\r\n\t\t{\r\n\t\t\tlog::error(\"Failed to load cubemap textures. Textures `%s` and `%s` aren't identical\",\r\n\t\t\t\tlayers[l-1]->origin().c_str(), layers[l]->origin().c_str());\r\n\t\t\treturn Texture();\r\n\t\t}\r\n\t}\r\n\r\n\tsize_t layerSize = layers[0]->dataSizeForAllMipLevels();\r\n\tTextureDescription::Pointer desc(new TextureDescription);\r\n\tdesc->target = GL_TEXTURE_CUBE_MAP;\r\n\tdesc->layersCount = 6;\r\n\tdesc->bitsPerPixel = layers[0]->bitsPerPixel;\r\n\tdesc->channels = layers[0]->channels;\r\n\tdesc->compressed = layers[0]->compressed;\r\n\tdesc->format = layers[0]->format;\r\n\tdesc->internalformat = layers[0]->internalformat;\r\n\tdesc->mipMapCount= layers[0]->mipMapCount;\r\n\tdesc->size = layers[0]->size;\r\n\tdesc->type = layers[0]->type;\r\n\tdesc->data.resize(desc->layersCount * layerSize);\r\n\tfor (size_t l = 0; l < desc->layersCount; ++l)\r\n\t\tetCopyMemory(desc->data.element_ptr(l * layerSize), layers[l]->data.element_ptr(0), layerSize);\r\n\r\n\tTexture result(new TextureData(renderContext(), desc, texId, false));\r\n\t\r\n\tfor (size_t i = 0; i < 6; ++i)\r\n\t\tresult->addOrigin(layers[i]->origin());\r\n\t\r\n\tcache.manage(result, _private->loader);\r\n\t\r\n\treturn result;\r\n}\r\n\r\nTexture TextureFactory::createTextureWrapper(uint32_t texture, const vec2i& size, const std::string& name)\r\n{\r\n\treturn Texture(new TextureData(renderContext(), texture, size, name));\r\n}\r\n\r\nvoid TextureFactory::reloadObject(LoadableObject::Pointer object, ObjectsCache&)\r\n{\r\n\tTextureDescription::Pointer newData = et::loadTexture(object->origin());\r\n\tif (newData.valid())\r\n\t\tTexture(object)->updateData(renderContext(), newData);\r\n}\r\n<|endoftext|>"} {"text":"\/*\r\ngpe_scene_particle_class.cpp\r\nThis file is part of:\r\nGAME PENCIL ENGINE\r\nhttps:\/\/create.pawbyte.com\r\nCopyright (c) 2014-2020 Nathan Hurde, Chase Lee.\r\n\r\nCopyright (c) 2014-2020 PawByte LLC.\r\nCopyright (c) 2014-2020 Game Pencil Engine contributors ( Contributors Page )\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the “Software”), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n\r\n-Game Pencil Engine \r\n\r\n\r\n*\/\r\n#include \"gpe_scene_particle_class.h\"\r\n\r\nGPE_SceneParticleEmitter::GPE_SceneParticleEmitter( GPE_GeneralResourceContainer *pFolder )\r\n{\r\n iconTexture = guiRCM->texture_add( APP_DIRECTORY_NAME+\"resources\/gfx\/iconpacks\/fontawesome\/magic.png\") ;\r\n branchType = BRANCH_TYPE_PARTIClE_EMITTER;\r\n if( projectParentFolder!=NULL)\r\n {\r\n emmitterInEditor = new GPE_DropDown_Resouce_Menu( \"Particle Emitter\",projectParentFolder->find_resource_from_name(RESOURCE_TYPE_NAMES[RESOURCE_TYPE_EMITTER]+\"s\"),-1,true);\r\n emmitterInEditor->set_width(192);\r\n }\r\n else\r\n {\r\n emmitterInEditor = NULL;\r\n }\r\n}\r\n\r\nGPE_SceneParticleEmitter::~GPE_SceneParticleEmitter()\r\n{\r\n\r\n}\r\n\r\nvoid GPE_SceneParticleEmitter::add_typed_elements()\r\n{\r\n if( PANEL_INSPECTOR!=NULL )\r\n {\r\n \/\/PANEL_INSPECTOR->add_gui_element( lightIsActive, true );\r\n }\r\n}\r\n\r\nbool GPE_SceneParticleEmitter::build_intohtml5_file(std::ofstream * fileTarget, int leftTabAmount, GPE_GeneralResourceContainer * localResTypeController )\r\n{\r\n GPE_SceneBasicClass::build_intohtml5_file( fileTarget, leftTabAmount+1, localResTypeController);\r\n return true;\r\n}\r\n\r\nvoid GPE_SceneParticleEmitter::process_elements()\r\n{\r\n GPE_SceneBasicClass::process_elements();\r\n}\r\n\r\nvoid GPE_SceneParticleEmitter::render_branch()\r\n{\r\n\r\n}\r\n\r\nbool GPE_SceneParticleEmitter::save_branch_data(std::ofstream * fileTarget, int nestedFoldersIn )\r\n{\r\n if( fileTarget!=NULL && fileTarget->is_open() )\r\n {\r\n std::string nestedTabsStr = generate_tabs( nestedFoldersIn );\r\n *fileTarget << nestedTabsStr+\" GPE_AmbientLight=\";\r\n if( xPosField!=NULL)\r\n {\r\n xPosField->make_valid_number(0);\r\n *fileTarget << xPosField->get_held_number() << \",\";\r\n }\r\n else\r\n {\r\n *fileTarget << \"-0,\";\r\n }\r\n if( yPosField!=NULL)\r\n {\r\n yPosField->make_valid_number(0);\r\n *fileTarget << yPosField->get_held_number() << \",\";\r\n }\r\n else\r\n {\r\n *fileTarget << \"-0,\";\r\n }\r\n if( branchColor!=NULL)\r\n {\r\n *fileTarget << branchColor->get_hex_string() << \",\";\r\n }\r\n else\r\n {\r\n *fileTarget << \"#FFFF00,\";\r\n }\r\n if( branchAlpha!=NULL)\r\n {\r\n *fileTarget << int_to_string( branchAlpha->get_value() )<< \",\";\r\n }\r\n else\r\n {\r\n *fileTarget << \"255,\";\r\n }\r\n *fileTarget << opName+\",,\\n\";\r\n GPE_SceneBasicClass::save_branch_data( fileTarget, nestedFoldersIn+1 );\r\n return true;\r\n }\r\n return false;\r\n}\r\nDelete gpe_scene_particle_class.cpp<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: brwview.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: oj $ $Date: 2002-05-02 07:10:09 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SBX_BRWVIEW_HXX\n#include \"brwview.hxx\"\n#endif\n#ifndef _SBA_GRID_HXX\n#include \"sbagrid.hxx\"\n#endif\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef _SV_SPLIT_HXX\n#include \n#endif\n#ifndef DBACCESS_UI_DBTREEVIEW_HXX\n#include \"dbtreeview.hxx\"\n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _DBU_RESOURCE_HRC_\n#include \"dbu_resource.hrc\"\n#endif\n#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_\n#include \n#endif\n#ifndef _SBA_BWRCTRLR_HXX\n#include \"brwctrlr.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_\n#include \n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n\n\nusing namespace dbaui;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::form;\n\/\/ using namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\n\n\nnamespace\n{\n sal_Bool isGrabVclControlFocusAllowed(const UnoDataBrowserView* _pView)\n {\n sal_Bool bGrabFocus = sal_False;\n SbaGridControl* pVclControl = _pView->getVclControl();\n Reference< ::com::sun::star::awt::XControl > xGrid = _pView->getGridControl();\n if (pVclControl && xGrid.is())\n {\n bGrabFocus = sal_True;\n if(!pVclControl->HasChildPathFocus())\n {\n Reference xChild(xGrid->getModel(),UNO_QUERY);\n Reference xLoad;\n if(xChild.is())\n xLoad = Reference(xChild->getParent(),UNO_QUERY);\n bGrabFocus = xLoad.is() && xLoad->isLoaded();\n }\n }\n return bGrabFocus;\n }\n}\n\/\/==================================================================\n\/\/= UnoDataBrowserView\n\/\/==================================================================\n\n\/\/ -------------------------------------------------------------------------\nUnoDataBrowserView::UnoDataBrowserView( Window* pParent,\n IController* _pController,\n const Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rFactory)\n :ODataView(pParent,_pController,_rFactory)\n ,m_pVclControl(NULL)\n ,m_pSplitter(NULL)\n ,m_pTreeView(NULL)\n ,m_pStatus(NULL)\n{\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::Construct(const Reference< ::com::sun::star::awt::XControlModel >& xModel)\n{\n try\n {\n ODataView::Construct();\n\n \/\/ our UNO representation\n m_xMe = VCLUnoHelper::CreateControlContainer(this);\n\n \/\/ create the (UNO-) control\n m_xGrid = new SbaXGridControl(getORB());\n DBG_ASSERT(m_xGrid.is(), \"UnoDataBrowserView::Construct : could not create a grid control !\");\n \/\/ in design mode (for the moment)\n m_xGrid->setDesignMode(sal_True);\n\n Reference< ::com::sun::star::awt::XWindow > xGridWindow(m_xGrid, UNO_QUERY);\n xGridWindow->setVisible(sal_True);\n xGridWindow->setEnable(sal_True);\n\n \/\/ introduce the model to the grid\n m_xGrid->setModel(xModel);\n \/\/ introduce the container (me) to the grid\n Reference< ::com::sun::star::beans::XPropertySet > xModelSet(xModel, UNO_QUERY);\n getContainer()->addControl(::comphelper::getString(xModelSet->getPropertyValue(PROPERTY_NAME)), m_xGrid);\n\n \/\/ get the VCL-control\n m_pVclControl = NULL;\n Reference< ::com::sun::star::awt::XWindowPeer > xPeer = m_xGrid->getPeer();\n if (xPeer.is())\n {\n SbaXGridPeer* pPeer = SbaXGridPeer::getImplementation(xPeer);\n if (pPeer)\n m_pVclControl = static_cast(pPeer->GetWindow());\n\n ::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::AddWindow));\n }\n\n DBG_ASSERT(m_pVclControl != NULL, \"UnoDataBrowserView::Construct : no real grid control !\");\n }\n catch(Exception&)\n {\n ::comphelper::disposeComponent(m_xGrid);\n throw;\n }\n}\n\/\/ -------------------------------------------------------------------------\nUnoDataBrowserView::~UnoDataBrowserView()\n{\n\n ::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n m_pVclControl = NULL;\n\n delete m_pSplitter;\n m_pSplitter = NULL;\n setTreeView(NULL);\n\n if ( m_pStatus )\n {\n delete m_pStatus;\n m_pStatus = NULL;\n }\n\n ::comphelper::disposeComponent(m_xGrid);\n ::comphelper::disposeComponent(m_xMe);\n}\n\/\/ -----------------------------------------------------------------------------\nIMPL_LINK( UnoDataBrowserView, SplitHdl, void*, p )\n{\n long nTest = m_pSplitter->GetPosPixel().Y();\n m_pSplitter->SetPosPixel( Point( m_pSplitter->GetSplitPosPixel(), m_pSplitter->GetPosPixel().Y() ) );\n Resize();\n\n return 0L;\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::setSplitter(Splitter* _pSplitter)\n{\n m_pSplitter = _pSplitter;\n m_pSplitter->SetSplitHdl( LINK( this, UnoDataBrowserView, SplitHdl ) );\n LINK( this, UnoDataBrowserView, SplitHdl ).Call(m_pSplitter);\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::setTreeView(DBTreeView* _pTreeView)\n{\n if (m_pTreeView != _pTreeView)\n {\n if (m_pTreeView)\n {\n ::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n\n Window* pDeleteIt = m_pTreeView;\n m_pTreeView = NULL;\n delete pDeleteIt;\n }\n m_pTreeView = _pTreeView;\n if ( m_pTreeView )\n ::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::AddWindow));\n }\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::showStatus( const String& _rStatus )\n{\n if (0 == _rStatus.Len())\n hideStatus();\n else\n {\n if (!m_pStatus)\n m_pStatus = new FixedText(this);\n m_pStatus->SetText(_rStatus);\n m_pStatus->Show();\n Resize();\n Update();\n }\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::hideStatus()\n{\n if (!m_pStatus || !m_pStatus->IsVisible())\n \/\/ nothing to do\n return;\n m_pStatus->Hide();\n Resize();\n Update();\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::resizeDocumentView(Rectangle& _rPlayground)\n{\n Point aSplitPos;\n Size aSplitSize;\n Point aPlaygroundPos( _rPlayground.TopLeft() );\n Size aPlaygroundSize( _rPlayground.GetSize() );\n\n if (m_pTreeView && m_pTreeView->IsVisible() && m_pSplitter)\n {\n \/\/ calculate the splitter pos and size\n aSplitPos = m_pSplitter->GetPosPixel();\n aSplitPos.Y() = aPlaygroundPos.Y();\n aSplitSize = m_pSplitter->GetOutputSizePixel();\n aSplitSize.Height() = aPlaygroundSize.Height();\n\n if( ( aSplitPos.X() + aSplitSize.Width() ) > ( aPlaygroundSize.Width() ))\n aSplitPos.X() = aPlaygroundSize.Width() - aSplitSize.Width();\n\n if( aSplitPos.X() <= aPlaygroundPos.X() )\n aSplitPos.X() = aPlaygroundPos.X() + sal_Int32(aPlaygroundSize.Width() * 0.2);\n\n \/\/ the tree pos and size\n Point aTreeViewPos( aPlaygroundPos );\n Size aTreeViewSize( aSplitPos.X(), aPlaygroundSize.Height() );\n\n \/\/ the status pos and size\n if (m_pStatus && m_pStatus->IsVisible())\n {\n Size aStatusSize(aPlaygroundPos.X(), GetTextHeight() + 2);\n aStatusSize = LogicToPixel(aStatusSize, MAP_APPFONT);\n aStatusSize.Width() = aTreeViewSize.Width() - 2 - 2;\n\n Point aStatusPos( aPlaygroundPos.X() + 2, aTreeViewPos.Y() + aTreeViewSize.Height() - aStatusSize.Height() );\n m_pStatus->SetPosSizePixel( aStatusPos, aStatusSize );\n aTreeViewSize.Height() -= aStatusSize.Height();\n }\n\n \/\/ set the size of treelistbox\n m_pTreeView->SetPosSizePixel( aTreeViewPos, aTreeViewSize );\n\n \/\/set the size of the splitter\n m_pSplitter->SetPosSizePixel( aSplitPos, Size( aSplitSize.Width(), aPlaygroundSize.Height() ) );\n m_pSplitter->SetDragRectPixel( _rPlayground );\n }\n\n \/\/ set the size of grid control\n Reference< ::com::sun::star::awt::XWindow > xGridAsWindow(m_xGrid, UNO_QUERY);\n if (xGridAsWindow.is())\n xGridAsWindow->setPosSize( aSplitPos.X() + aSplitSize.Width(), aPlaygroundPos.Y(),\n aPlaygroundSize.Width() - aSplitSize.Width() - aSplitPos.X(), aPlaygroundSize.Height(), ::com::sun::star::awt::PosSize::POSSIZE);\n\n \/\/ just for completeness: there is no space left, we occupied it all ...\n _rPlayground.SetPos( _rPlayground.BottomRight() );\n _rPlayground.SetSize( Size( 0, 0 ) );\n}\n\n\/\/------------------------------------------------------------------\nsal_uInt16 UnoDataBrowserView::Model2ViewPos(sal_uInt16 nPos) const\n{\n return m_pVclControl ? m_pVclControl->GetViewColumnPos(m_pVclControl->GetColumnIdFromModelPos(nPos)) : -1;\n}\n\n\/\/------------------------------------------------------------------\nsal_uInt16 UnoDataBrowserView::View2ModelPos(sal_uInt16 nPos) const\n{\n return m_pVclControl ? m_pVclControl->GetModelColumnPos(m_pVclControl->GetColumnIdFromViewPos(nPos)) : -1;\n}\n\n\/\/------------------------------------------------------------------\nsal_uInt16 UnoDataBrowserView::ViewColumnCount() const\n{\n return m_pVclControl ? m_pVclControl->GetViewColCount() : 0;\n}\n\n\/\/------------------------------------------------------------------\nvoid UnoDataBrowserView::GetFocus()\n{\n ODataView::GetFocus();\n if( m_pTreeView && m_pTreeView->IsVisible() && !m_pTreeView->HasChildPathFocus())\n m_pTreeView->GrabFocus();\n else if (m_pVclControl && m_xGrid.is())\n {\n sal_Bool bGrabFocus = sal_False;\n if(!m_pVclControl->HasChildPathFocus())\n {\n bGrabFocus = isGrabVclControlFocusAllowed(this);\n if( bGrabFocus )\n m_pVclControl->GrabFocus();\n }\n if(!bGrabFocus && m_pTreeView && m_pTreeView->IsVisible() )\n m_pTreeView->GrabFocus();\n }\n}\n\/\/ -------------------------------------------------------------------------\nlong UnoDataBrowserView::PreNotify( NotifyEvent& rNEvt )\n{\n long nDone = 0L;\n if(rNEvt.GetType() == EVENT_KEYINPUT)\n {\n sal_Bool bGrabAllowed = isGrabVclControlFocusAllowed(this);\n if ( bGrabAllowed )\n {\n const KeyEvent* pKeyEvt = rNEvt.GetKeyEvent();\n const KeyCode& rKeyCode = pKeyEvt->GetKeyCode();\n if( rKeyCode == KeyCode(KEY_E,TRUE,TRUE,FALSE) )\n {\n if ( m_pTreeView && m_pVclControl && m_pTreeView->HasChildPathFocus() )\n m_pVclControl->GrabFocus();\n nDone = 1L;\n }\n }\n }\n return nDone ? nDone : ODataView::PreNotify(rNEvt);\n}\n\n\/\/ -----------------------------------------------------------------------------\nBrowserViewStatusDisplay::BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus )\n :m_pView(_pView)\n{\n if (m_pView)\n m_pView->showStatus(_rStatus);\n}\n\n\/\/ -----------------------------------------------------------------------------\nBrowserViewStatusDisplay::~BrowserViewStatusDisplay( )\n{\n if (m_pView)\n m_pView->showStatus(String());\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n\n\n#101214# enable ctrl+shift+e also to switch back fromgrid to treeview\/*************************************************************************\n *\n * $RCSfile: brwview.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: oj $ $Date: 2002-07-11 10:01:56 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SBX_BRWVIEW_HXX\n#include \"brwview.hxx\"\n#endif\n#ifndef _SBA_GRID_HXX\n#include \"sbagrid.hxx\"\n#endif\n#ifndef _TOOLKIT_HELPER_VCLUNOHELPER_HXX_\n#include \n#endif\n#ifndef _COMPHELPER_TYPES_HXX_\n#include \n#endif\n#ifndef _SV_SPLIT_HXX\n#include \n#endif\n#ifndef DBACCESS_UI_DBTREEVIEW_HXX\n#include \"dbtreeview.hxx\"\n#endif\n#ifndef DBACCESS_SHARED_DBUSTRINGS_HRC\n#include \"dbustrings.hrc\"\n#endif\n#ifndef _DBAUI_MODULE_DBU_HXX_\n#include \"moduledbu.hxx\"\n#endif\n#ifndef _DBU_RESOURCE_HRC_\n#include \"dbu_resource.hrc\"\n#endif\n#ifndef _COM_SUN_STAR_FORM_XLOADABLE_HPP_\n#include \n#endif\n#ifndef _SBA_BWRCTRLR_HXX\n#include \"brwctrlr.hxx\"\n#endif\n#ifndef _COM_SUN_STAR_AWT_XCONTROLCONTAINER_HPP_\n#include \n#endif\n#ifndef DBAUI_TOOLS_HXX\n#include \"UITools.hxx\"\n#endif\n\n\nusing namespace dbaui;\nusing namespace ::com::sun::star::uno;\nusing namespace ::com::sun::star::sdb;\nusing namespace ::com::sun::star::form;\n\/\/ using namespace ::com::sun::star::sdbcx;\nusing namespace ::com::sun::star::beans;\nusing namespace ::com::sun::star::container;\n\n\nnamespace\n{\n sal_Bool isGrabVclControlFocusAllowed(const UnoDataBrowserView* _pView)\n {\n sal_Bool bGrabFocus = sal_False;\n SbaGridControl* pVclControl = _pView->getVclControl();\n Reference< ::com::sun::star::awt::XControl > xGrid = _pView->getGridControl();\n if (pVclControl && xGrid.is())\n {\n bGrabFocus = sal_True;\n if(!pVclControl->HasChildPathFocus())\n {\n Reference xChild(xGrid->getModel(),UNO_QUERY);\n Reference xLoad;\n if(xChild.is())\n xLoad = Reference(xChild->getParent(),UNO_QUERY);\n bGrabFocus = xLoad.is() && xLoad->isLoaded();\n }\n }\n return bGrabFocus;\n }\n}\n\/\/==================================================================\n\/\/= UnoDataBrowserView\n\/\/==================================================================\n\n\/\/ -------------------------------------------------------------------------\nUnoDataBrowserView::UnoDataBrowserView( Window* pParent,\n IController* _pController,\n const Reference< ::com::sun::star::lang::XMultiServiceFactory >& _rFactory)\n :ODataView(pParent,_pController,_rFactory)\n ,m_pVclControl(NULL)\n ,m_pSplitter(NULL)\n ,m_pTreeView(NULL)\n ,m_pStatus(NULL)\n{\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::Construct(const Reference< ::com::sun::star::awt::XControlModel >& xModel)\n{\n try\n {\n ODataView::Construct();\n\n \/\/ our UNO representation\n m_xMe = VCLUnoHelper::CreateControlContainer(this);\n\n \/\/ create the (UNO-) control\n m_xGrid = new SbaXGridControl(getORB());\n DBG_ASSERT(m_xGrid.is(), \"UnoDataBrowserView::Construct : could not create a grid control !\");\n \/\/ in design mode (for the moment)\n m_xGrid->setDesignMode(sal_True);\n\n Reference< ::com::sun::star::awt::XWindow > xGridWindow(m_xGrid, UNO_QUERY);\n xGridWindow->setVisible(sal_True);\n xGridWindow->setEnable(sal_True);\n\n \/\/ introduce the model to the grid\n m_xGrid->setModel(xModel);\n \/\/ introduce the container (me) to the grid\n Reference< ::com::sun::star::beans::XPropertySet > xModelSet(xModel, UNO_QUERY);\n getContainer()->addControl(::comphelper::getString(xModelSet->getPropertyValue(PROPERTY_NAME)), m_xGrid);\n\n \/\/ get the VCL-control\n m_pVclControl = NULL;\n Reference< ::com::sun::star::awt::XWindowPeer > xPeer = m_xGrid->getPeer();\n if (xPeer.is())\n {\n SbaXGridPeer* pPeer = SbaXGridPeer::getImplementation(xPeer);\n if (pPeer)\n m_pVclControl = static_cast(pPeer->GetWindow());\n\n ::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::AddWindow));\n }\n\n DBG_ASSERT(m_pVclControl != NULL, \"UnoDataBrowserView::Construct : no real grid control !\");\n }\n catch(Exception&)\n {\n ::comphelper::disposeComponent(m_xGrid);\n throw;\n }\n}\n\/\/ -------------------------------------------------------------------------\nUnoDataBrowserView::~UnoDataBrowserView()\n{\n\n ::dbaui::notifySystemWindow(this,m_pVclControl,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n m_pVclControl = NULL;\n\n delete m_pSplitter;\n m_pSplitter = NULL;\n setTreeView(NULL);\n\n if ( m_pStatus )\n {\n delete m_pStatus;\n m_pStatus = NULL;\n }\n\n ::comphelper::disposeComponent(m_xGrid);\n ::comphelper::disposeComponent(m_xMe);\n}\n\/\/ -----------------------------------------------------------------------------\nIMPL_LINK( UnoDataBrowserView, SplitHdl, void*, p )\n{\n long nTest = m_pSplitter->GetPosPixel().Y();\n m_pSplitter->SetPosPixel( Point( m_pSplitter->GetSplitPosPixel(), m_pSplitter->GetPosPixel().Y() ) );\n Resize();\n\n return 0L;\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::setSplitter(Splitter* _pSplitter)\n{\n m_pSplitter = _pSplitter;\n m_pSplitter->SetSplitHdl( LINK( this, UnoDataBrowserView, SplitHdl ) );\n LINK( this, UnoDataBrowserView, SplitHdl ).Call(m_pSplitter);\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::setTreeView(DBTreeView* _pTreeView)\n{\n if (m_pTreeView != _pTreeView)\n {\n if (m_pTreeView)\n {\n ::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::RemoveWindow));\n\n Window* pDeleteIt = m_pTreeView;\n m_pTreeView = NULL;\n delete pDeleteIt;\n }\n m_pTreeView = _pTreeView;\n if ( m_pTreeView )\n ::dbaui::notifySystemWindow(this,m_pTreeView,::comphelper::mem_fun(&TaskPaneList::AddWindow));\n }\n}\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::showStatus( const String& _rStatus )\n{\n if (0 == _rStatus.Len())\n hideStatus();\n else\n {\n if (!m_pStatus)\n m_pStatus = new FixedText(this);\n m_pStatus->SetText(_rStatus);\n m_pStatus->Show();\n Resize();\n Update();\n }\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::hideStatus()\n{\n if (!m_pStatus || !m_pStatus->IsVisible())\n \/\/ nothing to do\n return;\n m_pStatus->Hide();\n Resize();\n Update();\n}\n\n\/\/ -------------------------------------------------------------------------\nvoid UnoDataBrowserView::resizeDocumentView(Rectangle& _rPlayground)\n{\n Point aSplitPos;\n Size aSplitSize;\n Point aPlaygroundPos( _rPlayground.TopLeft() );\n Size aPlaygroundSize( _rPlayground.GetSize() );\n\n if (m_pTreeView && m_pTreeView->IsVisible() && m_pSplitter)\n {\n \/\/ calculate the splitter pos and size\n aSplitPos = m_pSplitter->GetPosPixel();\n aSplitPos.Y() = aPlaygroundPos.Y();\n aSplitSize = m_pSplitter->GetOutputSizePixel();\n aSplitSize.Height() = aPlaygroundSize.Height();\n\n if( ( aSplitPos.X() + aSplitSize.Width() ) > ( aPlaygroundSize.Width() ))\n aSplitPos.X() = aPlaygroundSize.Width() - aSplitSize.Width();\n\n if( aSplitPos.X() <= aPlaygroundPos.X() )\n aSplitPos.X() = aPlaygroundPos.X() + sal_Int32(aPlaygroundSize.Width() * 0.2);\n\n \/\/ the tree pos and size\n Point aTreeViewPos( aPlaygroundPos );\n Size aTreeViewSize( aSplitPos.X(), aPlaygroundSize.Height() );\n\n \/\/ the status pos and size\n if (m_pStatus && m_pStatus->IsVisible())\n {\n Size aStatusSize(aPlaygroundPos.X(), GetTextHeight() + 2);\n aStatusSize = LogicToPixel(aStatusSize, MAP_APPFONT);\n aStatusSize.Width() = aTreeViewSize.Width() - 2 - 2;\n\n Point aStatusPos( aPlaygroundPos.X() + 2, aTreeViewPos.Y() + aTreeViewSize.Height() - aStatusSize.Height() );\n m_pStatus->SetPosSizePixel( aStatusPos, aStatusSize );\n aTreeViewSize.Height() -= aStatusSize.Height();\n }\n\n \/\/ set the size of treelistbox\n m_pTreeView->SetPosSizePixel( aTreeViewPos, aTreeViewSize );\n\n \/\/set the size of the splitter\n m_pSplitter->SetPosSizePixel( aSplitPos, Size( aSplitSize.Width(), aPlaygroundSize.Height() ) );\n m_pSplitter->SetDragRectPixel( _rPlayground );\n }\n\n \/\/ set the size of grid control\n Reference< ::com::sun::star::awt::XWindow > xGridAsWindow(m_xGrid, UNO_QUERY);\n if (xGridAsWindow.is())\n xGridAsWindow->setPosSize( aSplitPos.X() + aSplitSize.Width(), aPlaygroundPos.Y(),\n aPlaygroundSize.Width() - aSplitSize.Width() - aSplitPos.X(), aPlaygroundSize.Height(), ::com::sun::star::awt::PosSize::POSSIZE);\n\n \/\/ just for completeness: there is no space left, we occupied it all ...\n _rPlayground.SetPos( _rPlayground.BottomRight() );\n _rPlayground.SetSize( Size( 0, 0 ) );\n}\n\n\/\/------------------------------------------------------------------\nsal_uInt16 UnoDataBrowserView::Model2ViewPos(sal_uInt16 nPos) const\n{\n return m_pVclControl ? m_pVclControl->GetViewColumnPos(m_pVclControl->GetColumnIdFromModelPos(nPos)) : -1;\n}\n\n\/\/------------------------------------------------------------------\nsal_uInt16 UnoDataBrowserView::View2ModelPos(sal_uInt16 nPos) const\n{\n return m_pVclControl ? m_pVclControl->GetModelColumnPos(m_pVclControl->GetColumnIdFromViewPos(nPos)) : -1;\n}\n\n\/\/------------------------------------------------------------------\nsal_uInt16 UnoDataBrowserView::ViewColumnCount() const\n{\n return m_pVclControl ? m_pVclControl->GetViewColCount() : 0;\n}\n\n\/\/------------------------------------------------------------------\nvoid UnoDataBrowserView::GetFocus()\n{\n ODataView::GetFocus();\n if( m_pTreeView && m_pTreeView->IsVisible() && !m_pTreeView->HasChildPathFocus())\n m_pTreeView->GrabFocus();\n else if (m_pVclControl && m_xGrid.is())\n {\n sal_Bool bGrabFocus = sal_False;\n if(!m_pVclControl->HasChildPathFocus())\n {\n bGrabFocus = isGrabVclControlFocusAllowed(this);\n if( bGrabFocus )\n m_pVclControl->GrabFocus();\n }\n if(!bGrabFocus && m_pTreeView && m_pTreeView->IsVisible() )\n m_pTreeView->GrabFocus();\n }\n}\n\/\/ -------------------------------------------------------------------------\nlong UnoDataBrowserView::PreNotify( NotifyEvent& rNEvt )\n{\n long nDone = 0L;\n if(rNEvt.GetType() == EVENT_KEYINPUT)\n {\n sal_Bool bGrabAllowed = isGrabVclControlFocusAllowed(this);\n if ( bGrabAllowed )\n {\n const KeyEvent* pKeyEvt = rNEvt.GetKeyEvent();\n const KeyCode& rKeyCode = pKeyEvt->GetKeyCode();\n if( rKeyCode == KeyCode(KEY_E,TRUE,TRUE,FALSE) )\n {\n if ( m_pTreeView && m_pVclControl && m_pTreeView->HasChildPathFocus() )\n m_pVclControl->GrabFocus();\n else if ( m_pTreeView && m_pVclControl && m_pVclControl->HasChildPathFocus() )\n m_pTreeView->GrabFocus();\n\n nDone = 1L;\n }\n }\n }\n return nDone ? nDone : ODataView::PreNotify(rNEvt);\n}\n\n\/\/ -----------------------------------------------------------------------------\nBrowserViewStatusDisplay::BrowserViewStatusDisplay( UnoDataBrowserView* _pView, const String& _rStatus )\n :m_pView(_pView)\n{\n if (m_pView)\n m_pView->showStatus(_rStatus);\n}\n\n\/\/ -----------------------------------------------------------------------------\nBrowserViewStatusDisplay::~BrowserViewStatusDisplay( )\n{\n if (m_pView)\n m_pView->showStatus(String());\n}\n\/\/ -----------------------------------------------------------------------------\n\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: sqledit.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: fs $ $Date: 2001-08-23 14:47:34 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_SQLEDIT_HXX\n#include \"sqledit.hxx\"\n#endif\n#ifndef DBAUI_QUERYVIEW_TEXT_HXX\n#include \"QueryTextView.hxx\"\n#endif\n#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX\n#include \"querycontainerwindow.hxx\"\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#include \"dbaccess_helpid.hrc\"\n#ifndef DBACCESS_UI_BROWSER_ID_HXX\n#include \"browserids.hxx\"\n#endif\n#ifndef DBAUI_QUERYCONTROLLER_HXX\n#include \"querycontroller.hxx\"\n#endif\n#ifndef DBAUI_UNDOSQLEDIT_HXX\n#include \"undosqledit.hxx\"\n#endif\n#ifndef DBAUI_QUERYDESIGNVIEW_HXX\n#include \"QueryDesignView.hxx\"\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OSqlEdit\n\/\/------------------------------------------------------------------------------\nusing namespace dbaui;\n\nDBG_NAME(OSqlEdit);\nOSqlEdit::OSqlEdit( OQueryTextView* pParent, WinBits nWinStyle ) :\n MultiLineEdit( pParent, nWinStyle )\n ,m_bAccelAction( sal_False )\n ,m_bStopTimer(sal_False )\n ,m_pView(pParent)\n{\n DBG_CTOR(OSqlEdit,NULL);\n SetHelpId( HID_CTL_QRYSQLEDIT );\n SetModifyHdl( LINK(this, OSqlEdit, ModifyHdl) );\n\n m_timerUndoActionCreation.SetTimeout(1000);\n m_timerUndoActionCreation.SetTimeoutHdl(LINK(this, OSqlEdit, OnUndoActionTimer));\n\n m_timerInvalidate.SetTimeout(200);\n m_timerInvalidate.SetTimeoutHdl(LINK(this, OSqlEdit, OnInvalidateTimer));\n m_timerInvalidate.Start();\n}\n\n\/\/------------------------------------------------------------------------------\nOSqlEdit::~OSqlEdit()\n{\n if (m_timerUndoActionCreation.IsActive())\n m_timerUndoActionCreation.Stop();\n DBG_DTOR(OSqlEdit,NULL);\n}\n\/\/------------------------------------------------------------------------------\nvoid OSqlEdit::KeyInput( const KeyEvent& rKEvt )\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);\n\n \/\/ Ist dies ein Cut, Copy, Paste Event?\n KeyFuncType aKeyFunc = rKEvt.GetKeyCode().GetFunction();\n if( (aKeyFunc==KEYFUNC_CUT)||(aKeyFunc==KEYFUNC_COPY)||(aKeyFunc==KEYFUNC_PASTE) )\n m_bAccelAction = sal_True;\n\n MultiLineEdit::KeyInput( rKEvt );\n\n if( m_bAccelAction )\n m_bAccelAction = sal_False;\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool OSqlEdit::IsInAccelAct()\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n \/\/ Das Cut, Copy, Paste per Accel. fuehrt neben der Aktion im Edit im View\n \/\/ auch die entsprechenden Slots aus. Die Aktionen finden also zweimal statt.\n \/\/ Um dies zu verhindern, kann im View beim SlotExec diese Funktion\n \/\/ aufgerufen werden.\n\n return m_bAccelAction;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OSqlEdit::GetFocus()\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n m_strOrigText = GetText();\n MultiLineEdit::GetFocus();\n}\n\n\/\/------------------------------------------------------------------------------\nIMPL_LINK(OSqlEdit, OnUndoActionTimer, void*, EMPTYARG)\n{\n String aText = GetText();\n if(aText != m_strOrigText)\n {\n SfxUndoManager* pUndoMgr = m_pView->getContainerWindow()->getDesignView()->getController()->getUndoMgr();\n OSqlEditUndoAct* pUndoAct = new OSqlEditUndoAct( this );\n\n pUndoAct->SetOriginalText( m_strOrigText );\n pUndoMgr->AddUndoAction( pUndoAct );\n\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_UNDO);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_REDO);\n\n m_strOrigText = aText;\n }\n\n return 0L;\n}\n\/\/------------------------------------------------------------------------------\nIMPL_LINK(OSqlEdit, OnInvalidateTimer, void*, EMPTYARG)\n{\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);\n if(!m_bStopTimer)\n m_timerInvalidate.Start();\n return 0L;\n}\n\/\/------------------------------------------------------------------------------\nIMPL_LINK(OSqlEdit, ModifyHdl, void*, EMPTYTAG)\n{\n if (m_timerUndoActionCreation.IsActive())\n m_timerUndoActionCreation.Stop();\n m_timerUndoActionCreation.Start();\n\n if (!m_pView->getContainerWindow()->getDesignView()->getController()->isModified())\n m_pView->getContainerWindow()->getDesignView()->getController()->setModified( sal_True );\n\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_SBA_QRY_EXECUTE);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);\n\n m_lnkTextModifyHdl.Call(NULL);\n return 0;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OSqlEdit::OverloadedSetText(const String& rNewText)\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n if (m_timerUndoActionCreation.IsActive())\n { \/\/ die noch anstehenden Undo-Action erzeugen\n m_timerUndoActionCreation.Stop();\n LINK(this, OSqlEdit, OnUndoActionTimer).Call(NULL);\n }\n\n MultiLineEdit::SetText(rNewText);\n m_strOrigText = rNewText;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OSqlEdit::stopTimer()\n{\n m_bStopTimer = sal_True;\n if (m_timerInvalidate.IsActive())\n m_timerInvalidate.Stop();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OSqlEdit::startTimer()\n{\n m_bStopTimer = sal_False;\n if (!m_timerInvalidate.IsActive())\n m_timerInvalidate.Start();\n}\n\n\/\/==============================================================================\nINTEGRATION: CWS insight01 (1.5.126); FILE MERGED 2004\/07\/15 10:52:33 oj 1.5.126.2: add chkthis macros 2004\/07\/09 14:05:15 oj 1.5.126.1: resource changes\/*************************************************************************\n *\n * $RCSfile: sqledit.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2004-08-02 15:36:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the License); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an AS IS basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n#ifndef DBAUI_SQLEDIT_HXX\n#include \"sqledit.hxx\"\n#endif\n#ifndef DBAUI_QUERYVIEW_TEXT_HXX\n#include \"QueryTextView.hxx\"\n#endif\n#ifndef DBAUI_QUERYCONTAINERWINDOW_HXX\n#include \"querycontainerwindow.hxx\"\n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n#include \"dbaccess_helpid.hrc\"\n#ifndef DBACCESS_UI_BROWSER_ID_HXX\n#include \"browserids.hxx\"\n#endif\n#ifndef DBAUI_QUERYCONTROLLER_HXX\n#include \"querycontroller.hxx\"\n#endif\n#ifndef DBAUI_UNDOSQLEDIT_HXX\n#include \"undosqledit.hxx\"\n#endif\n#ifndef DBAUI_QUERYDESIGNVIEW_HXX\n#include \"QueryDesignView.hxx\"\n#endif\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ OSqlEdit\n\/\/------------------------------------------------------------------------------\nusing namespace dbaui;\n\nDBG_NAME(OSqlEdit);\nOSqlEdit::OSqlEdit( OQueryTextView* pParent, WinBits nWinStyle ) :\n MultiLineEdit( pParent, nWinStyle )\n ,m_bAccelAction( sal_False )\n ,m_bStopTimer(sal_False )\n ,m_pView(pParent)\n{\n DBG_CTOR(OSqlEdit,NULL);\n SetHelpId( HID_CTL_QRYSQLEDIT );\n SetModifyHdl( LINK(this, OSqlEdit, ModifyHdl) );\n\n m_timerUndoActionCreation.SetTimeout(1000);\n m_timerUndoActionCreation.SetTimeoutHdl(LINK(this, OSqlEdit, OnUndoActionTimer));\n\n m_timerInvalidate.SetTimeout(200);\n m_timerInvalidate.SetTimeoutHdl(LINK(this, OSqlEdit, OnInvalidateTimer));\n m_timerInvalidate.Start();\n}\n\n\/\/------------------------------------------------------------------------------\nOSqlEdit::~OSqlEdit()\n{\n DBG_DTOR(OSqlEdit,NULL);\n if (m_timerUndoActionCreation.IsActive())\n m_timerUndoActionCreation.Stop();\n}\n\/\/------------------------------------------------------------------------------\nvoid OSqlEdit::KeyInput( const KeyEvent& rKEvt )\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);\n\n \/\/ Ist dies ein Cut, Copy, Paste Event?\n KeyFuncType aKeyFunc = rKEvt.GetKeyCode().GetFunction();\n if( (aKeyFunc==KEYFUNC_CUT)||(aKeyFunc==KEYFUNC_COPY)||(aKeyFunc==KEYFUNC_PASTE) )\n m_bAccelAction = sal_True;\n\n MultiLineEdit::KeyInput( rKEvt );\n\n if( m_bAccelAction )\n m_bAccelAction = sal_False;\n}\n\n\/\/------------------------------------------------------------------------------\nsal_Bool OSqlEdit::IsInAccelAct()\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n \/\/ Das Cut, Copy, Paste per Accel. fuehrt neben der Aktion im Edit im View\n \/\/ auch die entsprechenden Slots aus. Die Aktionen finden also zweimal statt.\n \/\/ Um dies zu verhindern, kann im View beim SlotExec diese Funktion\n \/\/ aufgerufen werden.\n\n return m_bAccelAction;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OSqlEdit::GetFocus()\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n m_strOrigText =GetText();\n MultiLineEdit::GetFocus();\n}\n\n\/\/------------------------------------------------------------------------------\nIMPL_LINK(OSqlEdit, OnUndoActionTimer, void*, EMPTYARG)\n{\n String aText =GetText();\n if(aText != m_strOrigText)\n {\n SfxUndoManager* pUndoMgr = m_pView->getContainerWindow()->getDesignView()->getController()->getUndoMgr();\n OSqlEditUndoAct* pUndoAct = new OSqlEditUndoAct( this );\n\n pUndoAct->SetOriginalText( m_strOrigText );\n pUndoMgr->AddUndoAction( pUndoAct );\n\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_UNDO);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_REDO);\n\n m_strOrigText =aText;\n }\n\n return 0L;\n}\n\/\/------------------------------------------------------------------------------\nIMPL_LINK(OSqlEdit, OnInvalidateTimer, void*, EMPTYARG)\n{\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);\n if(!m_bStopTimer)\n m_timerInvalidate.Start();\n return 0L;\n}\n\/\/------------------------------------------------------------------------------\nIMPL_LINK(OSqlEdit, ModifyHdl, void*, EMPTYTAG)\n{\n if (m_timerUndoActionCreation.IsActive())\n m_timerUndoActionCreation.Stop();\n m_timerUndoActionCreation.Start();\n\n if (!m_pView->getContainerWindow()->getDesignView()->getController()->isModified())\n m_pView->getContainerWindow()->getDesignView()->getController()->setModified( sal_True );\n\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_SBA_QRY_EXECUTE);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_CUT);\n m_pView->getContainerWindow()->getDesignView()->getController()->InvalidateFeature(SID_COPY);\n\n m_lnkTextModifyHdl.Call(NULL);\n return 0;\n}\n\n\/\/------------------------------------------------------------------------------\nvoid OSqlEdit::OverloadedSetText(const String& rNewText)\n{\n DBG_CHKTHIS(OSqlEdit,NULL);\n if (m_timerUndoActionCreation.IsActive())\n { \/\/ die noch anstehenden Undo-Action erzeugen\n m_timerUndoActionCreation.Stop();\n LINK(this, OSqlEdit, OnUndoActionTimer).Call(NULL);\n }\n\n MultiLineEdit::SetText(rNewText);\n m_strOrigText =rNewText;\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OSqlEdit::stopTimer()\n{\n m_bStopTimer = sal_True;\n if (m_timerInvalidate.IsActive())\n m_timerInvalidate.Stop();\n}\n\/\/ -----------------------------------------------------------------------------\nvoid OSqlEdit::startTimer()\n{\n m_bStopTimer = sal_False;\n if (!m_timerInvalidate.IsActive())\n m_timerInvalidate.Start();\n}\n\n\/\/==============================================================================\n<|endoftext|>"} {"text":"#include \"app\/view\/layout_hierarchy.h\"\n\n#include \"core\/epi\/disposed.h\"\n#include \"core\/epi\/visibility.h\"\n#include \"core\/util\/holder_util.h\"\n\n#include \"graphics\/base\/size.h\"\n#include \"graphics\/inf\/renderer.h\"\n\n#include \"app\/base\/event.h\"\n#include \"app\/inf\/layout.h\"\n#include \"app\/view\/view.h\"\n\nnamespace ark {\n\nLayoutHierarchy::Slot::Slot(const sp& renderer, bool layoutRequested)\n : _x(0), _y(0), _layout_width(0), _layout_height(0), _layout_requested(layoutRequested), _renderer(renderer), _view(renderer.as()), _layout_event_listener(renderer.as()),\n _disposed(renderer.as()), _visibility(renderer.as())\n{\n DASSERT(_renderer);\n}\n\nvoid LayoutHierarchy::Slot::traverse(const Holder::Visitor& visitor)\n{\n if(_view)\n HolderUtil::visit(_view, visitor);\n else\n HolderUtil::visit(_renderer, visitor);\n}\n\nbool LayoutHierarchy::Slot::isDisposed() const\n{\n return _disposed && _disposed->val();\n}\n\nbool LayoutHierarchy::Slot::layoutRequested() const\n{\n return _layout_requested;\n}\n\nvoid LayoutHierarchy::Slot::updateLayout()\n{\n if(_view)\n {\n _layout_width = _view->size()->width();\n _layout_height = _view->size()->height();\n }\n _layout_requested = false;\n}\n\nvoid LayoutHierarchy::Slot::doPlace(Layout::Context& ctx, float clientHeight, const sp& layout)\n{\n if(_view)\n {\n const sp& layoutParam = _view->layoutParam();\n DASSERT(layoutParam);\n if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)\n {\n const Rect& margins = layoutParam->margins();\n const Rect target = layout->place(ctx, layoutParam);\n _y = clientHeight - layoutParam->contentHeight() - target.top() - margins.top();\n _x = target.left() + margins.left();\n }\n }\n}\n\nvoid LayoutHierarchy::Slot::doWrapContentPlace(Layout::Context& ctx, const sp& layout, Rect& contentRect) const\n{\n if(_view)\n {\n const sp& layoutParam = _view->layoutParam();\n DASSERT(layoutParam);\n if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)\n {\n const Rect rect = layout->place(ctx, layoutParam);\n contentRect.setLeft(std::min(contentRect.left(), rect.left()));\n contentRect.setTop(std::min(contentRect.top(), rect.top()));\n contentRect.setRight(std::max(contentRect.right(), rect.right()));\n contentRect.setBottom(std::max(contentRect.bottom(), rect.bottom()));\n }\n }\n}\n\nvoid LayoutHierarchy::Slot::doLayoutEnd(const Rect& p)\n{\n if(_view)\n {\n _x += p.left();\n _y -= p.top();\n }\n updateLayout();\n}\n\nvoid LayoutHierarchy::Slot::render(RenderRequest& renderRequest, const V3& position)\n{\n if(!_layout_requested)\n {\n _renderer->render(renderRequest, position + V3(_x, _y, 0));\n if(_view)\n _layout_requested = _layout_width != _view->size()->width() || _layout_height != _view->size()->height();\n }\n}\n\nbool LayoutHierarchy::Slot::onEventDispatch(const Event& event, float x, float y)\n{\n if(_view && (!_visibility || _visibility->val()))\n {\n const sp& layoutParam = _view->layoutParam();\n const Rect target(x + _x, y + _y, x + _x + layoutParam->contentWidth(), y + _y + layoutParam->contentHeight());\n const Event viewEvent(event.action(), event.x() - _x - x, event.y() - _y - y, event.timestamp(), event.code());\n const bool ptin = event.ptin(target);\n if(_layout_event_listener)\n return _layout_event_listener->onEvent(event, target.left(), target.top(), ptin);\n return _view->dispatchEvent(viewEvent, ptin);\n }\n return false;\n}\n\nsp LayoutHierarchy::Slot::getLayoutParam() const\n{\n return _view ? static_cast>(_view->layoutParam()) : nullptr;\n}\n\nLayoutHierarchy::LayoutHierarchy(const sp& layout)\n : _layout(layout)\n{\n}\n\nvoid LayoutHierarchy::traverse(const Holder::Visitor& visitor)\n{\n for(const sp& i : _slots)\n i->traverse(visitor);\n for(const sp& i : _incremental)\n i->traverse(visitor);\n}\n\nvoid LayoutHierarchy::render(RenderRequest& renderRequest, const V3& position) const\n{\n for(const sp& i: _slots)\n i->render(renderRequest, position);\n}\n\nbool LayoutHierarchy::onEvent(const Event& event, float x, float y) const\n{\n Event::Action action = event.action();\n if(action == Event::ACTION_MOVE || action == Event::ACTION_UP || action == Event::ACTION_DOWN)\n {\n for(auto iter =_slots.rbegin(); iter != _slots.rend(); ++iter)\n if((*iter)->onEventDispatch(event, x, y))\n return true;\n }\n return false;\n}\n\nbool LayoutHierarchy::isLayoutNeeded(const LayoutParam& layoutParam)\n{\n bool layoutNeeded = false;\n for(auto iter = _slots.begin(); iter != _slots.end(); ++iter)\n {\n const sp& i = *iter;\n if(i->isDisposed())\n {\n iter = _slots.erase(iter);\n if(iter == _slots.end())\n return true;\n continue;\n }\n layoutNeeded = layoutNeeded || i->layoutRequested();\n }\n\n const V3 newLayoutSize = layoutParam.size()->val();\n if(newLayoutSize != _layout_size)\n {\n _layout_size = newLayoutSize;\n return true;\n }\n return layoutNeeded;\n}\n\nstd::vector> LayoutHierarchy::getLayoutParams() const\n{\n std::vector> layoutParams;\n\n for(const sp& i : _slots)\n {\n sp lp = i->getLayoutParam();\n if(lp && lp->display() == LayoutParam::DISPLAY_BLOCK)\n layoutParams.push_back(std::move(lp));\n }\n\n return layoutParams;\n}\n\nvoid LayoutHierarchy::updateLayout(LayoutParam& layoutParam)\n{\n if(_incremental.size())\n {\n for(const sp& i : _incremental)\n _slots.push_back(i);\n _incremental.clear();\n }\n if(isLayoutNeeded(layoutParam))\n {\n if(_layout)\n {\n Layout::Context ctx(layoutParam, [this]() {\n return this->getLayoutParams();\n });\n\n if(layoutParam.isWrapContent())\n doWrapContentLayout(ctx, layoutParam);\n\n _layout->begin(ctx, layoutParam);\n\n for(const sp& i: _slots)\n i->doPlace(ctx, layoutParam.contentHeight(), _layout);\n\n const Rect p = _layout->end(ctx);\n for(const sp& i : _slots)\n i->doLayoutEnd(p);\n }\n else\n for(const sp& i : _slots)\n i->updateLayout();\n }\n}\n\nvoid LayoutHierarchy::doWrapContentLayout(Layout::Context& ctx, LayoutParam& layoutParam)\n{\n LayoutParam lp(layoutParam);\n Rect clientRect;\n _layout->begin(ctx, lp);\n for(const sp& i: _slots)\n i->doWrapContentPlace(ctx, _layout, clientRect);\n\n _layout->end(ctx);\n layoutParam.setContentWidth(clientRect.width());\n layoutParam.setContentHeight(clientRect.height());\n}\n\nvoid LayoutHierarchy::addRenderer(const sp& renderer)\n{\n DASSERT(renderer);\n _incremental.push_back(sp::make(renderer, static_cast(_layout)));\n}\n\n}\nLayout bugfix#include \"app\/view\/layout_hierarchy.h\"\n\n#include \"core\/epi\/disposed.h\"\n#include \"core\/epi\/visibility.h\"\n#include \"core\/util\/holder_util.h\"\n\n#include \"graphics\/base\/size.h\"\n#include \"graphics\/inf\/renderer.h\"\n\n#include \"app\/base\/event.h\"\n#include \"app\/inf\/layout.h\"\n#include \"app\/view\/view.h\"\n\nnamespace ark {\n\nLayoutHierarchy::Slot::Slot(const sp& renderer, bool layoutRequested)\n : _x(0), _y(0), _layout_width(0), _layout_height(0), _layout_requested(layoutRequested), _renderer(renderer), _view(renderer.as()), _layout_event_listener(renderer.as()),\n _disposed(renderer.as()), _visibility(renderer.as())\n{\n DASSERT(_renderer);\n}\n\nvoid LayoutHierarchy::Slot::traverse(const Holder::Visitor& visitor)\n{\n if(_view)\n HolderUtil::visit(_view, visitor);\n else\n HolderUtil::visit(_renderer, visitor);\n}\n\nbool LayoutHierarchy::Slot::isDisposed() const\n{\n return _disposed && _disposed->val();\n}\n\nbool LayoutHierarchy::Slot::layoutRequested() const\n{\n return _layout_requested;\n}\n\nvoid LayoutHierarchy::Slot::updateLayout()\n{\n if(_view)\n {\n _layout_width = _view->size()->width();\n _layout_height = _view->size()->height();\n }\n _layout_requested = false;\n}\n\nvoid LayoutHierarchy::Slot::doPlace(Layout::Context& ctx, float clientHeight, const sp& layout)\n{\n if(_view)\n {\n const sp& layoutParam = _view->layoutParam();\n DASSERT(layoutParam);\n if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)\n {\n const Rect& margins = layoutParam->margins();\n const Rect target = layout->place(ctx, layoutParam);\n _y = clientHeight - layoutParam->contentHeight() - target.top() - margins.top();\n _x = target.left() + margins.left();\n }\n }\n}\n\nvoid LayoutHierarchy::Slot::doWrapContentPlace(Layout::Context& ctx, const sp& layout, Rect& contentRect) const\n{\n if(_view)\n {\n const sp& layoutParam = _view->layoutParam();\n DASSERT(layoutParam);\n if(layoutParam->display() == LayoutParam::DISPLAY_BLOCK)\n {\n const Rect rect = layout->place(ctx, layoutParam);\n contentRect.setLeft(std::min(contentRect.left(), rect.left()));\n contentRect.setTop(std::min(contentRect.top(), rect.top()));\n contentRect.setRight(std::max(contentRect.right(), rect.right()));\n contentRect.setBottom(std::max(contentRect.bottom(), rect.bottom()));\n }\n }\n}\n\nvoid LayoutHierarchy::Slot::doLayoutEnd(const Rect& p)\n{\n if(_view)\n {\n _x += p.left();\n _y -= p.top();\n }\n updateLayout();\n}\n\nvoid LayoutHierarchy::Slot::render(RenderRequest& renderRequest, const V3& position)\n{\n if(!_layout_requested)\n {\n _renderer->render(renderRequest, position + V3(_x, _y, 0));\n if(_view)\n _layout_requested = _layout_width != _view->size()->width() || _layout_height != _view->size()->height();\n }\n}\n\nbool LayoutHierarchy::Slot::onEventDispatch(const Event& event, float x, float y)\n{\n if(_view && (!_visibility || _visibility->val()))\n {\n const sp& layoutParam = _view->layoutParam();\n const Rect target(x + _x, y + _y, x + _x + layoutParam->contentWidth(), y + _y + layoutParam->contentHeight());\n const Event viewEvent(event.action(), event.x() - _x - x, event.y() - _y - y, event.timestamp(), event.code());\n const bool ptin = event.ptin(target);\n if(_layout_event_listener)\n return _layout_event_listener->onEvent(event, target.left(), target.top(), ptin);\n return _view->dispatchEvent(viewEvent, ptin);\n }\n return false;\n}\n\nsp LayoutHierarchy::Slot::getLayoutParam() const\n{\n return _view ? static_cast>(_view->layoutParam()) : nullptr;\n}\n\nLayoutHierarchy::LayoutHierarchy(const sp& layout)\n : _layout(layout)\n{\n}\n\nvoid LayoutHierarchy::traverse(const Holder::Visitor& visitor)\n{\n for(const sp& i : _slots)\n i->traverse(visitor);\n for(const sp& i : _incremental)\n i->traverse(visitor);\n}\n\nvoid LayoutHierarchy::render(RenderRequest& renderRequest, const V3& position) const\n{\n for(const sp& i: _slots)\n i->render(renderRequest, position);\n}\n\nbool LayoutHierarchy::onEvent(const Event& event, float x, float y) const\n{\n Event::Action action = event.action();\n if(action == Event::ACTION_MOVE || action == Event::ACTION_UP || action == Event::ACTION_DOWN)\n {\n for(auto iter =_slots.rbegin(); iter != _slots.rend(); ++iter)\n if((*iter)->onEventDispatch(event, x, y))\n return true;\n }\n return false;\n}\n\nbool LayoutHierarchy::isLayoutNeeded(const LayoutParam& layoutParam)\n{\n bool layoutNeeded = false;\n for(auto iter = _slots.begin(); iter != _slots.end(); )\n {\n const sp& i = *iter;\n if(i->isDisposed())\n {\n iter = _slots.erase(iter);\n layoutNeeded = true;\n }\n else\n ++iter;\n layoutNeeded = layoutNeeded || i->layoutRequested();\n }\n\n const V3 newLayoutSize = layoutParam.size()->val();\n if(newLayoutSize != _layout_size)\n {\n _layout_size = newLayoutSize;\n return true;\n }\n return layoutNeeded;\n}\n\nstd::vector> LayoutHierarchy::getLayoutParams() const\n{\n std::vector> layoutParams;\n\n for(const sp& i : _slots)\n {\n sp lp = i->getLayoutParam();\n if(lp && lp->display() == LayoutParam::DISPLAY_BLOCK)\n layoutParams.push_back(std::move(lp));\n }\n\n return layoutParams;\n}\n\nvoid LayoutHierarchy::updateLayout(LayoutParam& layoutParam)\n{\n if(_incremental.size())\n {\n for(const sp& i : _incremental)\n _slots.push_back(i);\n _incremental.clear();\n }\n if(isLayoutNeeded(layoutParam))\n {\n if(_layout)\n {\n Layout::Context ctx(layoutParam, [this]() {\n return this->getLayoutParams();\n });\n\n if(layoutParam.isWrapContent())\n doWrapContentLayout(ctx, layoutParam);\n\n _layout->begin(ctx, layoutParam);\n\n for(const sp& i: _slots)\n i->doPlace(ctx, layoutParam.contentHeight(), _layout);\n\n const Rect p = _layout->end(ctx);\n for(const sp& i : _slots)\n i->doLayoutEnd(p);\n }\n else\n for(const sp& i : _slots)\n i->updateLayout();\n }\n}\n\nvoid LayoutHierarchy::doWrapContentLayout(Layout::Context& ctx, LayoutParam& layoutParam)\n{\n LayoutParam lp(layoutParam);\n Rect clientRect;\n _layout->begin(ctx, lp);\n for(const sp& i: _slots)\n i->doWrapContentPlace(ctx, _layout, clientRect);\n\n _layout->end(ctx);\n layoutParam.setContentWidth(clientRect.width());\n layoutParam.setContentHeight(clientRect.height());\n}\n\nvoid LayoutHierarchy::addRenderer(const sp& renderer)\n{\n DASSERT(renderer);\n _incremental.push_back(sp::make(renderer, static_cast(_layout)));\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: WTypeSelect.hxx,v $\n *\n * $Revision: 1.15 $\n *\n * last change: $Author: ihi $ $Date: 2007-11-21 16:02:37 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_WIZ_TYPESELECT_HXX\n#define DBAUI_WIZ_TYPESELECT_HXX\n\n#ifndef DBAUI_WIZ_TABBPAGE_HXX\n#include \"WTabPage.hxx\"\n#endif\n#ifndef _SV_LSTBOX_HXX\n#include \n#endif\n#ifndef _SV_FIELD_HXX\n#include \n#endif\n#ifndef _SV_FIXED_HXX\n#include \n#endif\n#ifndef DBAUI_FIELDDESCRIPTIONCONTROL_HXX\n#include \"FieldDescControl.hxx\"\n#endif\n#ifndef DBAUI_TYPEINFO_HXX\n#include \"TypeInfo.hxx\"\n#endif\n#ifndef _SV_BUTTON_HXX\n#include \n#endif\n\nclass SvStream;\nclass SvParser;\nnamespace dbaui\n{\n class OTableDesignHelpBar;\n \/\/ =============================================================================================\n \/\/ OWizTypeSelectControl\n \/\/ =============================================================================================\n class OWizTypeSelectControl : public OFieldDescControl\n {\n protected:\n virtual void ActivateAggregate( EControlType eType );\n virtual void DeactivateAggregate( EControlType eType );\n\n virtual void CellModified(long nRow, sal_uInt16 nColId );\n\n virtual ::com::sun::star::lang::Locale GetLocale() const;\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > GetFormatter() const;\n virtual TOTypeInfoSP getTypeInfo(sal_Int32 _nPos);\n virtual const OTypeInfoMap* getTypeInfo() const;\n virtual sal_Bool isAutoIncrementValueEnabled() const;\n virtual ::rtl::OUString getAutoIncrementValue() const;\n\n public:\n OWizTypeSelectControl(Window* pParent, const ResId& rResId,OTableDesignHelpBar* pHelpBar=NULL);\n virtual ~OWizTypeSelectControl();\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection();\n };\n\n\n \/\/ ========================================================\n \/\/ Wizard Page: OWizTypeSelectList\n \/\/ definiert nur das ::com::sun::star::ucb::Command f\"ur das Contextmenu\n \/\/ ========================================================\n class OWizTypeSelectList : public MultiListBox\n {\n sal_Bool m_bPKey;\n sal_Bool IsPrimaryKeyAllowed() const;\n void setPrimaryKey( OFieldDescription* _pFieldDescr,\n sal_uInt16 _nPos,\n sal_Bool _bSet=sal_False);\n protected:\n virtual long PreNotify( NotifyEvent& rNEvt );\n public:\n OWizTypeSelectList( Window* pParent, WinBits nStyle = WB_BORDER ) : MultiListBox(pParent,nStyle) {};\n OWizTypeSelectList( Window* pParent, const ResId& rResId ) : MultiListBox(pParent,rResId) {};\n void SetPKey(sal_Bool bPKey) { m_bPKey = bPKey; }\n };\n \/\/ ========================================================\n \/\/ Wizard Page: OWizTypeSelect\n \/\/ Dient als Basis Klasse fuer unterschiedliche Kopiereigenschaften\n \/\/ FillColumnList wird aufgerufen, wenn der Button AUTO ausgeloest wird.\n \/\/ ========================================================\n class OWizTypeSelect : public OWizardPage\n {\n friend class OWizTypeSelectControl;\n friend class OWizTypeSelectList;\n\n DECL_LINK( ColumnSelectHdl, MultiListBox* );\n DECL_LINK( ButtonClickHdl, Button * );\n protected:\n OWizTypeSelectList m_lbColumnNames;\n FixedLine m_flColumns;\n OWizTypeSelectControl m_aTypeControl;\n FixedLine m_flAutoType;\n FixedText m_ftAuto;\n NumericField m_etAuto;\n PushButton m_pbAuto;\n\n Image m_imgPKey;\n SvStream* m_pParserStream; \/\/ stream to read the tokens from or NULL\n ::rtl::OUString m_sAutoIncrementValue;\n sal_Int32 m_nDisplayRow;\n sal_Bool m_bAutoIncrementEnabled;\n sal_Bool m_bDuplicateName;\n\n void fillColumnList(sal_uInt32 nRows);\n virtual SvParser* createReader(sal_Int32 _nRows) = 0;\n\n void EnableAuto(sal_Bool bEnable);\n public:\n virtual void Reset ( );\n virtual void ActivatePage( );\n virtual void Resize();\n virtual sal_Bool LeavePage();\n virtual String GetTitle() const;\n\n OWizTypeSelect(Window* pParent,SvStream* _pStream = NULL);\n virtual ~OWizTypeSelect();\n\n inline void setDisplayRow(sal_Int32 _nRow) { m_nDisplayRow = _nRow - 1; }\n inline void setDuplicateName(sal_Bool _bDuplicateName) { m_bDuplicateName = _bDuplicateName; }\n };\n}\n#endif \/\/ DBAUI_WIZ_TYPESELECT_HXX\n\n\n\nINTEGRATION: CWS dba24d (1.14.88); FILE MERGED 2007\/12\/01 13:41:11 fs 1.14.88.2: RESYNC: (1.14-1.15); FILE MERGED 2007\/11\/08 14:21:04 fs 1.14.88.1: #i81658# re-factoring of the Copy Table wizard\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: WTypeSelect.hxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: rt $ $Date: 2008-01-30 08:49:15 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef DBAUI_WIZ_TYPESELECT_HXX\n#define DBAUI_WIZ_TYPESELECT_HXX\n\n#include \"FieldDescControl.hxx\"\n#include \"TypeInfo.hxx\"\n#include \"WTabPage.hxx\"\n\n#include \n#include \n#include \n#include \n\nclass SvStream;\nclass SvParser;\nnamespace dbaui\n{\n class OTableDesignHelpBar;\n \/\/ =============================================================================================\n \/\/ OWizTypeSelectControl\n \/\/ =============================================================================================\n class OWizTypeSelectControl : public OFieldDescControl\n {\n protected:\n virtual void ActivateAggregate( EControlType eType );\n virtual void DeactivateAggregate( EControlType eType );\n\n virtual void CellModified(long nRow, sal_uInt16 nColId );\n\n virtual ::com::sun::star::lang::Locale GetLocale() const;\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter > GetFormatter() const;\n virtual TOTypeInfoSP getTypeInfo(sal_Int32 _nPos);\n virtual const OTypeInfoMap* getTypeInfo() const;\n virtual sal_Bool isAutoIncrementValueEnabled() const;\n virtual ::rtl::OUString getAutoIncrementValue() const;\n\n public:\n OWizTypeSelectControl(Window* pParent, const ResId& rResId,OTableDesignHelpBar* pHelpBar=NULL);\n virtual ~OWizTypeSelectControl();\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XDatabaseMetaData> getMetaData();\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection> getConnection();\n };\n\n\n \/\/ ========================================================\n \/\/ Wizard Page: OWizTypeSelectList\n \/\/ definiert nur das ::com::sun::star::ucb::Command f\"ur das Contextmenu\n \/\/ ========================================================\n class OWizTypeSelectList : public MultiListBox\n {\n sal_Bool m_bPKey;\n sal_Bool IsPrimaryKeyAllowed() const;\n void setPrimaryKey( OFieldDescription* _pFieldDescr,\n sal_uInt16 _nPos,\n sal_Bool _bSet=sal_False);\n protected:\n virtual long PreNotify( NotifyEvent& rNEvt );\n public:\n OWizTypeSelectList( Window* pParent, WinBits nStyle = WB_BORDER ) : MultiListBox(pParent,nStyle) {};\n OWizTypeSelectList( Window* pParent, const ResId& rResId ) : MultiListBox(pParent,rResId) {};\n void SetPKey(sal_Bool bPKey) { m_bPKey = bPKey; }\n };\n\n \/\/ ========================================================\n \/\/ Wizard Page: OWizTypeSelect\n \/\/ Dient als Basis Klasse fuer unterschiedliche Kopiereigenschaften\n \/\/ FillColumnList wird aufgerufen, wenn der Button AUTO ausgeloest wird.\n \/\/ ========================================================\n class OWizTypeSelect : public OWizardPage\n {\n friend class OWizTypeSelectControl;\n friend class OWizTypeSelectList;\n\n DECL_LINK( ColumnSelectHdl, MultiListBox* );\n DECL_LINK( ButtonClickHdl, Button * );\n protected:\n OWizTypeSelectList m_lbColumnNames;\n FixedLine m_flColumns;\n OWizTypeSelectControl m_aTypeControl;\n FixedLine m_flAutoType;\n FixedText m_ftAuto;\n NumericField m_etAuto;\n PushButton m_pbAuto;\n\n Image m_imgPKey;\n SvStream* m_pParserStream; \/\/ stream to read the tokens from or NULL\n ::rtl::OUString m_sAutoIncrementValue;\n sal_Int32 m_nDisplayRow;\n sal_Bool m_bAutoIncrementEnabled;\n sal_Bool m_bDuplicateName;\n\n void fillColumnList(sal_uInt32 nRows);\n virtual SvParser* createReader(sal_Int32 _nRows) = 0;\n\n void EnableAuto(sal_Bool bEnable);\n public:\n virtual void Reset ( );\n virtual void ActivatePage( );\n virtual void Resize();\n virtual sal_Bool LeavePage();\n virtual String GetTitle() const;\n\n OWizTypeSelect(Window* pParent, SvStream* _pStream = NULL );\n virtual ~OWizTypeSelect();\n\n inline void setDisplayRow(sal_Int32 _nRow) { m_nDisplayRow = _nRow - 1; }\n inline void setDuplicateName(sal_Bool _bDuplicateName) { m_bDuplicateName = _bDuplicateName; }\n };\n\n \/\/ ========================================================\n typedef OWizTypeSelect* (*TypeSelectionPageFactory)( Window*, SvStream& );\n}\n#endif \/\/ DBAUI_WIZ_TYPESELECT_HXX\n\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/x86\/insts\/microldstop.hh\"\n#include \n\nnamespace X86ISA\n{\n std::string LdStOp::generateDisassembly(Addr pc,\n const SymbolTable *symtab) const\n {\n std::stringstream response;\n\n printMnemonic(response, instMnem, mnemonic);\n printDestReg(response, 0, dataSize);\n response << \", \";\n printSegment(response, segment);\n ccprintf(response, \":[%d*\", scale);\n printSrcReg(response, 0, addressSize);\n response << \" + \";\n printSrcReg(response, 1, addressSize);\n ccprintf(response, \" + %#x]\", disp);\n return response.str();\n }\n}\nX86: Hide the irrelevant portions of the address components for load and store microops.\/*\n * Copyright (c) 2007 The Hewlett-Packard Development Company\n * All rights reserved.\n *\n * Redistribution and use of this software in source and binary forms,\n * with or without modification, are permitted provided that the\n * following conditions are met:\n *\n * The software must be used only for Non-Commercial Use which means any\n * use which is NOT directed to receiving any direct monetary\n * compensation for, or commercial advantage from such use. Illustrative\n * examples of non-commercial use are academic research, personal study,\n * teaching, education and corporate research & development.\n * Illustrative examples of commercial use are distributing products for\n * commercial advantage and providing services using the software for\n * commercial advantage.\n *\n * If you wish to use this software or functionality therein that may be\n * covered by patents for commercial use, please contact:\n * Director of Intellectual Property Licensing\n * Office of Strategy and Technology\n * Hewlett-Packard Company\n * 1501 Page Mill Road\n * Palo Alto, California 94304\n *\n * Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer. Redistributions\n * in binary form must reproduce the above copyright notice, this list of\n * conditions and the following disclaimer in the documentation and\/or\n * other materials provided with the distribution. Neither the name of\n * the COPYRIGHT HOLDER(s), HEWLETT-PACKARD COMPANY, nor the names of its\n * contributors may be used to endorse or promote products derived from\n * this software without specific prior written permission. No right of\n * sublicense is granted herewith. Derivatives of the software and\n * output created using the software may be prepared, but only for\n * Non-Commercial Uses. Derivatives of the software may be shared with\n * others provided: (i) the others agree to abide by the list of\n * conditions herein which includes the Non-Commercial Use restrictions;\n * and (ii) such Derivatives of the software include the above copyright\n * notice to acknowledge the contribution from this software where\n * applicable, this list of conditions and the disclaimer below.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\n * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\n * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\n * Authors: Gabe Black\n *\/\n\n#include \"arch\/x86\/insts\/microldstop.hh\"\n#include \n\nnamespace X86ISA\n{\n std::string LdStOp::generateDisassembly(Addr pc,\n const SymbolTable *symtab) const\n {\n std::stringstream response;\n bool someAddr = false;\n\n printMnemonic(response, instMnem, mnemonic);\n if(flags[IsLoad])\n printDestReg(response, 0, dataSize);\n else\n printSrcReg(response, 2, dataSize);\n response << \", \";\n printSegment(response, segment);\n response << \":[\";\n if(scale != 0 && _srcRegIdx[0] != ZeroReg)\n {\n if(scale != 1)\n ccprintf(response, \"%d*\", scale);\n printSrcReg(response, 0, addressSize);\n someAddr = true;\n }\n if(_srcRegIdx[1] != ZeroReg)\n {\n if(someAddr)\n response << \" + \";\n printSrcReg(response, 1, addressSize);\n someAddr = true;\n }\n if(disp != 0)\n {\n if(someAddr)\n response << \" + \";\n ccprintf(response, \"%#x\", disp);\n someAddr = true;\n }\n if(!someAddr)\n response << \"0\";\n response << \"]\";\n return response.str();\n }\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n\n#include \"AnalysisProcessor.h\"\n#include \"pin.H\"\n\n#define CB_BEFORE 0\n#define CB_AFTER 1\n\nextern AnalysisProcessor ap;\n\n\n\/* NameSapce for all Python Bindings variables *\/\nnamespace PyTritonOptions {\n\n \/* Debug configurations *\/\n bool dumpStats = false;\n bool dumpTrace = false;\n\n \/* Execution configurations *\/\n char *startAnalysisFromSymbol = NULL;\n std::set startAnalysisFromAddr;\n std::set stopAnalysisFromAddr;\n\n \/* Callback configurations *\/\n PyObject *callbackBefore = NULL; \/\/ Before the instruction processing\n PyObject *callbackAfter = NULL; \/\/ After the instruction processing\n\n \/* Taint configurations *\/\n std::map> taintRegFromAddr; \/\/ \n std::map> untaintRegFromAddr; \/\/ \n std::map> taintMemFromAddr; \/\/ \n std::map> untaintMemFromAddr; \/\/ \n};\n\n\nstatic char Triton_addCallback_doc[] = \"Add a callback for each instruction instrumented\";\nstatic PyObject *Triton_addCallback(PyObject *self, PyObject *args)\n{\n PyObject *function;\n PyObject *flag;\n\n \/* Extract arguments *\/\n PyArg_ParseTuple(args, \"O|O\", &function, &flag);\n\n if (!PyCallable_Check(function)){\n PyErr_Format(PyExc_TypeError, \"addCallback(): expected a function callback as first argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the second arg is CB_BEFORE or CB_AFTER *\/\n if (!PyLong_Check(flag) && !PyInt_Check(flag)) {\n PyErr_Format(PyExc_TypeError, \"addCallback(): expected an integer as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n if (PyLong_AsLong(flag) == CB_BEFORE)\n PyTritonOptions::callbackBefore = function;\n else if ((PyLong_AsLong(flag) == CB_AFTER))\n PyTritonOptions::callbackAfter = function;\n else {\n PyErr_Format(PyExc_TypeError, \"addCallback(): expected CB_BEFORE or CB_AFTER as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n return Py_None;\n}\n\n\nstatic char Triton_dumpTrace_doc[] = \"Dump the trace at the end of the execution\";\nstatic PyObject *Triton_dumpTrace(PyObject *self, PyObject *flag)\n{\n if (!PyBool_Check(flag)){\n PyErr_Format(PyExc_TypeError, \"dumpTrace(): expected a boolean\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::dumpTrace = (flag == Py_True);\n return Py_None;\n}\n\n\nstatic char Triton_dumpStats_doc[] = \"Dump statistics at the end of the execution\";\nstatic PyObject *Triton_dumpStats(PyObject *self, PyObject *flag)\n{\n if (!PyBool_Check(flag)){\n PyErr_Format(PyExc_TypeError, \"dumpStats(): expected a boolean\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::dumpStats = (flag == Py_True);\n return Py_None;\n}\n\n\nstatic char Triton_isMemTainted_doc[] = \"Check if the memory is tainted\";\nstatic PyObject *Triton_isMemTainted(PyObject *self, PyObject *mem)\n{\n if (!PyLong_Check(mem) && !PyInt_Check(mem)){\n PyErr_Format(PyExc_TypeError, \"isMemTainted(): expected an address (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n if (ap.isMemTainted(PyInt_AsLong(mem)) == true)\n return Py_True;\n return Py_False;\n}\n\n\nstatic char Triton_isRegTainted_doc[] = \"Check if the register is tainted\";\nstatic PyObject *Triton_isRegTainted(PyObject *self, PyObject *reg)\n{\n if (!PyLong_Check(reg) && !PyInt_Check(reg)){\n PyErr_Format(PyExc_TypeError, \"isRegTainted(): expected a reg (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n if (ap.isRegTainted(PyInt_AsLong(reg)) == true)\n return Py_True;\n return Py_False;\n}\n\n\nstatic char Triton_opcodeToString_doc[] = \"Returns a string with the opcode of the instruction\";\nstatic PyObject *Triton_opcodeToString(PyObject *self, PyObject *opcode)\n{\n if (!PyLong_Check(opcode) && !PyInt_Check(opcode)){\n PyErr_Format(PyExc_TypeError, \"opcodeToString(): expected an opcode (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n return Py_BuildValue(\"s\", OPCODE_StringShort(PyInt_AsLong(opcode)).c_str());\n}\n\n\nstatic char Triton_runProgram_doc[] = \"Start the Pin instrumentation\";\nstatic PyObject *Triton_runProgram(PyObject *self, PyObject *noarg)\n{\n \/\/ Never returns - Rock 'n roll baby \\o\/\n PIN_StartProgram();\n return Py_None;\n}\n\n\nstatic char Triton_startAnalysisFromSymbol_doc[] = \"Start the symbolic execution from a specific name point\";\nstatic PyObject *Triton_startAnalysisFromSymbol(PyObject *self, PyObject *name)\n{\n\n if (!PyString_Check(name)){\n PyErr_Format(PyExc_TypeError, \"startAnalysisFromSymbol(): expected a string as argument\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::startAnalysisFromSymbol = PyString_AsString(name);\n return Py_None;\n}\n\n\nstatic char Triton_startAnalysisFromAddr_doc[] = \"Start the symbolic execution from a specific address\";\nstatic PyObject *Triton_startAnalysisFromAddr(PyObject *self, PyObject *addr)\n{\n\n if (!PyLong_Check(addr) && !PyInt_Check(addr)){\n PyErr_Format(PyExc_TypeError, \"startAnalysisFromAddr(): expected an address as argument\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::startAnalysisFromAddr.insert(PyLong_AsLong(addr));\n return Py_None;\n}\n\n\nstatic char Triton_stopAnalysisFromAddr_doc[] = \"Stop the symbolic execution from a specific address\";\nstatic PyObject *Triton_stopAnalysisFromAddr(PyObject *self, PyObject *addr)\n{\n\n if (!PyLong_Check(addr) && !PyInt_Check(addr)){\n PyErr_Format(PyExc_TypeError, \"stopAnalysisFromAddr(): expected an address\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::stopAnalysisFromAddr.insert(PyLong_AsLong(addr));\n return Py_None;\n}\n\n\nstatic char Triton_taintRegFromAddr_doc[] = \"Taint specific registers from an address\";\nstatic PyObject *Triton_taintRegFromAddr(PyObject *self, PyObject *args)\n{\n PyObject *addr;\n PyObject *regs;\n std::list regsList;\n\n \/* Extract arguments *\/\n PyArg_ParseTuple(args, \"O|O\", &addr, ®s);\n\n \/* Check if the first arg (addr) is a integer *\/\n if (!PyLong_Check(addr) && !PyInt_Check(addr)) {\n PyErr_Format(PyExc_TypeError, \"taintRegFromAddr(): expected an address as first argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the second arg (regs) is a list *\/\n if (!PyList_Check(regs)) {\n PyErr_Format(PyExc_TypeError, \"taintRegFromAddr(): expected a list as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the regs list contains only integer item and craft a std::list *\/\n for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){\n PyObject *item = PyList_GetItem(regs, i);\n if (!PyLong_Check(item) && !PyInt_Check(item)){\n PyErr_Format(PyExc_TypeError, \"taintRegFromAddr(): The second argument must be a list of integer\");\n PyErr_Print();\n exit(-1);\n }\n regsList.push_back(PyLong_AsLong(item));\n }\n\n \/* Update taint configuration *\/\n PyTritonOptions::taintRegFromAddr.insert(std::pair>(PyLong_AsLong(addr), regsList));\n return Py_None;\n}\n\n\nstatic char Triton_untaintRegFromAddr_doc[] = \"Untaint specific registers from an address\";\nstatic PyObject *Triton_untaintRegFromAddr(PyObject *self, PyObject *args)\n{\n PyObject *addr;\n PyObject *regs;\n std::list regsList;\n\n \/* Extract arguments *\/\n PyArg_ParseTuple(args, \"O|O\", &addr, ®s);\n\n \/* Check if the first arg (addr) is a integer *\/\n if (!PyLong_Check(addr) && !PyInt_Check(addr)) {\n PyErr_Format(PyExc_TypeError, \"untaintRegFromAddr(): expected an address as first argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the second arg (regs) is a list *\/\n if (!PyList_Check(regs)) {\n PyErr_Format(PyExc_TypeError, \"untaintRegFromAddr(): expected a list as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the regs list contains only integer item and craft a std::list *\/\n for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){\n PyObject *item = PyList_GetItem(regs, i);\n if (!PyLong_Check(item) && !PyInt_Check(item)){\n PyErr_Format(PyExc_TypeError, \"untaintRegFromAddr(): The second argument must be a list of integer\");\n PyErr_Print();\n exit(-1);\n }\n regsList.push_back(PyLong_AsLong(item));\n }\n\n \/* Update taint configuration *\/\n PyTritonOptions::untaintRegFromAddr.insert(std::pair>(PyLong_AsLong(addr), regsList));\n\n return Py_None;\n}\n\n\nPyMethodDef pythonCallbacks[] = {\n {\"addCallback\", Triton_addCallback, METH_VARARGS, Triton_addCallback_doc},\n {\"dumpStats\", Triton_dumpStats, METH_O, Triton_dumpStats_doc},\n {\"dumpTrace\", Triton_dumpTrace, METH_O, Triton_dumpTrace_doc},\n {\"isMemTainted\", Triton_isMemTainted, METH_O, Triton_isMemTainted_doc},\n {\"isRegTainted\", Triton_isRegTainted, METH_O, Triton_isRegTainted_doc},\n {\"opcodeToString\", Triton_opcodeToString, METH_O, Triton_opcodeToString_doc},\n {\"runProgram\", Triton_runProgram, METH_NOARGS, Triton_runProgram_doc},\n {\"startAnalysisFromAddr\", Triton_startAnalysisFromAddr, METH_O, Triton_startAnalysisFromAddr_doc},\n {\"startAnalysisFromSymbol\", Triton_startAnalysisFromSymbol, METH_O, Triton_startAnalysisFromSymbol_doc},\n {\"stopAnalysisFromAddr\", Triton_stopAnalysisFromAddr, METH_O, Triton_stopAnalysisFromAddr_doc},\n {\"taintRegFromAddr\", Triton_taintRegFromAddr, METH_VARARGS, Triton_taintRegFromAddr_doc},\n {\"untaintRegFromAddr\", Triton_untaintRegFromAddr, METH_VARARGS, Triton_untaintRegFromAddr_doc},\n {NULL, NULL, 0, NULL}\n};\n\nExport taintReg() and untaintReg() into Python bindings\n#include \n#include \n#include \n#include \n\n#include \"AnalysisProcessor.h\"\n#include \"pin.H\"\n\n#define CB_BEFORE 0\n#define CB_AFTER 1\n\nextern AnalysisProcessor ap;\n\n\n\/* NameSapce for all Python Bindings variables *\/\nnamespace PyTritonOptions {\n\n \/* Debug configurations *\/\n bool dumpStats = false;\n bool dumpTrace = false;\n\n \/* Execution configurations *\/\n char *startAnalysisFromSymbol = NULL;\n std::set startAnalysisFromAddr;\n std::set stopAnalysisFromAddr;\n\n \/* Callback configurations *\/\n PyObject *callbackBefore = NULL; \/\/ Before the instruction processing\n PyObject *callbackAfter = NULL; \/\/ After the instruction processing\n\n \/* Taint configurations *\/\n std::map> taintRegFromAddr; \/\/ \n std::map> untaintRegFromAddr; \/\/ \n std::map> taintMemFromAddr; \/\/ \n std::map> untaintMemFromAddr; \/\/ \n};\n\n\nstatic char Triton_addCallback_doc[] = \"Add a callback for each instruction instrumented\";\nstatic PyObject *Triton_addCallback(PyObject *self, PyObject *args)\n{\n PyObject *function;\n PyObject *flag;\n\n \/* Extract arguments *\/\n PyArg_ParseTuple(args, \"O|O\", &function, &flag);\n\n if (!PyCallable_Check(function)){\n PyErr_Format(PyExc_TypeError, \"addCallback(): expected a function callback as first argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the second arg is CB_BEFORE or CB_AFTER *\/\n if (!PyLong_Check(flag) && !PyInt_Check(flag)) {\n PyErr_Format(PyExc_TypeError, \"addCallback(): expected an integer as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n if (PyLong_AsLong(flag) == CB_BEFORE)\n PyTritonOptions::callbackBefore = function;\n else if ((PyLong_AsLong(flag) == CB_AFTER))\n PyTritonOptions::callbackAfter = function;\n else {\n PyErr_Format(PyExc_TypeError, \"addCallback(): expected CB_BEFORE or CB_AFTER as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n return Py_None;\n}\n\n\nstatic char Triton_dumpTrace_doc[] = \"Dump the trace at the end of the execution\";\nstatic PyObject *Triton_dumpTrace(PyObject *self, PyObject *flag)\n{\n if (!PyBool_Check(flag)){\n PyErr_Format(PyExc_TypeError, \"dumpTrace(): expected a boolean\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::dumpTrace = (flag == Py_True);\n return Py_None;\n}\n\n\nstatic char Triton_dumpStats_doc[] = \"Dump statistics at the end of the execution\";\nstatic PyObject *Triton_dumpStats(PyObject *self, PyObject *flag)\n{\n if (!PyBool_Check(flag)){\n PyErr_Format(PyExc_TypeError, \"dumpStats(): expected a boolean\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::dumpStats = (flag == Py_True);\n return Py_None;\n}\n\n\nstatic char Triton_isMemTainted_doc[] = \"Check if the memory is tainted\";\nstatic PyObject *Triton_isMemTainted(PyObject *self, PyObject *mem)\n{\n if (!PyLong_Check(mem) && !PyInt_Check(mem)){\n PyErr_Format(PyExc_TypeError, \"isMemTainted(): expected an address (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n if (ap.isMemTainted(PyInt_AsLong(mem)) == true)\n return Py_True;\n return Py_False;\n}\n\n\nstatic char Triton_isRegTainted_doc[] = \"Check if the register is tainted\";\nstatic PyObject *Triton_isRegTainted(PyObject *self, PyObject *reg)\n{\n if (!PyLong_Check(reg) && !PyInt_Check(reg)){\n PyErr_Format(PyExc_TypeError, \"isRegTainted(): expected a reg id (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n if (ap.isRegTainted(PyInt_AsLong(reg)) == true)\n return Py_True;\n return Py_False;\n}\n\n\nstatic char Triton_opcodeToString_doc[] = \"Returns a string with the opcode of the instruction\";\nstatic PyObject *Triton_opcodeToString(PyObject *self, PyObject *opcode)\n{\n if (!PyLong_Check(opcode) && !PyInt_Check(opcode)){\n PyErr_Format(PyExc_TypeError, \"opcodeToString(): expected an opcode (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n return Py_BuildValue(\"s\", OPCODE_StringShort(PyInt_AsLong(opcode)).c_str());\n}\n\n\nstatic char Triton_runProgram_doc[] = \"Start the Pin instrumentation\";\nstatic PyObject *Triton_runProgram(PyObject *self, PyObject *noarg)\n{\n \/\/ Never returns - Rock 'n roll baby \\o\/\n PIN_StartProgram();\n return Py_None;\n}\n\n\nstatic char Triton_startAnalysisFromSymbol_doc[] = \"Start the symbolic execution from a specific name point\";\nstatic PyObject *Triton_startAnalysisFromSymbol(PyObject *self, PyObject *name)\n{\n\n if (!PyString_Check(name)){\n PyErr_Format(PyExc_TypeError, \"startAnalysisFromSymbol(): expected a string as argument\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::startAnalysisFromSymbol = PyString_AsString(name);\n return Py_None;\n}\n\n\nstatic char Triton_startAnalysisFromAddr_doc[] = \"Start the symbolic execution from a specific address\";\nstatic PyObject *Triton_startAnalysisFromAddr(PyObject *self, PyObject *addr)\n{\n\n if (!PyLong_Check(addr) && !PyInt_Check(addr)){\n PyErr_Format(PyExc_TypeError, \"startAnalysisFromAddr(): expected an address as argument\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::startAnalysisFromAddr.insert(PyLong_AsLong(addr));\n return Py_None;\n}\n\n\nstatic char Triton_stopAnalysisFromAddr_doc[] = \"Stop the symbolic execution from a specific address\";\nstatic PyObject *Triton_stopAnalysisFromAddr(PyObject *self, PyObject *addr)\n{\n\n if (!PyLong_Check(addr) && !PyInt_Check(addr)){\n PyErr_Format(PyExc_TypeError, \"stopAnalysisFromAddr(): expected an address\");\n PyErr_Print();\n exit(-1);\n }\n PyTritonOptions::stopAnalysisFromAddr.insert(PyLong_AsLong(addr));\n return Py_None;\n}\n\n\nstatic char Triton_taintReg_doc[] = \"Taint a register\";\nstatic PyObject *Triton_taintReg(PyObject *self, PyObject *reg)\n{\n if (!PyLong_Check(reg) && !PyInt_Check(reg)){\n PyErr_Format(PyExc_TypeError, \"taintReg(): expected a reg id (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n ap.taintReg(PyInt_AsLong(reg));\n return Py_None;\n}\n\n\nstatic char Triton_taintRegFromAddr_doc[] = \"Taint specific registers from an address\";\nstatic PyObject *Triton_taintRegFromAddr(PyObject *self, PyObject *args)\n{\n PyObject *addr;\n PyObject *regs;\n std::list regsList;\n\n \/* Extract arguments *\/\n PyArg_ParseTuple(args, \"O|O\", &addr, ®s);\n\n \/* Check if the first arg (addr) is a integer *\/\n if (!PyLong_Check(addr) && !PyInt_Check(addr)) {\n PyErr_Format(PyExc_TypeError, \"taintRegFromAddr(): expected an address as first argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the second arg (regs) is a list *\/\n if (!PyList_Check(regs)) {\n PyErr_Format(PyExc_TypeError, \"taintRegFromAddr(): expected a list as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the regs list contains only integer item and craft a std::list *\/\n for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){\n PyObject *item = PyList_GetItem(regs, i);\n if (!PyLong_Check(item) && !PyInt_Check(item)){\n PyErr_Format(PyExc_TypeError, \"taintRegFromAddr(): The second argument must be a list of reg id (integer)\");\n PyErr_Print();\n exit(-1);\n }\n regsList.push_back(PyLong_AsLong(item));\n }\n\n \/* Update taint configuration *\/\n PyTritonOptions::taintRegFromAddr.insert(std::pair>(PyLong_AsLong(addr), regsList));\n return Py_None;\n}\n\n\nstatic char Triton_untaintReg_doc[] = \"Untaint a register\";\nstatic PyObject *Triton_untaintReg(PyObject *self, PyObject *reg)\n{\n if (!PyLong_Check(reg) && !PyInt_Check(reg)){\n PyErr_Format(PyExc_TypeError, \"untaintReg(): expected a reg id (integer) as argument\");\n PyErr_Print();\n exit(-1);\n }\n ap.untaintReg(PyInt_AsLong(reg));\n return Py_None;\n}\n\n\nstatic char Triton_untaintRegFromAddr_doc[] = \"Untaint specific registers from an address\";\nstatic PyObject *Triton_untaintRegFromAddr(PyObject *self, PyObject *args)\n{\n PyObject *addr;\n PyObject *regs;\n std::list regsList;\n\n \/* Extract arguments *\/\n PyArg_ParseTuple(args, \"O|O\", &addr, ®s);\n\n \/* Check if the first arg (addr) is a integer *\/\n if (!PyLong_Check(addr) && !PyInt_Check(addr)) {\n PyErr_Format(PyExc_TypeError, \"untaintRegFromAddr(): expected an address as first argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the second arg (regs) is a list *\/\n if (!PyList_Check(regs)) {\n PyErr_Format(PyExc_TypeError, \"untaintRegFromAddr(): expected a list as second argument\");\n PyErr_Print();\n exit(-1);\n }\n\n \/* Check if the regs list contains only integer item and craft a std::list *\/\n for (Py_ssize_t i = 0; i < PyList_Size(regs); i++){\n PyObject *item = PyList_GetItem(regs, i);\n if (!PyLong_Check(item) && !PyInt_Check(item)){\n PyErr_Format(PyExc_TypeError, \"untaintRegFromAddr(): The second argument must be a list of reg id (integer)\");\n PyErr_Print();\n exit(-1);\n }\n regsList.push_back(PyLong_AsLong(item));\n }\n\n \/* Update taint configuration *\/\n PyTritonOptions::untaintRegFromAddr.insert(std::pair>(PyLong_AsLong(addr), regsList));\n\n return Py_None;\n}\n\n\nPyMethodDef pythonCallbacks[] = {\n {\"addCallback\", Triton_addCallback, METH_VARARGS, Triton_addCallback_doc},\n {\"dumpStats\", Triton_dumpStats, METH_O, Triton_dumpStats_doc},\n {\"dumpTrace\", Triton_dumpTrace, METH_O, Triton_dumpTrace_doc},\n {\"isMemTainted\", Triton_isMemTainted, METH_O, Triton_isMemTainted_doc},\n {\"isRegTainted\", Triton_isRegTainted, METH_O, Triton_isRegTainted_doc},\n {\"opcodeToString\", Triton_opcodeToString, METH_O, Triton_opcodeToString_doc},\n {\"runProgram\", Triton_runProgram, METH_NOARGS, Triton_runProgram_doc},\n {\"startAnalysisFromAddr\", Triton_startAnalysisFromAddr, METH_O, Triton_startAnalysisFromAddr_doc},\n {\"startAnalysisFromSymbol\", Triton_startAnalysisFromSymbol, METH_O, Triton_startAnalysisFromSymbol_doc},\n {\"stopAnalysisFromAddr\", Triton_stopAnalysisFromAddr, METH_O, Triton_stopAnalysisFromAddr_doc},\n {\"taintReg\", Triton_taintReg, METH_O, Triton_taintReg_doc},\n {\"taintRegFromAddr\", Triton_taintRegFromAddr, METH_VARARGS, Triton_taintRegFromAddr_doc},\n {\"untaintReg\", Triton_untaintReg, METH_O, Triton_untaintReg_doc},\n {\"untaintRegFromAddr\", Triton_untaintRegFromAddr, METH_VARARGS, Triton_untaintRegFromAddr_doc},\n {NULL, NULL, 0, NULL}\n};\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2021 by Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n#ifndef IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP\n#define IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP\n\n#include \n#include \n\nnamespace iox\n{\nnamespace posix\n{\nclass UnixDomainSocket;\n}\n\nnamespace platform\n{\nconstexpr uint64_t IOX_MAX_FILENAME_LENGTH = 255U;\nconstexpr uint64_t IOX_MAX_PATH_LENGTH = 1023U;\nconstexpr bool IOX_SHM_WRITE_ZEROS_ON_CREATION = true;\nconstexpr uint64_t IOX_MAX_SHM_NAME_LENGTH = SHM_NAME_MAX;\nconstexpr const char IOX_PATH_SEPARATORS[] = \"\/\";\nconstexpr uint64_t IOX_UDS_SOCKET_MAX_MESSAGE_SIZE = 2048;\nconstexpr const char IOX_UDS_SOCKET_PATH_PREFIX[] = \"\/tmp\/\";\nconstexpr const char IOX_LOCK_FILE_PATH_PREFIX[] = \"\/tmp\/\";\nusing IoxIpcChannelType = iox::posix::UnixDomainSocket;\n} \/\/ namespace platform\n} \/\/ namespace iox\n\n#endif \/\/ IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP\niox-#33 Use MAX_SHM_NAME_LENGTH value from windows in mac\/\/ Copyright (c) 2021 by Apex.AI Inc. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ SPDX-License-Identifier: Apache-2.0\n#ifndef IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP\n#define IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP\n\n#include \n\nnamespace iox\n{\nnamespace posix\n{\nclass UnixDomainSocket;\n}\n\nnamespace platform\n{\nconstexpr uint64_t IOX_MAX_FILENAME_LENGTH = 255U;\nconstexpr uint64_t IOX_MAX_PATH_LENGTH = 1023U;\nconstexpr bool IOX_SHM_WRITE_ZEROS_ON_CREATION = true;\n\/\/ it should be SHM_NAME_MAX but it is unknown in which header this define\n\/\/ is defined\nconstexpr uint64_t IOX_MAX_SHM_NAME_LENGTH = 255U;\nconstexpr const char IOX_PATH_SEPARATORS[] = \"\/\";\nconstexpr uint64_t IOX_UDS_SOCKET_MAX_MESSAGE_SIZE = 2048;\nconstexpr const char IOX_UDS_SOCKET_PATH_PREFIX[] = \"\/tmp\/\";\nconstexpr const char IOX_LOCK_FILE_PATH_PREFIX[] = \"\/tmp\/\";\nusing IoxIpcChannelType = iox::posix::UnixDomainSocket;\n} \/\/ namespace platform\n} \/\/ namespace iox\n\n#endif \/\/ IOX_HOOFS_MAC_PLATFORM_PLATFORM_SETTINGS_HPP\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2003-2006 Funambol\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n\n#include \"base\/memTracker.h\"\n\n\nMemTracker::MemTracker(bool useMemTracking) {\n tracking = useMemTracking;\n}\n\nMemTracker::~MemTracker() {}\n\n\n\/\/ Add alloc informations to the list.\nvoid MemTracker::addTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum) {\n\t\n\tAllocInfo info;\n\tstrncpy(info.file, fname, MAX_LENGHT_FILE-1);\n\tinfo.address = addr;\n\tinfo.line\t = lnum;\n\tinfo.size\t = asize;\n\n allocList.add(info);\n}\n\n\n\/\/ Remove alloc informations from the list by the given address.\nvoid MemTracker::removeTrack(DWORD addr) {\n\t\n\tint size = allocList.size();\n if (!size)\n\t\treturn;\n\t\n if ( addr == ((AllocInfo*)allocList.front())->address ) {\n allocList.remove(0);\n return;\n }\n else {\n int i;\n\t for (i=1; iaddress ) {\n allocList.remove(i);\n\t\t\t break;\n }\n\t }\n }\t \n}\n\n\n\/\/ To print final results of memory allocations.\nvoid MemTracker::dumpUnfreed() {\n\n DWORD totalSize = 0;\n\tAllocInfo *info;\n\tint i;\n\n disableMemTracker();\n\n int size = allocList.size();\n\tLOG.debug(\"-------------------- MEMORY LEAKS: ------------------------\");\n LOG.debug(\"-----------------------------------------------------------\");\n LOG.debug(\"%d leaks found!\", size);\n\n info = (AllocInfo*)allocList.front();\n LOG.debug(\"addr: %lx - size:%3ld, file: %s:%d\", info->address, info->size, info->file, info->line);\n for(i=1; iaddress, info->size, info->file, info->line);\n\t\ttotalSize += info->size;\n\t}\n\n\tLOG.debug(\"Total Unfreed: %d bytes\", totalSize);\n LOG.debug(\"-----------------------------------------------------------\\n\");\n\n allocList.clear();\n}\n\n\n\/\/\n\/\/ Functions to enable\/disable tracking of memory leaks.\n\/\/ Note: need to disable trackers when calling add\/removeTracker\n\/\/ to avoid loops into new\/delete operators!\n\/\/ \nvoid MemTracker::enableMemTracker() {\n tracking = TRUE;\n}\nvoid MemTracker::disableMemTracker() {\n tracking = FALSE;\n}\n\n\/\/ Are we tracking memory leaks?\nbool MemTracker::isMemTracking() {\n return tracking;\n}\n\n\n\/\/ -------------------------------------------------\n\n\/\/ not used\nArrayElement* AllocInfo::clone() {\n AllocInfo* ret = new AllocInfo();\n ret->address = address;\n ret->size = size;\n ret->line = line;\n strncpy(ret->file, file, MAX_LENGHT_FILE-1);\n return ret;\n}\n\n\n\ncorrection to MemTracker\/*\n * Copyright (C) 2003-2006 Funambol\n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n\n#include \"base\/memTracker.h\"\n\n\nMemTracker::MemTracker(bool useMemTracking) {\n tracking = useMemTracking;\n}\n\nMemTracker::~MemTracker() {}\n\n\n\/\/ Add alloc informations to the list.\nvoid MemTracker::addTrack(DWORD addr, DWORD asize, const char *fname, DWORD lnum) {\n\t\n\tAllocInfo info;\n\tstrncpy(info.file, fname, MAX_LENGHT_FILE-1);\n\tinfo.address = addr;\n\tinfo.line\t = lnum;\n\tinfo.size\t = asize;\n\n allocList.add(info);\n}\n\n\n\/\/ Remove alloc informations from the list by the given address.\nvoid MemTracker::removeTrack(DWORD addr) {\n\t\n\tint size = allocList.size();\n if (!size)\n\t\treturn;\n\t\n if ( addr == ((AllocInfo*)allocList.front())->address ) {\n allocList.remove(0);\n return;\n }\n else {\n int i;\n\t for (i=1; iaddress ) {\n allocList.remove(i);\n\t\t\t break;\n }\n\t }\n }\t \n}\n\n\n\/\/ To print final results of memory allocations.\nvoid MemTracker::dumpUnfreed() {\n\n DWORD totalSize = 0;\n\tAllocInfo *info;\n\tint i;\n\n disableMemTracker();\n\n int size = allocList.size();\n\tLOG.debug(\"-------------------- MEMORY LEAKS: ------------------------\");\n LOG.debug(\"-----------------------------------------------------------\");\n LOG.debug(\"%d leaks found!\", size);\n\n info = (AllocInfo*)allocList.front();\n LOG.debug(\"addr: %lx - size:%3ld, file: %s:%d\", info->address, info->size, info->file, info->line);\n\ttotalSize += info->size;\n for(i=1; iaddress, info->size, info->file, info->line);\n\t\ttotalSize += info->size;\n\t}\n\n\tLOG.debug(\"Total Unfreed: %d bytes\", totalSize);\n LOG.debug(\"-----------------------------------------------------------\\n\");\n\n allocList.clear();\n}\n\n\n\/\/\n\/\/ Functions to enable\/disable tracking of memory leaks.\n\/\/ Note: need to disable trackers when calling add\/removeTracker\n\/\/ to avoid loops into new\/delete operators!\n\/\/ \nvoid MemTracker::enableMemTracker() {\n tracking = TRUE;\n}\nvoid MemTracker::disableMemTracker() {\n tracking = FALSE;\n}\n\n\/\/ Are we tracking memory leaks?\nbool MemTracker::isMemTracking() {\n return tracking;\n}\n\n\n\/\/ -------------------------------------------------\n\n\/\/ not used\nArrayElement* AllocInfo::clone() {\n AllocInfo* ret = new AllocInfo();\n ret->address = address;\n ret->size = size;\n ret->line = line;\n strncpy(ret->file, file, MAX_LENGHT_FILE-1);\n return ret;\n}\n\n\n\n<|endoftext|>"} {"text":"\/*\n * This file is part of the µOS++ distribution.\n * (https:\/\/github.com\/micro-os-plus)\n * Copyright (c) 2016 Liviu Ionescu.\n *\n * µOS++ is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, version 3.\n *\n * µOS++ is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n\n#include \n#include \n\n\/\/ ----------------------------------------------------------------------------\n\n#include \n#include \n#include \n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace os\n{\n namespace rtos\n {\n static Systick_clock::rep __systick_now;\n static Realtime_clock::rep __rtc_now;\n\n } \/* namespace rtos *\/\n} \/* namespace os *\/\n\n\/\/ ----------------------------------------------------------------------------\n\nvoid\nos_systick_handler (void)\n{\n using namespace os::rtos;\n\n \/\/ Prevent scheduler actions before starting it.\n if (scheduler::started ())\n {\n os_impl_systick_handler ();\n }\n __systick_now++;\n\n#if !defined(OS_INCLUDE_REALTIME_CLOCK_DRIVER)\n static uint32_t ticks = Systick_clock::frequency_hz;\n\n if (--ticks == 0)\n {\n ticks = Systick_clock::frequency_hz;\n\n os_rtc_handler ();\n }\n#endif\n}\n\nvoid\nos_rtc_handler (void)\n{\n using namespace os::rtos;\n\n \/\/ Prevent scheduler actions before starting it.\n if (scheduler::started ())\n {\n os_impl_rtc_handler ();\n }\n ++__rtc_now;\n}\n\nvoid __attribute__((weak))\nos_impl_systick_handler (void)\n{\n \/\/ TODO\n}\n\nvoid __attribute__((weak))\nos_impl_rtc_handler (void)\n{\n \/\/ TODO\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace os\n{\n namespace rtos\n {\n\n#pragma GCC diagnostic push\n\/\/ TODO: remove it when fully implemented\n\/\/#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n\/\/ ======================================================================\n\n \/**\n * @details\n *\n * @note Can be invoked from Interrupt Service Routines.\n *\/\n Systick_clock::rep\n Systick_clock::now (void)\n {\n Critical_section_irq cs; \/\/ ---- Critical section -----\n\n \/\/ Prevent inconsistent values using the critical section.\n return __systick_now;\n }\n\n \/**\n * @details\n * Return the very accurate current time, using the internal\n * SysTick cycle counter, which, at 100 MHz and 1000 ticks\/sec\n * allows a 10 ns resolution.\n *\n * The function adjust for border conditions, when the SysTick\n * counter is reloaded during the call.\n *\n * @note Can be invoked from Interrupt Service Routines.\n *\/\n Systick_clock::rep\n Systick_clock::now (current_t* details)\n {\n assert(details != nullptr);\n\n \/\/ The core frequency can be returned right away, since\n \/\/ is not expected to change during this call.\n details->core_frequency_hz = SystemCoreClock;\n\n \/\/ The timer reload value, it is the divisor - 1.\n uint32_t load = SysTick->LOAD;\n \/\/ Can also be returned right away.\n details->divisor = load + 1;\n\n \/\/ The ticks and cycles must be read atomically, use a critical\n \/\/ section and adjust for border condition, when the event\n \/\/ came exactly after entering the critical section.\n uint64_t ticks;\n uint32_t val;\n {\n Critical_section_irq cs; \/\/ ----- Critical section -----\n\n \/\/ Sample ticks counter inside critical section.\n ticks = __systick_now;\n\n \/\/ Initial sample of the decrementing counter.\n \/\/ Might happen before the event, will be used as such.\n val = SysTick->VAL;\n\n \/\/ Check overflow. If the exception is pending, it means the\n \/\/ ticks counter was not yet updated, but the counter was reloaded.\n if (SysTick->CTRL & SCB_ICSR_PENDSTSET_Msk)\n {\n \/\/ Sample the decrementing counter again to validate the\n \/\/ initial sample.\n uint32_t val_update = SysTick->VAL;\n if (val_update > val)\n {\n \/\/ The second sample is more accurate.\n val = val_update;\n }\n ticks++; \/\/ Adjust to next tick.\n }\n }\n details->cycles = load - val;\n details->ticks = ticks;\n\n return ticks;\n }\n\n \/**\n * @details\n * Put the current thread to sleep, until the next n-th\n * SysTick occurs. Depending when the call is issued, the\n * first tick counted may be very short.\n *\n * @warning Cannot be invoked from Interrupt Service Routines.\n *\/\n result_t\n Systick_clock::sleep_for (Systick_clock::sleep_rep ticks)\n {\n os_assert_err(!scheduler::in_handler_mode (), EPERM);\n\n trace::printf (\"Systick_clock::sleep_for(%d_ticks)\\n\", ticks);\n\n#if defined(OS_INCLUDE_PORT_RTOS_SYSTICK_CLOCK_SLEEP_FOR)\n return port::Systick_clock::sleep_for (ticks);\n#else\n \/\/ TODO\n return result::ok;\n#endif\n }\n\n \/**\n * @details\n *\n * @note Can be invoked from Interrupt Service Routines.\n *\/\n Realtime_clock::rep\n Realtime_clock::now (void)\n {\n return __rtc_now;\n }\n\n \/**\n * @details\n * Put the current thread to sleep, until the next n-th\n * RTC second occurs. Depending when the call is issued, the\n * first second counted may be very short.\n *\n * @warning Cannot be invoked from Interrupt Service Routines.\n *\/\n result_t\n Realtime_clock::sleep_for (Realtime_clock::sleep_rep secs)\n {\n os_assert_err(!scheduler::in_handler_mode (), EPERM);\n\n trace::printf (\"Realtime_clock::sleep_for(%ds)\\n\", secs);\n\n \/\/ TODO\n __rtc_now += secs;\n return result::ok;\n }\n\n#pragma GCC diagnostic pop\n\n } \/* namespace rtos *\/\n} \/* namespace os *\/\nos-clocks: add RTC:initialize()\/*\n * This file is part of the µOS++ distribution.\n * (https:\/\/github.com\/micro-os-plus)\n * Copyright (c) 2016 Liviu Ionescu.\n *\n * µOS++ is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as\n * published by the Free Software Foundation, version 3.\n *\n * µOS++ is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with this program. If not, see .\n *\/\n\n#include \n#include \n\n#include \n#include \n\n\/\/ ----------------------------------------------------------------------------\n\n#include \n#include \n#include \n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace os\n{\n namespace rtos\n {\n static Systick_clock::rep __systick_now;\n static Realtime_clock::rep __rtc_now;\n\n } \/* namespace rtos *\/\n} \/* namespace os *\/\n\n\/\/ ----------------------------------------------------------------------------\n\nvoid\nos_systick_handler (void)\n{\n using namespace os::rtos;\n\n \/\/ Prevent scheduler actions before starting it.\n if (scheduler::started ())\n {\n os_impl_systick_handler ();\n }\n __systick_now++;\n\n#if !defined(OS_INCLUDE_REALTIME_CLOCK_DRIVER)\n static uint32_t ticks = Systick_clock::frequency_hz;\n\n if (--ticks == 0)\n {\n ticks = Systick_clock::frequency_hz;\n\n os_rtc_handler ();\n }\n#endif\n}\n\nvoid\nos_rtc_handler (void)\n{\n using namespace os::rtos;\n\n \/\/ Prevent scheduler actions before starting it.\n if (scheduler::started ())\n {\n os_impl_rtc_handler ();\n }\n ++__rtc_now;\n}\n\nvoid __attribute__((weak))\nos_impl_systick_handler (void)\n{\n \/\/ TODO\n}\n\nvoid __attribute__((weak))\nos_impl_rtc_handler (void)\n{\n \/\/ TODO\n}\n\n\/\/ ----------------------------------------------------------------------------\n\nnamespace os\n{\n namespace rtos\n {\n\n#pragma GCC diagnostic push\n\/\/ TODO: remove it when fully implemented\n\/\/#pragma GCC diagnostic ignored \"-Wunused-parameter\"\n\n\/\/ ======================================================================\n\n \/**\n * @details\n *\n * @note Can be invoked from Interrupt Service Routines.\n *\/\n Systick_clock::rep\n Systick_clock::now (void)\n {\n Critical_section_irq cs; \/\/ ---- Critical section -----\n\n \/\/ Prevent inconsistent values using the critical section.\n return __systick_now;\n }\n\n \/**\n * @details\n * Return the very accurate current time, using the internal\n * SysTick cycle counter, which, at 100 MHz and 1000 ticks\/sec\n * allows a 10 ns resolution.\n *\n * The function adjust for border conditions, when the SysTick\n * counter is reloaded during the call.\n *\n * @note Can be invoked from Interrupt Service Routines.\n *\/\n Systick_clock::rep\n Systick_clock::now (current_t* details)\n {\n assert(details != nullptr);\n\n \/\/ The core frequency can be returned right away, since\n \/\/ is not expected to change during this call.\n details->core_frequency_hz = SystemCoreClock;\n\n \/\/ The timer reload value, it is the divisor - 1.\n uint32_t load = SysTick->LOAD;\n \/\/ Can also be returned right away.\n details->divisor = load + 1;\n\n \/\/ The ticks and cycles must be read atomically, use a critical\n \/\/ section and adjust for border condition, when the event\n \/\/ came exactly after entering the critical section.\n uint64_t ticks;\n uint32_t val;\n {\n Critical_section_irq cs; \/\/ ----- Critical section -----\n\n \/\/ Sample ticks counter inside critical section.\n ticks = __systick_now;\n\n \/\/ Initial sample of the decrementing counter.\n \/\/ Might happen before the event, will be used as such.\n val = SysTick->VAL;\n\n \/\/ Check overflow. If the exception is pending, it means the\n \/\/ ticks counter was not yet updated, but the counter was reloaded.\n if (SysTick->CTRL & SCB_ICSR_PENDSTSET_Msk)\n {\n \/\/ Sample the decrementing counter again to validate the\n \/\/ initial sample.\n uint32_t val_update = SysTick->VAL;\n if (val_update > val)\n {\n \/\/ The second sample is more accurate.\n val = val_update;\n }\n ticks++; \/\/ Adjust to next tick.\n }\n }\n details->cycles = load - val;\n details->ticks = ticks;\n\n return ticks;\n }\n\n \/**\n * @details\n * Put the current thread to sleep, until the next n-th\n * SysTick occurs. Depending when the call is issued, the\n * first tick counted may be very short.\n *\n * @warning Cannot be invoked from Interrupt Service Routines.\n *\/\n result_t\n Systick_clock::sleep_for (Systick_clock::sleep_rep ticks)\n {\n os_assert_err(!scheduler::in_handler_mode (), EPERM);\n\n trace::printf (\"Systick_clock::sleep_for(%d_ticks)\\n\", ticks);\n\n#if defined(OS_INCLUDE_PORT_RTOS_SYSTICK_CLOCK_SLEEP_FOR)\n return port::Systick_clock::sleep_for (ticks);\n#else\n \/\/ TODO\n return result::ok;\n#endif\n }\n\n \/**\n * @details\n * Must be called only once, during inits.\n *\n * @warning Cannot be invoked from Interrupt Service Routines.\n *\/\n result_t\n Realtime_clock::initialize (void)\n {\n os_assert_err(!scheduler::in_handler_mode (), EPERM);\n\n \/\/ TODO: Use the RTC driver to initialise the seconds to epoch.\n\n return result::ok;\n }\n\n \/**\n * @details\n *\n * @note Can be invoked from Interrupt Service Routines.\n *\/\n Realtime_clock::rep\n Realtime_clock::now (void)\n {\n return __rtc_now;\n }\n\n \/**\n * @details\n * Put the current thread to sleep, until the next n-th\n * RTC second occurs. Depending when the call is issued, the\n * first second counted may be very short.\n *\n * @warning Cannot be invoked from Interrupt Service Routines.\n *\/\n result_t\n Realtime_clock::sleep_for (Realtime_clock::sleep_rep secs)\n {\n os_assert_err(!scheduler::in_handler_mode (), EPERM);\n\n trace::printf (\"Realtime_clock::sleep_for(%ds)\\n\", secs);\n\n \/\/ TODO\n __rtc_now += secs;\n return result::ok;\n }\n\n#pragma GCC diagnostic pop\n\n } \/* namespace rtos *\/\n} \/* namespace os *\/\n<|endoftext|>"} {"text":"#include \n#include \n\nusing namespace Halide;\n\nint main(int argc, char **argv) {\n Var x, y;\n\n Func pred(\"pred\");\n pred(x, y) = x < y;\n\n Func selector(\"selector\");\n selector(x, y) = select(pred(x, y), 1, 0);\n\n \/\/ Load a vector of 8 bools\n pred.compute_root();\n selector.compute_root().vectorize(x, 8);\n\n RDom range(0, 100, 0, 100);\n int32_t result = evaluate(lambda(sum(selector(range.x, range.y))));\n\n assert(result == 4950);\n\n printf(\"Success!\\n\");\n return 0;\n}\nHad this under two names. Delete the less descriptive one.<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2014, Oculus VR, Inc.\r\n * All rights reserved.\r\n *\r\n * This source code is licensed under the BSD-style license found in the\r\n * LICENSE file in the root directory of this source tree. An additional grant \r\n * of patent rights can be found in the PATENTS file in the same directory.\r\n *\r\n *\/\r\n\r\n\/\/ ----------------------------------------------------------------------\r\n\/\/ RakNet version 1.0\r\n\/\/ Filename Ping.cpp\r\n\/\/ Very basic chat engine example\r\n\/\/ ----------------------------------------------------------------------\r\n#include \"MessageIdentifiers.h\"\r\n\r\n#include \"RakPeerInterface.h\"\r\n#include \"RakPeerInterface.h\"\r\n#include \"RakNetTypes.h\"\r\n#include \"GetTime.h\"\r\n#include \"BitStream.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"Gets.h\"\r\n\r\n#ifdef WIN32\r\n#include \"Kbhit.h\"\r\n#else\r\n#include \"Kbhit.h\"\r\n#endif\r\n\r\nint main(void)\r\n{\r\n\t\/\/ Pointers to the interfaces of our server and client.\r\n\t\/\/ Note we can easily have both in the same program\r\n\tRakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance();\r\n\tRakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();\r\n\r\n\tint i = server->GetNumberOfAddresses();\r\n\r\n\t\/\/ Holds packets\r\n\tRakNet::Packet* p;\r\n\r\n\t\/\/ Record the first client that connects to us so we can pass it to the ping function\r\n\tRakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;\r\n\tbool packetFromServer;\r\n\tchar portstring[30];\r\n\r\n\tprintf(\"This is a sample of how to send offline pings and get offline ping\\n\");\r\n\tprintf(\"responses.\\n\");\r\n\tprintf(\"Difficulty: Beginner\\n\\n\");\r\n\r\n\t\/\/ A server\r\n\tputs(\"Enter the server port to listen on\");\r\n\tGets(portstring,sizeof(portstring));\r\n\tif (portstring[0]==0)\r\n\t\tstrcpy(portstring,\"60000\");\r\n\r\n\t\/\/ Enumeration data\r\n\tputs(\"Enter offline ping response data (for return by a LAN discovery for example)\");\r\n\tputs(\"Hit enter for none.\");\r\n\tchar enumData[512];\r\n\tGets(enumData,sizeof(enumData));\r\n\tif (enumData[0])\r\n\t\tserver->SetOfflinePingResponse(enumData, (const unsigned int) strlen(enumData)+1);\r\n\r\n\tputs(\"Starting server.\");\r\n\r\n\t\/\/ The server has to be started to respond to pings.\r\n\tRakNet::SocketDescriptor socketDescriptor(atoi(portstring),0);\r\n\tbool b = server->Startup(2, &socketDescriptor, 1)==RakNet::RAKNET_STARTED;\r\n\tserver->SetMaximumIncomingConnections(2);\r\n\tif (b)\r\n\t\tputs(\"Server started, waiting for connections.\");\r\n\telse\r\n\t{ \r\n\t\tputs(\"Server failed to start. Terminating.\");\r\n\t\texit(1);\r\n\t}\r\n\r\n\tsocketDescriptor.port=0;\r\n\tclient->Startup(1,&socketDescriptor, 1);\r\n\r\n\tputs(\"'q' to quit, any other key to send a ping from the client.\");\r\n\tchar buff[256];\r\n\r\n\t\/\/ Loop for input\r\n\twhile (1)\r\n\t{\r\n\t\tif (kbhit())\r\n\t\t{\r\n\t\t\t\/\/ Holds user data\r\n\t\t\tchar ip[64], serverPort[30], clientPort[30];\r\n\r\n\t\t\tif (Gets(buff,sizeof(buff))&&(buff[0]=='q'))\r\n\t\t\t\tbreak;\r\n\t\t\telse\r\n\t\t\t{\r\n\r\n\t\t\t\t\/\/ Get our input\r\n\t\t\t\tputs(\"Enter the client port to listen on, or 0\");\r\n\t\t\t\tGets(clientPort,sizeof(clientPort));\r\n\t\t\t\tif (clientPort[0]==0)\r\n\t\t\t\t\tstrcpy(clientPort, \"0\");\r\n\t\t\t\tputs(\"Enter IP to ping\");\r\n\t\t\t\tGets(ip, sizeof(ip));\r\n\t\t\t\tif (ip[0]==0)\r\n\t\t\t\t\tstrcpy(ip, \"127.0.0.1\");\r\n\t\t\t\tputs(\"Enter the port to ping\");\r\n\t\t\t\tGets(serverPort,sizeof(serverPort));\r\n\t\t\t\tif (serverPort[0]==0)\r\n\t\t\t\t\tstrcpy(serverPort, \"60000\");\r\n\r\n\t\t\t\tclient->Ping(ip, atoi(serverPort), false);\r\n\r\n\t\t\t\tputs(\"Pinging\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ Get a packet from either the server or the client\r\n\t\tp = server->Receive();\r\n\r\n\t\tif (p==0)\r\n\t\t{\r\n\t\t\tpacketFromServer=false;\r\n\t\t\tp = client->Receive();\r\n\t\t}\r\n\t\telse\r\n\t\t\tpacketFromServer=true;\r\n\r\n\t\tif (p==0)\r\n\t\t\tcontinue;\r\n\r\n\r\n\t\t\/\/ Check if this is a network message packet\r\n\t\tswitch (p->data[0])\r\n\t\t{\r\n\t\t\tcase ID_UNCONNECTED_PONG:\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned int dataLength;\r\n\t\t\t\t\tRakNet::TimeMS time;\r\n\t\t\t\t\tRakNet::BitStream bsIn(p->data,p->length,false);\r\n\t\t\t\t\tbsIn.IgnoreBytes(1);\r\n\t\t\t\t\tbsIn.Read(time);\r\n\t\t\t\t\tdataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS);\r\n\t\t\t\t\tprintf(\"ID_UNCONNECTED_PONG from SystemAddress %s.\\n\", p->systemAddress.ToString(true));\r\n\t\t\t\t\tprintf(\"Time is %i\\n\",time);\r\n\t\t\t\t\tprintf(\"Ping is %i\\n\", (unsigned int)(RakNet::GetTimeMS()-time));\r\n\t\t\t\t\tprintf(\"Data is %i bytes long.\\n\", dataLength);\r\n\t\t\t\t\tif (dataLength > 0)\r\n\t\t\t\t\t\tprintf(\"Data is %s\\n\", p->data+sizeof(unsigned char)+sizeof(RakNet::TimeMS));\r\n\r\n\t\t\t\t\t\/\/ In this sample since the client is not running a game we can save CPU cycles by\r\n\t\t\t\t\t\/\/ Stopping the network threads after receiving the pong.\r\n\t\t\t\t\tclient->Shutdown(100);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase ID_UNCONNECTED_PING:\r\n\t\t\t\tbreak;\r\n\t\t\tcase ID_UNCONNECTED_PING_OPEN_CONNECTIONS:\r\n\t\t\t\tbreak;\t\t\t\r\n\t\t}\r\n\r\n\t\t\/\/ We're done with the packet\r\n\t\tif (packetFromServer)\r\n\t\t\tserver->DeallocatePacket(p);\r\n\t\telse\r\n\t\t\tclient->DeallocatePacket(p);\r\n\t}\r\n\r\n\t\/\/ We're done with the network\r\n\tRakNet::RakPeerInterface::DestroyInstance(server);\r\n\tRakNet::RakPeerInterface::DestroyInstance(client);\r\n\r\n\treturn 0;\r\n}\r\nUpdate ping.\/*\r\n * Copyright (c) 2014, Oculus VR, Inc.\r\n * All rights reserved.\r\n *\r\n * This source code is licensed under the BSD-style license found in the\r\n * LICENSE file in the root directory of this source tree. An additional grant \r\n * of patent rights can be found in the PATENTS file in the same directory.\r\n *\r\n *\/\r\n\r\n\/\/ ----------------------------------------------------------------------\r\n\/\/ RakNet version 1.0\r\n\/\/ Filename Ping.cpp\r\n\/\/ Very basic chat engine example\r\n\/\/ ----------------------------------------------------------------------\r\n#include \"MessageIdentifiers.h\"\r\n\r\n#include \"RakPeerInterface.h\"\r\n#include \"RakPeerInterface.h\"\r\n#include \"RakNetTypes.h\"\r\n#include \"GetTime.h\"\r\n#include \"BitStream.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"Gets.h\"\r\n\r\n#ifdef WIN32\r\n#include \"Kbhit.h\"\r\n#else\r\n#include \"Kbhit.h\"\r\n#endif\r\n\r\nint main(void)\r\n{\r\n\t\/\/ Pointers to the interfaces of our server and client.\r\n\t\/\/ Note we can easily have both in the same program\r\n\tRakNet::RakPeerInterface *client=RakNet::RakPeerInterface::GetInstance();\r\n\tRakNet::RakPeerInterface *server=RakNet::RakPeerInterface::GetInstance();\r\n\r\n\tint i = server->GetNumberOfAddresses();\r\n\r\n\t\/\/ Holds packets\r\n\tRakNet::Packet* p;\r\n\r\n\t\/\/ Record the first client that connects to us so we can pass it to the ping function\r\n\tRakNet::SystemAddress clientID=RakNet::UNASSIGNED_SYSTEM_ADDRESS;\r\n\tbool packetFromServer;\r\n\tchar portstring[30];\r\n\r\n\tprintf(\"This is a sample of how to send offline pings and get offline ping\\n\");\r\n\tprintf(\"responses.\\n\");\r\n\tprintf(\"Difficulty: Beginner\\n\\n\");\r\n\r\n\t\/\/ A server\r\n\tputs(\"Enter the server port to listen on\");\r\n\tGets(portstring,sizeof(portstring));\r\n\tif (portstring[0]==0)\r\n\t\tstrcpy(portstring,\"60000\");\r\n\r\n\t\/\/ Enumeration data\r\n\tputs(\"Enter offline ping response data (for return by a LAN discovery for example)\");\r\n\tputs(\"Hit enter for none.\");\r\n\tchar enumData[512];\r\n\tGets(enumData,sizeof(enumData));\r\n\tif (enumData[0])\r\n\t\tserver->SetOfflinePingResponse(enumData, (const unsigned int) strlen(enumData)+1);\r\n\r\n\tputs(\"Starting server.\");\r\n\r\n\t\/\/ The server has to be started to respond to pings.\r\n\tRakNet::SocketDescriptor socketDescriptor(atoi(portstring),0);\r\n\tbool b = server->Startup(2, &socketDescriptor, 1)==RakNet::StartupResult::RAKNET_STARTED;\r\n\tserver->SetMaximumIncomingConnections(2);\r\n\tif (b)\r\n\t\tputs(\"Server started, waiting for connections.\");\r\n\telse\r\n\t{ \r\n\t\tputs(\"Server failed to start. Terminating.\");\r\n\t\texit(1);\r\n\t}\r\n\r\n\tsocketDescriptor.port=0;\r\n\tclient->Startup(1,&socketDescriptor, 1);\r\n\r\n\tputs(\"'q' to quit, any other key to send a ping from the client.\");\r\n\tchar buff[256];\r\n\r\n\t\/\/ Loop for input\r\n\twhile (1)\r\n\t{\r\n\t\tif (kbhit())\r\n\t\t{\r\n\t\t\t\/\/ Holds user data\r\n\t\t\tchar ip[64], serverPort[30], clientPort[30];\r\n\r\n\t\t\tif (Gets(buff,sizeof(buff))&&(buff[0]=='q'))\r\n\t\t\t\tbreak;\r\n\t\t\telse\r\n\t\t\t{\r\n\r\n\t\t\t\t\/\/ Get our input\r\n\t\t\t\tputs(\"Enter the client port to listen on, or 0\");\r\n\t\t\t\tGets(clientPort,sizeof(clientPort));\r\n\t\t\t\tif (clientPort[0]==0)\r\n\t\t\t\t\tstrcpy(clientPort, \"0\");\r\n\t\t\t\tputs(\"Enter IP to ping\");\r\n\t\t\t\tGets(ip, sizeof(ip));\r\n\t\t\t\tif (ip[0]==0)\r\n\t\t\t\t\tstrcpy(ip, \"127.0.0.1\");\r\n\t\t\t\tputs(\"Enter the port to ping\");\r\n\t\t\t\tGets(serverPort,sizeof(serverPort));\r\n\t\t\t\tif (serverPort[0]==0)\r\n\t\t\t\t\tstrcpy(serverPort, \"60000\");\r\n\r\n\t\t\t\tclient->Ping(ip, atoi(serverPort), false);\r\n\r\n\t\t\t\tputs(\"Pinging\");\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t\/\/ Get a packet from either the server or the client\r\n\t\tp = server->Receive();\r\n\r\n\t\tif (p==0)\r\n\t\t{\r\n\t\t\tpacketFromServer=false;\r\n\t\t\tp = client->Receive();\r\n\t\t}\r\n\t\telse\r\n\t\t\tpacketFromServer=true;\r\n\r\n\t\tif (p==0)\r\n\t\t\tcontinue;\r\n\r\n\r\n\t\t\/\/ Check if this is a network message packet\r\n\t\tswitch (p->data[0])\r\n\t\t{\r\n\t\t\tcase ID_UNCONNECTED_PONG:\r\n\t\t\t\t{\r\n\t\t\t\t\tunsigned int dataLength;\r\n\t\t\t\t\tRakNet::TimeMS time;\r\n\t\t\t\t\tRakNet::BitStream bsIn(p->data,p->length,false);\r\n\t\t\t\t\tbsIn.IgnoreBytes(1);\r\n\t\t\t\t\tbsIn.Read(time);\r\n\t\t\t\t\tdataLength = p->length - sizeof(unsigned char) - sizeof(RakNet::TimeMS);\r\n\t\t\t\t\tprintf(\"ID_UNCONNECTED_PONG from SystemAddress %s.\\n\", p->systemAddress.ToString(true));\r\n\t\t\t\t\tprintf(\"Time is %i\\n\",time);\r\n\t\t\t\t\tprintf(\"Ping is %i\\n\", (unsigned int)(RakNet::GetTimeMS()-time));\r\n\t\t\t\t\tprintf(\"Data is %i bytes long.\\n\", dataLength);\r\n\t\t\t\t\tif (dataLength > 0)\r\n\t\t\t\t\t\tprintf(\"Data is %s\\n\", p->data+sizeof(unsigned char)+sizeof(RakNet::TimeMS));\r\n\r\n\t\t\t\t\t\/\/ In this sample since the client is not running a game we can save CPU cycles by\r\n\t\t\t\t\t\/\/ Stopping the network threads after receiving the pong.\r\n\t\t\t\t\tclient->Shutdown(100);\r\n\t\t\t\t}\r\n\t\t\t\tbreak;\r\n\t\t\tcase ID_UNCONNECTED_PING:\r\n\t\t\t\tbreak;\r\n\t\t\tcase ID_UNCONNECTED_PING_OPEN_CONNECTIONS:\r\n\t\t\t\tbreak;\t\t\t\r\n\t\t}\r\n\r\n\t\t\/\/ We're done with the packet\r\n\t\tif (packetFromServer)\r\n\t\t\tserver->DeallocatePacket(p);\r\n\t\telse\r\n\t\t\tclient->DeallocatePacket(p);\r\n\t}\r\n\r\n\t\/\/ We're done with the network\r\n\tRakNet::RakPeerInterface::DestroyInstance(server);\r\n\tRakNet::RakPeerInterface::DestroyInstance(client);\r\n\r\n\treturn 0;\r\n}\r\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2009, Asmodehn's Corp.\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, \n * \t this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * \t\tnotice, this list of conditions and the following disclaimer in the \n * \t documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Asmodehn's Corp. nor the names of its \n * \t contributors may be used to endorse or promote products derived\n * \t from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n * \n *\/\n\n#include \"header.hh\"\n\nint main ( int argc, char* argv[] )\n{\n\treturn displayXX(\"test\");\n}\nchanged header include command\/**\n * Copyright (c) 2009, Asmodehn's Corp.\n * All rights reserved.\n * \n * Redistribution and use in source and binary forms, with or without \n * modification, are permitted provided that the following conditions are met:\n * \n * * Redistributions of source code must retain the above copyright notice, \n * \t this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * \t\tnotice, this list of conditions and the following disclaimer in the \n * \t documentation and\/or other materials provided with the distribution.\n * * Neither the name of the Asmodehn's Corp. nor the names of its \n * \t contributors may be used to endorse or promote products derived\n * \t from this software without specific prior written permission.\n * \n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,\n * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\n * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS\n * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR \n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS \n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN \n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) \n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n * THE POSSIBILITY OF SUCH DAMAGE.\n * \n *\/\n\n#include \"ProjectA\/header.hh\"\n\nint main ( int argc, char* argv[] )\n{\n\treturn A_display(\"test A\");\n}\n<|endoftext|>"} {"text":"#include \"vm\/test\/test.hpp\"\n\n\/* Project *\/\n#include \"vm.hpp\"\n#include \"message.hpp\"\n#include \"builtin\/array.hpp\"\n#include \"builtin\/module.hpp\"\n#include \"builtin\/fixnum.hpp\"\n#include \"builtin\/string.hpp\"\n#include \"builtin\/symbol.hpp\"\n\n\/* Testee *\/\n#include \"builtin\/nativemethod.hpp\"\n\n#include \"subtend\/ruby.h\"\n\n\/* Re-reset *\/\n#undef Qfalse\n#undef Qtrue\n#undef Qnil\n#undef Qundef\n\n#define Qfalse RBX_Qfalse\n#define Qtrue RBX_Qtrue\n#define Qnil RBX_Qnil\n#define Qundef RBX_Qundef\n\n#define Sfalse ((VALUE)6L)\n#define Strue ((VALUE)10L)\n#define Snil ((VALUE)14L)\n#define Sundef ((VALUE)18L)\n\n\/* From vm\/objectmemory.hpp *\/\n#undef ALLOC_N\n#define ALLOC_N(type, size) ((type*)calloc(size, sizeof(type)))\n\nstatic NativeMethodContext* hidden_context = NULL;\nstatic Array* hidden_ruby_array = NULL;\nstatic Object* hidden_receiver = NULL;\nstatic int hidden_argc = 0;\nstatic Handle* hidden_c_array = NULL;\n\nusing namespace rubinius;\n\nextern \"C\" {\n\n Handle minus_three_arity(Handle ruby_array)\n {\n hidden_context = NativeMethodContext::current();\n hidden_ruby_array = as(hidden_context->object_from(ruby_array));\n\n Object* first = hidden_ruby_array->get(hidden_context->state(), 0);\n\n return hidden_context->handle_for(first);\n }\n\n Handle minus_two_arity(Handle receiver, Handle ruby_array)\n {\n hidden_context = NativeMethodContext::current();\n hidden_receiver = hidden_context->object_from(receiver);\n hidden_ruby_array = as(hidden_context->object_from(ruby_array));\n\n Object* first = hidden_ruby_array->get(hidden_context->state(), 0);\n\n return hidden_context->handle_for(first);\n }\n\n Handle minus_one_arity(int argc, Handle* args, Handle receiver)\n {\n hidden_context = NativeMethodContext::current();\n hidden_argc = argc;\n hidden_c_array = args;\n hidden_receiver = hidden_context->object_from(receiver);\n\n return args[0];\n }\n\n Handle one_arg(Handle receiver, Handle arg1)\n {\n hidden_context = NativeMethodContext::current();\n hidden_receiver = hidden_context->object_from(receiver);\n\n return hidden_context->handle_for(Fixnum::from(1));\n }\n\n Handle two_arg(Handle receiver, Handle arg1, Handle arg2)\n {\n hidden_context = NativeMethodContext::current();\n hidden_receiver = hidden_context->object_from(receiver);\n\n return hidden_context->handle_for(Fixnum::from(2));\n }\n\n Handle three_arg(Handle receiver, Handle arg1, Handle arg2, Handle arg3)\n {\n hidden_context = NativeMethodContext::current();\n hidden_receiver = hidden_context->object_from(receiver);\n\n return hidden_context->handle_for(Fixnum::from(3));\n }\n\n Handle four_arg(Handle receiver, Handle arg1, Handle arg2, Handle arg3, Handle arg4)\n {\n hidden_context = NativeMethodContext::current();\n hidden_receiver = hidden_context->object_from(receiver);\n\n return hidden_context->handle_for(Fixnum::from(4));\n }\n\n Handle five_arg(Handle receiver, Handle arg1, Handle arg2, Handle arg3, Handle arg4, Handle arg5)\n {\n hidden_context = NativeMethodContext::current();\n hidden_receiver = hidden_context->object_from(receiver);\n\n return hidden_context->handle_for(Fixnum::from(5));\n }\n\n Handle funcaller2(Handle receiver, Handle array, Handle obj)\n {\n hidden_context = NativeMethodContext::current();\n Symbol* method = hidden_context->state()->symbol(\"blah\");\n\n Handle args[1];\n\n args[0] = obj;\n\n \/* Handle ret = *\/ rb_funcall2(array, reinterpret_cast(method), 1, args);\n\n return obj;\n }\n\n}\n\n\nclass TestSubtend : public CxxTest::TestSuite\n{\n public:\n\n VM* my_state;\n Task* my_task;\n Message* my_message;\n Module* my_module;\n\n void setUp() {\n my_state = new VM(65536 * 1000);\n my_task = Task::create(my_state);\n my_message = new Message(my_state);\n my_module = Module::create(my_state);\n\n my_message->set_caller(my_task->active());\n }\n\n void tearDown() {\n hidden_context = NULL;\n hidden_ruby_array = NULL;\n hidden_argc = 0;\n hidden_c_array = NULL;\n\n delete my_message;\n delete my_state;\n }\n\n \/* Tests *\/\n\n void test_ruby_to_c_call_with_args_as_ruby_array()\n {\n Array* args = Array::create(my_state, 10);\n Array* control = Array::create(my_state, 10);\n\n for (std::size_t i = 0; i < 10; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &minus_three_arity,\n Fixnum::from(ARGS_IN_RUBY_ARRAY));\n\n my_message->method = method;\n bool ret = method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(ret, true);\n\n TS_ASSERT_DIFFERS(hidden_context, static_cast(NULL));\n\n TS_ASSERT_EQUALS(hidden_ruby_array, args);\n\n for (std::size_t i = 0; i < 10; ++i) {\n TS_ASSERT_EQUALS(hidden_ruby_array->get(my_state, i), control->get(my_state, i));\n }\n\n TS_ASSERT_EQUALS(hidden_context->return_value(), hidden_ruby_array->get(my_state, 0));\n }\n\n void test_ruby_to_c_call_with_receiver_and_args_as_ruby_array()\n {\n Array* args = Array::create(my_state, 10);\n Array* control = Array::create(my_state, 10);\n\n for (std::size_t i = 0; i < 10; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &minus_two_arity,\n Fixnum::from(RECEIVER_PLUS_ARGS_IN_RUBY_ARRAY));\n\n my_message->method = method;\n bool ret = method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(ret, true);\n\n TS_ASSERT_DIFFERS(hidden_context, static_cast(NULL));\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(hidden_ruby_array, args);\n\n for (std::size_t i = 0; i < 10; ++i) {\n TS_ASSERT_EQUALS(hidden_ruby_array->get(my_state, i), control->get(my_state, i));\n }\n\n TS_ASSERT_EQUALS(hidden_context->return_value(), hidden_ruby_array->get(my_state, 0));\n }\n\n void test_ruby_to_c_call_with_arg_count_args_in_c_array_plus_receiver()\n {\n Array* args = Array::create(my_state, 10);\n Array* control = Array::create(my_state, 10);\n\n for (std::size_t i = 0; i < 10; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &minus_one_arity,\n Fixnum::from(ARG_COUNT_ARGS_IN_C_ARRAY_PLUS_RECEIVER));\n\n my_message->method = method;\n bool ret = method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(ret, true);\n\n TS_ASSERT_DIFFERS(hidden_context, static_cast(NULL));\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(hidden_argc, 10);\n\n for (std::size_t i = 0; i < 10; ++i) {\n TS_ASSERT_EQUALS(hidden_context->object_from(hidden_c_array[i]), control->get(my_state, i));\n }\n\n TS_ASSERT_EQUALS(hidden_context->return_value(), control->get(my_state, 0));\n }\n\n \/* TODO: Should check object identities too? *\/\n void test_ruby_to_c_call_with_recv_plus_one()\n {\n int arg_count = 1;\n\n Array* args = Array::create(my_state, arg_count);\n Array* control = Array::create(my_state, arg_count);\n\n for (int i = 0; i < arg_count; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &one_arg,\n Fixnum::from(arg_count));\n\n my_message->method = method;\n method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(as(hidden_context->return_value())->to_int(), arg_count);\n }\n\n void test_ruby_to_c_call_clears_caller_stack()\n {\n Task* task = Task::create(my_state, 2);\n task->push(Fixnum::from(4));\n\n MethodContext* top = task->active();\n\n TS_ASSERT_EQUALS(top->calculate_sp(), 0);\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->use_from_task(task, 1);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n my_message->stack = 1;\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &one_arg,\n Fixnum::from(1));\n\n my_message->method = method;\n method->execute(my_state, task, *my_message);\n\n TS_ASSERT_EQUALS(task->active(), top);\n TS_ASSERT_EQUALS(top->calculate_sp(), 0);\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(as(hidden_context->return_value())->to_int(), 1);\n TS_ASSERT_EQUALS(as(top->pop())->to_int(), 1);\n }\n\n void test_ruby_to_c_call_with_recv_plus_two()\n {\n int arg_count = 2;\n\n Array* args = Array::create(my_state, arg_count);\n Array* control = Array::create(my_state, arg_count);\n\n for (int i = 0; i < arg_count; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &two_arg,\n Fixnum::from(arg_count));\n\n my_message->method = method;\n method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(as(hidden_context->return_value())->to_int(), arg_count);\n }\n\n void test_ruby_to_c_call_with_recv_plus_three()\n {\n int arg_count = 3;\n\n Array* args = Array::create(my_state, arg_count);\n Array* control = Array::create(my_state, arg_count);\n\n for (int i = 0; i < arg_count; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &three_arg,\n Fixnum::from(arg_count));\n\n my_message->method = method;\n method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(as(hidden_context->return_value())->to_int(), arg_count);\n }\n\n void test_ruby_to_c_call_with_recv_plus_four()\n {\n int arg_count = 4;\n\n Array* args = Array::create(my_state, arg_count);\n Array* control = Array::create(my_state, arg_count);\n\n for (int i = 0; i < arg_count; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &four_arg,\n Fixnum::from(arg_count));\n\n my_message->method = method;\n method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(as(hidden_context->return_value())->to_int(), arg_count);\n }\n\n void test_ruby_to_c_call_with_recv_plus_five()\n {\n int arg_count = 5;\n\n Array* args = Array::create(my_state, arg_count);\n Array* control = Array::create(my_state, arg_count);\n\n for (int i = 0; i < arg_count; ++i) {\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, i, obj);\n control->set(my_state, i, obj);\n }\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &five_arg,\n Fixnum::from(arg_count));\n\n my_message->method = method;\n method->execute(my_state, my_task, *my_message);\n\n TS_ASSERT_EQUALS(hidden_receiver, receiver);\n TS_ASSERT_EQUALS(as(hidden_context->return_value())->to_int(), arg_count);\n }\n\n void test_rb_funcall()\n {\n \/* No actual Ruby code involved.. *\/\n CompiledMethod* target = CompiledMethod::create(my_state);\n target->iseq(my_state, InstructionSequence::create(my_state, 1));\n target->iseq()->opcodes()->put(my_state, 0, Fixnum::from(InstructionSequence::insn_ret));\n target->total_args(my_state, Fixnum::from(1));\n target->required_args(my_state, target->total_args());\n target->stack_size(my_state, Fixnum::from(1));\n\n Symbol* name = my_state->symbol(\"blah\");\n my_state->globals.true_class.get()->method_table()->store(my_state, name, target);\n\n target->formalize(my_state);\n\n Array* args = Array::create(my_state, 2);\n Object* obj = my_state->new_object(my_state->globals.object.get());\n\n args->set(my_state, 0, Qtrue);\n args->set(my_state, 1, obj);\n\n Object* receiver = my_state->new_object(my_state->globals.object.get());\n\n my_message->recv = receiver;\n my_message->set_arguments(my_state, args);\n my_message->name = my_state->symbol(\"__subtend_fake_funcall_test_method__\");\n\n NativeMethod* method = NativeMethod::create(my_state,\n String::create(my_state, __FILE__),\n my_module,\n my_message->name,\n &funcaller2,\n Fixnum::from(2));\n\n my_message->method = method;\n \/* This only loads the cm. *\/\n method->execute(my_state, my_task, *my_message);\n\n my_task->active()->vmm->run(my_task->active()->vmm, my_task, my_task->active());\n\n TS_ASSERT_EQUALS(obj, my_task->active()->top());\n\n \/* TODO: Need some more reasonable tests here? *\/\n }\n\n};\nRemoved old subtend VM tests.<|endoftext|>"} {"text":"\/*\n * RustEditor: Plugin to add Rust language support to QtCreator IDE.\n * Copyright (C) 2015 Davide Ghilardi\n *\n * This file is part of RustEditor.\n *\n * RustEditor is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * RustEditor is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with RustEditor. If not, see .\n*\/\n\n#include \"configuration.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace {\n const QLatin1String SETTINGS_GROUP(\"RustEditorConfiguration\");\n\n const QLatin1String RUST_SRC_ENV(\"RUST_SRC_PATH\");\n const QLatin1String RUST_SRC_DEF(\"\/usr\/src\/rust\");\n\n const QLatin1String RACER_PATH_DEF(\"\/usr\/bin\");\n}\n\nusing namespace RustEditor::Internal;\n\nConfiguration *Configuration::cfg_instance = NULL;\n\nConfiguration::Configuration(QObject *parent):\n QObject(parent)\n{\n load();\n cfg_instance = this;\n}\n\nConfiguration *Configuration::getInstancePtr()\n{\n Q_ASSERT(cfg_instance != NULL);\n return cfg_instance;\n}\n\nconst Settings &Configuration::getSettingsPtr()\n{\n return cfg_instance->rusteditorSettings;\n}\n\nvoid Configuration::setSettings(const Settings &newSettings)\n{\n cfg_instance->rusteditorSettings = newSettings;\n cfg_instance->save();\n}\n\nvoid Configuration::load()\n{\n bool saveSettings = false;\n\n QSettings *qtCreatorSettings = Core::ICore::settings();\n qtCreatorSettings->beginGroup(SETTINGS_GROUP);\n rusteditorSettings.load(*qtCreatorSettings);\n\n Utils::FileName rustSrcPath = cfgPathLookup(rusteditorSettings.rustSrcPath(), Utils::FileName::fromString(RUST_SRC_DEF), RUST_SRC_ENV, saveSettings);\n rusteditorSettings.setRustSrcPath(rustSrcPath);\n\n Utils::FileName racerPath = cfgPathLookup(rusteditorSettings.racerPath(), Utils::FileName::fromString(RACER_PATH_DEF), QLatin1String(\"\"), saveSettings);\n rusteditorSettings.setRacerPath(racerPath);\n\n qtCreatorSettings->endGroup();\n\n if (saveSettings)\n save();\n}\n\nvoid Configuration::save()\n{\n QSettings *settings = Core::ICore::settings();\n settings->beginGroup(SETTINGS_GROUP);\n rusteditorSettings.save(*settings);\n settings->endGroup();\n}\n\nUtils::FileName Configuration::cfgPathLookup(const Utils::FileName &cfg, const Utils::FileName &def, const QString &envKey, bool &save)\n{\n Utils::FileName result;\n if (cfg.isEmpty()) {\n Utils::Environment env = Utils::Environment::systemEnvironment();\n if (!envKey.isEmpty()){\n Utils::FileName location = env.searchInPath(envKey);\n QFileInfo fi = location.toFileInfo();\n\n if (fi.exists() && fi.isDir()) result = location;\n else result = def;\n\n }else{\n\n result = def;\n }\n }else{\n result = cfg;\n }\n save = save || (result != cfg);\n return result;\n}\n\nModified default rust source dir\/*\n * RustEditor: Plugin to add Rust language support to QtCreator IDE.\n * Copyright (C) 2015 Davide Ghilardi\n *\n * This file is part of RustEditor.\n *\n * RustEditor is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License as published by\n * the Free Software Foundation, either version 2.1 of the License, or\n * (at your option) any later version.\n *\n * RustEditor is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with RustEditor. If not, see .\n*\/\n\n#include \"configuration.h\"\n\n#include \n#include \n\n#include \n#include \n#include \n\nnamespace {\n const QLatin1String SETTINGS_GROUP(\"RustEditorConfiguration\");\n\n const QLatin1String RUST_SRC_ENV(\"RUST_SRC_PATH\");\n const QLatin1String RUST_SRC_DEF(\"\/usr\/src\/rust\/src\");\n\n const QLatin1String RACER_PATH_DEF(\"\/usr\/bin\");\n}\n\nusing namespace RustEditor::Internal;\n\nConfiguration *Configuration::cfg_instance = NULL;\n\nConfiguration::Configuration(QObject *parent):\n QObject(parent)\n{\n load();\n cfg_instance = this;\n}\n\nConfiguration *Configuration::getInstancePtr()\n{\n Q_ASSERT(cfg_instance != NULL);\n return cfg_instance;\n}\n\nconst Settings &Configuration::getSettingsPtr()\n{\n return cfg_instance->rusteditorSettings;\n}\n\nvoid Configuration::setSettings(const Settings &newSettings)\n{\n cfg_instance->rusteditorSettings = newSettings;\n cfg_instance->save();\n}\n\nvoid Configuration::load()\n{\n bool saveSettings = false;\n\n QSettings *qtCreatorSettings = Core::ICore::settings();\n qtCreatorSettings->beginGroup(SETTINGS_GROUP);\n rusteditorSettings.load(*qtCreatorSettings);\n\n Utils::FileName rustSrcPath = cfgPathLookup(rusteditorSettings.rustSrcPath(), Utils::FileName::fromString(RUST_SRC_DEF), RUST_SRC_ENV, saveSettings);\n rusteditorSettings.setRustSrcPath(rustSrcPath);\n\n Utils::FileName racerPath = cfgPathLookup(rusteditorSettings.racerPath(), Utils::FileName::fromString(RACER_PATH_DEF), QLatin1String(\"\"), saveSettings);\n rusteditorSettings.setRacerPath(racerPath);\n\n qtCreatorSettings->endGroup();\n\n if (saveSettings)\n save();\n}\n\nvoid Configuration::save()\n{\n QSettings *settings = Core::ICore::settings();\n settings->beginGroup(SETTINGS_GROUP);\n rusteditorSettings.save(*settings);\n settings->endGroup();\n}\n\nUtils::FileName Configuration::cfgPathLookup(const Utils::FileName &cfg, const Utils::FileName &def, const QString &envKey, bool &save)\n{\n Utils::FileName result;\n if (cfg.isEmpty()) {\n Utils::Environment env = Utils::Environment::systemEnvironment();\n if (!envKey.isEmpty()){\n Utils::FileName location = env.searchInPath(envKey);\n QFileInfo fi = location.toFileInfo();\n\n if (fi.exists() && fi.isDir()) result = location;\n else result = def;\n\n }else{\n\n result = def;\n }\n }else{\n result = cfg;\n }\n save = save || (result != cfg);\n return result;\n}\n\n<|endoftext|>"} {"text":"\/*!\n * \\file int_path.hpp\n * \\brief file int_path.hpp\n *\n * Copyright 2017 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin \n *\n *\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"array2d.hpp\"\n#include \"bounding_box.hpp\"\n#include \"util_private.hpp\"\n\nnamespace fastuidraw\n{\n namespace detail\n {\n class IntBezierCurve\n {\n public:\n\n template\n class transformation\n {\n public:\n transformation(T sc = T(1), vecN tr = vecN(T(0))):\n m_scale(sc),\n m_translate(tr)\n {}\n\n T\n scale(void) const\n {\n return m_scale;\n }\n\n vecN\n translate(void) const\n {\n return m_translate;\n }\n\n template\n transformation\n cast(void) const\n {\n return transformation(U(m_scale), vecN(m_translate));\n }\n\n vecN\n operator()(vecN p) const\n {\n return m_translate + m_scale * p;\n }\n\n private:\n T m_scale;\n vecN m_translate;\n };\n\n class ID_t\n {\n public:\n ID_t(void):\n m_contourID(-1),\n m_curveID(-1)\n {}\n\n unsigned int m_contourID;\n unsigned int m_curveID;\n };\n\n IntBezierCurve(const ID_t &pID, const IntBezierCurve &curve):\n m_ID(pID),\n m_control_pts(curve.m_control_pts),\n m_num_control_pts(curve.m_num_control_pts),\n m_as_polynomial_fcn(curve.m_as_polynomial_fcn),\n m_derivatives_cancel(curve.m_derivatives_cancel),\n m_bb(curve.m_bb)\n {\n }\n\n IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &pt1):\n m_ID(pID),\n m_control_pts(pt0, pt1, ivec2(), ivec2()),\n m_num_control_pts(2)\n {\n process_control_pts();\n }\n\n IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct,\n const ivec2 &pt1):\n m_ID(pID),\n m_control_pts(pt0, ct, pt1, ivec2()),\n m_num_control_pts(3)\n {\n process_control_pts();\n }\n\n IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct0,\n const ivec2 &ct1, const ivec2 &pt1):\n m_ID(pID),\n m_control_pts(pt0, ct0, ct1, pt1),\n m_num_control_pts(4)\n {\n process_control_pts();\n }\n\n ~IntBezierCurve()\n {}\n\n const ID_t&\n ID(void) const\n {\n return m_ID;\n }\n\n const_c_array\n control_pts(void) const\n {\n return const_c_array(m_control_pts.c_ptr(), m_num_control_pts);\n }\n\n const BoundingBox&\n bounding_box(void) const\n {\n return m_bb;\n }\n\n BoundingBox\n bounding_box(const transformation &tr) const\n {\n BoundingBox R;\n R.union_point(tr(m_bb.min_point()));\n R.union_point(tr(m_bb.max_point()));\n return R;\n }\n\n static\n bool\n are_ordered_neighbors(const IntBezierCurve &curve0,\n const IntBezierCurve &curve1)\n {\n return curve0.control_pts().back() == curve1.control_pts().front();\n }\n\n int\n degree(void) const\n {\n FASTUIDRAWassert(m_num_control_pts > 0);\n return m_num_control_pts - 1;\n }\n\n const_c_array\n derivatives_cancel(void) const\n {\n return const_c_array(m_derivatives_cancel.c_ptr(),\n m_num_derivatives_cancel);\n }\n\n const_c_array\n as_polynomial(int coord) const\n {\n return const_c_array(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n }\n\n vecN, 2>\n as_polynomial(void) const\n {\n return vecN, 2>(as_polynomial(0), as_polynomial(1));\n }\n\n vec2\n eval(float t) const;\n\n private:\n void\n process_control_pts(void);\n\n void\n compute_derivatives_cancel_pts(void);\n\n c_array\n as_polynomial(int coord)\n {\n return c_array(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n }\n\n ID_t m_ID;\n vecN m_control_pts;\n unsigned int m_num_control_pts;\n vecN m_as_polynomial_fcn;\n\n \/\/ where dx\/dt +- dy\/dt = 0\n vecN m_derivatives_cancel;\n unsigned int m_num_derivatives_cancel;\n BoundingBox m_bb;\n };\n\n class IntContour\n {\n public:\n IntContour(void)\n {}\n\n void\n add_curve(const IntBezierCurve &curve)\n {\n FASTUIDRAWassert(m_curves.empty() || IntBezierCurve::are_ordered_neighbors(m_curves.back(), curve));\n m_curves.push_back(curve);\n }\n\n bool\n closed(void)\n {\n return !m_curves.empty()\n && IntBezierCurve::are_ordered_neighbors(m_curves.back(), m_curves.front());\n }\n\n const std::vector&\n curves(void) const\n {\n return m_curves;\n }\n\n const IntBezierCurve&\n curve(unsigned int curveID) const\n {\n FASTUIDRAWassert(curveID < m_curves.size());\n return m_curves[curveID];\n }\n\n \/* Filter the Contour as follows:\n 1. Collapse any curves that are within a texel\n 2. Curves of tiny curvature are realized as a line\n 3. Cubics are broken into quadratics\n The transformation tr is -NOT- applied to the contour,\n it is used as the transformation from IntContour\n coordinates to texel coordinates. The value of texel_size\n gives the size of a texel with the texel at (0, 0)\n starting at (0, 0) [in texel coordinates].\n *\/\n void\n filter(float curvature_collapse,\n const IntBezierCurve::transformation &tr, ivec2 texel_size);\n\n void\n add_to_path(const IntBezierCurve::transformation &tr, Path *dst) const;\n\n private:\n std::vector m_curves;\n };\n\n class IntPath\n {\n public:\n IntPath(void)\n {}\n\n void\n move_to(const ivec2 &pt);\n\n void\n line_to(const ivec2 &pt);\n\n void\n conic_to(const ivec2 &control_pt, const ivec2 &pt);\n\n void\n cubic_to(const ivec2 &control_pt0, const ivec2 &control_pt1, const ivec2 &pt);\n\n bool\n empty(void) const\n {\n return m_contours.empty();\n }\n\n \/* Add this IntPath with a transforamtion tr applied to it to a\n pre-exising (and possibly empty) Path.\n \\param tr transformation to apply to data of path\n *\/\n void\n add_to_path(const IntBezierCurve::transformation &tr, Path *dst) const;\n\n \/* Filter the Path as follows:\n 1. Collapse any curves that are within a texel\n 2. Curves of tiny curvature are realized as a line\n 3. Cubics are broken into quadratics\n The transformation tr is -NOT- applied to the path,\n it is used as the transformation from IntContour\n coordinates to texel coordinates. The value of texel_size\n gives the size of a texel with the texel at (0, 0)\n starting at (0, 0) [in texel coordinates].\n *\/\n void\n filter(float curvature_collapse,\n const IntBezierCurve::transformation &tr,\n ivec2 texel_size);\n\n\n \/* Compute distance field data, where distance values are\n sampled at the center of each texel; the caller needs to\n make sure that the path with the transformation tr applied\n is entirely within the region [0, W] x [0, H] where\n (W, H) = texel_size * image_sz.\n \\param texel_size the size of each texel in coordinates\n AFTER tr is applied\n \\param image_sz size of the distance field to make\n \\param tr transformation to apply to data of path\n *\/\n void\n extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,\n float max_distance,\n IntBezierCurve::transformation tr,\n GlyphRenderDataDistanceField *dst) const;\n\n\n \/* Compute curve-pair render data. The caller should have applied\n filter() before calling to reduce cubics and collapse tiny\n curves; also, the caller needs to make sure that the path\n with the transformation tr applied is entirely within the\n region [0, W] x [0, H] where (W, H) = texel_size * image_sz.\n \\param texel_size the size of each texel in coordinates\n AFTER tr is applied\n \\param image_sz size of the distance field to make\n \\param tr transformation to apply to data of path\n *\/\n void\n extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,\n IntBezierCurve::transformation tr,\n GlyphRenderDataCurvePair *dst) const;\n\n private:\n IntBezierCurve::ID_t\n computeID(void);\n\n fastuidraw::ivec2 m_last_pt;\n std::vector m_contours;\n };\n\n } \/\/namespace fastuidraw\n} \/\/namespace detail\nfastuidraw\/private\/int_path: add comparison operator to IntBezierCurve::ID_t\/*!\n * \\file int_path.hpp\n * \\brief file int_path.hpp\n *\n * Copyright 2017 by Intel.\n *\n * Contact: kevin.rogovin@intel.com\n *\n * This Source Code Form is subject to the\n * terms of the Mozilla Public License, v. 2.0.\n * If a copy of the MPL was not distributed with\n * this file, You can obtain one at\n * http:\/\/mozilla.org\/MPL\/2.0\/.\n *\n * \\author Kevin Rogovin \n *\n *\/\n\n#pragma once\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"array2d.hpp\"\n#include \"bounding_box.hpp\"\n#include \"util_private.hpp\"\n\nnamespace fastuidraw\n{\n namespace detail\n {\n class IntBezierCurve\n {\n public:\n\n template\n class transformation\n {\n public:\n transformation(T sc = T(1), vecN tr = vecN(T(0))):\n m_scale(sc),\n m_translate(tr)\n {}\n\n T\n scale(void) const\n {\n return m_scale;\n }\n\n vecN\n translate(void) const\n {\n return m_translate;\n }\n\n template\n transformation\n cast(void) const\n {\n return transformation(U(m_scale), vecN(m_translate));\n }\n\n vecN\n operator()(vecN p) const\n {\n return m_translate + m_scale * p;\n }\n\n private:\n T m_scale;\n vecN m_translate;\n };\n\n class ID_t\n {\n public:\n ID_t(void):\n m_contourID(-1),\n m_curveID(-1)\n {}\n\n bool\n operator<(const ID_t &rhs) const\n {\n return m_contourID == rhs.m_contourID\n || (m_contourID == rhs.m_contourID\n && m_curveID << rhs.m_curveID);\n }\n\n unsigned int m_contourID;\n unsigned int m_curveID;\n };\n\n IntBezierCurve(const ID_t &pID, const IntBezierCurve &curve):\n m_ID(pID),\n m_control_pts(curve.m_control_pts),\n m_num_control_pts(curve.m_num_control_pts),\n m_as_polynomial_fcn(curve.m_as_polynomial_fcn),\n m_derivatives_cancel(curve.m_derivatives_cancel),\n m_bb(curve.m_bb)\n {\n }\n\n IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &pt1):\n m_ID(pID),\n m_control_pts(pt0, pt1, ivec2(), ivec2()),\n m_num_control_pts(2)\n {\n process_control_pts();\n }\n\n IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct,\n const ivec2 &pt1):\n m_ID(pID),\n m_control_pts(pt0, ct, pt1, ivec2()),\n m_num_control_pts(3)\n {\n process_control_pts();\n }\n\n IntBezierCurve(const ID_t &pID, const ivec2 &pt0, const ivec2 &ct0,\n const ivec2 &ct1, const ivec2 &pt1):\n m_ID(pID),\n m_control_pts(pt0, ct0, ct1, pt1),\n m_num_control_pts(4)\n {\n process_control_pts();\n }\n\n ~IntBezierCurve()\n {}\n\n const ID_t&\n ID(void) const\n {\n return m_ID;\n }\n\n const_c_array\n control_pts(void) const\n {\n return const_c_array(m_control_pts.c_ptr(), m_num_control_pts);\n }\n\n const BoundingBox&\n bounding_box(void) const\n {\n return m_bb;\n }\n\n BoundingBox\n bounding_box(const transformation &tr) const\n {\n BoundingBox R;\n R.union_point(tr(m_bb.min_point()));\n R.union_point(tr(m_bb.max_point()));\n return R;\n }\n\n static\n bool\n are_ordered_neighbors(const IntBezierCurve &curve0,\n const IntBezierCurve &curve1)\n {\n return curve0.control_pts().back() == curve1.control_pts().front();\n }\n\n int\n degree(void) const\n {\n FASTUIDRAWassert(m_num_control_pts > 0);\n return m_num_control_pts - 1;\n }\n\n const_c_array\n derivatives_cancel(void) const\n {\n return const_c_array(m_derivatives_cancel.c_ptr(),\n m_num_derivatives_cancel);\n }\n\n const_c_array\n as_polynomial(int coord) const\n {\n return const_c_array(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n }\n\n vecN, 2>\n as_polynomial(void) const\n {\n return vecN, 2>(as_polynomial(0), as_polynomial(1));\n }\n\n vec2\n eval(float t) const;\n\n private:\n void\n process_control_pts(void);\n\n void\n compute_derivatives_cancel_pts(void);\n\n c_array\n as_polynomial(int coord)\n {\n return c_array(m_as_polynomial_fcn[coord].c_ptr(), m_num_control_pts);\n }\n\n ID_t m_ID;\n vecN m_control_pts;\n unsigned int m_num_control_pts;\n vecN m_as_polynomial_fcn;\n\n \/\/ where dx\/dt +- dy\/dt = 0\n vecN m_derivatives_cancel;\n unsigned int m_num_derivatives_cancel;\n BoundingBox m_bb;\n };\n\n class IntContour\n {\n public:\n IntContour(void)\n {}\n\n void\n add_curve(const IntBezierCurve &curve)\n {\n FASTUIDRAWassert(m_curves.empty() || IntBezierCurve::are_ordered_neighbors(m_curves.back(), curve));\n m_curves.push_back(curve);\n }\n\n bool\n closed(void)\n {\n return !m_curves.empty()\n && IntBezierCurve::are_ordered_neighbors(m_curves.back(), m_curves.front());\n }\n\n const std::vector&\n curves(void) const\n {\n return m_curves;\n }\n\n const IntBezierCurve&\n curve(unsigned int curveID) const\n {\n FASTUIDRAWassert(curveID < m_curves.size());\n return m_curves[curveID];\n }\n\n \/* Filter the Contour as follows:\n 1. Collapse any curves that are within a texel\n 2. Curves of tiny curvature are realized as a line\n 3. Cubics are broken into quadratics\n The transformation tr is -NOT- applied to the contour,\n it is used as the transformation from IntContour\n coordinates to texel coordinates. The value of texel_size\n gives the size of a texel with the texel at (0, 0)\n starting at (0, 0) [in texel coordinates].\n *\/\n void\n filter(float curvature_collapse,\n const IntBezierCurve::transformation &tr, ivec2 texel_size);\n\n void\n add_to_path(const IntBezierCurve::transformation &tr, Path *dst) const;\n\n private:\n std::vector m_curves;\n };\n\n class IntPath\n {\n public:\n IntPath(void)\n {}\n\n void\n move_to(const ivec2 &pt);\n\n void\n line_to(const ivec2 &pt);\n\n void\n conic_to(const ivec2 &control_pt, const ivec2 &pt);\n\n void\n cubic_to(const ivec2 &control_pt0, const ivec2 &control_pt1, const ivec2 &pt);\n\n bool\n empty(void) const\n {\n return m_contours.empty();\n }\n\n \/* Add this IntPath with a transforamtion tr applied to it to a\n pre-exising (and possibly empty) Path.\n \\param tr transformation to apply to data of path\n *\/\n void\n add_to_path(const IntBezierCurve::transformation &tr, Path *dst) const;\n\n \/* Filter the Path as follows:\n 1. Collapse any curves that are within a texel\n 2. Curves of tiny curvature are realized as a line\n 3. Cubics are broken into quadratics\n The transformation tr is -NOT- applied to the path,\n it is used as the transformation from IntContour\n coordinates to texel coordinates. The value of texel_size\n gives the size of a texel with the texel at (0, 0)\n starting at (0, 0) [in texel coordinates].\n *\/\n void\n filter(float curvature_collapse,\n const IntBezierCurve::transformation &tr,\n ivec2 texel_size);\n\n\n \/* Compute distance field data, where distance values are\n sampled at the center of each texel; the caller needs to\n make sure that the path with the transformation tr applied\n is entirely within the region [0, W] x [0, H] where\n (W, H) = texel_size * image_sz.\n \\param texel_size the size of each texel in coordinates\n AFTER tr is applied\n \\param image_sz size of the distance field to make\n \\param tr transformation to apply to data of path\n *\/\n void\n extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,\n float max_distance,\n IntBezierCurve::transformation tr,\n GlyphRenderDataDistanceField *dst) const;\n\n\n \/* Compute curve-pair render data. The caller should have applied\n filter() before calling to reduce cubics and collapse tiny\n curves; also, the caller needs to make sure that the path\n with the transformation tr applied is entirely within the\n region [0, W] x [0, H] where (W, H) = texel_size * image_sz.\n \\param texel_size the size of each texel in coordinates\n AFTER tr is applied\n \\param image_sz size of the distance field to make\n \\param tr transformation to apply to data of path\n *\/\n void\n extract_render_data(const ivec2 &texel_size, const ivec2 &image_sz,\n IntBezierCurve::transformation tr,\n GlyphRenderDataCurvePair *dst) const;\n\n private:\n IntBezierCurve::ID_t\n computeID(void);\n\n fastuidraw::ivec2 m_last_pt;\n std::vector m_contours;\n };\n\n } \/\/namespace fastuidraw\n} \/\/namespace detail\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (ivan.frade@nokia.com)\n**\n** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at ivan.frade@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"..\/testhelpers.h\"\n#include \"..\/tracker_direct_common.h\"\n\n#include \n#include \n\nclass tst_QSparqlTrackerDirectConcurrency : public QObject\n{\n Q_OBJECT\npublic:\n tst_QSparqlTrackerDirectConcurrency();\n virtual ~tst_QSparqlTrackerDirectConcurrency();\n\nprivate:\n\nprivate slots:\n void initTestCase();\n void cleanupTestCase();\n void init();\n void cleanup();\n\n void sameConnection_selectQueries();\n void sameConnection_selectQueries_data();\n \/\/void sameConnection_updateQueries();\n void sameConnection_multipleThreads_selectQueries();\n void sameConnection_multipleThreads_selectQueries_data();\n \/\/void sameConnection_multipleThreads_updateQueries();\n\n \/\/ multpleConnections tests will all be multi threaded\n \/\/void multipleConnections_selectQueries();\n \/\/void multipleConnections_updateQueries();\n\nprivate:\n QSharedPointer dataReadySpy;\n};\n\nnamespace {\n\nclass SignalObject : public QObject\n{\n Q_OBJECT\npublic:\n SignalObject() : position(0) {}\n ~SignalObject()\n {\n \/\/ delete the signal mappers that were created\n foreach(QSignalMapper* map, signalMaps) {\n delete map;\n }\n }\n\n QSet pendingResults;\n int position;\n QList signalMaps;\n QList > resultRanges;\n\n void append(QSparqlResult *r, QPair range)\n {\n QSignalMapper *dataReadyMapper = new QSignalMapper();\n QSignalMapper *finishedMapper = new QSignalMapper();\n dataReadyMapper->setMapping(r, position);\n finishedMapper->setMapping(r, position);\n position++;\n\n connect(r, SIGNAL(dataReady(int)), dataReadyMapper, SLOT(map()));\n connect(dataReadyMapper, SIGNAL(mapped(int)), this, SLOT(onDataReady(int)));\n connect(r, SIGNAL(finished()), finishedMapper, SLOT(map()));\n connect(finishedMapper, SIGNAL(mapped(int)), this, SLOT(onFinished(int)));\n\n resultList.append(r);\n resultRanges.append(range);\n pendingResults.insert(r);\n\n \/\/ keep track of the signal mappers to delete later\n signalMaps.append(dataReadyMapper);\n signalMaps.append(finishedMapper);\n }\n QList resultList;\n\n bool waitForAllFinished(int silenceTimeoutMs)\n {\n QTime timeoutTimer;\n timeoutTimer.start();\n bool timeout = false;\n while (!pendingResults.empty() && !timeout) {\n const int pendingResultsCountBefore = pendingResults.count();\n QTest::qWait(silenceTimeoutMs \/ 10);\n if (pendingResults.count() < pendingResultsCountBefore) {\n timeoutTimer.restart();\n }\n else if (timeoutTimer.elapsed() > silenceTimeoutMs) {\n timeout = true;\n }\n }\n return !timeout;\n }\n\npublic Q_SLOTS:\n void onDataReady(int listPos)\n {\n QSparqlResult *result = resultList.at(listPos);\n while (result->next()) {\n \/\/ just do something pointless with the result\n result->value(1).toInt();\n result->value(0).toString();\n }\n }\n\n void onFinished(int listPos)\n {\n QPair resultRange = resultRanges.at(listPos);\n QSparqlResult* result = resultList.at(listPos);\n int expectedResultSize = (resultRange.second - resultRange.first) + 1;\n QCOMPARE(expectedResultSize, result->size());\n \/\/ the results should have been fully nexted in the data ready function\n QCOMPARE(result->pos(), (int)QSparql::AfterLastRow);\n \/\/ go back through the results and validate that they are in range\n int resultCount = 0;\n while (result->previous()) {\n \/\/we don't know the order, so just ensure the result is within range\n QVERIFY(result->value(1).toInt() <= resultRange.second && result->value(1).toInt() >= resultRange.first);\n resultCount++;\n }\n \/\/ now make sure the results counted match the size\n QCOMPARE(resultCount, expectedResultSize);\n pendingResults.remove(result);\n }\n\n};\n\nclass ThreadObject : public QObject\n{\n Q_OBJECT\npublic:\n QSparqlConnection *connection;\n SignalObject *signalObject;\n QList resultList;\n bool deleteConnection;\n bool deleteSignalObject;\n\n int numQueries;\n int testDataSize;\n\n ThreadObject()\n : connection(0), signalObject(0), deleteConnection(false), deleteSignalObject(false)\n {\n }\n\n ~ThreadObject()\n {\n }\n\n void cleanup()\n {\n if (deleteConnection) {\n delete connection;\n } else {\n \/\/ if we were passed a connection, delete the results\n \/\/ here to avoid leaking them\n foreach(QSparqlResult* result, resultList)\n delete result;\n }\n\n if (deleteSignalObject)\n delete signalObject;\n }\n void setParameters(int numQueries, int testDataSize)\n {\n this->numQueries = numQueries;\n this->testDataSize = testDataSize;\n }\n void setConnection(QSparqlConnection* connection)\n {\n this->connection = connection;\n }\n\n void setSignalObject(SignalObject* signalObject)\n {\n this->signalObject = signalObject;\n\n }\n\n void waitForFinished()\n {\n signalObject->waitForAllFinished(8000);\n }\n\npublic Q_SLOTS:\n void startQueries()\n {\n if (!connection) {\n this->connection = new QSparqlConnection(\"QTRACKER_DIRECT\");\n deleteConnection = true;\n }\n if (!signalObject) {\n this->signalObject = new SignalObject();\n deleteSignalObject = true;\n }\n\n QTime time = QTime::currentTime();\n qsrand((uint)time.msec());\n \/\/ store the result ranges we are going to use\n QList > resultRanges;\n \/\/ first result will read everything\n resultRanges.append(qMakePair(1, testDataSize));\n for (int i=1;i resultRange = resultRanges.at(i);\n QSparqlQuery select(QString(\"select ?u ?t {?u a nmm:MusicPiece;\"\n \"nmm:trackNumber ?t;\"\n \"nie:isLogicalPartOf \"\n \"FILTER ( ?t >=%1 && ?t <=%2 ) }\").arg(resultRange.first).arg(resultRange.second));\n QSparqlResult *result = connection->exec(select);\n resultList.append(result);\n signalObject->append(result, resultRange);\n }\n\n waitForFinished();\n cleanup();\n this->thread()->quit();\n }\n\n};\n\n} \/\/end namespace\n\ntst_QSparqlTrackerDirectConcurrency::tst_QSparqlTrackerDirectConcurrency()\n{\n}\n\ntst_QSparqlTrackerDirectConcurrency::~tst_QSparqlTrackerDirectConcurrency()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::initTestCase()\n{\n \/\/ For running the test without installing the plugins. Should work in\n \/\/ normal and vpath builds.\n QCoreApplication::addLibraryPath(\"..\/..\/..\/plugins\");\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::cleanupTestCase()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::init()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::cleanup()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries()\n{\n QFETCH(int, testDataAmount);\n QFETCH(int, numQueries);\n QFETCH(int, maxThreadCount);\n\n QSparqlConnectionOptions options;\n options.setDataReadyInterval(500);\n options.setMaxThreadCount(maxThreadCount);\n const QString testTag(\"\");\n QScopedPointer testData(createTestData(testDataAmount, \"\", testTag));\n QTest::qWait(2000);\n QVERIFY( testData->isOK() );\n\n \/\/ seed the random number generator\n QTime time = QTime::currentTime();\n qsrand((uint)time.msec());\n \/\/ store the result ranges we are going to use\n QList > resultRanges;\n \/\/ first result will read everything\n resultRanges.append(qMakePair(1, 3000));\n for (int i=1;i resultRange = resultRanges.at(i);\n QSparqlQuery select(QString(\"select ?u ?t {?u a nmm:MusicPiece;\"\n \"nmm:trackNumber ?t;\"\n \"nie:isLogicalPartOf \"\n \"FILTER ( ?t >=%1 && ?t <=%2 ) }\").arg(resultRange.first).arg(resultRange.second));\n QSparqlResult *result = conn.exec(select);\n signalObject.append(result, resultRange);\n }\n\n QVERIFY(signalObject.waitForAllFinished(8000));\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries_data()\n{\n QTest::addColumn(\"testDataAmount\");\n QTest::addColumn(\"numQueries\");\n QTest::addColumn(\"maxThreadCount\");\n\n QTest::newRow(\"3000 items, 10 queries, 4 Threads\") <<\n 3000 << 10 << 4;\n QTest::newRow(\"3000 items, 100 queries, 4 Threads\") <<\n 3000 << 100 << 4;\n QTest::newRow(\"3000 items, 10 queries, 1 Thread\") <<\n 3000 << 10 << 1;\n QTest::newRow(\"3000 items, 100 queries, 1 Thread\") <<\n 3000 << 100 << 1;\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries()\n{\n QFETCH(int, testDataAmount);\n QFETCH(int, numQueries);\n QFETCH(int, numThreads);\n\n QSparqlConnection connection(\"QTRACKER_DIRECT\");\n const QString testTag(\"\");\n QScopedPointer testData(createTestData(testDataAmount, \"\", testTag));\n QTest::qWait(2000);\n QVERIFY( testData->isOK() );\n\n QList createdThreads;\n QList threadObjects;\n for (int i=0;isetConnection(&connection);\n threadObject->setParameters(numQueries, testDataAmount);\n threadObject->moveToThread(newThread);\n\n \/\/ connec the threads started signal to the slot that does the work\n QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries()));\n }\n \/\/ start all the threads\n foreach(QThread* thread, createdThreads) {\n thread->start();\n }\n \/\/ wait for all the threads then delete\n \/\/ TODO: add timer so we don't wait forever\n foreach(QThread* thread, createdThreads) {\n while (!thread->isFinished())\n QTest::qWait(500);\n delete thread;\n }\n\n \/\/cleanup\n foreach(ThreadObject *threadObject, threadObjects)\n delete threadObject;\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries_data()\n{\n QTest::addColumn(\"testDataAmount\");\n QTest::addColumn(\"numQueries\");\n QTest::addColumn(\"numThreads\");\n\n QTest::newRow(\"3000 items, 10 queries, 2 Threads\") <<\n 3000 << 10 << 2;\n QTest::newRow(\"3000 items, 100 queries, 2 Threads\") <<\n 3000 << 100 << 2;\n QTest::newRow(\"3000 items, 10 queries, 10 Threads\") <<\n 3000 << 10 << 10;\n QTest::newRow(\"3000 items, 100 queries, 10 Threads\") <<\n 3000 << 100 << 10;\n}\n\nQTEST_MAIN( tst_QSparqlTrackerDirectConcurrency )\n#include \"tst_qsparql_tracker_direct_concurrency.moc\"\nAdd a test for multiple connections\/threads with select queries\/****************************************************************************\n**\n** Copyright (C) 2010-2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (ivan.frade@nokia.com)\n**\n** This file is part of the test suite of the QtSparql module (not yet part of the Qt Toolkit).\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** GNU Lesser General Public License Usage\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this\n** file. Please review the following information to ensure the GNU Lesser\n** General Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU General\n** Public License version 3.0 as published by the Free Software Foundation\n** and appearing in the file LICENSE.GPL included in the packaging of this\n** file. Please review the following information to ensure the GNU General\n** Public License version 3.0 requirements will be met:\n** http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** Other Usage\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at ivan.frade@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"..\/testhelpers.h\"\n#include \"..\/tracker_direct_common.h\"\n\n#include \n#include \n\nclass tst_QSparqlTrackerDirectConcurrency : public QObject\n{\n Q_OBJECT\npublic:\n tst_QSparqlTrackerDirectConcurrency();\n virtual ~tst_QSparqlTrackerDirectConcurrency();\n\nprivate:\n\nprivate slots:\n void initTestCase();\n void cleanupTestCase();\n void init();\n void cleanup();\n\n void sameConnection_selectQueries();\n void sameConnection_selectQueries_data();\n \/\/void sameConnection_updateQueries();\n void sameConnection_multipleThreads_selectQueries();\n void sameConnection_multipleThreads_selectQueries_data();\n \/\/void sameConnection_multipleThreads_updateQueries();\n\n \/\/ multpleConnections tests will all be multi threaded\n void multipleConnections_selectQueries();\n void multipleConnections_selectQueries_data();\n \/\/void multipleConnections_updateQueries();\n\nprivate:\n QSharedPointer dataReadySpy;\n};\n\nnamespace {\n\nclass SignalObject : public QObject\n{\n Q_OBJECT\npublic:\n SignalObject() : position(0) {}\n ~SignalObject()\n {\n \/\/ delete the signal mappers that were created\n foreach(QSignalMapper* map, signalMaps) {\n delete map;\n }\n }\n\n QSet pendingResults;\n int position;\n QList signalMaps;\n QList > resultRanges;\n\n void append(QSparqlResult *r, QPair range)\n {\n QSignalMapper *dataReadyMapper = new QSignalMapper();\n QSignalMapper *finishedMapper = new QSignalMapper();\n dataReadyMapper->setMapping(r, position);\n finishedMapper->setMapping(r, position);\n position++;\n\n connect(r, SIGNAL(dataReady(int)), dataReadyMapper, SLOT(map()));\n connect(dataReadyMapper, SIGNAL(mapped(int)), this, SLOT(onDataReady(int)));\n connect(r, SIGNAL(finished()), finishedMapper, SLOT(map()));\n connect(finishedMapper, SIGNAL(mapped(int)), this, SLOT(onFinished(int)));\n\n resultList.append(r);\n resultRanges.append(range);\n pendingResults.insert(r);\n\n \/\/ keep track of the signal mappers to delete later\n signalMaps.append(dataReadyMapper);\n signalMaps.append(finishedMapper);\n }\n QList resultList;\n\n bool waitForAllFinished(int silenceTimeoutMs)\n {\n QTime timeoutTimer;\n timeoutTimer.start();\n bool timeout = false;\n while (!pendingResults.empty() && !timeout) {\n const int pendingResultsCountBefore = pendingResults.count();\n QTest::qWait(silenceTimeoutMs \/ 10);\n if (pendingResults.count() < pendingResultsCountBefore) {\n timeoutTimer.restart();\n }\n else if (timeoutTimer.elapsed() > silenceTimeoutMs) {\n timeout = true;\n }\n }\n return !timeout;\n }\n\npublic Q_SLOTS:\n void onDataReady(int listPos)\n {\n QSparqlResult *result = resultList.at(listPos);\n while (result->next()) {\n \/\/ just do something pointless with the result\n result->value(1).toInt();\n result->value(0).toString();\n }\n }\n\n void onFinished(int listPos)\n {\n QPair resultRange = resultRanges.at(listPos);\n QSparqlResult* result = resultList.at(listPos);\n int expectedResultSize = (resultRange.second - resultRange.first) + 1;\n QCOMPARE(expectedResultSize, result->size());\n \/\/ the results should have been fully nexted in the data ready function\n QCOMPARE(result->pos(), (int)QSparql::AfterLastRow);\n \/\/ go back through the results and validate that they are in range\n int resultCount = 0;\n while (result->previous()) {\n \/\/we don't know the order, so just ensure the result is within range\n QVERIFY(result->value(1).toInt() <= resultRange.second && result->value(1).toInt() >= resultRange.first);\n resultCount++;\n }\n \/\/ now make sure the results counted match the size\n QCOMPARE(resultCount, expectedResultSize);\n pendingResults.remove(result);\n }\n\n};\n\nclass ThreadObject : public QObject\n{\n Q_OBJECT\npublic:\n QSparqlConnection *connection;\n SignalObject *signalObject;\n QList resultList;\n bool deleteConnection;\n bool deleteSignalObject;\n\n int numQueries;\n int testDataSize;\n\n ThreadObject()\n : connection(0), signalObject(0), deleteConnection(false), deleteSignalObject(false)\n {\n }\n\n ~ThreadObject()\n {\n }\n\n void cleanup()\n {\n if (deleteConnection) {\n delete connection;\n } else {\n \/\/ if we were passed a connection, delete the results\n \/\/ here to avoid leaking them\n foreach(QSparqlResult* result, resultList)\n delete result;\n }\n\n if (deleteSignalObject)\n delete signalObject;\n }\n void setParameters(int numQueries, int testDataSize)\n {\n this->numQueries = numQueries;\n this->testDataSize = testDataSize;\n }\n void setConnection(QSparqlConnection* connection)\n {\n this->connection = connection;\n }\n\n void setSignalObject(SignalObject* signalObject)\n {\n this->signalObject = signalObject;\n\n }\n\n void waitForFinished()\n {\n signalObject->waitForAllFinished(8000);\n }\n\npublic Q_SLOTS:\n void startQueries()\n {\n if (!connection) {\n this->connection = new QSparqlConnection(\"QTRACKER_DIRECT\");\n deleteConnection = true;\n }\n if (!signalObject) {\n this->signalObject = new SignalObject();\n deleteSignalObject = true;\n }\n\n QTime time = QTime::currentTime();\n qsrand((uint)time.msec());\n \/\/ store the result ranges we are going to use\n QList > resultRanges;\n \/\/ first result will read everything\n resultRanges.append(qMakePair(1, testDataSize));\n for (int i=1;i resultRange = resultRanges.at(i);\n QSparqlQuery select(QString(\"select ?u ?t {?u a nmm:MusicPiece;\"\n \"nmm:trackNumber ?t;\"\n \"nie:isLogicalPartOf \"\n \"FILTER ( ?t >=%1 && ?t <=%2 ) }\").arg(resultRange.first).arg(resultRange.second));\n QSparqlResult *result = connection->exec(select);\n resultList.append(result);\n signalObject->append(result, resultRange);\n }\n\n waitForFinished();\n cleanup();\n this->thread()->quit();\n }\n\n};\n\n} \/\/end namespace\n\ntst_QSparqlTrackerDirectConcurrency::tst_QSparqlTrackerDirectConcurrency()\n{\n}\n\ntst_QSparqlTrackerDirectConcurrency::~tst_QSparqlTrackerDirectConcurrency()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::initTestCase()\n{\n \/\/ For running the test without installing the plugins. Should work in\n \/\/ normal and vpath builds.\n QCoreApplication::addLibraryPath(\"..\/..\/..\/plugins\");\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::cleanupTestCase()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::init()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::cleanup()\n{\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries()\n{\n QFETCH(int, testDataAmount);\n QFETCH(int, numQueries);\n QFETCH(int, maxThreadCount);\n\n QSparqlConnectionOptions options;\n options.setDataReadyInterval(500);\n options.setMaxThreadCount(maxThreadCount);\n const QString testTag(\"\");\n QScopedPointer testData(createTestData(testDataAmount, \"\", testTag));\n QTest::qWait(2000);\n QVERIFY( testData->isOK() );\n\n \/\/ seed the random number generator\n QTime time = QTime::currentTime();\n qsrand((uint)time.msec());\n \/\/ store the result ranges we are going to use\n QList > resultRanges;\n \/\/ first result will read everything\n resultRanges.append(qMakePair(1, 3000));\n for (int i=1;i resultRange = resultRanges.at(i);\n QSparqlQuery select(QString(\"select ?u ?t {?u a nmm:MusicPiece;\"\n \"nmm:trackNumber ?t;\"\n \"nie:isLogicalPartOf \"\n \"FILTER ( ?t >=%1 && ?t <=%2 ) }\").arg(resultRange.first).arg(resultRange.second));\n QSparqlResult *result = conn.exec(select);\n signalObject.append(result, resultRange);\n }\n\n QVERIFY(signalObject.waitForAllFinished(8000));\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_selectQueries_data()\n{\n QTest::addColumn(\"testDataAmount\");\n QTest::addColumn(\"numQueries\");\n QTest::addColumn(\"maxThreadCount\");\n\n QTest::newRow(\"3000 items, 10 queries, 4 Threads\") <<\n 3000 << 10 << 4;\n QTest::newRow(\"3000 items, 100 queries, 4 Threads\") <<\n 3000 << 100 << 4;\n QTest::newRow(\"3000 items, 10 queries, 1 Thread\") <<\n 3000 << 10 << 1;\n QTest::newRow(\"3000 items, 100 queries, 1 Thread\") <<\n 3000 << 100 << 1;\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries()\n{\n QFETCH(int, testDataAmount);\n QFETCH(int, numQueries);\n QFETCH(int, numThreads);\n\n QSparqlConnection connection(\"QTRACKER_DIRECT\");\n const QString testTag(\"\");\n QScopedPointer testData(createTestData(testDataAmount, \"\", testTag));\n QTest::qWait(2000);\n QVERIFY( testData->isOK() );\n\n QList createdThreads;\n QList threadObjects;\n for (int i=0;isetConnection(&connection);\n threadObject->setParameters(numQueries, testDataAmount);\n threadObject->moveToThread(newThread);\n\n \/\/ connec the threads started signal to the slot that does the work\n QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries()));\n }\n \/\/ start all the threads\n foreach(QThread* thread, createdThreads) {\n thread->start();\n }\n \/\/ wait for all the threads then delete\n \/\/ TODO: add timer so we don't wait forever\n foreach(QThread* thread, createdThreads) {\n while (!thread->isFinished())\n QTest::qWait(500);\n delete thread;\n }\n\n \/\/cleanup\n foreach(ThreadObject *threadObject, threadObjects)\n delete threadObject;\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::sameConnection_multipleThreads_selectQueries_data()\n{\n QTest::addColumn(\"testDataAmount\");\n QTest::addColumn(\"numQueries\");\n QTest::addColumn(\"numThreads\");\n\n QTest::newRow(\"3000 items, 10 queries, 2 Threads\") <<\n 3000 << 10 << 2;\n QTest::newRow(\"3000 items, 100 queries, 2 Threads\") <<\n 3000 << 100 << 2;\n QTest::newRow(\"3000 items, 10 queries, 10 Threads\") <<\n 3000 << 10 << 10;\n QTest::newRow(\"3000 items, 100 queries, 10 Threads\") <<\n 3000 << 100 << 10;\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::multipleConnections_selectQueries()\n{\n QFETCH(int, testDataAmount);\n QFETCH(int, numQueries);\n QFETCH(int, numThreads);\n\n QSparqlConnection connection(\"QTRACKER_DIRECT\");\n const QString testTag(\"\");\n QScopedPointer testData(createTestData(testDataAmount, \"\", testTag));\n QTest::qWait(2000);\n QVERIFY( testData->isOK() );\n\n QList createdThreads;\n QList threadObjects;\n for (int i=0;isetParameters(numQueries, testDataAmount);\n threadObject->moveToThread(newThread);\n\n \/\/ connec the threads started signal to the slot that does the work\n QObject::connect(newThread, SIGNAL(started()), threadObject, SLOT(startQueries()));\n }\n \/\/ start all the threads\n foreach(QThread* thread, createdThreads) {\n thread->start();\n }\n \/\/ wait for all the threads then delete\n \/\/ TODO: add timer so we don't wait forever\n foreach(QThread* thread, createdThreads) {\n while (!thread->isFinished())\n QTest::qWait(500);\n delete thread;\n }\n \/\/cleanup\n foreach(ThreadObject *threadObject, threadObjects)\n delete threadObject;\n}\n\nvoid tst_QSparqlTrackerDirectConcurrency::multipleConnections_selectQueries_data()\n{\n qDebug() << \"This data function has been called....\";\n QTest::addColumn(\"testDataAmount\");\n QTest::addColumn(\"numQueries\");\n QTest::addColumn(\"numThreads\");\n\n QTest::newRow(\"3000 items, 10 queries, 2 Threads\") <<\n 3000 << 10 << 2;\n QTest::newRow(\"3000 items, 100 queries, 2 Threads\") <<\n 3000 << 100 << 2;\n QTest::newRow(\"3000 items, 10 queries, 10 Threads\") <<\n 3000 << 10 << 10;\n QTest::newRow(\"3000 items, 100 queries, 10 Threads\") <<\n 3000 << 100 << 10;\n}\n\nQTEST_MAIN( tst_QSparqlTrackerDirectConcurrency )\n#include \"tst_qsparql_tracker_direct_concurrency.moc\"\n<|endoftext|>"} {"text":"\/** @file\n @brief Implementation\n\n @date 2014\n\n @author\n Ryan Pavlik\n \n \n*\/\n\n\/\/ Copyright 2014 Sensics, Inc.\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ (Final version intended to be licensed under\n\/\/ the Apache License, Version 2.0)\n\n\/\/ Internal Includes\n#include \"ServerImpl.h\"\n#include \n#include \n#include \n#include \n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include \n#include \n\nnamespace osvr {\nnamespace server {\n ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)\n : m_conn(conn), m_ctx(make_shared()),\n m_running(false) {\n if (!m_conn) {\n throw std::logic_error(\n \"Can't pass a null ConnectionPtr into Server constructor!\");\n }\n osvr::connection::Connection::storeConnection(*m_ctx, m_conn);\n\n if (!m_sysDevice) {\n m_sysDevice = connection::DeviceToken::createVirtualDevice(\n util::messagekeys::systemSender(), m_conn);\n }\n if (!m_routingMessageType) {\n m_routingMessageType =\n m_conn->registerMessageType(util::messagekeys::routingData());\n }\n }\n\n ServerImpl::~ServerImpl() { stop(); }\n\n void ServerImpl::start() {\n boost::unique_lock lock(m_runControl);\n m_running = true;\n\n \/\/ Use a lambda to run the loop.\n m_thread = boost::thread([&] {\n bool keepRunning = true;\n ::util::LoopGuard guard(m_run);\n do {\n keepRunning = this->loop();\n } while (keepRunning);\n m_ctx.reset();\n m_conn.reset();\n m_running = false;\n });\n m_run.signalAndWaitForStart();\n }\n\n void ServerImpl::startAndAwaitShutdown() {\n start();\n m_thread.join();\n }\n\n void ServerImpl::stop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalAndWaitForShutdown();\n m_thread.join();\n m_thread = boost::thread();\n }\n void ServerImpl::signalStop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalShutdown();\n }\n\n void ServerImpl::loadPlugin(std::string const &pluginName) {\n m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,\n m_ctx, pluginName));\n }\n\n void ServerImpl::instantiateDriver(std::string const &plugin,\n std::string const &driver,\n std::string const ¶ms) {\n m_ctx->instantiateDriver(plugin, driver, params);\n }\n\n void ServerImpl::triggerHardwareDetect() {\n m_callControlled(std::bind(\n &pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));\n }\n\n void ServerImpl::registerMainloopMethod(MainloopMethod f) {\n if (f) {\n m_mainloopMethods.push_back(f);\n }\n }\n\n bool ServerImpl::loop() {\n m_conn->process();\n for (auto &f : m_mainloopMethods) {\n f();\n }\n \/\/\/ @todo do queued things in here?\n \/\/\/ @todo configurable waiting?\n m_thread.yield();\n return m_run.shouldContinue();\n }\n\n template \n inline void ServerImpl::m_callControlled(Callable f) {\n boost::unique_lock lock(m_runControl);\n if (m_running) {\n \/\/\/ @todo not yet implemented\n throw std::logic_error(\"not yet implemented\");\n }\n f();\n }\n\n} \/\/ namespace server\n} \/\/ namespace osvrcallControlled in server is OK if we're running as long as we're in the right thread.\/** @file\n @brief Implementation\n\n @date 2014\n\n @author\n Ryan Pavlik\n \n \n*\/\n\n\/\/ Copyright 2014 Sensics, Inc.\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ (Final version intended to be licensed under\n\/\/ the Apache License, Version 2.0)\n\n\/\/ Internal Includes\n#include \"ServerImpl.h\"\n#include \n#include \n#include \n#include \n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include \n#include \n\nnamespace osvr {\nnamespace server {\n ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)\n : m_conn(conn), m_ctx(make_shared()),\n m_running(false) {\n if (!m_conn) {\n throw std::logic_error(\n \"Can't pass a null ConnectionPtr into Server constructor!\");\n }\n osvr::connection::Connection::storeConnection(*m_ctx, m_conn);\n\n if (!m_sysDevice) {\n m_sysDevice = connection::DeviceToken::createVirtualDevice(\n util::messagekeys::systemSender(), m_conn);\n }\n if (!m_routingMessageType) {\n m_routingMessageType =\n m_conn->registerMessageType(util::messagekeys::routingData());\n }\n }\n\n ServerImpl::~ServerImpl() { stop(); }\n\n void ServerImpl::start() {\n boost::unique_lock lock(m_runControl);\n m_running = true;\n\n \/\/ Use a lambda to run the loop.\n m_thread = boost::thread([&] {\n bool keepRunning = true;\n ::util::LoopGuard guard(m_run);\n do {\n keepRunning = this->loop();\n } while (keepRunning);\n m_ctx.reset();\n m_conn.reset();\n m_running = false;\n });\n m_run.signalAndWaitForStart();\n }\n\n void ServerImpl::startAndAwaitShutdown() {\n start();\n m_thread.join();\n }\n\n void ServerImpl::stop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalAndWaitForShutdown();\n m_thread.join();\n m_thread = boost::thread();\n }\n void ServerImpl::signalStop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalShutdown();\n }\n\n void ServerImpl::loadPlugin(std::string const &pluginName) {\n m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,\n m_ctx, pluginName));\n }\n\n void ServerImpl::instantiateDriver(std::string const &plugin,\n std::string const &driver,\n std::string const ¶ms) {\n m_ctx->instantiateDriver(plugin, driver, params);\n }\n\n void ServerImpl::triggerHardwareDetect() {\n m_callControlled(std::bind(\n &pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));\n }\n\n void ServerImpl::registerMainloopMethod(MainloopMethod f) {\n if (f) {\n m_mainloopMethods.push_back(f);\n }\n }\n\n bool ServerImpl::loop() {\n m_conn->process();\n for (auto &f : m_mainloopMethods) {\n f();\n }\n \/\/\/ @todo do queued things in here?\n \/\/\/ @todo configurable waiting?\n m_thread.yield();\n return m_run.shouldContinue();\n }\n\n template \n inline void ServerImpl::m_callControlled(Callable f) {\n boost::unique_lock lock(m_runControl);\n if (m_running && boost::this_thread::get_id() != m_thread.get_id()) {\n \/\/\/ @todo callControlled after the run loop started from outside the\n \/\/\/ run loop's thread is not yet implemented\n throw std::logic_error(\"not yet implemented\");\n }\n f();\n }\n\n} \/\/ namespace server\n} \/\/ namespace osvr<|endoftext|>"} {"text":"\/**\n * \\ file UniversalFixedDelayLineFilter.cpp\n *\/\n\n#include \n\n#include \n#include \n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include \n\n#include \n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line100_delay50_test )\n{\n boost::scoped_array data(new float[PROCESSSIZE]);\n for(std::int64_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n\n ATK::InPointerFilter generator(data.get(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n boost::scoped_array outdata(new float[PROCESSSIZE]);\n\n ATK::UniversalFixedDelayLineFilter filter(100);\n filter.set_input_sampling_rate(48000);\n filter.set_input_port(0, &generator, 0);\n filter.set_delay(50);\n\n ATK::OutPointerFilter output(outdata.get(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &filter, 0);\n\n output.process(1);\n output.process(49);\n output.process(51);\n output.process(PROCESSSIZE - 1 - 49 -51);\n \n for(std::int64_t i = 0; i < 50; ++i)\n {\n BOOST_REQUIRE_EQUAL(0, outdata[i]);\n }\n \n for(std::int64_t i = 50; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);\n }\n}\nTesting additional options in the delay line\/**\n * \\ file UniversalFixedDelayLineFilter.cpp\n *\/\n\n#include \n\n#include \n#include \n\n#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_NO_MAIN\n#include \n\n#include \n\n#define PROCESSSIZE (1024*64)\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line100_delay50_test )\n{\n boost::scoped_array data(new float[PROCESSSIZE]);\n for(std::int64_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n\n ATK::InPointerFilter generator(data.get(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n boost::scoped_array outdata(new float[PROCESSSIZE]);\n\n ATK::UniversalFixedDelayLineFilter filter(100);\n filter.set_input_sampling_rate(48000);\n filter.set_input_port(0, &generator, 0);\n filter.set_delay(50);\n\n ATK::OutPointerFilter output(outdata.get(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &filter, 0);\n\n output.process(49);\n output.process(1);\n output.process(51);\n output.process(PROCESSSIZE - 1 - 49 -51);\n \n for(std::int64_t i = 0; i < 50; ++i)\n {\n BOOST_REQUIRE_EQUAL(0, outdata[i]);\n }\n \n for(std::int64_t i = 50; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_EQUAL(data[i - 50], outdata[i]);\n }\n}\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line25_delay24_blend_1_feedforward_1_feedback_0_test )\n{\n boost::scoped_array data(new float[PROCESSSIZE]);\n for(std::int64_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n\n ATK::InPointerFilter generator(data.get(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n boost::scoped_array outdata(new float[PROCESSSIZE]);\n\n ATK::UniversalFixedDelayLineFilter filter(25);\n filter.set_input_sampling_rate(48000);\n filter.set_input_port(0, &generator, 0);\n filter.set_delay(24);\n filter.set_blend(1);\n filter.set_feedback(0);\n filter.set_feedforward(1);\n\n ATK::OutPointerFilter output(outdata.get(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &filter, 0);\n\n output.process(49);\n output.process(1);\n output.process(51);\n output.process(PROCESSSIZE - 1 - 49 -51);\n\n for(std::int64_t i = 24; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_SMALL(outdata[i], 0.0001f);\n }\n}\n\nBOOST_AUTO_TEST_CASE( UniversalFixedDelayLineFilter_sinus_line25_delay24_blend_0_feedforward_0_feedback_1_test )\n{\n boost::scoped_array data(new float[PROCESSSIZE]);\n for(std::int64_t i = 0; i < PROCESSSIZE; ++i)\n {\n data[i] = std::sin(2 * boost::math::constants::pi() * (i+1.)\/48000 * 1000);\n }\n\n ATK::InPointerFilter generator(data.get(), 1, PROCESSSIZE, false);\n generator.set_output_sampling_rate(48000);\n\n boost::scoped_array outdata(new float[PROCESSSIZE]);\n\n ATK::UniversalFixedDelayLineFilter filter(25);\n filter.set_input_sampling_rate(48000);\n filter.set_input_port(0, &generator, 0);\n filter.set_delay(24);\n filter.set_blend(0);\n filter.set_feedback(1);\n filter.set_feedforward(0);\n\n ATK::OutPointerFilter output(outdata.get(), 1, PROCESSSIZE, false);\n output.set_input_sampling_rate(48000);\n output.set_input_port(0, &filter, 0);\n\n output.process(49);\n output.process(1);\n output.process(51);\n output.process(PROCESSSIZE - 1 - 49 -51);\n\n for(std::int64_t i = 24; i < PROCESSSIZE; ++i)\n {\n BOOST_REQUIRE_SMALL(outdata[i], 0.0001f);\n }\n}\n<|endoftext|>"} {"text":"\/** @file\n @brief Implementation\n\n @date 2014\n\n @author\n Ryan Pavlik\n \n \n*\/\n\n\/\/ Copyright 2014 Sensics, Inc.\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ (Final version intended to be licensed under\n\/\/ the Apache License, Version 2.0)\n\n\/\/ Internal Includes\n#include \"ServerImpl.h\"\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include \n#include \n\nnamespace osvr {\nnamespace server {\n ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)\n : m_conn(conn), m_ctx(make_shared()),\n m_running(false) {\n if (!m_conn) {\n throw std::logic_error(\n \"Can't pass a null ConnectionPtr into Server constructor!\");\n }\n osvr::connection::Connection::storeConnection(*m_ctx, m_conn);\n\n if (!m_sysDevice) {\n m_sysDevice = connection::DeviceToken::createVirtualDevice(\n util::messagekeys::systemSender(), m_conn);\n }\n if (!m_routingMessageType) {\n m_routingMessageType =\n m_conn->registerMessageType(util::messagekeys::routingData());\n }\n m_conn->registerConnectionHandler(\n std::bind(&ServerImpl::triggerHardwareDetect, std::ref(*this)));\n m_conn->registerConnectionHandler(\n std::bind(&ServerImpl::m_sendRoutes, std::ref(*this)));\n }\n\n ServerImpl::~ServerImpl() { stop(); }\n\n void ServerImpl::start() {\n boost::unique_lock lock(m_runControl);\n m_running = true;\n\n \/\/ Use a lambda to run the loop.\n m_thread = boost::thread([&] {\n bool keepRunning = true;\n ::util::LoopGuard guard(m_run);\n do {\n keepRunning = this->loop();\n } while (keepRunning);\n m_ctx.reset();\n m_conn.reset();\n m_running = false;\n });\n m_run.signalAndWaitForStart();\n }\n\n void ServerImpl::startAndAwaitShutdown() {\n start();\n awaitShutdown();\n }\n\n void ServerImpl::awaitShutdown() { m_thread.join(); }\n\n void ServerImpl::stop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalAndWaitForShutdown();\n m_thread.join();\n m_thread = boost::thread();\n }\n\n void ServerImpl::signalStop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalShutdown();\n }\n\n void ServerImpl::loadPlugin(std::string const &pluginName) {\n m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,\n m_ctx, pluginName));\n }\n\n void ServerImpl::instantiateDriver(std::string const &plugin,\n std::string const &driver,\n std::string const ¶ms) {\n m_ctx->instantiateDriver(plugin, driver, params);\n }\n\n void ServerImpl::triggerHardwareDetect() {\n OSVR_DEV_VERBOSE(\"Performing hardware auto-detection.\");\n m_callControlled(std::bind(\n &pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));\n }\n\n void ServerImpl::registerMainloopMethod(MainloopMethod f) {\n if (f) {\n m_callControlled([&] { m_mainloopMethods.push_back(f); });\n }\n }\n\n bool ServerImpl::loop() {\n bool shouldContinue;\n {\n \/\/\/ @todo More elegant way of running queued things than grabbing a\n \/\/\/ mutex each time through?\n boost::unique_lock lock(m_mainThreadMutex);\n m_conn->process();\n for (auto &f : m_mainloopMethods) {\n f();\n }\n shouldContinue = m_run.shouldContinue();\n }\n \/\/\/ @todo configurable waiting?\n m_thread.yield();\n return shouldContinue;\n }\n\n bool ServerImpl::addRoute(std::string const &routingDirective) {\n bool wasNew;\n m_callControlled([&] { wasNew = m_routes.addRoute(routingDirective); });\n return wasNew;\n }\n\n std::string ServerImpl::getRoutes(bool styled) const {\n std::string ret;\n m_callControlled([&] { ret = m_routes.getRoutes(styled); });\n return ret;\n }\n\n std::string ServerImpl::getSource(std::string const &destination) const {\n std::string ret;\n m_callControlled([&] { ret = m_routes.getSource(destination); });\n return ret;\n }\n\n void ServerImpl::m_sendRoutes() {\n std::string message = getRoutes(false);\n OSVR_DEV_VERBOSE(\"Transmitting \" << m_routes.size()\n << \" routes to the client.\");\n m_sysDevice->sendData(m_routingMessageType.get(), message.c_str(),\n message.size());\n }\n\n} \/\/ namespace server\n} \/\/ namespace osvrDon't have a nested callControlled when sending routes.\/** @file\n @brief Implementation\n\n @date 2014\n\n @author\n Ryan Pavlik\n \n \n*\/\n\n\/\/ Copyright 2014 Sensics, Inc.\n\/\/\n\/\/ All rights reserved.\n\/\/\n\/\/ (Final version intended to be licensed under\n\/\/ the Apache License, Version 2.0)\n\n\/\/ Internal Includes\n#include \"ServerImpl.h\"\n#include \n#include \n#include \n#include \n#include \n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n#include \n#include \n\nnamespace osvr {\nnamespace server {\n ServerImpl::ServerImpl(connection::ConnectionPtr const &conn)\n : m_conn(conn), m_ctx(make_shared()),\n m_running(false) {\n if (!m_conn) {\n throw std::logic_error(\n \"Can't pass a null ConnectionPtr into Server constructor!\");\n }\n osvr::connection::Connection::storeConnection(*m_ctx, m_conn);\n\n if (!m_sysDevice) {\n m_sysDevice = connection::DeviceToken::createVirtualDevice(\n util::messagekeys::systemSender(), m_conn);\n }\n if (!m_routingMessageType) {\n m_routingMessageType =\n m_conn->registerMessageType(util::messagekeys::routingData());\n }\n m_conn->registerConnectionHandler(\n std::bind(&ServerImpl::triggerHardwareDetect, std::ref(*this)));\n m_conn->registerConnectionHandler(\n std::bind(&ServerImpl::m_sendRoutes, std::ref(*this)));\n }\n\n ServerImpl::~ServerImpl() { stop(); }\n\n void ServerImpl::start() {\n boost::unique_lock lock(m_runControl);\n m_running = true;\n\n \/\/ Use a lambda to run the loop.\n m_thread = boost::thread([&] {\n bool keepRunning = true;\n ::util::LoopGuard guard(m_run);\n do {\n keepRunning = this->loop();\n } while (keepRunning);\n m_ctx.reset();\n m_conn.reset();\n m_running = false;\n });\n m_run.signalAndWaitForStart();\n }\n\n void ServerImpl::startAndAwaitShutdown() {\n start();\n awaitShutdown();\n }\n\n void ServerImpl::awaitShutdown() { m_thread.join(); }\n\n void ServerImpl::stop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalAndWaitForShutdown();\n m_thread.join();\n m_thread = boost::thread();\n }\n\n void ServerImpl::signalStop() {\n boost::unique_lock lock(m_runControl);\n m_run.signalShutdown();\n }\n\n void ServerImpl::loadPlugin(std::string const &pluginName) {\n m_callControlled(std::bind(&pluginhost::RegistrationContext::loadPlugin,\n m_ctx, pluginName));\n }\n\n void ServerImpl::instantiateDriver(std::string const &plugin,\n std::string const &driver,\n std::string const ¶ms) {\n m_ctx->instantiateDriver(plugin, driver, params);\n }\n\n void ServerImpl::triggerHardwareDetect() {\n OSVR_DEV_VERBOSE(\"Performing hardware auto-detection.\");\n m_callControlled(std::bind(\n &pluginhost::RegistrationContext::triggerHardwareDetect, m_ctx));\n }\n\n void ServerImpl::registerMainloopMethod(MainloopMethod f) {\n if (f) {\n m_callControlled([&] { m_mainloopMethods.push_back(f); });\n }\n }\n\n bool ServerImpl::loop() {\n bool shouldContinue;\n {\n \/\/\/ @todo More elegant way of running queued things than grabbing a\n \/\/\/ mutex each time through?\n boost::unique_lock lock(m_mainThreadMutex);\n m_conn->process();\n for (auto &f : m_mainloopMethods) {\n f();\n }\n shouldContinue = m_run.shouldContinue();\n }\n \/\/\/ @todo configurable waiting?\n m_thread.yield();\n return shouldContinue;\n }\n\n bool ServerImpl::addRoute(std::string const &routingDirective) {\n bool wasNew;\n m_callControlled([&] { wasNew = m_routes.addRoute(routingDirective); });\n return wasNew;\n }\n\n std::string ServerImpl::getRoutes(bool styled) const {\n std::string ret;\n m_callControlled([&] { ret = m_routes.getRoutes(styled); });\n return ret;\n }\n\n std::string ServerImpl::getSource(std::string const &destination) const {\n std::string ret;\n m_callControlled([&] { ret = m_routes.getSource(destination); });\n return ret;\n }\n\n void ServerImpl::m_sendRoutes() {\n std::string message = m_routes.getRoutes();\n OSVR_DEV_VERBOSE(\"Transmitting \" << m_routes.size()\n << \" routes to the client.\");\n m_sysDevice->sendData(m_routingMessageType.get(), message.c_str(),\n message.size());\n }\n\n} \/\/ namespace server\n} \/\/ namespace osvr<|endoftext|>"} {"text":"\/\/ Arguments: Doubles, Doubles, Doubles, Doubles\n#include \n\nusing stan::math::var;\nusing std::numeric_limits;\nusing std::vector;\n\nclass AgradDistributionsStudentT : public AgradDistributionTest {\n public:\n void valid_values(vector >& parameters,\n vector& log_prob) {\n vector param(4);\n\n param[0] = 1.0; \/\/ y\n param[1] = 1.0; \/\/ nu\n param[2] = 0.0; \/\/ mu\n param[3] = 1.0; \/\/ sigma\n parameters.push_back(param);\n log_prob.push_back(-1.837877066409345339082); \/\/ expected log_prob\n\n param[0] = -3.0; \/\/ y\n param[1] = 2.0; \/\/ nu\n param[2] = 0.0; \/\/ mu\n param[3] = 1.0; \/\/ sigma\n parameters.push_back(param);\n log_prob.push_back(-3.596842909197555560041); \/\/ expected log_prob\n }\n\n void invalid_values(vector& index, vector& value) {\n \/\/ y\n\n \/\/ nu\n index.push_back(1U);\n value.push_back(0.0);\n\n index.push_back(1U);\n value.push_back(-1.0);\n\n index.push_back(1U);\n value.push_back(numeric_limits::infinity());\n\n index.push_back(1U);\n value.push_back(-numeric_limits::infinity());\n\n \/\/ mu\n index.push_back(2U);\n value.push_back(numeric_limits::infinity());\n\n index.push_back(2U);\n value.push_back(-numeric_limits::infinity());\n\n \/\/ sigma\n index.push_back(3U);\n value.push_back(0.0);\n\n index.push_back(3U);\n value.push_back(-1.0);\n\n index.push_back(3U);\n value.push_back(numeric_limits::infinity());\n\n index.push_back(3U);\n value.push_back(-numeric_limits::infinity());\n }\n\n template \n typename stan::return_type::type log_prob(\n const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,\n const T4&, const T5&) {\n return stan::math::student_t_log(y, nu, mu, sigma);\n }\n\n template \n typename stan::return_type::type log_prob(\n const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,\n const T4&, const T5&) {\n return stan::math::student_t_log(y, nu, mu, sigma);\n }\n\n template \n typename stan::return_type::type\n log_prob_function(const T_y& y, const T_dof& nu, const T_loc& mu,\n const T_scale& sigma, const T4&, const T5&) {\n using boost::math::lgamma;\n using stan::math::log1p;\n using stan::math::LOG_SQRT_PI;\n using stan::math::square;\n using std::log;\n\n return lgamma((nu + 1.0) \/ 2.0) - lgamma(nu \/ 2.0) - LOG_SQRT_PI\n - 0.5 * log(nu) - log(sigma)\n - ((nu + 1.0) \/ 2.0) * log1p(square(((y - mu) \/ sigma)) \/ nu);\n }\n};\n[Jenkins] auto-formatting by clang-format version 6.0.0 (tags\/google\/stable\/2017-11-14)\/\/ Arguments: Doubles, Doubles, Doubles, Doubles\n#include \n\nusing stan::math::var;\nusing std::numeric_limits;\nusing std::vector;\n\nclass AgradDistributionsStudentT : public AgradDistributionTest {\n public:\n void valid_values(vector >& parameters,\n vector& log_prob) {\n vector param(4);\n\n param[0] = 1.0; \/\/ y\n param[1] = 1.0; \/\/ nu\n param[2] = 0.0; \/\/ mu\n param[3] = 1.0; \/\/ sigma\n parameters.push_back(param);\n log_prob.push_back(-1.837877066409345339082); \/\/ expected log_prob\n\n param[0] = -3.0; \/\/ y\n param[1] = 2.0; \/\/ nu\n param[2] = 0.0; \/\/ mu\n param[3] = 1.0; \/\/ sigma\n parameters.push_back(param);\n log_prob.push_back(-3.596842909197555560041); \/\/ expected log_prob\n }\n\n void invalid_values(vector& index, vector& value) {\n \/\/ y\n\n \/\/ nu\n index.push_back(1U);\n value.push_back(0.0);\n\n index.push_back(1U);\n value.push_back(-1.0);\n\n index.push_back(1U);\n value.push_back(numeric_limits::infinity());\n\n index.push_back(1U);\n value.push_back(-numeric_limits::infinity());\n\n \/\/ mu\n index.push_back(2U);\n value.push_back(numeric_limits::infinity());\n\n index.push_back(2U);\n value.push_back(-numeric_limits::infinity());\n\n \/\/ sigma\n index.push_back(3U);\n value.push_back(0.0);\n\n index.push_back(3U);\n value.push_back(-1.0);\n\n index.push_back(3U);\n value.push_back(numeric_limits::infinity());\n\n index.push_back(3U);\n value.push_back(-numeric_limits::infinity());\n }\n\n template \n typename stan::return_type::type log_prob(\n const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,\n const T4&, const T5&) {\n return stan::math::student_t_log(y, nu, mu, sigma);\n }\n\n template \n typename stan::return_type::type log_prob(\n const T_y& y, const T_dof& nu, const T_loc& mu, const T_scale& sigma,\n const T4&, const T5&) {\n return stan::math::student_t_log(y, nu, mu, sigma);\n }\n\n template \n typename stan::return_type::type\n log_prob_function(const T_y& y, const T_dof& nu, const T_loc& mu,\n const T_scale& sigma, const T4&, const T5&) {\n using boost::math::lgamma;\n using stan::math::LOG_SQRT_PI;\n using stan::math::log1p;\n using stan::math::square;\n using std::log;\n\n return lgamma((nu + 1.0) \/ 2.0) - lgamma(nu \/ 2.0) - LOG_SQRT_PI\n - 0.5 * log(nu) - log(sigma)\n - ((nu + 1.0) \/ 2.0) * log1p(square(((y - mu) \/ sigma)) \/ nu);\n }\n};\n<|endoftext|>"} {"text":"\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ C++ Includes -----------------------------------\n\n\/\/ Local Includes -----------------------------------\n#include \"elem.h\"\n#include \"mesh_base.h\"\n#include \"parallel.h\"\n#include \"partitioner.h\"\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Partitioner implementation\n\n\nvoid Partitioner::partition (MeshBase& mesh,\n\t\t\t const unsigned int n)\n{\n \/\/ For now we don't repartition in parallel\n if (!mesh.is_serial())\n return;\n\n \/\/ Set the number of partitions in the mesh\n mesh.set_n_partitions()=n;\n\n \/\/ Call the partitioning function\n this->_do_partition(mesh,n);\n\n \/\/ Set the node's processor ids\n Partitioner::set_node_processor_ids(mesh);\n}\n\n\n\n\n\nvoid Partitioner::repartition (MeshBase& mesh,\n\t\t\t const unsigned int n)\n{\n \/\/ Set the number of partitions in the mesh\n mesh.set_n_partitions()=n;\n \n \/\/ Call the partitioning function\n this->_do_repartition(mesh,n);\n\n \/\/ Set the node's processor ids\n Partitioner::set_node_processor_ids(mesh);\n}\n\n\n\n\n\nvoid Partitioner::single_partition (MeshBase& mesh)\n{\n \/\/ Loop over all the elements and assign them to processor 0.\n MeshBase::element_iterator elem_it = mesh.elements_begin();\n const MeshBase::element_iterator elem_end = mesh.elements_end(); \n\n for ( ; elem_it != elem_end; ++elem_it)\n (*elem_it)->processor_id() = 0;\n\n \/\/ For a single partition, all the nodes are on processor 0\n MeshBase::node_iterator node_it = mesh.nodes_begin();\n const MeshBase::node_iterator node_end = mesh.nodes_end();\n \n for ( ; node_it != node_end; ++node_it)\n (*node_it)->processor_id() = 0;\n}\n\n\n\n\nvoid Partitioner::set_node_processor_ids(MeshBase& mesh)\n{\n \/\/ This function must be run on all processors at once\n parallel_only();\n\n \/\/ Unset any previously-set node processor ids\n \/\/ (maybe from previous partitionings).\n MeshBase::node_iterator node_it = mesh.nodes_begin();\n const MeshBase::node_iterator node_end = mesh.nodes_end();\n \n for ( ; node_it != node_end; ++node_it)\n {\n Node *node = *node_it;\n assert(node);\n node->invalidate_processor_id();\n }\n \n \n \/\/ Loop over all the active elements\n MeshBase::element_iterator elem_it = mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = mesh.active_elements_end(); \n \n for ( ; elem_it != elem_end; ++elem_it)\n {\n Elem* elem = *elem_it;\n assert(elem);\n \n \/\/ For each node, set the processor ID to the min of\n \/\/ its current value and this Element's processor id.\n for (unsigned int n=0; nn_nodes(); ++n)\n\telem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),\n\t\t\t\t\t\t elem->processor_id());\n }\n\n \/\/ And loop over the subactive elements, but don't reassign\n \/\/ nodes that are already active on another processor.\n MeshBase::element_iterator sub_it = mesh.subactive_elements_begin();\n const MeshBase::element_iterator sub_end = mesh.subactive_elements_end(); \n \n for ( ; sub_it != sub_end; ++sub_it)\n {\n Elem* elem = *sub_it;\n assert(elem);\n \n for (unsigned int n=0; nn_nodes(); ++n)\n if (elem->get_node(n)->processor_id() == DofObject::invalid_processor_id)\n\t elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),\n\t\t\t\t\t\t elem->processor_id());\n }\n\n \/\/ At this point, if we're in parallel, all our own processor ids\n \/\/ should be correct, but ghost nodes may be incorrect. However,\n \/\/ our tenative processor ids will let us know who to ask.\n\n \/\/ Loop over all the nodes, count the ones on each processor\n std::vector\n ghost_objects_from_proc(libMesh::n_processors(), 0);\n\n node_it = mesh.nodes_begin();\n for ( ; node_it != node_end; ++node_it)\n {\n Node *node = *node_it;\n assert(node);\n unsigned int obj_procid = node->processor_id();\n assert(obj_procid != DofObject::invalid_processor_id);\n ghost_objects_from_proc[obj_procid]++;\n }\n\n \/\/ Request sets to send to each processor\n std::vector >\n requested_ids(libMesh::n_processors());\n\n \/\/ We know how many objects live on each processor, so reserve()\n \/\/ space for each.\n for (unsigned int p=0; p != libMesh::n_processors(); ++p)\n if (p != libMesh::processor_id())\n requested_ids[p].reserve(ghost_objects_from_proc[p]);\n\n node_it = mesh.nodes_begin();\n for ( ; node_it != node_end; ++node_it)\n {\n Node *node = *node_it;\n requested_ids[node->processor_id()].push_back(node->id());\n }\n\n \/\/ Next set ghost object ids from other processors\n for (unsigned int p=1; p != libMesh::n_processors(); ++p)\n {\n \/\/ Trade my requests with processor procup and procdown\n unsigned int procup = (libMesh::processor_id() + p) %\n libMesh::n_processors();\n unsigned int procdown = (libMesh::n_processors() +\n libMesh::processor_id() - p) %\n libMesh::n_processors();\n std::vector request_to_fill;\n Parallel::send_receive(procup, requested_ids[procup],\n procdown, request_to_fill);\n\n \/\/ Fill those requests\n std::vector new_ids(request_to_fill.size());\n for (unsigned int i=0; i != request_to_fill.size(); ++i)\n {\n Node *node = mesh.node_ptr(request_to_fill[i]);\n assert(node);\n new_ids[i] = node->processor_id();\n }\n\n \/\/ Trade back the results\n std::vector filled_request;\n Parallel::send_receive(procdown, new_ids,\n procup, filled_request);\n assert(filled_request.size() == requested_ids[procup].size());\n \n \/\/ And copy the id changes we've now been informed of\n for (unsigned int i=0; i != filled_request.size(); ++i)\n {\n Node *node = mesh.node_ptr(requested_ids[procup][i]);\n assert(filled_request[i] < libMesh::n_processors());\n node->processor_id(filled_request[i]);\n }\n }\n}\ndo not partition into more pieces than we have active elements\/\/ $Id$\n\n\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2007 Benjamin S. Kirk, John W. Peterson\n \n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n \n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n \n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ C++ Includes -----------------------------------\n\n\/\/ Local Includes -----------------------------------\n#include \"elem.h\"\n#include \"mesh_base.h\"\n#include \"parallel.h\"\n#include \"partitioner.h\"\n\n\n\/\/ ------------------------------------------------------------\n\/\/ Partitioner implementation\n\n\nvoid Partitioner::partition (MeshBase& mesh,\n\t\t\t const unsigned int n)\n{\n \/\/ For now we don't repartition in parallel\n if (!mesh.is_serial())\n return;\n\n \/\/ we cannot partition into more pieces than we have\n \/\/ active elements!\n const unsigned int n_parts =\n std::min(mesh.n_active_elem(), n);\n \n \/\/ Set the number of partitions in the mesh\n mesh.set_n_partitions()=n_parts;\n\n \/\/ Call the partitioning function\n this->_do_partition(mesh,n_parts);\n\n \/\/ Set the node's processor ids\n Partitioner::set_node_processor_ids(mesh);\n}\n\n\n\n\n\nvoid Partitioner::repartition (MeshBase& mesh,\n\t\t\t const unsigned int n)\n{\n \/\/ we cannot partition into more pieces than we have\n \/\/ active elements!\n const unsigned int n_parts =\n std::min(mesh.n_active_elem(), n);\n \n \/\/ Set the number of partitions in the mesh\n mesh.set_n_partitions()=n_parts;\n \n \/\/ Call the partitioning function\n this->_do_repartition(mesh,n_parts);\n\n \/\/ Set the node's processor ids\n Partitioner::set_node_processor_ids(mesh);\n}\n\n\n\n\n\nvoid Partitioner::single_partition (MeshBase& mesh)\n{\n \/\/ Loop over all the elements and assign them to processor 0.\n MeshBase::element_iterator elem_it = mesh.elements_begin();\n const MeshBase::element_iterator elem_end = mesh.elements_end(); \n\n for ( ; elem_it != elem_end; ++elem_it)\n (*elem_it)->processor_id() = 0;\n\n \/\/ For a single partition, all the nodes are on processor 0\n MeshBase::node_iterator node_it = mesh.nodes_begin();\n const MeshBase::node_iterator node_end = mesh.nodes_end();\n \n for ( ; node_it != node_end; ++node_it)\n (*node_it)->processor_id() = 0;\n}\n\n\n\n\nvoid Partitioner::set_node_processor_ids(MeshBase& mesh)\n{\n \/\/ This function must be run on all processors at once\n parallel_only();\n\n \/\/ Unset any previously-set node processor ids\n \/\/ (maybe from previous partitionings).\n MeshBase::node_iterator node_it = mesh.nodes_begin();\n const MeshBase::node_iterator node_end = mesh.nodes_end();\n \n for ( ; node_it != node_end; ++node_it)\n {\n Node *node = *node_it;\n assert(node);\n node->invalidate_processor_id();\n }\n \n \n \/\/ Loop over all the active elements\n MeshBase::element_iterator elem_it = mesh.active_elements_begin();\n const MeshBase::element_iterator elem_end = mesh.active_elements_end(); \n \n for ( ; elem_it != elem_end; ++elem_it)\n {\n Elem* elem = *elem_it;\n assert(elem);\n \n \/\/ For each node, set the processor ID to the min of\n \/\/ its current value and this Element's processor id.\n for (unsigned int n=0; nn_nodes(); ++n)\n\telem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),\n\t\t\t\t\t\t elem->processor_id());\n }\n\n \/\/ And loop over the subactive elements, but don't reassign\n \/\/ nodes that are already active on another processor.\n MeshBase::element_iterator sub_it = mesh.subactive_elements_begin();\n const MeshBase::element_iterator sub_end = mesh.subactive_elements_end(); \n \n for ( ; sub_it != sub_end; ++sub_it)\n {\n Elem* elem = *sub_it;\n assert(elem);\n \n for (unsigned int n=0; nn_nodes(); ++n)\n if (elem->get_node(n)->processor_id() == DofObject::invalid_processor_id)\n\t elem->get_node(n)->processor_id() = std::min(elem->get_node(n)->processor_id(),\n\t\t\t\t\t\t elem->processor_id());\n }\n\n \/\/ At this point, if we're in parallel, all our own processor ids\n \/\/ should be correct, but ghost nodes may be incorrect. However,\n \/\/ our tenative processor ids will let us know who to ask.\n\n \/\/ Loop over all the nodes, count the ones on each processor\n std::vector\n ghost_objects_from_proc(libMesh::n_processors(), 0);\n\n node_it = mesh.nodes_begin();\n for ( ; node_it != node_end; ++node_it)\n {\n Node *node = *node_it;\n assert(node);\n unsigned int obj_procid = node->processor_id();\n assert(obj_procid != DofObject::invalid_processor_id);\n ghost_objects_from_proc[obj_procid]++;\n }\n\n \/\/ Request sets to send to each processor\n std::vector >\n requested_ids(libMesh::n_processors());\n\n \/\/ We know how many objects live on each processor, so reserve()\n \/\/ space for each.\n for (unsigned int p=0; p != libMesh::n_processors(); ++p)\n if (p != libMesh::processor_id())\n requested_ids[p].reserve(ghost_objects_from_proc[p]);\n\n node_it = mesh.nodes_begin();\n for ( ; node_it != node_end; ++node_it)\n {\n Node *node = *node_it;\n requested_ids[node->processor_id()].push_back(node->id());\n }\n\n \/\/ Next set ghost object ids from other processors\n for (unsigned int p=1; p != libMesh::n_processors(); ++p)\n {\n \/\/ Trade my requests with processor procup and procdown\n unsigned int procup = (libMesh::processor_id() + p) %\n libMesh::n_processors();\n unsigned int procdown = (libMesh::n_processors() +\n libMesh::processor_id() - p) %\n libMesh::n_processors();\n std::vector request_to_fill;\n Parallel::send_receive(procup, requested_ids[procup],\n procdown, request_to_fill);\n\n \/\/ Fill those requests\n std::vector new_ids(request_to_fill.size());\n for (unsigned int i=0; i != request_to_fill.size(); ++i)\n {\n Node *node = mesh.node_ptr(request_to_fill[i]);\n assert(node);\n new_ids[i] = node->processor_id();\n }\n\n \/\/ Trade back the results\n std::vector filled_request;\n Parallel::send_receive(procdown, new_ids,\n procup, filled_request);\n assert(filled_request.size() == requested_ids[procup].size());\n \n \/\/ And copy the id changes we've now been informed of\n for (unsigned int i=0; i != filled_request.size(); ++i)\n {\n Node *node = mesh.node_ptr(requested_ids[procup][i]);\n assert(filled_request[i] < libMesh::n_processors());\n node->processor_id(filled_request[i]);\n }\n }\n}\n<|endoftext|>"} {"text":"#ifndef ENTT_SIGNAL_SIGH_HPP\n#define ENTT_SIGNAL_SIGH_HPP\n\n\n#include \n#include \n#include \n#include \n#include \n#include \"..\/config\/config.h\"\n#include \"delegate.hpp\"\n#include \"fwd.hpp\"\n\n\nnamespace entt {\n\n\n\/**\n * @brief Unmanaged signal handler declaration.\n *\n * Primary template isn't defined on purpose. All the specializations give a\n * compile-time error unless the template parameter is a function type.\n *\n * @tparam Function A valid function type.\n * @tparam Collector Type of collector to use, if any.\n *\/\ntemplate\nstruct sigh;\n\n\n\/**\n * @brief Sink implementation.\n *\n * Primary template isn't defined on purpose. All the specializations give a\n * compile-time error unless the template parameter is a function type.\n *\n * @tparam Function A valid function type.\n *\/\ntemplate\nclass sink;\n\n\n\/**\n * @brief Sink implementation.\n *\n * A sink is an opaque object used to connect listeners to signals.\n * The function type for a listener is the one of the signal to which it\n * belongs.\n *\n * The clear separation between a signal and a sink permits to store the former\n * as private data member without exposing the publish functionality to the\n * users of a class.\n *\n * @tparam Ret Return type of a function type.\n * @tparam Args Types of arguments of a function type.\n *\/\ntemplate\nclass sink {\n \/*! @brief A signal is allowed to create sinks. *\/\n template\n friend struct sigh;\n\n sink(std::vector> *ref) ENTT_NOEXCEPT\n : calls{ref}\n {}\n\npublic:\n \/**\n * @brief Returns false if at least a listener is connected to the sink.\n * @return True if the sink has no listeners connected, false otherwise.\n *\/\n bool empty() const ENTT_NOEXCEPT {\n return calls->empty();\n }\n\n \/**\n * @brief Connects a free function to a signal.\n *\n * The signal handler performs checks to avoid multiple connections for free\n * functions.\n *\n * @tparam Function A valid free function pointer.\n *\/\n template\n void connect() {\n disconnect();\n delegate delegate{};\n delegate.template connect();\n calls->emplace_back(std::move(delegate));\n }\n\n \/**\n * @brief Connects a member function or a free function with payload to a\n * signal.\n *\n * The signal isn't responsible for the connected object or the payload.\n * Users must always guarantee that the lifetime of the instance overcomes\n * the one of the delegate. On the other side, the signal handler performs\n * checks to avoid multiple connections for the same function.\n * When used to connect a free function with payload, its signature must be\n * such that the instance is the first argument before the ones used to\n * define the delegate itself.\n *\n * @tparam Candidate Member or free function to connect to the signal.\n * @tparam Type Type of class or type of payload.\n * @param value_or_instance A valid pointer that fits the purpose.\n *\/\n template\n void connect(Type *value_or_instance) {\n disconnect(value_or_instance);\n delegate delegate{};\n delegate.template connect(value_or_instance);\n calls->emplace_back(std::move(delegate));\n }\n\n \/**\n * @brief Disconnects a free function from a signal.\n * @tparam Function A valid free function pointer.\n *\/\n template\n void disconnect() {\n delegate delegate{};\n delegate.template connect();\n calls->erase(std::remove(calls->begin(), calls->end(), std::move(delegate)), calls->end());\n }\n\n \/**\n * @brief Disconnects a member function or a free function with payload from\n * a signal.\n * @tparam Candidate Member or free function to disconnect from the signal.\n * @tparam Type Type of class or type of payload.\n * @param value_or_instance A valid pointer that fits the purpose.\n *\/\n template\n void disconnect(Type *value_or_instance) {\n delegate delegate{};\n delegate.template connect(value_or_instance);\n calls->erase(std::remove_if(calls->begin(), calls->end(), [delegate](const auto &other) {\n return other == delegate && other.instance() == delegate.instance();\n }), calls->end());\n }\n\n \/**\n * @brief Disconnects member functions or free functions based on an\n * instance or specific payload.\n * @param value_or_instance A valid pointer that fits the purpose.\n *\/\n void disconnect(const void *value_or_instance) {\n calls->erase(std::remove_if(calls->begin(), calls->end(), [value_or_instance](const auto &delegate) {\n return value_or_instance == delegate.instance();\n }), calls->end());\n }\n\n \/*! @brief Disconnects all the listeners from a signal. *\/\n void disconnect() {\n calls->clear();\n }\n\nprivate:\n std::vector> *calls;\n};\n\n\n\/**\n * @brief Unmanaged signal handler definition.\n *\n * Unmanaged signal handler. It works directly with naked pointers to classes\n * and pointers to member functions as well as pointers to free functions. Users\n * of this class are in charge of disconnecting instances before deleting them.\n *\n * This class serves mainly two purposes:\n *\n * * Creating signals to use later to notify a bunch of listeners.\n * * Collecting results from a set of functions like in a voting system.\n *\n * @tparam Ret Return type of a function type.\n * @tparam Args Types of arguments of a function type.\n *\/\ntemplate\nstruct sigh {\n \/*! @brief Unsigned integer type. *\/\n using size_type = typename std::vector>::size_type;\n \/*! @brief Sink type. *\/\n using sink_type = entt::sink;\n\n \/**\n * @brief Instance type when it comes to connecting member functions.\n * @tparam Class Type of class to which the member function belongs.\n *\/\n template\n using instance_type = Class *;\n\n \/**\n * @brief Number of listeners connected to the signal.\n * @return Number of listeners currently connected.\n *\/\n size_type size() const ENTT_NOEXCEPT {\n return calls.size();\n }\n\n \/**\n * @brief Returns false if at least a listener is connected to the signal.\n * @return True if the signal has no listeners connected, false otherwise.\n *\/\n bool empty() const ENTT_NOEXCEPT {\n return calls.empty();\n }\n\n \/**\n * @brief Returns a sink object for the given signal.\n *\n * A sink is an opaque object used to connect listeners to signals.\n * The function type for a listener is the one of the signal to which it\n * belongs. The order of invocation of the listeners isn't guaranteed.\n *\n * @return A temporary sink object.\n *\/\n sink_type sink() ENTT_NOEXCEPT {\n return { &calls };\n }\n\n \/**\n * @brief Triggers a signal.\n *\n * All the listeners are notified. Order isn't guaranteed.\n *\n * @param args Arguments to use to invoke listeners.\n *\/\n void publish(Args... args) const {\n for(auto pos = calls.size(); pos; --pos) {\n calls[pos-1](args...);\n }\n }\n\n \/**\n * @brief Collects return values from the listeners.\n *\n * The collector must expose a call operator with the following properties:\n *\n * * The return type is either `void` or such that it's convertible to\n * `bool`. In the second case, a true value will stop the iteration.\n * * The list of parameters is empty if `Ret` is `void`, otherwise it\n * contains a single element such that `Ret` is convertible to it.\n *\n * @tparam Func Type of collector to use, if any.\n * @param func A valid function object.\n * @param args Arguments to use to invoke listeners.\n *\/\n template\n void collect(Func func, Args... args) const {\n bool stop = false;\n\n for(auto pos = calls.size(); pos && !stop; --pos) {\n if constexpr(std::is_void_v) {\n if constexpr(std::is_invocable_r_v) {\n calls[pos-1](args...);\n stop = func();\n } else {\n calls[pos-1](args...);\n func();\n }\n } else {\n if constexpr(std::is_invocable_r_v) {\n stop = func(calls[pos-1](args...));\n } else {\n func(calls[pos-1](args...));\n }\n }\n }\n }\n\n \/**\n * @brief Swaps listeners between the two signals.\n * @param lhs A valid signal object.\n * @param rhs A valid signal object.\n *\/\n friend void swap(sigh &lhs, sigh &rhs) {\n using std::swap;\n swap(lhs.calls, rhs.calls);\n }\n\nprivate:\n std::vector> calls;\n};\n\n\n}\n\n\n#endif \/\/ ENTT_SIGNAL_SIGH_HPP\ncleanup#ifndef ENTT_SIGNAL_SIGH_HPP\n#define ENTT_SIGNAL_SIGH_HPP\n\n\n#include \n#include \n#include \n#include \n#include \n#include \"..\/config\/config.h\"\n#include \"delegate.hpp\"\n#include \"fwd.hpp\"\n\n\nnamespace entt {\n\n\n\/**\n * @brief Unmanaged signal handler declaration.\n *\n * Primary template isn't defined on purpose. All the specializations give a\n * compile-time error unless the template parameter is a function type.\n *\n * @tparam Function A valid function type.\n *\/\ntemplate\nstruct sigh;\n\n\n\/**\n * @brief Sink implementation.\n *\n * Primary template isn't defined on purpose. All the specializations give a\n * compile-time error unless the template parameter is a function type.\n *\n * @tparam Function A valid function type.\n *\/\ntemplate\nclass sink;\n\n\n\/**\n * @brief Sink implementation.\n *\n * A sink is an opaque object used to connect listeners to signals.\n * The function type for a listener is the one of the signal to which it\n * belongs.\n *\n * The clear separation between a signal and a sink permits to store the former\n * as private data member without exposing the publish functionality to the\n * users of a class.\n *\n * @tparam Ret Return type of a function type.\n * @tparam Args Types of arguments of a function type.\n *\/\ntemplate\nclass sink {\n \/*! @brief A signal is allowed to create sinks. *\/\n template\n friend struct sigh;\n\n sink(std::vector> *ref) ENTT_NOEXCEPT\n : calls{ref}\n {}\n\npublic:\n \/**\n * @brief Returns false if at least a listener is connected to the sink.\n * @return True if the sink has no listeners connected, false otherwise.\n *\/\n bool empty() const ENTT_NOEXCEPT {\n return calls->empty();\n }\n\n \/**\n * @brief Connects a free function to a signal.\n *\n * The signal handler performs checks to avoid multiple connections for free\n * functions.\n *\n * @tparam Function A valid free function pointer.\n *\/\n template\n void connect() {\n disconnect();\n delegate delegate{};\n delegate.template connect();\n calls->emplace_back(std::move(delegate));\n }\n\n \/**\n * @brief Connects a member function or a free function with payload to a\n * signal.\n *\n * The signal isn't responsible for the connected object or the payload.\n * Users must always guarantee that the lifetime of the instance overcomes\n * the one of the delegate. On the other side, the signal handler performs\n * checks to avoid multiple connections for the same function.\n * When used to connect a free function with payload, its signature must be\n * such that the instance is the first argument before the ones used to\n * define the delegate itself.\n *\n * @tparam Candidate Member or free function to connect to the signal.\n * @tparam Type Type of class or type of payload.\n * @param value_or_instance A valid pointer that fits the purpose.\n *\/\n template\n void connect(Type *value_or_instance) {\n disconnect(value_or_instance);\n delegate delegate{};\n delegate.template connect(value_or_instance);\n calls->emplace_back(std::move(delegate));\n }\n\n \/**\n * @brief Disconnects a free function from a signal.\n * @tparam Function A valid free function pointer.\n *\/\n template\n void disconnect() {\n delegate delegate{};\n delegate.template connect();\n calls->erase(std::remove(calls->begin(), calls->end(), std::move(delegate)), calls->end());\n }\n\n \/**\n * @brief Disconnects a member function or a free function with payload from\n * a signal.\n * @tparam Candidate Member or free function to disconnect from the signal.\n * @tparam Type Type of class or type of payload.\n * @param value_or_instance A valid pointer that fits the purpose.\n *\/\n template\n void disconnect(Type *value_or_instance) {\n delegate delegate{};\n delegate.template connect(value_or_instance);\n calls->erase(std::remove_if(calls->begin(), calls->end(), [delegate](const auto &other) {\n return other == delegate && other.instance() == delegate.instance();\n }), calls->end());\n }\n\n \/**\n * @brief Disconnects member functions or free functions based on an\n * instance or specific payload.\n * @param value_or_instance A valid pointer that fits the purpose.\n *\/\n void disconnect(const void *value_or_instance) {\n calls->erase(std::remove_if(calls->begin(), calls->end(), [value_or_instance](const auto &delegate) {\n return value_or_instance == delegate.instance();\n }), calls->end());\n }\n\n \/*! @brief Disconnects all the listeners from a signal. *\/\n void disconnect() {\n calls->clear();\n }\n\nprivate:\n std::vector> *calls;\n};\n\n\n\/**\n * @brief Unmanaged signal handler definition.\n *\n * Unmanaged signal handler. It works directly with naked pointers to classes\n * and pointers to member functions as well as pointers to free functions. Users\n * of this class are in charge of disconnecting instances before deleting them.\n *\n * This class serves mainly two purposes:\n *\n * * Creating signals to use later to notify a bunch of listeners.\n * * Collecting results from a set of functions like in a voting system.\n *\n * @tparam Ret Return type of a function type.\n * @tparam Args Types of arguments of a function type.\n *\/\ntemplate\nstruct sigh {\n \/*! @brief Unsigned integer type. *\/\n using size_type = typename std::vector>::size_type;\n \/*! @brief Sink type. *\/\n using sink_type = entt::sink;\n\n \/**\n * @brief Instance type when it comes to connecting member functions.\n * @tparam Class Type of class to which the member function belongs.\n *\/\n template\n using instance_type = Class *;\n\n \/**\n * @brief Number of listeners connected to the signal.\n * @return Number of listeners currently connected.\n *\/\n size_type size() const ENTT_NOEXCEPT {\n return calls.size();\n }\n\n \/**\n * @brief Returns false if at least a listener is connected to the signal.\n * @return True if the signal has no listeners connected, false otherwise.\n *\/\n bool empty() const ENTT_NOEXCEPT {\n return calls.empty();\n }\n\n \/**\n * @brief Returns a sink object for the given signal.\n *\n * A sink is an opaque object used to connect listeners to signals.\n * The function type for a listener is the one of the signal to which it\n * belongs. The order of invocation of the listeners isn't guaranteed.\n *\n * @return A temporary sink object.\n *\/\n sink_type sink() ENTT_NOEXCEPT {\n return { &calls };\n }\n\n \/**\n * @brief Triggers a signal.\n *\n * All the listeners are notified. Order isn't guaranteed.\n *\n * @param args Arguments to use to invoke listeners.\n *\/\n void publish(Args... args) const {\n for(auto pos = calls.size(); pos; --pos) {\n calls[pos-1](args...);\n }\n }\n\n \/**\n * @brief Collects return values from the listeners.\n *\n * The collector must expose a call operator with the following properties:\n *\n * * The return type is either `void` or such that it's convertible to\n * `bool`. In the second case, a true value will stop the iteration.\n * * The list of parameters is empty if `Ret` is `void`, otherwise it\n * contains a single element such that `Ret` is convertible to it.\n *\n * @tparam Func Type of collector to use, if any.\n * @param func A valid function object.\n * @param args Arguments to use to invoke listeners.\n *\/\n template\n void collect(Func func, Args... args) const {\n bool stop = false;\n\n for(auto pos = calls.size(); pos && !stop; --pos) {\n if constexpr(std::is_void_v) {\n if constexpr(std::is_invocable_r_v) {\n calls[pos-1](args...);\n stop = func();\n } else {\n calls[pos-1](args...);\n func();\n }\n } else {\n if constexpr(std::is_invocable_r_v) {\n stop = func(calls[pos-1](args...));\n } else {\n func(calls[pos-1](args...));\n }\n }\n }\n }\n\n \/**\n * @brief Swaps listeners between the two signals.\n * @param lhs A valid signal object.\n * @param rhs A valid signal object.\n *\/\n friend void swap(sigh &lhs, sigh &rhs) {\n using std::swap;\n swap(lhs.calls, rhs.calls);\n }\n\nprivate:\n std::vector> calls;\n};\n\n\n}\n\n\n#endif \/\/ ENTT_SIGNAL_SIGH_HPP\n<|endoftext|>"} {"text":"\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n \n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\nstatic char *_FileName_ = __FILE__;\n\nstatic struct hostent *host_ptr = NULL;\nstatic char hostname[MAXHOSTNAMELEN];\nstatic char full_hostname[MAXHOSTNAMELEN];\nstatic unsigned int ip_addr;\nstatic int hostnames_initialized = 0;\nstatic void init_hostnames();\n\n\/\/ Return our hostname in a static data buffer.\nchar *\nmy_hostname()\n{\n\tif( ! hostnames_initialized ) {\n\t\tinit_hostnames();\n\t}\n\treturn hostname;\n}\n\n\n\/\/ Return our full hostname (with domain) in a static data buffer.\nchar*\nmy_full_hostname()\n{\n\tif( ! hostnames_initialized ) {\n\t\tinit_hostnames();\n\t}\n\treturn full_hostname;\n}\n\n\n\/\/ Return the host-ordered, unsigned int version of our hostname.\nunsigned int\nmy_ip_addr()\n{\n\tif( ! hostnames_initialized ) {\n\t\tinit_hostnames();\n\t}\n\treturn ip_addr;\n}\n\n\nvoid\ninit_hostnames()\n{\n\tchar* tmp;\n\n\t\t\/\/ Get our local hostname, and strip off the domain if\n\t\t\/\/ gethostname returns it.\n\tif( gethostname(hostname, sizeof(hostname)) == 0 ) {\n\t\ttmp = strchr( hostname, '.' );\n\t\tif( tmp ) {\n\t\t\t*tmp = '\\0';\n\t\t}\n\t} else {\n\t\tEXCEPT( \"gethostname failed, errno = %d\", \n#ifndef WIN32\n\t\t\terrno );\n#else\n\t\t\tWSAGetLastError() );\n#endif\n\t}\n\n\t\t\/\/ Look up our official host information\n\tif( (host_ptr = gethostbyname(hostname)) == NULL ) {\n\t\tEXCEPT( \"gethostbyname(%s) failed, errno = %d\", hostname, errno );\n\t}\n\n\t\t\/\/ Grab our ip_addr and fully qualified hostname\n\tmemcpy( &ip_addr, host_ptr->h_addr, (size_t)host_ptr->h_length );\n\tip_addr = ntohl( ip_addr );\n\n\tstrcpy( full_hostname, host_ptr->h_name );\n\t\n\thostnames_initialized = TRUE;\n}\n\n+ We now malloc the space we need instead of using fixed length buffers. + We're much smarter about finding my_full_hostname, even in the face of misconfigured machines. If it's not where it should be, we search through the host aliases, and even call res_init() to find the default domain name that the resolver thinks it should use. Ideally, we'd do an inverse query to DNS to be sure.\/***************************Copyright-DO-NOT-REMOVE-THIS-LINE**\n * CONDOR Copyright Notice\n *\n * See LICENSE.TXT for additional notices and disclaimers.\n *\n * Copyright (c)1990-1998 CONDOR Team, Computer Sciences Department, \n * University of Wisconsin-Madison, Madison, WI. All Rights Reserved. \n * No use of the CONDOR Software Program Source Code is authorized \n * without the express consent of the CONDOR Team. For more information \n * contact: CONDOR Team, Attention: Professor Miron Livny, \n * 7367 Computer Sciences, 1210 W. Dayton St., Madison, WI 53706-1685, \n * (608) 262-0856 or miron@cs.wisc.edu.\n *\n * U.S. Government Rights Restrictions: Use, duplication, or disclosure \n * by the U.S. Government is subject to restrictions as set forth in \n * subparagraph (c)(1)(ii) of The Rights in Technical Data and Computer \n * Software clause at DFARS 252.227-7013 or subparagraphs (c)(1) and \n * (2) of Commercial Computer Software-Restricted Rights at 48 CFR \n * 52.227-19, as applicable, CONDOR Team, Attention: Professor Miron \n * Livny, 7367 Computer Sciences, 1210 W. Dayton St., Madison, \n * WI 53706-1685, (608) 262-0856 or miron@cs.wisc.edu.\n****************************Copyright-DO-NOT-REMOVE-THIS-LINE**\/\n\n \n\n#include \"condor_common.h\"\n#include \"condor_debug.h\"\nstatic char *_FileName_ = __FILE__;\n\nstatic struct hostent *host_ptr = NULL;\nstatic char* hostname = NULL;\nstatic char* full_hostname = NULL;\nstatic unsigned int ip_addr;\nstatic int hostnames_initialized = 0;\nstatic void init_hostnames();\n\nextern \"C\" {\n\n\/\/ Return our hostname in a static data buffer.\nchar *\nmy_hostname()\n{\n\tif( ! hostnames_initialized ) {\n\t\tinit_hostnames();\n\t}\n\treturn hostname;\n}\n\n\n\/\/ Return our full hostname (with domain) in a static data buffer.\nchar*\nmy_full_hostname()\n{\n\tif( ! hostnames_initialized ) {\n\t\tinit_hostnames();\n\t}\n\treturn full_hostname;\n}\n\n\n\/\/ Return the host-ordered, unsigned int version of our hostname.\nunsigned int\nmy_ip_addr()\n{\n\tif( ! hostnames_initialized ) {\n\t\tinit_hostnames();\n\t}\n\treturn ip_addr;\n}\n\n} \/* extern \"C\" *\/\n\n#if !defined(WIN32)\n#include \n#include \n#endif\n\nvoid\ninit_hostnames()\n{\n\tchar *tmp, hostbuf[MAXHOSTNAMELEN];\n\tint i;\n\n\tif( hostname ) {\n\t\tfree( hostname );\n\t}\n\tif( full_hostname ) {\n\t\tfree( full_hostname );\n\t\tfull_hostname = NULL;\n\t}\n\n\t\t\/\/ Get our local hostname, and strip off the domain if\n\t\t\/\/ gethostname returns it.\n\tif( gethostname(hostbuf, sizeof(hostbuf)) == 0 ) {\n\t\tif( (tmp = strchr(hostbuf, '.')) ) {\n\t\t\t\t\/\/ There's a '.' in the hostname, assume we've got the\n\t\t\t\t\/\/ full hostname here, save it, and trim the domain\n\t\t\t\t\/\/ off and save that as the hostname.\n\t\t\tfull_hostname = strdup( hostbuf );\n\t\t\t*tmp = '\\0';\n\t\t}\n\t\thostname = strdup( hostbuf );\n\t} else {\n\t\tEXCEPT( \"gethostname failed, errno = %d\", \n#ifndef WIN32\n\t\t\t\terrno );\n#else\n\t\tWSAGetLastError() );\n#endif\n }\n\t\n\t\t\/\/ Look up our official host information\n\tif( (host_ptr = gethostbyname(hostbuf)) == NULL ) {\n\t\tEXCEPT( \"gethostbyname(%s) failed, errno = %d\", hostbuf, errno );\n\t}\n\n\t\t\/\/ Grab our ip_addr\n\tmemcpy( &ip_addr, host_ptr->h_addr, (size_t)host_ptr->h_length );\n ip_addr = ntohl( ip_addr );\n\n\t \/\/ If we don't have our full_hostname yet, try to find it. \n\tif( ! full_hostname ) {\n\t\t\t\/\/ See if it's correct in the hostent we've got.\n\t\tif( (tmp = strchr(host_ptr->h_name, '.')) ) {\n\t\t\t\t\/\/ There's a '.' in the \"name\", use that as full.\n\t\t\tfull_hostname = strdup( host_ptr->h_name );\n\t\t}\n\t}\n\n\tif( ! full_hostname ) {\n\t\t\t\/\/ We still haven't found it yet, try all the aliases\n\t\t\t\/\/ until we find one with a '.'\n\t\tfor( i=0; host_ptr->h_aliases[i], !full_hostname; i++ ) {\n\t\t\tif( (tmp = strchr(host_ptr->h_aliases[i], '.')) ) { \n\t\t\t\tfull_hostname = strdup( host_ptr->h_aliases[i] );\n\t\t\t}\n\t\t}\n\t}\n\n#if !defined( WIN32 ) \/* I'm not sure how to do this on NT *\/\n\tif( ! full_hostname ) {\n\t\t\t\/\/ We still haven't found it yet, try to use the\n\t\t\t\/\/ resolver. *sigh*\n\t\tres_init();\n\t\tif( _res.defdname ) {\n\t\t\t\t\/\/ We know our default domain name, append that.\n\t\t\tstrcat( hostbuf, \".\" );\n\t\t\tstrcat( hostbuf, _res.defdname );\n\t\t\tfull_hostname = strdup( hostbuf );\n\t\t}\n\t}\n#endif \/* WIN32 *\/\n\tif( ! full_hostname ) {\n\t\t\t\/\/ Still can't find it, just give up.\n\t\tfull_hostname = strdup( hostname );\n\t}\n\n\thostnames_initialized = TRUE;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/base\/platform_thread.h\"\n\n#include \"webrtc\/base\/atomicops.h\"\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/base\/timeutils.h\"\n#include \"webrtc\/base\/trace_event.h\"\n\n#if defined(WEBRTC_LINUX)\n#include \n#include \n#endif\n\nnamespace rtc {\n\nPlatformThreadId CurrentThreadId() {\n PlatformThreadId ret;\n#if defined(WEBRTC_WIN)\n ret = GetCurrentThreadId();\n#elif defined(WEBRTC_POSIX)\n#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)\n ret = pthread_mach_thread_np(pthread_self());\n#elif defined(WEBRTC_LINUX)\n ret = syscall(__NR_gettid);\n#elif defined(WEBRTC_ANDROID)\n ret = gettid();\n#else\n \/\/ Default implementation for nacl and solaris.\n ret = reinterpret_cast(pthread_self());\n#endif\n#endif \/\/ defined(WEBRTC_POSIX)\n RTC_DCHECK(ret);\n return ret;\n}\n\nPlatformThreadRef CurrentThreadRef() {\n#if defined(WEBRTC_WIN)\n return GetCurrentThreadId();\n#elif defined(WEBRTC_POSIX)\n return pthread_self();\n#endif\n}\n\nbool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {\n#if defined(WEBRTC_WIN)\n return a == b;\n#elif defined(WEBRTC_POSIX)\n return pthread_equal(a, b);\n#endif\n}\n\nvoid SetCurrentThreadName(const char* name) {\n#if defined(WEBRTC_WIN)\n struct {\n DWORD dwType;\n LPCSTR szName;\n DWORD dwThreadID;\n DWORD dwFlags;\n } threadname_info = {0x1000, name, static_cast(-1), 0};\n\n __try {\n ::RaiseException(0x406D1388, 0, sizeof(threadname_info) \/ sizeof(DWORD),\n reinterpret_cast(&threadname_info));\n } __except (EXCEPTION_EXECUTE_HANDLER) {\n }\n#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)\n prctl(PR_SET_NAME, reinterpret_cast(name));\n#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)\n pthread_setname_np(name);\n#endif\n}\n\nnamespace {\n#if defined(WEBRTC_WIN)\nvoid CALLBACK RaiseFlag(ULONG_PTR param) {\n *reinterpret_cast(param) = true;\n}\n#else\nstruct ThreadAttributes {\n ThreadAttributes() { pthread_attr_init(&attr); }\n ~ThreadAttributes() { pthread_attr_destroy(&attr); }\n pthread_attr_t* operator&() { return &attr; }\n pthread_attr_t attr;\n};\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nPlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,\n void* obj,\n const char* thread_name)\n : run_function_deprecated_(func),\n obj_(obj),\n name_(thread_name ? thread_name : \"webrtc\") {\n RTC_DCHECK(func);\n RTC_DCHECK(name_.length() < 64);\n spawned_thread_checker_.DetachFromThread();\n}\n\nPlatformThread::PlatformThread(ThreadRunFunction func,\n void* obj,\n const char* thread_name,\n ThreadPriority priority \/*= kNormalPriority*\/)\n : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {\n RTC_DCHECK(func);\n RTC_DCHECK(!name_.empty());\n \/\/ TODO(tommi): Consider lowering the limit to 15 (limit on Linux).\n RTC_DCHECK(name_.length() < 64);\n spawned_thread_checker_.DetachFromThread();\n}\n\nPlatformThread::~PlatformThread() {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n#if defined(WEBRTC_WIN)\n RTC_DCHECK(!thread_);\n RTC_DCHECK(!thread_id_);\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\n#if defined(WEBRTC_WIN)\nDWORD WINAPI PlatformThread::StartThread(void* param) {\n \/\/ The GetLastError() function only returns valid results when it is called\n \/\/ after a Win32 API function that returns a \"failed\" result. A crash dump\n \/\/ contains the result from GetLastError() and to make sure it does not\n \/\/ falsely report a Windows error we call SetLastError here.\n ::SetLastError(ERROR_SUCCESS);\n static_cast(param)->Run();\n return 0;\n}\n#else\nvoid* PlatformThread::StartThread(void* param) {\n static_cast(param)->Run();\n return 0;\n}\n#endif \/\/ defined(WEBRTC_WIN)\n\nvoid PlatformThread::Start() {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n RTC_DCHECK(!thread_) << \"Thread already started?\";\n#if defined(WEBRTC_WIN)\n stop_ = false;\n\n \/\/ See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.\n \/\/ Set the reserved stack stack size to 1M, which is the default on Windows\n \/\/ and Linux.\n thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,\n STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);\n RTC_CHECK(thread_) << \"CreateThread failed\";\n RTC_DCHECK(thread_id_);\n#else\n ThreadAttributes attr;\n \/\/ Set the stack stack size to 1M.\n pthread_attr_setstacksize(&attr, 1024 * 1024);\n RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nbool PlatformThread::IsRunning() const {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n#if defined(WEBRTC_WIN)\n return thread_ != nullptr;\n#else\n return thread_ != 0;\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nPlatformThreadRef PlatformThread::GetThreadRef() const {\n#if defined(WEBRTC_WIN)\n return thread_id_;\n#else\n return thread_;\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nvoid PlatformThread::Stop() {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n if (!IsRunning())\n return;\n\n#if defined(WEBRTC_WIN)\n \/\/ Set stop_ to |true| on the worker thread.\n bool queued = QueueAPC(&RaiseFlag, reinterpret_cast(&stop_));\n \/\/ Queuing the APC can fail if the thread is being terminated.\n RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);\n WaitForSingleObject(thread_, INFINITE);\n CloseHandle(thread_);\n thread_ = nullptr;\n thread_id_ = 0;\n#else\n if (!run_function_)\n RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));\n RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));\n if (!run_function_)\n AtomicOps::ReleaseStore(&stop_flag_, 0);\n thread_ = 0;\n#endif \/\/ defined(WEBRTC_WIN)\n spawned_thread_checker_.DetachFromThread();\n}\n\n\/\/ TODO(tommi): Deprecate the loop behavior in PlatformThread.\n\/\/ * Introduce a new callback type that returns void.\n\/\/ * Remove potential for a busy loop in PlatformThread.\n\/\/ * Delegate the responsibility for how to stop the thread, to the\n\/\/ implementation that actually uses the thread.\n\/\/ All implementations will need to be aware of how the thread should be stopped\n\/\/ and encouraging a busy polling loop, can be costly in terms of power and cpu.\nvoid PlatformThread::Run() {\n \/\/ Attach the worker thread checker to this thread.\n RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());\n rtc::SetCurrentThreadName(name_.c_str());\n\n if (run_function_) {\n SetPriority(priority_);\n run_function_(obj_);\n return;\n }\n\n\/\/ TODO(tommi): Delete the rest of this function when looping isn't supported.\n#if RTC_DCHECK_IS_ON\n \/\/ These constants control the busy loop detection algorithm below.\n \/\/ |kMaxLoopCount| controls the limit for how many times we allow the loop\n \/\/ to run within a period, before DCHECKing.\n \/\/ |kPeriodToMeasureMs| controls how long that period is.\n static const int kMaxLoopCount = 1000;\n static const int kPeriodToMeasureMs = 100;\n int64_t loop_stamps[kMaxLoopCount] = {};\n int64_t sequence_nr = 0;\n#endif\n\n do {\n TRACE_EVENT1(\"webrtc\", \"PlatformThread::Run\", \"name\", name_.c_str());\n\n \/\/ The interface contract of Start\/Stop is that for a successful call to\n \/\/ Start, there should be at least one call to the run function. So we\n \/\/ call the function before checking |stop_|.\n if (!run_function_deprecated_(obj_))\n break;\n#if RTC_DCHECK_IS_ON\n auto id = sequence_nr % kMaxLoopCount;\n loop_stamps[id] = rtc::TimeMillis();\n if (sequence_nr > kMaxLoopCount) {\n auto compare_id = (id + 1) % kMaxLoopCount;\n auto diff = loop_stamps[id] - loop_stamps[compare_id];\n RTC_DCHECK_GE(diff, 0);\n if (diff < kPeriodToMeasureMs) {\n RTC_NOTREACHED() << \"This thread is too busy: \" << name_ << \" \" << diff\n << \"ms sequence=\" << sequence_nr << \" \"\n << loop_stamps[id] << \" vs \" << loop_stamps[compare_id]\n << \", \" << id << \" vs \" << compare_id;\n }\n }\n ++sequence_nr;\n#endif\n#if defined(WEBRTC_WIN)\n \/\/ Alertable sleep to permit RaiseFlag to run and update |stop_|.\n SleepEx(0, true);\n } while (!stop_);\n#else\n#if defined(WEBRTC_MAC)\n sched_yield();\n#else\n static const struct timespec ts_null = {0};\n nanosleep(&ts_null, nullptr);\n#endif\n } while (!AtomicOps::AcquireLoad(&stop_flag_));\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nbool PlatformThread::SetPriority(ThreadPriority priority) {\n#if RTC_DCHECK_IS_ON\n if (run_function_) {\n \/\/ The non-deprecated way of how this function gets called, is that it must\n \/\/ be called on the worker thread itself.\n RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());\n } else {\n \/\/ In the case of deprecated use of this method, it must be called on the\n \/\/ same thread as the PlatformThread object is constructed on.\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n RTC_DCHECK(IsRunning());\n }\n#endif\n\n#if defined(WEBRTC_WIN)\n return SetThreadPriority(thread_, priority) != FALSE;\n#elif defined(__native_client__)\n \/\/ Setting thread priorities is not supported in NaCl.\n return true;\n#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)\n \/\/ TODO(tommi): Switch to the same mechanism as Chromium uses for changing\n \/\/ thread priorities.\n return true;\n#else\n#ifdef WEBRTC_THREAD_RR\n const int policy = SCHED_RR;\n#else\n const int policy = SCHED_FIFO;\n#endif\n const int min_prio = sched_get_priority_min(policy);\n const int max_prio = sched_get_priority_max(policy);\n if (min_prio == -1 || max_prio == -1) {\n return false;\n }\n\n if (max_prio - min_prio <= 2)\n return false;\n\n \/\/ Convert webrtc priority to system priorities:\n sched_param param;\n const int top_prio = max_prio - 1;\n const int low_prio = min_prio + 1;\n switch (priority) {\n case kLowPriority:\n param.sched_priority = low_prio;\n break;\n case kNormalPriority:\n \/\/ The -1 ensures that the kHighPriority is always greater or equal to\n \/\/ kNormalPriority.\n param.sched_priority = (low_prio + top_prio - 1) \/ 2;\n break;\n case kHighPriority:\n param.sched_priority = std::max(top_prio - 2, low_prio);\n break;\n case kHighestPriority:\n param.sched_priority = std::max(top_prio - 1, low_prio);\n break;\n case kRealtimePriority:\n param.sched_priority = top_prio;\n break;\n }\n return pthread_setschedparam(thread_, policy, ¶m) == 0;\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\n#if defined(WEBRTC_WIN)\nbool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n RTC_DCHECK(IsRunning());\n\n return QueueUserAPC(function, thread_, data) != FALSE;\n}\n#endif\n\n} \/\/ namespace rtc\nAdd a missing DCHECK to PlatformThread::SetPriority. This DCHECK is for the 'new and improved' way of setting thread priority. What could happen is that code that's migrating over to the new method might still have a lingering SetPriority call, that could incorrectly bind the 'spawned_thread_checker_' to the construction thread.\/*\n * Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"webrtc\/base\/platform_thread.h\"\n\n#include \"webrtc\/base\/atomicops.h\"\n#include \"webrtc\/base\/checks.h\"\n#include \"webrtc\/base\/timeutils.h\"\n#include \"webrtc\/base\/trace_event.h\"\n\n#if defined(WEBRTC_LINUX)\n#include \n#include \n#endif\n\nnamespace rtc {\n\nPlatformThreadId CurrentThreadId() {\n PlatformThreadId ret;\n#if defined(WEBRTC_WIN)\n ret = GetCurrentThreadId();\n#elif defined(WEBRTC_POSIX)\n#if defined(WEBRTC_MAC) || defined(WEBRTC_IOS)\n ret = pthread_mach_thread_np(pthread_self());\n#elif defined(WEBRTC_LINUX)\n ret = syscall(__NR_gettid);\n#elif defined(WEBRTC_ANDROID)\n ret = gettid();\n#else\n \/\/ Default implementation for nacl and solaris.\n ret = reinterpret_cast(pthread_self());\n#endif\n#endif \/\/ defined(WEBRTC_POSIX)\n RTC_DCHECK(ret);\n return ret;\n}\n\nPlatformThreadRef CurrentThreadRef() {\n#if defined(WEBRTC_WIN)\n return GetCurrentThreadId();\n#elif defined(WEBRTC_POSIX)\n return pthread_self();\n#endif\n}\n\nbool IsThreadRefEqual(const PlatformThreadRef& a, const PlatformThreadRef& b) {\n#if defined(WEBRTC_WIN)\n return a == b;\n#elif defined(WEBRTC_POSIX)\n return pthread_equal(a, b);\n#endif\n}\n\nvoid SetCurrentThreadName(const char* name) {\n#if defined(WEBRTC_WIN)\n struct {\n DWORD dwType;\n LPCSTR szName;\n DWORD dwThreadID;\n DWORD dwFlags;\n } threadname_info = {0x1000, name, static_cast(-1), 0};\n\n __try {\n ::RaiseException(0x406D1388, 0, sizeof(threadname_info) \/ sizeof(DWORD),\n reinterpret_cast(&threadname_info));\n } __except (EXCEPTION_EXECUTE_HANDLER) {\n }\n#elif defined(WEBRTC_LINUX) || defined(WEBRTC_ANDROID)\n prctl(PR_SET_NAME, reinterpret_cast(name));\n#elif defined(WEBRTC_MAC) || defined(WEBRTC_IOS)\n pthread_setname_np(name);\n#endif\n}\n\nnamespace {\n#if defined(WEBRTC_WIN)\nvoid CALLBACK RaiseFlag(ULONG_PTR param) {\n *reinterpret_cast(param) = true;\n}\n#else\nstruct ThreadAttributes {\n ThreadAttributes() { pthread_attr_init(&attr); }\n ~ThreadAttributes() { pthread_attr_destroy(&attr); }\n pthread_attr_t* operator&() { return &attr; }\n pthread_attr_t attr;\n};\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nPlatformThread::PlatformThread(ThreadRunFunctionDeprecated func,\n void* obj,\n const char* thread_name)\n : run_function_deprecated_(func),\n obj_(obj),\n name_(thread_name ? thread_name : \"webrtc\") {\n RTC_DCHECK(func);\n RTC_DCHECK(name_.length() < 64);\n spawned_thread_checker_.DetachFromThread();\n}\n\nPlatformThread::PlatformThread(ThreadRunFunction func,\n void* obj,\n const char* thread_name,\n ThreadPriority priority \/*= kNormalPriority*\/)\n : run_function_(func), priority_(priority), obj_(obj), name_(thread_name) {\n RTC_DCHECK(func);\n RTC_DCHECK(!name_.empty());\n \/\/ TODO(tommi): Consider lowering the limit to 15 (limit on Linux).\n RTC_DCHECK(name_.length() < 64);\n spawned_thread_checker_.DetachFromThread();\n}\n\nPlatformThread::~PlatformThread() {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n#if defined(WEBRTC_WIN)\n RTC_DCHECK(!thread_);\n RTC_DCHECK(!thread_id_);\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\n#if defined(WEBRTC_WIN)\nDWORD WINAPI PlatformThread::StartThread(void* param) {\n \/\/ The GetLastError() function only returns valid results when it is called\n \/\/ after a Win32 API function that returns a \"failed\" result. A crash dump\n \/\/ contains the result from GetLastError() and to make sure it does not\n \/\/ falsely report a Windows error we call SetLastError here.\n ::SetLastError(ERROR_SUCCESS);\n static_cast(param)->Run();\n return 0;\n}\n#else\nvoid* PlatformThread::StartThread(void* param) {\n static_cast(param)->Run();\n return 0;\n}\n#endif \/\/ defined(WEBRTC_WIN)\n\nvoid PlatformThread::Start() {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n RTC_DCHECK(!thread_) << \"Thread already started?\";\n#if defined(WEBRTC_WIN)\n stop_ = false;\n\n \/\/ See bug 2902 for background on STACK_SIZE_PARAM_IS_A_RESERVATION.\n \/\/ Set the reserved stack stack size to 1M, which is the default on Windows\n \/\/ and Linux.\n thread_ = ::CreateThread(nullptr, 1024 * 1024, &StartThread, this,\n STACK_SIZE_PARAM_IS_A_RESERVATION, &thread_id_);\n RTC_CHECK(thread_) << \"CreateThread failed\";\n RTC_DCHECK(thread_id_);\n#else\n ThreadAttributes attr;\n \/\/ Set the stack stack size to 1M.\n pthread_attr_setstacksize(&attr, 1024 * 1024);\n RTC_CHECK_EQ(0, pthread_create(&thread_, &attr, &StartThread, this));\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nbool PlatformThread::IsRunning() const {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n#if defined(WEBRTC_WIN)\n return thread_ != nullptr;\n#else\n return thread_ != 0;\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nPlatformThreadRef PlatformThread::GetThreadRef() const {\n#if defined(WEBRTC_WIN)\n return thread_id_;\n#else\n return thread_;\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nvoid PlatformThread::Stop() {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n if (!IsRunning())\n return;\n\n#if defined(WEBRTC_WIN)\n \/\/ Set stop_ to |true| on the worker thread.\n bool queued = QueueAPC(&RaiseFlag, reinterpret_cast(&stop_));\n \/\/ Queuing the APC can fail if the thread is being terminated.\n RTC_CHECK(queued || GetLastError() == ERROR_GEN_FAILURE);\n WaitForSingleObject(thread_, INFINITE);\n CloseHandle(thread_);\n thread_ = nullptr;\n thread_id_ = 0;\n#else\n if (!run_function_)\n RTC_CHECK_EQ(1, AtomicOps::Increment(&stop_flag_));\n RTC_CHECK_EQ(0, pthread_join(thread_, nullptr));\n if (!run_function_)\n AtomicOps::ReleaseStore(&stop_flag_, 0);\n thread_ = 0;\n#endif \/\/ defined(WEBRTC_WIN)\n spawned_thread_checker_.DetachFromThread();\n}\n\n\/\/ TODO(tommi): Deprecate the loop behavior in PlatformThread.\n\/\/ * Introduce a new callback type that returns void.\n\/\/ * Remove potential for a busy loop in PlatformThread.\n\/\/ * Delegate the responsibility for how to stop the thread, to the\n\/\/ implementation that actually uses the thread.\n\/\/ All implementations will need to be aware of how the thread should be stopped\n\/\/ and encouraging a busy polling loop, can be costly in terms of power and cpu.\nvoid PlatformThread::Run() {\n \/\/ Attach the worker thread checker to this thread.\n RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());\n rtc::SetCurrentThreadName(name_.c_str());\n\n if (run_function_) {\n SetPriority(priority_);\n run_function_(obj_);\n return;\n }\n\n\/\/ TODO(tommi): Delete the rest of this function when looping isn't supported.\n#if RTC_DCHECK_IS_ON\n \/\/ These constants control the busy loop detection algorithm below.\n \/\/ |kMaxLoopCount| controls the limit for how many times we allow the loop\n \/\/ to run within a period, before DCHECKing.\n \/\/ |kPeriodToMeasureMs| controls how long that period is.\n static const int kMaxLoopCount = 1000;\n static const int kPeriodToMeasureMs = 100;\n int64_t loop_stamps[kMaxLoopCount] = {};\n int64_t sequence_nr = 0;\n#endif\n\n do {\n TRACE_EVENT1(\"webrtc\", \"PlatformThread::Run\", \"name\", name_.c_str());\n\n \/\/ The interface contract of Start\/Stop is that for a successful call to\n \/\/ Start, there should be at least one call to the run function. So we\n \/\/ call the function before checking |stop_|.\n if (!run_function_deprecated_(obj_))\n break;\n#if RTC_DCHECK_IS_ON\n auto id = sequence_nr % kMaxLoopCount;\n loop_stamps[id] = rtc::TimeMillis();\n if (sequence_nr > kMaxLoopCount) {\n auto compare_id = (id + 1) % kMaxLoopCount;\n auto diff = loop_stamps[id] - loop_stamps[compare_id];\n RTC_DCHECK_GE(diff, 0);\n if (diff < kPeriodToMeasureMs) {\n RTC_NOTREACHED() << \"This thread is too busy: \" << name_ << \" \" << diff\n << \"ms sequence=\" << sequence_nr << \" \"\n << loop_stamps[id] << \" vs \" << loop_stamps[compare_id]\n << \", \" << id << \" vs \" << compare_id;\n }\n }\n ++sequence_nr;\n#endif\n#if defined(WEBRTC_WIN)\n \/\/ Alertable sleep to permit RaiseFlag to run and update |stop_|.\n SleepEx(0, true);\n } while (!stop_);\n#else\n#if defined(WEBRTC_MAC)\n sched_yield();\n#else\n static const struct timespec ts_null = {0};\n nanosleep(&ts_null, nullptr);\n#endif\n } while (!AtomicOps::AcquireLoad(&stop_flag_));\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\nbool PlatformThread::SetPriority(ThreadPriority priority) {\n#if RTC_DCHECK_IS_ON\n if (run_function_) {\n \/\/ The non-deprecated way of how this function gets called, is that it must\n \/\/ be called on the worker thread itself.\n RTC_DCHECK(!thread_checker_.CalledOnValidThread());\n RTC_DCHECK(spawned_thread_checker_.CalledOnValidThread());\n } else {\n \/\/ In the case of deprecated use of this method, it must be called on the\n \/\/ same thread as the PlatformThread object is constructed on.\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n RTC_DCHECK(IsRunning());\n }\n#endif\n\n#if defined(WEBRTC_WIN)\n return SetThreadPriority(thread_, priority) != FALSE;\n#elif defined(__native_client__)\n \/\/ Setting thread priorities is not supported in NaCl.\n return true;\n#elif defined(WEBRTC_CHROMIUM_BUILD) && defined(WEBRTC_LINUX)\n \/\/ TODO(tommi): Switch to the same mechanism as Chromium uses for changing\n \/\/ thread priorities.\n return true;\n#else\n#ifdef WEBRTC_THREAD_RR\n const int policy = SCHED_RR;\n#else\n const int policy = SCHED_FIFO;\n#endif\n const int min_prio = sched_get_priority_min(policy);\n const int max_prio = sched_get_priority_max(policy);\n if (min_prio == -1 || max_prio == -1) {\n return false;\n }\n\n if (max_prio - min_prio <= 2)\n return false;\n\n \/\/ Convert webrtc priority to system priorities:\n sched_param param;\n const int top_prio = max_prio - 1;\n const int low_prio = min_prio + 1;\n switch (priority) {\n case kLowPriority:\n param.sched_priority = low_prio;\n break;\n case kNormalPriority:\n \/\/ The -1 ensures that the kHighPriority is always greater or equal to\n \/\/ kNormalPriority.\n param.sched_priority = (low_prio + top_prio - 1) \/ 2;\n break;\n case kHighPriority:\n param.sched_priority = std::max(top_prio - 2, low_prio);\n break;\n case kHighestPriority:\n param.sched_priority = std::max(top_prio - 1, low_prio);\n break;\n case kRealtimePriority:\n param.sched_priority = top_prio;\n break;\n }\n return pthread_setschedparam(thread_, policy, ¶m) == 0;\n#endif \/\/ defined(WEBRTC_WIN)\n}\n\n#if defined(WEBRTC_WIN)\nbool PlatformThread::QueueAPC(PAPCFUNC function, ULONG_PTR data) {\n RTC_DCHECK(thread_checker_.CalledOnValidThread());\n RTC_DCHECK(IsRunning());\n\n return QueueUserAPC(function, thread_, data) != FALSE;\n}\n#endif\n\n} \/\/ namespace rtc\n<|endoftext|>"} {"text":"\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * synexts\/lang_item.cpp\n * - Binds language items to #[lang_item] tagged items\n *\/\n#include \n#include \"..\/common.hpp\"\n#include \"..\/ast\/ast.hpp\"\n#include \"..\/ast\/crate.hpp\"\n\n\nvoid handle_lang_item(const Span& sp, AST::Crate& crate, const AST::Path& path, const ::std::string& name, AST::eItemType type)\n{\n if(name == \"phantom_fn\") {\n \/\/ - Just save path\n }\n else if( name == \"send\" ) {\n \/\/ Don't care, Send is fully library in mrustc\n \/\/ - Needed for `static`\n }\n else if( name == \"sync\" ) {\n \/\/ Don't care, Sync is fully library in mrustc\n \/\/ - Needed for `static`\n }\n else if( name == \"sized\" ) {\n DEBUG(\"Bind 'sized' to \" << path);\n }\n else if( name == \"copy\" ) {\n DEBUG(\"Bind 'copy' to \" << path);\n }\n \/\/ ops traits\n else if( name == \"drop\" ) { DEBUG(\"Bind '\"<Expand lang - \"start\"\/*\n * MRustC - Rust Compiler\n * - By John Hodge (Mutabah\/thePowersGang)\n *\n * synexts\/lang_item.cpp\n * - Binds language items to #[lang_item] tagged items\n *\/\n#include \n#include \"..\/common.hpp\"\n#include \"..\/ast\/ast.hpp\"\n#include \"..\/ast\/crate.hpp\"\n\n\nvoid handle_lang_item(const Span& sp, AST::Crate& crate, const AST::Path& path, const ::std::string& name, AST::eItemType type)\n{\n if(name == \"phantom_fn\") {\n \/\/ - Just save path\n }\n else if( name == \"send\" ) {\n \/\/ Don't care, Send is fully library in mrustc\n \/\/ - Needed for `static`\n }\n else if( name == \"sync\" ) {\n \/\/ Don't care, Sync is fully library in mrustc\n \/\/ - Needed for `static`\n }\n else if( name == \"sized\" ) {\n DEBUG(\"Bind 'sized' to \" << path);\n }\n else if( name == \"copy\" ) {\n DEBUG(\"Bind 'copy' to \" << path);\n }\n \/\/ ops traits\n else if( name == \"drop\" ) { DEBUG(\"Bind '\"<second << \" and \" << path);\n }\n}\n\nclass Decorator_LangItem:\n public ExpandDecorator\n{\npublic:\n AttrStage stage() const override { return AttrStage::EarlyPost; }\n void handle(const Span& sp, const AST::MetaItem& attr, AST::Crate& crate, const AST::Path& path, AST::Module& mod, AST::Item& i) const override\n {\n TU_MATCH_DEF(::AST::Item, (i), (e),\n (\n TODO(sp, \"Unknown item type with #[lang=\\\"\"<"} {"text":"#include \"Sketch.h\"\n\n#include \"chr\/gl\/draw\/Sphere.h\"\n\nusing namespace std;\nusing namespace chr;\nusing namespace gl;\nusing namespace draw;\nusing namespace path;\n\nconstexpr float R1 = 6;\nconstexpr float R2 = 300;\nconstexpr float TURNS = 20;\nconstexpr float DD1 = 1.0f;\nconstexpr float DD2 = 3.0f;\n\nconstexpr int NUM_SPHERES = 1000;\nconstexpr float SWELL_FACTOR = 0.125f;\n\nSketch::Sketch()\n :\n shader(InputSource::resource(\"Shader.vert\"), InputSource::resource(\"Shader.frag\"))\n{}\n\nvoid Sketch::setup()\n{\n texture = Texture::ImageRequest(\"checker.png\")\n .setFlags(image::FLAGS_RBGA)\n .setFilters(GL_NEAREST, GL_NEAREST);\n\n batch\n .setShader(shader)\n .setShaderColor(0.25f, 1.0f, 0.0f, 1)\n .setTexture(texture);\n\n Sphere()\n .setFrontFace(CW)\n .setSectorCount(20)\n .setStackCount(10)\n .setRadius(5)\n .append(batch, Matrix());\n\n instanceBuffer = InstanceBuffer(GL_DYNAMIC_DRAW);\n\n spiral.setup(surface, R1, R2, TURNS, DD1, DD2, 10 * NUM_SPHERES, 10);\n\n \/\/ ---\n\n glEnable(GL_CULL_FACE);\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_TRUE);\n\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n}\n\nvoid Sketch::resize()\n{\n camera\n .setFov(45)\n .setClip(0.1f, 1000.0f)\n .setWindowSize(windowInfo.size);\n}\n\nvoid Sketch::update()\n{\n spiral.update(surface, clock()->getTime(), SWELL_FACTOR);\n}\n\nvoid Sketch::draw()\n{\n glClearColor(0.4f, 0.8f, 1.0f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n \/\/ ---\n\n camera.getViewMatrix()\n .setIdentity()\n .translate(0, 0, -300)\n .rotateX(115 * D2R)\n .rotateY(0);\n\n State()\n .setShaderMatrix(camera.getViewMatrix())\n .setShaderMatrix(camera.getProjectionMatrix())\n .setShaderUniform(\"u_light_position\", camera.getEyePosition())\n .setShaderUniform(\"u_light_color\", glm::vec3(1.0, 1.0, 1.0))\n .setShaderUniform(\"u_light_intensity\", 1.0f)\n .setShaderUniform(\"u_ambient_color\", glm::vec3(0, 0, 0))\n .setShaderUniform(\"u_specular_color\", glm::vec3(1, 1, 1))\n .setShaderUniform(\"u_shininess\", 25.0f)\n .setShaderUniform(\"u_has_texture\", true)\n .setShaderUniform(\"u_has_color\", true) \/\/ i.e. do not use diffuse color but vertex color instead\n .apply();\n\n threadSpiral(instanceBuffer, spiral.path, 10);\n batch.flush(instanceBuffer);\n\n State()\n .setShaderMatrix(camera.getViewProjectionMatrix())\n .apply();\n}\n\nvoid Sketch::threadSpiral(InstanceBuffer &instanceBuffer, const FollowablePath3D &path, float spacing)\n{\n instanceBuffer.clearMatrices();\n\n float offset = 0;\n Matrix matrix;\n\n for (int i = 0; i < NUM_SPHERES; i++)\n {\n auto value = path.offsetToValue(offset);\n value.applyToMatrix(matrix);\n instanceBuffer.addMatrix(matrix);\n offset += spacing;\n }\n}\nTestingDynamicInstancing: Re-indenting#include \"Sketch.h\"\n\n#include \"chr\/gl\/draw\/Sphere.h\"\n\nusing namespace std;\nusing namespace chr;\nusing namespace gl;\nusing namespace draw;\nusing namespace path;\n\nconstexpr float R1 = 6;\nconstexpr float R2 = 300;\nconstexpr float TURNS = 20;\nconstexpr float DD1 = 1.0f;\nconstexpr float DD2 = 3.0f;\n\nconstexpr int NUM_SPHERES = 1000;\nconstexpr float SWELL_FACTOR = 0.125f;\n\nSketch::Sketch()\n:\nshader(InputSource::resource(\"Shader.vert\"), InputSource::resource(\"Shader.frag\"))\n{}\n\nvoid Sketch::setup()\n{\n texture = Texture::ImageRequest(\"checker.png\")\n .setFlags(image::FLAGS_RBGA)\n .setFilters(GL_NEAREST, GL_NEAREST);\n\n batch\n .setShader(shader)\n .setShaderColor(0.25f, 1.0f, 0.0f, 1)\n .setTexture(texture);\n\n Sphere()\n .setFrontFace(CW)\n .setSectorCount(20)\n .setStackCount(10)\n .setRadius(5)\n .append(batch, Matrix());\n\n instanceBuffer = InstanceBuffer(GL_DYNAMIC_DRAW);\n\n spiral.setup(surface, R1, R2, TURNS, DD1, DD2, 10 * NUM_SPHERES, 10);\n\n \/\/ ---\n\n glEnable(GL_CULL_FACE);\n glEnable(GL_DEPTH_TEST);\n glDepthMask(GL_TRUE);\n\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n}\n\nvoid Sketch::resize()\n{\n camera\n .setFov(45)\n .setClip(0.1f, 1000.0f)\n .setWindowSize(windowInfo.size);\n}\n\nvoid Sketch::update()\n{\n spiral.update(surface, clock()->getTime(), SWELL_FACTOR);\n}\n\nvoid Sketch::draw()\n{\n glClearColor(0.4f, 0.8f, 1.0f, 1.0f);\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n\n \/\/ ---\n\n camera.getViewMatrix()\n .setIdentity()\n .translate(0, 0, -300)\n .rotateX(115 * D2R)\n .rotateY(0);\n\n State()\n .setShaderMatrix(camera.getViewMatrix())\n .setShaderMatrix(camera.getProjectionMatrix())\n .setShaderUniform(\"u_light_position\", camera.getEyePosition())\n .setShaderUniform(\"u_light_color\", glm::vec3(1.0, 1.0, 1.0))\n .setShaderUniform(\"u_light_intensity\", 1.0f)\n .setShaderUniform(\"u_ambient_color\", glm::vec3(0, 0, 0))\n .setShaderUniform(\"u_specular_color\", glm::vec3(1, 1, 1))\n .setShaderUniform(\"u_shininess\", 25.0f)\n .setShaderUniform(\"u_has_texture\", true)\n .setShaderUniform(\"u_has_color\", true) \/\/ i.e. do not use diffuse color but vertex color instead\n .apply();\n\n threadSpiral(instanceBuffer, spiral.path, 10);\n batch.flush(instanceBuffer);\n\n State()\n .setShaderMatrix(camera.getViewProjectionMatrix())\n .apply();\n}\n\nvoid Sketch::threadSpiral(InstanceBuffer &instanceBuffer, const FollowablePath3D &path, float spacing)\n{\n instanceBuffer.clearMatrices();\n\n float offset = 0;\n Matrix matrix;\n\n for (int i = 0; i < NUM_SPHERES; i++)\n {\n auto value = path.offsetToValue(offset);\n value.applyToMatrix(matrix);\n instanceBuffer.addMatrix(matrix);\n offset += spacing;\n }\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \n\n\n#include \"itkIntensityWindowingImageFilter.h\"\n#include \"itkRandomImageSource.h\"\n\nint itkIntensityWindowingImageFilterTest(int, char* [] )\n{\n std::cout << \"itkIntensityWindowingImageFilterTest Start\" << std::endl;\n\n typedef itk::Image TestInputImage;\n typedef itk::Image TestOutputImage;\n\n TestInputImage::RegionType region;\n TestInputImage::SizeType size; size.Fill(64);\n TestInputImage::IndexType index; index.Fill(0);\n\n region.SetIndex (index);\n region.SetSize (size);\n\n\n typedef itk::IntensityWindowingImageFilter FilterType;\n FilterType::Pointer filter = FilterType::New();\n\n \/\/ Now generate a real image\n\n typedef itk::RandomImageSource SourceType;\n SourceType::Pointer source = SourceType::New();\n TestInputImage::SizeValueType randomSize[3] = {17, 8, 20};\n\n\n \/\/ Set up source\n source->SetSize(randomSize);\n double minValue = -128.0;\n double maxValue = 127.0;\n\n source->SetMin( static_cast< TestInputImage::PixelType >( minValue ) );\n source->SetMax( static_cast< TestInputImage::PixelType >( maxValue ) );\n\n filter->SetInput(source->GetOutput());\n\n const double desiredMinimum = -1.0;\n const double desiredMaximum = 1.0;\n\n const float windowMinimum = -50.0f;\n const float windowMaximum = 50.0f;\n\n filter->SetOutputMinimum( desiredMinimum );\n filter->SetOutputMaximum( desiredMaximum );\n filter->SetWindowMinimum( windowMinimum );\n filter->SetWindowMaximum( windowMaximum );\n\n std::cout << \"Window minimum:maximum = \" << windowMinimum << \":\" << windowMaximum << \", equivalent window:level = \" << filter->GetWindow() << \":\" << filter->GetLevel() << std::endl;\n\n try\n {\n filter->UpdateLargestPossibleRegion();\n filter->SetFunctor(filter->GetFunctor());\n }\n catch (itk::ExceptionObject& e)\n {\n std::cerr << \"Exception detected: \" << e;\n return -1;\n }\n\n typedef itk::MinimumMaximumImageCalculator< TestOutputImage > CalculatorType;\n CalculatorType::Pointer calculator = CalculatorType::New();\n\n calculator->SetImage( filter->GetOutput() );\n\n calculator->Compute();\n\n const double tolerance = 1e-7;\n\n const double obtainedMinimum = calculator->GetMinimum();\n const double obtainedMaximum = calculator->GetMaximum();\n\n if( itk::Math::abs( obtainedMinimum - desiredMinimum ) > tolerance )\n {\n std::cerr << \"Error in minimum\" << std::endl;\n std::cerr << \"Expected minimum = \" << desiredMinimum << std::endl;\n std::cerr << \"Obtained minimum = \" << obtainedMinimum << std::endl;\n return EXIT_FAILURE;\n }\n\n if( itk::Math::abs( obtainedMaximum - desiredMaximum ) > tolerance )\n {\n std::cerr << \"Error in maximum\" << std::endl;\n std::cerr << \"Expected maximum = \" << desiredMaximum << std::endl;\n std::cerr << \"Obtained maximum = \" << obtainedMaximum << std::endl;\n return EXIT_FAILURE;\n }\n\n const float window = 50.0f;\n const float level = 50.0f;\n\n filter->SetWindowLevel( window, level );\n\n std::cout << \"Window:level = \"\n << filter->GetWindow() << \":\"\n << filter->GetLevel()\n << \", equivalent window minimum:maximum = \"\n << filter->GetWindowMinimum()\n << \":\" << filter->GetWindowMaximum() << std::endl;\n\n try\n {\n filter->UpdateLargestPossibleRegion();\n }\n catch (itk::ExceptionObject& e)\n {\n std::cerr << \"Exception detected: \" << e;\n return -1;\n }\n\n calculator->Compute();\n\n const double obtainedMinimum2 = calculator->GetMinimum();\n const double obtainedMaximum2 = calculator->GetMaximum();\n\n if( itk::Math::abs( obtainedMinimum2 - desiredMinimum ) > tolerance )\n {\n std::cerr << \"Error in minimum\" << std::endl;\n std::cerr << \"Expected minimum = \" << desiredMinimum << std::endl;\n std::cerr << \"Obtained minimum = \" << obtainedMinimum2 << std::endl;\n return EXIT_FAILURE;\n }\n\n if( itk::Math::abs( obtainedMaximum2 - desiredMaximum ) > tolerance )\n {\n std::cerr << \"Error in maximum\" << std::endl;\n std::cerr << \"Expected maximum = \" << desiredMaximum << std::endl;\n std::cerr << \"Obtained maximum = \" << obtainedMaximum2 << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test PASSED ! \" << std::endl;\n return EXIT_SUCCESS;\n\n}\nSTYLE: Improve the itkIntensityWindowingImageFilter test style\/*=========================================================================\n *\n * Copyright Insight Software Consortium\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0.txt\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *=========================================================================*\/\n\n#include \n\n#include \"itkIntensityWindowingImageFilter.h\"\n#include \"itkRandomImageSource.h\"\n\nint itkIntensityWindowingImageFilterTest(int, char* [] )\n{\n std::cout << \"Testing itk::IntensityWindowingImageFilter class\" << std::endl;\n\n const unsigned int Dimension = 3;\n typedef float PixelType;\n\n typedef itk::Image< PixelType, Dimension > TestInputImage;\n typedef itk::Image< PixelType, Dimension > TestOutputImage;\n\n TestInputImage::RegionType region;\n TestInputImage::SizeType size; size.Fill(64);\n TestInputImage::IndexType index; index.Fill(0);\n\n region.SetIndex (index);\n region.SetSize (size);\n\n\n typedef itk::IntensityWindowingImageFilter< TestInputImage, TestOutputImage > FilterType;\n FilterType::Pointer filter = FilterType::New();\n\n \/\/ Now generate a real image\n\n typedef itk::RandomImageSource SourceType;\n SourceType::Pointer source = SourceType::New();\n TestInputImage::SizeValueType randomSize[3] = {17, 8, 20};\n\n\n \/\/ Set up source\n source->SetSize(randomSize);\n double minValue = -128.0;\n double maxValue = 127.0;\n\n source->SetMin( static_cast< TestInputImage::PixelType >( minValue ) );\n source->SetMax( static_cast< TestInputImage::PixelType >( maxValue ) );\n\n filter->SetInput(source->GetOutput());\n\n const double desiredMinimum = -1.0;\n const double desiredMaximum = 1.0;\n\n const float windowMinimum = -50.0f;\n const float windowMaximum = 50.0f;\n\n filter->SetOutputMinimum( desiredMinimum );\n filter->SetOutputMaximum( desiredMaximum );\n filter->SetWindowMinimum( windowMinimum );\n filter->SetWindowMaximum( windowMaximum );\n\n std::cout << \"Window minimum:maximum = \"\n << windowMinimum << \":\" << windowMaximum\n << \", equivalent window:level = \"\n << filter->GetWindow() << \":\" << filter->GetLevel() << std::endl;\n\n try\n {\n filter->UpdateLargestPossibleRegion();\n filter->SetFunctor(filter->GetFunctor());\n }\n catch (itk::ExceptionObject& e)\n {\n std::cerr << \"Exception detected: \" << e;\n return -1;\n }\n\n typedef itk::MinimumMaximumImageCalculator< TestOutputImage > CalculatorType;\n CalculatorType::Pointer calculator = CalculatorType::New();\n\n calculator->SetImage( filter->GetOutput() );\n\n calculator->Compute();\n\n const double tolerance = 1e-7;\n\n const double obtainedMinimum = calculator->GetMinimum();\n const double obtainedMaximum = calculator->GetMaximum();\n\n if( itk::Math::abs( obtainedMinimum - desiredMinimum ) > tolerance )\n {\n std::cerr << \"Error in minimum\" << std::endl;\n std::cerr << \"Expected minimum = \" << desiredMinimum << std::endl;\n std::cerr << \"Obtained minimum = \" << obtainedMinimum << std::endl;\n return EXIT_FAILURE;\n }\n\n if( itk::Math::abs( obtainedMaximum - desiredMaximum ) > tolerance )\n {\n std::cerr << \"Error in maximum\" << std::endl;\n std::cerr << \"Expected maximum = \" << desiredMaximum << std::endl;\n std::cerr << \"Obtained maximum = \" << obtainedMaximum << std::endl;\n return EXIT_FAILURE;\n }\n\n const float window = 50.0f;\n const float level = 50.0f;\n\n filter->SetWindowLevel( window, level );\n\n std::cout << \"Window:level = \"\n << filter->GetWindow() << \":\"\n << filter->GetLevel()\n << \", equivalent window minimum:maximum = \"\n << filter->GetWindowMinimum()\n << \":\" << filter->GetWindowMaximum() << std::endl;\n\n try\n {\n filter->UpdateLargestPossibleRegion();\n }\n catch (itk::ExceptionObject& e)\n {\n std::cerr << \"Exception detected: \" << e;\n return -1;\n }\n\n calculator->Compute();\n\n const double obtainedMinimum2 = calculator->GetMinimum();\n const double obtainedMaximum2 = calculator->GetMaximum();\n\n if( itk::Math::abs( obtainedMinimum2 - desiredMinimum ) > tolerance )\n {\n std::cerr << \"Error in minimum\" << std::endl;\n std::cerr << \"Expected minimum = \" << desiredMinimum << std::endl;\n std::cerr << \"Obtained minimum = \" << obtainedMinimum2 << std::endl;\n return EXIT_FAILURE;\n }\n\n if( itk::Math::abs( obtainedMaximum2 - desiredMaximum ) > tolerance )\n {\n std::cerr << \"Error in maximum\" << std::endl;\n std::cerr << \"Expected maximum = \" << desiredMaximum << std::endl;\n std::cerr << \"Obtained maximum = \" << obtainedMaximum2 << std::endl;\n return EXIT_FAILURE;\n }\n\n std::cout << \"Test PASSED ! \" << std::endl;\n return EXIT_SUCCESS;\n\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \n#include \n#include \n\n#include \"math\/vector3.hpp\"\n\n\/\/#include \"projection.hpp\"\n\/\/#include \"integrator.hpp\"\n\n\/\/ this needs to be improved to be able to have different precisions\n\/\/ and perhaps different color systems (if applicable)\nstruct color\n{\n\tfloat r, g, b, a;\n};\n\n\/\/ A screen raster, which holds a pixel buffer\nstruct Raster\n{\n\tRaster(size_t width, size_t height)\n\t : m_width(width), m_height(height)\n\t{\n\t\tm_data.resize(m_width * m_height);\n\t}\n\n\tconst color *operator[](size_t y) const\n\t\t{ return &m_data[y * m_width]; }\n\tcolor *operator[](size_t y)\n\t\t{ return &m_data[y * m_width]; }\n\n\tsize_t width() const { return m_width; }\n\tsize_t height() const { return m_height; }\n\nprivate:\n\tstd::vector m_data;\n\tconst size_t m_width, m_height;\n};\n\ntemplate \nvoid render(RasterTy &raster, IntegratorTy &&integrator)\n{\n\t\/\/ this is where the rendering happens:\n\t\/\/ 1. project a camera ray for every pixel\n\t\/\/ (according to some subpixel sampling distribution)\n\t\/\/ 2. integrate the camera ray to assign a color\n\t\/\/ 3. post-process as needed\n\t\/\/ 4. output the rest\n\n\t\/\/ this is just a test render\n\tfor (size_t y = 0; y < raster.height(); ++y) {\n\t\tfor (size_t x = 0; x < raster.width(); ++x) {\n\t\t float px = ((float)x \/ raster.width() - 0.5f) * 2;\n\t\t float py = ((float)y \/ raster.height() - 0.5f) * 2;\n\t\t \n\t\t math::float3 cam_dir = normalize(math::float3(px, py, 0.5f));\n\t\t math::float3 cam_pos(0, 0, 0);\n\t\t \n\t\t math::float3 color = integrator(cam_pos, cam_dir);\n\t\t \n\t\t raster[y][x].r = color.x;\n\t\t raster[y][x].g = color.y;\n\t\t raster[y][x].b = color.z;\n\t\t}\n\t}\n}\nResize can be replaced with constructor, more elegant.#pragma once\n\n#include \n\n#include \n#include \n#include \n\n#include \"math\/vector3.hpp\"\n\n\/\/#include \"projection.hpp\"\n\/\/#include \"integrator.hpp\"\n\n\/\/ this needs to be improved to be able to have different precisions\n\/\/ and perhaps different color systems (if applicable)\nstruct color\n{\n\tfloat r, g, b, a;\n};\n\n\/\/ A screen raster, which holds a pixel buffer\nstruct Raster\n{\n\tRaster(size_t width, size_t height)\n\t : m_width(width), m_height(height), m_data(width * height)\n\t{\n\t}\n\n\tconst color *operator[](size_t y) const\n\t\t{ return &m_data[y * m_width]; }\n\tcolor *operator[](size_t y)\n\t\t{ return &m_data[y * m_width]; }\n\n\tsize_t width() const { return m_width; }\n\tsize_t height() const { return m_height; }\n\nprivate:\n\tconst size_t m_width, m_height;\n\tstd::vector m_data;\n};\n\ntemplate \nvoid render(RasterTy &raster, IntegratorTy &&integrator)\n{\n\t\/\/ this is where the rendering happens:\n\t\/\/ 1. project a camera ray for every pixel\n\t\/\/ (according to some subpixel sampling distribution)\n\t\/\/ 2. integrate the camera ray to assign a color\n\t\/\/ 3. post-process as needed\n\t\/\/ 4. output the rest\n\n\t\/\/ this is just a test render\n\tfor (size_t y = 0; y < raster.height(); ++y) {\n\t\tfor (size_t x = 0; x < raster.width(); ++x) {\n\t\t float px = ((float)x \/ raster.width() - 0.5f) * 2;\n\t\t float py = ((float)y \/ raster.height() - 0.5f) * 2;\n\t\t \n\t\t math::float3 cam_dir = normalize(math::float3(px, py, 0.5f));\n\t\t math::float3 cam_pos(0, 0, 0);\n\t\t \n\t\t math::float3 color = integrator(cam_pos, cam_dir);\n\t\t \n\t\t raster[y][x].r = color.x;\n\t\t raster[y][x].g = color.y;\n\t\t raster[y][x].b = color.z;\n\t\t}\n\t}\n}\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* common headers *\/\n#include \"common.h\"\n\n\/* interface headers *\/\n#include \"EvdevJoystick.h\"\n\n#ifdef HAVE_LINUX_INPUT_H\n\n\/* system headers *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* implementation headers *\/\n#include \"ErrorHandler.h\"\n\n#define test_bit(nr, addr) \\\n\t(((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0)\n\n\n\nbool EvdevJoystick::isEvdevAvailable()\n{\n \/* Test whether this driver should be used without actually\n * loading it. Will return false if no event devices can be\n * located, or if it has been specifically disabled by setting\n * the environment variable BZFLAG_ENABLE_EVDEV=0\n *\/\n\n char *envvar = getenv(\"BZFLAG_ENABLE_EVDEV\");\n if (envvar)\n return atoi(envvar) != 0;\n\n std::map joysticks;\n scanForJoysticks(joysticks);\n return !joysticks.empty();\n}\n\n\nEvdevJoystick::EvdevJoystick()\n{\n joystickfd = 0;\n currentJoystick = NULL;\n ff_rumble = new struct ff_effect;\n scanForJoysticks(joysticks);\n}\n\nEvdevJoystick::~EvdevJoystick()\n{\n initJoystick(\"\");\n delete ff_rumble;\n}\n\nvoid EvdevJoystick::scanForJoysticks(std::map &joysticks)\n{\n joysticks.clear();\n\n const std::string inputdirName = \"\/dev\/input\";\n DIR* inputdir = opendir(inputdirName.c_str());\n if (!inputdir)\n return;\n\n struct dirent *dent;\n while ((dent = readdir(inputdir))) {\n EvdevJoystickInfo info;\n\n \/* Does it look like an event device? *\/\n if (strncmp(dent->d_name, \"event\", 5))\n continue;\n\n \/* Can we open it? *\/\n info.filename = inputdirName + \"\/\" + dent->d_name;\n int fd = open(info.filename.c_str(), O_RDWR);\n if (!fd)\n continue;\n\n \/* Does it look like a joystick? *\/\n if (!(collectJoystickBits(fd, info) && isJoystick(info))) {\n close(fd);\n continue;\n }\n\n \/* Can we get its name? *\/\n char jsname[128];\n if (ioctl(fd, EVIOCGNAME(sizeof(jsname)-1), jsname) < 0) {\n close(fd);\n continue;\n }\n jsname[sizeof(jsname)-1] = '\\0';\n\n close(fd);\n\n \/* Yay, add it to our map.\n *\n * FIXME: we can't handle multiple joysticks with the same name yet.\n * This could be fixed by disambiguating jsname if it already\n * exists in 'joysticks', but the user would still have a hard\n * time knowing which device to pick.\n *\/\n joysticks[jsname] = info;\n }\n\n closedir(inputdir);\n}\n\nbool EvdevJoystick::collectJoystickBits(int fd, struct EvdevJoystickInfo &info)\n{\n \/* Collect all the bitfields we're interested in from an event device\n * at the given file descriptor.\n *\/\n if (ioctl(fd, EVIOCGBIT(0, sizeof(info.evbit)), info.evbit) < 0)\n return false;\n if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(info.keybit)), info.keybit) < 0)\n return false;\n if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(info.absbit)), info.absbit) < 0)\n return false;\n if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(info.ffbit)), info.ffbit) < 0)\n return false;\n\n \/* Collect information about our absolute axes *\/\n int axis;\n for (axis=0; axis<2; axis++) {\n if (ioctl(fd, EVIOCGABS(axis + ABS_X), &info.axis_info[axis]) < 0)\n return false;\n }\n\n return true;\n}\n\nbool\t\t\tEvdevJoystick::isJoystick(struct EvdevJoystickInfo &info)\n{\n \/* Look at the capability bitfields in the given EvdevJoystickInfo, and\n * decide whether the device is indeed a joystick. This uses the same criteria\n * that SDL does- it at least needs X and Y axes, and one joystick-like button.\n *\/\n if (!test_bit(EV_KEY, info.evbit))\n return false;\n if (!(test_bit(BTN_TRIGGER, info.keybit) ||\n\ttest_bit(BTN_A, info.keybit) ||\n\ttest_bit(BTN_1, info.keybit)))\n return false;\n\n if (!test_bit(EV_ABS, info.evbit))\n return false;\n if (!(test_bit(ABS_X, info.absbit) &&\n\ttest_bit(ABS_Y, info.absbit)))\n return false;\n\n return true;\n}\n\nvoid\t\t\tEvdevJoystick::initJoystick(const char* joystickName)\n{\n \/* Close the previous joystick *\/\n ffResetRumble();\n if (joystickfd > 0)\n close(joystickfd);\n currentJoystick = NULL;\n joystickfd = 0;\n\n if (!strcmp(joystickName, \"off\") || !strcmp(joystickName, \"\")) {\n \/* No joystick configured, we're done *\/\n return;\n }\n\n std::map::iterator iter;\n iter = joysticks.find(joystickName);\n if (iter == joysticks.end()) {\n printError(\"The selected joystick no longer exists.\");\n return;\n }\n\n \/* Looks like we might have a valid joystick, try to open it *\/\n EvdevJoystickInfo *info = &iter->second;\n joystickfd = open(info->filename.c_str(), O_RDWR | O_NONBLOCK);\n if (joystickfd > 0) {\n \/* Yay, it worked *\/\n currentJoystick = info;\n }\n else {\n printError(\"Error opening the selected joystick.\");\n }\n\n buttons = 0;\n}\n\nbool\t\t\tEvdevJoystick::joystick() const\n{\n return currentJoystick != NULL;\n}\n\nvoid EvdevJoystick::poll()\n{\n \/* Read as many input events as are available, and update our current state\n *\/\n struct input_event ev;\n while (read(joystickfd, &ev, sizeof(ev)) > 0) {\n switch (ev.type) {\n\n case EV_ABS:\n switch (ev.code) {\n case ABS_X: currentJoystick->axis_info[0].value = ev.value; break;\n case ABS_Y: currentJoystick->axis_info[1].value = ev.value; break;\n }\n break;\n\n case EV_KEY:\n setButton(mapButton(ev.code), ev.value);\n break;\n\n }\n }\n}\n\nint EvdevJoystick::mapButton(int bit_num)\n{\n \/* Given an evdev button number, map it back to a small integer that most\n * people would consider the button's actual number. This also ensures\n * that we can fit all buttons in \"buttons\" as long as the number of buttons\n * is less than the architecture's word size ;)\n *\n * We just scan through the joystick's keybits, counting how many\n * set bits we encounter before this one. If the indicated bit isn't\n * set in keybits, this is a bad event and we return -1.\n * If this linear scan becomes a noticeable performance drain, this could\n * easily be precomputed and stored in an std:map.\n *\/\n int i;\n int button_num = 0;\n const int total_bits = sizeof(currentJoystick->keybit)*sizeof(unsigned long)*8;\n\n for (i=0; ikeybit))\n button_num++;\n }\n return -1;\n}\n\nvoid EvdevJoystick::setButton(int button_num, int state)\n{\n\n if (button_num >= 0) {\n int mask = 1<axis_info[axis].value;\n value -= currentJoystick->axis_info[axis].minimum;\n value = value * 2000 \/ (currentJoystick->axis_info[axis].maximum -\n\t\t\t currentJoystick->axis_info[axis].minimum);\n value -= 1000;\n\n \/* No cheating by modifying joystick drivers, or using some that rate\n * their maximum and minimum conservatively like the input spec allows.\n *\/\n if (value < -1000) value = -1000;\n if (value > 1000) value = 1000;\n\n \/* All the cool kids are doing it... *\/\n value = (value * abs(value)) \/ 1000;\n\n axes[axis] = value;\n }\n x = axes[0];\n y = axes[1];\n }\n else {\n x = y = 0;\n }\n}\n\nunsigned long\t\tEvdevJoystick::getJoyButtons()\n{\n if (currentJoystick) {\n poll();\n return buttons;\n }\n else {\n return 0;\n }\n}\n\nvoid EvdevJoystick::getJoyDevices(std::vector\n\t\t\t\t\t\t &list) const\n{\n std::map::const_iterator i;\n for (i = joysticks.begin(); i != joysticks.end(); ++i)\n list.push_back(i->first);\n}\n\nbool EvdevJoystick::ffHasRumble() const\n{\n#ifdef HAVE_FF_EFFECT_RUMBLE\n if (!currentJoystick)\n return false;\n else\n return test_bit(EV_FF, currentJoystick->evbit) &&\n test_bit(FF_RUMBLE, currentJoystick->ffbit);\n#else\n return false;\n#endif\n}\n\nvoid EvdevJoystick::ffResetRumble()\n{\n#ifdef HAVE_FF_EFFECT_RUMBLE\n \/* Erase old effects before closing a device,\n * if we had any, then initialize the ff_rumble struct.\n *\/\n if (ffHasRumble() && ff_rumble->id != -1) {\n\n \/* Stop the effect first *\/\n struct input_event event;\n event.type = EV_FF;\n event.code = ff_rumble->id;\n event.value = 0;\n write(joystickfd, &event, sizeof(event));\n\n \/* Erase the downloaded effect *\/\n ioctl(joystickfd, EVIOCRMFF, ff_rumble->id);\n }\n\n \/* Reinit the ff_rumble struct. It starts out with\n * an id of -1, prompting the driver to assign us one.\n * Once that happens, we stick with the same effect slot\n * as long as we have the device open.\n *\/\n memset(ff_rumble, 0, sizeof(*ff_rumble));\n ff_rumble->type = FF_RUMBLE;\n ff_rumble->id = -1;\n#endif\n}\n\n#ifdef HAVE_FF_EFFECT_RUMBLE\nvoid EvdevJoystick::ffRumble(int count,\n\t\t\t\t\t\tfloat delay, float duration,\n\t\t\t\t\t\tfloat strong_motor,\n\t\t\t\t\t\tfloat weak_motor)\n{\n if (!ffHasRumble())\n return;\n\n \/* Stop the previous effect we were playing, if any *\/\n if (ff_rumble->id != -1) {\n struct input_event event;\n event.type = EV_FF;\n event.code = ff_rumble->id;\n event.value = 0;\n write(joystickfd, &event, sizeof(event));\n }\n\n if (count > 0) {\n \/* Download an updated effect *\/\n ff_rumble->u.rumble.strong_magnitude = (int) (0xFFFF * strong_motor + 0.5);\n ff_rumble->u.rumble.weak_magnitude = (int) (0xFFFF * weak_motor + 0.5);\n ff_rumble->replay.length = (int) (duration * 1000 + 0.5);\n ff_rumble->replay.delay = (int) (delay * 1000 + 0.5);\n ioctl(joystickfd, EVIOCSFF, ff_rumble);\n\n \/* Play it the indicated number of times *\/\n struct input_event event;\n event.type = EV_FF;\n event.code = ff_rumble->id;\n event.value = count;\n write(joystickfd, &event, sizeof(event));\n }\n}\n#else\nvoid EvdevJoystick::ffRumble(int, float, float, float, float)\n{\n}\n#endif\n\n#endif \/* HAVE_LINUX_INPUT_H *\/\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\nSome event driver are bugged, so prefer disabling it via BZDB forever\/* bzflag\n * Copyright (c) 1993 - 2004 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n\/* common headers *\/\n#include \"common.h\"\n\n\/* interface headers *\/\n#include \"EvdevJoystick.h\"\n\n#ifdef HAVE_LINUX_INPUT_H\n\n\/* system headers *\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/* implementation headers *\/\n#include \"ErrorHandler.h\"\n#include \"StateDatabase.h\"\n\n#define test_bit(nr, addr) \\\n\t(((1UL << ((nr) & 31)) & (((const unsigned int *) addr)[(nr) >> 5])) != 0)\n\n\n\nbool EvdevJoystick::isEvdevAvailable()\n{\n \/* Test whether this driver should be used without actually\n * loading it. Will return false if no event devices can be\n * located, or if it has been specifically disabled by setting\n * the environment variable BZFLAG_ENABLE_EVDEV=0\n *\/\n\n if (BZDB.isSet(\"enable_evdev\") && !BZDB.isTrue(\"enable_evdev\"))\n return false;\n\n std::map joysticks;\n scanForJoysticks(joysticks);\n return !joysticks.empty();\n}\n\n\nEvdevJoystick::EvdevJoystick()\n{\n joystickfd = 0;\n currentJoystick = NULL;\n ff_rumble = new struct ff_effect;\n scanForJoysticks(joysticks);\n}\n\nEvdevJoystick::~EvdevJoystick()\n{\n initJoystick(\"\");\n delete ff_rumble;\n}\n\nvoid EvdevJoystick::scanForJoysticks(std::map &joysticks)\n{\n joysticks.clear();\n\n const std::string inputdirName = \"\/dev\/input\";\n DIR* inputdir = opendir(inputdirName.c_str());\n if (!inputdir)\n return;\n\n struct dirent *dent;\n while ((dent = readdir(inputdir))) {\n EvdevJoystickInfo info;\n\n \/* Does it look like an event device? *\/\n if (strncmp(dent->d_name, \"event\", 5))\n continue;\n\n \/* Can we open it? *\/\n info.filename = inputdirName + \"\/\" + dent->d_name;\n int fd = open(info.filename.c_str(), O_RDWR);\n if (!fd)\n continue;\n\n \/* Does it look like a joystick? *\/\n if (!(collectJoystickBits(fd, info) && isJoystick(info))) {\n close(fd);\n continue;\n }\n\n \/* Can we get its name? *\/\n char jsname[128];\n if (ioctl(fd, EVIOCGNAME(sizeof(jsname)-1), jsname) < 0) {\n close(fd);\n continue;\n }\n jsname[sizeof(jsname)-1] = '\\0';\n\n close(fd);\n\n \/* Yay, add it to our map.\n *\n * FIXME: we can't handle multiple joysticks with the same name yet.\n * This could be fixed by disambiguating jsname if it already\n * exists in 'joysticks', but the user would still have a hard\n * time knowing which device to pick.\n *\/\n joysticks[jsname] = info;\n }\n\n closedir(inputdir);\n}\n\nbool EvdevJoystick::collectJoystickBits(int fd, struct EvdevJoystickInfo &info)\n{\n \/* Collect all the bitfields we're interested in from an event device\n * at the given file descriptor.\n *\/\n if (ioctl(fd, EVIOCGBIT(0, sizeof(info.evbit)), info.evbit) < 0)\n return false;\n if (ioctl(fd, EVIOCGBIT(EV_KEY, sizeof(info.keybit)), info.keybit) < 0)\n return false;\n if (ioctl(fd, EVIOCGBIT(EV_ABS, sizeof(info.absbit)), info.absbit) < 0)\n return false;\n if (ioctl(fd, EVIOCGBIT(EV_FF, sizeof(info.ffbit)), info.ffbit) < 0)\n return false;\n\n \/* Collect information about our absolute axes *\/\n int axis;\n for (axis=0; axis<2; axis++) {\n if (ioctl(fd, EVIOCGABS(axis + ABS_X), &info.axis_info[axis]) < 0)\n return false;\n }\n\n return true;\n}\n\nbool\t\t\tEvdevJoystick::isJoystick(struct EvdevJoystickInfo &info)\n{\n \/* Look at the capability bitfields in the given EvdevJoystickInfo, and\n * decide whether the device is indeed a joystick. This uses the same criteria\n * that SDL does- it at least needs X and Y axes, and one joystick-like button.\n *\/\n if (!test_bit(EV_KEY, info.evbit))\n return false;\n if (!(test_bit(BTN_TRIGGER, info.keybit) ||\n\ttest_bit(BTN_A, info.keybit) ||\n\ttest_bit(BTN_1, info.keybit)))\n return false;\n\n if (!test_bit(EV_ABS, info.evbit))\n return false;\n if (!(test_bit(ABS_X, info.absbit) &&\n\ttest_bit(ABS_Y, info.absbit)))\n return false;\n\n return true;\n}\n\nvoid\t\t\tEvdevJoystick::initJoystick(const char* joystickName)\n{\n \/* Close the previous joystick *\/\n ffResetRumble();\n if (joystickfd > 0)\n close(joystickfd);\n currentJoystick = NULL;\n joystickfd = 0;\n\n if (!strcmp(joystickName, \"off\") || !strcmp(joystickName, \"\")) {\n \/* No joystick configured, we're done *\/\n return;\n }\n\n std::map::iterator iter;\n iter = joysticks.find(joystickName);\n if (iter == joysticks.end()) {\n printError(\"The selected joystick no longer exists.\");\n return;\n }\n\n \/* Looks like we might have a valid joystick, try to open it *\/\n EvdevJoystickInfo *info = &iter->second;\n joystickfd = open(info->filename.c_str(), O_RDWR | O_NONBLOCK);\n if (joystickfd > 0) {\n \/* Yay, it worked *\/\n currentJoystick = info;\n }\n else {\n printError(\"Error opening the selected joystick.\");\n }\n\n buttons = 0;\n}\n\nbool\t\t\tEvdevJoystick::joystick() const\n{\n return currentJoystick != NULL;\n}\n\nvoid EvdevJoystick::poll()\n{\n \/* Read as many input events as are available, and update our current state\n *\/\n struct input_event ev;\n while (read(joystickfd, &ev, sizeof(ev)) > 0) {\n switch (ev.type) {\n\n case EV_ABS:\n switch (ev.code) {\n case ABS_X: currentJoystick->axis_info[0].value = ev.value; break;\n case ABS_Y: currentJoystick->axis_info[1].value = ev.value; break;\n }\n break;\n\n case EV_KEY:\n setButton(mapButton(ev.code), ev.value);\n break;\n\n }\n }\n}\n\nint EvdevJoystick::mapButton(int bit_num)\n{\n \/* Given an evdev button number, map it back to a small integer that most\n * people would consider the button's actual number. This also ensures\n * that we can fit all buttons in \"buttons\" as long as the number of buttons\n * is less than the architecture's word size ;)\n *\n * We just scan through the joystick's keybits, counting how many\n * set bits we encounter before this one. If the indicated bit isn't\n * set in keybits, this is a bad event and we return -1.\n * If this linear scan becomes a noticeable performance drain, this could\n * easily be precomputed and stored in an std:map.\n *\/\n int i;\n int button_num = 0;\n const int total_bits = sizeof(currentJoystick->keybit)*sizeof(unsigned long)*8;\n\n for (i=0; ikeybit))\n button_num++;\n }\n return -1;\n}\n\nvoid EvdevJoystick::setButton(int button_num, int state)\n{\n\n if (button_num >= 0) {\n int mask = 1<axis_info[axis].value;\n value -= currentJoystick->axis_info[axis].minimum;\n value = value * 2000 \/ (currentJoystick->axis_info[axis].maximum -\n\t\t\t currentJoystick->axis_info[axis].minimum);\n value -= 1000;\n\n \/* No cheating by modifying joystick drivers, or using some that rate\n * their maximum and minimum conservatively like the input spec allows.\n *\/\n if (value < -1000) value = -1000;\n if (value > 1000) value = 1000;\n\n \/* All the cool kids are doing it... *\/\n value = (value * abs(value)) \/ 1000;\n\n axes[axis] = value;\n }\n x = axes[0];\n y = axes[1];\n }\n else {\n x = y = 0;\n }\n}\n\nunsigned long\t\tEvdevJoystick::getJoyButtons()\n{\n if (currentJoystick) {\n poll();\n return buttons;\n }\n else {\n return 0;\n }\n}\n\nvoid EvdevJoystick::getJoyDevices(std::vector\n\t\t\t\t\t\t &list) const\n{\n std::map::const_iterator i;\n for (i = joysticks.begin(); i != joysticks.end(); ++i)\n list.push_back(i->first);\n}\n\nbool EvdevJoystick::ffHasRumble() const\n{\n#ifdef HAVE_FF_EFFECT_RUMBLE\n if (!currentJoystick)\n return false;\n else\n return test_bit(EV_FF, currentJoystick->evbit) &&\n test_bit(FF_RUMBLE, currentJoystick->ffbit);\n#else\n return false;\n#endif\n}\n\nvoid EvdevJoystick::ffResetRumble()\n{\n#ifdef HAVE_FF_EFFECT_RUMBLE\n \/* Erase old effects before closing a device,\n * if we had any, then initialize the ff_rumble struct.\n *\/\n if (ffHasRumble() && ff_rumble->id != -1) {\n\n \/* Stop the effect first *\/\n struct input_event event;\n event.type = EV_FF;\n event.code = ff_rumble->id;\n event.value = 0;\n write(joystickfd, &event, sizeof(event));\n\n \/* Erase the downloaded effect *\/\n ioctl(joystickfd, EVIOCRMFF, ff_rumble->id);\n }\n\n \/* Reinit the ff_rumble struct. It starts out with\n * an id of -1, prompting the driver to assign us one.\n * Once that happens, we stick with the same effect slot\n * as long as we have the device open.\n *\/\n memset(ff_rumble, 0, sizeof(*ff_rumble));\n ff_rumble->type = FF_RUMBLE;\n ff_rumble->id = -1;\n#endif\n}\n\n#ifdef HAVE_FF_EFFECT_RUMBLE\nvoid EvdevJoystick::ffRumble(int count,\n\t\t\t\t\t\tfloat delay, float duration,\n\t\t\t\t\t\tfloat strong_motor,\n\t\t\t\t\t\tfloat weak_motor)\n{\n if (!ffHasRumble())\n return;\n\n \/* Stop the previous effect we were playing, if any *\/\n if (ff_rumble->id != -1) {\n struct input_event event;\n event.type = EV_FF;\n event.code = ff_rumble->id;\n event.value = 0;\n write(joystickfd, &event, sizeof(event));\n }\n\n if (count > 0) {\n \/* Download an updated effect *\/\n ff_rumble->u.rumble.strong_magnitude = (int) (0xFFFF * strong_motor + 0.5);\n ff_rumble->u.rumble.weak_magnitude = (int) (0xFFFF * weak_motor + 0.5);\n ff_rumble->replay.length = (int) (duration * 1000 + 0.5);\n ff_rumble->replay.delay = (int) (delay * 1000 + 0.5);\n ioctl(joystickfd, EVIOCSFF, ff_rumble);\n\n \/* Play it the indicated number of times *\/\n struct input_event event;\n event.type = EV_FF;\n event.code = ff_rumble->id;\n event.value = count;\n write(joystickfd, &event, sizeof(event));\n }\n}\n#else\nvoid EvdevJoystick::ffRumble(int, float, float, float, float)\n{\n}\n#endif\n\n#endif \/* HAVE_LINUX_INPUT_H *\/\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"gitcommand.h\"\n#include \"gitconstants.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nQ_DECLARE_METATYPE(QVariant)\n\nnamespace Git {\nnamespace Internal {\n\nstatic QString msgTermination(int exitCode, const QString &binaryPath, const QStringList &args)\n{\n QString cmd = QFileInfo(binaryPath).baseName();\n if (!args.empty()) {\n cmd += QLatin1Char(' ');\n cmd += args.front();\n }\n return exitCode ?\n QCoreApplication::translate(\"GitCommand\", \"\\n'%1' failed (exit code %2).\\n\").arg(cmd).arg(exitCode) :\n QCoreApplication::translate(\"GitCommand\", \"\\n'%1' completed (exit code %2).\\n\").arg(cmd).arg(exitCode);\n}\n\nGitCommand::Job::Job(const QStringList &a, int t) :\n arguments(a),\n timeout(t)\n{\n \/\/ Finished cookie is emitted via queued slot, needs metatype\n static const int qvMetaId = qRegisterMetaType();\n Q_UNUSED(qvMetaId)\n}\n\nGitCommand::GitCommand(const QStringList &binary,\n const QString &workingDirectory,\n const QStringList &environment,\n const QVariant &cookie) :\n m_binaryPath(binary.front()),\n m_basicArguments(binary),\n m_workingDirectory(workingDirectory),\n m_environment(environment),\n m_cookie(cookie),\n m_reportTerminationMode(NoReport)\n{\n m_basicArguments.pop_front();\n}\n\nGitCommand::TerminationReportMode GitCommand::reportTerminationMode() const\n{\n return m_reportTerminationMode;\n}\n\nvoid GitCommand::setTerminationReportMode(TerminationReportMode m)\n{\n m_reportTerminationMode = m;\n}\n\nvoid GitCommand::addJob(const QStringList &arguments, int timeout)\n{\n m_jobs.push_back(Job(arguments, timeout));\n}\n\nvoid GitCommand::execute()\n{\n if (Git::Constants::debug)\n qDebug() << \"GitCommand::execute\" << m_workingDirectory << m_jobs.size();\n\n if (m_jobs.empty())\n return;\n\n \/\/ For some reason QtConcurrent::run() only works on this\n QFuture task = QtConcurrent::run(this, &GitCommand::run);\n const QString taskName = QLatin1String(\"Git \") + m_jobs.front().arguments.at(0);\n\n Core::ICore::instance()->progressManager()->addTask(task, taskName,\n QLatin1String(\"Git.action\"));\n}\n\nQString GitCommand::msgTimeout(int seconds)\n{\n return tr(\"Error: Git timed out after %1s.\").arg(seconds);\n}\n\nvoid GitCommand::run()\n{\n if (Git::Constants::debug)\n qDebug() << \"GitCommand::run\" << m_workingDirectory << m_jobs.size();\n QProcess process;\n if (!m_workingDirectory.isEmpty())\n process.setWorkingDirectory(m_workingDirectory);\n\n process.setEnvironment(m_environment);\n\n QByteArray stdOut;\n QByteArray stdErr;\n QString error;\n\n const int count = m_jobs.size();\n int exitCode = -1;\n bool ok = true;\n for (int j = 0; j < count; j++) {\n if (Git::Constants::debug)\n qDebug() << \"GitCommand::run\" << j << '\/' << count << m_jobs.at(j).arguments;\n\n process.start(m_binaryPath, m_basicArguments + m_jobs.at(j).arguments);\n if(!process.waitForStarted()) {\n ok = false;\n error += QString::fromLatin1(\"Error: \\\"%1\\\" could not be started: %2\").arg(m_binaryPath, process.errorString());\n break;\n }\n\n process.closeWriteChannel();\n const int timeOutSeconds = m_jobs.at(j).timeout;\n if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOutSeconds * 1000,\n &stdOut, &stdErr)) {\n Utils::SynchronousProcess::stopProcess(process);\n ok = false;\n error += msgTimeout(timeOutSeconds);\n break;\n }\n\n error += QString::fromLocal8Bit(stdErr);\n exitCode = process.exitCode();\n switch (m_reportTerminationMode) {\n case NoReport:\n break;\n case ReportStdout:\n stdOut += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments).toUtf8();\n break;\n case ReportStderr:\n error += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments);\n break;\n }\n }\n\n \/\/ Special hack: Always produce output for diff\n if (ok && stdOut.isEmpty() && m_jobs.front().arguments.at(0) == QLatin1String(\"diff\")) {\n stdOut += \"The file does not differ from HEAD\";\n } else {\n \/\/ @TODO: Remove, see below\n if (ok && m_jobs.front().arguments.at(0) == QLatin1String(\"status\"))\n removeColorCodes(&stdOut);\n }\n\n if (ok && !stdOut.isEmpty())\n emit outputData(stdOut);\n\n if (!error.isEmpty())\n emit errorText(error);\n\n emit finished(ok, exitCode, m_cookie);\n if (ok)\n emit success();\n \/\/ As it is used asynchronously, we need to delete ourselves\n this->deleteLater();\n}\n\n\/\/ Clean output from carriage return and ANSI color codes.\n\/\/ @TODO: Remove once all relevant commands support \"--no-color\",\n\/\/(\"status\" is missing it as of git 1.6.2)\n\nvoid GitCommand::removeColorCodes(QByteArray *data)\n{\n \/\/ Remove ansi color codes that look like \"ESC[m\"\n const QByteArray ansiColorEscape(\"\\033[\");\n int escapePos = 0;\n while (true) {\n const int nextEscapePos = data->indexOf(ansiColorEscape, escapePos);\n if (nextEscapePos == -1)\n break;\n const int endEscapePos = data->indexOf('m', nextEscapePos + ansiColorEscape.size());\n if (endEscapePos != -1) {\n data->remove(nextEscapePos, endEscapePos - nextEscapePos + 1);\n escapePos = nextEscapePos;\n } else {\n escapePos = nextEscapePos + ansiColorEscape.size();\n }\n }\n}\n\nvoid GitCommand::setCookie(const QVariant &cookie)\n{\n m_cookie = cookie;\n}\n\nQVariant GitCommand::cookie() const\n{\n return m_cookie;\n}\n\n\n} \/\/ namespace Internal\n} \/\/ namespace Git\nGit: Fix misleading status message.\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** Commercial Usage\n**\n** Licensees holding valid Qt Commercial licenses may use this file in\n** accordance with the Qt Commercial License Agreement provided with the\n** Software or, alternatively, in accordance with the terms contained in\n** a written agreement between you and Nokia.\n**\n** GNU Lesser General Public License Usage\n**\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at http:\/\/qt.nokia.com\/contact.\n**\n**************************************************************************\/\n\n#include \"gitcommand.h\"\n#include \"gitconstants.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nQ_DECLARE_METATYPE(QVariant)\n\nnamespace Git {\nnamespace Internal {\n\nstatic QString msgTermination(int exitCode, const QString &binaryPath, const QStringList &args)\n{\n QString cmd = QFileInfo(binaryPath).baseName();\n if (!args.empty()) {\n cmd += QLatin1Char(' ');\n cmd += args.front();\n }\n return exitCode ?\n QCoreApplication::translate(\"GitCommand\", \"\\n'%1' failed (exit code %2).\\n\").arg(cmd).arg(exitCode) :\n QCoreApplication::translate(\"GitCommand\", \"\\n'%1' completed (exit code %2).\\n\").arg(cmd).arg(exitCode);\n}\n\nGitCommand::Job::Job(const QStringList &a, int t) :\n arguments(a),\n timeout(t)\n{\n \/\/ Finished cookie is emitted via queued slot, needs metatype\n static const int qvMetaId = qRegisterMetaType();\n Q_UNUSED(qvMetaId)\n}\n\nGitCommand::GitCommand(const QStringList &binary,\n const QString &workingDirectory,\n const QStringList &environment,\n const QVariant &cookie) :\n m_binaryPath(binary.front()),\n m_basicArguments(binary),\n m_workingDirectory(workingDirectory),\n m_environment(environment),\n m_cookie(cookie),\n m_reportTerminationMode(NoReport)\n{\n m_basicArguments.pop_front();\n}\n\nGitCommand::TerminationReportMode GitCommand::reportTerminationMode() const\n{\n return m_reportTerminationMode;\n}\n\nvoid GitCommand::setTerminationReportMode(TerminationReportMode m)\n{\n m_reportTerminationMode = m;\n}\n\nvoid GitCommand::addJob(const QStringList &arguments, int timeout)\n{\n m_jobs.push_back(Job(arguments, timeout));\n}\n\nvoid GitCommand::execute()\n{\n if (Git::Constants::debug)\n qDebug() << \"GitCommand::execute\" << m_workingDirectory << m_jobs.size();\n\n if (m_jobs.empty())\n return;\n\n \/\/ For some reason QtConcurrent::run() only works on this\n QFuture task = QtConcurrent::run(this, &GitCommand::run);\n const QString taskName = QLatin1String(\"Git \") + m_jobs.front().arguments.at(0);\n\n Core::ICore::instance()->progressManager()->addTask(task, taskName,\n QLatin1String(\"Git.action\"));\n}\n\nQString GitCommand::msgTimeout(int seconds)\n{\n return tr(\"Error: Git timed out after %1s.\").arg(seconds);\n}\n\nvoid GitCommand::run()\n{\n if (Git::Constants::debug)\n qDebug() << \"GitCommand::run\" << m_workingDirectory << m_jobs.size();\n QProcess process;\n if (!m_workingDirectory.isEmpty())\n process.setWorkingDirectory(m_workingDirectory);\n\n process.setEnvironment(m_environment);\n\n QByteArray stdOut;\n QByteArray stdErr;\n QString error;\n\n const int count = m_jobs.size();\n int exitCode = -1;\n bool ok = true;\n for (int j = 0; j < count; j++) {\n if (Git::Constants::debug)\n qDebug() << \"GitCommand::run\" << j << '\/' << count << m_jobs.at(j).arguments;\n\n process.start(m_binaryPath, m_basicArguments + m_jobs.at(j).arguments);\n if(!process.waitForStarted()) {\n ok = false;\n error += QString::fromLatin1(\"Error: \\\"%1\\\" could not be started: %2\").arg(m_binaryPath, process.errorString());\n break;\n }\n\n process.closeWriteChannel();\n const int timeOutSeconds = m_jobs.at(j).timeout;\n if (!Utils::SynchronousProcess::readDataFromProcess(process, timeOutSeconds * 1000,\n &stdOut, &stdErr)) {\n Utils::SynchronousProcess::stopProcess(process);\n ok = false;\n error += msgTimeout(timeOutSeconds);\n break;\n }\n\n error += QString::fromLocal8Bit(stdErr);\n exitCode = process.exitCode();\n switch (m_reportTerminationMode) {\n case NoReport:\n break;\n case ReportStdout:\n stdOut += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments).toUtf8();\n break;\n case ReportStderr:\n error += msgTermination(exitCode, m_binaryPath, m_jobs.at(j).arguments);\n break;\n }\n }\n\n \/\/ Special hack: Always produce output for diff\n if (ok && stdOut.isEmpty() && m_jobs.front().arguments.at(0) == QLatin1String(\"diff\")) {\n stdOut += \"No difference to HEAD\";\n } else {\n \/\/ @TODO: Remove, see below\n if (ok && m_jobs.front().arguments.at(0) == QLatin1String(\"status\"))\n removeColorCodes(&stdOut);\n }\n\n if (ok && !stdOut.isEmpty())\n emit outputData(stdOut);\n\n if (!error.isEmpty())\n emit errorText(error);\n\n emit finished(ok, exitCode, m_cookie);\n if (ok)\n emit success();\n \/\/ As it is used asynchronously, we need to delete ourselves\n this->deleteLater();\n}\n\n\/\/ Clean output from carriage return and ANSI color codes.\n\/\/ @TODO: Remove once all relevant commands support \"--no-color\",\n\/\/(\"status\" is missing it as of git 1.6.2)\n\nvoid GitCommand::removeColorCodes(QByteArray *data)\n{\n \/\/ Remove ansi color codes that look like \"ESC[m\"\n const QByteArray ansiColorEscape(\"\\033[\");\n int escapePos = 0;\n while (true) {\n const int nextEscapePos = data->indexOf(ansiColorEscape, escapePos);\n if (nextEscapePos == -1)\n break;\n const int endEscapePos = data->indexOf('m', nextEscapePos + ansiColorEscape.size());\n if (endEscapePos != -1) {\n data->remove(nextEscapePos, endEscapePos - nextEscapePos + 1);\n escapePos = nextEscapePos;\n } else {\n escapePos = nextEscapePos + ansiColorEscape.size();\n }\n }\n}\n\nvoid GitCommand::setCookie(const QVariant &cookie)\n{\n m_cookie = cookie;\n}\n\nQVariant GitCommand::cookie() const\n{\n return m_cookie;\n}\n\n\n} \/\/ namespace Internal\n} \/\/ namespace Git\n<|endoftext|>"} {"text":"#include \"SkFontHost.h\"\n#include \n\n\/\/ define this to use pre-compiled tables for gamma. This is slightly faster,\n\/\/ and doesn't create any RW global memory, but means we cannot change the\n\/\/ gamma at runtime.\n#define USE_PREDEFINED_GAMMA_TABLES\n\n#ifndef USE_PREDEFINED_GAMMA_TABLES\n \/\/ define this if you want to spew out the \"C\" code for the tables, given\n \/\/ the current values for SK_BLACK_GAMMA and SK_WHITE_GAMMA.\n #define DUMP_GAMMA_TABLESx\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifdef USE_PREDEFINED_GAMMA_TABLES\n\n#include \"sk_predefined_gamma.h\"\n\n#else \/\/ use writable globals for gamma tables\n\nstatic bool gGammaIsBuilt;\nstatic uint8_t gBlackGamma[256], gWhiteGamma[256];\n\n#define SK_BLACK_GAMMA (1.4f)\n#define SK_WHITE_GAMMA (1\/1.4f)\n\nstatic void build_power_table(uint8_t table[], float ee)\n{\n \/\/ printf(\"------ build_power_table %g\\n\", ee);\n for (int i = 0; i < 256; i++)\n {\n float x = i \/ 255.f;\n \/\/ printf(\" %d %g\", i, x);\n x = powf(x, ee);\n \/\/ printf(\" %g\", x);\n int xx = SkScalarRound(SkFloatToScalar(x * 255));\n \/\/ printf(\" %d\\n\", xx);\n table[i] = SkToU8(xx);\n }\n}\n\n#ifdef DUMP_GAMMA_TABLES\n\n#include \"SkString.h\"\n\nstatic void dump_a_table(const char name[], const uint8_t table[],\n float gamma) {\n SkDebugf(\"\\n\");\n SkDebugf(\"\\\/\\\/ Gamma table for %g\\n\", gamma);\n SkDebugf(\"static const uint8_t %s[] = {\\n\", name);\n for (int y = 0; y < 16; y++) {\n SkString line, tmp;\n for (int x = 0; x < 16; x++) {\n tmp.printf(\"0x%02X, \", *table++);\n line.append(tmp);\n }\n SkDebugf(\" %s\\n\", line.c_str());\n }\n SkDebugf(\"};\\n\");\n}\n\n#endif\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkFontHost::GetGammaTables(const uint8_t* tables[2])\n{\n#ifndef USE_PREDEFINED_GAMMA_TABLES\n if (!gGammaIsBuilt)\n {\n build_power_table(gBlackGamma, SK_BLACK_GAMMA);\n build_power_table(gWhiteGamma, SK_WHITE_GAMMA);\n gGammaIsBuilt = true;\n\n#ifdef DUMP_GAMMA_TABLES\n dump_a_table(\"gBlackGamma\", gBlackGamma, SK_BLACK_GAMMA);\n dump_a_table(\"gWhiteGamma\", gWhiteGamma, SK_WHITE_GAMMA);\n#endif\n }\n#endif\n tables[0] = gBlackGamma;\n tables[1] = gWhiteGamma;\n}\n\n\/\/ If the luminance is <= this value, then apply the black gamma table\n#define BLACK_GAMMA_THRESHOLD 0x40\n\n\/\/ If the luminance is >= this value, then apply the white gamma table\n#define WHITE_GAMMA_THRESHOLD 0xC0\n\nint SkFontHost::ComputeGammaFlag(const SkPaint& paint)\n{\n if (paint.getShader() == NULL)\n {\n SkColor c = paint.getColor();\n int r = SkColorGetR(c);\n int g = SkColorGetG(c);\n int b = SkColorGetB(c);\n int luminance = (r * 2 + g * 5 + b) >> 3;\n \n if (luminance <= BLACK_GAMMA_THRESHOLD)\n {\n \/\/ printf(\"------ black gamma for [%d %d %d]\\n\", r, g, b);\n return SkScalerContext::kGammaForBlack_Flag;\n }\n if (luminance >= WHITE_GAMMA_THRESHOLD)\n {\n \/\/ printf(\"------ white gamma for [%d %d %d]\\n\", r, g, b);\n return SkScalerContext::kGammaForWhite_Flag;\n }\n }\n return 0;\n}\n\nallow the gamma to be changed at runtime#include \"SkFontHost.h\"\n#include \n\n\/\/ define this to use pre-compiled tables for gamma. This is slightly faster,\n\/\/ and doesn't create any RW global memory, but means we cannot change the\n\/\/ gamma at runtime.\n\/\/#define USE_PREDEFINED_GAMMA_TABLES\n\n#ifndef USE_PREDEFINED_GAMMA_TABLES\n \/\/ define this if you want to spew out the \"C\" code for the tables, given\n \/\/ the current values for SK_BLACK_GAMMA and SK_WHITE_GAMMA.\n #define DUMP_GAMMA_TABLESx\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"SkGraphics.h\"\n\n\/\/ declared here, so we can link against it elsewhere\nvoid skia_set_text_gamma(float blackGamma, float whiteGamma);\n\n#ifdef USE_PREDEFINED_GAMMA_TABLES\n\n#include \"sk_predefined_gamma.h\"\n\nvoid skia_set_text_gamma(float blackGamma, float whiteGamma) {}\n\n#else \/\/ use writable globals for gamma tables\n\nstatic void build_power_table(uint8_t table[], float ee)\n{\n SkDebugf(\"------ build_power_table %g\\n\", ee);\n for (int i = 0; i < 256; i++)\n {\n float x = i \/ 255.f;\n \/\/ printf(\" %d %g\", i, x);\n x = powf(x, ee);\n \/\/ printf(\" %g\", x);\n int xx = SkScalarRound(SkFloatToScalar(x * 255));\n \/\/ printf(\" %d\\n\", xx);\n table[i] = SkToU8(xx);\n }\n}\n\nstatic bool gGammaIsBuilt;\nstatic uint8_t gBlackGamma[256], gWhiteGamma[256];\n\nstatic float gBlackGammaCoeff = 1.4f;\nstatic float gWhiteGammaCoeff = 1\/1.4f;\n\nvoid skia_set_text_gamma(float blackGamma, float whiteGamma) {\n gBlackGammaCoeff = blackGamma;\n gWhiteGammaCoeff = whiteGamma;\n gGammaIsBuilt = false;\n SkGraphics::SetFontCacheUsed(0);\n build_power_table(gBlackGamma, gBlackGammaCoeff);\n build_power_table(gWhiteGamma, gWhiteGammaCoeff);\n}\n\n#ifdef DUMP_GAMMA_TABLES\n\n#include \"SkString.h\"\n\nstatic void dump_a_table(const char name[], const uint8_t table[],\n float gamma) {\n SkDebugf(\"\\n\");\n SkDebugf(\"\\\/\\\/ Gamma table for %g\\n\", gamma);\n SkDebugf(\"static const uint8_t %s[] = {\\n\", name);\n for (int y = 0; y < 16; y++) {\n SkString line, tmp;\n for (int x = 0; x < 16; x++) {\n tmp.printf(\"0x%02X, \", *table++);\n line.append(tmp);\n }\n SkDebugf(\" %s\\n\", line.c_str());\n }\n SkDebugf(\"};\\n\");\n}\n\n#endif\n\n#endif\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid SkFontHost::GetGammaTables(const uint8_t* tables[2])\n{\n#ifndef USE_PREDEFINED_GAMMA_TABLES\n if (!gGammaIsBuilt)\n {\n build_power_table(gBlackGamma, gBlackGammaCoeff);\n build_power_table(gWhiteGamma, gWhiteGammaCoeff);\n gGammaIsBuilt = true;\n\n#ifdef DUMP_GAMMA_TABLES\n dump_a_table(\"gBlackGamma\", gBlackGamma, gBlackGammaCoeff);\n dump_a_table(\"gWhiteGamma\", gWhiteGamma, gWhiteGammaCoeff);\n#endif\n }\n#endif\n tables[0] = gBlackGamma;\n tables[1] = gWhiteGamma;\n}\n\n\/\/ If the luminance is <= this value, then apply the black gamma table\n#define BLACK_GAMMA_THRESHOLD 0x40\n\n\/\/ If the luminance is >= this value, then apply the white gamma table\n#define WHITE_GAMMA_THRESHOLD 0xC0\n\nint SkFontHost::ComputeGammaFlag(const SkPaint& paint)\n{\n if (paint.getShader() == NULL)\n {\n SkColor c = paint.getColor();\n int r = SkColorGetR(c);\n int g = SkColorGetG(c);\n int b = SkColorGetB(c);\n int luminance = (r * 2 + g * 5 + b) >> 3;\n \n if (luminance <= BLACK_GAMMA_THRESHOLD)\n {\n \/\/ printf(\"------ black gamma for [%d %d %d]\\n\", r, g, b);\n return SkScalerContext::kGammaForBlack_Flag;\n }\n if (luminance >= WHITE_GAMMA_THRESHOLD)\n {\n \/\/ printf(\"------ white gamma for [%d %d %d]\\n\", r, g, b);\n return SkScalerContext::kGammaForWhite_Flag;\n }\n }\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/\/ Gets a shared vector for a row\nSHAREDVECTORN row(unsigned i)\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + i;\n v._inc = leading_dim();\n v._len = _columns;\n return v;\n}\n\n\/\/\/ Gets a constant shared vector for a row\nCONST_SHAREDVECTORN row(unsigned i) const\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n CONST_SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + i;\n v._inc = leading_dim();\n v._len = _columns;\n return v;\n}\n\n\/\/\/ Gets a shared vector for a column \nSHAREDVECTORN column(unsigned i)\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + leading_dim() * i;\n v._inc = 1;\n v._len = _rows;\n return v;\n}\n\n\/\/\/ Gets a shared vector for a column \nCONST_SHAREDVECTORN column(unsigned i) const\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n CONST_SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + leading_dim() * i;\n v._inc = 1;\n v._len = _rows;\n return v;\n}\n\n\/\/\/ Gets a block as a shared matrix\nSHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end)\n{\n #ifndef NEXCEPT\n if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)\n throw InvalidIndexException();\n #endif\n\n \/\/ determine the offset\n const unsigned OFFSET = data() - _data.get();\n\n SHAREDMATRIXN m;\n m._data = _data;\n m._rows = row_end - row_start;\n m._columns = col_end - col_start;\n m._ld = leading_dim();\n m._start = OFFSET + m._ld * col_start + row_start;\n return m; \n}\n\n\/\/\/ Gets a block as a constant shared matrix\nCONST_SHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) const\n{\n #ifndef NEXCEPT\n if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)\n throw InvalidIndexException();\n #endif\n\n \/\/ determine the offset\n const unsigned OFFSET = data() - _data.get();\n\n CONST_SHAREDMATRIXN m;\n m._data = _data;\n m._rows = row_end - row_start;\n m._columns = col_end - col_start;\n m._ld = leading_dim();\n m._start = OFFSET + m._ld * col_start + row_start;\n return m; \n}\n\n\n\/\/\/ Get an iterator to the beginning \nITERATOR begin()\n{\n ITERATOR i;\n i._count = 0;\n i._sz = _rows*_columns;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = i._current_data = data();\n return i;\n}\n\n\/\/\/ Get an iterator to the end\nITERATOR end()\n{\n ITERATOR i;\n i._sz = _rows*_columns;\n i._count = i._sz;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = data();\n i._current_data = data() + i._ld*i._columns;\n return i;\n}\n\n\/\/\/ Get an iterator to the beginning \nCONST_ITERATOR begin() const\n{\n CONST_ITERATOR i;\n i._count = 0;\n i._sz = _rows*_columns;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = i._current_data = data();\n return i;\n}\n\n\/\/\/ Get an iterator to the end\nCONST_ITERATOR end() const\n{\n CONST_ITERATOR i;\n i._sz = _rows*_columns;\n i._count = i._sz;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = data();\n i._current_data = data() + i._ld*i._columns;\n return i;\n}\n\n\/\/\/ Sets a matrix from a vector\ntemplate \nXMATRIXN& set(const V& v, Transposition trans)\n{\n #ifndef NEXCEPT\n if (sizeof(data()) != sizeof(v.data()))\n throw DataMismatchException();\n #endif\n\n \/\/ resize the matrix\n if (trans == eNoTranspose)\n resize(v.size(), 1);\n else\n resize(1, v.size());\n\n if (_rows > 0 && _columns > 0)\n CBLAS::copy(v.size(), v.data(), 1, _data.get(), 1);\n\n return *this;\n}\n\n\/\/\/ Determines the transpose of a matrix and stores the result in a given matrix\ntemplate \nstatic M& transpose(const XMATRIXN& m, M& result)\n{\n #ifndef NEXCEPT\n if (sizeof(m.data()) != sizeof(result.data()))\n throw DataMismatchException();\n #endif\n\n \/\/ resize the result\n result.resize(m.columns(), m.rows());\n\n const REAL* mdata = m.data();\n REAL* rdata = result.data();\n for (unsigned i=0; i< m.rows(); i++)\n for (unsigned j=0; j< m.columns(); j++)\n rdata[i*result.leading_dim()+j] = mdata[j*m.leading_dim()+i];\n \n return result;\n}\n\n\/\/\/ Adds m to *this in place\ntemplate \nXMATRIXN& operator+=(const M& m)\n{\n #ifndef NEXCEPT\n if (_rows != m.rows() || _columns != m.columns())\n throw MissizeException(); \n if (sizeof(data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n\n if (_rows > 0 && _columns > 0) \n std::transform(begin(), end(), m.begin(), begin(), std::plus());\n return *this;\n}\n\n\/\/\/ Subtracts m from *this in place\ntemplate \nXMATRIXN& operator-=(const M& m)\n{\n #ifndef NEXCEPT\n if (_rows != m.rows() || _columns != m.columns())\n throw MissizeException(); \n if (sizeof(data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n \n if (_rows > 0 && _columns > 0) \n std::transform(begin(), end(), m.begin(), begin(), std::minus());\n return *this;\n}\n\n\/\/\/ Multiplies the diagonal matrix formed from d by the matrix m\ntemplate \nstatic W& diag_mult(const V& d, const XMATRIXN& m, W& result)\n{\n #ifndef NEXCEPT\n if (d.size() != m.rows())\n throw MissizeException();\n if (sizeof(d.data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n\n result.resize(d.size(), m.columns());\n for (unsigned i=0; i< m.columns(); i++)\n std::transform(d.begin(), d.end(), m.begin()+m.rows()*i, result.begin()+result.rows()*i, std::multiplies());\n\n return result;\n}\n\n\/\/\/ Multiplies the diagonal matrix formed from d by the matrix transpose(m)\ntemplate \nstatic W& diag_mult_transpose(const V& d, const XMATRIXN& m, W& result)\n{\n #ifndef NEXCEPT\n if (d.size() != m.columns())\n throw MissizeException();\n if (sizeof(d.data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n\n \/\/ copy the transpose of m to the result\n XMATRIXN::transpose(m, result);\n\n \/\/ do the specified number of times\n for (unsigned i=0; i< m.rows(); i++)\n CBLAS::scal(d.size(), d[i], result.begin()+i, result.rows());\n\n return result;\n}\n\n\/\/\/ Multiplies the diagonal matrix formed from d by the vector v\ntemplate \nstatic W& diag_mult(const V& d, const U& v, W& result)\n{\n #ifndef NEXCEPT\n if (d.size() != v.size())\n throw MissizeException();\n if (sizeof(d.data()) != sizeof(v.data()))\n throw DataMismatchException();\n if (sizeof(d.data()) != sizeof(result.data()))\n throw DataMismatchException();\n #endif\n\n result.resize(d.size());\n std::transform(d.begin(), d.end(), v.begin(), result.begin(), std::multiplies());\n return result;\n}\n\nFixed compile bug in MatrixN::diag_mult_transpose()?\/\/\/ Gets a shared vector for a row\nSHAREDVECTORN row(unsigned i)\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + i;\n v._inc = leading_dim();\n v._len = _columns;\n return v;\n}\n\n\/\/\/ Gets a constant shared vector for a row\nCONST_SHAREDVECTORN row(unsigned i) const\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n CONST_SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + i;\n v._inc = leading_dim();\n v._len = _columns;\n return v;\n}\n\n\/\/\/ Gets a shared vector for a column \nSHAREDVECTORN column(unsigned i)\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + leading_dim() * i;\n v._inc = 1;\n v._len = _rows;\n return v;\n}\n\n\/\/\/ Gets a shared vector for a column \nCONST_SHAREDVECTORN column(unsigned i) const\n{\n \/\/ get the starting offset\n const unsigned OFFSET = data() - _data.get();\n\n CONST_SHAREDVECTORN v;\n v._data = _data;\n v._start = OFFSET + leading_dim() * i;\n v._inc = 1;\n v._len = _rows;\n return v;\n}\n\n\/\/\/ Gets a block as a shared matrix\nSHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end)\n{\n #ifndef NEXCEPT\n if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)\n throw InvalidIndexException();\n #endif\n\n \/\/ determine the offset\n const unsigned OFFSET = data() - _data.get();\n\n SHAREDMATRIXN m;\n m._data = _data;\n m._rows = row_end - row_start;\n m._columns = col_end - col_start;\n m._ld = leading_dim();\n m._start = OFFSET + m._ld * col_start + row_start;\n return m; \n}\n\n\/\/\/ Gets a block as a constant shared matrix\nCONST_SHAREDMATRIXN block(unsigned row_start, unsigned row_end, unsigned col_start, unsigned col_end) const\n{\n #ifndef NEXCEPT\n if (row_end < row_start || row_end > _rows || col_end < col_start || col_end > _columns)\n throw InvalidIndexException();\n #endif\n\n \/\/ determine the offset\n const unsigned OFFSET = data() - _data.get();\n\n CONST_SHAREDMATRIXN m;\n m._data = _data;\n m._rows = row_end - row_start;\n m._columns = col_end - col_start;\n m._ld = leading_dim();\n m._start = OFFSET + m._ld * col_start + row_start;\n return m; \n}\n\n\n\/\/\/ Get an iterator to the beginning \nITERATOR begin()\n{\n ITERATOR i;\n i._count = 0;\n i._sz = _rows*_columns;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = i._current_data = data();\n return i;\n}\n\n\/\/\/ Get an iterator to the end\nITERATOR end()\n{\n ITERATOR i;\n i._sz = _rows*_columns;\n i._count = i._sz;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = data();\n i._current_data = data() + i._ld*i._columns;\n return i;\n}\n\n\/\/\/ Get an iterator to the beginning \nCONST_ITERATOR begin() const\n{\n CONST_ITERATOR i;\n i._count = 0;\n i._sz = _rows*_columns;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = i._current_data = data();\n return i;\n}\n\n\/\/\/ Get an iterator to the end\nCONST_ITERATOR end() const\n{\n CONST_ITERATOR i;\n i._sz = _rows*_columns;\n i._count = i._sz;\n i._ld = leading_dim();\n i._rows = _rows;\n i._columns = _columns;\n i._data_start = data();\n i._current_data = data() + i._ld*i._columns;\n return i;\n}\n\n\/\/\/ Sets a matrix from a vector\ntemplate \nXMATRIXN& set(const V& v, Transposition trans)\n{\n #ifndef NEXCEPT\n if (sizeof(data()) != sizeof(v.data()))\n throw DataMismatchException();\n #endif\n\n \/\/ resize the matrix\n if (trans == eNoTranspose)\n resize(v.size(), 1);\n else\n resize(1, v.size());\n\n if (_rows > 0 && _columns > 0)\n CBLAS::copy(v.size(), v.data(), 1, _data.get(), 1);\n\n return *this;\n}\n\n\/\/\/ Determines the transpose of a matrix and stores the result in a given matrix\ntemplate \nstatic M& transpose(const XMATRIXN& m, M& result)\n{\n #ifndef NEXCEPT\n if (sizeof(m.data()) != sizeof(result.data()))\n throw DataMismatchException();\n #endif\n\n \/\/ resize the result\n result.resize(m.columns(), m.rows());\n\n const REAL* mdata = m.data();\n REAL* rdata = result.data();\n for (unsigned i=0; i< m.rows(); i++)\n for (unsigned j=0; j< m.columns(); j++)\n rdata[i*result.leading_dim()+j] = mdata[j*m.leading_dim()+i];\n \n return result;\n}\n\n\/\/\/ Adds m to *this in place\ntemplate \nXMATRIXN& operator+=(const M& m)\n{\n #ifndef NEXCEPT\n if (_rows != m.rows() || _columns != m.columns())\n throw MissizeException(); \n if (sizeof(data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n\n if (_rows > 0 && _columns > 0) \n std::transform(begin(), end(), m.begin(), begin(), std::plus());\n return *this;\n}\n\n\/\/\/ Subtracts m from *this in place\ntemplate \nXMATRIXN& operator-=(const M& m)\n{\n #ifndef NEXCEPT\n if (_rows != m.rows() || _columns != m.columns())\n throw MissizeException(); \n if (sizeof(data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n \n if (_rows > 0 && _columns > 0) \n std::transform(begin(), end(), m.begin(), begin(), std::minus());\n return *this;\n}\n\n\/\/\/ Multiplies the diagonal matrix formed from d by the matrix m\ntemplate \nstatic W& diag_mult(const V& d, const XMATRIXN& m, W& result)\n{\n #ifndef NEXCEPT\n if (d.size() != m.rows())\n throw MissizeException();\n if (sizeof(d.data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n\n result.resize(d.size(), m.columns());\n for (unsigned i=0; i< m.columns(); i++)\n std::transform(d.begin(), d.end(), m.begin()+m.rows()*i, result.begin()+result.rows()*i, std::multiplies());\n\n return result;\n}\n\n\/\/\/ Multiplies the diagonal matrix formed from d by the matrix transpose(m)\ntemplate \nstatic W& diag_mult_transpose(const V& d, const XMATRIXN& m, W& result)\n{\n #ifndef NEXCEPT\n if (d.size() != m.columns())\n throw MissizeException();\n if (sizeof(d.data()) != sizeof(m.data()))\n throw DataMismatchException();\n #endif\n\n \/\/ copy the transpose of m to the result\n XMATRIXN::transpose(m, result);\n\n \/\/ do the specified number of times\n for (unsigned i=0; i< m.rows(); i++)\n CBLAS::scal(d.size(), d[i], result.data()+i, result.lda());\n\n return result;\n}\n\n\/\/\/ Multiplies the diagonal matrix formed from d by the vector v\ntemplate \nstatic W& diag_mult(const V& d, const U& v, W& result)\n{\n #ifndef NEXCEPT\n if (d.size() != v.size())\n throw MissizeException();\n if (sizeof(d.data()) != sizeof(v.data()))\n throw DataMismatchException();\n if (sizeof(d.data()) != sizeof(result.data()))\n throw DataMismatchException();\n #endif\n\n result.resize(d.size());\n std::transform(d.begin(), d.end(), v.begin(), result.begin(), std::multiplies());\n return result;\n}\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n * Copyright (C) 2012-2015 by Savoir-Faire Linux *\n * Author : Alexandre Lision *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program. If not, see . *\n ***************************************************************************\/\n#include \"directrenderer.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef CLOCK_REALTIME\n#define CLOCK_REALTIME 0\n#endif\n\n#include \"private\/videorenderermanager.h\"\n#include \"video\/resolution.h\"\n#include \"private\/videorenderer_p.h\"\n\nnamespace Video {\n\nclass DirectRendererPrivate : public QObject\n{\n Q_OBJECT\npublic:\n DirectRendererPrivate(Video::DirectRenderer* parent);\nprivate:\n\/\/ Video::DirectRenderer* q_ptr;\n};\n\n}\n\nVideo::DirectRendererPrivate::DirectRendererPrivate(Video::DirectRenderer* parent) : QObject(parent)\/*, q_ptr(parent)*\/\n{\n}\n\n\/\/\/Constructor\nVideo::DirectRenderer::DirectRenderer(const QByteArray& id, const QSize& res): Renderer(id, res), d_ptr(new DirectRendererPrivate(this))\n{\n setObjectName(\"Video::DirectRenderer:\"+id);\n}\n\n\/\/\/Destructor\nVideo::DirectRenderer::~DirectRenderer()\n{\n}\n\nvoid Video::DirectRenderer::startRendering()\n{\n Video::Renderer::d_ptr->m_isRendering = true;\n emit started();\n}\nvoid Video::DirectRenderer::stopRendering ()\n{\n Video::Renderer::d_ptr->m_isRendering = false;\n emit stopped();\n}\n\nvoid Video::DirectRenderer::onNewFrame(const std::shared_ptr >& frame, int w, int h)\n{\n if (!isRendering()) {\n return;\n }\n\n Video::Renderer::d_ptr->m_pSize.setWidth(w);\n Video::Renderer::d_ptr->m_pSize.setHeight(h);\n Video::Renderer::d_ptr->m_pSFrame = frame;\n emit frameUpdated();\n}\n\nVideo::Renderer::ColorSpace Video::DirectRenderer::colorSpace() const\n{\n return Video::Renderer::ColorSpace::RGBA;\n}\n\n#include \nvideo: return the correct colorspace\/****************************************************************************\n * Copyright (C) 2012-2015 by Savoir-Faire Linux *\n * Author : Alexandre Lision *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of the GNU Lesser General Public *\n * License as published by the Free Software Foundation; either *\n * version 2.1 of the License, or (at your option) any later version. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU *\n * Lesser General Public License for more details. *\n * *\n * You should have received a copy of the GNU General Public License *\n * along with this program. If not, see . *\n ***************************************************************************\/\n#include \"directrenderer.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef CLOCK_REALTIME\n#define CLOCK_REALTIME 0\n#endif\n\n#include \"private\/videorenderermanager.h\"\n#include \"video\/resolution.h\"\n#include \"private\/videorenderer_p.h\"\n\nnamespace Video {\n\nclass DirectRendererPrivate : public QObject\n{\n Q_OBJECT\npublic:\n DirectRendererPrivate(Video::DirectRenderer* parent);\nprivate:\n\/\/ Video::DirectRenderer* q_ptr;\n};\n\n}\n\nVideo::DirectRendererPrivate::DirectRendererPrivate(Video::DirectRenderer* parent) : QObject(parent)\/*, q_ptr(parent)*\/\n{\n}\n\n\/\/\/Constructor\nVideo::DirectRenderer::DirectRenderer(const QByteArray& id, const QSize& res): Renderer(id, res), d_ptr(new DirectRendererPrivate(this))\n{\n setObjectName(\"Video::DirectRenderer:\"+id);\n}\n\n\/\/\/Destructor\nVideo::DirectRenderer::~DirectRenderer()\n{\n}\n\nvoid Video::DirectRenderer::startRendering()\n{\n Video::Renderer::d_ptr->m_isRendering = true;\n emit started();\n}\nvoid Video::DirectRenderer::stopRendering ()\n{\n Video::Renderer::d_ptr->m_isRendering = false;\n emit stopped();\n}\n\nvoid Video::DirectRenderer::onNewFrame(const std::shared_ptr >& frame, int w, int h)\n{\n if (!isRendering()) {\n return;\n }\n\n Video::Renderer::d_ptr->m_pSize.setWidth(w);\n Video::Renderer::d_ptr->m_pSize.setHeight(h);\n Video::Renderer::d_ptr->m_pSFrame = frame;\n emit frameUpdated();\n}\n\nVideo::Renderer::ColorSpace Video::DirectRenderer::colorSpace() const\n{\n#ifdef Q_OS_DARWIN\n return Video::Renderer::ColorSpace::RGBA;\n#else\n return Video::Renderer::ColorSpace::BGRA;\n#endif\n}\n\n#include \n<|endoftext|>"} {"text":"#ifndef OSRM_CONTRACTOR_FILES_HPP\n#define OSRM_CONTRACTOR_FILES_HPP\n\n#include \"contractor\/query_graph.hpp\"\n\n#include \"util\/serialization.hpp\"\n\n#include \"storage\/io.hpp\"\n\nnamespace osrm\n{\nnamespace contractor\n{\nnamespace files\n{\n\n\/\/ reads .osrm.hsgr file\ntemplate\ninline void readGraph(const boost::filesystem::path &path,\n unsigned &checksum,\n detail::QueryGraph &graph)\n{\n const auto fingerprint = storage::io::FileReader::VerifyFingerprint;\n storage::io::FileReader reader{path, fingerprint};\n\n reader.ReadInto(checksum);\n util::serialization::read(reader, graph);\n}\n\n\/\/ writes .osrm.hsgr file\ntemplate\ninline void writeGraph(const boost::filesystem::path &path,\n unsigned checksum,\n const detail::QueryGraph &graph)\n{\n const auto fingerprint = storage::io::FileWriter::GenerateFingerprint;\n storage::io::FileWriter writer{path, fingerprint};\n\n writer.WriteOne(checksum);\n util::serialization::write(writer, graph);\n}\n\n}\n}\n}\n\n#endif\nFix readGraph to not use UseSharedMemory#ifndef OSRM_CONTRACTOR_FILES_HPP\n#define OSRM_CONTRACTOR_FILES_HPP\n\n#include \"contractor\/query_graph.hpp\"\n\n#include \"util\/serialization.hpp\"\n\n#include \"storage\/io.hpp\"\n\nnamespace osrm\n{\nnamespace contractor\n{\nnamespace files\n{\n\n\/\/ reads .osrm.hsgr file\ntemplate \ninline void readGraph(const boost::filesystem::path &path, unsigned &checksum, QueryGraphT &graph)\n{\n static_assert(std::is_same::value ||\n std::is_same::value,\n \"graph must be of type QueryGraph<>\");\n\n const auto fingerprint = storage::io::FileReader::VerifyFingerprint;\n storage::io::FileReader reader{path, fingerprint};\n\n reader.ReadInto(checksum);\n util::serialization::read(reader, graph);\n}\n\n\/\/ writes .osrm.hsgr file\ntemplate \ninline void\nwriteGraph(const boost::filesystem::path &path, unsigned checksum, const QueryGraphT &graph)\n{\n static_assert(std::is_same::value ||\n std::is_same::value,\n \"graph must be of type QueryGraph<>\");\n const auto fingerprint = storage::io::FileWriter::GenerateFingerprint;\n storage::io::FileWriter writer{path, fingerprint};\n\n writer.WriteOne(checksum);\n util::serialization::write(writer, graph);\n}\n}\n}\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_ANY_HPP\n#define MAPNIK_IMAGE_ANY_HPP\n\n#include \n#include \n#include \n\nnamespace mapnik {\n\nusing image_base = util::variant;\n\n\nstruct MAPNIK_DECL image_any : image_base\n{\n image_any() = default;\n\n image_any(int width,\n int height,\n image_dtype type = image_dtype_rgba8,\n bool initialize = true,\n bool premultiplied = false,\n bool painted = false);\n\n template \n image_any(T && data) noexcept\n : image_base(std::move(data)) {}\n\n unsigned char const* bytes() const;\n unsigned char* bytes();\n std::size_t width() const;\n std::size_t height() const;\n bool get_premultiplied() const;\n bool painted() const;\n std::size_t size() const;\n std::size_t row_size() const;\n double get_offset() const;\n double get_scaling() const;\n image_dtype get_dtype() const;\n void set_offset(double val);\n void set_scaling(double val);\n};\n\nMAPNIK_DECL image_any create_image_any(int width,\n int height,\n image_dtype type = image_dtype_rgba8,\n bool initialize = true,\n bool premultiplied = false,\n bool painted = false);\n\n} \/\/ end mapnik ns\n\n#endif \/\/ MAPNIK_IMAGE_ANY_HPP\nfix variable shadowing in image_any\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2015 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_IMAGE_ANY_HPP\n#define MAPNIK_IMAGE_ANY_HPP\n\n#include \n#include \n#include \n\nnamespace mapnik {\n\nusing image_base = util::variant;\n\n\nstruct MAPNIK_DECL image_any : image_base\n{\n image_any() = default;\n\n image_any(int width,\n int height,\n image_dtype type = image_dtype_rgba8,\n bool initialize = true,\n bool premultiplied = false,\n bool painted = false);\n\n template \n image_any(T && _data) noexcept\n : image_base(std::move(_data)) {}\n\n unsigned char const* bytes() const;\n unsigned char* bytes();\n std::size_t width() const;\n std::size_t height() const;\n bool get_premultiplied() const;\n bool painted() const;\n std::size_t size() const;\n std::size_t row_size() const;\n double get_offset() const;\n double get_scaling() const;\n image_dtype get_dtype() const;\n void set_offset(double val);\n void set_scaling(double val);\n};\n\nMAPNIK_DECL image_any create_image_any(int width,\n int height,\n image_dtype type = image_dtype_rgba8,\n bool initialize = true,\n bool premultiplied = false,\n bool painted = false);\n\n} \/\/ end mapnik ns\n\n#endif \/\/ MAPNIK_IMAGE_ANY_HPP\n<|endoftext|>"} {"text":"#ifndef INCLUDED_U5E_UTF32_NATIVE_HPP\n#define INCLUDED_U5E_UTF32_NATIVE_HPP\n\n#include \n#include \n#include \n\nnamespace u5e {\n \/**\n * u5e::utf32_native\n *\n * The native utf32 encoding is built with the native 32 bit\n * integer type. It is specially more useful for cases where\n * you need to do extensive manipulation on text, since it\n * allows you to have constant random access time.\n *\/\n template \n class utf32_native {\n encoding_assertion _assertion;\n public:\n \/\/ value_type is always codepoint\n typedef codepoint value_type;\n \/\/ pointer to encoded_buffer\n typedef utf32_native* pointer;\n \/\/ const pointer to encoded_buffer\n typedef const utf32_native* const_pointer;\n \/\/ reference to encoded_buffer\n typedef utf32_native& reference;\n \/\/ size type is always size_t, regardless of encoding, in order to\n \/\/ isolate the knowledge of the encoding from the user code\n typedef std::size_t size_type;\n \/\/ difference type is always ptrdiff_t, regardrless of encoding,\n \/\/ in order to isolate the knowledge of the encoding from the user\n \/\/ code\n typedef std::ptrdiff_t difference_type;\n\n \/\/ since this is the native utf32, we can just delegate this\n typedef typename BUFFERTYPE::iterator iterator;\n typedef typename BUFFERTYPE::reverse_iterator reverse_iterator;\n typedef typename BUFFERTYPE::const_iterator const_iterator;\n typedef typename BUFFERTYPE::const_reverse_iterator const_reverse_iterator;\n\n \/**\n * Constructors\n *\/\n utf32_native() = default;\n utf32_native(const BUFFERTYPE& raw_buffer)\n : raw_buffer(raw_buffer) { };\n utf32_native& operator=(const utf32_native &other) = delete;\n \n inline iterator begin() {\n return iterator(raw_buffer.begin());\n }\n \n inline iterator end() {\n return iterator(raw_buffer.end());\n }\n \n private:\n \/\/ raw buffer as specified by the storage type\n BUFFERTYPE raw_buffer;\n };\n}\n\n#endif\nadd cbegin\/cend to utf32_native#ifndef INCLUDED_U5E_UTF32_NATIVE_HPP\n#define INCLUDED_U5E_UTF32_NATIVE_HPP\n\n#include \n#include \n#include \n\nnamespace u5e {\n \/**\n * u5e::utf32_native\n *\n * The native utf32 encoding is built with the native 32 bit\n * integer type. It is specially more useful for cases where\n * you need to do extensive manipulation on text, since it\n * allows you to have constant random access time.\n *\/\n template \n class utf32_native {\n encoding_assertion _assertion;\n public:\n \/\/ value_type is always codepoint\n typedef codepoint value_type;\n \/\/ pointer to encoded_buffer\n typedef utf32_native* pointer;\n \/\/ const pointer to encoded_buffer\n typedef const utf32_native* const_pointer;\n \/\/ reference to encoded_buffer\n typedef utf32_native& reference;\n \/\/ size type is always size_t, regardless of encoding, in order to\n \/\/ isolate the knowledge of the encoding from the user code\n typedef std::size_t size_type;\n \/\/ difference type is always ptrdiff_t, regardrless of encoding,\n \/\/ in order to isolate the knowledge of the encoding from the user\n \/\/ code\n typedef std::ptrdiff_t difference_type;\n\n \/\/ since this is the native utf32, we can just delegate this\n typedef typename BUFFERTYPE::iterator iterator;\n typedef typename BUFFERTYPE::reverse_iterator reverse_iterator;\n typedef typename BUFFERTYPE::const_iterator const_iterator;\n typedef typename BUFFERTYPE::const_reverse_iterator const_reverse_iterator;\n\n \/**\n * Constructors\n *\/\n utf32_native() = default;\n utf32_native(const BUFFERTYPE& raw_buffer)\n : raw_buffer(raw_buffer) { };\n utf32_native& operator=(const utf32_native &other) = delete;\n \n inline iterator begin() {\n return iterator(raw_buffer.begin());\n }\n \n inline iterator end() {\n return iterator(raw_buffer.end());\n }\n\n inline const_iterator cbegin() {\n return const_iterator(raw_buffer.cbegin());\n }\n \n inline const_iterator cend() {\n return const_iterator(raw_buffer.cend());\n }\n\n private:\n \/\/ raw buffer as specified by the storage type\n BUFFERTYPE raw_buffer;\n };\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/\/ \\file test_helper.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief Unit test helping routines.\n\/\/----------------------------------------------------------------------------\n\/\/ Author: Serge Aleynikov\n\/\/ Created: 2010-01-06\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (C) 2010 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#ifndef _UTXX_TEST_HELPER_HPP_\n#define _UTXX_TEST_HELPER_HPP_\n\n#include \n\n#define BOOST_CURRENT_TEST_NAME \\\n boost::unit_test::framework::current_test_case().p_name->c_str()\n\n#define UTXX_REQUIRE_NO_THROW(Expr) \\\n try { Expr; } \\\n catch (std::exception const& e) { \\\n BOOST_MESSAGE(e.what()); \\\n BOOST_REQUIRE_NO_THROW(Expr); \\\n }\n\n#define UTXX_CHECK_NO_THROW(Expr) \\\n try { Expr; } \\\n catch (std::exception const& e) { \\\n BOOST_MESSAGE(e.what()); \\\n BOOST_CHECK_NO_THROW(Expr); \\\n }\n\nnamespace utxx {\n\ninline long env(const char* a_var, long a_default) {\n const char* p = getenv(a_var);\n return p ? atoi(p) : a_default;\n}\n\ninline bool get_test_argv(const std::string& a_opt,\n const std::string& a_long_opt = \"\") {\n int argc = boost::unit_test::framework::master_test_suite().argc;\n char** argv = boost::unit_test::framework::master_test_suite().argv;\n\n if (a_opt.empty() && a_long_opt.empty()) return false;\n\n auto same = [=](const std::string& a, int i) {\n return !a.empty() && a == argv[i];\n };\n\n for (int i=1; i < argc; i++) {\n if (same(a_opt, i)) return true;\n if (same(a_long_opt, i)) return true;\n }\n\n return false;\n}\n\ninline bool get_test_argv(const std::string& a_opt,\n const std::string& a_long_opt,\n std::string& a_value) {\n int argc = boost::unit_test::framework::master_test_suite().argc;\n char** argv = boost::unit_test::framework::master_test_suite().argv;\n\n if (a_opt.empty() && a_long_opt.empty()) return false;\n\n auto same = [=](const std::string& a, int i) {\n return !a.empty() && a == argv[i] &&\n (i < argc-1 && argv[i+1][i] != '-');\n };\n\n for (int i=1; i < argc; i++) {\n if (same(a_opt, i)) { a_value = argv[++i]; return true; }\n if (same(a_long_opt, i)) { a_value = argv[++i]; return true; }\n }\n\n return false;\n}\n\n} \/\/ namespace utxx::test\n\n#endif \/\/ _UTXX_TEST_HELPER_HPP_\n\nAdd include with unit_test parameters\/\/----------------------------------------------------------------------------\n\/\/\/ \\file test_helper.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief Unit test helping routines.\n\/\/----------------------------------------------------------------------------\n\/\/ Author: Serge Aleynikov\n\/\/ Created: 2010-01-06\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (C) 2010 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#pragma once\n\n#include \n#include \n\n#define BOOST_CURRENT_TEST_NAME \\\n boost::unit_test::framework::current_test_case().p_name->c_str()\n\n#define UTXX_REQUIRE_NO_THROW(Expr) \\\n try { Expr; } \\\n catch (std::exception const& e) { \\\n BOOST_MESSAGE(e.what()); \\\n BOOST_REQUIRE_NO_THROW(Expr); \\\n }\n\n#define UTXX_CHECK_NO_THROW(Expr) \\\n try { Expr; } \\\n catch (std::exception const& e) { \\\n BOOST_MESSAGE(e.what()); \\\n BOOST_CHECK_NO_THROW(Expr); \\\n }\n\nnamespace utxx {\n\ninline long env(const char* a_var, long a_default) {\n const char* p = getenv(a_var);\n return p ? atoi(p) : a_default;\n}\n\ninline bool get_test_argv(const std::string& a_opt,\n const std::string& a_long_opt = \"\") {\n int argc = boost::unit_test::framework::master_test_suite().argc;\n char** argv = boost::unit_test::framework::master_test_suite().argv;\n\n if (a_opt.empty() && a_long_opt.empty()) return false;\n\n auto same = [=](const std::string& a, int i) {\n return !a.empty() && a == argv[i];\n };\n\n for (int i=1; i < argc; i++) {\n if (same(a_opt, i)) return true;\n if (same(a_long_opt, i)) return true;\n }\n\n return false;\n}\n\ninline bool get_test_argv(const std::string& a_opt,\n const std::string& a_long_opt,\n std::string& a_value) {\n int argc = boost::unit_test::framework::master_test_suite().argc;\n char** argv = boost::unit_test::framework::master_test_suite().argv;\n\n if (a_opt.empty() && a_long_opt.empty()) return false;\n\n auto same = [=](const std::string& a, int i) {\n return !a.empty() && a == argv[i] &&\n (i < argc-1 && argv[i+1][i] != '-');\n };\n\n for (int i=1; i < argc; i++) {\n if (same(a_opt, i)) { a_value = argv[++i]; return true; }\n if (same(a_long_opt, i)) { a_value = argv[++i]; return true; }\n }\n\n return false;\n}\n\n} \/\/ namespace utxx::test<|endoftext|>"} {"text":"\/** \n * @file lldockcontrol.cpp\n * @brief Creates a panel of a specific kind for a toast\n *\n * $LicenseInfo:firstyear=2000&license=viewergpl$\n * \n * Copyright (c) 2000-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"linden_common.h\"\n\n#include \"lldockcontrol.h\"\n#include \"lldockablefloater.h\"\n\nLLDockControl::LLDockControl(LLView* dockWidget, LLFloater* dockableFloater,\n\t\tconst LLUIImagePtr& dockTongue, DocAt dockAt, get_allowed_rect_callback_t get_allowed_rect_callback) :\n\t\tmDockWidget(dockWidget), mDockableFloater(dockableFloater), mDockTongue(dockTongue)\n{\n\tmDockAt = dockAt;\n\n\tif (dockableFloater->isDocked())\n\t{\n\t\ton();\n\t}\n\telse\n\t{\n\t\toff();\n\t}\n\n\tif (!(get_allowed_rect_callback))\n\t{\n\t\tmGetAllowedRectCallback = boost::bind(&LLDockControl::getAllowedRect, this, _1);\n\t}\n\telse\n\t{\n\t\tmGetAllowedRectCallback = get_allowed_rect_callback;\n\t}\n\n\tif (dockWidget != NULL) \n\t{\n\t\trepositionDockable();\n\t}\n\n\tif (mDockWidget != NULL)\n\t{\n\t\tmDockWidgetVisible = isDockVisible();\n\t}\n\telse\n\t{\n\t\tmDockWidgetVisible = false;\n\t}\n}\n\nLLDockControl::~LLDockControl()\n{\n}\n\nvoid LLDockControl::setDock(LLView* dockWidget)\n{\n\tmDockWidget = dockWidget;\n\tif (mDockWidget != NULL)\n\t{\n\t\trepositionDockable();\n\t\tmDockWidgetVisible = isDockVisible();\n\t}\n\telse\n\t{\n\t\tmDockWidgetVisible = false;\n\t}\n}\n\nvoid LLDockControl::getAllowedRect(LLRect& rect)\n{\n\trect = mDockableFloater->getRootView()->getRect();\n}\n\nvoid LLDockControl::repositionDockable()\n{\n\tLLRect dockRect = mDockWidget->calcScreenRect();\n\tLLRect rootRect;\n\tmGetAllowedRectCallback(rootRect);\n\n\t\/\/ recalculate dockable position if dock position changed, dock visibility changed,\n\t\/\/ root view rect changed or recalculation is forced\n\tif (mPrevDockRect != dockRect || mDockWidgetVisible != isDockVisible()\n\t\t\t|| mRootRect != rootRect || mRecalculateDocablePosition)\n\t{\n\t\t\/\/ undock dockable and off() if dock not visible\n\t\tif (!isDockVisible())\n\t\t{\n\t\t\tmDockableFloater->setDocked(false);\n\t\t\t\/\/ force off() since dockable may not have dockControll at this time\n\t\t\toff();\n\t\t\tLLDockableFloater* dockable_floater =\n\t\t\t\t\tdynamic_cast (mDockableFloater);\n\t\t\tif(dockable_floater != NULL)\n\t\t\t{\n\t\t\t\tdockable_floater->onDockHidden();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(mEnabled)\n\t\t\t{\n\t\t\t\tmoveDockable();\n\t\t\t}\n\t\t\tLLDockableFloater* dockable_floater =\n\t\t\t\t\tdynamic_cast (mDockableFloater);\n\t\t\tif(dockable_floater != NULL)\n\t\t\t{\n\t\t\t\tdockable_floater->onDockShown();\n\t\t\t}\n\t\t}\n\n\t\tmPrevDockRect = dockRect;\n\t\tmRootRect = rootRect;\n\t\tmRecalculateDocablePosition = false;\n\t\tmDockWidgetVisible = isDockVisible();\n\t}\n}\n\nbool LLDockControl::isDockVisible()\n{\n\tbool res = true;\n\n\tif (mDockWidget != NULL)\n\t{\n\t\t\/\/we should check all hierarchy\n\t\tres = mDockWidget->isInVisibleChain();\n\t\tif (res)\n\t\t{\n\t\t\tLLRect dockRect = mDockWidget->calcScreenRect();\n\n\t\t\tswitch (mDockAt)\n\t\t\t{\n\t\t\tcase LEFT: \/\/ to keep compiler happy\n\t\t\t\tbreak;\n\t\t\tcase TOP:\n\t\t\t\t\/\/ check is dock inside parent rect\n\t\t\t\tLLRect dockParentRect =\n\t\t\t\t\t\tmDockWidget->getParent()->calcScreenRect();\n\t\t\t\tif (dockRect.mRight <= dockParentRect.mLeft\n\t\t\t\t\t\t|| dockRect.mLeft >= dockParentRect.mRight)\n\t\t\t\t{\n\t\t\t\t\tres = false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res;\n}\n\nvoid LLDockControl::moveDockable()\n{\n\t\/\/ calculate new dockable position\n\tLLRect dockRect = mDockWidget->calcScreenRect();\n\tLLRect rootRect;\n\tmGetAllowedRectCallback(rootRect);\n\n\tbool use_tongue = false;\n\tLLDockableFloater* dockable_floater =\n\t\t\tdynamic_cast (mDockableFloater);\n\tif (dockable_floater != NULL)\n\t{\n\t\tuse_tongue = dockable_floater->getUseTongue();\n\t}\n\n\tLLRect dockableRect = mDockableFloater->calcScreenRect();\n\tS32 x = 0;\n\tS32 y = 0;\n\tLLRect dockParentRect;\n\tswitch (mDockAt)\n\t{\n\tcase LEFT:\n\t\tx = dockRect.mLeft;\n\t\ty = dockRect.mTop + mDockTongue->getHeight() + dockableRect.getHeight();\n\t\t\/\/ check is dockable inside root view rect\n\t\tif (x < rootRect.mLeft)\n\t\t{\n\t\t\tx = rootRect.mLeft;\n\t\t}\n\t\tif (x + dockableRect.getWidth() > rootRect.mRight)\n\t\t{\n\t\t\tx = rootRect.mRight - dockableRect.getWidth();\n\t\t}\n\t\t\n\t\tmDockTongueX = x + dockableRect.getWidth()\/2 - mDockTongue->getWidth() \/ 2;\n\t\t\n\t\tmDockTongueY = dockRect.mTop;\n\t\tbreak;\n\n\tcase TOP:\n\t\tx = dockRect.getCenterX() - dockableRect.getWidth() \/ 2;\n\t\ty = dockRect.mTop + dockableRect.getHeight();\n\t\t\/\/ unique docking used with dock tongue, so add tongue height o the Y coordinate\n\t\tif (use_tongue)\n\t\t{\n\t\t\ty += mDockTongue->getHeight();\n\t\t}\n\n\t\t\/\/ check is dockable inside root view rect\n\t\tif (x < rootRect.mLeft)\n\t\t{\n\t\t\tx = rootRect.mLeft;\n\t\t}\n\t\tif (x + dockableRect.getWidth() > rootRect.mRight)\n\t\t{\n\t\t\tx = rootRect.mRight - dockableRect.getWidth();\n\t\t}\n\n\n\t\t\/\/ calculate dock tongue position\n\t\tdockParentRect = mDockWidget->getParent()->calcScreenRect();\n\t\tif (dockRect.getCenterX() < dockParentRect.mLeft)\n\t\t{\n\t\t\tmDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() \/ 2;\n\t\t}\n\t\telse if (dockRect.getCenterX() > dockParentRect.mRight)\n\t\t{\n\t\t\tmDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() \/ 2;;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() \/ 2;\n\t\t}\n\t\tmDockTongueY = dockRect.mTop;\n\n\t\tbreak;\n\t}\n\n\t\/\/ move dockable\n\tdockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(),\n\t\t\tdockableRect.getHeight());\n\tLLRect localDocableParentRect;\n\tmDockableFloater->getParent()->screenRectToLocal(dockableRect,\n\t\t\t&localDocableParentRect);\n\tmDockableFloater->setRect(localDocableParentRect);\n\n\tmDockableFloater->screenPointToLocal(mDockTongueX, mDockTongueY,\n\t\t\t&mDockTongueX, &mDockTongueY);\n\n}\n\nvoid LLDockControl::on()\n{\n\t if (isDockVisible())\n\t{\n\t\tmEnabled = true;\n\t\tmRecalculateDocablePosition = true;\n\t}\n}\n\nvoid LLDockControl::off()\n{\n\tmEnabled = false;\n}\n\nvoid LLDockControl::forceRecalculatePosition()\n{\n\tmRecalculateDocablePosition = true;\n}\n\nvoid LLDockControl::drawToungue()\n{\n\tbool use_tongue = false;\n\tLLDockableFloater* dockable_floater =\n\t\t\tdynamic_cast (mDockableFloater);\n\tif (dockable_floater != NULL)\n\t{\n\t\tuse_tongue = dockable_floater->getUseTongue();\n\t}\n\n\tif (mEnabled && use_tongue)\n\t{\n\t\tmDockTongue->draw(mDockTongueX, mDockTongueY);\n\t}\n}\n\nCID-344\/** \n * @file lldockcontrol.cpp\n * @brief Creates a panel of a specific kind for a toast\n *\n * $LicenseInfo:firstyear=2000&license=viewergpl$\n * \n * Copyright (c) 2000-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"linden_common.h\"\n\n#include \"lldockcontrol.h\"\n#include \"lldockablefloater.h\"\n\nLLDockControl::LLDockControl(LLView* dockWidget, LLFloater* dockableFloater,\n\t\tconst LLUIImagePtr& dockTongue, DocAt dockAt, get_allowed_rect_callback_t get_allowed_rect_callback) :\n\t\tmDockWidget(dockWidget),\n\t\tmDockableFloater(dockableFloater),\n\t\tmDockTongue(dockTongue),\n\t\tmDockTongueX(0),\n\t\tmDockTongueY(0)\n{\n\tmDockAt = dockAt;\n\n\tif (dockableFloater->isDocked())\n\t{\n\t\ton();\n\t}\n\telse\n\t{\n\t\toff();\n\t}\n\n\tif (!(get_allowed_rect_callback))\n\t{\n\t\tmGetAllowedRectCallback = boost::bind(&LLDockControl::getAllowedRect, this, _1);\n\t}\n\telse\n\t{\n\t\tmGetAllowedRectCallback = get_allowed_rect_callback;\n\t}\n\n\tif (dockWidget != NULL) \n\t{\n\t\trepositionDockable();\n\t}\n\n\tif (mDockWidget != NULL)\n\t{\n\t\tmDockWidgetVisible = isDockVisible();\n\t}\n\telse\n\t{\n\t\tmDockWidgetVisible = false;\n\t}\n}\n\nLLDockControl::~LLDockControl()\n{\n}\n\nvoid LLDockControl::setDock(LLView* dockWidget)\n{\n\tmDockWidget = dockWidget;\n\tif (mDockWidget != NULL)\n\t{\n\t\trepositionDockable();\n\t\tmDockWidgetVisible = isDockVisible();\n\t}\n\telse\n\t{\n\t\tmDockWidgetVisible = false;\n\t}\n}\n\nvoid LLDockControl::getAllowedRect(LLRect& rect)\n{\n\trect = mDockableFloater->getRootView()->getRect();\n}\n\nvoid LLDockControl::repositionDockable()\n{\n\tLLRect dockRect = mDockWidget->calcScreenRect();\n\tLLRect rootRect;\n\tmGetAllowedRectCallback(rootRect);\n\n\t\/\/ recalculate dockable position if dock position changed, dock visibility changed,\n\t\/\/ root view rect changed or recalculation is forced\n\tif (mPrevDockRect != dockRect || mDockWidgetVisible != isDockVisible()\n\t\t\t|| mRootRect != rootRect || mRecalculateDocablePosition)\n\t{\n\t\t\/\/ undock dockable and off() if dock not visible\n\t\tif (!isDockVisible())\n\t\t{\n\t\t\tmDockableFloater->setDocked(false);\n\t\t\t\/\/ force off() since dockable may not have dockControll at this time\n\t\t\toff();\n\t\t\tLLDockableFloater* dockable_floater =\n\t\t\t\t\tdynamic_cast (mDockableFloater);\n\t\t\tif(dockable_floater != NULL)\n\t\t\t{\n\t\t\t\tdockable_floater->onDockHidden();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif(mEnabled)\n\t\t\t{\n\t\t\t\tmoveDockable();\n\t\t\t}\n\t\t\tLLDockableFloater* dockable_floater =\n\t\t\t\t\tdynamic_cast (mDockableFloater);\n\t\t\tif(dockable_floater != NULL)\n\t\t\t{\n\t\t\t\tdockable_floater->onDockShown();\n\t\t\t}\n\t\t}\n\n\t\tmPrevDockRect = dockRect;\n\t\tmRootRect = rootRect;\n\t\tmRecalculateDocablePosition = false;\n\t\tmDockWidgetVisible = isDockVisible();\n\t}\n}\n\nbool LLDockControl::isDockVisible()\n{\n\tbool res = true;\n\n\tif (mDockWidget != NULL)\n\t{\n\t\t\/\/we should check all hierarchy\n\t\tres = mDockWidget->isInVisibleChain();\n\t\tif (res)\n\t\t{\n\t\t\tLLRect dockRect = mDockWidget->calcScreenRect();\n\n\t\t\tswitch (mDockAt)\n\t\t\t{\n\t\t\tcase LEFT: \/\/ to keep compiler happy\n\t\t\t\tbreak;\n\t\t\tcase TOP:\n\t\t\t\t\/\/ check is dock inside parent rect\n\t\t\t\tLLRect dockParentRect =\n\t\t\t\t\t\tmDockWidget->getParent()->calcScreenRect();\n\t\t\t\tif (dockRect.mRight <= dockParentRect.mLeft\n\t\t\t\t\t\t|| dockRect.mLeft >= dockParentRect.mRight)\n\t\t\t\t{\n\t\t\t\t\tres = false;\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn res;\n}\n\nvoid LLDockControl::moveDockable()\n{\n\t\/\/ calculate new dockable position\n\tLLRect dockRect = mDockWidget->calcScreenRect();\n\tLLRect rootRect;\n\tmGetAllowedRectCallback(rootRect);\n\n\tbool use_tongue = false;\n\tLLDockableFloater* dockable_floater =\n\t\t\tdynamic_cast (mDockableFloater);\n\tif (dockable_floater != NULL)\n\t{\n\t\tuse_tongue = dockable_floater->getUseTongue();\n\t}\n\n\tLLRect dockableRect = mDockableFloater->calcScreenRect();\n\tS32 x = 0;\n\tS32 y = 0;\n\tLLRect dockParentRect;\n\tswitch (mDockAt)\n\t{\n\tcase LEFT:\n\t\tx = dockRect.mLeft;\n\t\ty = dockRect.mTop + mDockTongue->getHeight() + dockableRect.getHeight();\n\t\t\/\/ check is dockable inside root view rect\n\t\tif (x < rootRect.mLeft)\n\t\t{\n\t\t\tx = rootRect.mLeft;\n\t\t}\n\t\tif (x + dockableRect.getWidth() > rootRect.mRight)\n\t\t{\n\t\t\tx = rootRect.mRight - dockableRect.getWidth();\n\t\t}\n\t\t\n\t\tmDockTongueX = x + dockableRect.getWidth()\/2 - mDockTongue->getWidth() \/ 2;\n\t\t\n\t\tmDockTongueY = dockRect.mTop;\n\t\tbreak;\n\n\tcase TOP:\n\t\tx = dockRect.getCenterX() - dockableRect.getWidth() \/ 2;\n\t\ty = dockRect.mTop + dockableRect.getHeight();\n\t\t\/\/ unique docking used with dock tongue, so add tongue height o the Y coordinate\n\t\tif (use_tongue)\n\t\t{\n\t\t\ty += mDockTongue->getHeight();\n\t\t}\n\n\t\t\/\/ check is dockable inside root view rect\n\t\tif (x < rootRect.mLeft)\n\t\t{\n\t\t\tx = rootRect.mLeft;\n\t\t}\n\t\tif (x + dockableRect.getWidth() > rootRect.mRight)\n\t\t{\n\t\t\tx = rootRect.mRight - dockableRect.getWidth();\n\t\t}\n\n\n\t\t\/\/ calculate dock tongue position\n\t\tdockParentRect = mDockWidget->getParent()->calcScreenRect();\n\t\tif (dockRect.getCenterX() < dockParentRect.mLeft)\n\t\t{\n\t\t\tmDockTongueX = dockParentRect.mLeft - mDockTongue->getWidth() \/ 2;\n\t\t}\n\t\telse if (dockRect.getCenterX() > dockParentRect.mRight)\n\t\t{\n\t\t\tmDockTongueX = dockParentRect.mRight - mDockTongue->getWidth() \/ 2;;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmDockTongueX = dockRect.getCenterX() - mDockTongue->getWidth() \/ 2;\n\t\t}\n\t\tmDockTongueY = dockRect.mTop;\n\n\t\tbreak;\n\t}\n\n\t\/\/ move dockable\n\tdockableRect.setLeftTopAndSize(x, y, dockableRect.getWidth(),\n\t\t\tdockableRect.getHeight());\n\tLLRect localDocableParentRect;\n\tmDockableFloater->getParent()->screenRectToLocal(dockableRect,\n\t\t\t&localDocableParentRect);\n\tmDockableFloater->setRect(localDocableParentRect);\n\n\tmDockableFloater->screenPointToLocal(mDockTongueX, mDockTongueY,\n\t\t\t&mDockTongueX, &mDockTongueY);\n\n}\n\nvoid LLDockControl::on()\n{\n\t if (isDockVisible())\n\t{\n\t\tmEnabled = true;\n\t\tmRecalculateDocablePosition = true;\n\t}\n}\n\nvoid LLDockControl::off()\n{\n\tmEnabled = false;\n}\n\nvoid LLDockControl::forceRecalculatePosition()\n{\n\tmRecalculateDocablePosition = true;\n}\n\nvoid LLDockControl::drawToungue()\n{\n\tbool use_tongue = false;\n\tLLDockableFloater* dockable_floater =\n\t\t\tdynamic_cast (mDockableFloater);\n\tif (dockable_floater != NULL)\n\t{\n\t\tuse_tongue = dockable_floater->getUseTongue();\n\t}\n\n\tif (mEnabled && use_tongue)\n\t{\n\t\tmDockTongue->draw(mDockTongueX, mDockTongueY);\n\t}\n}\n\n<|endoftext|>"} {"text":"#include \"providers\/LinkResolver.hpp\"\n\n#include \"common\/Common.hpp\"\n#include \"common\/NetworkRequest.hpp\"\n\n#include \n\nnamespace chatterino {\n\nvoid LinkResolver::getLinkInfo(const QString url,\n std::function successCallback)\n{\n QString requestUrl(\"https:\/\/api.betterttv.net\/2\/link_resolver\/\" + \n QUrl::toPercentEncoding(url, \"\", \"\/:\"));\n\n NetworkRequest request(requestUrl);\n request.setCaller(QThread::currentThread());\n request.setTimeout(30000);\n request.onSuccess([successCallback](auto result) mutable -> Outcome {\n auto root = result.parseJson();\n \/* When tooltip is not a string, in this case, \n onError runs before onSuccess, \n so there is no point in doing \"if\" condition. *\/\n auto tooltip = root.value(\"tooltip\").toString();\n successCallback(QUrl::fromPercentEncoding(tooltip.toUtf8()));\n\n return Success;\n });\n\n request.onError([successCallback](auto result) {\n successCallback(\"No link info found\");\n\n return true;\n });\n\n request.execute();\n}\n\n} \/\/ namespace chatterino\nRun away from BTTV API.#include \"providers\/LinkResolver.hpp\"\n\n#include \"common\/Common.hpp\"\n#include \"common\/NetworkRequest.hpp\"\n\n#include \n\nnamespace chatterino {\n\nvoid LinkResolver::getLinkInfo(const QString url,\n std::function successCallback)\n{\n QString requestUrl(\"https:\/\/braize.pajlada.com\/chatterino\/link_resolver\/\" + \n QUrl::toPercentEncoding(url, \"\", \"\/:\"));\n\n NetworkRequest request(requestUrl);\n request.setCaller(QThread::currentThread());\n request.setTimeout(30000);\n request.onSuccess([successCallback](auto result) mutable -> Outcome {\n auto root = result.parseJson();\n \/* When tooltip is not a string, in this case, \n onError runs before onSuccess, \n so there is no point in doing \"if\" condition. *\/\n auto tooltip = root.value(\"tooltip\").toString();\n successCallback(QUrl::fromPercentEncoding(tooltip.toUtf8()));\n\n return Success;\n });\n\n request.onError([successCallback](auto result) {\n successCallback(\"No link info found\");\n\n return true;\n });\n\n request.execute();\n}\n\n} \/\/ namespace chatterino\n<|endoftext|>"} {"text":"\/* test_junctions_creator.cc -- Unit-tests for the JunctionsCreator class\n\n Copyright (c) 2015, The Griffith Lab\n\n Author: Avinash Ramu \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE. *\/\n\n#include \n#include \n#include \n#include \"junctions_creator.h\"\n\nclass JunctionsCreateTest : public ::testing::Test {\n public:\n JunctionsCreator jc1;\n};\n\nTEST_F(JunctionsCreateTest, ParseInput) {\n int argc = 2;\n char * argv[] = {\"create\", \"test_input.bam\"};\n int ret = jc1.parse_options(argc, argv);\n string expected_bam(\"test_input.bam\");\n ASSERT_EQ(expected_bam, jc1.get_bam());\n ASSERT_EQ(0, ret);\n}\n\nTEST_F(JunctionsCreateTest, ParseNoInput) {\n int argc = 1;\n char * argv[] = {\"create\"};\n ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);\n}\n\nTEST_F(JunctionsCreateTest, ParseIncorrectOption) {\n int argc = 2;\n char * argv[] = {\"create\", \"-k\", \"24\", \"test_input.bam\"};\n ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);\n}\n\nTEST_F(JunctionsCreateTest, Usage) {\n ostringstream out, out2;\n out << \"\\nUsage:\\t\\t\" << \"regtools junctions create [options] indexed_alignments.bam\";\n out << \"\\nOptions:\";\n out << \"\\t\" << \"-a INT\\tMinimum anchor length. Junctions which satisfy a minimum \"\n \"anchor length on both sides are reported. [8]\";\n out << \"\\n\\t\\t\" << \"-i INT\\tMinimum intron length. [70]\";\n out << \"\\n\\t\\t\" << \"-I INT\\tMaximum intron length. [500000]\";\n out << \"\\n\\t\\t\" << \"-o FILE\\tThe file to write output to. [STDOUT]\";\n out << \"\\n\\t\\t\" << \"-r STR\\tThe region to identify junctions \"\n \"in \\\"chr:start-end\\\" format. Entire BAM by default.\";\n out << \"\\n\";\n j1.usage(out2);\n ASSERT_EQ(out.str(), out2.str()) << \"Error parsing as expected\";\n}\nRename j1 to jc1\/* test_junctions_creator.cc -- Unit-tests for the JunctionsCreator class\n\n Copyright (c) 2015, The Griffith Lab\n\n Author: Avinash Ramu \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE. *\/\n\n#include \n#include \n#include \n#include \"junctions_creator.h\"\n\nclass JunctionsCreateTest : public ::testing::Test {\n public:\n JunctionsCreator jc1;\n};\n\nTEST_F(JunctionsCreateTest, ParseInput) {\n int argc = 2;\n char * argv[] = {\"create\", \"test_input.bam\"};\n int ret = jc1.parse_options(argc, argv);\n string expected_bam(\"test_input.bam\");\n ASSERT_EQ(expected_bam, jc1.get_bam());\n ASSERT_EQ(0, ret);\n}\n\nTEST_F(JunctionsCreateTest, ParseNoInput) {\n int argc = 1;\n char * argv[] = {\"create\"};\n ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);\n}\n\nTEST_F(JunctionsCreateTest, ParseIncorrectOption) {\n int argc = 2;\n char * argv[] = {\"create\", \"-k\", \"24\", \"test_input.bam\"};\n ASSERT_THROW(jc1.parse_options(argc, argv), std::runtime_error);\n}\n\nTEST_F(JunctionsCreateTest, Usage) {\n ostringstream out, out2;\n out << \"\\nUsage:\\t\\t\" << \"regtools junctions create [options] indexed_alignments.bam\";\n out << \"\\nOptions:\";\n out << \"\\t\" << \"-a INT\\tMinimum anchor length. Junctions which satisfy a minimum \"\n \"anchor length on both sides are reported. [8]\";\n out << \"\\n\\t\\t\" << \"-i INT\\tMinimum intron length. [70]\";\n out << \"\\n\\t\\t\" << \"-I INT\\tMaximum intron length. [500000]\";\n out << \"\\n\\t\\t\" << \"-o FILE\\tThe file to write output to. [STDOUT]\";\n out << \"\\n\\t\\t\" << \"-r STR\\tThe region to identify junctions \"\n \"in \\\"chr:start-end\\\" format. Entire BAM by default.\";\n out << \"\\n\";\n jc1.usage(out2);\n ASSERT_EQ(out.str(), out2.str()) << \"Error parsing as expected\";\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"askpassphrasedialog.h\"\n#include \"ui_askpassphrasedialog.h\"\n\n#include \"guiconstants.h\"\n#include \"walletmodel.h\"\n\n#include \"allocators.h\"\n\n#include \n#include \n#include \n\nAskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AskPassphraseDialog),\n mode(mode),\n model(0),\n fCapsLock(false)\n{\n ui->setupUi(this);\n\n ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);\n\n \/\/ Setup Caps Lock detection.\n ui->passEdit1->installEventFilter(this);\n ui->passEdit2->installEventFilter(this);\n ui->passEdit3->installEventFilter(this);\n\n switch(mode)\n {\n case Encrypt: \/\/ Ask passphrase x2\n ui->passLabel1->hide();\n ui->passEdit1->hide();\n ui->warningLabel->setText(tr(\"Enter the new passphrase to the wallet.Please use a passphrase of 10 or more random characters<\/b>, or eight or more words<\/b>.\"));\n setWindowTitle(tr(\"Encrypt wallet\"));\n break;\n case Unlock: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to unlock the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Unlock wallet\"));\n break;\n case Decrypt: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to decrypt the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Decrypt wallet\"));\n break;\n case ChangePass: \/\/ Ask old passphrase + new passphrase x2\n setWindowTitle(tr(\"Change passphrase\"));\n ui->warningLabel->setText(tr(\"Enter the old and new passphrase to the wallet.\"));\n break;\n }\n\n textChanged();\n connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n}\n\nAskPassphraseDialog::~AskPassphraseDialog()\n{\n \/\/ Attempt to overwrite text so that they do not linger around in memory\n ui->passEdit1->setText(QString(\" \").repeated(ui->passEdit1->text().size()));\n ui->passEdit2->setText(QString(\" \").repeated(ui->passEdit2->text().size()));\n ui->passEdit3->setText(QString(\" \").repeated(ui->passEdit3->text().size()));\n delete ui;\n}\n\nvoid AskPassphraseDialog::setModel(WalletModel *model)\n{\n this->model = model;\n}\n\nvoid AskPassphraseDialog::accept()\n{\n SecureString oldpass, newpass1, newpass2;\n if(!model)\n return;\n oldpass.reserve(MAX_PASSPHRASE_SIZE);\n newpass1.reserve(MAX_PASSPHRASE_SIZE);\n newpass2.reserve(MAX_PASSPHRASE_SIZE);\n \/\/ TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)\n \/\/ Alternately, find a way to make this input mlock()'d to begin with.\n oldpass.assign(ui->passEdit1->text().toStdString().c_str());\n newpass1.assign(ui->passEdit2->text().toStdString().c_str());\n newpass2.assign(ui->passEdit3->text().toStdString().c_str());\n\n switch(mode)\n {\n case Encrypt: {\n if(newpass1.empty() || newpass2.empty())\n {\n \/\/ Cannot encrypt with empty passphrase\n break;\n }\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm wallet encryption\"),\n tr(\"Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR BITCOINS<\/b>!\") + \"

\" + tr(\"Are you sure you wish to encrypt your wallet?\"),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n if(retval == QMessageBox::Yes)\n {\n if(newpass1 == newpass2)\n {\n if(model->setWalletEncrypted(true, newpass1))\n {\n QMessageBox::warning(this, tr(\"Wallet encrypted\"),\n \"\" +\n tr(\"Bitcoin will close now to finish the encryption process. \"\n \"Remember that encrypting your wallet cannot fully protect \"\n \"your bitcoins from being stolen by malware infecting your computer.\") +\n \"

\" +\n tr(\"IMPORTANT: Any previous backups you have made of your wallet file \"\n \"should be replaced with the newly generated, encrypted wallet file. \"\n \"For security reasons, previous backups of the unencrypted wallet file \"\n \"will become useless as soon as you start using the new, encrypted wallet.\") +\n \"<\/b><\/qt>\");\n QApplication::quit();\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"Wallet encryption failed due to an internal error. Your wallet was not encrypted.\"));\n }\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n }\n else\n {\n QDialog::reject(); \/\/ Cancelled\n }\n } break;\n case Unlock:\n if(!model->setWalletLocked(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case Decrypt:\n if(!model->setWalletEncrypted(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet decryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case ChangePass:\n if(newpass1 == newpass2)\n {\n if(model->changePassphrase(oldpass, newpass1))\n {\n QMessageBox::information(this, tr(\"Wallet encrypted\"),\n tr(\"Wallet passphrase was successfully changed.\"));\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n break;\n }\n}\n\nvoid AskPassphraseDialog::textChanged()\n{\n \/\/ Validate input, set Ok button to enabled when acceptable\n bool acceptable = false;\n switch(mode)\n {\n case Encrypt: \/\/ New passphrase x2\n acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n case Unlock: \/\/ Old passphrase x1\n case Decrypt:\n acceptable = !ui->passEdit1->text().isEmpty();\n break;\n case ChangePass: \/\/ Old passphrase x1, new passphrase x2\n acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n }\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);\n}\n\nbool AskPassphraseDialog::event(QEvent *event)\n{\n \/\/ Detect Caps Lock key press.\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n if (ke->key() == Qt::Key_CapsLock) {\n fCapsLock = !fCapsLock;\n }\n if (fCapsLock) {\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else {\n ui->capsLabel->clear();\n }\n }\n return QWidget::event(event);\n}\n\nbool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)\n{\n \/* Detect Caps Lock.\n * There is no good OS-independent way to check a key state in Qt, but we\n * can detect Caps Lock by checking for the following condition:\n * Shift key is down and the result is a lower case character, or\n * Shift key is not down and the result is an upper case character.\n *\/\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n QString str = ke->text();\n if (str.length() != 0) {\n const QChar *psz = str.unicode();\n bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;\n if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {\n fCapsLock = true;\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else if (psz->isLetter()) {\n fCapsLock = false;\n ui->capsLabel->clear();\n }\n }\n }\n return QDialog::eventFilter(object, event);\n}\nConsistent lettering\/\/ Copyright (c) 2011-2013 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"askpassphrasedialog.h\"\n#include \"ui_askpassphrasedialog.h\"\n\n#include \"guiconstants.h\"\n#include \"walletmodel.h\"\n\n#include \"allocators.h\"\n\n#include \n#include \n#include \n\nAskPassphraseDialog::AskPassphraseDialog(Mode mode, QWidget *parent) :\n QDialog(parent),\n ui(new Ui::AskPassphraseDialog),\n mode(mode),\n model(0),\n fCapsLock(false)\n{\n ui->setupUi(this);\n\n ui->passEdit1->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit2->setMaxLength(MAX_PASSPHRASE_SIZE);\n ui->passEdit3->setMaxLength(MAX_PASSPHRASE_SIZE);\n\n \/\/ Setup Caps Lock detection.\n ui->passEdit1->installEventFilter(this);\n ui->passEdit2->installEventFilter(this);\n ui->passEdit3->installEventFilter(this);\n\n switch(mode)\n {\n case Encrypt: \/\/ Ask passphrase x2\n ui->passLabel1->hide();\n ui->passEdit1->hide();\n ui->warningLabel->setText(tr(\"Enter the new passphrase to the wallet.Please use a passphrase of ten or more random characters<\/b>, or eight or more words<\/b>.\"));\n setWindowTitle(tr(\"Encrypt wallet\"));\n break;\n case Unlock: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to unlock the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Unlock wallet\"));\n break;\n case Decrypt: \/\/ Ask passphrase\n ui->warningLabel->setText(tr(\"This operation needs your wallet passphrase to decrypt the wallet.\"));\n ui->passLabel2->hide();\n ui->passEdit2->hide();\n ui->passLabel3->hide();\n ui->passEdit3->hide();\n setWindowTitle(tr(\"Decrypt wallet\"));\n break;\n case ChangePass: \/\/ Ask old passphrase + new passphrase x2\n setWindowTitle(tr(\"Change passphrase\"));\n ui->warningLabel->setText(tr(\"Enter the old and new passphrase to the wallet.\"));\n break;\n }\n\n textChanged();\n connect(ui->passEdit1, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit2, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n connect(ui->passEdit3, SIGNAL(textChanged(QString)), this, SLOT(textChanged()));\n}\n\nAskPassphraseDialog::~AskPassphraseDialog()\n{\n \/\/ Attempt to overwrite text so that they do not linger around in memory\n ui->passEdit1->setText(QString(\" \").repeated(ui->passEdit1->text().size()));\n ui->passEdit2->setText(QString(\" \").repeated(ui->passEdit2->text().size()));\n ui->passEdit3->setText(QString(\" \").repeated(ui->passEdit3->text().size()));\n delete ui;\n}\n\nvoid AskPassphraseDialog::setModel(WalletModel *model)\n{\n this->model = model;\n}\n\nvoid AskPassphraseDialog::accept()\n{\n SecureString oldpass, newpass1, newpass2;\n if(!model)\n return;\n oldpass.reserve(MAX_PASSPHRASE_SIZE);\n newpass1.reserve(MAX_PASSPHRASE_SIZE);\n newpass2.reserve(MAX_PASSPHRASE_SIZE);\n \/\/ TODO: get rid of this .c_str() by implementing SecureString::operator=(std::string)\n \/\/ Alternately, find a way to make this input mlock()'d to begin with.\n oldpass.assign(ui->passEdit1->text().toStdString().c_str());\n newpass1.assign(ui->passEdit2->text().toStdString().c_str());\n newpass2.assign(ui->passEdit3->text().toStdString().c_str());\n\n switch(mode)\n {\n case Encrypt: {\n if(newpass1.empty() || newpass2.empty())\n {\n \/\/ Cannot encrypt with empty passphrase\n break;\n }\n QMessageBox::StandardButton retval = QMessageBox::question(this, tr(\"Confirm wallet encryption\"),\n tr(\"Warning: If you encrypt your wallet and lose your passphrase, you will LOSE ALL OF YOUR BITCOINS<\/b>!\") + \"

\" + tr(\"Are you sure you wish to encrypt your wallet?\"),\n QMessageBox::Yes|QMessageBox::Cancel,\n QMessageBox::Cancel);\n if(retval == QMessageBox::Yes)\n {\n if(newpass1 == newpass2)\n {\n if(model->setWalletEncrypted(true, newpass1))\n {\n QMessageBox::warning(this, tr(\"Wallet encrypted\"),\n \"\" +\n tr(\"Bitcoin will close now to finish the encryption process. \"\n \"Remember that encrypting your wallet cannot fully protect \"\n \"your bitcoins from being stolen by malware infecting your computer.\") +\n \"

\" +\n tr(\"IMPORTANT: Any previous backups you have made of your wallet file \"\n \"should be replaced with the newly generated, encrypted wallet file. \"\n \"For security reasons, previous backups of the unencrypted wallet file \"\n \"will become useless as soon as you start using the new, encrypted wallet.\") +\n \"<\/b><\/qt>\");\n QApplication::quit();\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"Wallet encryption failed due to an internal error. Your wallet was not encrypted.\"));\n }\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n }\n else\n {\n QDialog::reject(); \/\/ Cancelled\n }\n } break;\n case Unlock:\n if(!model->setWalletLocked(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet unlock failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case Decrypt:\n if(!model->setWalletEncrypted(false, oldpass))\n {\n QMessageBox::critical(this, tr(\"Wallet decryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n else\n {\n QDialog::accept(); \/\/ Success\n }\n break;\n case ChangePass:\n if(newpass1 == newpass2)\n {\n if(model->changePassphrase(oldpass, newpass1))\n {\n QMessageBox::information(this, tr(\"Wallet encrypted\"),\n tr(\"Wallet passphrase was successfully changed.\"));\n QDialog::accept(); \/\/ Success\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The passphrase entered for the wallet decryption was incorrect.\"));\n }\n }\n else\n {\n QMessageBox::critical(this, tr(\"Wallet encryption failed\"),\n tr(\"The supplied passphrases do not match.\"));\n }\n break;\n }\n}\n\nvoid AskPassphraseDialog::textChanged()\n{\n \/\/ Validate input, set Ok button to enabled when acceptable\n bool acceptable = false;\n switch(mode)\n {\n case Encrypt: \/\/ New passphrase x2\n acceptable = !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n case Unlock: \/\/ Old passphrase x1\n case Decrypt:\n acceptable = !ui->passEdit1->text().isEmpty();\n break;\n case ChangePass: \/\/ Old passphrase x1, new passphrase x2\n acceptable = !ui->passEdit1->text().isEmpty() && !ui->passEdit2->text().isEmpty() && !ui->passEdit3->text().isEmpty();\n break;\n }\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(acceptable);\n}\n\nbool AskPassphraseDialog::event(QEvent *event)\n{\n \/\/ Detect Caps Lock key press.\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n if (ke->key() == Qt::Key_CapsLock) {\n fCapsLock = !fCapsLock;\n }\n if (fCapsLock) {\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else {\n ui->capsLabel->clear();\n }\n }\n return QWidget::event(event);\n}\n\nbool AskPassphraseDialog::eventFilter(QObject *object, QEvent *event)\n{\n \/* Detect Caps Lock.\n * There is no good OS-independent way to check a key state in Qt, but we\n * can detect Caps Lock by checking for the following condition:\n * Shift key is down and the result is a lower case character, or\n * Shift key is not down and the result is an upper case character.\n *\/\n if (event->type() == QEvent::KeyPress) {\n QKeyEvent *ke = static_cast(event);\n QString str = ke->text();\n if (str.length() != 0) {\n const QChar *psz = str.unicode();\n bool fShift = (ke->modifiers() & Qt::ShiftModifier) != 0;\n if ((fShift && *psz >= 'a' && *psz <= 'z') || (!fShift && *psz >= 'A' && *psz <= 'Z')) {\n fCapsLock = true;\n ui->capsLabel->setText(tr(\"Warning: The Caps Lock key is on!\"));\n } else if (psz->isLetter()) {\n fCapsLock = false;\n ui->capsLabel->clear();\n }\n }\n }\n return QDialog::eventFilter(object, event);\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016-2018 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nstatic UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)\n{\n if (request.fHelp) {\n return \"help message\";\n }\n return request.params.write(0, 0);\n}\n\nstatic const CRPCCommand vRPCCommands[] =\n{\n { \"test\", \"rpcNestedTest\", &rpcNestedTest_rpc, {} },\n};\n\nvoid RPCNestedTests::rpcNestedTests()\n{\n \/\/ do some test setup\n \/\/ could be moved to a more generic place when we add more tests on QT level\n tableRPC.appendCommand(\"rpcNestedTest\", &vRPCCommands[0]);\n \/\/mempool.setSanityCheck(1.0);\n\n LogInstance().DisconnectTestLogger(); \/\/ Already started by the common test setup, so stop it to avoid interference\n TestingSetup test;\n\n if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();\n\n std::string result;\n std::string result2;\n std::string filtered;\n auto node = interfaces::MakeNode();\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()[chain]\", &filtered); \/\/simple result filtering with path\n QVERIFY(result==\"main\");\n QVERIFY(filtered == \"getblockchaininfo()[chain]\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock(getbestblockhash())\"); \/\/simple 2 level nesting\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock(getblock(getbestblockhash())[hash], true)\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)\"); \/\/4 level nesting with whitespace, filtering path and boolean parameter\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo\");\n QVERIFY(result.substr(0,1) == \"{\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()\");\n QVERIFY(result.substr(0,1) == \"{\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo \"); \/\/whitespace at the end will be tolerated\n QVERIFY(result.substr(0,1) == \"{\");\n\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()[\\\"chain\\\"]\")); \/\/Quote path identifier are allowed, but look after a child containing the quotes in the key\n QVERIFY(result == \"null\");\n\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"createrawtransaction [] {} 0\")); \/\/parameter not in brackets are allowed\n (RPCConsole::RPCExecuteCommandLine(*node, result2, \"createrawtransaction([],{},0)\")); \/\/parameter in brackets are allowed\n QVERIFY(result == result2);\n (RPCConsole::RPCExecuteCommandLine(*node, result2, \"createrawtransaction( [], {} , 0 )\")); \/\/whitespace between parameters is allowed\n QVERIFY(result == result2);\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock(getbestblockhash())[tx][0]\", &filtered);\n QVERIFY(result == \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b\");\n QVERIFY(filtered == \"getblock(getbestblockhash())[tx][0]\");\n\n RPCConsole::RPCParseCommandLine(nullptr, result, \"importprivkey\", false, &filtered);\n QVERIFY(filtered == \"importprivkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"signmessagewithprivkey abc\", false, &filtered);\n QVERIFY(filtered == \"signmessagewithprivkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"signmessagewithprivkey abc,def\", false, &filtered);\n QVERIFY(filtered == \"signmessagewithprivkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"signrawtransactionwithkey(abc)\", false, &filtered);\n QVERIFY(filtered == \"signrawtransactionwithkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"walletpassphrase(help())\", false, &filtered);\n QVERIFY(filtered == \"walletpassphrase(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"walletpassphrasechange(help(walletpassphrasechange(abc)))\", false, &filtered);\n QVERIFY(filtered == \"walletpassphrasechange(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(encryptwallet(abc, def))\", false, &filtered);\n QVERIFY(filtered == \"help(encryptwallet(…))\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(importprivkey())\", false, &filtered);\n QVERIFY(filtered == \"help(importprivkey(…))\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(importprivkey(help()))\", false, &filtered);\n QVERIFY(filtered == \"help(importprivkey(…))\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(importprivkey(abc), walletpassphrase(def))\", false, &filtered);\n QVERIFY(filtered == \"help(importprivkey(…), walletpassphrase(…))\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest\");\n QVERIFY(result == \"[]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest ''\");\n QVERIFY(result == \"[\\\"\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest \\\"\\\"\");\n QVERIFY(result == \"[\\\"\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest '' abc\");\n QVERIFY(result == \"[\\\"\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc '' abc\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc abc\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc\\t\\tabc\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest(abc )\");\n QVERIFY(result == \"[\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest( abc )\");\n QVERIFY(result == \"[\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest( abc , cba )\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"cba\\\"]\");\n\n \/\/ do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo() .\\n\"), std::runtime_error); \/\/invalid syntax\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo() getblockchaininfo()\"), std::runtime_error); \/\/invalid syntax\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo(\")); \/\/tolerate non closing brackets if we have no arguments\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()()()\")); \/\/tolerate non command brackts\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo(True)\"), UniValue); \/\/invalid argument\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"a(getblockchaininfo(True))\"), UniValue); \/\/method not found\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc,,abc\"), std::runtime_error); \/\/don't tollerate empty arguments when using ,\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest(abc,,abc)\"), std::runtime_error); \/\/don't tollerate empty arguments when using ,\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest(abc,,)\"), std::runtime_error); \/\/don't tollerate empty arguments when using ,\n}\nAdd missing ECC_Stop(); in GUI rpcnestedtests.cpp\/\/ Copyright (c) 2016-2018 The Syscoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\nstatic UniValue rpcNestedTest_rpc(const JSONRPCRequest& request)\n{\n if (request.fHelp) {\n return \"help message\";\n }\n return request.params.write(0, 0);\n}\n\nstatic const CRPCCommand vRPCCommands[] =\n{\n { \"test\", \"rpcNestedTest\", &rpcNestedTest_rpc, {} },\n};\n\nvoid RPCNestedTests::rpcNestedTests()\n{\n \/\/ do some test setup\n \/\/ could be moved to a more generic place when we add more tests on QT level\n tableRPC.appendCommand(\"rpcNestedTest\", &vRPCCommands[0]);\n \/\/mempool.setSanityCheck(1.0);\n\n ECC_Stop(); \/\/ Already started by the common test setup, so stop it to avoid interference\n LogInstance().DisconnectTestLogger();\n\n TestingSetup test;\n\n if (RPCIsInWarmup(nullptr)) SetRPCWarmupFinished();\n\n std::string result;\n std::string result2;\n std::string filtered;\n auto node = interfaces::MakeNode();\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()[chain]\", &filtered); \/\/simple result filtering with path\n QVERIFY(result==\"main\");\n QVERIFY(filtered == \"getblockchaininfo()[chain]\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock(getbestblockhash())\"); \/\/simple 2 level nesting\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock(getblock(getbestblockhash())[hash], true)\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock( getblock( getblock(getbestblockhash())[hash] )[hash], true)\"); \/\/4 level nesting with whitespace, filtering path and boolean parameter\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo\");\n QVERIFY(result.substr(0,1) == \"{\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()\");\n QVERIFY(result.substr(0,1) == \"{\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo \"); \/\/whitespace at the end will be tolerated\n QVERIFY(result.substr(0,1) == \"{\");\n\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()[\\\"chain\\\"]\")); \/\/Quote path identifier are allowed, but look after a child containing the quotes in the key\n QVERIFY(result == \"null\");\n\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"createrawtransaction [] {} 0\")); \/\/parameter not in brackets are allowed\n (RPCConsole::RPCExecuteCommandLine(*node, result2, \"createrawtransaction([],{},0)\")); \/\/parameter in brackets are allowed\n QVERIFY(result == result2);\n (RPCConsole::RPCExecuteCommandLine(*node, result2, \"createrawtransaction( [], {} , 0 )\")); \/\/whitespace between parameters is allowed\n QVERIFY(result == result2);\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"getblock(getbestblockhash())[tx][0]\", &filtered);\n QVERIFY(result == \"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b\");\n QVERIFY(filtered == \"getblock(getbestblockhash())[tx][0]\");\n\n RPCConsole::RPCParseCommandLine(nullptr, result, \"importprivkey\", false, &filtered);\n QVERIFY(filtered == \"importprivkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"signmessagewithprivkey abc\", false, &filtered);\n QVERIFY(filtered == \"signmessagewithprivkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"signmessagewithprivkey abc,def\", false, &filtered);\n QVERIFY(filtered == \"signmessagewithprivkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"signrawtransactionwithkey(abc)\", false, &filtered);\n QVERIFY(filtered == \"signrawtransactionwithkey(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"walletpassphrase(help())\", false, &filtered);\n QVERIFY(filtered == \"walletpassphrase(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"walletpassphrasechange(help(walletpassphrasechange(abc)))\", false, &filtered);\n QVERIFY(filtered == \"walletpassphrasechange(…)\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(encryptwallet(abc, def))\", false, &filtered);\n QVERIFY(filtered == \"help(encryptwallet(…))\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(importprivkey())\", false, &filtered);\n QVERIFY(filtered == \"help(importprivkey(…))\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(importprivkey(help()))\", false, &filtered);\n QVERIFY(filtered == \"help(importprivkey(…))\");\n RPCConsole::RPCParseCommandLine(nullptr, result, \"help(importprivkey(abc), walletpassphrase(def))\", false, &filtered);\n QVERIFY(filtered == \"help(importprivkey(…), walletpassphrase(…))\");\n\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest\");\n QVERIFY(result == \"[]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest ''\");\n QVERIFY(result == \"[\\\"\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest \\\"\\\"\");\n QVERIFY(result == \"[\\\"\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest '' abc\");\n QVERIFY(result == \"[\\\"\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc '' abc\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc abc\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc\\t\\tabc\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest(abc )\");\n QVERIFY(result == \"[\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest( abc )\");\n QVERIFY(result == \"[\\\"abc\\\"]\");\n RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest( abc , cba )\");\n QVERIFY(result == \"[\\\"abc\\\",\\\"cba\\\"]\");\n\n \/\/ do the QVERIFY_EXCEPTION_THROWN checks only with Qt5.3 and higher (QVERIFY_EXCEPTION_THROWN was introduced in Qt5.3)\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo() .\\n\"), std::runtime_error); \/\/invalid syntax\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo() getblockchaininfo()\"), std::runtime_error); \/\/invalid syntax\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo(\")); \/\/tolerate non closing brackets if we have no arguments\n (RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo()()()\")); \/\/tolerate non command brackts\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"getblockchaininfo(True)\"), UniValue); \/\/invalid argument\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"a(getblockchaininfo(True))\"), UniValue); \/\/method not found\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest abc,,abc\"), std::runtime_error); \/\/don't tollerate empty arguments when using ,\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest(abc,,abc)\"), std::runtime_error); \/\/don't tollerate empty arguments when using ,\n QVERIFY_EXCEPTION_THROWN(RPCConsole::RPCExecuteCommandLine(*node, result, \"rpcNestedTest(abc,,)\"), std::runtime_error); \/\/don't tollerate empty arguments when using ,\n}\n<|endoftext|>"} {"text":"\/**\n * @file\n *\/\n#pragma once\n\n#include \"bi\/data\/Frame.hpp\"\n#include \"bi\/data\/Iterator.hpp\"\n#include \"bi\/data\/copy.hpp\"\n#include \"bi\/data\/constant.hpp\"\n\n#include \n\nnamespace bi {\n\/**\n * Array. Combines underlying data and a frame describing the shape of that\n * data. Allows the construction of views of the data, where a view indexes\n * either an individual element or some range of elements.\n *\n * @ingroup library\n *\n * @tparam Type Value type.\n * @tparam Frame Frame type.\n *\/\ntemplate\nclass Array {\n template\n friend class Array;\n\n \/**\n * @internal These are declare ahead due to some issues with clang++ around\n * the return type of operator(), which in turn calls viewReturn().\n *\/\nprotected:\n \/**\n * Frame.\n *\/\n Frame frame;\n\n \/**\n * Value.\n *\/\n Type* ptr;\n\n \/**\n * Do we own the underlying buffer?\n *\/\n bool own;\n\n \/**\n * Copy from another array.\n *\/\n template\n void copy(const Array& o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n int_t block = common_view(frame.block(), o.frame.block()).size();\n auto iter1 = begin();\n auto end1 = end();\n auto iter2 = o.begin();\n auto end2 = o.end();\n\n for (; iter1 != end1; iter1 += block, iter2 += block) {\n std::memcpy(&(*iter1), &(*iter2), block * sizeof(Type));\n }\n assert(iter2 == end2);\n }\n\n \/**\n * Return value of view when result is an array.\n *\/\n template\n Array viewReturn(const View1& view, const Frame1& frame) {\n return Array(ptr + frame.serial(view), frame);\n }\n\n template\n Array viewReturn(const View1& view,\n const Frame1& frame) const {\n return Array(ptr + frame.serial(view), frame);\n }\n\n \/**\n * Return value of view when result is a scalar.\n *\/\n template\n Type& viewReturn(const View1& view, const EmptyFrame& frame) {\n return ptr[frame.serial(view)];\n }\n\n template\n const Type& viewReturn(const View1& view, const EmptyFrame& frame) const {\n return ptr[frame.serial(view)];\n }\n\npublic:\n \/**\n * Constructor with new allocation.\n *\n * @tparam ...Args Arbitrary types.\n *\n * @param frame Frame.\n * @param args Optional constructor arguments.\n *\n * Memory is allocated for the array, and is freed on destruction.\n *\/\n template\n Array(const Frame& frame, Args ... args) :\n frame(frame) {\n create(&ptr, frame);\n fill(ptr, frame, args...);\n }\n\n \/**\n * Constructor with existing allocation.\n *\n * @tparam Frame Frame type.\n *\n * @param ptr Existing allocation.\n * @param frame Frame.\n *\/\n Array(Type* ptr, const Frame& frame) :\n frame(frame),\n ptr(ptr),\n own(false) {\n \/\/\n }\n\n \/**\n * Copy constructor.\n *\/\n Array(const Array& o) :\n frame(o.frame) {\n create(&ptr, frame);\n fill(ptr, frame);\n own = true;\n *this = o;\n }\n\n \/**\n * Move constructor.\n *\/\n\/\/ Array(Array && o) :\n\/\/ frame(o.frame),\n\/\/ ptr(o.ptr),\n\/\/ own(o.own) {\n\/\/ o.own = false; \/\/ ownership moves\n\/\/ }\n\n \/**\n * Destructor.\n *\/\n ~Array() {\n if (own) {\n release(ptr, frame);\n }\n }\n\n \/**\n * Copy assignment. The frames of the two arrays must conform.\n *\/\n Array& operator=(const Array& o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n if (ptr != o.ptr) {\n copy(o);\n }\n return *this;\n }\n\n \/**\n * Move assignment. The frames of the two arrays must conform.\n *\/\n\/\/ Array& operator=(Array && o) {\n\/\/ \/* pre-condition *\/\n\/\/ assert(frame.conforms(o.frame));\n\/\/\n\/\/ if (ptr == o.ptr) {\n\/\/ \/* just take ownership *\/\n\/\/ if (!own) {\n\/\/ std::swap(own, o.own);\n\/\/ }\n\/\/ } else {\n\/\/ \/* copy assignment *\/\n\/\/ copy(o);\n\/\/ }\n\/\/ return *this;\n\/\/ }\n\n \/**\n * Generic assignment. The frames of the two arrays must conform.\n *\/\n template\n Array& operator=(const Array& o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n copy(o);\n return *this;\n }\n\n \/**\n * View operator.\n *\n * @tparam View1 View type.\n *\n * @param o View.\n *\n * @return The new array.\n *\n * @internal The decltype use for the return type here seems necessary,\n * clang++ is otherwise giving these a const return type.\n *\/\n template\n auto operator()(\n const View1& view) -> decltype(viewReturn(view, this->frame(view))) {\n return viewReturn(view, frame(view));\n }\n\n \/**\n * View operator.\n *\/\n template\n auto operator()(\n const View1& view) const -> decltype(viewReturn(view, this->frame(view))) {\n return viewReturn(view, frame(view));\n }\n\n \/**\n * @name Selections\n *\/\n \/\/@{\n \/**\n * Access the first element.\n *\/\n Type& front() {\n return *ptr;\n }\n\n \/**\n * Access the first element.\n *\/\n const Type& front() const {\n return *ptr;\n }\n\n \/**\n * Access the last element.\n *\/\n Type& back() {\n return ptr + frame.lead - 1;\n }\n\n \/**\n * Access the last element.\n *\/\n const Type& back() const {\n return ptr + frame.lead - 1;\n }\n \/\/@}\n\n \/**\n * @name Queries\n *\/\n \/\/@{\n \/**\n * Get the length of the @p i th dimension.\n *\/\n int_t length(const int i) const {\n return frame.length(i);\n }\n\n \/**\n * Get the stride of the @p i th dimension.\n *\/\n int_t stride(const int i) const {\n return frame.stride(i);\n }\n\n \/**\n * Get the lead of the @p i th dimension.\n *\/\n int_t lead(const int i) const {\n return frame.lead(i);\n }\n\n \/**\n * Raw pointer to underlying buffer.\n *\/\n Type* buf() {\n return ptr;\n }\n\n \/**\n * Raw pointer to underlying buffer.\n *\/\n Type* const buf() const {\n return ptr;\n }\n \/\/@}\n\n \/**\n * @name Collections\n *\/\n \/\/@{\n \/**\n * Get lengths.\n *\n * @tparam Integer Integer type.\n *\n * @param[out] out Array assumed to have at least count() elements.\n *\/\n template\n void lengths(Integer* out) const {\n frame.lengths(out);\n }\n\n \/**\n * Get strides.\n *\n * @tparam Integer Integer type.\n *\n * @param[out] out Array assumed to have at least count() elements.\n *\/\n template\n void strides(Integer* out) const {\n frame.strides(out);\n }\n\n \/**\n * Get leads.\n *\n * @tparam Integer Integer type.\n *\n * @param[out] out Array assumed to have at least count() elements.\n *\/\n template\n void leads(Integer* out) const {\n frame.leads(out);\n }\n \/\/@}\n\n \/**\n * @name Reductions\n *\/\n \/\/@{\n \/**\n * Number of spans in the frame.\n *\/\n static constexpr int count() {\n return Frame::count();\n }\n\n \/**\n * Are all elements stored contiguously in memory?\n *\/\n bool contiguous() const {\n return frame.contiguous();\n }\n \/\/@}\n\n \/**\n * @name Iteration\n *\/\n \/\/@{\n \/**\n * Iterator pointing to the first element.\n *\n * Iterators are used to access the elements of an array sequentially.\n * Elements are visited in the order in which they are stored in memory;\n * the rightmost dimension is the fastest moving (for a matrix, this is\n * \"row major\" order).\n *\n * The idiom of iterator usage is as for the STL.\n *\/\n Iterator begin() {\n return Iterator(ptr, frame);\n }\n\n \/**\n * Iterator pointing to the first element.\n *\/\n Iterator begin() const {\n return Iterator(ptr, frame);\n }\n\n \/**\n * Iterator pointing to one beyond the last element.\n *\/\n Iterator end() {\n return begin() + frame.size();\n }\n\n \/**\n * Iterator pointing to one beyond the last element.\n *\/\n Iterator end() const {\n return begin() + frame.size();\n }\n};\n\n\/**\n * Default array for `D` dimensions.\n *\/\ntemplate\nusing DefaultArray = Array::type>;\n}\nReintroduced move constructor and move assignment for arrays.\/**\n * @file\n *\/\n#pragma once\n\n#include \"bi\/data\/Frame.hpp\"\n#include \"bi\/data\/Iterator.hpp\"\n#include \"bi\/data\/copy.hpp\"\n#include \"bi\/data\/constant.hpp\"\n\n#include \n\nnamespace bi {\n\/**\n * Array. Combines underlying data and a frame describing the shape of that\n * data. Allows the construction of views of the data, where a view indexes\n * either an individual element or some range of elements.\n *\n * @ingroup library\n *\n * @tparam Type Value type.\n * @tparam Frame Frame type.\n *\/\ntemplate\nclass Array {\n template\n friend class Array;\n\n \/**\n * @internal These are declare ahead due to some issues with clang++ around\n * the return type of operator(), which in turn calls viewReturn().\n *\/\nprotected:\n \/**\n * Frame.\n *\/\n Frame frame;\n\n \/**\n * Value.\n *\/\n Type* ptr;\n\n \/**\n * Do we own the underlying buffer?\n *\/\n bool own;\n\n \/**\n * Copy from another array.\n *\/\n template\n void copy(const Array& o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n int_t block = common_view(frame.block(), o.frame.block()).size();\n auto iter1 = begin();\n auto end1 = end();\n auto iter2 = o.begin();\n auto end2 = o.end();\n\n for (; iter1 != end1; iter1 += block, iter2 += block) {\n std::memcpy(&(*iter1), &(*iter2), block * sizeof(Type));\n }\n assert(iter2 == end2);\n }\n\n \/**\n * Return value of view when result is an array.\n *\/\n template\n Array viewReturn(const View1& view, const Frame1& frame) {\n return Array(ptr + frame.serial(view), frame);\n }\n\n template\n Array viewReturn(const View1& view,\n const Frame1& frame) const {\n return Array(ptr + frame.serial(view), frame);\n }\n\n \/**\n * Return value of view when result is a scalar.\n *\/\n template\n Type& viewReturn(const View1& view, const EmptyFrame& frame) {\n return ptr[frame.serial(view)];\n }\n\n template\n const Type& viewReturn(const View1& view, const EmptyFrame& frame) const {\n return ptr[frame.serial(view)];\n }\n\npublic:\n \/**\n * Constructor with new allocation.\n *\n * @tparam ...Args Arbitrary types.\n *\n * @param frame Frame.\n * @param args Optional constructor arguments.\n *\n * Memory is allocated for the array, and is freed on destruction.\n *\/\n template\n Array(const Frame& frame, Args ... args) :\n frame(frame) {\n create(&ptr, frame);\n fill(ptr, frame, args...);\n }\n\n \/**\n * Constructor with existing allocation.\n *\n * @tparam Frame Frame type.\n *\n * @param ptr Existing allocation.\n * @param frame Frame.\n *\/\n Array(Type* ptr, const Frame& frame) :\n frame(frame),\n ptr(ptr),\n own(false) {\n \/\/\n }\n\n \/**\n * Copy constructor.\n *\/\n Array(const Array& o) :\n frame(o.frame) {\n create(&ptr, frame);\n fill(ptr, frame);\n own = true;\n *this = o;\n }\n\n \/**\n * Move constructor.\n *\/\n Array(Array && o) :\n frame(o.frame),\n ptr(o.ptr),\n own(o.own) {\n o.own = false; \/\/ ownership moves\n }\n\n \/**\n * Destructor.\n *\/\n ~Array() {\n if (own) {\n release(ptr, frame);\n }\n }\n\n \/**\n * Copy assignment. The frames of the two arrays must conform.\n *\/\n Array& operator=(const Array& o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n if (ptr != o.ptr) {\n copy(o);\n }\n return *this;\n }\n\n \/**\n * Move assignment. The frames of the two arrays must conform.\n *\/\n Array& operator=(Array && o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n if (ptr == o.ptr) {\n \/* just take ownership *\/\n if (!own) {\n std::swap(own, o.own);\n }\n } else {\n \/* copy assignment; note that we cannot simply move, even if this\n * object owns its buffer, as there may exist non-owning arrays\n * with the same buffer *\/\n copy(o);\n }\n return *this;\n }\n\n \/**\n * Generic assignment. The frames of the two arrays must conform.\n *\/\n template\n Array& operator=(const Array& o) {\n \/* pre-condition *\/\n assert(frame.conforms(o.frame));\n\n copy(o);\n return *this;\n }\n\n \/**\n * View operator.\n *\n * @tparam View1 View type.\n *\n * @param o View.\n *\n * @return The new array.\n *\n * @internal The decltype use for the return type here seems necessary,\n * clang++ is otherwise giving these a const return type.\n *\/\n template\n auto operator()(\n const View1& view) -> decltype(viewReturn(view, this->frame(view))) {\n return viewReturn(view, frame(view));\n }\n\n \/**\n * View operator.\n *\/\n template\n auto operator()(\n const View1& view) const -> decltype(viewReturn(view, this->frame(view))) {\n return viewReturn(view, frame(view));\n }\n\n \/**\n * @name Selections\n *\/\n \/\/@{\n \/**\n * Access the first element.\n *\/\n Type& front() {\n return *ptr;\n }\n\n \/**\n * Access the first element.\n *\/\n const Type& front() const {\n return *ptr;\n }\n\n \/**\n * Access the last element.\n *\/\n Type& back() {\n return ptr + frame.lead - 1;\n }\n\n \/**\n * Access the last element.\n *\/\n const Type& back() const {\n return ptr + frame.lead - 1;\n }\n \/\/@}\n\n \/**\n * @name Queries\n *\/\n \/\/@{\n \/**\n * Get the length of the @p i th dimension.\n *\/\n int_t length(const int i) const {\n return frame.length(i);\n }\n\n \/**\n * Get the stride of the @p i th dimension.\n *\/\n int_t stride(const int i) const {\n return frame.stride(i);\n }\n\n \/**\n * Get the lead of the @p i th dimension.\n *\/\n int_t lead(const int i) const {\n return frame.lead(i);\n }\n\n \/**\n * Raw pointer to underlying buffer.\n *\/\n Type* buf() {\n return ptr;\n }\n\n \/**\n * Raw pointer to underlying buffer.\n *\/\n Type* const buf() const {\n return ptr;\n }\n \/\/@}\n\n \/**\n * @name Collections\n *\/\n \/\/@{\n \/**\n * Get lengths.\n *\n * @tparam Integer Integer type.\n *\n * @param[out] out Array assumed to have at least count() elements.\n *\/\n template\n void lengths(Integer* out) const {\n frame.lengths(out);\n }\n\n \/**\n * Get strides.\n *\n * @tparam Integer Integer type.\n *\n * @param[out] out Array assumed to have at least count() elements.\n *\/\n template\n void strides(Integer* out) const {\n frame.strides(out);\n }\n\n \/**\n * Get leads.\n *\n * @tparam Integer Integer type.\n *\n * @param[out] out Array assumed to have at least count() elements.\n *\/\n template\n void leads(Integer* out) const {\n frame.leads(out);\n }\n \/\/@}\n\n \/**\n * @name Reductions\n *\/\n \/\/@{\n \/**\n * Number of spans in the frame.\n *\/\n static constexpr int count() {\n return Frame::count();\n }\n\n \/**\n * Are all elements stored contiguously in memory?\n *\/\n bool contiguous() const {\n return frame.contiguous();\n }\n \/\/@}\n\n \/**\n * @name Iteration\n *\/\n \/\/@{\n \/**\n * Iterator pointing to the first element.\n *\n * Iterators are used to access the elements of an array sequentially.\n * Elements are visited in the order in which they are stored in memory;\n * the rightmost dimension is the fastest moving (for a matrix, this is\n * \"row major\" order).\n *\n * The idiom of iterator usage is as for the STL.\n *\/\n Iterator begin() {\n return Iterator(ptr, frame);\n }\n\n \/**\n * Iterator pointing to the first element.\n *\/\n Iterator begin() const {\n return Iterator(ptr, frame);\n }\n\n \/**\n * Iterator pointing to one beyond the last element.\n *\/\n Iterator end() {\n return begin() + frame.size();\n }\n\n \/**\n * Iterator pointing to one beyond the last element.\n *\/\n Iterator end() const {\n return begin() + frame.size();\n }\n};\n\n\/**\n * Default array for `D` dimensions.\n *\/\ntemplate\nusing DefaultArray = Array::type>;\n}\n<|endoftext|>"} {"text":"\/*** Copyright (c), The Regents of the University of California ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\/*\n These routines are used to implement the OS level authentication scheme.\n\n\n Returns codes of 0 indicate success, others are iRODS error codes.\n*\/\n\n#include \n#include \n#include \n#ifndef windows_platform\n#include \n#include \n#include \n#include \n#endif\n\n#include \"rods.hpp\"\n#include \"rcGlobalExtern.hpp\"\n#include \"authenticate.hpp\"\nextern \"C\" {\n\n int\n osauthVerifyResponse( char *challenge, char *username, char *response ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthVerifyResponse\";\n char authenticator[16]; \/* MD5 hash *\/\n char md5buffer[CHALLENGE_LEN + MAX_PASSWORD_LEN + 2];\n char md5digest[RESPONSE_LEN + 2];\n int uid, status, i;\n char *keybuf;\n int key_len;\n MD5_CTX ctx;\n\n uid = osauthGetUid( username );\n if ( uid == -1 ) {\n return SYS_USER_RETRIEVE_ERR;\n }\n\n \/* read the key from the key file *\/\n if ( ( status = osauthGetKey( &keybuf, &key_len ) ) ) {\n rodsLogError( LOG_ERROR, status,\n \"%s: error retrieving key.\", fname );\n return status;\n }\n\n \/* generate the authenticator *\/\n status = osauthGenerateAuthenticator( username, uid, challenge,\n keybuf, key_len,\n authenticator, 16 );\n if ( status ) {\n rodsLog( LOG_ERROR,\n \"%s: could not generate the authenticator\", fname );\n free( keybuf );\n return status;\n }\n free( keybuf );\n\n \/* now append this hash with the challenge, and\n take the md5 sum of that *\/\n memset( md5buffer, 0, sizeof( md5buffer ) );\n memset( md5digest, 0, sizeof( md5digest ) );\n memcpy( md5buffer, challenge, CHALLENGE_LEN );\n memcpy( md5buffer + CHALLENGE_LEN, authenticator, 16 );\n MD5Init( &ctx );\n MD5Update( &ctx, ( unsigned char* )md5buffer, CHALLENGE_LEN + MAX_PASSWORD_LEN );\n MD5Final( ( unsigned char* )md5digest, &ctx );\n for ( i = 0; i < RESPONSE_LEN; i++ ) {\n \/* make sure 'string' doesn't end early\n (this matches client digest generation). *\/\n if ( md5digest[i] == '\\0' ) {\n md5digest[i]++;\n }\n }\n\n \/* compare the calculated digest to the client response *\/\n for ( i = 0; i < RESPONSE_LEN; i++ ) {\n if ( response[i] != md5digest[i] ) {\n rodsLog( LOG_ERROR, \"%s: calculated digest doesn't match client response\",\n fname );\n return CAT_INVALID_AUTHENTICATION;\n }\n }\n\n return 0;\n\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGenerateAuthenticator - this functions creates\n * an authenticator from the passed in parameters. The\n * parameters are concatenated together, and then an\n * md5 hash is generated and provided in the output\n * parameter. Returns 0 on success, error code on error.\n *\/\n int\n osauthGenerateAuthenticator( char *username, int uid,\n char *challenge, char *key, int key_len,\n char *authenticator, int authenticator_len ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthGenerateAuthenticator\";\n char *buffer, *bufp;\n int buflen;\n char md5digest[16];\n MD5_CTX ctx;\n\n if ( authenticator == NULL ||\n authenticator_len < 16 ) {\n return USER_INPUT_OPTION_ERR;\n }\n\n \/* calculate buffer size and allocate *\/\n buflen = username ? strlen( username ) : 0;\n buflen += sizeof( uid ) + CHALLENGE_LEN + key_len;\n buffer = ( char* )malloc( buflen );\n if ( buffer == NULL ) {\n rodsLog( LOG_ERROR,\n \"%s: could not allocate memory buffer. errno = %d\",\n fname, errno );\n return SYS_MALLOC_ERR;\n }\n\n \/* concatenate the input parameters *\/\n bufp = buffer;\n if ( username && strlen( username ) ) {\n memcpy( bufp, username, strlen( username ) );\n bufp += strlen( username );\n }\n#if defined(OS_AUTH_NO_UID)\n uid = 0;\n#endif\n memcpy( bufp, &uid, sizeof( uid ) );\n bufp += sizeof( uid );\n if ( challenge ) {\n memcpy( bufp, challenge, CHALLENGE_LEN );\n bufp += CHALLENGE_LEN;\n }\n if ( key ) {\n memcpy( bufp, key, key_len );\n }\n\n \/* generate an MD5 hash of the buffer, and copy it\n to the output parameter authenticator *\/\n MD5Init( &ctx );\n MD5Update( &ctx, ( unsigned char* )buffer, buflen );\n MD5Final( ( unsigned char* )md5digest, &ctx );\n memcpy( authenticator, md5digest, 16 );\n\n return 0;\n\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGetKey - read key from OS_AUTH_KEYFILE\n *\n * The return parameters include a malloc'ed buffer in\n * *key that is the responsibility of the caller to free.\n * The length of the buffer is in *key_len.\n *\/\n int\n osauthGetKey( char **key, int *key_len ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthGetKey\";\n char *keyfile, *keybuf;\n int buflen, key_fd, nb;\n\n if ( key == NULL || key_len == NULL ) {\n return USER__NULL_INPUT_ERR;\n }\n\n keyfile = getenv( \"irodsOsAuthKeyfile\" );\n if ( keyfile == NULL || *keyfile == '\\0' ) {\n keyfile = OS_AUTH_KEYFILE;\n }\n\n key_fd = open( keyfile, O_RDONLY, 0 );\n if ( key_fd < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: couldn't open %s for reading. errno = %d\",\n fname, keyfile, errno );\n free( keybuf );\n return FILE_OPEN_ERR;\n }\n off_t lseek_return = lseek( key_fd, 0, SEEK_END );\n int errsv = errno;\n if ( ( off_t )-1 == lseek_return ) {\n fprintf( stderr, \"SEEK_END lseek failed with error %d.\\n\", errsv );\n close( key_fd );\n return UNIX_FILE_LSEEK_ERR;\n }\n if ( lseek_return > std::numeric_limits::max() ) {\n fprintf( stderr, \"file of size %ju is too large for a long long.\\n\", ( uintmax_t )lseek_return );\n close( key_fd );\n return UNIX_FILE_LSEEK_ERR;\n }\n buflen = lseek_return;\n lseek_return = lseek( key_fd, 0, SEEK_SET );\n errsv = errno;\n if ( ( off_t )-1 == lseek_return ) {\n fprintf( stderr, \"SEEK_SET lseek failed with error %d.\\n\", errsv );\n close( key_fd );\n return UNIX_FILE_LSEEK_ERR;\n }\n\n keybuf = ( char* )malloc( buflen );\n if ( keybuf == NULL ) {\n rodsLog( LOG_ERROR,\n \"%s: could not allocate memory for key buffer. errno = %d\",\n fname, errno );\n return SYS_MALLOC_ERR;\n }\n nb = read( key_fd, keybuf, buflen );\n if ( nb < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: couldn't read key from %s. errno = %d\",\n fname, keyfile, errno );\n free( keybuf );\n return FILE_READ_ERR;\n }\n close( key_fd );\n\n *key_len = buflen;\n *key = keybuf;\n\n return 0;\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGetAuth - this function runs the OS_AUTH_CMD command to\n * retrieve an authenticator for the calling user.\n *\/\n int\n osauthGetAuth( char *challenge,\n char *username,\n char *authenticator,\n int authenticator_buflen ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthGetAuth\";\n int pipe1[2], pipe2[2];\n pid_t childPid;\n int childStatus = 0;\n int child_stdin, child_stdout, nb;\n int buflen, challenge_len = CHALLENGE_LEN;\n char buffer[128];\n\n if ( challenge == NULL || username == NULL || authenticator == NULL ) {\n return USER__NULL_INPUT_ERR;\n }\n\n if ( pipe( pipe1 ) < 0 ) {\n rodsLog( LOG_ERROR, \"%s: pipe1 create failed. errno = %d\",\n fname, errno );\n return SYS_PIPE_ERROR - errno;\n }\n if ( pipe( pipe2 ) < 0 ) {\n rodsLog( LOG_ERROR, \"%s: pipe2 create failed. errno = %d\",\n fname, errno );\n close( pipe1[0] );\n close( pipe1[1] );\n return SYS_PIPE_ERROR - errno;\n }\n\n childPid = RODS_FORK();\n\n if ( childPid < 0 ) {\n rodsLog( LOG_ERROR, \"%s: RODS_FORK failed. errno = %d\",\n fname, errno );\n close( pipe1[0] );\n close( pipe1[1] );\n close( pipe2[0] );\n close( pipe2[1] );\n return SYS_FORK_ERROR;\n }\n else if ( childPid == 0 ) {\n \/* in the child process *\/\n\n \/* pipe1 will be for child's stdin *\/\n close( pipe1[1] );\n dup2( pipe1[0], 0 );\n \/* pipe2 will be for child's stdout *\/\n close( pipe2[0] );\n dup2( pipe2[1], 1 );\n\n \/* set the username in an environment variable *\/\n setenv( OS_AUTH_ENV_USER, username, 1 );\n\n \/* run the OS_AUTH_CMD *\/\n execlp( OS_AUTH_CMD, OS_AUTH_CMD, ( char* )NULL );\n rodsLog( LOG_ERROR, \"%s: child execl %s failed. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n }\n else {\n \/* in the parent process *\/\n close( pipe1[0] );\n child_stdin = pipe1[1]; \/* parent writes to child's stdin *\/\n close( pipe2[1] );\n child_stdout = pipe2[0]; \/* parent reads from child's stdout *\/\n\n \/* send the challenge to the OS_AUTH_CMD program on its stdin *\/\n nb = write( child_stdin, &challenge_len, sizeof( challenge_len ) );\n if ( nb < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: error writing challenge_len to %s. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n close( child_stdin );\n close( child_stdout );\n return SYS_PIPE_ERROR - errno;\n }\n nb = write( child_stdin, challenge, challenge_len );\n if ( nb < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: error writing challenge to %s. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n close( child_stdin );\n close( child_stdout );\n return SYS_PIPE_ERROR - errno;\n }\n\n \/* read the response *\/\n buflen = read( child_stdout, buffer, 128 );\n if ( buflen < 0 ) {\n rodsLog( LOG_ERROR, \"%s: error reading from %s. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n close( child_stdin );\n close( child_stdout );\n return SYS_PIPE_ERROR - errno;\n }\n\n close( child_stdin );\n close( child_stdout );\n\n if ( waitpid( childPid, &childStatus, 0 ) < 0 ) {\n rodsLog( LOG_ERROR, \"%s: waitpid error. errno = %d\",\n fname, errno );\n return EXEC_CMD_ERROR;\n }\n\n if ( WIFEXITED( childStatus ) ) {\n if ( WEXITSTATUS( childStatus ) ) {\n rodsLog( LOG_ERROR,\n \"%s: command failed: %s\", fname, buffer );\n return EXEC_CMD_ERROR;\n }\n }\n else {\n rodsLog( LOG_ERROR,\n \"%s: some error running %s\", fname, OS_AUTH_CMD );\n }\n\n \/* authenticator is in buffer now *\/\n if ( buflen > authenticator_buflen ) {\n rodsLog( LOG_ERROR,\n \"%s: not enough space in return buffer for authenticator\", fname );\n return EXEC_CMD_OUTPUT_TOO_LARGE;\n }\n memcpy( authenticator, buffer, buflen );\n }\n\n return 0;\n\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGetUid - looks up the given username using getpwnam\n * and returns the user's uid if successful, or -1 if not.\n *\/\n int\n osauthGetUid( char *username ) {\n static char fname[] = \"osauthGetUid\";\n struct passwd *pwent;\n\n errno = 0;\n pwent = getpwnam( username );\n if ( pwent == NULL ) {\n if ( errno ) {\n rodsLog( LOG_ERROR,\n \"%s: error calling getpwnam for %s. errno = %d\",\n fname, username ? username : \"\", errno );\n return -1;\n }\n else {\n rodsLog( LOG_ERROR,\n \"%s: no such user %s\", fname, username );\n return -1;\n }\n }\n return pwent->pw_uid;\n }\n\n \/*\n * osauthGetUsername - looks up the user identified by\n * the uid determined by getuid(). Places the username\n * in the provided username buffer and returns the uid\n * on success, or -1 if not.\n *\/\n int\n osauthGetUsername( char *username, int username_len ) {\n static char fname[] = \"osauthGetUsername\";\n struct passwd *pwent;\n int uid;\n\n uid = getuid();\n errno = 0;\n pwent = getpwuid( uid );\n if ( pwent == NULL ) {\n if ( errno ) {\n rodsLog( LOG_ERROR,\n \"%s: error calling getpwuid for uid %d. errno = %d\",\n fname, uid, errno );\n return -1;\n }\n else {\n rodsLog( LOG_ERROR, \"%s: no user with uid %d\",\n fname, uid );\n return -1;\n }\n }\n if ( ( unsigned int )username_len <= strlen( pwent->pw_name ) ) {\n rodsLog( LOG_ERROR, \"%s: username input buffer too small (%d <= %d)\",\n fname, username_len, strlen( pwent->pw_name ) );\n return -1;\n }\n strcpy( username, pwent->pw_name );\n\n return uid;\n }\n\n} \/\/ extern \"C\"\n[#858] initialized pointer before use\/*** Copyright (c), The Regents of the University of California ***\n *** For more information please refer to files in the COPYRIGHT directory ***\/\n\/*\n These routines are used to implement the OS level authentication scheme.\n\n\n Returns codes of 0 indicate success, others are iRODS error codes.\n*\/\n\n#include \n#include \n#include \n#ifndef windows_platform\n#include \n#include \n#include \n#include \n#endif\n\n#include \"rods.hpp\"\n#include \"rcGlobalExtern.hpp\"\n#include \"authenticate.hpp\"\nextern \"C\" {\n\n int\n osauthVerifyResponse( char *challenge, char *username, char *response ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthVerifyResponse\";\n char authenticator[16]; \/* MD5 hash *\/\n char md5buffer[CHALLENGE_LEN + MAX_PASSWORD_LEN + 2];\n char md5digest[RESPONSE_LEN + 2];\n int uid, status, i;\n char *keybuf = NULL;\n int key_len;\n MD5_CTX ctx;\n\n uid = osauthGetUid( username );\n if ( uid == -1 ) {\n return SYS_USER_RETRIEVE_ERR;\n }\n\n \/* read the key from the key file *\/\n if ( ( status = osauthGetKey( &keybuf, &key_len ) ) ) {\n rodsLogError( LOG_ERROR, status,\n \"%s: error retrieving key.\", fname );\n return status;\n }\n\n \/* generate the authenticator *\/\n status = osauthGenerateAuthenticator( username, uid, challenge,\n keybuf, key_len,\n authenticator, 16 );\n if ( status ) {\n rodsLog( LOG_ERROR,\n \"%s: could not generate the authenticator\", fname );\n free( keybuf );\n return status;\n }\n free( keybuf );\n\n \/* now append this hash with the challenge, and\n take the md5 sum of that *\/\n memset( md5buffer, 0, sizeof( md5buffer ) );\n memset( md5digest, 0, sizeof( md5digest ) );\n memcpy( md5buffer, challenge, CHALLENGE_LEN );\n memcpy( md5buffer + CHALLENGE_LEN, authenticator, 16 );\n MD5Init( &ctx );\n MD5Update( &ctx, ( unsigned char* )md5buffer, CHALLENGE_LEN + MAX_PASSWORD_LEN );\n MD5Final( ( unsigned char* )md5digest, &ctx );\n for ( i = 0; i < RESPONSE_LEN; i++ ) {\n \/* make sure 'string' doesn't end early\n (this matches client digest generation). *\/\n if ( md5digest[i] == '\\0' ) {\n md5digest[i]++;\n }\n }\n\n \/* compare the calculated digest to the client response *\/\n for ( i = 0; i < RESPONSE_LEN; i++ ) {\n if ( response[i] != md5digest[i] ) {\n rodsLog( LOG_ERROR, \"%s: calculated digest doesn't match client response\",\n fname );\n return CAT_INVALID_AUTHENTICATION;\n }\n }\n\n return 0;\n\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGenerateAuthenticator - this functions creates\n * an authenticator from the passed in parameters. The\n * parameters are concatenated together, and then an\n * md5 hash is generated and provided in the output\n * parameter. Returns 0 on success, error code on error.\n *\/\n int\n osauthGenerateAuthenticator( char *username, int uid,\n char *challenge, char *key, int key_len,\n char *authenticator, int authenticator_len ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthGenerateAuthenticator\";\n char *buffer, *bufp;\n int buflen;\n char md5digest[16];\n MD5_CTX ctx;\n\n if ( authenticator == NULL ||\n authenticator_len < 16 ) {\n return USER_INPUT_OPTION_ERR;\n }\n\n \/* calculate buffer size and allocate *\/\n buflen = username ? strlen( username ) : 0;\n buflen += sizeof( uid ) + CHALLENGE_LEN + key_len;\n buffer = ( char* )malloc( buflen );\n if ( buffer == NULL ) {\n rodsLog( LOG_ERROR,\n \"%s: could not allocate memory buffer. errno = %d\",\n fname, errno );\n return SYS_MALLOC_ERR;\n }\n\n \/* concatenate the input parameters *\/\n bufp = buffer;\n if ( username && strlen( username ) ) {\n memcpy( bufp, username, strlen( username ) );\n bufp += strlen( username );\n }\n#if defined(OS_AUTH_NO_UID)\n uid = 0;\n#endif\n memcpy( bufp, &uid, sizeof( uid ) );\n bufp += sizeof( uid );\n if ( challenge ) {\n memcpy( bufp, challenge, CHALLENGE_LEN );\n bufp += CHALLENGE_LEN;\n }\n if ( key ) {\n memcpy( bufp, key, key_len );\n }\n\n \/* generate an MD5 hash of the buffer, and copy it\n to the output parameter authenticator *\/\n MD5Init( &ctx );\n MD5Update( &ctx, ( unsigned char* )buffer, buflen );\n MD5Final( ( unsigned char* )md5digest, &ctx );\n memcpy( authenticator, md5digest, 16 );\n\n return 0;\n\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGetKey - read key from OS_AUTH_KEYFILE\n *\n * The return parameters include a malloc'ed buffer in\n * *key that is the responsibility of the caller to free.\n * The length of the buffer is in *key_len.\n *\/\n int\n osauthGetKey( char **key, int *key_len ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthGetKey\";\n char *keyfile;\n int buflen, key_fd, nb;\n\n if ( key == NULL || key_len == NULL ) {\n return USER__NULL_INPUT_ERR;\n }\n\n keyfile = getenv( \"irodsOsAuthKeyfile\" );\n if ( keyfile == NULL || *keyfile == '\\0' ) {\n keyfile = OS_AUTH_KEYFILE;\n }\n\n key_fd = open( keyfile, O_RDONLY, 0 );\n if ( key_fd < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: couldn't open %s for reading. errno = %d\",\n fname, keyfile, errno );\n return FILE_OPEN_ERR;\n }\n off_t lseek_return = lseek( key_fd, 0, SEEK_END );\n int errsv = errno;\n if ( ( off_t )-1 == lseek_return ) {\n fprintf( stderr, \"SEEK_END lseek failed with error %d.\\n\", errsv );\n close( key_fd );\n return UNIX_FILE_LSEEK_ERR;\n }\n if ( lseek_return > std::numeric_limits::max() ) {\n fprintf( stderr, \"file of size %ju is too large for a long long.\\n\", ( uintmax_t )lseek_return );\n close( key_fd );\n return UNIX_FILE_LSEEK_ERR;\n }\n buflen = lseek_return;\n lseek_return = lseek( key_fd, 0, SEEK_SET );\n errsv = errno;\n if ( ( off_t )-1 == lseek_return ) {\n fprintf( stderr, \"SEEK_SET lseek failed with error %d.\\n\", errsv );\n close( key_fd );\n return UNIX_FILE_LSEEK_ERR;\n }\n\n char * keybuf = ( char* )malloc( buflen );\n if ( keybuf == NULL ) {\n rodsLog( LOG_ERROR,\n \"%s: could not allocate memory for key buffer. errno = %d\",\n fname, errno );\n return SYS_MALLOC_ERR;\n }\n nb = read( key_fd, keybuf, buflen );\n if ( nb < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: couldn't read key from %s. errno = %d\",\n fname, keyfile, errno );\n free( keybuf );\n return FILE_READ_ERR;\n }\n close( key_fd );\n\n *key_len = buflen;\n *key = keybuf;\n\n return 0;\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGetAuth - this function runs the OS_AUTH_CMD command to\n * retrieve an authenticator for the calling user.\n *\/\n int\n osauthGetAuth( char *challenge,\n char *username,\n char *authenticator,\n int authenticator_buflen ) {\n#if defined(OS_AUTH)\n static char fname[] = \"osauthGetAuth\";\n int pipe1[2], pipe2[2];\n pid_t childPid;\n int childStatus = 0;\n int child_stdin, child_stdout, nb;\n int buflen, challenge_len = CHALLENGE_LEN;\n char buffer[128];\n\n if ( challenge == NULL || username == NULL || authenticator == NULL ) {\n return USER__NULL_INPUT_ERR;\n }\n\n if ( pipe( pipe1 ) < 0 ) {\n rodsLog( LOG_ERROR, \"%s: pipe1 create failed. errno = %d\",\n fname, errno );\n return SYS_PIPE_ERROR - errno;\n }\n if ( pipe( pipe2 ) < 0 ) {\n rodsLog( LOG_ERROR, \"%s: pipe2 create failed. errno = %d\",\n fname, errno );\n close( pipe1[0] );\n close( pipe1[1] );\n return SYS_PIPE_ERROR - errno;\n }\n\n childPid = RODS_FORK();\n\n if ( childPid < 0 ) {\n rodsLog( LOG_ERROR, \"%s: RODS_FORK failed. errno = %d\",\n fname, errno );\n close( pipe1[0] );\n close( pipe1[1] );\n close( pipe2[0] );\n close( pipe2[1] );\n return SYS_FORK_ERROR;\n }\n else if ( childPid == 0 ) {\n \/* in the child process *\/\n\n \/* pipe1 will be for child's stdin *\/\n close( pipe1[1] );\n dup2( pipe1[0], 0 );\n \/* pipe2 will be for child's stdout *\/\n close( pipe2[0] );\n dup2( pipe2[1], 1 );\n\n \/* set the username in an environment variable *\/\n setenv( OS_AUTH_ENV_USER, username, 1 );\n\n \/* run the OS_AUTH_CMD *\/\n execlp( OS_AUTH_CMD, OS_AUTH_CMD, ( char* )NULL );\n rodsLog( LOG_ERROR, \"%s: child execl %s failed. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n }\n else {\n \/* in the parent process *\/\n close( pipe1[0] );\n child_stdin = pipe1[1]; \/* parent writes to child's stdin *\/\n close( pipe2[1] );\n child_stdout = pipe2[0]; \/* parent reads from child's stdout *\/\n\n \/* send the challenge to the OS_AUTH_CMD program on its stdin *\/\n nb = write( child_stdin, &challenge_len, sizeof( challenge_len ) );\n if ( nb < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: error writing challenge_len to %s. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n close( child_stdin );\n close( child_stdout );\n return SYS_PIPE_ERROR - errno;\n }\n nb = write( child_stdin, challenge, challenge_len );\n if ( nb < 0 ) {\n rodsLog( LOG_ERROR,\n \"%s: error writing challenge to %s. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n close( child_stdin );\n close( child_stdout );\n return SYS_PIPE_ERROR - errno;\n }\n\n \/* read the response *\/\n buflen = read( child_stdout, buffer, 128 );\n if ( buflen < 0 ) {\n rodsLog( LOG_ERROR, \"%s: error reading from %s. errno = %d\",\n fname, OS_AUTH_CMD, errno );\n close( child_stdin );\n close( child_stdout );\n return SYS_PIPE_ERROR - errno;\n }\n\n close( child_stdin );\n close( child_stdout );\n\n if ( waitpid( childPid, &childStatus, 0 ) < 0 ) {\n rodsLog( LOG_ERROR, \"%s: waitpid error. errno = %d\",\n fname, errno );\n return EXEC_CMD_ERROR;\n }\n\n if ( WIFEXITED( childStatus ) ) {\n if ( WEXITSTATUS( childStatus ) ) {\n rodsLog( LOG_ERROR,\n \"%s: command failed: %s\", fname, buffer );\n return EXEC_CMD_ERROR;\n }\n }\n else {\n rodsLog( LOG_ERROR,\n \"%s: some error running %s\", fname, OS_AUTH_CMD );\n }\n\n \/* authenticator is in buffer now *\/\n if ( buflen > authenticator_buflen ) {\n rodsLog( LOG_ERROR,\n \"%s: not enough space in return buffer for authenticator\", fname );\n return EXEC_CMD_OUTPUT_TOO_LARGE;\n }\n memcpy( authenticator, buffer, buflen );\n }\n\n return 0;\n\n#else \/* defined OS_AUTH *\/\n if ( ProcessType == CLIENT_PT ) {\n return OSAUTH_NOT_BUILT_INTO_CLIENT;\n }\n else {\n return OSAUTH_NOT_BUILT_INTO_SERVER;\n }\n#endif\n }\n\n \/*\n * osauthGetUid - looks up the given username using getpwnam\n * and returns the user's uid if successful, or -1 if not.\n *\/\n int\n osauthGetUid( char *username ) {\n static char fname[] = \"osauthGetUid\";\n struct passwd *pwent;\n\n errno = 0;\n pwent = getpwnam( username );\n if ( pwent == NULL ) {\n if ( errno ) {\n rodsLog( LOG_ERROR,\n \"%s: error calling getpwnam for %s. errno = %d\",\n fname, username ? username : \"\", errno );\n return -1;\n }\n else {\n rodsLog( LOG_ERROR,\n \"%s: no such user %s\", fname, username );\n return -1;\n }\n }\n return pwent->pw_uid;\n }\n\n \/*\n * osauthGetUsername - looks up the user identified by\n * the uid determined by getuid(). Places the username\n * in the provided username buffer and returns the uid\n * on success, or -1 if not.\n *\/\n int\n osauthGetUsername( char *username, int username_len ) {\n static char fname[] = \"osauthGetUsername\";\n struct passwd *pwent;\n int uid;\n\n uid = getuid();\n errno = 0;\n pwent = getpwuid( uid );\n if ( pwent == NULL ) {\n if ( errno ) {\n rodsLog( LOG_ERROR,\n \"%s: error calling getpwuid for uid %d. errno = %d\",\n fname, uid, errno );\n return -1;\n }\n else {\n rodsLog( LOG_ERROR, \"%s: no user with uid %d\",\n fname, uid );\n return -1;\n }\n }\n if ( ( unsigned int )username_len <= strlen( pwent->pw_name ) ) {\n rodsLog( LOG_ERROR, \"%s: username input buffer too small (%d <= %d)\",\n fname, username_len, strlen( pwent->pw_name ) );\n return -1;\n }\n strcpy( username, pwent->pw_name );\n\n return uid;\n }\n\n} \/\/ extern \"C\"\n<|endoftext|>"} {"text":"chore(root): add stub for logger builder include#pragma once\n\nnamespace blackhole {\n\n} \/\/ namespace blackhole\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\n#include \"common.hpp\"\n#include \"components\/logger.hpp\"\n#include \"components\/x11\/xresources.hpp\"\n#include \"utils\/file.hpp\"\n#include \"utils\/string.hpp\"\n\nLEMONBUDDY_NS\n\n#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get(section, name, var)\n#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get(section, name)\n\nusing ptree = boost::property_tree::ptree;\n\nDEFINE_ERROR(value_error);\nDEFINE_ERROR(key_error);\n\nclass config {\n public:\n \/**\n * Construct config\n *\/\n explicit config(const logger& logger, const xresource_manager& xrm)\n : m_logger(logger), m_xrm(xrm) {}\n\n \/**\n * Load configuration and validate bar section\n *\n * This is done outside the constructor due to boost::di noexcept\n *\/\n void load(string file, string barname) {\n m_file = file;\n m_current_bar = barname;\n\n if (!file_util::exists(file))\n throw application_error(\"Could not find config file: \" + file);\n\n try {\n boost::property_tree::read_ini(file, m_ptree);\n } catch (const std::exception& e) {\n throw application_error(e.what());\n }\n\n auto bars = defined_bars();\n if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end())\n throw application_error(\"Undefined bar: \" + m_current_bar);\n\n if (has_env(\"XDG_CONFIG_HOME\"))\n file = string_util::replace(file, read_env(\"XDG_CONFIG_HOME\"), \"$XDG_CONFIG_HOME\");\n if (has_env(\"HOME\"))\n file = string_util::replace(file, read_env(\"HOME\"), \"~\");\n m_logger.trace(\"config: Loaded %s\", file);\n m_logger.trace(\"config: Current bar section: [%s]\", bar_section());\n }\n\n \/**\n * Get path of loaded file\n *\/\n string filepath() const {\n return m_file;\n }\n\n \/**\n * Get the section name of the bar in use\n *\/\n string bar_section() const {\n return \"bar\/\" + m_current_bar;\n }\n\n \/**\n * Get a list of defined bar sections in the current config\n *\/\n vector defined_bars() const {\n vector bars;\n\n for (auto&& p : m_ptree) {\n if (p.first.compare(0, 4, \"bar\/\") == 0)\n bars.emplace_back(p.first.substr(4));\n }\n\n return bars;\n }\n\n \/**\n * Build path used to find a parameter in the given section\n *\/\n string build_path(const string& section, const string& key) const {\n return section + \".\" + key;\n }\n\n \/**\n * Get parameter for the current bar by name\n *\/\n template \n T get(string key) const {\n return get(bar_section(), key);\n }\n\n \/**\n * Get value of a variable by section and parameter name\n *\/\n template \n T get(string section, string key) const {\n auto val = m_ptree.get_optional(build_path(section, key));\n\n if (val == boost::none)\n throw key_error(\"Missing parameter [\" + section + \".\" + key + \"]\");\n\n auto str_val = m_ptree.get(build_path(section, key));\n\n return dereference_var(section, key, str_val, val.get());\n }\n\n \/**\n * Get value of a variable by section and parameter name\n * with a default value in case the parameter isn't defined\n *\/\n template \n T get(string section, string key, T default_value) const {\n auto val = m_ptree.get_optional(build_path(section, key));\n auto str_val = m_ptree.get_optional(build_path(section, key));\n\n return dereference_var(\n section, key, str_val.get_value_or(\"\"), val.get_value_or(default_value));\n }\n\n \/**\n * Get list of values for the current bar by name\n *\/\n template \n T get_list(string key) const {\n return get_list(bar_section(), key);\n }\n\n \/**\n * Get list of values by section and parameter name\n *\/\n template \n vector get_list(string section, string key) const {\n vector vec;\n optional value;\n\n while ((value = m_ptree.get_optional(\n build_path(section, key) + \"-\" + to_string(vec.size()))) != boost::none) {\n auto str_val = m_ptree.get(build_path(section, key) + \"-\" + to_string(vec.size()));\n vec.emplace_back(dereference_var(section, key, str_val, value.get()));\n }\n\n if (vec.empty())\n throw key_error(\"Missing parameter [\" + section + \".\" + key + \"-0]\");\n\n return vec;\n }\n\n \/**\n * Get list of values by section and parameter name\n * with a default list in case the list isn't defined\n *\/\n template \n vector get_list(string section, string key, vector default_value) const {\n vector vec;\n optional value;\n\n while ((value = m_ptree.get_optional(\n build_path(section, key) + \"-\" + to_string(vec.size()))) != boost::none) {\n auto str_val = m_ptree.get(build_path(section, key) + \"-\" + to_string(vec.size()));\n vec.emplace_back(dereference_var(section, key, str_val, value.get()));\n }\n\n if (vec.empty())\n return default_value;\n else\n return vec;\n }\n\n \/**\n * Configure injection module\n *\/\n template \n static di::injector configure() {\n return di::make_injector(logger::configure(), xresource_manager::configure());\n }\n\n protected:\n \/**\n * Find value of a config parameter defined as a reference\n * variable using ${section.param} or ${env:VAR}\n * ${self.key} may be used to reference the current bar section\n *\n * @deprecated: ${BAR.key} has been replaced with ${self.key}\n * but the former is kept to avoid breaking current configs\n *\/\n template \n T dereference_var(string ref_section, string ref_key, string var, const T ref_val) const {\n auto n = var.find(\"${\");\n auto m = var.find(\"}\");\n\n if (n != 0 || m != var.length() - 1)\n return ref_val;\n\n auto path = var.substr(2, m - 2);\n\n if (path.find(\"env:\") == 0) {\n if (has_env(path.substr(4).c_str()))\n return boost::lexical_cast(read_env(path.substr(4).c_str()));\n return ref_val;\n }\n\n if (path.find(\"xrdb:\") == 0) {\n if (std::is_same())\n return boost::lexical_cast(m_xrm.get_string(path.substr(5)));\n else if (std::is_same())\n return boost::lexical_cast(m_xrm.get_float(path.substr(5)));\n else if (std::is_same())\n return boost::lexical_cast(m_xrm.get_int(path.substr(5)));\n }\n\n auto ref_path = build_path(ref_section, ref_key);\n\n if ((n = path.find(\".\")) == string::npos)\n throw value_error(\"Invalid reference defined at [\" + ref_path + \"]\");\n\n auto section = path.substr(0, n);\n\n section = string_util::replace(section, \"BAR\", bar_section());\n section = string_util::replace(section, \"self\", bar_section());\n\n auto key = path.substr(n + 1, path.length() - n - 1);\n auto val = m_ptree.get_optional(build_path(section, key));\n\n if (val == boost::none)\n throw value_error(\"Unexisting reference defined at [\" + ref_path + \"]\");\n\n auto str_val = m_ptree.get(build_path(section, key));\n\n return dereference_var(section, key, str_val, val.get());\n }\n\n private:\n const logger& m_logger;\n const xresource_manager& m_xrm;\n ptree m_ptree;\n string m_file;\n string m_current_bar;\n};\n\nLEMONBUDDY_NS_END\nfix(config): Test type and not value#pragma once\n\n#include \n#include \n#include \n\n#include \"common.hpp\"\n#include \"components\/logger.hpp\"\n#include \"components\/x11\/xresources.hpp\"\n#include \"utils\/file.hpp\"\n#include \"utils\/string.hpp\"\n\nLEMONBUDDY_NS\n\n#define GET_CONFIG_VALUE(section, var, name) var = m_conf.get(section, name, var)\n#define REQ_CONFIG_VALUE(section, var, name) var = m_conf.get(section, name)\n\nusing ptree = boost::property_tree::ptree;\n\nDEFINE_ERROR(value_error);\nDEFINE_ERROR(key_error);\n\nclass config {\n public:\n \/**\n * Construct config\n *\/\n explicit config(const logger& logger, const xresource_manager& xrm)\n : m_logger(logger), m_xrm(xrm) {}\n\n \/**\n * Load configuration and validate bar section\n *\n * This is done outside the constructor due to boost::di noexcept\n *\/\n void load(string file, string barname) {\n m_file = file;\n m_current_bar = barname;\n\n if (!file_util::exists(file))\n throw application_error(\"Could not find config file: \" + file);\n\n try {\n boost::property_tree::read_ini(file, m_ptree);\n } catch (const std::exception& e) {\n throw application_error(e.what());\n }\n\n auto bars = defined_bars();\n if (std::find(bars.begin(), bars.end(), m_current_bar) == bars.end())\n throw application_error(\"Undefined bar: \" + m_current_bar);\n\n if (has_env(\"XDG_CONFIG_HOME\"))\n file = string_util::replace(file, read_env(\"XDG_CONFIG_HOME\"), \"$XDG_CONFIG_HOME\");\n if (has_env(\"HOME\"))\n file = string_util::replace(file, read_env(\"HOME\"), \"~\");\n m_logger.trace(\"config: Loaded %s\", file);\n m_logger.trace(\"config: Current bar section: [%s]\", bar_section());\n }\n\n \/**\n * Get path of loaded file\n *\/\n string filepath() const {\n return m_file;\n }\n\n \/**\n * Get the section name of the bar in use\n *\/\n string bar_section() const {\n return \"bar\/\" + m_current_bar;\n }\n\n \/**\n * Get a list of defined bar sections in the current config\n *\/\n vector defined_bars() const {\n vector bars;\n\n for (auto&& p : m_ptree) {\n if (p.first.compare(0, 4, \"bar\/\") == 0)\n bars.emplace_back(p.first.substr(4));\n }\n\n return bars;\n }\n\n \/**\n * Build path used to find a parameter in the given section\n *\/\n string build_path(const string& section, const string& key) const {\n return section + \".\" + key;\n }\n\n \/**\n * Get parameter for the current bar by name\n *\/\n template \n T get(string key) const {\n return get(bar_section(), key);\n }\n\n \/**\n * Get value of a variable by section and parameter name\n *\/\n template \n T get(string section, string key) const {\n auto val = m_ptree.get_optional(build_path(section, key));\n\n if (val == boost::none)\n throw key_error(\"Missing parameter [\" + section + \".\" + key + \"]\");\n\n auto str_val = m_ptree.get(build_path(section, key));\n\n return dereference_var(section, key, str_val, val.get());\n }\n\n \/**\n * Get value of a variable by section and parameter name\n * with a default value in case the parameter isn't defined\n *\/\n template \n T get(string section, string key, T default_value) const {\n auto val = m_ptree.get_optional(build_path(section, key));\n auto str_val = m_ptree.get_optional(build_path(section, key));\n\n return dereference_var(\n section, key, str_val.get_value_or(\"\"), val.get_value_or(default_value));\n }\n\n \/**\n * Get list of values for the current bar by name\n *\/\n template \n T get_list(string key) const {\n return get_list(bar_section(), key);\n }\n\n \/**\n * Get list of values by section and parameter name\n *\/\n template \n vector get_list(string section, string key) const {\n vector vec;\n optional value;\n\n while ((value = m_ptree.get_optional(\n build_path(section, key) + \"-\" + to_string(vec.size()))) != boost::none) {\n auto str_val = m_ptree.get(build_path(section, key) + \"-\" + to_string(vec.size()));\n vec.emplace_back(dereference_var(section, key, str_val, value.get()));\n }\n\n if (vec.empty())\n throw key_error(\"Missing parameter [\" + section + \".\" + key + \"-0]\");\n\n return vec;\n }\n\n \/**\n * Get list of values by section and parameter name\n * with a default list in case the list isn't defined\n *\/\n template \n vector get_list(string section, string key, vector default_value) const {\n vector vec;\n optional value;\n\n while ((value = m_ptree.get_optional(\n build_path(section, key) + \"-\" + to_string(vec.size()))) != boost::none) {\n auto str_val = m_ptree.get(build_path(section, key) + \"-\" + to_string(vec.size()));\n vec.emplace_back(dereference_var(section, key, str_val, value.get()));\n }\n\n if (vec.empty())\n return default_value;\n else\n return vec;\n }\n\n \/**\n * Configure injection module\n *\/\n template \n static di::injector configure() {\n return di::make_injector(logger::configure(), xresource_manager::configure());\n }\n\n protected:\n \/**\n * Find value of a config parameter defined as a reference\n * variable using ${section.param} or ${env:VAR}\n * ${self.key} may be used to reference the current bar section\n *\n * @deprecated: ${BAR.key} has been replaced with ${self.key}\n * but the former is kept to avoid breaking current configs\n *\/\n template \n T dereference_var(string ref_section, string ref_key, string var, const T ref_val) const {\n auto n = var.find(\"${\");\n auto m = var.find(\"}\");\n\n if (n != 0 || m != var.length() - 1)\n return ref_val;\n\n auto path = var.substr(2, m - 2);\n\n if (path.find(\"env:\") == 0) {\n if (has_env(path.substr(4).c_str()))\n return boost::lexical_cast(read_env(path.substr(4).c_str()));\n return ref_val;\n }\n\n if (path.find(\"xrdb:\") == 0) {\n if (std::is_same::value)\n return boost::lexical_cast(m_xrm.get_string(path.substr(5)));\n else if (std::is_same::value)\n return boost::lexical_cast(m_xrm.get_float(path.substr(5)));\n else if (std::is_same::value)\n return boost::lexical_cast(m_xrm.get_int(path.substr(5)));\n return ref_val;\n }\n\n auto ref_path = build_path(ref_section, ref_key);\n\n if ((n = path.find(\".\")) == string::npos)\n throw value_error(\"Invalid reference defined at [\" + ref_path + \"]\");\n\n auto section = path.substr(0, n);\n\n section = string_util::replace(section, \"BAR\", bar_section());\n section = string_util::replace(section, \"self\", bar_section());\n\n auto key = path.substr(n + 1, path.length() - n - 1);\n auto val = m_ptree.get_optional(build_path(section, key));\n\n if (val == boost::none)\n throw value_error(\"Unexisting reference defined at [\" + ref_path + \"]\");\n\n auto str_val = m_ptree.get(build_path(section, key));\n\n return dereference_var(section, key, str_val, val.get());\n }\n\n private:\n const logger& m_logger;\n const xresource_manager& m_xrm;\n ptree m_ptree;\n string m_file;\n string m_current_bar;\n};\n\nLEMONBUDDY_NS_END\n<|endoftext|>"} {"text":"#pragma once\n\/*\n* Covariant Script Version Info\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n* Copyright (C) 2018 Michael Lee(李登淳)\n* Email: mikecovlee@163.com\n* Github: https:\/\/github.com\/mikecovlee\n*\n* Version Format:\n* 1 . 0 . 0 [Version Code](Preview\/Unstable\/Stable) Build 1\n* | | | |\n* | | Minor Status\n* | Major\n* Master\n*\n*\/\n#define COVSCRIPT_VERSION_NUM 3,0,1,2\n#define COVSCRIPT_VERSION_STR \"3.0.1 Acipenser sinensis(Stable) Build 2\"\n#define COVSCRIPT_STD_VERSION 190101\n#define COVSCRIPT_ABI_VERSION 190101\n#if defined(_WIN32) || defined(WIN32)\n#define COVSCRIPT_PLATFORM_WIN32\n#endif\nUpdate version.hpp#pragma once\n\/*\n* Covariant Script Version Info\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\n* Copyright (C) 2018 Michael Lee(李登淳)\n* Email: mikecovlee@163.com\n* Github: https:\/\/github.com\/mikecovlee\n*\n* Version Format:\n* 1 . 0 . 0 [Version Code](Preview\/Unstable\/Stable) Build 1\n* | | | |\n* | | Minor Status\n* | Major\n* Master\n*\n*\/\n#define COVSCRIPT_VERSION_NUM 3,0,2,2\n#define COVSCRIPT_VERSION_STR \"3.0.2 Acipenser sinensis(Unstable) Build 2\"\n#define COVSCRIPT_STD_VERSION 190101\n#define COVSCRIPT_ABI_VERSION 190101\n#if defined(_WIN32) || defined(WIN32)\n#define COVSCRIPT_PLATFORM_WIN32\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014 Eran Pe'er.\n *\n * This program is made available under the terms of the MIT License.\n *\n * Created on Mar 10, 2014\n *\/\n\n#ifndef MethodMock_h__\n#define MethodMock_h__\n\n#include \n#include \n#include \n#include \n\n#include \"mockutils\/TupleDispatcher.hpp\"\n#include \"fakeit\/DomainObjects.hpp\"\n#include \"fakeit\/ActualInvocation.hpp\"\n#include \"fakeit\/Behavior.hpp\"\n\nnamespace fakeit {\n\nstatic std::atomic_int invocationOrdinal;\n\ntemplate\nstruct MethodInvocationMock: public ActualInvocation::Matcher, public MethodInvocationHandler {\n\n\tvirtual std::shared_ptr::Matcher> getMatcher()= 0;\n\n};\n\nclass finally {\nprivate:\n\tstd::function finallyClause;\n\tfinally(const finally &);\n\tfinally& operator=(const finally &);\npublic:\n\texplicit finally(std::function f) :\n\t\t\tfinallyClause(f) {\n\t}\n\n\t~finally() {\n\t\tfinallyClause();\n\t}\n};\n\nclass NoMoreRecordedBehaviorException : public std::exception {\n\n};\n\ntemplate\nstruct RecordedMethodBody: public MethodInvocationHandler {\n\n\tRecordedMethodBody(Method & method): method(method) {\n\t\tclear();\n\t}\n\n\tvoid AppendDo(std::function method) {\n\t\tstd::shared_ptr> doMock = std::shared_ptr> { new Repeat(\n\t\t\t\tmethod) };\n\t\tAppendDo(doMock);\n\t}\n\n\tvoid LastDo(std::function method) {\n\t\tstd::shared_ptr> doMock = std::shared_ptr> { new Repeat(\n\t\t\t\tmethod) };\n\t\tLastDo(doMock);\n\t}\n\n\tvoid AppendDo(std::shared_ptr > doMock) {\n\t\tappend(doMock);\n\t}\n\n\tvoid LastDo(std::shared_ptr > doMock) {\n\t\tappend(doMock);\n\t\tbehaviorMocks.pop_back();\n\t}\n\n\tR handleMethodInvocation(arglist&... args) override {\n\t\tstd::shared_ptr> behavior = behaviorMocks.front();\n\t\tstd::function < void() > finallyClause = [&]()->void {\n\t\t\tif (behavior->isDone())\n\t\t\tbehaviorMocks.erase(behaviorMocks.begin());\n\t\t};\n\t\tfinally onExit(finallyClause);\n\t\treturn behavior->invoke(args...);\n\t}\n\nprivate:\n\n\n\tstruct ThrowUnexpectedMethodCall: public Behavior {\n\n\t\tvirtual ~ThrowUnexpectedMethodCall() = default;\n\n\t\tvirtual R invoke(arglist&... args) override {\n\t\t\tNoMoreRecordedBehaviorException e;\n\t\t\tthrow e;\n\t\t}\n\n\t\tvirtual bool isDone() override {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tMethod & method;\n\n\tvoid append(std::shared_ptr> mock) {\n\t\tbehaviorMocks.insert(behaviorMocks.end() - 1, mock);\n\t}\n\n\tvoid clear() {\n\t\tbehaviorMocks.clear();\n\t\tauto doMock = std::shared_ptr> { new ThrowUnexpectedMethodCall() };\n\t\tbehaviorMocks.push_back(doMock);\n\t}\n\n\tstd::vector>>behaviorMocks;\n};\n\ntemplate\nstruct MethodInvocationMockBase: public virtual MethodInvocationMock {\n\n\tMethodInvocationMockBase(const Method& method, std::shared_ptr::Matcher> matcher,\n\t\t\tstd::shared_ptr> invocationHandler) :\n\t\t\tmethod(method), matcher { matcher }, invocationHandler { invocationHandler } {\n\t}\n\n\tR handleMethodInvocation(arglist&... args) override {\n\t\treturn invocationHandler->handleMethodInvocation(args...);\n\t}\n\n\tvirtual bool matches(ActualInvocation& actualInvocation) {\n\t\treturn matcher->matches(actualInvocation);\n\t}\n\n\tstd::shared_ptr::Matcher> getMatcher() override {\n\t\treturn matcher;\n\t}\n\nprivate:\n\tconst Method& method;\n\tstd::shared_ptr::Matcher> matcher;\n\tstd::shared_ptr> invocationHandler;\n};\n\ntemplate\nstruct ExpectedArgumentsInvocationMatcher: public ActualInvocation::Matcher {\n\tExpectedArgumentsInvocationMatcher(const arglist&... args) :\n\t\t\texpectedArguments(args...) {\n\t}\n\n\tvirtual bool matches(ActualInvocation& invocation) override {\n\t\tif (invocation.getActualMatcher().get() == this)\n\t\t\treturn true;\n\t\treturn matches(invocation.getActualArguments());\n\t}\nprivate:\n\tvirtual bool matches(const std::tuple& actualArgs) {\n\t\treturn expectedArguments == actualArgs;\n\t}\n\tconst std::tuple expectedArguments;\n};\n\ntemplate\nstruct UserDefinedInvocationMatcher: public ActualInvocation::Matcher {\n\tUserDefinedInvocationMatcher(std::function matcher) :\n\t\t\tmatcher { matcher } {\n\t}\n\n\tvirtual bool matches(ActualInvocation& invocation) override {\n\t\tif (invocation.getActualMatcher().get() == this)\n\t\t\treturn true;\n\t\treturn matches(invocation.getActualArguments());\n\t}\nprivate:\n\tvirtual bool matches(const std::tuple& actualArgs) {\n\t\treturn invoke(matcher, std::tuple { actualArgs });\n\t}\n\tstd::function matcher;\n};\n\ntemplate\nstruct DefaultInvocationMatcher: public ActualInvocation::Matcher {\n\tDefaultInvocationMatcher() {\n\t}\n\n\tvirtual bool matches(ActualInvocation& invocation) override {\n\t\treturn matches(invocation.getActualArguments());\n\t}\n\nprivate:\n\tvirtual bool matches(const std::tuple& actualArgs) {\n\t\treturn true;\n\t}\n};\n\n\ntemplate\nclass MethodMock: public virtual MethodInvocationHandler, public virtual ActualInvocationsSource {\n\n\tclass MethodImpl : public Method {\n\t\tstd::string _name;\n\tpublic:\n\t\tMethodImpl(std::string name):_name(name){}\n\n\t\tvirtual std::string name() const override {\n\t\t\treturn _name;\n\t\t}\n\n\t\tvoid setName(const std::string& name){\n\t\t\t_name = name;\n\t\t}\n\t};\n\n\tMockObject& mock;\n\tR (C::*vMethod)(arglist...);\n\tMethodImpl method;\n\tstd::vector>>methodInvocationMocks;\n\tstd::vector>> actualInvocations;\n\n\tstd::shared_ptr> buildMethodInvocationMock(\n\t\t\tstd::shared_ptr::Matcher> invocationMatcher,\n\t\t\tstd::shared_ptr> invocationHandler) {\n\t\treturn std::shared_ptr> {\n\t\t\tnew MethodInvocationMockBase(this->getMethod(), invocationMatcher,\n\t\t\t\t\tinvocationHandler)};\n\t}\n\n\tstd::shared_ptr> getMethodInvocationMockForActualArgs(ActualInvocation& invocation) {\n\t\tfor (auto i = methodInvocationMocks.rbegin(); i != methodInvocationMocks.rend(); ++i) {\n\t\t\tif ((*i)->matches(invocation)) {\n\t\t\t\treturn (*i);\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\npublic:\n\n\tMethodMock(MockObject& mock, R (C::*vMethod)(arglist...)) :\n\t\t\tmock(mock), vMethod(vMethod), method{typeid(vMethod).name()} {\n\t}\n\n\tvirtual ~MethodMock() {\n\t}\n\n\tMethod& getMethod() {\n\t\treturn method;\n\t}\n\n\tvoid stubMethodInvocation(std::shared_ptr::Matcher> invocationMatcher,\n\t\t\tstd::shared_ptr> invocationHandler) {\n\t\tauto mock = buildMethodInvocationMock(invocationMatcher, invocationHandler);\n\t\tmethodInvocationMocks.push_back(mock);\n\t}\n\n\tvoid clear() {\n\t\tmethodInvocationMocks.clear();\n\t}\n\n\tR handleMethodInvocation(arglist&... args) override {\n\t\tint ordinal = invocationOrdinal++;\n\t\tauto actualInvoaction = std::shared_ptr> { new ActualInvocation(ordinal, this->getMethod(),\n\t\t\t\targs...) };\n\t\tauto methodInvocationMock = getMethodInvocationMockForActualArgs(*actualInvoaction);\n\t\tif (!methodInvocationMock) {\n\t\t\tUnexpectedMethodCallException e(this->method);\n\t\t\tFakeIt::log(e);\n\t\t\tthrow e;\n\t\t}\n\t\tauto matcher = methodInvocationMock->getMatcher();\n\t\tactualInvoaction->setActualMatcher(matcher);\n\t\tactualInvocations.push_back(actualInvoaction);\n\t\ttry {\n\t\t\treturn methodInvocationMock->handleMethodInvocation(args...);\n\t\t} catch (NoMoreRecordedBehaviorException&){\n\t\t\tUnexpectedMethodCallException e(this->method);\n\t\t\tFakeIt::log(e);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tstd::vector> > getActualInvocations(\n\t\t\ttypename ActualInvocation::Matcher& matcher) {\n\t\tstd::vector < std::shared_ptr> > result;\n\t\tfor (auto actualInvocation : actualInvocations) {\n\t\t\tif (matcher.matches(*actualInvocation)) {\n\t\t\t\tresult.push_back(actualInvocation);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid getActualInvocations(std::unordered_set& into) const {\n\t\tfor (auto invocation : actualInvocations) {\n\t\t\tinto.insert(invocation.get());\n\t\t}\n\t}\n\n\tvoid setMethodDetails(const std::string& mockName, const std::string& methodName) {\n\t\tconst std::string fullName {mockName + \".\" + methodName};\n\t\tmethod.setName(fullName);\n\t}\n\n};\n\n}\n\n#endif \/\/ MethodMock_h__\nRefactor. Improve class names.\/*\n * Copyright (c) 2014 Eran Pe'er.\n *\n * This program is made available under the terms of the MIT License.\n *\n * Created on Mar 10, 2014\n *\/\n\n#ifndef MethodMock_h__\n#define MethodMock_h__\n\n#include \n#include \n#include \n#include \n\n#include \"mockutils\/TupleDispatcher.hpp\"\n#include \"fakeit\/DomainObjects.hpp\"\n#include \"fakeit\/ActualInvocation.hpp\"\n#include \"fakeit\/Behavior.hpp\"\n\nnamespace fakeit {\n\nstatic std::atomic_int invocationOrdinal;\n\ntemplate\nstruct MethodInvocationMock: public ActualInvocation::Matcher, public MethodInvocationHandler {\n\n\tvirtual ~MethodInvocationMock() = default;\n\n\tvirtual std::shared_ptr::Matcher> getMatcher()= 0;\n\n};\n\nclass finally {\nprivate:\n\tstd::function finallyClause;\n\tfinally(const finally &);\n\tfinally& operator=(const finally &);\npublic:\n\texplicit finally(std::function f) :\n\t\t\tfinallyClause(f) {\n\t}\n\n\t~finally() {\n\t\tfinallyClause();\n\t}\n};\n\nclass NoMoreRecordedBehaviorException : public std::exception {\n\n};\n\ntemplate\nstruct RecordedMethodBody: public MethodInvocationHandler {\n\n\tRecordedMethodBody(Method & method): method(method) {\n\t\tclear();\n\t}\n\n\tvoid AppendDo(std::function method) {\n\t\tstd::shared_ptr> doMock = std::shared_ptr> { new Repeat(\n\t\t\t\tmethod) };\n\t\tAppendDo(doMock);\n\t}\n\n\tvoid LastDo(std::function method) {\n\t\tstd::shared_ptr> doMock = std::shared_ptr> { new Repeat(\n\t\t\t\tmethod) };\n\t\tLastDo(doMock);\n\t}\n\n\tvoid AppendDo(std::shared_ptr > doMock) {\n\t\tappend(doMock);\n\t}\n\n\tvoid LastDo(std::shared_ptr > doMock) {\n\t\tappend(doMock);\n\t\tbehaviorMocks.pop_back();\n\t}\n\n\tR handleMethodInvocation(arglist&... args) override {\n\t\tstd::shared_ptr> behavior = behaviorMocks.front();\n\t\tstd::function < void() > finallyClause = [&]()->void {\n\t\t\tif (behavior->isDone())\n\t\t\tbehaviorMocks.erase(behaviorMocks.begin());\n\t\t};\n\t\tfinally onExit(finallyClause);\n\t\treturn behavior->invoke(args...);\n\t}\n\nprivate:\n\n\tstruct NoMoreRecordedBehavior: public Behavior {\n\n\t\tvirtual ~NoMoreRecordedBehavior() = default;\n\n\t\tvirtual R invoke(arglist&... args) override {\n\t\t\tNoMoreRecordedBehaviorException e;\n\t\t\tthrow e;\n\t\t}\n\n\t\tvirtual bool isDone() override {\n\t\t\treturn false;\n\t\t}\n\t};\n\n\tMethod & method;\n\n\tvoid append(std::shared_ptr> mock) {\n\t\tbehaviorMocks.insert(behaviorMocks.end() - 1, mock);\n\t}\n\n\tvoid clear() {\n\t\tbehaviorMocks.clear();\n\t\tauto doMock = std::shared_ptr> { new NoMoreRecordedBehavior() };\n\t\tbehaviorMocks.push_back(doMock);\n\t}\n\n\tstd::vector>>behaviorMocks;\n};\n\ntemplate\nstruct MethodInvocationMockBase: public virtual MethodInvocationMock {\n\n\tvirtual ~MethodInvocationMockBase() = default;\n\n\tMethodInvocationMockBase(const Method& method, std::shared_ptr::Matcher> matcher,\n\t\t\tstd::shared_ptr> invocationHandler) :\n\t\t\tmethod(method), matcher { matcher }, invocationHandler { invocationHandler } {\n\t}\n\n\tR handleMethodInvocation(arglist&... args) override {\n\t\treturn invocationHandler->handleMethodInvocation(args...);\n\t}\n\n\tvirtual bool matches(ActualInvocation& actualInvocation) {\n\t\treturn matcher->matches(actualInvocation);\n\t}\n\n\tstd::shared_ptr::Matcher> getMatcher() override {\n\t\treturn matcher;\n\t}\n\nprivate:\n\tconst Method& method;\n\tstd::shared_ptr::Matcher> matcher;\n\tstd::shared_ptr> invocationHandler;\n};\n\ntemplate\nstruct ExpectedArgumentsInvocationMatcher: public ActualInvocation::Matcher {\n\n\tvirtual ~ExpectedArgumentsInvocationMatcher() = default;\n\n\tExpectedArgumentsInvocationMatcher(const arglist&... args) :\n\t\t\texpectedArguments(args...) {\n\t}\n\n\tvirtual bool matches(ActualInvocation& invocation) override {\n\t\tif (invocation.getActualMatcher().get() == this)\n\t\t\treturn true;\n\t\treturn matches(invocation.getActualArguments());\n\t}\n\nprivate:\n\tvirtual bool matches(const std::tuple& actualArgs) {\n\t\treturn expectedArguments == actualArgs;\n\t}\n\tconst std::tuple expectedArguments;\n};\n\ntemplate\nstruct UserDefinedInvocationMatcher: public ActualInvocation::Matcher {\n\tvirtual ~UserDefinedInvocationMatcher() = default;\n\n\tUserDefinedInvocationMatcher(std::function matcher) :\n\t\t\tmatcher { matcher } {\n\t}\n\n\tvirtual bool matches(ActualInvocation& invocation) override {\n\t\tif (invocation.getActualMatcher().get() == this)\n\t\t\treturn true;\n\t\treturn matches(invocation.getActualArguments());\n\t}\nprivate:\n\tvirtual bool matches(const std::tuple& actualArgs) {\n\t\treturn invoke(matcher, std::tuple { actualArgs });\n\t}\n\tstd::function matcher;\n};\n\ntemplate\nstruct DefaultInvocationMatcher: public ActualInvocation::Matcher {\n\n\tvirtual ~DefaultInvocationMatcher() = default;\n\n\tDefaultInvocationMatcher() {\n\t}\n\n\tvirtual bool matches(ActualInvocation& invocation) override {\n\t\treturn matches(invocation.getActualArguments());\n\t}\n\nprivate:\n\tvirtual bool matches(const std::tuple& actualArgs) {\n\t\treturn true;\n\t}\n};\n\n\ntemplate\nclass MethodMock: public virtual MethodInvocationHandler, public virtual ActualInvocationsSource {\n\n\tclass MethodImpl : public Method {\n\t\tstd::string _name;\n\tpublic:\n\t\tMethodImpl(std::string name):_name(name){}\n\n\t\tvirtual std::string name() const override {\n\t\t\treturn _name;\n\t\t}\n\n\t\tvoid setName(const std::string& name){\n\t\t\t_name = name;\n\t\t}\n\t};\n\n\tMockObject& mock;\n\tR (C::*vMethod)(arglist...);\n\tMethodImpl method;\n\tstd::vector>>methodInvocationMocks;\n\tstd::vector>> actualInvocations;\n\n\tstd::shared_ptr> buildMethodInvocationMock(\n\t\t\tstd::shared_ptr::Matcher> invocationMatcher,\n\t\t\tstd::shared_ptr> invocationHandler) {\n\t\treturn std::shared_ptr> {\n\t\t\tnew MethodInvocationMockBase(this->getMethod(), invocationMatcher,\n\t\t\t\t\tinvocationHandler)};\n\t}\n\n\tstd::shared_ptr> getMethodInvocationMockForActualArgs(ActualInvocation& invocation) {\n\t\tfor (auto i = methodInvocationMocks.rbegin(); i != methodInvocationMocks.rend(); ++i) {\n\t\t\tif ((*i)->matches(invocation)) {\n\t\t\t\treturn (*i);\n\t\t\t}\n\t\t}\n\t\treturn nullptr;\n\t}\n\npublic:\n\n\tMethodMock(MockObject& mock, R (C::*vMethod)(arglist...)) :\n\t\t\tmock(mock), vMethod(vMethod), method{typeid(vMethod).name()} {\n\t}\n\n\tvirtual ~MethodMock() {\n\t}\n\n\tMethod& getMethod() {\n\t\treturn method;\n\t}\n\n\tvoid stubMethodInvocation(std::shared_ptr::Matcher> invocationMatcher,\n\t\t\tstd::shared_ptr> invocationHandler) {\n\t\tauto mock = buildMethodInvocationMock(invocationMatcher, invocationHandler);\n\t\tmethodInvocationMocks.push_back(mock);\n\t}\n\n\tvoid clear() {\n\t\tmethodInvocationMocks.clear();\n\t}\n\n\tR handleMethodInvocation(arglist&... args) override {\n\t\tint ordinal = invocationOrdinal++;\n\t\tauto actualInvoaction = std::shared_ptr> { new ActualInvocation(ordinal, this->getMethod(),\n\t\t\t\targs...) };\n\t\tauto methodInvocationMock = getMethodInvocationMockForActualArgs(*actualInvoaction);\n\t\tif (!methodInvocationMock) {\n\t\t\tUnexpectedMethodCallException e(this->method);\n\t\t\tFakeIt::log(e);\n\t\t\tthrow e;\n\t\t}\n\t\tauto matcher = methodInvocationMock->getMatcher();\n\t\tactualInvoaction->setActualMatcher(matcher);\n\t\tactualInvocations.push_back(actualInvoaction);\n\t\ttry {\n\t\t\treturn methodInvocationMock->handleMethodInvocation(args...);\n\t\t} catch (NoMoreRecordedBehaviorException&){\n\t\t\tUnexpectedMethodCallException e(this->method);\n\t\t\tFakeIt::log(e);\n\t\t\tthrow e;\n\t\t}\n\t}\n\n\tstd::vector> > getActualInvocations(\n\t\t\ttypename ActualInvocation::Matcher& matcher) {\n\t\tstd::vector < std::shared_ptr> > result;\n\t\tfor (auto actualInvocation : actualInvocations) {\n\t\t\tif (matcher.matches(*actualInvocation)) {\n\t\t\t\tresult.push_back(actualInvocation);\n\t\t\t}\n\t\t}\n\t\treturn result;\n\t}\n\n\tvoid getActualInvocations(std::unordered_set& into) const {\n\t\tfor (auto invocation : actualInvocations) {\n\t\t\tinto.insert(invocation.get());\n\t\t}\n\t}\n\n\tvoid setMethodDetails(const std::string& mockName, const std::string& methodName) {\n\t\tconst std::string fullName {mockName + \".\" + methodName};\n\t\tmethod.setName(fullName);\n\t}\n\n};\n\n}\n\n#endif \/\/ MethodMock_h__\n<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_METAWRITER_HPP\n#define MAPNIK_METAWRITER_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\n\/\/ stl\n#include \n#include \n\n\nnamespace mapnik {\n\nclass text_placement_info;\nclass text_path;\n\n\/** Implementation of std::map that also returns const& for operator[]. *\/\nclass metawriter_property_map\n{\npublic:\n typedef std::map property_map;\n typedef property_map::const_iterator const_iterator;\n\n metawriter_property_map() :\n m_(),\n not_found_() {}\n\n UnicodeString const& operator[](std::string const& key) const;\n UnicodeString& operator[](std::string const& key) {return m_[key];}\n\n std::map::const_iterator find(std::string const& key) const\n {\n return m_.find(key);\n }\n\n std::map::const_iterator end() const\n {\n return m_.end();\n }\n\n UnicodeString const& get(std::string const& key) const\n {\n return (*this)[key];\n }\n\nprivate:\n property_map m_;\n UnicodeString not_found_;\n};\n\n\n\/** All properties to be output by a metawriter. *\/\nclass metawriter_properties : public std::set\n{\npublic:\n metawriter_properties(boost::optional str);\n metawriter_properties() {}\n template metawriter_properties(\n InputIterator first, InputIterator last) : std::set(first, last) {}\n std::string to_string() const;\n};\n\n\/** Abstract baseclass for all metawriter classes. *\/\nclass metawriter\n{\npublic:\n typedef coord_transform path_type;\n metawriter(metawriter_properties dflt_properties) :\n dflt_properties_(dflt_properties),\n width_(0),\n height_(0) {}\n virtual ~metawriter() {}\n \/** Output a rectangular area.\n * \\param box Area (in pixel coordinates)\n * \\param feature The feature being processed\n * \\param prj_trans Projection transformation\n * \\param t Coordinate transformation\n * \\param properties List of properties to output\n *\/\n virtual void add_box(box2d const& box, Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n virtual void add_text(boost::ptr_vector &placements,\n box2d const& extents,\n Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n virtual void add_polygon(path_type & path,\n Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n virtual void add_line(path_type & path,\n Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n\n \/** Start processing.\n * Write file header, init database connection, ...\n *\n * \\param properties metawriter_property_map object with userdefined values.\n * Useful for setting filename etc.\n *\/\n virtual void start(metawriter_property_map const& properties)\n {\n boost::ignore_unused_variable_warning(properties);\n }\n\n \/** Stop processing.\n * Write file footer, close database connection, ...\n *\/\n virtual void stop() {}\n \/** Set output size (pixels).\n * All features that are completely outside this size are discarded.\n *\/\n void set_size(int width, int height) { width_ = width; height_ = height; }\n \/** Set Map object's srs. *\/\n virtual void set_map_srs(projection const& proj) { \/* Not required when working with image coordinates. *\/ }\n \/** Return the list of default properties. *\/\n metawriter_properties const& get_default_properties() const { return dflt_properties_;}\nprotected:\n metawriter_properties dflt_properties_;\n \/** Output width (pixels). *\/\n int width_;\n \/** Output height (pixels). *\/\n int height_;\n};\n\n\/** Shared pointer to metawriter object. *\/\ntypedef boost::shared_ptr metawriter_ptr;\n\/** Metawriter object + properties. *\/\ntypedef std::pair metawriter_with_properties;\n\n}\n\n#endif \/\/ MAPNIK_METAWRITER_HPP\n+ fix unused parameter warning\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2011 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_METAWRITER_HPP\n#define MAPNIK_METAWRITER_HPP\n\n\/\/ mapnik\n#include \n#include \n#include \n\n\/\/ boost\n#include \n#include \n#include \n#include \n\n\/\/ stl\n#include \n#include \n\n\nnamespace mapnik {\n\nclass text_placement_info;\nclass text_path;\n\n\/** Implementation of std::map that also returns const& for operator[]. *\/\nclass metawriter_property_map\n{\npublic:\n typedef std::map property_map;\n typedef property_map::const_iterator const_iterator;\n\n metawriter_property_map() :\n m_(),\n not_found_() {}\n\n UnicodeString const& operator[](std::string const& key) const;\n UnicodeString& operator[](std::string const& key) {return m_[key];}\n\n std::map::const_iterator find(std::string const& key) const\n {\n return m_.find(key);\n }\n\n std::map::const_iterator end() const\n {\n return m_.end();\n }\n\n UnicodeString const& get(std::string const& key) const\n {\n return (*this)[key];\n }\n\nprivate:\n property_map m_;\n UnicodeString not_found_;\n};\n\n\n\/** All properties to be output by a metawriter. *\/\nclass metawriter_properties : public std::set\n{\npublic:\n metawriter_properties(boost::optional str);\n metawriter_properties() {}\n template metawriter_properties(\n InputIterator first, InputIterator last) : std::set(first, last) {}\n std::string to_string() const;\n};\n\n\/** Abstract baseclass for all metawriter classes. *\/\nclass metawriter\n{\npublic:\n typedef coord_transform path_type;\n metawriter(metawriter_properties dflt_properties) :\n dflt_properties_(dflt_properties),\n width_(0),\n height_(0) {}\n virtual ~metawriter() {}\n \/** Output a rectangular area.\n * \\param box Area (in pixel coordinates)\n * \\param feature The feature being processed\n * \\param prj_trans Projection transformation\n * \\param t Coordinate transformation\n * \\param properties List of properties to output\n *\/\n virtual void add_box(box2d const& box, Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n virtual void add_text(boost::ptr_vector &placements,\n box2d const& extents,\n Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n virtual void add_polygon(path_type & path,\n Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n virtual void add_line(path_type & path,\n Feature const& feature,\n CoordTransform const& t,\n metawriter_properties const& properties)=0;\n\n \/** Start processing.\n * Write file header, init database connection, ...\n *\n * \\param properties metawriter_property_map object with userdefined values.\n * Useful for setting filename etc.\n *\/\n virtual void start(metawriter_property_map const& properties)\n {\n boost::ignore_unused_variable_warning(properties);\n }\n\n \/** Stop processing.\n * Write file footer, close database connection, ...\n *\/\n virtual void stop() {}\n \/** Set output size (pixels).\n * All features that are completely outside this size are discarded.\n *\/\n void set_size(int width, int height) { width_ = width; height_ = height; }\n \/** Set Map object's srs. *\/\n virtual void set_map_srs(projection const& proj)\n {\n boost::ignore_unused_variable_warning(proj);\n }\n\n \/** Return the list of default properties. *\/\n metawriter_properties const& get_default_properties() const { return dflt_properties_;}\nprotected:\n metawriter_properties dflt_properties_;\n \/** Output width (pixels). *\/\n int width_;\n \/** Output height (pixels). *\/\n int height_;\n};\n\n\/** Shared pointer to metawriter object. *\/\ntypedef boost::shared_ptr metawriter_ptr;\n\/** Metawriter object + properties. *\/\ntypedef std::pair metawriter_with_properties;\n\n}\n\n#endif \/\/ MAPNIK_METAWRITER_HPP\n<|endoftext|>"} {"text":"\/******************************************************************************\n\n nomlib - C++11 cross-platform game engine\n\nCopyright (c) 2013, 2014 Jeffrey Carpenter \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n******************************************************************************\/\n#ifndef NOMLIB_MATH_SIZE2_HEADERS\n#define NOMLIB_MATH_SIZE2_HEADERS\n\n#include \n#include \n\n#include \"nomlib\/config.hpp\"\n\n\/\/ FIXME: The following declaration is necessary in order to avoid a very\n\/\/ nasty compiling conflict that can happen under Windows anytime the\n\/\/ windef.h header file is included (commonly from windows.h), due to min and\n\/\/ max macros being declared there. This is why macros are evil.\n\/\/\n\/\/ http:\/\/support.microsoft.com\/kb\/143208\n\/\/ http:\/\/stackoverflow.com\/questions\/5004858\/stdmin-gives-error\n#if defined( NOM_PLATFORM_WINDOWS )\n #undef min\n #undef max\n#endif\n\nnamespace nom {\n\n\/\/\/ \\brief Delimiter character to use with << operator\nconst std::string SIZE2_DELIMITER = \", \";\n\n\/\/\/ \\brief Size coordinates (width & height) container\ntemplate \nstruct Size2\n{\n \/\/\/ Default constructor; initialize values to Size2::null\n Size2 ( void ) :\n w ( -1 ),\n h ( -1 )\n {\n \/\/NOM_LOG_TRACE(NOM);\n }\n\n \/\/\/ Destructor\n ~Size2 ( void )\n {\n \/\/NOM_LOG_TRACE(NOM);\n }\n\n \/\/\/ Constructor variant for initializing width & height at construction\n Size2 ( T w, T h ) :\n w ( w ),\n h ( h )\n {\n \/\/NOM_LOG_TRACE(NOM);\n }\n\n \/\/\/ \\brief Construct an object using a specified value for both members.\n Size2( T factor )\n {\n this->w = factor;\n this->h = factor;\n }\n\n \/\/\/ \\brief Copy constructor\n \/\/\/\n \/\/\/ \\remarks The explicit keyword here will result in compile-time errors\n \/\/\/ in any instance that it finds incompatible casting occurring, such as if\n \/\/\/ you try to down-cast a Size2 to a Size2.\n template \n explicit Size2 ( const Size2& copy ) :\n w { static_cast ( copy.w ) },\n h { static_cast ( copy.h ) }\n {\n this->w = static_cast ( copy.w );\n this->h = static_cast ( copy.h );\n }\n\n \/\/\/ \\brief Compare two Size2 objects and return the larger width and height\n \/\/\/ of the two objects.\n template \n Size2 max( const Size2& rhs )\n {\n return Size2( std::max( this->w, rhs.w ), std::max( this->h, rhs.h ) );\n }\n\n \/\/\/ \\brief Compare two Size2 objects and return the smaller width and height\n \/\/\/ of the two objects.\n template \n Size2 min( const Size2& rhs )\n {\n return Size2( std::min( this->w, rhs.w ), std::min( this->h, rhs.h ) );\n }\n\n \/\/\/ \\brief Transpose width and height dimensions.\n void swap( void )\n {\n std::swap( this->w, this->h );\n }\n\n \/\/\/ \\brief Null value\n \/\/\/\n \/\/\/ \\remarks Null value implementation depends on signed (negative) numbers.\n static const Size2 null;\n\n \/\/\/ \\brief Zero value constant.\n static const Size2 zero;\n\n \/\/\/ Represents the width coordinate point\n T w;\n\n \/\/\/ Represents the height coordinate point\n T h;\n};\n\n\/\/\/ Pretty print a Size2 object using the following formatting:\n\/\/\/\n\/\/\/ , \n\/\/\/\n\/\/\/ An example print:\n\/\/\/\n\/\/\/ 128, 144\ntemplate \ninline std::ostream& operator <<( std::ostream& os, const Size2& pos )\n{\n os\n << pos.w\n << SIZE2_DELIMITER\n << pos.h;\n\n return os;\n}\n\ntemplate \ninline bool operator ==( const Size2& lhs, const Size2& rhs )\n{\n return ( lhs.w == rhs.w ) && ( lhs.h == rhs.h );\n}\n\ntemplate \ninline bool operator !=( const Size2& lhs, const Size2& rhs )\n{\n return ! ( lhs == rhs );\n}\n\n\/\/\/ \\brief Method overload of binary operator + (Addition)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Addition of both objects.\ntemplate \ninline Size2 operator +( const Size2& lhs, const Size2& rhs )\n{\n return Size2 (\n lhs.w + rhs.w,\n lhs.h + rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator ++ (Addition by 1)\n\/\/\/\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Addition of the right operand.\ntemplate \ninline Size2 operator ++( const Size2& rhs )\n{\n return Size2 (\n ++rhs.w,\n ++rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator - (subtraction)\n\/\/\/\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Opposite of the object.\ntemplate \ninline Size2 operator -( const Size2& rhs )\n{\n return Size2 (\n -rhs.w\n -rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator - (subtraction)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Subtraction of both objects.\ntemplate \ninline Size2 operator -( const Size2& lhs, const Size2& rhs )\n{\n return Size2 (\n lhs.w - rhs.w,\n lhs.h - rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator -- (subtraction by 1)\n\/\/\/\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Subtraction of the right operand.\ntemplate \ninline Size2 operator --( const Size2& rhs )\n{\n return Size2 (\n --rhs.w,\n --rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator * (Multiplication)\n\/\/\/\n\/\/\/ \\param rhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Multiplication of the right operand.\ntemplate \ninline Size2 operator *( const Size2& lhs, const Size2& rhs )\n{\n return Size2 ( lhs.w * rhs.w,\n lhs.h * rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator += (Addition)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Addition of both objects; result is assigned to the left\n\/\/\/ operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand,\ntemplate \ninline Size2& operator +=( Size2& lhs, const Size2& rhs )\n{\n lhs.w += rhs.w;\n lhs.h += rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator -= (Subtraction)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Subtraction of both objects; result is assigned to the left\n\/\/\/ operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand.\ntemplate \ninline Size2& operator -=( Size2& lhs, const Size2& rhs )\n{\n lhs.w -= rhs.w;\n lhs.h -= rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator *= (Multiplication)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Multiplication of both objects; result is assigned to the\n\/\/\/ left operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand.\ntemplate \ninline Size2& operator *=( Size2& lhs, const Size2& rhs )\n{\n lhs.w *= rhs.w;\n lhs.h *= rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator \/= (Division)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Division of both objects; result is assigned to the\n\/\/\/ left operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand.\ntemplate \ninline Size2& operator \/=( Size2& lhs, const Size2& rhs )\n{\n lhs.w \/= rhs.w;\n lhs.h \/= rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Lesser than comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator <( const Size2 lhs, const Size2& rhs )\n{\n return ( lhs.w < rhs.w ) && ( lhs.h < rhs.h );\n}\n\n\/\/\/ \\brief Greater than or equal to comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator >( const Size2& lhs, const Size2& rhs )\n{\n return ( rhs.w < lhs.w ) && ( rhs.h < lhs.h );\n}\n\n\/\/\/ \\brief Lesser than or equal to comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator <=( const Size2& lhs, const Size2& rhs )\n{\n return ( lhs.w <= rhs.w ) && ( lhs.h <= rhs.h );\n}\n\n\/\/\/ \\brief Greater than or equal to comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator >=( const Size2& lhs, const Size2& rhs )\n{\n return ( rhs.w <= lhs.w ) && ( rhs.h <= lhs.h );\n}\n\n\/\/\/ Size2 object defined using signed integers\ntypedef Size2 Size2i;\n\n\/\/\/ Size2 object defined using floating point numbers\ntypedef Size2 Size2f;\n\n\/\/\/ Size2 object defined using double-precision floating point numbers\ntypedef Size2 Size2d;\n\n} \/\/ namespace nom\n\n#endif \/\/ include guard defined\nIntroduce Size2 division operator\/******************************************************************************\n\n nomlib - C++11 cross-platform game engine\n\nCopyright (c) 2013, 2014 Jeffrey Carpenter \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n1. Redistributions of source code must retain the above copyright notice, this\n list of conditions and the following disclaimer.\n2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n******************************************************************************\/\n#ifndef NOMLIB_MATH_SIZE2_HEADERS\n#define NOMLIB_MATH_SIZE2_HEADERS\n\n#include \n#include \n\n#include \"nomlib\/config.hpp\"\n\n\/\/ FIXME: The following declaration is necessary in order to avoid a very\n\/\/ nasty compiling conflict that can happen under Windows anytime the\n\/\/ windef.h header file is included (commonly from windows.h), due to min and\n\/\/ max macros being declared there. This is why macros are evil.\n\/\/\n\/\/ http:\/\/support.microsoft.com\/kb\/143208\n\/\/ http:\/\/stackoverflow.com\/questions\/5004858\/stdmin-gives-error\n#if defined( NOM_PLATFORM_WINDOWS )\n #undef min\n #undef max\n#endif\n\nnamespace nom {\n\n\/\/\/ \\brief Delimiter character to use with << operator\nconst std::string SIZE2_DELIMITER = \", \";\n\n\/\/\/ \\brief Size coordinates (width & height) container\ntemplate \nstruct Size2\n{\n \/\/\/ Default constructor; initialize values to Size2::null\n Size2 ( void ) :\n w ( -1 ),\n h ( -1 )\n {\n \/\/NOM_LOG_TRACE(NOM);\n }\n\n \/\/\/ Destructor\n ~Size2 ( void )\n {\n \/\/NOM_LOG_TRACE(NOM);\n }\n\n \/\/\/ Constructor variant for initializing width & height at construction\n Size2 ( T w, T h ) :\n w ( w ),\n h ( h )\n {\n \/\/NOM_LOG_TRACE(NOM);\n }\n\n \/\/\/ \\brief Construct an object using a specified value for both members.\n Size2( T factor )\n {\n this->w = factor;\n this->h = factor;\n }\n\n \/\/\/ \\brief Copy constructor\n \/\/\/\n \/\/\/ \\remarks The explicit keyword here will result in compile-time errors\n \/\/\/ in any instance that it finds incompatible casting occurring, such as if\n \/\/\/ you try to down-cast a Size2 to a Size2.\n template \n explicit Size2 ( const Size2& copy ) :\n w { static_cast ( copy.w ) },\n h { static_cast ( copy.h ) }\n {\n this->w = static_cast ( copy.w );\n this->h = static_cast ( copy.h );\n }\n\n \/\/\/ \\brief Compare two Size2 objects and return the larger width and height\n \/\/\/ of the two objects.\n template \n Size2 max( const Size2& rhs )\n {\n return Size2( std::max( this->w, rhs.w ), std::max( this->h, rhs.h ) );\n }\n\n \/\/\/ \\brief Compare two Size2 objects and return the smaller width and height\n \/\/\/ of the two objects.\n template \n Size2 min( const Size2& rhs )\n {\n return Size2( std::min( this->w, rhs.w ), std::min( this->h, rhs.h ) );\n }\n\n \/\/\/ \\brief Transpose width and height dimensions.\n void swap( void )\n {\n std::swap( this->w, this->h );\n }\n\n \/\/\/ \\brief Null value\n \/\/\/\n \/\/\/ \\remarks Null value implementation depends on signed (negative) numbers.\n static const Size2 null;\n\n \/\/\/ \\brief Zero value constant.\n static const Size2 zero;\n\n \/\/\/ Represents the width coordinate point\n T w;\n\n \/\/\/ Represents the height coordinate point\n T h;\n};\n\n\/\/\/ Pretty print a Size2 object using the following formatting:\n\/\/\/\n\/\/\/ , \n\/\/\/\n\/\/\/ An example print:\n\/\/\/\n\/\/\/ 128, 144\ntemplate \ninline std::ostream& operator <<( std::ostream& os, const Size2& pos )\n{\n os\n << pos.w\n << SIZE2_DELIMITER\n << pos.h;\n\n return os;\n}\n\ntemplate \ninline bool operator ==( const Size2& lhs, const Size2& rhs )\n{\n return ( lhs.w == rhs.w ) && ( lhs.h == rhs.h );\n}\n\ntemplate \ninline bool operator !=( const Size2& lhs, const Size2& rhs )\n{\n return ! ( lhs == rhs );\n}\n\n\/\/\/ \\brief Method overload of binary operator + (Addition)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Addition of both objects.\ntemplate \ninline Size2 operator +( const Size2& lhs, const Size2& rhs )\n{\n return Size2 (\n lhs.w + rhs.w,\n lhs.h + rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator ++ (Addition by 1)\n\/\/\/\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Addition of the right operand.\ntemplate \ninline Size2 operator ++( const Size2& rhs )\n{\n return Size2 (\n ++rhs.w,\n ++rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator - (subtraction)\n\/\/\/\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Opposite of the object.\ntemplate \ninline Size2 operator -( const Size2& rhs )\n{\n return Size2 (\n -rhs.w\n -rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator - (subtraction)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Subtraction of both objects.\ntemplate \ninline Size2 operator -( const Size2& lhs, const Size2& rhs )\n{\n return Size2 (\n lhs.w - rhs.w,\n lhs.h - rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator -- (subtraction by 1)\n\/\/\/\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Subtraction of the right operand.\ntemplate \ninline Size2 operator --( const Size2& rhs )\n{\n return Size2 (\n --rhs.w,\n --rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator * (Multiplication)\n\/\/\/\n\/\/\/ \\param rhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Multiplication of the right operand.\ntemplate \ninline Size2 operator *( const Size2& lhs, const Size2& rhs )\n{\n return Size2 ( lhs.w * rhs.w,\n lhs.h * rhs.h\n );\n}\n\n\/\/\/ \\brief Method overload of binary operator += (Addition)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Addition of both objects; result is assigned to the left\n\/\/\/ operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand,\ntemplate \ninline Size2& operator +=( Size2& lhs, const Size2& rhs )\n{\n lhs.w += rhs.w;\n lhs.h += rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator -= (Subtraction)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Subtraction of both objects; result is assigned to the left\n\/\/\/ operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand.\ntemplate \ninline Size2& operator -=( Size2& lhs, const Size2& rhs )\n{\n lhs.w -= rhs.w;\n lhs.h -= rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator *= (Multiplication)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Multiplication of both objects; result is assigned to the\n\/\/\/ left operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand.\ntemplate \ninline Size2& operator *=( Size2& lhs, const Size2& rhs )\n{\n lhs.w *= rhs.w;\n lhs.h *= rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator \/= (Division assignment)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\remarks Division of both objects; result is assigned to the\n\/\/\/ left operand.\n\/\/\/\n\/\/\/ \\returns Reference to left operand.\ntemplate \ninline Size2& operator \/=( Size2& lhs, const Size2& rhs )\n{\n lhs.w \/= rhs.w;\n lhs.h \/= rhs.h;\n\n return lhs;\n}\n\n\/\/\/ \\brief Method overload of binary operator \/ (Division)\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\n\/\/\/\n\/\/\/ \\returns Size2 template type returned by value\ntemplate \ninline Size2 operator \/( const Size2& lhs, const Size2& rhs )\n{\n Size2 ret;\n ret.w = lhs.w \/ rhs.w;\n ret.h = lhs.h \/ rhs.h;\n\n return ret;\n}\n\n\/\/\/ \\brief Lesser than comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator <( const Size2 lhs, const Size2& rhs )\n{\n return ( lhs.w < rhs.w ) && ( lhs.h < rhs.h );\n}\n\n\/\/\/ \\brief Greater than or equal to comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator >( const Size2& lhs, const Size2& rhs )\n{\n return ( rhs.w < lhs.w ) && ( rhs.h < lhs.h );\n}\n\n\/\/\/ \\brief Lesser than or equal to comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator <=( const Size2& lhs, const Size2& rhs )\n{\n return ( lhs.w <= rhs.w ) && ( lhs.h <= rhs.h );\n}\n\n\/\/\/ \\brief Greater than or equal to comparison operator.\n\/\/\/\n\/\/\/ \\param lhs Left operand.\n\/\/\/ \\param rhs Right operand.\ntemplate \ninline bool operator >=( const Size2& lhs, const Size2& rhs )\n{\n return ( rhs.w <= lhs.w ) && ( rhs.h <= lhs.h );\n}\n\n\/\/\/ Size2 object defined using signed integers\ntypedef Size2 Size2i;\n\n\/\/\/ Size2 object defined using floating point numbers\ntypedef Size2 Size2f;\n\n\/\/\/ Size2 object defined using double-precision floating point numbers\ntypedef Size2 Size2d;\n\n} \/\/ namespace nom\n\n#endif \/\/ include guard defined\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/\/ \\file variant_tree.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief This file contains a tree class that can hold variant values.\n\/\/----------------------------------------------------------------------------\n\/\/ Author: Serge Aleynikov\n\/\/ Created: 2010-07-10\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file may be included in various open-source projects.\n\nCopyright (C) 2010 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#ifndef _UTIL_VARIANT_TREE_HPP_\n#define _UTIL_VARIANT_TREE_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost {\nnamespace property_tree {\n \/\/ Custom translator that works with util::variant instead of std::string.\n \/\/ This translator is used to read\/write values from files.\n template <>\n struct translator_between\n {\n typedef translator_between type;\n typedef std::string external_type;\n typedef util::variant internal_type;\n\n boost::optional get_value(const internal_type& value) const {\n return boost::optional(\n value.type() == internal_type::TYPE_NULL ? \"\" : value.to_string());\n }\n\n boost::optional put_value(const external_type& value) const {\n try {\n long n = lexical_cast(value);\n for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it)\n if (*it < '0' || *it > '9')\n throw false;\n return boost::optional(n);\n } catch (...) {}\n try {\n double n = lexical_cast(value);\n return boost::optional(n);\n } catch (...) {}\n if (value == \"true\" || value == \"false\")\n return boost::optional(value[0] == 't');\n return boost::optional(value);\n }\n };\n\n} \/\/ namespace property_tree\n} \/\/ namespace boost\n\nnamespace util {\n\nnamespace detail {\n\n \/\/ Custom translator that works with variant instead of std::string\n \/\/ This translator is used to get\/put values through explicit get\/put calls.\n template \n struct variant_translator\n {\n typedef Ext external_type;\n typedef variant internal_type;\n\n \/*\n typedef boost::mpl::joint_view\n > valid_non_string_types;\n *\/\n typedef variant::valid_types valid_types;\n\n external_type get_value(const internal_type& value) const {\n return value.get();\n }\n\n template\n typename boost::disable_if<\n boost::is_same<\n boost::mpl::end::type,\n boost::mpl::find\n >, \n internal_type>::type\n put_value(T value) const {\n return variant(value);\n }\n };\n\n typedef boost::property_tree::basic_ptree<\n std::string, \/\/ Key type\n variant, \/\/ Data type\n std::less \/\/ Key comparison\n > basic_variant_tree;\n\n} \/\/ namespace detail\n\nclass variant_tree : public detail::basic_variant_tree\n{\n typedef detail::basic_variant_tree base;\n typedef variant_tree self_type;\npublic:\n typedef boost::property_tree::ptree_bad_path bad_path;\n typedef std::pair value_type;\n\n variant_tree() {}\n variant_tree(const detail::basic_variant_tree& a_rhs)\n : detail::basic_variant_tree(a_rhs)\n {}\n variant_tree(const variant_tree& a_rhs)\n : detail::basic_variant_tree(a_rhs)\n {}\n\n template \n static void read_info(Source& src, variant_tree& tree) {\n boost::property_tree::info_parser::read_info(src, static_cast(tree));\n boost::property_tree::translator_between tr;\n translate_data(tr, tree);\n }\n\n template \n static void translate_data(T& tr, base& tree) {\n for (variant_tree::iterator it=tree.begin(); it != tree.end(); it++)\n translate_data(tr, it->second);\n tree.data() = *tr.put_value(tree.get_value());\n }\n\n template \n static void write_info(Target& tar, variant_tree& tree) {\n boost::property_tree::info_parser::write_info(tar, static_cast(tree));\n }\n\n template \n static void write_info(Target& tar, variant_tree& tree, const Settings& tt) {\n boost::property_tree::info_parser::write_info(tar, static_cast(tree), tt);\n }\n\n template \n T get_value() const {\n using boost::throw_exception;\n\n if(boost::optional o =\n base::get_value_optional(detail::variant_translator())) {\n return *o;\n }\n BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data(\n std::string(\"conversion of data to type \\\"\") +\n typeid(T).name() + \"\\\" failed\", base::data()));\n }\n\n template \n T get_value(const T& default_value) const {\n return base::get_value(default_value, detail::variant_translator());\n }\n\n std::string get_value(const char* default_value) const {\n return base::get_value(std::string(default_value),\n detail::variant_translator());\n }\n\n template \n boost::optional get_value_optional() const {\n return base::get_value(detail::variant_translator());\n }\n\n template \n void put_value(const T& value) {\n base::put_value(value, detail::variant_translator());\n }\n\n template \n T get(const path_type& path) const {\n try {\n return base::get_child(path).BOOST_NESTED_TEMPLATE\n get_value(detail::variant_translator());\n } catch (boost::bad_get& e) {\n std::stringstream s;\n s << \"Cannot convert value to type '\" << type_to_string() << \"'\";\n throw bad_path(s.str(), path);\n }\n }\n\n template \n T get(const path_type& path, const T& default_value) const {\n try {\n return base::get(path, default_value, detail::variant_translator());\n } catch (boost::bad_get& e) {\n throw bad_path(\"Wrong or missing value type\", path);\n }\n }\n\n std::string get(const path_type& path, const char* default_value) const {\n return base::get(path, std::string(default_value),\n detail::variant_translator());\n }\n\n template \n boost::optional get_optional(const path_type& path) const {\n return base::get_optional(path, detail::variant_translator());\n }\n\n template \n void put(const path_type& path, const T& value) {\n base::put(path, value, detail::variant_translator());\n }\n\n template \n self_type& add(const path_type& path, const T& value) {\n return static_cast(\n base::add(path, value, detail::variant_translator()));\n }\n\n void swap(variant_tree& rhs) {\n base::swap(static_cast(rhs));\n }\n void swap(boost::property_tree::basic_ptree<\n std::string, variant, std::less >& rhs) {\n base::swap(rhs);\n }\n\n self_type &get_child(const path_type &path) {\n return static_cast(base::get_child(path));\n }\n\n \/** Get the child at the given path, or throw @c ptree_bad_path. *\/\n const self_type &get_child(const path_type &path) const {\n return static_cast(base::get_child(path));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n self_type &get_child(const path_type &path, self_type &default_value) {\n return static_cast(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n const self_type &get_child(const path_type &path,\n const self_type &default_value) const {\n return static_cast(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional get_child_optional(const path_type &path) {\n boost::optional o = base::get_child_optional(path);\n if (!o)\n return boost::optional();\n return boost::optional(static_cast(*o));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional\n get_child_optional(const path_type &path) const {\n boost::optional o = base::get_child_optional(path);\n if (!o)\n return boost::optional();\n return boost::optional(static_cast(*o));\n }\n\n self_type &put_child(const path_type &path, const self_type &value) {\n return static_cast(base::put_child(path, value));\n }\n};\n\n} \/\/ namespace util\n\n#endif \/\/ _UTIL_VARIANT_TREE_HPP_\ntranslate method made protected\/\/----------------------------------------------------------------------------\n\/\/\/ \\file variant_tree.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief This file contains a tree class that can hold variant values.\n\/\/----------------------------------------------------------------------------\n\/\/ Author: Serge Aleynikov\n\/\/ Created: 2010-07-10\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file may be included in various open-source projects.\n\nCopyright (C) 2010 Serge Aleynikov \n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n\n#ifndef _UTIL_VARIANT_TREE_HPP_\n#define _UTIL_VARIANT_TREE_HPP_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace boost {\nnamespace property_tree {\n \/\/ Custom translator that works with util::variant instead of std::string.\n \/\/ This translator is used to read\/write values from files.\n template <>\n struct translator_between\n {\n typedef translator_between type;\n typedef std::string external_type;\n typedef util::variant internal_type;\n\n boost::optional get_value(const internal_type& value) const {\n return boost::optional(\n value.type() == internal_type::TYPE_NULL ? \"\" : value.to_string());\n }\n\n boost::optional put_value(const external_type& value) const {\n try {\n long n = lexical_cast(value);\n for(external_type::const_iterator it=value.begin(), end=value.end(); it!=end; ++it)\n if (*it < '0' || *it > '9')\n throw false;\n return boost::optional(n);\n } catch (...) {}\n try {\n double n = lexical_cast(value);\n return boost::optional(n);\n } catch (...) {}\n if (value == \"true\" || value == \"false\")\n return boost::optional(value[0] == 't');\n return boost::optional(value);\n }\n };\n\n} \/\/ namespace property_tree\n} \/\/ namespace boost\n\nnamespace util {\n\nnamespace detail {\n\n \/\/ Custom translator that works with variant instead of std::string\n \/\/ This translator is used to get\/put values through explicit get\/put calls.\n template \n struct variant_translator\n {\n typedef Ext external_type;\n typedef variant internal_type;\n\n \/*\n typedef boost::mpl::joint_view\n > valid_non_string_types;\n *\/\n typedef variant::valid_types valid_types;\n\n external_type get_value(const internal_type& value) const {\n return value.get();\n }\n\n template\n typename boost::disable_if<\n boost::is_same<\n boost::mpl::end::type,\n boost::mpl::find\n >, \n internal_type>::type\n put_value(T value) const {\n return variant(value);\n }\n };\n\n typedef boost::property_tree::basic_ptree<\n std::string, \/\/ Key type\n variant, \/\/ Data type\n std::less \/\/ Key comparison\n > basic_variant_tree;\n\n} \/\/ namespace detail\n\nclass variant_tree : public detail::basic_variant_tree\n{\n typedef detail::basic_variant_tree base;\n typedef variant_tree self_type;\npublic:\n typedef boost::property_tree::ptree_bad_path bad_path;\n typedef std::pair value_type;\n\n variant_tree() {}\n variant_tree(const detail::basic_variant_tree& a_rhs)\n : detail::basic_variant_tree(a_rhs)\n {}\n variant_tree(const variant_tree& a_rhs)\n : detail::basic_variant_tree(a_rhs)\n {}\n\n template \n static void read_info(Source& src, variant_tree& tree) {\n boost::property_tree::info_parser::read_info(src, static_cast(tree));\n boost::property_tree::translator_between tr;\n translate_data(tr, tree);\n }\n\n template \n static void write_info(Target& tar, variant_tree& tree) {\n boost::property_tree::info_parser::write_info(tar, static_cast(tree));\n }\n\n template \n static void write_info(Target& tar, variant_tree& tree, const Settings& tt) {\n boost::property_tree::info_parser::write_info(tar, static_cast(tree), tt);\n }\n\n template \n T get_value() const {\n using boost::throw_exception;\n\n if(boost::optional o =\n base::get_value_optional(detail::variant_translator())) {\n return *o;\n }\n BOOST_PROPERTY_TREE_THROW(boost::property_tree::ptree_bad_data(\n std::string(\"conversion of data to type \\\"\") +\n typeid(T).name() + \"\\\" failed\", base::data()));\n }\n\n template \n T get_value(const T& default_value) const {\n return base::get_value(default_value, detail::variant_translator());\n }\n\n std::string get_value(const char* default_value) const {\n return base::get_value(std::string(default_value),\n detail::variant_translator());\n }\n\n template \n boost::optional get_value_optional() const {\n return base::get_value(detail::variant_translator());\n }\n\n template \n void put_value(const T& value) {\n base::put_value(value, detail::variant_translator());\n }\n\n template \n T get(const path_type& path) const {\n try {\n return base::get_child(path).BOOST_NESTED_TEMPLATE\n get_value(detail::variant_translator());\n } catch (boost::bad_get& e) {\n std::stringstream s;\n s << \"Cannot convert value to type '\" << type_to_string() << \"'\";\n throw bad_path(s.str(), path);\n }\n }\n\n template \n T get(const path_type& path, const T& default_value) const {\n try {\n return base::get(path, default_value, detail::variant_translator());\n } catch (boost::bad_get& e) {\n throw bad_path(\"Wrong or missing value type\", path);\n }\n }\n\n std::string get(const path_type& path, const char* default_value) const {\n return base::get(path, std::string(default_value),\n detail::variant_translator());\n }\n\n template \n boost::optional get_optional(const path_type& path) const {\n return base::get_optional(path, detail::variant_translator());\n }\n\n template \n void put(const path_type& path, const T& value) {\n base::put(path, value, detail::variant_translator());\n }\n\n template \n self_type& add(const path_type& path, const T& value) {\n return static_cast(\n base::add(path, value, detail::variant_translator()));\n }\n\n void swap(variant_tree& rhs) {\n base::swap(static_cast(rhs));\n }\n void swap(boost::property_tree::basic_ptree<\n std::string, variant, std::less >& rhs) {\n base::swap(rhs);\n }\n\n self_type &get_child(const path_type &path) {\n return static_cast(base::get_child(path));\n }\n\n \/** Get the child at the given path, or throw @c ptree_bad_path. *\/\n const self_type &get_child(const path_type &path) const {\n return static_cast(base::get_child(path));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n self_type &get_child(const path_type &path, self_type &default_value) {\n return static_cast(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return @p default_value. *\/\n const self_type &get_child(const path_type &path,\n const self_type &default_value) const {\n return static_cast(base::get_child(path, default_value));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional get_child_optional(const path_type &path) {\n boost::optional o = base::get_child_optional(path);\n if (!o)\n return boost::optional();\n return boost::optional(static_cast(*o));\n }\n\n \/** Get the child at the given path, or return boost::null. *\/\n boost::optional\n get_child_optional(const path_type &path) const {\n boost::optional o = base::get_child_optional(path);\n if (!o)\n return boost::optional();\n return boost::optional(static_cast(*o));\n }\n\n self_type &put_child(const path_type &path, const self_type &value) {\n return static_cast(base::put_child(path, value));\n }\n\nprotected:\n template \n static void translate_data(T& tr, base& tree) {\n for (variant_tree::iterator it=tree.begin(); it != tree.end(); it++)\n translate_data(tr, it->second);\n tree.data() = *tr.put_value(tree.get_value());\n }\n};\n\n} \/\/ namespace util\n\n#endif \/\/ _UTIL_VARIANT_TREE_HPP_\n<|endoftext|>"} {"text":"\/\/----------------------------------------------------------------------------\n\/\/\/ \\file signal_block.hpp\n\/\/\/ \\author Serge ALeynikov \n\/\/\/ \\author Peter Simons (signal_block\/unblock)\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief Signal blocking class.\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2014 Serge Aleynikov \n\/\/ Copyright (c) 2010 Peter Simons (signal_block\/unblock)\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (c) 2014 Serge Aleynikov\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n#pragma once\n\n#include \n#include \n#include \n\nnamespace utxx\n{\n\n\/\/\/ Block all POSIX signals in the current scope.\n\/\/\/ \\sa signal_unblock\nclass signal_block : private boost::noncopyable {\n sigset_t m_orig_mask;\n bool m_restore;\n\n static sigset_t full() { sigset_t s; ::sigfillset(&s); return s; }\n static sigset_t empty() { sigset_t s; ::sigemptyset(&s); return s; }\npublic:\n\n explicit signal_block(bool a_block = true, bool a_restore = true)\n : signal_block(a_block ? full() : empty(), a_restore)\n {}\n\n explicit signal_block(sigset_t const& a_block, bool a_restore = true)\n : m_restore(a_restore)\n {\n if (sigisemptyset(&a_block))\n ::sigemptyset(&m_orig_mask);\n else\n block();\n }\n\n void block() {\n sigset_t block_all;\n if (::sigfillset(&block_all) < 0)\n UTXX_THROW_IO_ERROR(errno, \"sigfillset(3)\");\n if (::sigprocmask(SIG_SETMASK, &block_all, &m_orig_mask))\n UTXX_THROW_IO_ERROR(errno, \"sigprocmask(2)\");\n }\n\n ~signal_block() {\n if (!sigisemptyset(&m_orig_mask) && m_restore)\n ::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast(0));\n }\n};\n\n\/\/\/ Unblock all POSIX signals in the current scope.\n\/\/\/ \\sa signal_block\nclass signal_unblock : private boost::noncopyable {\n sigset_t m_orig_mask;\n bool m_restore;\npublic:\n signal_unblock(bool a_restore = true)\n : m_restore(a_restore)\n {\n sigset_t l_unblock_all;\n if (::sigemptyset(&l_unblock_all) < 0)\n UTXX_THROW_IO_ERROR(errno, \"sigfillset(3)\");\n if (::sigprocmask(SIG_SETMASK, &l_unblock_all, &m_orig_mask))\n UTXX_THROW_IO_ERROR(errno, \"sigprocmask(2)\");\n }\n\n ~signal_unblock() {\n if (m_restore)\n ::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast(0));\n }\n};\n\n\/\/\/ Get a list of all known signal names.\n\/\/\/ @return list of char strings that can be iterated until NULL.\nconst char** sig_names();\n\n\/\/\/ Total number of \"well-known\" signal names in the sig_names() array\nstatic constexpr size_t sig_names_count() { return 64; }\n\n\/\/\/ Get the name of an OS signal number.\n\/\/\/ @return signal name or \"\" if the name is not defined.\nconst char* sig_name(int a_signum);\n\n\/\/\/ Convert signal set to string\nstd::string sig_members(const sigset_t& a_set);\n\n\/\/\/ Initialize a signal set from an argument list\ntemplate \nsigset_t sig_init_set(Signals&&... args) {\n sigset_t sset;\n sigemptyset(&sset);\n int sigs[] = { args... };\n for (uint i=0; i < sizeof...(Signals); ++i)\n if (sigaddset(&sset, sigs[i]) < 0)\n UTXX_THROW_IO_ERROR(errno, \"Error in sigaddset[\", sigs[i], ']');\n return sset;\n}\n\n\/\/\/ Parse a string containing pipe\/comma\/column\/space delimited signal names.\n\/\/\/ The signal names are case insensitive and not required to begin with \"SIG\".\nsigset_t sig_members_parse(const std::string& a_signals, src_info&& a_si);\n\n\/\/\/ Convert a vector of integer signal numbers to sigset\nsigset_t sig_vector_to_set(const std::vector& a_signals);\n\n\/\/\/ Return a formatted string containing current signals\ninline std::string curr_signals_to_str(utxx::src_info&& si = utxx::src_info(), bool decode=false) {\n sigset_t old;\n char res[1024], buf[64];\n if (sigprocmask(SIG_SETMASK, NULL, &old) < 0)\n strcpy(buf, \"\");\n else\n snprintf(buf, sizeof(buf), \"%lx\", reinterpret_cast(old));\n\n auto n = snprintf(res, sizeof(res), \"%sPID: %d SigMask: %s\",\n si.empty() ? \"\" : si.to_string(\"[\",\"] \").c_str(), getpid(), res);\n if (decode)\n snprintf(res+n, sizeof(res)-n, \" %s\", utxx::sig_members(old).c_str());\n\n return res;\n}\n\n\n} \/\/ namespace utxx\nFix bug\/\/----------------------------------------------------------------------------\n\/\/\/ \\file signal_block.hpp\n\/\/\/ \\author Serge ALeynikov \n\/\/\/ \\author Peter Simons (signal_block\/unblock)\n\/\/----------------------------------------------------------------------------\n\/\/\/ \\brief Signal blocking class.\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2014 Serge Aleynikov \n\/\/ Copyright (c) 2010 Peter Simons (signal_block\/unblock)\n\/\/----------------------------------------------------------------------------\n\/*\n***** BEGIN LICENSE BLOCK *****\n\nThis file is part of the utxx open-source project.\n\nCopyright (c) 2014 Serge Aleynikov\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n***** END LICENSE BLOCK *****\n*\/\n#pragma once\n\n#include \n#include \n#include \n\nnamespace utxx\n{\n\n\/\/\/ Block all POSIX signals in the current scope.\n\/\/\/ \\sa signal_unblock\nclass signal_block : private boost::noncopyable {\n sigset_t m_orig_mask;\n bool m_restore;\n\n static sigset_t full() { sigset_t s; ::sigfillset(&s); return s; }\n static sigset_t empty() { sigset_t s; ::sigemptyset(&s); return s; }\npublic:\n\n explicit signal_block(bool a_block = true, bool a_restore = true)\n : signal_block(a_block ? full() : empty(), a_restore)\n {}\n\n explicit signal_block(sigset_t const& a_block, bool a_restore = true)\n : m_restore(a_restore)\n {\n if (sigisemptyset(&a_block))\n ::sigemptyset(&m_orig_mask);\n else\n block();\n }\n\n void block() {\n sigset_t block_all;\n if (::sigfillset(&block_all) < 0)\n UTXX_THROW_IO_ERROR(errno, \"sigfillset(3)\");\n if (::sigprocmask(SIG_SETMASK, &block_all, &m_orig_mask))\n UTXX_THROW_IO_ERROR(errno, \"sigprocmask(2)\");\n }\n\n ~signal_block() {\n if (!sigisemptyset(&m_orig_mask) && m_restore)\n ::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast(0));\n }\n};\n\n\/\/\/ Unblock all POSIX signals in the current scope.\n\/\/\/ \\sa signal_block\nclass signal_unblock : private boost::noncopyable {\n sigset_t m_orig_mask;\n bool m_restore;\npublic:\n signal_unblock(bool a_restore = true)\n : m_restore(a_restore)\n {\n sigset_t l_unblock_all;\n if (::sigemptyset(&l_unblock_all) < 0)\n UTXX_THROW_IO_ERROR(errno, \"sigfillset(3)\");\n if (::sigprocmask(SIG_SETMASK, &l_unblock_all, &m_orig_mask))\n UTXX_THROW_IO_ERROR(errno, \"sigprocmask(2)\");\n }\n\n ~signal_unblock() {\n if (m_restore)\n ::sigprocmask(SIG_SETMASK, &m_orig_mask, static_cast(0));\n }\n};\n\n\/\/\/ Get a list of all known signal names.\n\/\/\/ @return list of char strings that can be iterated until NULL.\nconst char** sig_names();\n\n\/\/\/ Total number of \"well-known\" signal names in the sig_names() array\nstatic constexpr size_t sig_names_count() { return 64; }\n\n\/\/\/ Get the name of an OS signal number.\n\/\/\/ @return signal name or \"\" if the name is not defined.\nconst char* sig_name(int a_signum);\n\n\/\/\/ Convert signal set to string\nstd::string sig_members(const sigset_t& a_set);\n\n\/\/\/ Initialize a signal set from an argument list\ntemplate \nsigset_t sig_init_set(Signals&&... args) {\n sigset_t sset;\n sigemptyset(&sset);\n int sigs[] = { args... };\n for (uint i=0; i < sizeof...(Signals); ++i)\n if (sigaddset(&sset, sigs[i]) < 0)\n UTXX_THROW_IO_ERROR(errno, \"Error in sigaddset[\", sigs[i], ']');\n return sset;\n}\n\n\/\/\/ Parse a string containing pipe\/comma\/column\/space delimited signal names.\n\/\/\/ The signal names are case insensitive and not required to begin with \"SIG\".\nsigset_t sig_members_parse(const std::string& a_signals, src_info&& a_si);\n\n\/\/\/ Convert a vector of integer signal numbers to sigset\nsigset_t sig_vector_to_set(const std::vector& a_signals);\n\n\/\/\/ Return a formatted string containing current signals\ninline std::string curr_signals_to_str(utxx::src_info&& si = utxx::src_info(), bool decode=false) {\n sigset_t old;\n char res[1024], buf[64];\n if (sigprocmask(SIG_SETMASK, NULL, &old) < 0)\n strcpy(buf, \"\");\n else\n snprintf(buf, sizeof(buf), \"%lx\", reinterpret_cast(old));\n\n auto n = snprintf(res, sizeof(res), \"%sPID: %d SigMask: %s\",\n si.empty() ? \"\" : si.to_string(\"[\",\"] \").c_str(), getpid(), buf);\n if (decode)\n snprintf(res+n, sizeof(res)-n, \" %s\", utxx::sig_members(old).c_str());\n\n return res;\n}\n\n\n} \/\/ namespace utxx\n<|endoftext|>"} {"text":"\/\/============================================================================\n\/\/ vSMC\/include\/vsmc\/core\/monitor.hpp\n\/\/----------------------------------------------------------------------------\n\/\/ vSMC: Scalable Monte Carlo\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2013-2015, Yan Zhou\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/============================================================================\n\n#ifndef VSMC_CORE_MONITOR_HPP\n#define VSMC_CORE_MONITOR_HPP\n\n#include \n#include \n#if VSMC_HAS_MKL\n#include \n#endif\n\n#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(func) \\\n VSMC_RUNTIME_ASSERT( \\\n (id < dim()), \"**Monitor::\" #func \"** INVALID ID NUMBER ARGUMENT\")\n\n#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(func) \\\n VSMC_RUNTIME_ASSERT((iter < iter_size()), \\\n \"**Monitor::\" #func \"** INVALID ITERATION NUMBER ARGUMENT\")\n\n#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(func, caller, name) \\\n VSMC_RUNTIME_ASSERT(static_cast(func), \\\n \"**Monitor::\" #caller \"** INVALID \" #name \" OBJECT\")\n\nnamespace vsmc\n{\n\n\/\/\/ \\brief Monitor for Monte Carlo integration\n\/\/\/ \\ingroup Core\ntemplate \nclass Monitor\n{\n public:\n typedef T value_type;\n typedef std::function &, double *)> eval_type;\n\n \/\/\/ \\brief Construct a Monitor with an evaluation object\n \/\/\/\n \/\/\/ \\param dim The dimension of the Monitor, i.e., the number of variables\n \/\/\/ \\param eval The evaluation object of type Monitor::eval_type\n \/\/\/ \\param record_only The Monitor only records results instead of\n \/\/\/ calculating them itself\n \/\/\/ \\param stage The stage of the Monitor. A Monitor may be evaluated\n \/\/\/ after\n \/\/\/ all steps that move the particles but before any resampling\n \/\/\/ (`MonitorMove`), or the possible resampling step but before any MCMC\n \/\/\/ steps (`MonitorResample`), all after all MCMC steps (`MonitorMCMC`).\n \/\/\/ If\n \/\/\/ a Monitor is present during initialization, then the initialization\n \/\/\/ are\n \/\/\/ taken as the step that moves particles, and both `MonitorResample` and\n \/\/\/ `MonitorMCMC` are considered after the possible resampling.\n \/\/\/\n \/\/\/ The evaluation object has the signature\n \/\/\/ ~~~{.cpp}\n \/\/\/ void eval (std::size_t iter, std::size_t dim, const Particle\n \/\/\/ &particle, double *result)\n \/\/\/ ~~~\n \/\/\/ where the first three arguments are passed in by the Sampler at the\n \/\/\/ end of each iteration. The evaluation occurs after the possible MCMC\n \/\/\/ moves. The output parameter `result` shall contain the results of the\n \/\/\/ evaluation.\n \/\/\/\n \/\/\/ If `record_only` is true, then the monitor only records the values\n \/\/\/ stored in `result`. Otherwise, the behavior is explained below\n \/\/\/\n \/\/\/ The array `result` is of length `particle.size() * dim`, and it\n \/\/\/ represents a row major matrix of dimension `particle.size()` by `dim`,\n \/\/\/ say \\f$R\\f$. Let \\f$W\\f$ be the vector of the normalized weights. The\n \/\/\/ Monitor will be respoinsible to compute the importance sampling\n \/\/\/ estimate \\f$r = R^TW\\f$ and record it. For example, say the purpose of\n \/\/\/ the Monitor is to record the importance sampling estimates of\n \/\/\/ \\f$E[h(X)]\\f$ where \\f$h(X) = (h_1(X),\\dots,h_d(X))\\f$. Then `result`\n \/\/\/ shall contain the evaluation of \\f$h(X_i)\\f$ for each \\f$i\\f$ from `0`\n \/\/\/ to `particle.size() - 1` in the order\n \/\/\/ \\f$(h_1(X_0), \\dots, h_d(X_0), h_1(X_1), \\dots, h_d(X_1), \\dots)\\f$.\n \/\/\/\n \/\/\/ After each evaluation, the iteration number `iter` and the imporatance\n \/\/\/ sampling estimates are recorded and can be retrived by `index()` and\n \/\/\/ `record()`.\n explicit Monitor(std::size_t dim, const eval_type &eval,\n bool record_only = false, MonitorStage stage = MonitorMCMC)\n : dim_(dim)\n , eval_(eval)\n , recording_(true)\n , record_only_(record_only)\n , stage_(stage)\n , name_(dim)\n {\n }\n\n \/\/\/ \\brief The dimension of the Monitor\n std::size_t dim() const { return dim_; }\n\n \/\/\/ \\brief If this is a record only Monitor\n bool record_only() const { return record_only_; }\n\n \/\/\/ \\brief The stage of the Montior\n MonitorStage stage() const { return stage_; }\n\n \/\/\/ \\brief The number of iterations has been recorded\n \/\/\/\n \/\/\/ \\details\n \/\/\/ This is not necessarily the same as Sampler::iter_size. For\n \/\/\/ example, a Monitor can be added only after a certain time point of the\n \/\/\/ sampler's iterations. Also the Monitor can be turned off for a period\n \/\/\/ during the iterations.\n std::size_t iter_size() const { return index_.size(); }\n\n \/\/\/ \\brief Reserve space for a specified number of iterations\n void reserve(std::size_t num)\n {\n index_.reserve(num);\n record_.reserve(dim_ * num);\n }\n\n \/\/\/ \\brief Whether the evaluation object is valid\n bool empty() const { return !static_cast(eval_); }\n\n \/\/\/ \\brief Read and write access to the names of variables\n \/\/\/\n \/\/\/ \\details\n \/\/\/ By default, each variable of a Monitor is unnamed and the returned\n \/\/\/ string is empty. However, the user can selectively set the names of\n \/\/\/ each variable. This effect how Sampler will print the headers of the\n \/\/\/ summary table.\n std::string &name(std::size_t id)\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);\n\n return name_[id];\n }\n\n \/\/\/ \\brief Read only access to the names of variables\n const std::string &name(std::size_t id) const\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);\n\n return name_[id];\n }\n\n \/\/\/ \\brief Get the iteration index of the sampler of a given Monitor\n \/\/\/ iteration\n \/\/\/\n \/\/\/ \\details\n \/\/\/ For example, if a Monitor is only added to the sampler at the\n \/\/\/ sampler's iteration `siter`. Then `index(0)` will be `siter` and so\n \/\/\/ on. If the Monitor is added before the sampler's initialization and\n \/\/\/ continued to be evaluated during the iterations without calling\n \/\/\/ `turnoff()`, then iter(iter) shall just be `iter`.\n std::size_t index(std::size_t iter) const\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(index);\n\n return index_[iter];\n }\n\n \/\/\/ \\brief Get the latest Monte Carlo integration record of a given\n \/\/\/ variable\n \/\/\/\n \/\/\/ \\details\n \/\/\/ For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1\n double record(std::size_t id) const\n {\n std::size_t iter = iter_size() ? iter_size() - 1 : iter_size();\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);\n\n return record_[iter * dim_ + id];\n }\n\n \/\/\/ \\brief Get the Monte Carlo integration record of a given variable and\n \/\/\/ the Monitor iteration\n \/\/\/\n \/\/\/ \\details\n \/\/\/ For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1\n double record(std::size_t id, std::size_t iter) const\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);\n\n return record_[iter * dim_ + id];\n }\n\n \/\/\/ \\brief Read the index history through an output iterator\n template \n void read_index(OutputIter first) const\n {\n std::copy(index_.begin(), index_.end(), first);\n }\n\n \/\/\/ \\brief Read only access to the raw data of the index vector\n const std::size_t *index_data() const { return index_.data(); }\n\n \/\/\/ \\brief Read only access to the raw data of records (a row major\n \/\/\/ matrix)\n const double *record_data() const { return record_.data(); }\n\n \/\/\/ \\brief Read only access to the raw data of records for a given\n \/\/\/ Monitor iteration\n const double *record_data(std::size_t iter) const\n {\n return record_.data() + iter * dim_;\n }\n\n \/\/\/ \\brief Read the record history for a given variable through an output\n \/\/\/ iterator\n template \n void read_record(std::size_t id, OutputIter first) const\n {\n const std::size_t N = iter_size();\n const double *riter = record_.data() + id;\n for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)\n *first = *riter;\n }\n\n \/\/\/ \\brief Read the record history of all variables through an array of\n \/\/\/ output iterators\n \/\/\/\n \/\/\/ \\param first An iterator of container of output iterators\n template \n void read_record_matrix(OutputIterIter first) const\n {\n for (std::size_t d = 0; d != dim_; ++d, ++first)\n read_record(d, *first);\n }\n\n \/\/\/ \\brief Read the record history of all variables through an output\n \/\/\/ iterator\n \/\/\/\n \/\/\/ \\param first The output iterator\n \/\/\/\n \/\/\/ For example, say `first` is of type `double *`, then if `order ==\n \/\/\/ ColMajor`, then, `first[j * iter_size() + i] == record(i, j)`.\n \/\/\/ Otherwise, if `order == RowMajor`, then `first[i * dim() + j] ==\n \/\/\/ record(i, j)`. That is, the output is an `iter_size()` by `dim()`\n \/\/\/ matrix, with the usual meaning of column or row major order.\n template \n void read_record_matrix(OutputIter first) const\n {\n const std::size_t N = iter_size();\n if (Order == ColMajor) {\n for (std::size_t d = 0; d != dim_; ++d) {\n const double *riter = record_.data() + d;\n for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)\n *first = *riter;\n }\n }\n\n if (Order == RowMajor)\n std::copy(record_.begin(), record_.end(), first);\n }\n\n \/\/\/ \\brief Set a new evaluation object of type eval_type\n void set_eval(const eval_type &new_eval) { eval_ = new_eval; }\n\n \/\/\/ \\brief Perform the evaluation for a given iteration and a Particle\n \/\/\/ object.\n \/\/\/\n \/\/\/ \\details\n \/\/\/ This function is called by a Sampler at the end of each\n \/\/\/ iteration. It does nothing if `recording()` returns `false`. Otherwise\n \/\/\/ it use the user defined evaluation object to compute results. When a\n \/\/\/ Monitor is constructed, `recording()` always returns `true`. It can be\n \/\/\/ turned off by `turn_off()` and turned on later by `turn_on()`.\n void eval(\n std::size_t iter, const Particle &particle, MonitorStage stage)\n {\n if (!recording_)\n return;\n\n if (stage != stage_)\n return;\n\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(eval_, eval, EVALUATION);\n\n result_.resize(dim_);\n if (record_only_) {\n eval_(iter, dim_, particle, result_.data());\n push_back(iter);\n\n return;\n }\n\n const std::size_t N = static_cast(particle.size());\n buffer_.resize(N * dim_);\n eval_(iter, dim_, particle, buffer_.data());\n#if VSMC_HAS_MKL\n if (ss_task_.ptr() == nullptr) {\n MKL_INT p = static_cast(dim_);\n MKL_INT n = static_cast(N);\n MKL_INT xstorage = VSL_SS_MATRIX_STORAGE_COLS;\n ss_task_.reset(\n &p, &n, &xstorage, buffer_.data(), result_.data(), nullptr);\n }\n ::vsldSSCompute(ss_task_.ptr(), VSL_SS_MEAN, VSL_SS_METHOD_FAST);\n#ifdef VSMC_CBLAS_INT\n ::cblas_dgemv(::CblasColMajor, ::CblasNoTrans,\n static_cast(dim_), static_cast(N),\n 1, buffer_.data(), static_cast(dim_),\n particle.weight_set().weight_data(), 1, 0, result_.data(), 1);\n#else \/\/ VSMC_CBLAS_INT\n const double *wptr = particle.weight_set().weight_data();\n const double *bptr = buffer_.data();\n std::fill(result_.begin(), result_.end(), 0.0);\n for (std::size_t i = 0; i != N; ++i)\n for (std::size_t d = 0; d != dim_; ++d, ++bptr)\n result_[d] += particle.weight_set().weight(i) * (*bptr);\n#endif \/\/ VSMC_CBLAS_INT\n#endif \/\/ VSMC_HAS_MKL\n push_back(iter);\n }\n\n \/\/\/ \\brief Clear all records of the index and integrations\n void clear()\n {\n index_.clear();\n record_.clear();\n }\n\n \/\/\/ \\brief Whether the Monitor is actively recording results\n bool recording() const { return recording_; }\n\n \/\/\/ \\brief Turn on the recording\n void turn_on() { recording_ = true; }\n\n \/\/\/ \\brief Turn off the recording\n void turn_off() { recording_ = false; }\n\n private:\n std::size_t dim_;\n eval_type eval_;\n bool recording_;\n bool record_only_;\n MonitorStage stage_;\n std::vector name_;\n std::vector index_;\n AlignedVector record_;\n AlignedVector result_;\n AlignedVector buffer_;\n#if VSMC_HAS_MKL\n MKLSSTask ss_task_;\n#endif\n\n void push_back(std::size_t iter)\n {\n index_.push_back(iter);\n record_.insert(record_.end(), result_.begin(), result_.end());\n }\n}; \/\/ class Monitor\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_CORE_MONITOR_HPP\nFix Monitor eval\/\/============================================================================\n\/\/ vSMC\/include\/vsmc\/core\/monitor.hpp\n\/\/----------------------------------------------------------------------------\n\/\/ vSMC: Scalable Monte Carlo\n\/\/----------------------------------------------------------------------------\n\/\/ Copyright (c) 2013-2015, Yan Zhou\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS AS IS\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/============================================================================\n\n#ifndef VSMC_CORE_MONITOR_HPP\n#define VSMC_CORE_MONITOR_HPP\n\n#include \n#include \n#if VSMC_HAS_MKL\n#include \n#endif\n\n#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(func) \\\n VSMC_RUNTIME_ASSERT( \\\n (id < dim()), \"**Monitor::\" #func \"** INVALID ID NUMBER ARGUMENT\")\n\n#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(func) \\\n VSMC_RUNTIME_ASSERT((iter < iter_size()), \\\n \"**Monitor::\" #func \"** INVALID ITERATION NUMBER ARGUMENT\")\n\n#define VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(func, caller, name) \\\n VSMC_RUNTIME_ASSERT(static_cast(func), \\\n \"**Monitor::\" #caller \"** INVALID \" #name \" OBJECT\")\n\nnamespace vsmc\n{\n\n\/\/\/ \\brief Monitor for Monte Carlo integration\n\/\/\/ \\ingroup Core\ntemplate \nclass Monitor\n{\n public:\n typedef T value_type;\n typedef std::function &, double *)> eval_type;\n\n \/\/\/ \\brief Construct a Monitor with an evaluation object\n \/\/\/\n \/\/\/ \\param dim The dimension of the Monitor, i.e., the number of variables\n \/\/\/ \\param eval The evaluation object of type Monitor::eval_type\n \/\/\/ \\param record_only The Monitor only records results instead of\n \/\/\/ calculating them itself\n \/\/\/ \\param stage The stage of the Monitor. A Monitor may be evaluated\n \/\/\/ after\n \/\/\/ all steps that move the particles but before any resampling\n \/\/\/ (`MonitorMove`), or the possible resampling step but before any MCMC\n \/\/\/ steps (`MonitorResample`), all after all MCMC steps (`MonitorMCMC`).\n \/\/\/ If\n \/\/\/ a Monitor is present during initialization, then the initialization\n \/\/\/ are\n \/\/\/ taken as the step that moves particles, and both `MonitorResample` and\n \/\/\/ `MonitorMCMC` are considered after the possible resampling.\n \/\/\/\n \/\/\/ The evaluation object has the signature\n \/\/\/ ~~~{.cpp}\n \/\/\/ void eval (std::size_t iter, std::size_t dim, const Particle\n \/\/\/ &particle, double *result)\n \/\/\/ ~~~\n \/\/\/ where the first three arguments are passed in by the Sampler at the\n \/\/\/ end of each iteration. The evaluation occurs after the possible MCMC\n \/\/\/ moves. The output parameter `result` shall contain the results of the\n \/\/\/ evaluation.\n \/\/\/\n \/\/\/ If `record_only` is true, then the monitor only records the values\n \/\/\/ stored in `result`. Otherwise, the behavior is explained below\n \/\/\/\n \/\/\/ The array `result` is of length `particle.size() * dim`, and it\n \/\/\/ represents a row major matrix of dimension `particle.size()` by `dim`,\n \/\/\/ say \\f$R\\f$. Let \\f$W\\f$ be the vector of the normalized weights. The\n \/\/\/ Monitor will be respoinsible to compute the importance sampling\n \/\/\/ estimate \\f$r = R^TW\\f$ and record it. For example, say the purpose of\n \/\/\/ the Monitor is to record the importance sampling estimates of\n \/\/\/ \\f$E[h(X)]\\f$ where \\f$h(X) = (h_1(X),\\dots,h_d(X))\\f$. Then `result`\n \/\/\/ shall contain the evaluation of \\f$h(X_i)\\f$ for each \\f$i\\f$ from `0`\n \/\/\/ to `particle.size() - 1` in the order\n \/\/\/ \\f$(h_1(X_0), \\dots, h_d(X_0), h_1(X_1), \\dots, h_d(X_1), \\dots)\\f$.\n \/\/\/\n \/\/\/ After each evaluation, the iteration number `iter` and the imporatance\n \/\/\/ sampling estimates are recorded and can be retrived by `index()` and\n \/\/\/ `record()`.\n explicit Monitor(std::size_t dim, const eval_type &eval,\n bool record_only = false, MonitorStage stage = MonitorMCMC)\n : dim_(dim)\n , eval_(eval)\n , recording_(true)\n , record_only_(record_only)\n , stage_(stage)\n , name_(dim)\n {\n }\n\n \/\/\/ \\brief The dimension of the Monitor\n std::size_t dim() const { return dim_; }\n\n \/\/\/ \\brief If this is a record only Monitor\n bool record_only() const { return record_only_; }\n\n \/\/\/ \\brief The stage of the Montior\n MonitorStage stage() const { return stage_; }\n\n \/\/\/ \\brief The number of iterations has been recorded\n \/\/\/\n \/\/\/ \\details\n \/\/\/ This is not necessarily the same as Sampler::iter_size. For\n \/\/\/ example, a Monitor can be added only after a certain time point of the\n \/\/\/ sampler's iterations. Also the Monitor can be turned off for a period\n \/\/\/ during the iterations.\n std::size_t iter_size() const { return index_.size(); }\n\n \/\/\/ \\brief Reserve space for a specified number of iterations\n void reserve(std::size_t num)\n {\n index_.reserve(num);\n record_.reserve(dim_ * num);\n }\n\n \/\/\/ \\brief Whether the evaluation object is valid\n bool empty() const { return !static_cast(eval_); }\n\n \/\/\/ \\brief Read and write access to the names of variables\n \/\/\/\n \/\/\/ \\details\n \/\/\/ By default, each variable of a Monitor is unnamed and the returned\n \/\/\/ string is empty. However, the user can selectively set the names of\n \/\/\/ each variable. This effect how Sampler will print the headers of the\n \/\/\/ summary table.\n std::string &name(std::size_t id)\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);\n\n return name_[id];\n }\n\n \/\/\/ \\brief Read only access to the names of variables\n const std::string &name(std::size_t id) const\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(name);\n\n return name_[id];\n }\n\n \/\/\/ \\brief Get the iteration index of the sampler of a given Monitor\n \/\/\/ iteration\n \/\/\/\n \/\/\/ \\details\n \/\/\/ For example, if a Monitor is only added to the sampler at the\n \/\/\/ sampler's iteration `siter`. Then `index(0)` will be `siter` and so\n \/\/\/ on. If the Monitor is added before the sampler's initialization and\n \/\/\/ continued to be evaluated during the iterations without calling\n \/\/\/ `turnoff()`, then iter(iter) shall just be `iter`.\n std::size_t index(std::size_t iter) const\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(index);\n\n return index_[iter];\n }\n\n \/\/\/ \\brief Get the latest Monte Carlo integration record of a given\n \/\/\/ variable\n \/\/\/\n \/\/\/ \\details\n \/\/\/ For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1\n double record(std::size_t id) const\n {\n std::size_t iter = iter_size() ? iter_size() - 1 : iter_size();\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);\n\n return record_[iter * dim_ + id];\n }\n\n \/\/\/ \\brief Get the Monte Carlo integration record of a given variable and\n \/\/\/ the Monitor iteration\n \/\/\/\n \/\/\/ \\details\n \/\/\/ For a `dim` dimension Monitor, `id` shall be 0 to `dim` - 1\n double record(std::size_t id, std::size_t iter) const\n {\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ID(record);\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_ITER(record);\n\n return record_[iter * dim_ + id];\n }\n\n \/\/\/ \\brief Read the index history through an output iterator\n template \n void read_index(OutputIter first) const\n {\n std::copy(index_.begin(), index_.end(), first);\n }\n\n \/\/\/ \\brief Read only access to the raw data of the index vector\n const std::size_t *index_data() const { return index_.data(); }\n\n \/\/\/ \\brief Read only access to the raw data of records (a row major\n \/\/\/ matrix)\n const double *record_data() const { return record_.data(); }\n\n \/\/\/ \\brief Read only access to the raw data of records for a given\n \/\/\/ Monitor iteration\n const double *record_data(std::size_t iter) const\n {\n return record_.data() + iter * dim_;\n }\n\n \/\/\/ \\brief Read the record history for a given variable through an output\n \/\/\/ iterator\n template \n void read_record(std::size_t id, OutputIter first) const\n {\n const std::size_t N = iter_size();\n const double *riter = record_.data() + id;\n for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)\n *first = *riter;\n }\n\n \/\/\/ \\brief Read the record history of all variables through an array of\n \/\/\/ output iterators\n \/\/\/\n \/\/\/ \\param first An iterator of container of output iterators\n template \n void read_record_matrix(OutputIterIter first) const\n {\n for (std::size_t d = 0; d != dim_; ++d, ++first)\n read_record(d, *first);\n }\n\n \/\/\/ \\brief Read the record history of all variables through an output\n \/\/\/ iterator\n \/\/\/\n \/\/\/ \\param first The output iterator\n \/\/\/\n \/\/\/ For example, say `first` is of type `double *`, then if `order ==\n \/\/\/ ColMajor`, then, `first[j * iter_size() + i] == record(i, j)`.\n \/\/\/ Otherwise, if `order == RowMajor`, then `first[i * dim() + j] ==\n \/\/\/ record(i, j)`. That is, the output is an `iter_size()` by `dim()`\n \/\/\/ matrix, with the usual meaning of column or row major order.\n template \n void read_record_matrix(OutputIter first) const\n {\n const std::size_t N = iter_size();\n if (Order == ColMajor) {\n for (std::size_t d = 0; d != dim_; ++d) {\n const double *riter = record_.data() + d;\n for (std::size_t i = 0; i != N; ++i, ++first, riter += dim_)\n *first = *riter;\n }\n }\n\n if (Order == RowMajor)\n std::copy(record_.begin(), record_.end(), first);\n }\n\n \/\/\/ \\brief Set a new evaluation object of type eval_type\n void set_eval(const eval_type &new_eval) { eval_ = new_eval; }\n\n \/\/\/ \\brief Perform the evaluation for a given iteration and a Particle\n \/\/\/ object.\n \/\/\/\n \/\/\/ \\details\n \/\/\/ This function is called by a Sampler at the end of each\n \/\/\/ iteration. It does nothing if `recording()` returns `false`. Otherwise\n \/\/\/ it use the user defined evaluation object to compute results. When a\n \/\/\/ Monitor is constructed, `recording()` always returns `true`. It can be\n \/\/\/ turned off by `turn_off()` and turned on later by `turn_on()`.\n void eval(\n std::size_t iter, const Particle &particle, MonitorStage stage)\n {\n if (!recording_)\n return;\n\n if (stage != stage_)\n return;\n\n VSMC_RUNTIME_ASSERT_CORE_MONITOR_FUNCTOR(eval_, eval, EVALUATION);\n\n result_.resize(dim_);\n if (record_only_) {\n eval_(iter, dim_, particle, result_.data());\n push_back(iter);\n\n return;\n }\n\n const std::size_t N = static_cast(particle.size());\n buffer_.resize(N * dim_);\n eval_(iter, dim_, particle, buffer_.data());\n\n#if VSMC_HAS_MKL\n MKL_INT p = static_cast(dim_);\n MKL_INT n = static_cast(N);\n MKL_INT xstorage = VSL_SS_MATRIX_STORAGE_COLS;\n const double *const x = buffer_.data();\n const double *const w = particle.weight_set().weight_data();\n const double *const s = result_.data();\n if (ss_task_.get() == nullptr)\n ss_task_.reset(&p, &n, &xstorage, x, w);\n ::vsliSSEditTask(ss_task_.ptr(), VSL_SS_ED_DIMEN, &p);\n ::vsliSSEditTask(ss_task_.ptr(), VSL_SS_ED_OBSERV_N, &n);\n ::vsliSSEditTask(ss_task_.ptr(), VSL_SS_ED_OBSERV_STORAGE, &xstorage);\n ::vsldSSEditTask(ss_task_.ptr(), VSL_SS_ED_OBSERV, x);\n ::vsldSSEditTask(ss_task_.ptr(), VSL_SS_ED_WEIGHTS, w);\n ::vsldSSEditTask(ss_task_.ptr(), VSL_SS_ED_SUM, s);\n ::vsldSSCompute(ss_task_.ptr(), VSL_SS_SUM, VSL_SS_METHOD_FAST);\n#else \/\/ VSMC_HAS_MKL\n#ifdef VSMC_CBLAS_INT\n ::cblas_dgemv(::CblasColMajor, ::CblasNoTrans,\n static_cast(dim_), static_cast(N),\n 1, buffer_.data(), static_cast(dim_),\n particle.weight_set().weight_data(), 1, 0, result_.data(), 1);\n#else \/\/ VSMC_CBLAS_INT\n const double *wptr = particle.weight_set().weight_data();\n const double *bptr = buffer_.data();\n std::fill(result_.begin(), result_.end(), 0.0);\n for (std::size_t i = 0; i != N; ++i)\n for (std::size_t d = 0; d != dim_; ++d, ++bptr)\n result_[d] += particle.weight_set().weight(i) * (*bptr);\n#endif \/\/ VSMC_CBLAS_INT\n#endif \/\/ VSMC_HAS_MKL\n\n push_back(iter);\n }\n\n \/\/\/ \\brief Clear all records of the index and integrations\n void clear()\n {\n index_.clear();\n record_.clear();\n }\n\n \/\/\/ \\brief Whether the Monitor is actively recording results\n bool recording() const { return recording_; }\n\n \/\/\/ \\brief Turn on the recording\n void turn_on() { recording_ = true; }\n\n \/\/\/ \\brief Turn off the recording\n void turn_off() { recording_ = false; }\n\n private:\n std::size_t dim_;\n eval_type eval_;\n bool recording_;\n bool record_only_;\n MonitorStage stage_;\n std::vector name_;\n std::vector index_;\n AlignedVector record_;\n AlignedVector result_;\n AlignedVector buffer_;\n#if VSMC_HAS_MKL\n MKLSSTask ss_task_;\n#endif\n\n void push_back(std::size_t iter)\n {\n index_.push_back(iter);\n record_.insert(record_.end(), result_.begin(), result_.end());\n }\n}; \/\/ class Monitor\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_CORE_MONITOR_HPP\n<|endoftext|>"} {"text":"\/\/=============================================================================================================\n\/**\n * @file main.cpp\n * @author Ruben Dörfel ;\n * @since 0.1.0\n * @date February, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Test for fitHpi function in inverse library.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace FIFFLIB;\nusing namespace UTILSLIB;\nusing namespace INVERSELIB;\nusing namespace Eigen;\n\n\/\/=============================================================================================================\n\/**\n * DECLARE CLASS TestHpiFit\n *\n * @brief The TestHpiFit class provides hpi fit verifivcation tests\n *\n *\/\nclass TestHpiFit: public QObject\n{\n Q_OBJECT\n\npublic:\n TestHpiFit();\n\nprivate slots:\n void initTestCase();\n void testDataPrepatationFinished();\n void compareFrequencies();\n void compareTranslation();\n void compareRotation();\n void compareAngle();\n void compareMove();\n void compareDetect();\n void compareTime();\n void cleanupTestCase();\n\nprivate:\n double dErrorTrans = 0.0003;\n double dErrorQuat = 0.002;\n double dErrorTime = 0.00000001;\n double dErrorAngle = 0.1;\n double dErrorDetect = 0.0;\n bool mDataPreparationFinishedCorrectly;\n MatrixXd mRefPos;\n MatrixXd mHpiPos;\n MatrixXd mRefResult;\n MatrixXd mHpiResult;\n QVector vFreqs;\n};\n\n\/\/=============================================================================================================\n\nTestHpiFit::TestHpiFit()\n: dErrorTrans(0.0003),\ndErrorQuat(0.002),\ndErrorTime(0.00000001),\ndErrorAngle(0.1),\ndErrorDetect(0.0),\nmDataPreparationFinishedCorrectly(false)\n{\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::initTestCase()\n{\n qInstallMessageHandler(ApplicationLogger::customLogWriter);\n qInfo() << \"Error Translation\" << dErrorTrans;\n qInfo() << \"Error Quaternion\" << dErrorQuat;\n QFile t_fileIn(QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/MEG\/sample\/test_hpiFit_raw.fif\");\n\n \/\/ Make sure test folder exists\n QFileInfo t_fileInInfo(t_fileIn);\n QDir().mkdir(t_fileInInfo.path());\n\n printf(\">>>>>>>>>>>>>>>>>>>>>>>>> Read Raw and HPI fit >>>>>>>>>>>>>>>>>>>>>>>>>\\n\");\n\n \/\/ Setup for reading the raw data\n FiffRawData raw;\n raw = FiffRawData(t_fileIn);\n QSharedPointer pFiffInfo = QSharedPointer(new FiffInfo(raw.info));\n\n \/\/ Only filter MEG channels\n RowVectorXi picks = raw.info.pick_types(true, false, false);\n RowVectorXd cals;\n\n FiffCoordTrans devHeadT = pFiffInfo->dev_head_t;\n\n \/\/ Set up the reading parameters\n fiff_int_t from;\n fiff_int_t to;\n fiff_int_t first = raw.first_samp;\n fiff_int_t last = raw.last_samp;\n MatrixXd mData, mTimes;\n\n float quantum_sec = 0.2f; \/\/read and write in 200 ms junks\n fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);\n\n \/\/ Read Quaternion File from maxfilter and calculated movements\/rotations with python\n IOUtils::read_eigen_matrix(mRefPos, QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/Result\/ref_hpiFit_pos.txt\");\n IOUtils::read_eigen_matrix(mRefResult, QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/Result\/ref_angle_move.txt\");\n\n mHpiResult = mRefResult;\n\n \/\/ define thresholds for big head movement detection\n float threshRot = 2.0f;\n float threshTrans = 0.002f;\n\n \/\/ Setup informations for HPI fit\n vFreqs = {154,158,161,166};\n QVector vError;\n VectorXd vGoF;\n FiffDigPointSet fittedPointSet;\n Eigen::MatrixXd mProjectors = Eigen::MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());\n QString sHPIResourceDir = QCoreApplication::applicationDirPath() + \"\/HPIFittingDebug\";\n bool bDoDebug = true;\n\n HPIFit HPI = HPIFit(pFiffInfo, true);\n\n \/\/ bring frequencies into right order\n from = first + mRefPos(0,0)*pFiffInfo->sfreq;\n to = from + quantum;\n if(!raw.read_raw_segment(mData, mTimes, from, to)) {\n qCritical(\"error during read_raw_segment\");\n }\n qInfo() << \"[done]\";\n\n qInfo() << \"Order Frequecies: ...\";\n HPI.findOrder(mData,\n mProjectors,\n pFiffInfo->dev_head_t,\n vFreqs,\n vError,\n vGoF,\n fittedPointSet,\n pFiffInfo);\n qInfo() << \"[done]\";\n\n for(int i = 0; i < mRefPos.rows(); i++) {\n from = first + mRefPos(i,0)*pFiffInfo->sfreq;\n to = from + quantum;\n if (to > last) {\n to = last;\n }\n qInfo() << \"Reading...\";\n if(!raw.read_raw_segment(mData, mTimes, from, to)) {\n qWarning(\"error during read_raw_segment\\n\");\n }\n\n qInfo() << \"HPI-Fit...\";\n HPI.fitHPI(mData,\n mProjectors,\n pFiffInfo->dev_head_t,\n vFreqs,\n vError,\n vGoF,\n fittedPointSet,\n pFiffInfo,\n bDoDebug = 0,\n sHPIResourceDir,\n 200,\n 1e-5f);\n qInfo() << \"[done]\\n\";\n\n if(MNEMath::compareTransformation(devHeadT.trans, pFiffInfo->dev_head_t.trans, threshRot, threshTrans)) {\n mHpiResult(i,2) = 1;\n }\n\n HPIFit::storeHeadPosition(mRefPos(i,0), pFiffInfo->dev_head_t.trans, mHpiPos, vGoF, vError);\n mHpiResult(i,0) = devHeadT.translationTo(pFiffInfo->dev_head_t.trans);\n mHpiResult(i,1) = devHeadT.angleTo(pFiffInfo->dev_head_t.trans);\n\n }\n\n mDataPreparationFinishedCorrectly = true;\n \/\/ For debug: position file for HPIFit\n\/\/ UTILSLIB::IOUtils::write_eigen_matrix(mHpiPos, QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/mHpiPos.txt\");\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::testDataPrepatationFinished()\n{\n QVERIFY(mDataPreparationFinishedCorrectly);\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::compareFrequencies()\n{\n QVector vFreqRef {166, 154, 161, 158};\n QVERIFY(vFreqRef == vFreqs);\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::compareTranslation()\n{\n RowVector3d vDiffTrans;\n vDiffTrans(0) = (mRefPos.col(4)-mHpiPos.col(4)).mean();\n vDiffTrans(1) = (mRefPos.col(5)-mHpiPos.col(5)).mean();\n vDiffTrans(2) = (mRefPos.col(6)-mHpiPos.col(6)).mean();\n qDebug() << \"ErrorTrans x: \" << std::abs(vDiffTrans(0));\n qDebug() << \"ErrorTrans y: \" << std::abs(vDiffTrans(1));\n qDebug() << \"ErrorTrans z: \" << std::abs(vDiffTrans(2));\n QVERIFY(std::abs(vDiffTrans(0)) < dErrorTrans);\n QVERIFY(std::abs(vDiffTrans(1)) < dErrorTrans);\n QVERIFY(std::abs(vDiffTrans(2)) < dErrorTrans);\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::compareRotation()\n{\n RowVector3d vDiffQuat;\n vDiffQuat(0) = (mRefPos.col(1)-mHpiPos.col(1)).mean();\n vDiffQuat(1) = (mRefPos.col(2)-mHpiPos.col(2)).mean();\n vDiffQuat(2) = (mRefPos.col(3)-mHpiPos.col(3)).mean();\n qDebug() << \"ErrorQuat q1: \" <delete unnecessary variable in test_hpi\/\/=============================================================================================================\n\/**\n * @file main.cpp\n * @author Ruben Dörfel ;\n * @since 0.1.0\n * @date February, 2020\n *\n * @section LICENSE\n *\n * Copyright (C) 2020, Ruben Dörfel. All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that\n * the following conditions are met:\n * * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n * following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and\n * the following disclaimer in the documentation and\/or other materials provided with the distribution.\n * * Neither the name of MNE-CPP authors nor the names of its contributors may be used\n * to endorse or promote products derived from this software without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED\n * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,\n * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n *\n * @brief Test for fitHpi function in inverse library.\n *\n *\/\n\n\/\/=============================================================================================================\n\/\/ INCLUDES\n\/\/=============================================================================================================\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n\n#include \n\n\/\/=============================================================================================================\n\/\/ QT INCLUDES\n\/\/=============================================================================================================\n\n#include \n#include \n#include \n#include \n#include \n\n\/\/=============================================================================================================\n\/\/ USED NAMESPACES\n\/\/=============================================================================================================\n\nusing namespace FIFFLIB;\nusing namespace UTILSLIB;\nusing namespace INVERSELIB;\nusing namespace Eigen;\n\n\/\/=============================================================================================================\n\/**\n * DECLARE CLASS TestHpiFit\n *\n * @brief The TestHpiFit class provides hpi fit verifivcation tests\n *\n *\/\nclass TestHpiFit: public QObject\n{\n Q_OBJECT\n\npublic:\n TestHpiFit();\n\nprivate slots:\n void initTestCase();\n void compareFrequencies();\n void compareTranslation();\n void compareRotation();\n void compareAngle();\n void compareMove();\n void compareDetect();\n void compareTime();\n void cleanupTestCase();\n\nprivate:\n double dErrorTrans = 0.0003;\n double dErrorQuat = 0.002;\n double dErrorTime = 0.00000001;\n double dErrorAngle = 0.1;\n double dErrorDetect = 0.0;\n MatrixXd mRefPos;\n MatrixXd mHpiPos;\n MatrixXd mRefResult;\n MatrixXd mHpiResult;\n QVector vFreqs;\n};\n\n\/\/=============================================================================================================\n\nTestHpiFit::TestHpiFit()\n: dErrorTrans(0.0003),\ndErrorQuat(0.002),\ndErrorTime(0.00000001),\ndErrorAngle(0.1),\ndErrorDetect(0.0)\n{\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::initTestCase()\n{\n qInstallMessageHandler(ApplicationLogger::customLogWriter);\n qInfo() << \"Error Translation\" << dErrorTrans;\n qInfo() << \"Error Quaternion\" << dErrorQuat;\n QFile t_fileIn(QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/MEG\/sample\/test_hpiFit_raw.fif\");\n\n \/\/ Make sure test folder exists\n QFileInfo t_fileInInfo(t_fileIn);\n QDir().mkdir(t_fileInInfo.path());\n\n printf(\">>>>>>>>>>>>>>>>>>>>>>>>> Read Raw and HPI fit >>>>>>>>>>>>>>>>>>>>>>>>>\\n\");\n\n \/\/ Setup for reading the raw data\n FiffRawData raw;\n raw = FiffRawData(t_fileIn);\n QSharedPointer pFiffInfo = QSharedPointer(new FiffInfo(raw.info));\n\n \/\/ Only filter MEG channels\n RowVectorXi picks = raw.info.pick_types(true, false, false);\n RowVectorXd cals;\n\n FiffCoordTrans devHeadT = pFiffInfo->dev_head_t;\n\n \/\/ Set up the reading parameters\n fiff_int_t from;\n fiff_int_t to;\n fiff_int_t first = raw.first_samp;\n fiff_int_t last = raw.last_samp;\n MatrixXd mData, mTimes;\n\n float quantum_sec = 0.2f; \/\/read and write in 200 ms junks\n fiff_int_t quantum = ceil(quantum_sec*pFiffInfo->sfreq);\n\n \/\/ Read Quaternion File from maxfilter and calculated movements\/rotations with python\n IOUtils::read_eigen_matrix(mRefPos, QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/Result\/ref_hpiFit_pos.txt\");\n IOUtils::read_eigen_matrix(mRefResult, QCoreApplication::applicationDirPath() + \"\/mne-cpp-test-data\/Result\/ref_angle_move.txt\");\n\n mHpiResult = mRefResult;\n\n \/\/ define thresholds for big head movement detection\n float threshRot = 2.0f;\n float threshTrans = 0.002f;\n\n \/\/ Setup informations for HPI fit\n vFreqs = {154,158,161,166};\n QVector vError;\n VectorXd vGoF;\n FiffDigPointSet fittedPointSet;\n Eigen::MatrixXd mProjectors = Eigen::MatrixXd::Identity(pFiffInfo->chs.size(), pFiffInfo->chs.size());\n QString sHPIResourceDir = QCoreApplication::applicationDirPath() + \"\/HPIFittingDebug\";\n bool bDoDebug = true;\n\n HPIFit HPI = HPIFit(pFiffInfo, true);\n\n \/\/ bring frequencies into right order\n from = first + mRefPos(0,0)*pFiffInfo->sfreq;\n to = from + quantum;\n if(!raw.read_raw_segment(mData, mTimes, from, to)) {\n qCritical(\"error during read_raw_segment\");\n }\n qInfo() << \"[done]\";\n\n qInfo() << \"Order Frequecies: ...\";\n HPI.findOrder(mData,\n mProjectors,\n pFiffInfo->dev_head_t,\n vFreqs,\n vError,\n vGoF,\n fittedPointSet,\n pFiffInfo);\n qInfo() << \"[done]\";\n\n for(int i = 0; i < mRefPos.rows(); i++) {\n from = first + mRefPos(i,0)*pFiffInfo->sfreq;\n to = from + quantum;\n if (to > last) {\n to = last;\n }\n qInfo() << \"Reading...\";\n if(!raw.read_raw_segment(mData, mTimes, from, to)) {\n qWarning(\"error during read_raw_segment\\n\");\n }\n\n qInfo() << \"HPI-Fit...\";\n HPI.fitHPI(mData,\n mProjectors,\n pFiffInfo->dev_head_t,\n vFreqs,\n vError,\n vGoF,\n fittedPointSet,\n pFiffInfo,\n bDoDebug = 0,\n sHPIResourceDir,\n 200,\n 1e-5f);\n qInfo() << \"[done]\\n\";\n\n if(MNEMath::compareTransformation(devHeadT.trans, pFiffInfo->dev_head_t.trans, threshRot, threshTrans)) {\n mHpiResult(i,2) = 1;\n }\n\n HPIFit::storeHeadPosition(mRefPos(i,0), pFiffInfo->dev_head_t.trans, mHpiPos, vGoF, vError);\n mHpiResult(i,0) = devHeadT.translationTo(pFiffInfo->dev_head_t.trans);\n mHpiResult(i,1) = devHeadT.angleTo(pFiffInfo->dev_head_t.trans);\n\n }\n \/\/ For debug: position file for HPIFit\n\/\/ UTILSLIB::IOUtils::write_eigen_matrix(mHpiPos, QCoreApplication::applicationDirPath() + \"\/MNE-sample-data\/mHpiPos.txt\");\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::compareFrequencies()\n{\n QVector vFreqRef {166, 154, 161, 158};\n QVERIFY(vFreqRef == vFreqs);\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::compareTranslation()\n{\n RowVector3d vDiffTrans;\n vDiffTrans(0) = (mRefPos.col(4)-mHpiPos.col(4)).mean();\n vDiffTrans(1) = (mRefPos.col(5)-mHpiPos.col(5)).mean();\n vDiffTrans(2) = (mRefPos.col(6)-mHpiPos.col(6)).mean();\n qDebug() << \"ErrorTrans x: \" << std::abs(vDiffTrans(0));\n qDebug() << \"ErrorTrans y: \" << std::abs(vDiffTrans(1));\n qDebug() << \"ErrorTrans z: \" << std::abs(vDiffTrans(2));\n QVERIFY(std::abs(vDiffTrans(0)) < dErrorTrans);\n QVERIFY(std::abs(vDiffTrans(1)) < dErrorTrans);\n QVERIFY(std::abs(vDiffTrans(2)) < dErrorTrans);\n}\n\n\/\/=============================================================================================================\n\nvoid TestHpiFit::compareRotation()\n{\n RowVector3d vDiffQuat;\n vDiffQuat(0) = (mRefPos.col(1)-mHpiPos.col(1)).mean();\n vDiffQuat(1) = (mRefPos.col(2)-mHpiPos.col(2)).mean();\n vDiffQuat(2) = (mRefPos.col(3)-mHpiPos.col(3)).mean();\n qDebug() << \"ErrorQuat q1: \" <"} {"text":"\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ transaction_test.cpp\n\/\/\n\/\/ Identification: tests\/concurrency\/transaction_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"harness.h\"\n#include \"concurrency\/transaction_tests_util.h\"\n\nnamespace peloton {\n\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Transaction Tests\n\/\/===--------------------------------------------------------------------===\/\/\n\nclass TransactionTests : public PelotonTest {};\n\nstd::vector TEST_TYPES = {\n \/\/ CONCURRENCY_TYPE_OCC\n CONCURRENCY_TYPE_2PL};\n\nvoid TransactionTest(concurrency::TransactionManager *txn_manager) {\n uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();\n\n for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {\n txn_manager->BeginTransaction();\n if (thread_id % 2 == 0) {\n std::chrono::microseconds sleep_time(1);\n std::this_thread::sleep_for(sleep_time);\n }\n\n if (txn_itr % 25 != 0) {\n txn_manager->CommitTransaction();\n } else {\n txn_manager->AbortTransaction();\n }\n }\n}\n\nvoid DirtyWriteTest(ConcurrencyType test_type) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n \/\/ T1 updates (0, ?) to (0, 1)\n \/\/ T2 updates (0, ?) to (0, 2)\n \/\/ T1 commits\n \/\/ T2 commits\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddUpdate(1, 0, 2);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n schedules.clear();\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddUpdate(1, 0, 2);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n \/\/ T0 delete (0, ?)\n \/\/ T1 update (0, ?) to (0, 3)\n \/\/ T0 commit\n \/\/ T1 commit\n scheduler.AddDelete(0, 0);\n scheduler.AddUpdate(1, 0, 3);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n schedules.clear();\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n \/\/ T0 delete (1, ?)\n \/\/ T1 delete (1, ?)\n \/\/ T0 commit\n \/\/ T1 commit\n scheduler.AddDelete(0, 1);\n scheduler.AddDelete(1, 1);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n schedules.clear();\n }\n}\n\nvoid DirtyReadTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n \/\/ T1 updates (0, ?) to (0, 1)\n \/\/ T2 reads (0, ?)\n \/\/ T1 commit\n \/\/ T2 commit\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n \/\/ T1 updates (0, ?) to (0, 1)\n \/\/ T2 reads (0, ?)\n \/\/ T2 commit\n \/\/ T1 commit\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n \/\/ T0 delete (0, ?)\n \/\/ T1 read (0, ?)\n \/\/ T0 commit\n \/\/ T1 commit\n scheduler.AddDelete(0, 0);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n}\n\nvoid FuzzyReadTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n \/\/ T0 read 0\n \/\/ T1 update (0, 0) to (0, 1)\n \/\/ T1 commit\n \/\/ T0 commit\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(1, 0, 1);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n\n LOG_TRACE(\"%lu\", scheduler.schedules.size());\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n \/\/ T0 read 0\n \/\/ T1 update (0, 0) to (0, 1)\n \/\/ T0 commit\n \/\/ T1 commit\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(1, 0, 1);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n \/\/ T0 read 0\n \/\/ T1 delete 0\n \/\/ T0 commit\n \/\/ T1 commit\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddDelete(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n}\n\nvoid PhantomTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddScan(0, 0);\n scheduler.AddInsert(1, 5, 0);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddScan(0, 0);\n scheduler.AddDelete(1, 4);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n }\n}\n\nvoid WriteSkewTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(0, 1, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddUpdate(1, 1, 2);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n \/\/ Can't all success\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(0, 1, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddUpdate(1, 1, 2);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n \/\/ First txn should success\n EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_ABORTED == scheduler.schedules[1].txn_result);\n }\n}\n\nvoid ReadSkewTest(ConcurrencyType test_type) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(1, 0, 1);\n scheduler.AddUpdate(1, 1, 1);\n scheduler.AddCommit(1);\n scheduler.AddRead(0, 1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n}\n\nTEST_F(TransactionTests, TransactionTest) {\n for (auto test_type : TEST_TYPES) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n\n LaunchParallelTest(8, TransactionTest, &txn_manager);\n\n std::cout << \"next Commit Id :: \" << txn_manager.GetNextCommitId() << \"\\n\";\n }\n}\n\nTEST_F(TransactionTests, AbortTest) {\n for (auto test_type : TEST_TYPES) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddUpdate(0, 0, 100);\n scheduler.AddAbort(0);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n EXPECT_EQ(0, scheduler.schedules[1].results[0]);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddInsert(0, 100, 0);\n scheduler.AddAbort(0);\n scheduler.AddRead(1, 100);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n EXPECT_EQ(-1, scheduler.schedules[1].results[0]);\n }\n }\n}\n\nTEST_F(TransactionTests, SerializableTest) {\n for (auto test_type : TEST_TYPES) {\n DirtyWriteTest(test_type);\n DirtyReadTest(test_type);\n FuzzyReadTest(test_type);\n WriteSkewTest(test_type);\n ReadSkewTest(test_type);\n \/\/ PhantomTes();\n }\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\ntxn test is too strict\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ PelotonDB\n\/\/\n\/\/ transaction_test.cpp\n\/\/\n\/\/ Identification: tests\/concurrency\/transaction_test.cpp\n\/\/\n\/\/ Copyright (c) 2015, Carnegie Mellon University Database Group\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"harness.h\"\n#include \"concurrency\/transaction_tests_util.h\"\n\nnamespace peloton {\n\nnamespace test {\n\n\/\/===--------------------------------------------------------------------===\/\/\n\/\/ Transaction Tests\n\/\/===--------------------------------------------------------------------===\/\/\n\nclass TransactionTests : public PelotonTest {};\n\nstd::vector TEST_TYPES = {\n \/\/ CONCURRENCY_TYPE_OCC\n CONCURRENCY_TYPE_2PL};\n\nvoid TransactionTest(concurrency::TransactionManager *txn_manager) {\n uint64_t thread_id = TestingHarness::GetInstance().GetThreadId();\n\n for (oid_t txn_itr = 1; txn_itr <= 50; txn_itr++) {\n txn_manager->BeginTransaction();\n if (thread_id % 2 == 0) {\n std::chrono::microseconds sleep_time(1);\n std::this_thread::sleep_for(sleep_time);\n }\n\n if (txn_itr % 25 != 0) {\n txn_manager->CommitTransaction();\n } else {\n txn_manager->AbortTransaction();\n }\n }\n}\n\nvoid DirtyWriteTest(ConcurrencyType test_type) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n \/\/ T1 updates (0, ?) to (0, 1)\n \/\/ T2 updates (0, ?) to (0, 2)\n \/\/ T1 commits\n \/\/ T2 commits\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddUpdate(1, 0, 2);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n schedules.clear();\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddUpdate(1, 0, 2);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n \/\/ T0 delete (0, ?)\n \/\/ T1 update (0, ?) to (0, 3)\n \/\/ T0 commit\n \/\/ T1 commit\n scheduler.AddDelete(0, 0);\n scheduler.AddUpdate(1, 0, 3);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n schedules.clear();\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n \/\/ T0 delete (1, ?)\n \/\/ T1 delete (1, ?)\n \/\/ T0 commit\n \/\/ T1 commit\n scheduler.AddDelete(0, 1);\n scheduler.AddDelete(1, 1);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n auto &schedules = scheduler.schedules;\n\n \/\/ T1 and T2 can't both succeed\n EXPECT_FALSE(schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_SUCCESS);\n \/\/ For MVCC, actually one and only one T should succeed?\n EXPECT_TRUE((schedules[0].txn_result == RESULT_SUCCESS &&\n schedules[1].txn_result == RESULT_ABORTED) ||\n (schedules[0].txn_result == RESULT_ABORTED &&\n schedules[1].txn_result == RESULT_SUCCESS));\n schedules.clear();\n }\n}\n\nvoid DirtyReadTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n \/\/ T1 updates (0, ?) to (0, 1)\n \/\/ T2 reads (0, ?)\n \/\/ T1 commit\n \/\/ T2 commit\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n \/\/ T1 updates (0, ?) to (0, 1)\n \/\/ T2 reads (0, ?)\n \/\/ T2 commit\n \/\/ T1 commit\n scheduler.AddUpdate(0, 0, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n\n \/\/ T0 delete (0, ?)\n \/\/ T1 read (0, ?)\n \/\/ T0 commit\n \/\/ T1 commit\n scheduler.AddDelete(0, 0);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_ABORTED == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n}\n\nvoid FuzzyReadTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n \/\/ T0 read 0\n \/\/ T1 update (0, 0) to (0, 1)\n \/\/ T1 commit\n \/\/ T0 commit\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(1, 0, 1);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n\n LOG_TRACE(\"%lu\", scheduler.schedules.size());\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n \/\/ T0 read 0\n \/\/ T1 update (0, 0) to (0, 1)\n \/\/ T0 commit\n \/\/ T1 commit\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(1, 0, 1);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n \/\/ T0 read 0\n \/\/ T1 delete 0\n \/\/ T0 commit\n \/\/ T1 commit\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddDelete(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n}\n\nvoid PhantomTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddScan(0, 0);\n scheduler.AddInsert(1, 5, 0);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddScan(0, 0);\n scheduler.AddDelete(1, 4);\n scheduler.AddCommit(1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n }\n}\n\nvoid WriteSkewTest(ConcurrencyType TEST_TYPE) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(TEST_TYPE);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(0, 1, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddUpdate(1, 1, 2);\n scheduler.AddCommit(0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n \/\/ Can't all success\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(0, 1, 1);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(0);\n scheduler.AddUpdate(1, 1, 2);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n \/\/ First txn should success\n EXPECT_TRUE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_ABORTED == scheduler.schedules[1].txn_result);\n }\n}\n\nvoid ReadSkewTest(ConcurrencyType test_type) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddRead(0, 0);\n scheduler.AddUpdate(1, 0, 1);\n scheduler.AddUpdate(1, 1, 1);\n scheduler.AddCommit(1);\n scheduler.AddRead(0, 1);\n scheduler.AddCommit(0);\n\n scheduler.Run();\n\n EXPECT_FALSE(RESULT_SUCCESS == scheduler.schedules[0].txn_result &&\n RESULT_SUCCESS == scheduler.schedules[1].txn_result);\n }\n}\n\nTEST_F(TransactionTests, TransactionTest) {\n for (auto test_type : TEST_TYPES) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n\n LaunchParallelTest(8, TransactionTest, &txn_manager);\n\n std::cout << \"next Commit Id :: \" << txn_manager.GetNextCommitId() << \"\\n\";\n }\n}\n\nTEST_F(TransactionTests, AbortTest) {\n for (auto test_type : TEST_TYPES) {\n auto &txn_manager =\n concurrency::TransactionManagerFactory::GetInstance(test_type);\n std::unique_ptr table(\n TransactionTestsUtil::CreateTable());\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddUpdate(0, 0, 100);\n scheduler.AddAbort(0);\n scheduler.AddRead(1, 0);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n EXPECT_EQ(0, scheduler.schedules[1].results[0]);\n }\n\n {\n TransactionScheduler scheduler(2, table.get(), &txn_manager);\n scheduler.AddInsert(0, 100, 0);\n scheduler.AddAbort(0);\n scheduler.AddRead(1, 100);\n scheduler.AddCommit(1);\n\n scheduler.Run();\n EXPECT_EQ(RESULT_ABORTED, scheduler.schedules[0].txn_result);\n EXPECT_EQ(RESULT_SUCCESS, scheduler.schedules[1].txn_result);\n EXPECT_EQ(-1, scheduler.schedules[1].results[0]);\n }\n }\n}\n\nTEST_F(TransactionTests, SerializableTest) {\n for (auto test_type : TEST_TYPES) {\n DirtyWriteTest(test_type);\n DirtyReadTest(test_type);\n FuzzyReadTest(test_type);\n WriteSkewTest(test_type);\n ReadSkewTest(test_type);\n \/\/ PhantomTes();\n }\n}\n\n} \/\/ End test namespace\n} \/\/ End peloton namespace\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2008-2018 the MRtrix3 contributors.\n*\n* This Source Code Form is subject to the terms of the Mozilla Public\n* License, v. 2.0. If a copy of the MPL was not distributed with this\n* file, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n*\n* MRtrix3 is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty\n* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\n* For more details, see http:\/\/www.mrtrix.org\/\n*\/\r\n#include \"gui\/mrview\/sync\/syncmanager.h\"\r\n#include \"gui\/mrview\/window.h\"\r\n#include \r\n#include \r\n#include \/\/shared_ptr\r\n#include \"gui\/mrview\/sync\/enums.h\"\r\n\r\nnamespace MR\r\n{\r\n namespace GUI\r\n {\r\n namespace MRView\r\n {\r\n namespace Sync\r\n {\r\n SyncManager::SyncManager() : QObject(0)\r\n {\r\n try\r\n {\r\n ips = new InterprocessCommunicator();\/\/will throw exception if it fails to set up a server\r\n connect(ips, SIGNAL(SyncDataReceived(std::vector>)), this, SLOT(OnIPSDataReceived(std::vector>)));\r\n }\r\n catch (...)\r\n {\r\n ips = 0;\r\n WARN(\"Sync set up failed.\");\r\n }\r\n }\r\n\r\n \/**\r\n * Returns true if this is in a state which is not appropriate to connect a window\r\n *\/\r\n bool SyncManager::GetInErrorState()\r\n {\r\n return ips == 0;\r\n }\r\n\r\n \/**\r\n * Sets the window to connect to. Code currently assumes this only occurs once. Also check GetInErrorState() before calling\r\n *\/\r\n void SyncManager::SetWindow(MR::GUI::MRView::Window* wind)\r\n {\r\n if (GetInErrorState())\r\n {\r\n throw Exception(\"Attempt to set window while in an error state\");\r\n }\r\n win = wind;\r\n connect(win, SIGNAL(focusChanged()), this, SLOT(OnWindowFocusChanged()));\r\n }\r\n\r\n \/**\r\n * Receives a signal from window that the focus has changed\r\n *\/\r\n void SyncManager::OnWindowFocusChanged()\r\n {\r\n if (win->sync_focus_on())\r\n {\r\n Eigen::Vector3f foc = win->focus();\r\n SendData(DataKey::WindowFocus, ToQByteArray(foc));\r\n }\r\n }\r\n\r\n \/**\r\n * Sends a signal to other processes to sync to a given key\/value\r\n *\/\r\n bool SyncManager::SendData(DataKey code, QByteArray dat)\r\n {\r\n QByteArray data;\r\n char codeAsChar[4];\r\n InterprocessCommunicator::Int32ToChar(codeAsChar, (int)code);\r\n data.insert(0, codeAsChar, 4);\r\n data.insert(4, dat, dat.size());\r\n\r\n return ips->SendData(data);\r\n }\r\n\r\n \/**\r\n * Receives a signal from another process that a value to sync has changed\r\n *\/\r\n void SyncManager::OnIPSDataReceived(std::vector> all_messages)\r\n {\r\n \/\/WARNING This code assumes that the order of syncing operations does not matter\r\n\r\n \/\/We have a list of messages found\r\n \/\/Categorise these. Only keep the last value sent for each message type, or we will change to an old value and then update other processes to this old value\r\n std::shared_ptr winFocus = 0;\r\n\r\n for (size_t i = 0; i < all_messages.size(); i++)\r\n {\r\n std::shared_ptr data = all_messages[i];\r\n\r\n if (data->size() < 4)\r\n {\r\n DEBUG(\"Bad data received to syncmanager: too short\");\r\n continue;\r\n }\r\n\r\n int idOfDataEntry = InterprocessCommunicator::CharTo32bitNum(data->data());\r\n\r\n switch (idOfDataEntry)\r\n {\r\n case (int)DataKey::WindowFocus:\r\n {\r\n \/\/This message has window focus information to sync with\r\n winFocus = data;\r\n break;\r\n }\r\n default:\r\n {\r\n DEBUG(\"Unknown data key received: \" + idOfDataEntry);\r\n break;\r\n }\r\n }\r\n }\r\n\r\n\r\n if (winFocus && win->sync_focus_on())\r\n {\r\n \/\/We received 1+ signals to change our window focus\r\n\r\n unsigned int offset = 4;\/\/we have already read 4 bytes, above\r\n \/\/Read three single point floats \r\n if (winFocus->size() != (int)(offset + 12)) \/\/cast to int to avoid compiler warning\r\n {\r\n DEBUG(\"Bad data received to sync manager: wrong length (window focus)\");\r\n }\r\n else\r\n {\r\n Eigen::Vector3f vec = FromQByteArray(*winFocus, offset);\r\n\r\n \/\/Check if already set to this value - Basic OOP: don't trust window to check things are changed before emitting a signal that the value has changed!\r\n Eigen::Vector3f win_vec = win->focus();\r\n if (win_vec[0] != vec[0] || win_vec[1] != vec[1] || win_vec[2] != vec[2])\r\n {\r\n \/\/Send to window\r\n win->set_focus(vec);\r\n }\r\n }\r\n }\r\n\r\n\r\n \/\/Redraw the window. \r\n win->updateGL();\r\n }\r\n\r\n \/**\r\n * Serialises a Vector3f as a QByteArray\r\n *\/\r\n QByteArray SyncManager::ToQByteArray(Eigen::Vector3f data)\r\n {\r\n char a[12];\r\n memcpy(a, &data, 12);\r\n QByteArray q;\r\n q.insert(0, a, 12); \/\/don't use the constructor; it ignores any data after hitting a \\0\r\n return q;\r\n }\r\n \/**\r\n * Deserialises a Vector3f from a QByteArray\r\n *\/\r\n Eigen::Vector3f SyncManager::FromQByteArray(QByteArray data, unsigned int offset)\r\n {\r\n Eigen::Vector3f read;\r\n memcpy(&read, data.data() + offset, 12);\r\n return read;\r\n }\r\n\r\n }\r\n }\r\n }\r\n}Fixed compiler warning appearing on OSX. Tested on Ubuntu 12.04 (Virtual Box) + Qt 4.8, Windows 10 + Qt 5.9.2, and OSX Darwin + Qt 5.10.1\/*\n* Copyright (c) 2008-2018 the MRtrix3 contributors.\n*\n* This Source Code Form is subject to the terms of the Mozilla Public\n* License, v. 2.0. If a copy of the MPL was not distributed with this\n* file, you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/\n*\n* MRtrix3 is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty\n* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n*\n* For more details, see http:\/\/www.mrtrix.org\/\n*\/\r\n#include \"gui\/mrview\/sync\/syncmanager.h\"\r\n#include \"gui\/mrview\/window.h\"\r\n#include \r\n#include \r\n#include \/\/shared_ptr\r\n#include \"gui\/mrview\/sync\/enums.h\"\r\n\r\nnamespace MR\r\n{\r\n namespace GUI\r\n {\r\n namespace MRView\r\n {\r\n namespace Sync\r\n {\r\n SyncManager::SyncManager() : QObject(0)\r\n {\r\n try\r\n {\r\n ips = new InterprocessCommunicator();\/\/will throw exception if it fails to set up a server\r\n connect(ips, SIGNAL(SyncDataReceived(std::vector>)), this, SLOT(OnIPSDataReceived(std::vector>)));\r\n }\r\n catch (...)\r\n {\r\n ips = 0;\r\n WARN(\"Sync set up failed.\");\r\n }\r\n }\r\n\r\n \/**\r\n * Returns true if this is in a state which is not appropriate to connect a window\r\n *\/\r\n bool SyncManager::GetInErrorState()\r\n {\r\n return ips == 0;\r\n }\r\n\r\n \/**\r\n * Sets the window to connect to. Code currently assumes this only occurs once. Also check GetInErrorState() before calling\r\n *\/\r\n void SyncManager::SetWindow(MR::GUI::MRView::Window* wind)\r\n {\r\n if (GetInErrorState())\r\n {\r\n throw Exception(\"Attempt to set window while in an error state\");\r\n }\r\n win = wind;\r\n connect(win, SIGNAL(focusChanged()), this, SLOT(OnWindowFocusChanged()));\r\n }\r\n\r\n \/**\r\n * Receives a signal from window that the focus has changed\r\n *\/\r\n void SyncManager::OnWindowFocusChanged()\r\n {\r\n if (win->sync_focus_on())\r\n {\r\n Eigen::Vector3f foc = win->focus();\r\n SendData(DataKey::WindowFocus, ToQByteArray(foc));\r\n }\r\n }\r\n\r\n \/**\r\n * Sends a signal to other processes to sync to a given key\/value\r\n *\/\r\n bool SyncManager::SendData(DataKey code, QByteArray dat)\r\n {\r\n QByteArray data;\r\n char codeAsChar[4];\r\n InterprocessCommunicator::Int32ToChar(codeAsChar, (int)code);\r\n data.insert(0, codeAsChar, 4);\r\n data.insert(4, dat, dat.size());\r\n\r\n return ips->SendData(data);\r\n }\r\n\r\n \/**\r\n * Receives a signal from another process that a value to sync has changed\r\n *\/\r\n void SyncManager::OnIPSDataReceived(std::vector> all_messages)\r\n {\r\n \/\/WARNING This code assumes that the order of syncing operations does not matter\r\n\r\n \/\/We have a list of messages found\r\n \/\/Categorise these. Only keep the last value sent for each message type, or we will change to an old value and then update other processes to this old value\r\n std::shared_ptr winFocus = 0;\r\n\r\n for (size_t i = 0; i < all_messages.size(); i++)\r\n {\r\n std::shared_ptr data = all_messages[i];\r\n\r\n if (data->size() < 4)\r\n {\r\n DEBUG(\"Bad data received to syncmanager: too short\");\r\n continue;\r\n }\r\n\r\n int idOfDataEntry = InterprocessCommunicator::CharTo32bitNum(data->data());\r\n\r\n switch (idOfDataEntry)\r\n {\r\n case (int)DataKey::WindowFocus:\r\n {\r\n \/\/This message has window focus information to sync with\r\n winFocus = data;\r\n break;\r\n }\r\n default:\r\n {\r\n DEBUG(\"Unknown data key received: \" + std::to_string(idOfDataEntry));\r\n break;\r\n }\r\n }\r\n }\r\n\r\n\r\n if (winFocus && win->sync_focus_on())\r\n {\r\n \/\/We received 1+ signals to change our window focus\r\n\r\n unsigned int offset = 4;\/\/we have already read 4 bytes, above\r\n \/\/Read three single point floats \r\n if (winFocus->size() != (int)(offset + 12)) \/\/cast to int to avoid compiler warning\r\n {\r\n DEBUG(\"Bad data received to sync manager: wrong length (window focus)\");\r\n }\r\n else\r\n {\r\n Eigen::Vector3f vec = FromQByteArray(*winFocus, offset);\r\n\r\n \/\/Check if already set to this value - Basic OOP: don't trust window to check things are changed before emitting a signal that the value has changed!\r\n Eigen::Vector3f win_vec = win->focus();\r\n if (win_vec[0] != vec[0] || win_vec[1] != vec[1] || win_vec[2] != vec[2])\r\n {\r\n \/\/Send to window\r\n win->set_focus(vec);\r\n }\r\n }\r\n }\r\n\r\n\r\n \/\/Redraw the window. \r\n win->updateGL();\r\n }\r\n\r\n \/**\r\n * Serialises a Vector3f as a QByteArray\r\n *\/\r\n QByteArray SyncManager::ToQByteArray(Eigen::Vector3f data)\r\n {\r\n char a[12];\r\n memcpy(a, &data, 12);\r\n QByteArray q;\r\n q.insert(0, a, 12); \/\/don't use the constructor; it ignores any data after hitting a \\0\r\n return q;\r\n }\r\n \/**\r\n * Deserialises a Vector3f from a QByteArray\r\n *\/\r\n Eigen::Vector3f SyncManager::FromQByteArray(QByteArray data, unsigned int offset)\r\n {\r\n Eigen::Vector3f read;\r\n memcpy(&read, data.data() + offset, 12);\r\n return read;\r\n }\r\n\r\n }\r\n }\r\n }\r\n}<|endoftext|>"} {"text":"\n#include \/\/ Чтобы определить NULL\n\n\/\/\/\/\/\/\/\/\/ Включения основного модуля module.h\n#include \"Module.h\"\n#include \"Function_module.h\"\n\n#include \n#include \n#include \/\/ для Рандомайзера \n\n\nusing namespace std;\n\n\n\/\/ Опишу функцию вне класса чтобы можно было применять cout\nFunctionResult* MathFunctionModule::executeFunction(regval functionId, regval *args){\n\tcout << \"Func executed\" << endl;\n\tif (!functionId) {\n\t\treturn NULL;\n\t}\n\n\t\/\/ эта конструкция чтобы создать заранее объект указатель на который будем возвращать\n\tchar ch4 = '1'; \/\/ имя надо будет поменять или просто что-то поменять. Но пока символ оставим в покое и буем работать с result.\n\trez = new FunctionResult(ch4);\n\n\t\/\/ Уже не тестовое задание пробуем описать\n\tswitch (functionId) {\n\t\t\/\/первая функция pow - квадрат. 1-й аргумент возводимое, второй - степень.\n\t\tcase 1:\n\t\t{\n\t\t\t\/\/C приведением типов\n\t\t\tdouble arg1,arg2,resOfPow;\n\t\t\targ1=*args;\n\t\t\targ2=*(args+1);\n\t\t\tresOfPow=pow(arg1,arg2);\n\t\t\trez->result = (int) resOfPow;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 2: \/\/ ABS модуль числа\n\t\t{\n\t\t\/*C приведением типов*\/ \n\t\t\tint resOfabs;\n\t\t\tresOfabs = abs(*args);\n\t\t\trez->result = resOfabs;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 3: \/\/ FMOD Остаток от деления\n\t\t{\n\t\t\tint resOfmod;\n\t\t\tresOfmod = (int) fmod(*args,*(args +1));\n\t\t\trez->result = resOfmod;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 4: \/\/ DIV Целочисленное деление\n\t\t\tint resOfdiv;\n\t\t\tresOfdiv = ( *args - (int)fmod(*args, *(args + 1)) ) \/ (*(args+1));\n\t\t\trez->result = resOfdiv;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\n\t\tcase 5: \/\/ Корень 2-й степени\n\t\t{\n\t\t\tint resOfsqrt;\n\t\t\tresOfsqrt = (int) sqrt(*args);\n\t\t\trez->result = resOfsqrt;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 6: \/\/ Рандомное целое число\n\t\t{\n\t\t\tint resOfrand;\n\t\t\tresOfrand = rand()%(*args) + (*(args+1)) ;\n\t\t\trez->result = resOfrand;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 7: \/\/ Синус\n\t\t{\n\t\t\tint resOfsin;\n\t\t\tresOfsin = (int) (1000 * sin(*args)) ;\n\t\t\trez->result = resOfsin;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 8: \/\/ Косинус\n\t\t{\n\t\t\tint resOfcos;\n\t\t\tresOfcos = (int)(1000 * cos(*args));\n\t\t\trez->result = resOfcos;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 9: \/\/ Тангенс\n\t\t{\n\t\t\tint resOftan;\n\t\t\tresOftan = (int)(1000 * tan(*args));\n\t\t\trez->result = resOftan;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 10: \/\/ АркСинус\n\t\t{\n\t\t\tint resOfasin;\n\t\t\tresOfasin = (int)(1000 * asin(*args));\n\t\t\trez->result = resOfasin;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 11: \/\/ АркКосинус\n\t\t{\n\t\t\tint resOfacos;\n\t\t\tresOfacos = (int)(1000 * acos(*args));\n\t\t\trez->result = resOfacos;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 12: \/\/ АркТангенс\n\t\t{\n\t\t\tint resOfatan;\n\t\t\tresOfatan = (int)(1000 * atan(*args));\n\t\t\trez->result = resOfatan;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 13: \/\/ Экспонента\n\t\t{\n\t\t\tint resOfexp;\n\t\t\tresOfexp = (int) exp(*args);\n\t\t\trez->result = resOfexp;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 14: \/\/ Логарифм Натуральный\n\t\t{\n\t\t\tint resOflog;\n\t\t\tresOflog = (int)log(*args);\n\t\t\trez->result = resOflog;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 15: \/\/ Десятичный логарифм\n\t\t{\n\t\t\tint resOflog10;\n\t\t\tresOflog10 = (int)log10(*args);\n\t\t\trez->result = resOflog10;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n }; \/\/ Конец switch\n\treturn rez;\n};\n\n\n\n\n\nint main(){\n\tint test;\n\ttest = 1;\n\tcout << test << endl;\n\n\n\tregval *arg1;\n\tregval x;\n\tx = 1;\n\targ1 = &x;\n\n\tregval TwoArgs[] = {2,3};\n\tregval absTestMas[] = { -14 };\n\tregval fmodTestMas[] = { 7, 4 };\n\tregval divTestMas[] = { 9, 4 };\n\tregval randTestMas[] = { 10, 1 };\n\tregval SiCoTanTestMas[] = {1};\n\t\n\tMathFunctionModule newObject;\n\n\tFunctionResult *FRobject;\n\n\t\/\/ проверка возведения в степень\n\tFRobject = newObject.executeFunction(1, TwoArgs); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n \n\n\t\/\/ Проверка получения абсолютной величины\n\tFRobject = newObject.executeFunction(2, absTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n\t\/\/ Проверка остатка от деления\n\tFRobject = newObject.executeFunction(3, fmodTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n\t\/\/ Проверка целочисленного деления на том же массиве\n\tFRobject = newObject.executeFunction(4, divTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\t\n\tcout << \"- - - \" << newObject.executeFunction(4, divTestMas)->result + newObject.executeFunction(4, divTestMas)->result << endl;\n\n\t\/\/ Проверка Установка рандомайзера. не важно что передаем в аргументах\n\tFRobject = newObject.executeFunction(5, divTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n\t\/\/ Проверяем рандомайзер \n\tFRobject = newObject.executeFunction(6, randTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject->result << endl;\n\tFRobject = newObject.executeFunction(6, randTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject->result << endl;\n\t\n\n\treturn 0;\n}\nupdate executeFunctions\n#include \/\/ Чтобы определить NULL\n\n\/\/\/\/\/\/\/\/\/ Включения основного модуля module.h\n#include \"Module.h\"\n#include \"Function_module.h\"\n\n#include \n#include \n#include \/\/ для Рандомайзера \n\n\nusing namespace std;\n\n\n\/\/ Опишу функцию вне класса чтобы можно было применять cout\nFunctionResult* MathFunctionModule::executeFunction(regval functionId, regval *args){\n\tcout << \"Func executed\" << endl;\n\tif (!functionId) {\n\t\treturn NULL;\n\t}\n\n\t\/\/ эта конструкция чтобы создать заранее объект указатель на который будем возвращать\n\tchar ch4 = '1'; \/\/ имя надо будет поменять или просто что-то поменять. Но пока символ оставим в покое и буем работать с result.\n\trez = new FunctionResult(ch4);\n\n\t\/\/ Уже не тестовое задание пробуем описать\n\tswitch (functionId) {\n\t\t\/\/первая функция pow - квадрат. 1-й аргумент возводимое, второй - степень.\n\t\tcase 1: \/\/ Тут вопрос про приведение типов\n\t\t{\n\t\t\t\/\/C приведением типов\n\t\t\tdouble arg1,arg2,resOfPow;\n\t\t\targ1=*args;\n\t\t\targ2=*(args+1);\n\t\t\tresOfPow=pow(arg1,arg2);\n\t\t\trez->result = (int) resOfPow;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 2: \/\/ ABS модуль числа\n\t\t{\n\t\t\/*C приведением типов*\/ \n\t\t\tint resOfabs;\n\t\t\tresOfabs = abs(*args);\n\t\t\trez->result = resOfabs;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 3: \/\/ FMOD Остаток от деления\n\t\t{\n\t\t\tint resOfmod;\n\t\t\tresOfmod = (int) fmod(*args,*(args +1));\n\t\t\trez->result = resOfmod;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 4: \/\/ DIV Целочисленное деление\n\t\t\tint resOfdiv;\n\t\t\tresOfdiv = ( *args - (int)fmod(*args, *(args + 1)) ) \/ (*(args+1));\n\t\t\trez->result = resOfdiv;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\n\t\tcase 5: \/\/ Корень 2-й степени Результат будем выводить умноженным на 1000, потому что растет медленно(меняется медленно)\n\t\t{\n\t\t\tint resOfsqrt;\n\t\t\tresOfsqrt = (int) (1000 * sqrt(*args));\n\t\t\trez->result = resOfsqrt;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 6: \/\/ Рандомное целое число\n\t\t{\n\t\t\tint resOfrand;\n\t\t\tresOfrand = rand()%(*args) + (*(args+1)) ;\n\t\t\trez->result = resOfrand;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 7: \/\/ Синус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах\n\t\t{\n\t\t\tint resOfsin;\n\t\t\tresOfsin = (int) (1000 * sin(*args\/1000)) ;\n\t\t\trez->result = resOfsin;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 8: \/\/ Косинус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах\n\t\t{\n\t\t\tint resOfcos;\n\t\t\tresOfcos = (int)(1000 * cos(*args\/1000));\n\t\t\trez->result = resOfcos;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 9: \/\/ Тангенс Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах\n\t\t{\n\t\t\tint resOftan;\n\t\t\tresOftan = (int)(1000 * tan(*args \/ 1000));\n\t\t\trez->result = resOftan;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 10: \/\/ АркСинус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах\n\t\t{\n\t\t\tint resOfasin;\n\t\t\tresOfasin = (int)(1000 * asin(*args \/ 1000));\n\t\t\trez->result = resOfasin;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 11: \/\/ АркКосинус Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах\n\t\t{\n\t\t\tint resOfacos;\n\t\t\tresOfacos = (int)(1000 * acos(*args \/ 1000));\n\t\t\trez->result = resOfacos;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 12: \/\/ АркТангенс Изменяется быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000 и выводить будем умножив на 1000, потому что быстро меняется в малых пределах\n\t\t{\n\t\t\tint resOfatan;\n\t\t\tresOfatan = (int)(1000 * atan(*args \/ 1000));\n\t\t\trez->result = resOfatan;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 13: \/\/ Экспонента Растет быстро поэтому ввод просим умножить на 1000 а в вычислениях введенное будем делить на 1000\n\t\t{\n\t\t\tint resOfexp;\n\t\t\tresOfexp = (int)exp(*args \/ 1000);\n\t\t\trez->result = resOfexp;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 14: \/\/ Логарифм Натуральный Растет медленно поэтому вывод умножим на 1000\n\t\t{\n\t\t\tint resOflog;\n\t\t\tresOflog = (int)( 1000* log(*args));\n\t\t\trez->result = resOflog;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n\t\tcase 15: \/\/ Десятичный логарифм Растет медленно поэтому вывод умножим на 1000\n\t\t{\n\t\t\tint resOflog10;\n\t\t\tresOflog10 = (int) (1000 * log10(*args));\n\t\t\trez->result = resOflog10;\n\t\t\t\/\/ Все сделали и выходим из свича\n\t\t\tbreak;\n\t\t}\n }; \/\/ Конец switch\n\treturn rez;\n};\n\n\n\n\n\nint main(){\n\tint test;\n\ttest = 1;\n\tcout << test << endl;\n\n\n\tregval *arg1;\n\tregval x;\n\tx = 1;\n\targ1 = &x;\n\n\tregval TwoArgs[] = {2,3};\n\tregval absTestMas[] = { -14 };\n\tregval fmodTestMas[] = { 7, 4 };\n\tregval divTestMas[] = { 9, 4 };\n\tregval randTestMas[] = { 10, 1 };\n\tregval SiCoTanTestMas[] = {1};\n\t\n\tMathFunctionModule newObject;\n\n\tFunctionResult *FRobject;\n\n\t\/\/ проверка возведения в степень\n\tFRobject = newObject.executeFunction(1, TwoArgs); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n \n\n\t\/\/ Проверка получения абсолютной величины\n\tFRobject = newObject.executeFunction(2, absTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n\t\/\/ Проверка остатка от деления\n\tFRobject = newObject.executeFunction(3, fmodTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n\t\/\/ Проверка целочисленного деления на том же массиве\n\tFRobject = newObject.executeFunction(4, divTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\t\n\tcout << \"- - - \" << newObject.executeFunction(4, divTestMas)->result + newObject.executeFunction(4, divTestMas)->result << endl;\n\n\t\/\/ Проверка Установка рандомайзера. не важно что передаем в аргументах\n\tFRobject = newObject.executeFunction(5, divTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject << endl;\n\tcout << FRobject->type << endl;\n\tcout << FRobject->result << endl;\n\n\t\/\/ Проверяем рандомайзер \n\tFRobject = newObject.executeFunction(6, randTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject->result << endl;\n\tFRobject = newObject.executeFunction(6, randTestMas); \/\/ не забываем что этот объект ссылается на свойство newObject. \n\tcout << FRobject->result << endl;\n\t\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n\n#include \"log.h\"\n#include \"common.h\"\n\n#include \"mem_vec_store.h\"\n#include \"bulk_operate.h\"\n#include \"local_vec_store.h\"\n#include \"mem_matrix_store.h\"\n#include \"NUMA_vector.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nmem_vec_store::ptr mem_vec_store::create(size_t length, int num_nodes,\n\t\tconst scalar_type &type)\n{\n\tif (num_nodes < 0)\n\t\treturn smp_vec_store::create(length, type);\n\telse\n\t\treturn NUMA_vec_store::create(length, num_nodes, type);\n}\n\nbool mem_vec_store::copy_from(const char *buf, size_t num_bytes)\n{\n\tif (get_raw_arr() == NULL)\n\t\treturn false;\n\n\tif (num_bytes % get_entry_size() != 0\n\t\t\t|| num_bytes \/ get_entry_size() != get_length())\n\t\treturn false;\n\tmemcpy(get_raw_arr(), buf, num_bytes);\n\treturn true;\n}\n\nsmp_vec_store::smp_vec_store(size_t length, const scalar_type &type): mem_vec_store(\n\t\tlength, type), data(length * type.get_size())\n{\n\tthis->arr = data.get_raw();\n}\n\nsmp_vec_store::smp_vec_store(const detail::raw_data_array &data,\n\t\tconst scalar_type &type): mem_vec_store(\n\t\t\tdata.get_num_bytes() \/ type.get_size(), type)\n{\n\tthis->data = data;\n\tthis->arr = this->data.get_raw();\n}\n\nsmp_vec_store::ptr smp_vec_store::create(const detail::raw_data_array &data,\n\t\t\tconst scalar_type &type)\n{\n\tif (data.get_num_bytes() % type.get_size() != 0) {\n\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t<< \"The data array has a wrong number of bytes\";\n\t\treturn smp_vec_store::ptr();\n\t}\n\treturn ptr(new smp_vec_store(data, type));\n}\n\nsmp_vec_store::ptr smp_vec_store::get(const smp_vec_store &idxs) const\n{\n\tif (idxs.get_type() != get_scalar_type()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"The index vector isn't of the off_t type\";\n\t\treturn smp_vec_store::ptr();\n\t}\n\n\tsmp_vec_store::ptr ret = smp_vec_store::create(idxs.get_length(), get_type());\n\tint num_threads = get_num_omp_threads();\n\tsize_t part_len = ceil(((double) idxs.get_length()) \/ num_threads);\n#pragma omp parallel for\n\tfor (int k = 0; k < num_threads; k++) {\n\t\tsize_t start = k * part_len;\n\t\tsize_t end = std::min((k + 1) * part_len, idxs.get_length());\n\t\tsize_t local_len = end >= start ? end - start : 0;\n\t\tif (local_len == 0)\n\t\t\tcontinue;\n\n\t\tstd::vector src_locs(local_len);\n\t\tfor (size_t i = 0; i < local_len; i++) {\n\t\t\toff_t idx = idxs.get(i + start);\n\t\t\t\/\/ Check if it's out of the range.\n\t\t\tif (idx < 0 && (size_t) idx >= this->get_length()) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t\t<< boost::format(\"%1% is out of range\") % idx;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsrc_locs[i] = this->get(idx);\n\t\t}\n\t\tget_type().get_sg().gather(src_locs,\n\t\t\t\tret->arr + start * ret->get_entry_size());\n\t}\n\treturn ret;\n}\n\nbool smp_vec_store::append(std::vector::const_iterator vec_it,\n\t\tstd::vector::const_iterator vec_end)\n{\n\t\/\/ Get the total size of the result vector.\n\tsize_t tot_res_size = this->get_length();\n\tfor (auto it = vec_it; it != vec_end; it++) {\n\t\ttot_res_size += (*it)->get_length();\n\t\tif (!(*it)->is_in_mem()) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"Not support appending an ext-mem vector to an in-mem vector\";\n\t\t\treturn false;\n\t\t}\n\t\tif (get_type() != (*it)->get_type()) {\n\t\t\tBOOST_LOG_TRIVIAL(error) << \"The two vectors don't have the same type\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Merge all results to a single vector.\n\toff_t loc = this->get_length() + get_sub_start();\n\tthis->resize(tot_res_size);\n\tfor (auto it = vec_it; it != vec_end; it++) {\n\t\tassert(loc + (*it)->get_length() <= this->get_length());\n\t\tassert((*it)->is_in_mem());\n\t\tconst mem_vec_store &mem_vec = static_cast(**it);\n\t\tbool ret = data.set_sub_arr(loc * get_entry_size(),\n\t\t\t\tmem_vec.get_raw_arr(), mem_vec.get_length() * get_entry_size());\n\t\tassert(ret);\n\t\tloc += (*it)->get_length();\n\t}\n\treturn true;\n}\n\nbool smp_vec_store::append(const vec_store &vec)\n{\n\tif (!vec.is_in_mem()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"The input vector isn't in memory\";\n\t\treturn false;\n\t}\n\tif (get_type() != vec.get_type()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"The two vectors don't have the same type\";\n\t\treturn false;\n\t}\n\t\/\/ TODO We might want to over expand a little, so we don't need to copy\n\t\/\/ the memory again and again.\n\t\/\/ TODO if this is a sub_vector, what should we do?\n\tassert(get_sub_start() == 0);\n\toff_t loc = this->get_length() + get_sub_start();\n\tthis->resize(vec.get_length() + get_length());\n\tassert(loc + vec.get_length() <= this->get_length());\n\tconst mem_vec_store &mem_vec = static_cast(vec);\n\tassert(mem_vec.get_raw_arr());\n\treturn data.set_sub_arr(loc * get_entry_size(), mem_vec.get_raw_arr(),\n\t\t\tmem_vec.get_length() * get_entry_size());\n}\n\nbool smp_vec_store::resize(size_t new_length)\n{\n\tif (new_length == get_length())\n\t\treturn true;\n\n\tsize_t tot_len = data.get_num_bytes() \/ get_type().get_size();\n\t\/\/ We don't want to reallocate memory when shrinking the vector.\n\tif (new_length < tot_len) {\n\t\treturn vec_store::resize(new_length);\n\t}\n\n\t\/\/ Keep the old information of the vector.\n\tdetail::raw_data_array old_data = data;\n\tchar *old_arr = arr;\n\tsize_t old_length = get_length();\n\n\tsize_t real_length = old_length;\n\tif (real_length == 0)\n\t\treal_length = 1;\n\tfor (; real_length < new_length; real_length *= 2);\n\tthis->data = detail::raw_data_array(real_length * get_type().get_size());\n\tthis->arr = this->data.get_raw();\n\tmemcpy(arr, old_arr, std::min(old_length, new_length) * get_entry_size());\n\treturn vec_store::resize(new_length);\n}\n\nbool smp_vec_store::expose_sub_vec(off_t start, size_t length)\n{\n\tsize_t tot_len = data.get_num_bytes() \/ get_type().get_size();\n\tif (start + length > tot_len) {\n\t\texit(1);\n\t\tBOOST_LOG_TRIVIAL(error) << \"expose_sub_vec: out of range\";\n\t\treturn false;\n\t}\n\n\tresize(length);\n\tarr = data.get_raw() + start * get_entry_size();\n\treturn true;\n}\n\nvec_store::ptr smp_vec_store::deep_copy() const\n{\n\tassert(get_raw_arr() == data.get_raw());\n\tdetail::raw_data_array data = this->data.deep_copy();\n\treturn smp_vec_store::create(data, get_type());\n}\n\nvec_store::ptr smp_vec_store::sort_with_index()\n{\n\tsmp_vec_store::ptr indexes = smp_vec_store::create(get_length(),\n\t\t\tget_scalar_type());\n\tget_type().get_sorter().sort_with_index(arr,\n\t\t\t(off_t *) indexes->arr, get_length(), false);\n\treturn indexes;\n}\n\nvoid smp_vec_store::set_data(const set_vec_operate &op)\n{\n\t\/\/ I assume this is column-wise matrix.\n\t\/\/ TODO parallel.\n\top.set(arr, get_length(), 0);\n}\n\nvoid smp_vec_store::set(const std::vector &locs)\n{\n\tassert(locs.size() <= get_length());\n\tget_type().get_sg().gather(locs, arr);\n}\n\nlocal_vec_store::ptr smp_vec_store::get_portion(off_t loc, size_t size)\n{\n\tif (loc + size > get_length()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"the portion is out of boundary\";\n\t\treturn local_vec_store::ptr();\n\t}\n\n\treturn local_vec_store::ptr(new local_ref_vec_store(get(loc),\n\t\t\t\tloc, size, get_type(), -1));\n}\n\nlocal_vec_store::const_ptr smp_vec_store::get_portion(off_t loc,\n\t\t\tsize_t size) const\n{\n\tif (loc + size > get_length()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"the portion is out of boundary\";\n\t\treturn local_vec_store::ptr();\n\t}\n\n\treturn local_vec_store::ptr(new local_cref_vec_store(get(loc),\n\t\t\t\tloc, size, get_type(), -1));\n}\n\nsize_t smp_vec_store::get_portion_size() const\n{\n\treturn 64 * 1024;\n}\n\nmatrix_store::const_ptr smp_vec_store::conv2mat(size_t nrow, size_t ncol,\n\t\t\tbool byrow) const\n{\n\tassert(arr == data.get_raw());\n\tif (get_length() < nrow * ncol) {\n\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t<< \"The vector doesn't have enough elements\";\n\t\treturn matrix_store::ptr();\n\t}\n\tif (byrow)\n\t\treturn mem_row_matrix_store::create(data, nrow, ncol, get_type());\n\telse\n\t\treturn mem_col_matrix_store::create(data, nrow, ncol, get_type());\n}\n\ntemplate<>\nvec_store::ptr create_vec_store(double start, double end,\n\t\tdouble stride)\n{\n\t\/\/ The result of division may generate a real number slightly smaller than\n\t\/\/ what we want because of the representation precision in the machine.\n\t\/\/ When we convert the real number to an integer, we may find the number\n\t\/\/ is smaller than exepcted. We need to add a very small number to\n\t\/\/ the real number to correct the problem.\n\t\/\/ TODO is it the right way to correct the problem?\n\tlong n = (end - start) \/ stride + 1e-9;\n\tif (n < 0) {\n\t\tBOOST_LOG_TRIVIAL(error) <<\"wrong sign in 'by' argument\";\n\t\treturn vec_store::ptr();\n\t}\n\t\/\/ We need to count the start element.\n\tn++;\n\n\tdetail::smp_vec_store::ptr v = detail::smp_vec_store::create(n,\n\t\t\tget_scalar_type());\n\tv->set_data(seq_set_vec_operate(n, start, stride));\n\treturn v;\n}\n\n}\n\n}\n[Matrix]: fix a bug in deep copy a mem vectore store.\/*\n * Copyright 2015 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n\n#include \"log.h\"\n#include \"common.h\"\n\n#include \"mem_vec_store.h\"\n#include \"bulk_operate.h\"\n#include \"local_vec_store.h\"\n#include \"mem_matrix_store.h\"\n#include \"NUMA_vector.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\nmem_vec_store::ptr mem_vec_store::create(size_t length, int num_nodes,\n\t\tconst scalar_type &type)\n{\n\tif (num_nodes < 0)\n\t\treturn smp_vec_store::create(length, type);\n\telse\n\t\treturn NUMA_vec_store::create(length, num_nodes, type);\n}\n\nbool mem_vec_store::copy_from(const char *buf, size_t num_bytes)\n{\n\tif (get_raw_arr() == NULL)\n\t\treturn false;\n\n\tif (num_bytes % get_entry_size() != 0\n\t\t\t|| num_bytes \/ get_entry_size() != get_length())\n\t\treturn false;\n\tmemcpy(get_raw_arr(), buf, num_bytes);\n\treturn true;\n}\n\nsmp_vec_store::smp_vec_store(size_t length, const scalar_type &type): mem_vec_store(\n\t\tlength, type), data(length * type.get_size())\n{\n\tthis->arr = data.get_raw();\n}\n\nsmp_vec_store::smp_vec_store(const detail::raw_data_array &data,\n\t\tconst scalar_type &type): mem_vec_store(\n\t\t\tdata.get_num_bytes() \/ type.get_size(), type)\n{\n\tassert(data.get_num_bytes() % type.get_size() == 0);\n\tthis->data = data;\n\tthis->arr = this->data.get_raw();\n}\n\nsmp_vec_store::ptr smp_vec_store::create(const detail::raw_data_array &data,\n\t\t\tconst scalar_type &type)\n{\n\tif (data.get_num_bytes() % type.get_size() != 0) {\n\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t<< \"The data array has a wrong number of bytes\";\n\t\treturn smp_vec_store::ptr();\n\t}\n\treturn ptr(new smp_vec_store(data, type));\n}\n\nsmp_vec_store::ptr smp_vec_store::get(const smp_vec_store &idxs) const\n{\n\tif (idxs.get_type() != get_scalar_type()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"The index vector isn't of the off_t type\";\n\t\treturn smp_vec_store::ptr();\n\t}\n\n\tsmp_vec_store::ptr ret = smp_vec_store::create(idxs.get_length(), get_type());\n\tint num_threads = get_num_omp_threads();\n\tsize_t part_len = ceil(((double) idxs.get_length()) \/ num_threads);\n#pragma omp parallel for\n\tfor (int k = 0; k < num_threads; k++) {\n\t\tsize_t start = k * part_len;\n\t\tsize_t end = std::min((k + 1) * part_len, idxs.get_length());\n\t\tsize_t local_len = end >= start ? end - start : 0;\n\t\tif (local_len == 0)\n\t\t\tcontinue;\n\n\t\tstd::vector src_locs(local_len);\n\t\tfor (size_t i = 0; i < local_len; i++) {\n\t\t\toff_t idx = idxs.get(i + start);\n\t\t\t\/\/ Check if it's out of the range.\n\t\t\tif (idx < 0 && (size_t) idx >= this->get_length()) {\n\t\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t\t<< boost::format(\"%1% is out of range\") % idx;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tsrc_locs[i] = this->get(idx);\n\t\t}\n\t\tget_type().get_sg().gather(src_locs,\n\t\t\t\tret->arr + start * ret->get_entry_size());\n\t}\n\treturn ret;\n}\n\nbool smp_vec_store::append(std::vector::const_iterator vec_it,\n\t\tstd::vector::const_iterator vec_end)\n{\n\t\/\/ Get the total size of the result vector.\n\tsize_t tot_res_size = this->get_length();\n\tfor (auto it = vec_it; it != vec_end; it++) {\n\t\ttot_res_size += (*it)->get_length();\n\t\tif (!(*it)->is_in_mem()) {\n\t\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t\t<< \"Not support appending an ext-mem vector to an in-mem vector\";\n\t\t\treturn false;\n\t\t}\n\t\tif (get_type() != (*it)->get_type()) {\n\t\t\tBOOST_LOG_TRIVIAL(error) << \"The two vectors don't have the same type\";\n\t\t\treturn false;\n\t\t}\n\t}\n\n\t\/\/ Merge all results to a single vector.\n\toff_t loc = this->get_length() + get_sub_start();\n\tthis->resize(tot_res_size);\n\tfor (auto it = vec_it; it != vec_end; it++) {\n\t\tassert(loc + (*it)->get_length() <= this->get_length());\n\t\tassert((*it)->is_in_mem());\n\t\tconst mem_vec_store &mem_vec = static_cast(**it);\n\t\tbool ret = data.set_sub_arr(loc * get_entry_size(),\n\t\t\t\tmem_vec.get_raw_arr(), mem_vec.get_length() * get_entry_size());\n\t\tassert(ret);\n\t\tloc += (*it)->get_length();\n\t}\n\treturn true;\n}\n\nbool smp_vec_store::append(const vec_store &vec)\n{\n\tif (!vec.is_in_mem()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"The input vector isn't in memory\";\n\t\treturn false;\n\t}\n\tif (get_type() != vec.get_type()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"The two vectors don't have the same type\";\n\t\treturn false;\n\t}\n\t\/\/ TODO We might want to over expand a little, so we don't need to copy\n\t\/\/ the memory again and again.\n\t\/\/ TODO if this is a sub_vector, what should we do?\n\tassert(get_sub_start() == 0);\n\toff_t loc = this->get_length() + get_sub_start();\n\tthis->resize(vec.get_length() + get_length());\n\tassert(loc + vec.get_length() <= this->get_length());\n\tconst mem_vec_store &mem_vec = static_cast(vec);\n\tassert(mem_vec.get_raw_arr());\n\treturn data.set_sub_arr(loc * get_entry_size(), mem_vec.get_raw_arr(),\n\t\t\tmem_vec.get_length() * get_entry_size());\n}\n\nbool smp_vec_store::resize(size_t new_length)\n{\n\tif (new_length == get_length())\n\t\treturn true;\n\n\tsize_t tot_len = data.get_num_bytes() \/ get_type().get_size();\n\t\/\/ We don't want to reallocate memory when shrinking the vector.\n\tif (new_length < tot_len) {\n\t\treturn vec_store::resize(new_length);\n\t}\n\n\t\/\/ Keep the old information of the vector.\n\tdetail::raw_data_array old_data = data;\n\tchar *old_arr = arr;\n\tsize_t old_length = get_length();\n\n\tsize_t real_length = old_length;\n\tif (real_length == 0)\n\t\treal_length = 1;\n\tfor (; real_length < new_length; real_length *= 2);\n\tthis->data = detail::raw_data_array(real_length * get_type().get_size());\n\tthis->arr = this->data.get_raw();\n\tmemcpy(arr, old_arr, std::min(old_length, new_length) * get_entry_size());\n\treturn vec_store::resize(new_length);\n}\n\nbool smp_vec_store::expose_sub_vec(off_t start, size_t length)\n{\n\tsize_t tot_len = data.get_num_bytes() \/ get_type().get_size();\n\tif (start + length > tot_len) {\n\t\texit(1);\n\t\tBOOST_LOG_TRIVIAL(error) << \"expose_sub_vec: out of range\";\n\t\treturn false;\n\t}\n\n\tresize(length);\n\tarr = data.get_raw() + start * get_entry_size();\n\treturn true;\n}\n\nvec_store::ptr smp_vec_store::deep_copy() const\n{\n\tassert(get_raw_arr() == data.get_raw());\n\tdetail::raw_data_array copy = this->data.deep_copy();\n\tsmp_vec_store::ptr ret = smp_vec_store::create(copy, get_type());\n\tret->resize(this->get_length());\n\treturn ret;\n}\n\nvec_store::ptr smp_vec_store::sort_with_index()\n{\n\tsmp_vec_store::ptr indexes = smp_vec_store::create(get_length(),\n\t\t\tget_scalar_type());\n\tget_type().get_sorter().sort_with_index(arr,\n\t\t\t(off_t *) indexes->arr, get_length(), false);\n\treturn indexes;\n}\n\nvoid smp_vec_store::set_data(const set_vec_operate &op)\n{\n\t\/\/ I assume this is column-wise matrix.\n\t\/\/ TODO parallel.\n\top.set(arr, get_length(), 0);\n}\n\nvoid smp_vec_store::set(const std::vector &locs)\n{\n\tassert(locs.size() <= get_length());\n\tget_type().get_sg().gather(locs, arr);\n}\n\nlocal_vec_store::ptr smp_vec_store::get_portion(off_t loc, size_t size)\n{\n\tif (loc + size > get_length()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"the portion is out of boundary\";\n\t\treturn local_vec_store::ptr();\n\t}\n\n\treturn local_vec_store::ptr(new local_ref_vec_store(get(loc),\n\t\t\t\tloc, size, get_type(), -1));\n}\n\nlocal_vec_store::const_ptr smp_vec_store::get_portion(off_t loc,\n\t\t\tsize_t size) const\n{\n\tif (loc + size > get_length()) {\n\t\tBOOST_LOG_TRIVIAL(error) << \"the portion is out of boundary\";\n\t\treturn local_vec_store::ptr();\n\t}\n\n\treturn local_vec_store::ptr(new local_cref_vec_store(get(loc),\n\t\t\t\tloc, size, get_type(), -1));\n}\n\nsize_t smp_vec_store::get_portion_size() const\n{\n\treturn 64 * 1024;\n}\n\nmatrix_store::const_ptr smp_vec_store::conv2mat(size_t nrow, size_t ncol,\n\t\t\tbool byrow) const\n{\n\tassert(arr == data.get_raw());\n\tif (get_length() < nrow * ncol) {\n\t\tBOOST_LOG_TRIVIAL(error)\n\t\t\t<< \"The vector doesn't have enough elements\";\n\t\treturn matrix_store::ptr();\n\t}\n\tif (byrow)\n\t\treturn mem_row_matrix_store::create(data, nrow, ncol, get_type());\n\telse\n\t\treturn mem_col_matrix_store::create(data, nrow, ncol, get_type());\n}\n\ntemplate<>\nvec_store::ptr create_vec_store(double start, double end,\n\t\tdouble stride)\n{\n\t\/\/ The result of division may generate a real number slightly smaller than\n\t\/\/ what we want because of the representation precision in the machine.\n\t\/\/ When we convert the real number to an integer, we may find the number\n\t\/\/ is smaller than exepcted. We need to add a very small number to\n\t\/\/ the real number to correct the problem.\n\t\/\/ TODO is it the right way to correct the problem?\n\tlong n = (end - start) \/ stride + 1e-9;\n\tif (n < 0) {\n\t\tBOOST_LOG_TRIVIAL(error) <<\"wrong sign in 'by' argument\";\n\t\treturn vec_store::ptr();\n\t}\n\t\/\/ We need to count the start element.\n\tn++;\n\n\tdetail::smp_vec_store::ptr v = detail::smp_vec_store::create(n,\n\t\t\tget_scalar_type());\n\tv->set_data(seq_set_vec_operate(n, start, stride));\n\treturn v;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: shapetransitionfactory.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 08:41:10 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifndef BOOST_BIND_HPP_INCLUDED\n#include \n#endif\n\n\nusing namespace ::com::sun::star;\n\nnamespace presentation {\nnamespace internal {\n\n\/***************************************************\n *** ***\n *** Shape Transition Effects ***\n *** ***\n ***************************************************\/\n\nnamespace {\n\nclass ClippingAnimation : public NumberAnimation\n{\npublic:\n ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn );\n\n ~ClippingAnimation();\n\n \/\/ Animation interface\n \/\/ -------------------\n virtual void start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer );\n virtual void end();\n\n \/\/ NumberAnimation interface\n \/\/ -----------------------\n virtual bool operator()( double nValue );\n virtual double getUnderlyingValue() const;\n\nprivate:\n void end_();\n\n AnimatableShapeSharedPtr mpShape;\n ShapeAttributeLayerSharedPtr mpAttrLayer;\n LayerManagerSharedPtr mpLayerManager;\n ClippingFunctor maClippingFunctor;\n bool mbSpriteActive;\n};\n\nClippingAnimation::ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn ) :\n mpShape(),\n mpAttrLayer(),\n mpLayerManager( rLayerManager ),\n maClippingFunctor( rPolygon,\n rTransitionInfo,\n bDirectionForward,\n bModeIn ),\n mbSpriteActive(false)\n{\n ENSURE_AND_THROW(\n rLayerManager.get(),\n \"ClippingAnimation::ClippingAnimation(): Invalid LayerManager\" );\n}\n\nClippingAnimation::~ClippingAnimation()\n{\n end_();\n}\n\nvoid ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer )\n{\n OSL_ENSURE( !mpShape.get(),\n \"ClippingAnimation::start(): Shape already set\" );\n OSL_ENSURE( !mpAttrLayer.get(),\n \"ClippingAnimation::start(): Attribute layer already set\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n ENSURE_AND_THROW( rShape.get(),\n \"ClippingAnimation::start(): Invalid shape\" );\n ENSURE_AND_THROW( rAttrLayer.get(),\n \"ClippingAnimation::start(): Invalid attribute layer\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n if( !mbSpriteActive )\n {\n mpLayerManager->enterAnimationMode( mpShape );\n mbSpriteActive = true;\n }\n}\n\nvoid ClippingAnimation::end()\n{\n end_();\n}\n\nvoid ClippingAnimation::end_()\n{\n if( mbSpriteActive )\n {\n mbSpriteActive = false;\n mpLayerManager->leaveAnimationMode( mpShape );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n }\n}\n\nbool ClippingAnimation::operator()( double nValue )\n{\n ENSURE_AND_RETURN(\n mpAttrLayer.get() && mpShape.get(),\n \"ClippingAnimation::operator(): Invalid ShapeAttributeLayer\" );\n\n \/\/ set new clip\n mpAttrLayer->setClip( maClippingFunctor( nValue,\n mpShape->getDOMBounds().getRange() ) );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n\n return true;\n}\n\ndouble ClippingAnimation::getUnderlyingValue() const\n{\n ENSURE_AND_THROW(\n mpAttrLayer.get(),\n \"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer\" );\n\n return 0.0; \/\/ though this should be used in concert with\n \/\/ ActivitiesFactory::createSimpleActivity, better\n \/\/ explicitely name our start value.\n \/\/ Permissible range for operator() above is [0,1]\n}\n\n} \/\/ anon namespace\n\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n uno::Reference< animations::XTransitionFilter > const& xTransition )\n{\n return createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n xTransition->getTransition(),\n xTransition->getSubtype() );\n}\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XTransitionFilter > const& xTransition,\n sal_Int16 nType,\n sal_Int16 nSubType )\n{\n ENSURE_AND_THROW(\n xTransition.is(),\n \"TransitionFactory::createShapeTransition(): Invalid XTransition\" );\n\n const TransitionInfo* pTransitionInfo(\n getTransitionInfo( nType, nSubType ) );\n\n AnimationActivitySharedPtr pGeneratedActivity;\n if( pTransitionInfo != NULL )\n {\n switch( pTransitionInfo->meTransitionClass )\n {\n default:\n case TransitionInfo::TRANSITION_INVALID:\n OSL_ENSURE( false,\n \"TransitionFactory::createShapeTransition(): Invalid transition type. \"\n \"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!\" );\n return AnimationActivitySharedPtr();\n\n\n case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:\n {\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n nType, nSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *pTransitionInfo,\n xTransition->getDirection(),\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n case TransitionInfo::TRANSITION_SPECIAL:\n {\n switch( nType )\n {\n case animations::TransitionType::RANDOM:\n {\n \/\/ select randomly one of the effects from the\n \/\/ TransitionFactoryTable\n\n const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );\n\n ENSURE_AND_THROW( pRandomTransitionInfo != NULL,\n \"TransitionFactory::createShapeTransition(): Got invalid random transition info\" );\n\n ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,\n \"TransitionFactory::createShapeTransition(): Got random again for random input!\" );\n\n \/\/ and recurse\n pGeneratedActivity = createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n pRandomTransitionInfo->mnTransitionType,\n pRandomTransitionInfo->mnTransitionSubType );\n }\n break;\n\n \/\/ TODO(F3): Implement slidewipe for shape\n case animations::TransitionType::SLIDEWIPE:\n {\n sal_Int16 nBarWipeSubType(0);\n bool bDirectionForward(true);\n\n \/\/ map slidewipe to BARWIPE, for now\n switch( nSubType )\n {\n case animations::TransitionSubType::FROMLEFT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMRIGHT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = false;\n break;\n\n case animations::TransitionSubType::FROMTOP:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMBOTTOM:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = false;\n break;\n\n default:\n ENSURE_AND_THROW( false,\n \"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE\" );\n break;\n }\n\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n animations::TransitionType::BARWIPE,\n nBarWipeSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *getTransitionInfo( animations::TransitionType::BARWIPE,\n nBarWipeSubType ),\n bDirectionForward,\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n default:\n {\n \/\/ TODO(F1): Check whether there's anything left, anyway,\n \/\/ for _shape_ transitions. AFAIK, there are no special\n \/\/ effects for shapes...\n\n \/\/ for now, map all to fade effect\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n AnimationFactory::createNumberPropertyAnimation(\n ::rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"Opacity\") ),\n rShape,\n rLayerManager ),\n xTransition->getMode() );\n }\n break;\n }\n }\n break;\n }\n }\n\n if( !pGeneratedActivity.get() )\n {\n \/\/ No animation generated, maybe no table entry for given\n \/\/ transition?\n OSL_TRACE(\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype (%d\/%d) \"\n \"combination encountered\",\n xTransition->getTransition(),\n xTransition->getSubtype() );\n OSL_ENSURE(\n false,\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype \"\n \"combination encountered\" );\n }\n\n return pGeneratedActivity;\n}\n\n}\n}\nINTEGRATION: CWS presfixes09 (1.5.10); FILE MERGED 2006\/10\/18 19:59:09 thb 1.5.10.5: RESYNC: (1.5-1.6); FILE MERGED 2006\/04\/24 13:25:33 thb 1.5.10.4: #i53194# Unified include statements (local headers always have double quotes; external headers angle brackets); reverted EventMultiplexer pause events to shared_ptr; removed EventMultiplexer::removeViewHandler(), since the handler is held weakly, anyway. 2006\/04\/12 20:40:08 thb 1.5.10.3: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006\/03\/24 18:23:25 thb 1.5.10.2: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow 2006\/03\/06 22:14:32 thb 1.5.10.1: #i53194# #i55294# #i59324# Overhauled IntrinsicAnimationActivity; fixes GIF animation import; corrected rehearse timings sprite size; several cosmetic changes (removed external header guards); prepared scene for sprite prio\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: shapetransitionfactory.cxx,v $\n *\n * $Revision: 1.7 $\n *\n * last change: $Author: kz $ $Date: 2006-12-13 15:45:03 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_slideshow.hxx\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \"transitionfactory.hxx\"\n#include \"transitiontools.hxx\"\n#include \"parametricpolypolygonfactory.hxx\"\n#include \"animationfactory.hxx\"\n#include \"clippingfunctor.hxx\"\n\n#include \n\n\nusing namespace ::com::sun::star;\n\nnamespace slideshow {\nnamespace internal {\n\n\/***************************************************\n *** ***\n *** Shape Transition Effects ***\n *** ***\n ***************************************************\/\n\nnamespace {\n\nclass ClippingAnimation : public NumberAnimation\n{\npublic:\n ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn );\n\n ~ClippingAnimation();\n\n \/\/ Animation interface\n \/\/ -------------------\n virtual void start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer );\n virtual void end();\n\n \/\/ NumberAnimation interface\n \/\/ -----------------------\n virtual bool operator()( double nValue );\n virtual double getUnderlyingValue() const;\n\nprivate:\n void end_();\n\n AnimatableShapeSharedPtr mpShape;\n ShapeAttributeLayerSharedPtr mpAttrLayer;\n LayerManagerSharedPtr mpLayerManager;\n ClippingFunctor maClippingFunctor;\n bool mbSpriteActive;\n};\n\nClippingAnimation::ClippingAnimation(\n const ParametricPolyPolygonSharedPtr& rPolygon,\n const LayerManagerSharedPtr& rLayerManager,\n const TransitionInfo& rTransitionInfo,\n bool bDirectionForward,\n bool bModeIn ) :\n mpShape(),\n mpAttrLayer(),\n mpLayerManager( rLayerManager ),\n maClippingFunctor( rPolygon,\n rTransitionInfo,\n bDirectionForward,\n bModeIn ),\n mbSpriteActive(false)\n{\n ENSURE_AND_THROW(\n rLayerManager,\n \"ClippingAnimation::ClippingAnimation(): Invalid LayerManager\" );\n}\n\nClippingAnimation::~ClippingAnimation()\n{\n try\n {\n end_();\n }\n catch (uno::Exception &) {\n OSL_ENSURE( false, rtl::OUStringToOString(\n comphelper::anyToString(\n cppu::getCaughtException() ),\n RTL_TEXTENCODING_UTF8 ).getStr() );\n }\n}\n\nvoid ClippingAnimation::start( const AnimatableShapeSharedPtr& rShape,\n const ShapeAttributeLayerSharedPtr& rAttrLayer )\n{\n OSL_ENSURE( !mpShape,\n \"ClippingAnimation::start(): Shape already set\" );\n OSL_ENSURE( !mpAttrLayer,\n \"ClippingAnimation::start(): Attribute layer already set\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n ENSURE_AND_THROW( rShape,\n \"ClippingAnimation::start(): Invalid shape\" );\n ENSURE_AND_THROW( rAttrLayer,\n \"ClippingAnimation::start(): Invalid attribute layer\" );\n\n mpShape = rShape;\n mpAttrLayer = rAttrLayer;\n\n if( !mbSpriteActive )\n {\n mpLayerManager->enterAnimationMode( mpShape );\n mbSpriteActive = true;\n }\n}\n\nvoid ClippingAnimation::end()\n{\n end_();\n}\n\nvoid ClippingAnimation::end_()\n{\n if( mbSpriteActive )\n {\n mbSpriteActive = false;\n mpLayerManager->leaveAnimationMode( mpShape );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n }\n}\n\nbool ClippingAnimation::operator()( double nValue )\n{\n ENSURE_AND_RETURN(\n mpAttrLayer && mpShape,\n \"ClippingAnimation::operator(): Invalid ShapeAttributeLayer\" );\n\n \/\/ set new clip\n mpAttrLayer->setClip( maClippingFunctor( nValue,\n mpShape->getDOMBounds().getRange() ) );\n\n if( mpShape->isUpdateNecessary() )\n mpLayerManager->notifyShapeUpdate( mpShape );\n\n return true;\n}\n\ndouble ClippingAnimation::getUnderlyingValue() const\n{\n ENSURE_AND_THROW(\n mpAttrLayer,\n \"ClippingAnimation::getUnderlyingValue(): Invalid ShapeAttributeLayer\" );\n\n return 0.0; \/\/ though this should be used in concert with\n \/\/ ActivitiesFactory::createSimpleActivity, better\n \/\/ explicitely name our start value.\n \/\/ Permissible range for operator() above is [0,1]\n}\n\n} \/\/ anon namespace\n\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n uno::Reference< animations::XTransitionFilter > const& xTransition )\n{\n return createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n xTransition->getTransition(),\n xTransition->getSubtype() );\n}\n\nAnimationActivitySharedPtr TransitionFactory::createShapeTransition(\n const ActivitiesFactory::CommonParameters& rParms,\n const AnimatableShapeSharedPtr& rShape,\n const LayerManagerSharedPtr& rLayerManager,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::animations::XTransitionFilter > const& xTransition,\n sal_Int16 nType,\n sal_Int16 nSubType )\n{\n ENSURE_AND_THROW(\n xTransition.is(),\n \"TransitionFactory::createShapeTransition(): Invalid XTransition\" );\n\n const TransitionInfo* pTransitionInfo(\n getTransitionInfo( nType, nSubType ) );\n\n AnimationActivitySharedPtr pGeneratedActivity;\n if( pTransitionInfo != NULL )\n {\n switch( pTransitionInfo->meTransitionClass )\n {\n default:\n case TransitionInfo::TRANSITION_INVALID:\n OSL_ENSURE( false,\n \"TransitionFactory::createShapeTransition(): Invalid transition type. \"\n \"Don't ask me for a 0 TransitionType, have no XTransitionFilter node instead!\" );\n return AnimationActivitySharedPtr();\n\n\n case TransitionInfo::TRANSITION_CLIP_POLYPOLYGON:\n {\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n nType, nSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *pTransitionInfo,\n xTransition->getDirection(),\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n case TransitionInfo::TRANSITION_SPECIAL:\n {\n switch( nType )\n {\n case animations::TransitionType::RANDOM:\n {\n \/\/ select randomly one of the effects from the\n \/\/ TransitionFactoryTable\n\n const TransitionInfo* pRandomTransitionInfo( getRandomTransitionInfo() );\n\n ENSURE_AND_THROW( pRandomTransitionInfo != NULL,\n \"TransitionFactory::createShapeTransition(): Got invalid random transition info\" );\n\n ENSURE_AND_THROW( pRandomTransitionInfo->mnTransitionType != animations::TransitionType::RANDOM,\n \"TransitionFactory::createShapeTransition(): Got random again for random input!\" );\n\n \/\/ and recurse\n pGeneratedActivity = createShapeTransition( rParms,\n rShape,\n rLayerManager,\n xTransition,\n pRandomTransitionInfo->mnTransitionType,\n pRandomTransitionInfo->mnTransitionSubType );\n }\n break;\n\n \/\/ TODO(F3): Implement slidewipe for shape\n case animations::TransitionType::SLIDEWIPE:\n {\n sal_Int16 nBarWipeSubType(0);\n bool bDirectionForward(true);\n\n \/\/ map slidewipe to BARWIPE, for now\n switch( nSubType )\n {\n case animations::TransitionSubType::FROMLEFT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMRIGHT:\n nBarWipeSubType = animations::TransitionSubType::LEFTTORIGHT;\n bDirectionForward = false;\n break;\n\n case animations::TransitionSubType::FROMTOP:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = true;\n break;\n\n case animations::TransitionSubType::FROMBOTTOM:\n nBarWipeSubType = animations::TransitionSubType::TOPTOBOTTOM;\n bDirectionForward = false;\n break;\n\n default:\n ENSURE_AND_THROW( false,\n \"TransitionFactory::createShapeTransition(): Unexpected subtype for SLIDEWIPE\" );\n break;\n }\n\n \/\/ generate parametric poly-polygon\n ParametricPolyPolygonSharedPtr pPoly(\n ParametricPolyPolygonFactory::createClipPolyPolygon(\n animations::TransitionType::BARWIPE,\n nBarWipeSubType ) );\n\n \/\/ create a clip activity from that\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n NumberAnimationSharedPtr(\n new ClippingAnimation(\n pPoly,\n rLayerManager,\n *getTransitionInfo( animations::TransitionType::BARWIPE,\n nBarWipeSubType ),\n bDirectionForward,\n xTransition->getMode() ) ),\n true );\n }\n break;\n\n default:\n {\n \/\/ TODO(F1): Check whether there's anything left, anyway,\n \/\/ for _shape_ transitions. AFAIK, there are no special\n \/\/ effects for shapes...\n\n \/\/ for now, map all to fade effect\n pGeneratedActivity = ActivitiesFactory::createSimpleActivity(\n rParms,\n AnimationFactory::createNumberPropertyAnimation(\n ::rtl::OUString(\n RTL_CONSTASCII_USTRINGPARAM(\"Opacity\") ),\n rShape,\n rLayerManager ),\n xTransition->getMode() );\n }\n break;\n }\n }\n break;\n }\n }\n\n if( !pGeneratedActivity )\n {\n \/\/ No animation generated, maybe no table entry for given\n \/\/ transition?\n OSL_TRACE(\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype (%d\/%d) \"\n \"combination encountered\",\n xTransition->getTransition(),\n xTransition->getSubtype() );\n OSL_ENSURE(\n false,\n \"TransitionFactory::createShapeTransition(): Unknown type\/subtype \"\n \"combination encountered\" );\n }\n\n return pGeneratedActivity;\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright 2014 Cloudius Systems\n *\n * Modified by Cloudius Systems\n *\/\n\n#ifndef CQL3_FUNCTION_NAME_HH\n#define CQL3_FUNCTION_NAME_HH\n\n#include \"core\/sstring.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \n#include \n\nnamespace cql3 {\n\nnamespace functions {\n\nclass function_name final {\npublic:\n const sstring keyspace;\n const sstring name;\n\n static function_name native_function(sstring name) {\n return function_name(db::system_keyspace::NAME, name);\n }\n\n function_name(sstring keyspace, sstring name)\n : keyspace(std::move(keyspace)), name(std::move(name)) {\n }\n\n function_name as_native_function() const {\n return native_function(name);\n }\n\n bool has_keyspace() const {\n return !keyspace.empty();\n }\n\n bool operator==(const function_name& x) const {\n return keyspace == x.keyspace && name == x.name;\n }\n};\n\ninline\nstd::ostream& operator<<(std::ostream& os, const function_name& fn) {\n if (!fn.keyspace.empty()) {\n os << fn.keyspace << \".\";\n }\n return os << fn.name;\n}\n\n}\n}\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(const cql3::functions::function_name& x) const {\n return std::hash()(x.keyspace) ^ std::hash()(x.name);\n }\n};\n\n}\n\n#endif\ncql3: make function_name friendlier to ANTLR\/*\n * Licensed to the Apache Software Foundation (ASF) under one\n * or more contributor license agreements. See the NOTICE file\n * distributed with this work for additional information\n * regarding copyright ownership. The ASF licenses this file\n * to you under the Apache License, Version 2.0 (the\n * \"License\"); you may not use this file except in compliance\n * with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/*\n * Copyright 2014 Cloudius Systems\n *\n * Modified by Cloudius Systems\n *\/\n\n#ifndef CQL3_FUNCTION_NAME_HH\n#define CQL3_FUNCTION_NAME_HH\n\n#include \"core\/sstring.hh\"\n#include \"db\/system_keyspace.hh\"\n#include \n#include \n\nnamespace cql3 {\n\nnamespace functions {\n\nclass function_name final {\npublic:\n sstring keyspace;\n sstring name;\n\n static function_name native_function(sstring name) {\n return function_name(db::system_keyspace::NAME, name);\n }\n\n function_name() = default; \/\/ for ANTLR\n function_name(sstring keyspace, sstring name)\n : keyspace(std::move(keyspace)), name(std::move(name)) {\n }\n\n function_name as_native_function() const {\n return native_function(name);\n }\n\n bool has_keyspace() const {\n return !keyspace.empty();\n }\n\n bool operator==(const function_name& x) const {\n return keyspace == x.keyspace && name == x.name;\n }\n};\n\ninline\nstd::ostream& operator<<(std::ostream& os, const function_name& fn) {\n if (!fn.keyspace.empty()) {\n os << fn.keyspace << \".\";\n }\n return os << fn.name;\n}\n\n}\n}\n\nnamespace std {\n\ntemplate <>\nstruct hash {\n size_t operator()(const cql3::functions::function_name& x) const {\n return std::hash()(x.keyspace) ^ std::hash()(x.name);\n }\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#include \"highlevel_feature_extractor.h\"\n#include \n\nusing namespace rcsc;\n\nHighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,\n int num_opponents,\n bool playing_offense) :\n FeatureExtractor(num_teammates, num_opponents, playing_offense)\n{\n assert(numTeammates >= 0);\n assert(numOpponents >= 0);\n numFeatures = num_basic_features + features_per_teammate * numTeammates\n + features_per_opponent * numOpponents;\n numFeatures+=2; \/\/ action status, stamina\n feature_vec.resize(numFeatures);\n}\n\nHighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}\n\nconst std::vector&\nHighLevelFeatureExtractor::ExtractFeatures(const rcsc::WorldModel& wm,\n\t\t\t\t\t bool last_action_status) {\n featIndx = 0;\n const ServerParam& SP = ServerParam::i();\n const SelfObject& self = wm.self();\n const Vector2D& self_pos = self.pos();\n const float self_ang = self.body().radian();\n const PlayerPtrCont& teammates = wm.teammatesFromSelf();\n const PlayerPtrCont& opponents = wm.opponentsFromSelf();\n float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()\n + SP.pitchHalfWidth() * SP.pitchHalfWidth());\n \/\/ features about self pos\n \/\/ Allow the agent to go 10% over the playfield in any direction\n float tolerance_x = .1 * SP.pitchHalfLength();\n float tolerance_y = .1 * SP.pitchHalfWidth();\n \/\/ Feature[0]: X-postion\n if (playingOffense) {\n addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n\n \/\/ Feature[1]: Y-Position\n addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y,\n SP.pitchHalfWidth() + tolerance_y);\n\n \/\/ Feature[2]: Self Angle\n addNormFeature(self_ang, -M_PI, M_PI);\n\n float r;\n float th;\n \/\/ Features about the ball\n Vector2D ball_pos = wm.ball().pos();\n angleDistToPoint(self_pos, ball_pos, th, r);\n \/\/ Feature[3] and [4]: (x,y) postition of the ball\n if (playingOffense) {\n addNormFeature(ball_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(ball_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n addNormFeature(ball_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y);\n \/\/ Feature[5]: Able to kick\n addNormFeature(self.isKickable(), false, true);\n\n \/\/ Features about distance to goal center\n Vector2D goalCenter(SP.pitchHalfLength(), 0);\n if (!playingOffense) {\n goalCenter.assign(-SP.pitchHalfLength(), 0);\n }\n angleDistToPoint(self_pos, goalCenter, th, r);\n \/\/ Feature[6]: Goal Center Distance\n addNormFeature(r, 0, maxR);\n \/\/ Feature[7]: Angle to goal center\n addNormFeature(th, -M_PI, M_PI);\n \/\/ Feature[8]: largest open goal angle\n addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);\n \/\/ Feature[9]: Dist to our closest opp\n if (numOpponents > 0) {\n calcClosestOpp(wm, self_pos, th, r);\n addNormFeature(r, 0, maxR);\n } else {\n addFeature(FEAT_INVALID);\n }\n\n \/\/ Features[9 - 9+T]: teammate's open angle to goal\n int detected_teammates = 0;\n for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {\n const PlayerObject* teammate = *it;\n if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {\n addNormFeature(calcLargestGoalAngle(wm, teammate->pos()), 0, M_PI);\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; i 0) {\n detected_teammates = 0;\n for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {\n const PlayerObject* teammate = *it;\n if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {\n calcClosestOpp(wm, teammate->pos(), th, r);\n addNormFeature(r, 0, maxR);\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; iunum() > 0 && detected_teammates < numTeammates) {\n addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate->pos()),0,M_PI);\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; iunum() > 0 && detected_teammates < numTeammates) {\n if (playingOffense) {\n addNormFeature(teammate->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(teammate->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n addNormFeature(teammate->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);\n addFeature(teammate->unum());\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; iunum() > 0 && detected_opponents < numOpponents) {\n if (playingOffense) {\n addNormFeature(opponent->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(opponent->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n addNormFeature(opponent->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);\n addFeature(opponent->unum());\n detected_opponents++;\n }\n }\n \/\/ Add zero features for any missing opponents\n for (int i=detected_opponents; ipos();\n if (!player->posValid()) {\n return false;\n }\n return pos.isValid();\n}\n\nUpdate highlevel_feature_extractor.cpp#ifdef HAVE_CONFIG_H\n#include \n#endif\n\n#include \"highlevel_feature_extractor.h\"\n#include \n\nusing namespace rcsc;\n\nHighLevelFeatureExtractor::HighLevelFeatureExtractor(int num_teammates,\n int num_opponents,\n bool playing_offense) :\n FeatureExtractor(num_teammates, num_opponents, playing_offense)\n{\n assert(numTeammates >= 0);\n assert(numOpponents >= 0);\n numFeatures = num_basic_features + features_per_teammate * numTeammates\n + features_per_opponent * numOpponents;\n numFeatures+=2; \/\/ action status, stamina\n feature_vec.resize(numFeatures);\n}\n\nHighLevelFeatureExtractor::~HighLevelFeatureExtractor() {}\n\nconst std::vector&\nHighLevelFeatureExtractor::ExtractFeatures(const rcsc::WorldModel& wm,\n\t\t\t\t\t bool last_action_status) {\n featIndx = 0;\n const ServerParam& SP = ServerParam::i();\n const SelfObject& self = wm.self();\n const Vector2D& self_pos = self.pos();\n const float self_ang = self.body().radian();\n const PlayerPtrCont& teammates = wm.teammatesFromSelf();\n const PlayerPtrCont& opponents = wm.opponentsFromSelf();\n float maxR = sqrtf(SP.pitchHalfLength() * SP.pitchHalfLength()\n + SP.pitchWidth() * SP.pitchWidth());\n \/\/ features about self pos\n \/\/ Allow the agent to go 10% over the playfield in any direction\n float tolerance_x = .1 * SP.pitchHalfLength();\n float tolerance_y = .1 * SP.pitchHalfWidth();\n \/\/ Feature[0]: X-postion\n if (playingOffense) {\n addNormFeature(self_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(self_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n\n \/\/ Feature[1]: Y-Position\n addNormFeature(self_pos.y, -SP.pitchHalfWidth() - tolerance_y,\n SP.pitchHalfWidth() + tolerance_y);\n\n \/\/ Feature[2]: Self Angle\n addNormFeature(self_ang, -M_PI, M_PI);\n\n float r;\n float th;\n \/\/ Features about the ball\n Vector2D ball_pos = wm.ball().pos();\n angleDistToPoint(self_pos, ball_pos, th, r);\n \/\/ Feature[3] and [4]: (x,y) postition of the ball\n if (playingOffense) {\n addNormFeature(ball_pos.x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(ball_pos.x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n addNormFeature(ball_pos.y, -SP.pitchHalfWidth() - tolerance_y, SP.pitchHalfWidth() + tolerance_y);\n \/\/ Feature[5]: Able to kick\n addNormFeature(self.isKickable(), false, true);\n\n \/\/ Features about distance to goal center\n Vector2D goalCenter(SP.pitchHalfLength(), 0);\n if (!playingOffense) {\n goalCenter.assign(-SP.pitchHalfLength(), 0);\n }\n angleDistToPoint(self_pos, goalCenter, th, r);\n \/\/ Feature[6]: Goal Center Distance\n addNormFeature(r, 0, maxR);\n \/\/ Feature[7]: Angle to goal center\n addNormFeature(th, -M_PI, M_PI);\n \/\/ Feature[8]: largest open goal angle\n addNormFeature(calcLargestGoalAngle(wm, self_pos), 0, M_PI);\n \/\/ Feature[9]: Dist to our closest opp\n if (numOpponents > 0) {\n calcClosestOpp(wm, self_pos, th, r);\n addNormFeature(r, 0, maxR);\n } else {\n addFeature(FEAT_INVALID);\n }\n\n \/\/ Features[9 - 9+T]: teammate's open angle to goal\n int detected_teammates = 0;\n for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {\n const PlayerObject* teammate = *it;\n if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {\n addNormFeature(calcLargestGoalAngle(wm, teammate->pos()), 0, M_PI);\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; i 0) {\n detected_teammates = 0;\n for (PlayerPtrCont::const_iterator it=teammates.begin(); it != teammates.end(); ++it) {\n const PlayerObject* teammate = *it;\n if (valid(teammate) && teammate->unum() > 0 && detected_teammates < numTeammates) {\n calcClosestOpp(wm, teammate->pos(), th, r);\n addNormFeature(r, 0, maxR);\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; iunum() > 0 && detected_teammates < numTeammates) {\n addNormFeature(calcLargestTeammateAngle(wm, self_pos, teammate->pos()),0,M_PI);\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; iunum() > 0 && detected_teammates < numTeammates) {\n if (playingOffense) {\n addNormFeature(teammate->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(teammate->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n addNormFeature(teammate->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);\n addFeature(teammate->unum());\n detected_teammates++;\n }\n }\n \/\/ Add zero features for any missing teammates\n for (int i=detected_teammates; iunum() > 0 && detected_opponents < numOpponents) {\n if (playingOffense) {\n addNormFeature(opponent->pos().x, -tolerance_x, SP.pitchHalfLength() + tolerance_x);\n } else {\n addNormFeature(opponent->pos().x, -SP.pitchHalfLength()-tolerance_x, tolerance_x);\n }\n addNormFeature(opponent->pos().y, -tolerance_y - SP.pitchHalfWidth(), SP.pitchHalfWidth() + tolerance_y);\n addFeature(opponent->unum());\n detected_opponents++;\n }\n }\n \/\/ Add zero features for any missing opponents\n for (int i=detected_opponents; ipos();\n if (!player->posValid()) {\n return false;\n }\n return pos.isValid();\n}\n\n<|endoftext|>"} {"text":"#include \"..\/MDFILU_test.h\"\n\nint\nmain(int argc, char *argv[])\n{\n \/\/ #ifdef VERBOSE_OUTPUT\n \/\/ debugStream.open(\"debug.out\");\n \/\/ #endif\n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(\n argc, argv, ::numbers::invalid_unsigned_int);\n const global_index_type degree(10);\n const unsigned int estimated_row_length(10);\n SourceMatrix system_matrix(degree,\n degree,\n \/*max_entries_per_row*\/ estimated_row_length);\n\n \/\/ Set value for system_matrix\n const bool use_sparse_matrix(true);\n if (use_sparse_matrix)\n {\n std::ifstream fin(\"sparse_matrix.dat\");\n while (true)\n {\n global_index_type i, j;\n data_type value;\n fin >> i >> j >> value;\n if (fin.eof())\n {\n break;\n }\n system_matrix.set(i, j, value);\n }\n fin.close();\n }\n else\n {\n std::ifstream fin(\"matrix.dat\");\n for (global_index_type i = 0; i < degree; ++i)\n for (global_index_type j = 0; j < degree; ++j)\n {\n data_type value;\n fin >> value;\n system_matrix.set(i, j, value);\n }\n fin.close();\n }\n\n system_matrix.compress(VectorOperation::insert);\n {\n \/\/ Out put system_matrix\n std::ofstream fout(\"matrix.out\");\n system_matrix.print(fout);\n fout.close();\n }\n MDFILU mdfilu(system_matrix, estimated_row_length, 20);\n\n \/\/ Out put LU\n {\n std::ofstream fout(\"LU.out\");\n mdfilu.get_LU().print(fout);\n fout.close();\n }\n\n \/\/ Test the MDFILU class by multiplying LU back\n \/\/ For now the sparsity pattern is ignored.\n {\n const data_type tolerance(1e-12);\n DynamicMatrix A(degree, degree, estimated_row_length);\n \/\/ Compute LD*U\n for (global_index_type i = 0; i < degree; ++i)\n {\n const global_index_type i_row = mdfilu.get_permutation()[i];\n for (global_index_type j = 0; j < degree; ++j)\n {\n const global_index_type j_col = mdfilu.get_permutation()[j];\n data_type value = 0;\n global_index_type vmult_max_index = 0;\n \/\/ Diagonal values of L is always 1 thus not been stored.\n \/\/ Recover its effect manually.\n if (j >= i)\n {\n value = mdfilu.get_LU().el(i_row, j_col);\n vmult_max_index = i;\n }\n else\n {\n vmult_max_index = j + 1;\n }\n for (global_index_type k = 0; k < vmult_max_index; ++k)\n {\n const global_index_type k_permuted =\n mdfilu.get_permutation()[k];\n value += mdfilu.get_LU().el(i_row, k_permuted) *\n mdfilu.get_LU().el(k_permuted, j_col);\n }\n if (std::abs(value) > tolerance)\n {\n A.set(i_row, j_col, value);\n }\n }\n }\n std::ofstream fout(\"A.out\");\n A.print(fout);\n fout.close();\n }\n\n \/\/ Report number of new fill-ins\n {\n std::ofstream fout(\"apply.out\");\n fout << \"\\nNumber of new fill-ins: \" << mdfilu.number_of_new_fill_ins()\n << std::endl\n << std::endl;\n fout.close();\n }\n\n \/\/ Apply LU and (LU)^-1 to a vector\n MDFVector v(degree);\n {\n const data_type a[degree] = {6, 10, 9, 5, 2, 5, 7, 3, 6, 3};\n\n for (global_index_type i = 0; i < degree; ++i)\n {\n v[i] = a[i];\n }\n }\n\n \/\/ Cache initial transpose status\n const bool use_tranpose_init_stats = mdfilu.UseTranspose();\n \/\/--------- Deal.II native Vector ---------\/\/\n mdfilu.SetUseTranspose(false);\n {\n MDFVector o(v);\n mdfilu.apply(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector (LU)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n {\n MDFVector o(v);\n mdfilu.apply_inverse(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector ((LU)^-1)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n\n mdfilu.SetUseTranspose(true);\n {\n MDFVector o(v);\n mdfilu.apply(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector ((LU)^T)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n {\n MDFVector o(v);\n mdfilu.apply_inverse(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector (((LU)^-1)^T)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n \/\/ Set flags\n mdfilu.SetUseTranspose(use_tranpose_init_stats);\n \/\/[END]\/\/ \/\/--------- Deal.II native Vector ---------\/\/\n \/\/--------- Deal.II wrapped Trilinos Vector ---------\/\/\n mdfilu.SetUseTranspose(false);\n {\n NSVector o;\n o = v;\n mdfilu.apply(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"Vector v:\" << std::endl;\n fout << v;\n fout << \"NSVector (LU)*v:\" << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n {\n NSVector o;\n o = v;\n mdfilu.apply_inverse(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"Vector v:\" << std::endl;\n fout << v;\n fout << \"NSVector ((LU)^-1)*v:\" << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n\n mdfilu.SetUseTranspose(true);\n {\n NSVector o;\n o = v;\n mdfilu.apply(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"Vector v:\" << std::endl;\n fout << v;\n fout << \"NSVector ((LU)^T)*v:\" << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n {\n NSVector o;\n o = v;\n mdfilu.apply_inverse(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"Vector v:\" << std::endl;\n fout << v;\n fout << \"NSVector (((LU)^-1)^T)*v:\" << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n mdfilu.SetUseTranspose(use_tranpose_init_stats);\n \/\/[END]\/\/ \/\/--------- Deal.II wrapped Trilinos Vector ---------\/\/\n\n \/\/--------- Finally, Preconditioner test ---------\/\/\n {\n \/\/ No preconditioner first\n Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());\n Epetra_Vector b(View,\n system_matrix.trilinos_matrix().RangeMap(),\n v.begin());\n AztecOO solver;\n solver.SetAztecOption(AZ_output, AZ_none);\n solver.SetAztecOption(AZ_solver, AZ_gmres);\n solver.SetLHS(&o);\n solver.SetRHS(&b);\n\n solver.SetAztecOption(AZ_precond, AZ_none);\n solver.SetUserMatrix(\n const_cast(&system_matrix.trilinos_matrix()));\n\n const unsigned int max_iterations = 1000;\n const double linear_residual = 1e-8;\n solver.Iterate(max_iterations, linear_residual);\n\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"GMRES Solved Ax=v without preconditioner:\" << std::endl;\n fout << \"NumIters: \" << solver.NumIters() << std::endl;\n fout << \"TrueResidual: \" << solver.TrueResidual() << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n {\n \/\/ No preconditioner first\n Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());\n Epetra_Vector b(View,\n system_matrix.trilinos_matrix().RangeMap(),\n v.begin());\n AztecOO solver;\n solver.SetAztecOption(AZ_output, AZ_none);\n solver.SetAztecOption(AZ_solver, AZ_gmres);\n solver.SetLHS(&o);\n solver.SetRHS(&b);\n\n solver.SetUserMatrix(\n const_cast(&system_matrix.trilinos_matrix()));\n\n mdfilu.SetUseTranspose(false);\n solver.SetPrecOperator(&mdfilu);\n\n const unsigned int max_iterations = 1000;\n const double linear_residual = 1e-8;\n solver.Iterate(max_iterations, linear_residual);\n\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"GMRES Solved Ax=v with MDFILU preconditioner:\" << std::endl;\n fout << \"NumIters: \" << solver.NumIters() << std::endl;\n fout << \"TrueResidual: \" << solver.TrueResidual() << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n mdfilu.SetUseTranspose(use_tranpose_init_stats);\n \/\/[END]\/\/ \/\/--------- Finally, Preconditioner test ---------\/\/\n\n \/\/ #ifdef VERBOSE_OUTPUT\n \/\/ debugStream.close();\n \/\/ #endif\n return (system(\"cat A.out apply.out LU.out matrix.out > output.out\"));\n}\nfix regTests module_MDFILU case002000 due to trilinos vector interface change#include \"..\/MDFILU_test.h\"\n\nint\nmain(int argc, char *argv[])\n{\n \/\/ #ifdef VERBOSE_OUTPUT\n \/\/ debugStream.open(\"debug.out\");\n \/\/ #endif\n\n Utilities::MPI::MPI_InitFinalize mpi_initialization(\n argc, argv, ::numbers::invalid_unsigned_int);\n const global_index_type degree(10);\n const unsigned int estimated_row_length(10);\n SourceMatrix system_matrix(degree,\n degree,\n \/*max_entries_per_row*\/ estimated_row_length);\n\n \/\/ Set value for system_matrix\n const bool use_sparse_matrix(true);\n if (use_sparse_matrix)\n {\n std::ifstream fin(\"sparse_matrix.dat\");\n while (true)\n {\n global_index_type i, j;\n data_type value;\n fin >> i >> j >> value;\n if (fin.eof())\n {\n break;\n }\n system_matrix.set(i, j, value);\n }\n fin.close();\n }\n else\n {\n std::ifstream fin(\"matrix.dat\");\n for (global_index_type i = 0; i < degree; ++i)\n for (global_index_type j = 0; j < degree; ++j)\n {\n data_type value;\n fin >> value;\n system_matrix.set(i, j, value);\n }\n fin.close();\n }\n\n system_matrix.compress(VectorOperation::insert);\n {\n \/\/ Out put system_matrix\n std::ofstream fout(\"matrix.out\");\n system_matrix.print(fout);\n fout.close();\n }\n MDFILU mdfilu(system_matrix, estimated_row_length, 20);\n\n \/\/ Out put LU\n {\n std::ofstream fout(\"LU.out\");\n mdfilu.get_LU().print(fout);\n fout.close();\n }\n\n \/\/ Test the MDFILU class by multiplying LU back\n \/\/ For now the sparsity pattern is ignored.\n {\n const data_type tolerance(1e-12);\n DynamicMatrix A(degree, degree, estimated_row_length);\n \/\/ Compute LD*U\n for (global_index_type i = 0; i < degree; ++i)\n {\n const global_index_type i_row = mdfilu.get_permutation()[i];\n for (global_index_type j = 0; j < degree; ++j)\n {\n const global_index_type j_col = mdfilu.get_permutation()[j];\n data_type value = 0;\n global_index_type vmult_max_index = 0;\n \/\/ Diagonal values of L is always 1 thus not been stored.\n \/\/ Recover its effect manually.\n if (j >= i)\n {\n value = mdfilu.get_LU().el(i_row, j_col);\n vmult_max_index = i;\n }\n else\n {\n vmult_max_index = j + 1;\n }\n for (global_index_type k = 0; k < vmult_max_index; ++k)\n {\n const global_index_type k_permuted =\n mdfilu.get_permutation()[k];\n value += mdfilu.get_LU().el(i_row, k_permuted) *\n mdfilu.get_LU().el(k_permuted, j_col);\n }\n if (std::abs(value) > tolerance)\n {\n A.set(i_row, j_col, value);\n }\n }\n }\n std::ofstream fout(\"A.out\");\n A.print(fout);\n fout.close();\n }\n\n \/\/ Report number of new fill-ins\n {\n std::ofstream fout(\"apply.out\");\n fout << \"\\nNumber of new fill-ins: \" << mdfilu.number_of_new_fill_ins()\n << std::endl\n << std::endl;\n fout.close();\n }\n\n \/\/ Apply LU and (LU)^-1 to a vector\n MDFVector v(degree);\n {\n const data_type a[degree] = {6, 10, 9, 5, 2, 5, 7, 3, 6, 3};\n\n for (global_index_type i = 0; i < degree; ++i)\n {\n v[i] = a[i];\n }\n }\n\n \/\/ Cache initial transpose status\n const bool use_tranpose_init_stats = mdfilu.UseTranspose();\n \/\/--------- Deal.II native Vector ---------\/\/\n mdfilu.SetUseTranspose(false);\n {\n MDFVector o(v);\n mdfilu.apply(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector (LU)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n {\n MDFVector o(v);\n mdfilu.apply_inverse(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector ((LU)^-1)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n\n mdfilu.SetUseTranspose(true);\n {\n MDFVector o(v);\n mdfilu.apply(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector ((LU)^T)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n {\n MDFVector o(v);\n mdfilu.apply_inverse(o, o);\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"Vector (((LU)^-1)^T)*v:\" << std::endl;\n fout << o << std::endl << std::endl;\n fout.close();\n }\n \/\/ Set flags\n mdfilu.SetUseTranspose(use_tranpose_init_stats);\n \/\/[END]\/\/ \/\/--------- Deal.II native Vector ---------\/\/\n \/\/--------- Deal.II wrapped Trilinos Vector ---------\/\/\n {\n mdfilu.SetUseTranspose(false);\n\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout.precision(3);\n fout << std::scientific;\n\n IndexSet idxset(degree);\n idxset.add_range(0, degree);\n NSVector o(idxset);\n\n o = v;\n mdfilu.apply(o, o);\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"NSVector (LU)*v:\" << std::endl;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n\n o = v;\n mdfilu.apply_inverse(o, o);\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"NSVector ((LU)^-1)*v:\" << std::endl;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n\n \/\/ Begain transplose\n mdfilu.SetUseTranspose(true);\n\n o = v;\n mdfilu.apply(o, o);\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"NSVector ((LU)^T)*v:\" << std::endl;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n\n o = v;\n mdfilu.apply_inverse(o, o);\n fout << \"Vector v:\" << std::endl;\n fout << v << std::endl;\n fout << \"NSVector (((LU)^-1)^T)*v:\" << std::endl;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n\n fout.close();\n }\n mdfilu.SetUseTranspose(use_tranpose_init_stats);\n \/\/[END]\/\/ \/\/--------- Deal.II wrapped Trilinos Vector ---------\/\/\n\n \/\/--------- Finally, Preconditioner test ---------\/\/\n {\n \/\/ No preconditioner first\n Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());\n Epetra_Vector b(View,\n system_matrix.trilinos_matrix().RangeMap(),\n v.begin());\n AztecOO solver;\n solver.SetAztecOption(AZ_output, AZ_none);\n solver.SetAztecOption(AZ_solver, AZ_gmres);\n solver.SetLHS(&o);\n solver.SetRHS(&b);\n\n solver.SetAztecOption(AZ_precond, AZ_none);\n solver.SetUserMatrix(\n const_cast(&system_matrix.trilinos_matrix()));\n\n const unsigned int max_iterations = 1000;\n const double linear_residual = 1e-8;\n solver.Iterate(max_iterations, linear_residual);\n\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"GMRES Solved Ax=v without preconditioner:\" << std::endl;\n fout << \"NumIters: \" << solver.NumIters() << std::endl;\n fout << \"TrueResidual: \" << solver.TrueResidual() << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n {\n \/\/ No preconditioner first\n Epetra_Vector o(system_matrix.trilinos_matrix().DomainMap());\n Epetra_Vector b(View,\n system_matrix.trilinos_matrix().RangeMap(),\n v.begin());\n AztecOO solver;\n solver.SetAztecOption(AZ_output, AZ_none);\n solver.SetAztecOption(AZ_solver, AZ_gmres);\n solver.SetLHS(&o);\n solver.SetRHS(&b);\n\n solver.SetUserMatrix(\n const_cast(&system_matrix.trilinos_matrix()));\n\n mdfilu.SetUseTranspose(false);\n solver.SetPrecOperator(&mdfilu);\n\n const unsigned int max_iterations = 1000;\n const double linear_residual = 1e-8;\n solver.Iterate(max_iterations, linear_residual);\n\n std::ofstream fout(\"apply.out\", std::fstream::app);\n fout << \"GMRES Solved Ax=v with MDFILU preconditioner:\" << std::endl;\n fout << \"NumIters: \" << solver.NumIters() << std::endl;\n fout << \"TrueResidual: \" << solver.TrueResidual() << std::endl;\n fout.precision(3);\n fout << std::scientific;\n for (global_index_type i = 0; i < degree; ++i)\n {\n fout << o[i] << ' ';\n }\n fout << std::endl << std::endl;\n fout.close();\n }\n mdfilu.SetUseTranspose(use_tranpose_init_stats);\n \/\/[END]\/\/ \/\/--------- Finally, Preconditioner test ---------\/\/\n\n \/\/ #ifdef VERBOSE_OUTPUT\n \/\/ debugStream.close();\n \/\/ #endif\n return (system(\"cat A.out apply.out LU.out matrix.out > output.out\"));\n}\n<|endoftext|>"} {"text":"#include\n#include\"opencv2\/highgui\/highgui.hpp\"\n#include\"opencv2\/imgproc\/imgproc.hpp\"\n#include\"opencv2\/core\/core.hpp\"\n#include \n\nusing namespace cv;\nusing namespace std;\n\n\/\/Input Mat, and Scalar bounds for thresholding.\nMat src;\nScalar upperBound;\nScalar lowerBound;\n\n\/\/Mode variables. Defaulted at -1 for checking.\nint colorMode=-1; \/\/0 for HSV, 1 for RGB.\nint inputMode=-1; \/\/0 FOr webcam, 1 for video file.\n\n\/\/File path variables\nint videoFilePath;\n\n\/\/capture variables;\nbool capture = false;\nint captureNum= 0; \nofstream outCenter; \nofstream outMoment; \nofstream outMouse;\n\nint mouseX;\nint mouseY;\n\nvoid onMove(int, void *);\nvoid onClickOriginal(int, int, int, int, void *);\nvoid saveFrame(Mat, Mat, int);\nvoid centerMoment(Mat, int &, int &);\nvoid centerFind(Mat, int &, int &);\n\n\nint main(int argc, char ** argv){\n\n\t\/\/Input parsing to select color mode, input mode and anything else needed.\t\n\tif(argc > 1){\n\t\tint num=1;\n\n\t\twhile(num < argc){\n\n\t\t\tstring input= argv[num];\n\t\t\t\n\t\t\t\/\/Help text.\n\t\t\tif(input == \"-help\" || input == \"-h\" || input == \"-H\"){\n\t\t cout<<\"Available options for v5:\"< params;\n params.push_back(CV_IMWRITE_PNG_COMPRESSION);\n params.push_back(9);\n\n\n if(!imwrite(original, imgOriginal, params))\n cerr<<\"Failed to write original\"< 10000){\n \t x =dM10\/area;\n y= dM01\/area;\n\t}\n\tif(capture)\n\t\toutMoment<(i);\n\t\tfirstX= -1;\n\t\tlastX = -1;\n\t\t\t\n\t\tfor(int j = 0; j0 || b>0 || c>0) && capture){\n\t\t\t\tif(firstX == -1)\n\t\t\t\t\tfirstX =j;\n\t\t\t\telse\n\t\t\t\t\tlastX = j;\n\t\t\n\t\t\t\tif(firstY == -1)\n\t\t\t\t\tfirstY= i;\n\t\t\t\telse\n\t\t\t\t\tlastY=i;\n\t\t\t}\n\t\t}\n\t\n\t\t\n\t}\n\tx = (lastX-firstX)\/2 +firstX;\n\ty = (lastY - firstY)\/2 +firstY;\n}\ntransparent rectangle..which crashes if it cant track.#include\n#include\"opencv2\/highgui\/highgui.hpp\"\n#include\"opencv2\/imgproc\/imgproc.hpp\"\n#include\"opencv2\/core\/core.hpp\"\n#include \n\nusing namespace cv;\nusing namespace std;\n\n\/\/Input Mat, and Scalar bounds for thresholding.\nMat src;\nScalar upperBound;\nScalar lowerBound;\n\n\/\/Mode variables. Defaulted at -1 for checking.\nint colorMode=-1; \/\/0 for HSV, 1 for RGB.\nint inputMode=-1; \/\/0 FOr webcam, 1 for video file.\n\n\/\/File path variables\nint videoFilePath;\n\n\/\/capture variables;\nbool capture = false;\nint captureNum= 0; \nofstream outCenter; \nofstream outMoment; \nofstream outMouse;\n\nint mouseX;\nint mouseY;\nbool thresholdSet = false;\n\nvoid onMove(int, void *);\nvoid onClickOriginal(int, int, int, int, void *);\nvoid saveFrame(Mat, Mat, int);\nvoid centerMoment(Mat, int &, int &);\nvoid centerFind(Mat, int &, int &);\n\n\nint main(int argc, char ** argv){\n\n\t\/\/Input parsing to select color mode, input mode and anything else needed.\t\n\tif(argc > 1){\n\t\tint num=1;\n\n\t\twhile(num < argc){\n\n\t\t\tstring input= argv[num];\n\t\t\t\n\t\t\t\/\/Help text.\n\t\t\tif(input == \"-help\" || input == \"-h\" || input == \"-H\"){\n\t\t cout<<\"Available options for v5:\"< params;\n params.push_back(CV_IMWRITE_PNG_COMPRESSION);\n params.push_back(9);\n\n\n if(!imwrite(original, imgOriginal, params))\n cerr<<\"Failed to write original\"< 10000){\n \t x =dM10\/area;\n y= dM01\/area;\n\t}\n\tif(capture)\n\t\toutMoment<(i);\n\t\tfirstX= -1;\n\t\tlastX = -1;\n\t\t\t\n\t\tfor(int j = 0; j0 || b>0 || c>0) && capture){\n\t\t\t\tif(firstX == -1)\n\t\t\t\t\tfirstX =j;\n\t\t\t\telse\n\t\t\t\t\tlastX = j;\n\t\t\n\t\t\t\tif(firstY == -1)\n\t\t\t\t\tfirstY= i;\n\t\t\t\telse\n\t\t\t\t\tlastY=i;\n\t\t\t}\n\t\t}\n\t\n\t\t\n\t}\n\tx = (lastX-firstX)\/2 +firstX;\n\ty = (lastY - firstY)\/2 +firstY;\n}\n<|endoftext|>"} {"text":"#ifndef ALGO_HPP\n#define ALGO_HPP\n\n#include \"ptree.hpp\"\n#include \"equivalence.hpp\"\n#include \"ztree.hpp\"\n#include \"khash.hh\"\n\n\nnamespace tree {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Central algorithm and stuff\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ porta il sottolbero radicato in x in una catena sinistra o destra a seconda di type\n\/\/ (algoritmi LEFT e RIGHT). Restituisce -1 in caso di errore, oppure 0 se l'albero e' nullo\ntemplate\nT list ( ptree& a, T i, equivalence_info& eqinfo, rotation_type type = LEFT ) {\n if ( i == EMPTY ) return 0;\n\n a.get_structure( eqinfo );\n\n T total = 0;\n while ( i != EMPTY ) {\n T next = i;\n\n T j = i;\n while ( ( type == RIGHT && ( a[j].left() && eqinfo[a[j].left()] == EMPTY ) ) ||\n ( type == LEFT && ( a[j].right() && eqinfo[a[j].right()] == EMPTY ) ) ) {\n next = ( type == LEFT ) ? a[j].right() : a[j].left();\n\n a.rotate( j, type );\n ++total;\n\n j = next;\n }\n\n \/\/ l'ultimo nodo che ho ruotato (oppure i invariato) e' quello da cui devo scendere\n i = ( type == LEFT ) ? a.base()[next].left() : a.base()[next].right();\n }\n\n return total;\n}\n\n\/\/ processing basato sull'algoritmo CENTRAL\ntemplate\nT central ( ptree& a, ptree& b ) {\n\n assert( a.size() == b.size() );\n equivalence_info eqinfo( a.size() );\n T total = 0;\n\n \/\/ cerco il nodo con c(x) massimo\n T cmax = 0, rx = 2 * a.size() + 1;\n T selected = a.best_c( b, eqinfo, cmax, rx, greater() );\n\n if ( cmax == 0 )\n return total;\n\n \/\/ porto il nodo selezionato alla radice in entrambi gli alberi\n total += a.to_root( selected );\n total += b.to_root( selected );\n\n \/\/ applico gli algoritmi left e right ai sottoalberi\n total += list( a, a.base()[selected].right(), eqinfo, LEFT );\n total += list( b, b.base()[selected].right(), eqinfo.inverse(), LEFT );\n total += list( a, a.base()[selected].left(), eqinfo, RIGHT );\n total += list( b, b.base()[selected].left(), eqinfo.inverse(), RIGHT );\n\n return total;\n}\n\ntemplate\nT centralfirststep ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n \/\/cout << \"centralfirststep()\" << endl;\n assert( a.size() == b.size() );\n\n T total = 0;\n\n \/\/ cerco il nodo con c(x) massimo\n T cmax = 0, rx = 2 * a.size() + 1;\n T selected = a.best_c( b, eqinfo, cmax, rx, greater() );\n\n if ( cmax == 0 || selected == EMPTY )\n return total;\n\n \/\/cout << \"selected node \" << selected << \" with cmax = \" << cmax << endl;\n\n \/\/ porto il nodo selezionato alla radice in entrambi gli alberi\n total += a.to_root( selected );\n total += b.to_root( selected );\n\n return total;\n}\n\n\ntemplate\nT movebestr ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n\n assert( a.size() == b.size() );\n T total = 0;\n\n \/\/ cerco il nodo con r(x) minimo\n T rx = 2 * a.size() + 1;\n T selected = a.best_r( b, eqinfo, rx, less() );\n\n if ( rx == 0 || selected == EMPTY )\n return total;\n\n \/\/cout << \"selected node \" << selected << \" with rx = \" << rx << endl;\n\n \/\/ porto il nodo selezionato alla radice in entrambi gli alberi\n total += a.to_root( selected );\n total += b.to_root( selected );\n\n return total;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ New algorithm and stuff\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ntemplate\nbool has_equivalent ( ptree& a, ptree& b ) {\n assert( a.size() == b.size() );\n\n equivalence_info eqinfo( a.size() );\n return a.equal_subtrees( b, eqinfo ) != 0;\n}\n\n\n\ntemplate\nT newalgo_r ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n assert( a.size() == b.size() );\n\n \/\/printf( \"a.root() = %d, b.root() = %d, size = %d\\n\", a.root(), b.root(), a.size() );\n if ( a.size() == 0 || a.size() == 1 )\n return 0;\n\n\n T total = 0;\n a.equal_subtrees( b, eqinfo ); \/\/ aggiorno gli intervalli\n total += k_equivalent(a, b, 1, eqinfo); \/\/ stacco nodi k-equivalenti\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno\n\n total += centralfirststep( a, b, eqinfo ); \/\/ porto un nodo a radice\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno (in particolare i figli)\n\n ptree al = a.left();\n ptree bl = b.left();\n ptree ar = a.right();\n ptree br = b.right();\n return total + newalgo_r( al, bl, eqinfo ) + newalgo_r( ar, br, eqinfo );\n}\n\n\n\ntemplate\nT newalgo ( ptree& a, ptree& b ) {\n \/\/cout << \"newalgo()\\n\";\n equivalence_info eqinfo( a.size() );\n return newalgo_r( a, b, eqinfo );\n}\n\n\n\n\n\ntemplate\nT mix_r ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n assert( a.size() == b.size() );\n\n\n if ( a.size() == 0 || a.size() == 1 )\n return 0;\n\n T total = 0;\n a.equal_subtrees( b, eqinfo ); \/\/ aggiorno gli intervalli\n \/\/print(a,b);\n \/\/cout << eqinfo << endl;\n total += k_equivalent(a, b, 1, eqinfo); \/\/ stacco nodi k-equivalenti\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno\n\n total += movebestr( a, b, eqinfo ); \/\/ porto un nodo a radice\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno (in particolare i figli)\n\n\n ptree al = a.left();\n ptree bl = b.left();\n ptree ar = a.right();\n ptree br = b.right();\n return total + mix_r( al, bl, eqinfo ) + mix_r( ar, br, eqinfo );\n}\n\n\n\ntemplate\nT mix ( ptree& a, ptree& b ) {\n \/\/cout << \"mix()\\n\";\n equivalence_info eqinfo( a.size() );\n return mix_r( a, b, eqinfo );\n}\n\n\n\n\n\n\n\ntemplate\nbool k_equivalent_r ( ptree& a, ptree& b, T k, equivalence_info& eqinfo, T before ) {\n if ( k == 0 ) {\n T after = a.equal_subtrees( b, eqinfo );\n\n T threshold = 1;\n if ( after - before >= threshold )\n return true; \/\/ keep\n else\n return false;\n }\n\n for ( T i = a.minimum(); i <= a.maximum(); ++i ) {\n if ( i == a.root() ) continue;\n\n \/*if( a.equal_subtrees( b, eqinfo ) != before ) {\n print(a,b,eqinfo);\n printf( \"now is %d, was %d\\n\", a.equal_subtrees( b, eqinfo ), before );\n cout << eqinfo << endl;\n exit(1);\n }*\/\n if ( eqinfo[i] != EMPTY ) continue;\n\n T father = a[i].father();\n\n a.up( i );\n bool keep = k_equivalent_r( a, b, k-1, eqinfo, before );\n\n\n if ( keep ) {\n \/\/cout << \"kept rotation up of \" << i << endl;\n \/\/print(a,b,eqinfo);\n return true; \/\/ keep\n }\n a.rotate( father, i );\n \/\/printf( \"restored rotation up of %d [%d, %d, %d]\\n\", i, a.minimum(), a.root(), a.maximum() );\n }\n\n return false;\n}\n\n\ntemplate\nT k_equivalent ( ptree& a, ptree& b, T k, equivalence_info& eqinfo ) {\n \/\/cout << \"k_equivalent()\" << endl;\n T total = 0;\n\n for ( T t = 1; t <= k; ) {\n T before = a.equal_subtrees( b, eqinfo );\n \/*cout << eqinfo << endl;\n a.debug();\n b.debug();\n print(a,b,eqinfo);*\/\n\n\n bool something = k_equivalent_r( a, b, t, eqinfo, before );\n if ( !something )\n assert ( a.equal_subtrees(b, eqinfo) == before );\n\n if ( !something )\n something = k_equivalent_r( b, a, t, eqinfo.inverse(), before );\n\n if ( !something ) \/\/ increase t\n ++t;\n else {\n total += t; \/\/ t remain the same (try to search again)\n }\n }\n\n\n return total;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntemplate\nclass unordered_set : public khset_t {};\n\n\nsize_t distance ( const ztree& a, const ztree& b, size_t& visited ) {\n visited = 0;\n\n if ( a == b ) return 0;\n unordered_set queued;\n deque > q;\n q.push_back( a );\n queued.insert( (int) a.to_ulong() );\n\n \/\/ During BFS I scan sequentially all nodes at distance d, exploring the next level d+1.\n \/\/ I set two extremes for two sets:\n \/\/ [0,left) contains the nodes at distance d, d-1, d-2.. 0 from the source node a\n \/\/ [left,right) contains the nodes at distance d+1 from a\n \/\/ When [0,left) = [0,0) means that I have exhausted all the nodes at distance d, d-1..\n \/\/ that means I generated all the nodes on the next level, so I can increase the distance\n \/\/ from the source.\n int left = 1; \/\/ Initially I have node a at distance 0 from a, so [0,left) must contain only node 0\n int right = 1; \/\/ The right limit is the left limit: I have no known node at distance 1\n size_t d = 0; \/\/ distance from a in the current level\n bool found = false;\n\n while( q.size() != 0 ) {\n size_t occupied = q.size() * sizeof( ztree ) + queued.size() * sizeof( unsigned long );\n if ( occupied > visited ) visited = occupied;\n \/\/ select first node in the deque and generates its outcoming star\n for ( unsigned int i = 1; i <= N; ++i ) {\n ztree newone = q.front();\n newone ^ i;\n\n \/\/ if I already queued (or visited) this node I simply skip it\n if ( queued.find( newone.to_ulong() ) != queued.end() )\n continue;\n\n \/\/ if I found it, exit from the loops\n if ( newone == b ) {\n found = true;\n break;\n }\n\n \/\/ otherwise put the new node in the deque and to the hashtable\n q.push_back( newone );\n queued.insert( newone.to_ulong() );\n right++;\n }\n\n if ( found ) break;\n\n \/\/ effectively pop the first element, after visiting him\n q.pop_front();\n --right;\n \/\/ start processing elements at the next level?\n if ( --left == 0 ) {\n left = right;\n ++d;\n }\n }\n\n if (!found) {\n cerr << \"Fatal error.\\n\";\n \/\/cout << queued.count( a.to_ulong() ) << \" \" << queued.count( b.to_ulong() ) << endl;\n exit( 1 );\n }\n\n \/\/visited = queued.size();\n return d + 1;\n}\n\n} \/\/ namespace tree\n\n#endif \/\/ ALGO_HPP\nremoved debug lines#ifndef ALGO_HPP\n#define ALGO_HPP\n\n#include \"ptree.hpp\"\n#include \"equivalence.hpp\"\n#include \"ztree.hpp\"\n#include \"khash.hh\"\n\n\nnamespace tree {\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Central algorithm and stuff\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n\/\/ porta il sottolbero radicato in x in una catena sinistra o destra a seconda di type\n\/\/ (algoritmi LEFT e RIGHT). Restituisce -1 in caso di errore, oppure 0 se l'albero e' nullo\ntemplate\nT list ( ptree& a, T i, equivalence_info& eqinfo, rotation_type type = LEFT ) {\n if ( i == EMPTY ) return 0;\n\n a.get_structure( eqinfo );\n\n T total = 0;\n while ( i != EMPTY ) {\n T next = i;\n\n T j = i;\n while ( ( type == RIGHT && ( a[j].left() && eqinfo[a[j].left()] == EMPTY ) ) ||\n ( type == LEFT && ( a[j].right() && eqinfo[a[j].right()] == EMPTY ) ) ) {\n next = ( type == LEFT ) ? a[j].right() : a[j].left();\n\n a.rotate( j, type );\n ++total;\n\n j = next;\n }\n\n \/\/ l'ultimo nodo che ho ruotato (oppure i invariato) e' quello da cui devo scendere\n i = ( type == LEFT ) ? a.base()[next].left() : a.base()[next].right();\n }\n\n return total;\n}\n\n\/\/ processing basato sull'algoritmo CENTRAL\ntemplate\nT central ( ptree& a, ptree& b ) {\n\n assert( a.size() == b.size() );\n equivalence_info eqinfo( a.size() );\n T total = 0;\n\n \/\/ cerco il nodo con c(x) massimo\n T cmax = 0, rx = 2 * a.size() + 1;\n T selected = a.best_c( b, eqinfo, cmax, rx, greater() );\n\n if ( cmax == 0 )\n return total;\n\n \/\/ porto il nodo selezionato alla radice in entrambi gli alberi\n total += a.to_root( selected );\n total += b.to_root( selected );\n\n \/\/ applico gli algoritmi left e right ai sottoalberi\n total += list( a, a.base()[selected].right(), eqinfo, LEFT );\n total += list( b, b.base()[selected].right(), eqinfo.inverse(), LEFT );\n total += list( a, a.base()[selected].left(), eqinfo, RIGHT );\n total += list( b, b.base()[selected].left(), eqinfo.inverse(), RIGHT );\n\n return total;\n}\n\ntemplate\nT centralfirststep ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n \/\/cout << \"centralfirststep()\" << endl;\n assert( a.size() == b.size() );\n\n T total = 0;\n\n \/\/ cerco il nodo con c(x) massimo\n T cmax = 0, rx = 2 * a.size() + 1;\n T selected = a.best_c( b, eqinfo, cmax, rx, greater() );\n\n if ( cmax == 0 || selected == EMPTY )\n return total;\n\n \/\/cout << \"selected node \" << selected << \" with cmax = \" << cmax << endl;\n\n \/\/ porto il nodo selezionato alla radice in entrambi gli alberi\n total += a.to_root( selected );\n total += b.to_root( selected );\n\n return total;\n}\n\n\ntemplate\nT movebestr ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n\n assert( a.size() == b.size() );\n T total = 0;\n\n \/\/ cerco il nodo con r(x) minimo\n T rx = 2 * a.size() + 1;\n T selected = a.best_r( b, eqinfo, rx, less() );\n\n if ( rx == 0 || selected == EMPTY )\n return total;\n\n \/\/cout << \"selected node \" << selected << \" with rx = \" << rx << endl;\n\n \/\/ porto il nodo selezionato alla radice in entrambi gli alberi\n total += a.to_root( selected );\n total += b.to_root( selected );\n\n return total;\n}\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ New algorithm and stuff\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\ntemplate\nbool has_equivalent ( ptree& a, ptree& b ) {\n assert( a.size() == b.size() );\n\n equivalence_info eqinfo( a.size() );\n return a.equal_subtrees( b, eqinfo ) != 0;\n}\n\n\n\ntemplate\nT newalgo_r ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n assert( a.size() == b.size() );\n\n if ( a.size() == 0 || a.size() == 1 )\n return 0;\n\n\n T total = 0;\n a.equal_subtrees( b, eqinfo ); \/\/ aggiorno gli intervalli\n total += k_equivalent(a, b, 1, eqinfo); \/\/ stacco nodi k-equivalenti\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno\n\n total += centralfirststep( a, b, eqinfo ); \/\/ porto un nodo a radice\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno (in particolare i figli)\n\n ptree al = a.left();\n ptree bl = b.left();\n ptree ar = a.right();\n ptree br = b.right();\n return total + newalgo_r( al, bl, eqinfo ) + newalgo_r( ar, br, eqinfo );\n}\n\n\n\ntemplate\nT newalgo ( ptree& a, ptree& b ) {\n \/\/cout << \"newalgo()\\n\";\n equivalence_info eqinfo( a.size() );\n return newalgo_r( a, b, eqinfo );\n}\n\n\n\n\n\ntemplate\nT mix_r ( ptree& a, ptree& b, equivalence_info& eqinfo ) {\n assert( a.size() == b.size() );\n\n\n if ( a.size() == 0 || a.size() == 1 )\n return 0;\n\n T total = 0;\n a.equal_subtrees( b, eqinfo ); \/\/ aggiorno gli intervalli\n total += k_equivalent(a, b, 1, eqinfo); \/\/ stacco nodi k-equivalenti\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno\n\n total += movebestr( a, b, eqinfo ); \/\/ porto un nodo a radice\n a.equal_subtrees( b, eqinfo ); \/\/ riaggiorno (in particolare i figli)\n\n\n ptree al = a.left();\n ptree bl = b.left();\n ptree ar = a.right();\n ptree br = b.right();\n return total + mix_r( al, bl, eqinfo ) + mix_r( ar, br, eqinfo );\n}\n\n\n\ntemplate\nT mix ( ptree& a, ptree& b ) {\n equivalence_info eqinfo( a.size() );\n return mix_r( a, b, eqinfo );\n}\n\n\n\n\n\n\n\ntemplate\nbool k_equivalent_r ( ptree& a, ptree& b, T k, equivalence_info& eqinfo, T before ) {\n if ( k == 0 ) {\n T after = a.equal_subtrees( b, eqinfo );\n\n T threshold = 1;\n if ( after - before >= threshold )\n return true; \/\/ keep\n else\n return false;\n }\n\n for ( T i = a.minimum(); i <= a.maximum(); ++i ) {\n if ( i == a.root() ) continue;\n\n if ( eqinfo[i] != EMPTY ) continue;\n\n T father = a[i].father();\n\n a.up( i );\n bool keep = k_equivalent_r( a, b, k-1, eqinfo, before );\n\n\n if ( keep )\n return true; \/\/ keep\n a.rotate( father, i );\n }\n\n return false;\n}\n\n\ntemplate\nT k_equivalent ( ptree& a, ptree& b, T k, equivalence_info& eqinfo ) {\n T total = 0;\n\n for ( T t = 1; t <= k; ) {\n T before = a.equal_subtrees( b, eqinfo );\n\n bool something = k_equivalent_r( a, b, t, eqinfo, before );\n if ( !something )\n assert ( a.equal_subtrees(b, eqinfo) == before );\n\n if ( !something )\n something = k_equivalent_r( b, a, t, eqinfo.inverse(), before );\n\n if ( !something ) \/\/ increase t\n ++t;\n else {\n total += t; \/\/ t remain the same (try to search again)\n }\n }\n\n\n return total;\n}\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ntemplate\nclass unordered_set : public khset_t {};\n\n\nsize_t distance ( const ztree& a, const ztree& b, size_t& visited ) {\n visited = 0;\n\n if ( a == b ) return 0;\n unordered_set queued;\n deque > q;\n q.push_back( a );\n queued.insert( (int) a.to_ulong() );\n\n \/\/ During BFS I scan sequentially all nodes at distance d, exploring the next level d+1.\n \/\/ I set two extremes for two sets:\n \/\/ [0,left) contains the nodes at distance d, d-1, d-2.. 0 from the source node a\n \/\/ [left,right) contains the nodes at distance d+1 from a\n \/\/ When [0,left) = [0,0) means that I have exhausted all the nodes at distance d, d-1..\n \/\/ that means I generated all the nodes on the next level, so I can increase the distance\n \/\/ from the source.\n int left = 1; \/\/ Initially I have node a at distance 0 from a, so [0,left) must contain only node 0\n int right = 1; \/\/ The right limit is the left limit: I have no known node at distance 1\n size_t d = 0; \/\/ distance from a in the current level\n bool found = false;\n\n while( q.size() != 0 ) {\n size_t occupied = q.size() * sizeof( ztree ) + queued.size() * sizeof( unsigned long );\n if ( occupied > visited ) visited = occupied;\n \/\/ select first node in the deque and generates its outcoming star\n for ( unsigned int i = 1; i <= N; ++i ) {\n ztree newone = q.front();\n newone ^ i;\n\n \/\/ if I already queued (or visited) this node I simply skip it\n if ( queued.find( newone.to_ulong() ) != queued.end() )\n continue;\n\n \/\/ if I found it, exit from the loops\n if ( newone == b ) {\n found = true;\n break;\n }\n\n \/\/ otherwise put the new node in the deque and to the hashtable\n q.push_back( newone );\n queued.insert( newone.to_ulong() );\n right++;\n }\n\n if ( found ) break;\n\n \/\/ effectively pop the first element, after visiting him\n q.pop_front();\n --right;\n \/\/ start processing elements at the next level?\n if ( --left == 0 ) {\n left = right;\n ++d;\n }\n }\n\n if (!found) {\n cerr << \"Fatal error.\\n\";\n \/\/cout << queued.count( a.to_ulong() ) << \" \" << queued.count( b.to_ulong() ) << endl;\n exit( 1 );\n }\n\n \/\/visited = queued.size();\n return d + 1;\n}\n\n} \/\/ namespace tree\n\n#endif \/\/ ALGO_HPP\n<|endoftext|>"} {"text":"\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"kudu\/clock\/hybrid_clock.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kudu\/clock\/mock_ntp.h\"\n#include \"kudu\/clock\/time_service.h\"\n#include \"kudu\/common\/timestamp.h\"\n#include \"kudu\/gutil\/casts.h\"\n#include \"kudu\/gutil\/ref_counted.h\"\n#include \"kudu\/gutil\/strings\/join.h\"\n#include \"kudu\/util\/atomic.h\"\n#include \"kudu\/util\/monotime.h\"\n#include \"kudu\/util\/random.h\"\n#include \"kudu\/util\/random_util.h\"\n#include \"kudu\/util\/scoped_cleanup.h\"\n#include \"kudu\/util\/status.h\"\n#include \"kudu\/util\/test_macros.h\"\n#include \"kudu\/util\/test_util.h\"\n#include \"kudu\/util\/thread.h\"\n\n\nDECLARE_bool(inject_unsync_time_errors);\nDECLARE_string(time_source);\n\nusing std::string;\nusing std::vector;\n\nnamespace kudu {\nnamespace clock {\n\nclass HybridClockTest : public KuduTest {\n public:\n HybridClockTest()\n : clock_(new HybridClock) {\n }\n\n void SetUp() override {\n KuduTest::SetUp();\n ASSERT_OK(clock_->Init());\n }\n\n protected:\n scoped_refptr clock_;\n};\n\nclock::MockNtp* mock_ntp(HybridClock* clock) {\n return down_cast(clock->time_service());\n}\n\nTEST(MockHybridClockTest, TestMockedSystemClock) {\n google::FlagSaver saver;\n FLAGS_time_source = \"mock\";\n scoped_refptr clock(new HybridClock);\n ASSERT_OK(clock->Init());\n Timestamp timestamp;\n uint64_t max_error_usec;\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(), 0);\n ASSERT_EQ(max_error_usec, 0);\n \/\/ If we read the clock again we should see the logical component be incremented.\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(), 1);\n \/\/ Now set an arbitrary time and check that is the time returned by the clock.\n uint64_t time = 1234 * 1000;\n uint64_t error = 100 * 1000;\n mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);\n mock_ntp(clock.get())->SetMockMaxClockErrorForTests(error);\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(),\n HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 0).ToUint64());\n ASSERT_EQ(max_error_usec, error);\n \/\/ Perform another read, we should observe the logical component increment, again.\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(),\n HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 1).ToUint64());\n}\n\n\/\/ Test that, if the rate at which the clock is read is greater than the maximum\n\/\/ resolution of the logical counter (12 bits in our implementation), it properly\n\/\/ \"overflows\" into the physical portion of the clock, and maintains all ordering\n\/\/ guarantees even as the physical clock continues to increase.\n\/\/\n\/\/ This is a regression test for KUDU-1345.\nTEST(MockHybridClockTest, TestClockDealsWithWrapping) {\n google::FlagSaver saver;\n FLAGS_time_source = \"mock\";\n scoped_refptr clock(new HybridClock);\n ASSERT_OK(clock->Init());\n mock_ntp(clock.get())->SetMockClockWallTimeForTests(1000);\n\n Timestamp prev = clock->Now();\n\n \/\/ Update the clock from 10us in the future\n ASSERT_OK(clock->Update(HybridClock::TimestampFromMicroseconds(1010)));\n\n \/\/ Now read the clock value enough times so that the logical value wraps\n \/\/ over, and should increment the _physical_ portion of the clock.\n for (int i = 0; i < 10000; i++) {\n Timestamp now = clock->Now();\n ASSERT_GT(now.value(), prev.value());\n prev = now;\n }\n ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(prev));\n\n \/\/ Advance the time microsecond by microsecond, and ensure the clock never\n \/\/ goes backwards.\n for (int time = 1001; time < 1020; time++) {\n mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);\n Timestamp now = clock->Now();\n\n \/\/ Clock should run strictly forwards.\n ASSERT_GT(now.value(), prev.value());\n\n \/\/ Additionally, once the physical time surpasses the logical time, we should\n \/\/ be running on the physical clock. Otherwise, we should stick with the physical\n \/\/ time we had rolled forward to above.\n if (time > 1012) {\n ASSERT_EQ(time, HybridClock::GetPhysicalValueMicros(now));\n } else {\n ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(now));\n }\n\n prev = now;\n }\n}\n\n\/\/ Test that two subsequent time reads are monotonically increasing.\nTEST_F(HybridClockTest, TestNow_ValuesIncreaseMonotonically) {\n const Timestamp now1 = clock_->Now();\n const Timestamp now2 = clock_->Now();\n ASSERT_LT(now1.value(), now2.value());\n}\n\n\/\/ Tests the clock updates with the incoming value if it is higher.\nTEST_F(HybridClockTest, TestUpdate_LogicalValueIncreasesByAmount) {\n Timestamp now = clock_->Now();\n uint64_t now_micros = HybridClock::GetPhysicalValueMicros(now);\n\n \/\/ increase the logical value\n uint64_t logical = HybridClock::GetLogicalValue(now);\n logical += 10;\n\n \/\/ increase the physical value so that we're sure the clock will take this\n \/\/ one, 200 msecs should be more than enough.\n now_micros += 200000;\n\n Timestamp now_increased = HybridClock::TimestampFromMicrosecondsAndLogicalValue(now_micros,\n logical);\n\n ASSERT_OK(clock_->Update(now_increased));\n\n Timestamp now2 = clock_->Now();\n ASSERT_EQ(logical + 1, HybridClock::GetLogicalValue(now2));\n ASSERT_EQ(HybridClock::GetPhysicalValueMicros(now) + 200000,\n HybridClock::GetPhysicalValueMicros(now2));\n}\n\n\/\/ Test that the incoming event is in the past, i.e. less than now - max_error\nTEST_F(HybridClockTest, TestWaitUntilAfter_TestCase1) {\n MonoTime no_deadline;\n MonoTime before = MonoTime::Now();\n\n Timestamp past_ts;\n uint64_t max_error;\n clock_->NowWithError(&past_ts, &max_error);\n\n \/\/ make the event 3 * the max. possible error in the past\n Timestamp past_ts_changed = HybridClock::AddPhysicalTimeToTimestamp(\n past_ts,\n MonoDelta::FromMicroseconds(-3 * static_cast(max_error)));\n ASSERT_OK(clock_->WaitUntilAfter(past_ts_changed, no_deadline));\n\n MonoTime after = MonoTime::Now();\n MonoDelta delta = after - before;\n \/\/ The delta should be close to 0, but it takes some time for the hybrid\n \/\/ logical clock to decide that it doesn't need to wait.\n ASSERT_LT(delta.ToMicroseconds(), 25000);\n}\n\n\/\/ The normal case for transactions. Obtain a timestamp and then wait until\n\/\/ we're sure that tx_latest < now_earliest.\nTEST_F(HybridClockTest, TestWaitUntilAfter_TestCase2) {\n MonoTime before = MonoTime::Now();\n\n \/\/ we do no time adjustment, this event should fall right within the possible\n \/\/ error interval\n Timestamp past_ts;\n uint64_t past_max_error;\n clock_->NowWithError(&past_ts, &past_max_error);\n \/\/ Make sure the error is at least a small number of microseconds, to ensure\n \/\/ that we always have to wait.\n past_max_error = std::max(past_max_error, static_cast(20));\n Timestamp wait_until = HybridClock::AddPhysicalTimeToTimestamp(\n past_ts,\n MonoDelta::FromMicroseconds(past_max_error));\n\n Timestamp current_ts;\n uint64_t current_max_error;\n clock_->NowWithError(¤t_ts, ¤t_max_error);\n\n \/\/ Check waiting with a deadline which already expired.\n {\n MonoTime deadline = before;\n Status s = clock_->WaitUntilAfter(wait_until, deadline);\n ASSERT_TRUE(s.IsTimedOut()) << s.ToString();\n }\n\n \/\/ Wait with a deadline well in the future. This should succeed.\n {\n MonoTime deadline = before + MonoDelta::FromSeconds(60);\n ASSERT_OK(clock_->WaitUntilAfter(wait_until, deadline));\n }\n\n MonoTime after = MonoTime::Now();\n MonoDelta delta = after - before;\n\n \/\/ In the common case current_max_error >= past_max_error and we should have waited\n \/\/ 2 * past_max_error, but if the clock's error is reset between the two reads we might\n \/\/ have waited less time, but always more than 'past_max_error'.\n if (current_max_error >= past_max_error) {\n ASSERT_GE(delta.ToMicroseconds(), 2 * past_max_error);\n } else {\n ASSERT_GE(delta.ToMicroseconds(), past_max_error);\n }\n}\n\nTEST_F(HybridClockTest, TestIsAfter) {\n Timestamp ts1 = clock_->Now();\n ASSERT_TRUE(clock_->IsAfter(ts1));\n\n \/\/ Update the clock in the future, make sure it still\n \/\/ handles \"IsAfter\" properly even when it's running in\n \/\/ \"logical\" mode.\n Timestamp now_increased = HybridClock::TimestampFromMicroseconds(\n HybridClock::GetPhysicalValueMicros(ts1) + 1 * 1000 * 1000);\n ASSERT_OK(clock_->Update(now_increased));\n Timestamp ts2 = clock_->Now();\n\n ASSERT_TRUE(clock_->IsAfter(ts1));\n ASSERT_TRUE(clock_->IsAfter(ts2));\n}\n\n\/\/ Thread which loops polling the clock and updating it slightly\n\/\/ into the future.\nvoid StresserThread(HybridClock* clock, AtomicBool* stop) {\n Random rng(GetRandomSeed32());\n Timestamp prev(0);\n while (!stop->Load()) {\n Timestamp t = clock->Now();\n CHECK_GT(t.value(), prev.value());\n prev = t;\n\n \/\/ Add a random bit of offset to the clock, and perform an update.\n Timestamp new_ts = HybridClock::AddPhysicalTimeToTimestamp(\n t, MonoDelta::FromMicroseconds(rng.Uniform(10000)));\n CHECK_OK(clock->Update(new_ts));\n }\n}\n\n\/\/ Regression test for KUDU-953: if threads are updating and polling the\n\/\/ clock concurrently, the clock should still never run backwards.\nTEST_F(HybridClockTest, TestClockDoesntGoBackwardsWithUpdates) {\n vector> threads;\n AtomicBool stop(false);\n\n SCOPED_CLEANUP({\n stop.Store(true);\n for (const auto& t : threads) {\n t->Join();\n }\n });\n\n for (int i = 0; i < 4; i++) {\n scoped_refptr thread;\n ASSERT_OK(Thread::Create(\"test\", \"stresser\",\n &StresserThread, clock_.get(), &stop,\n &thread));\n threads.push_back(thread);\n }\n\n SleepFor(MonoDelta::FromSeconds(1));\n}\n\nTEST_F(HybridClockTest, TestGetPhysicalComponentDifference) {\n Timestamp now1 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(100, 100);\n SleepFor(MonoDelta::FromMilliseconds(1));\n Timestamp now2 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(200, 0);\n MonoDelta delta = clock_->GetPhysicalComponentDifference(now2, now1);\n MonoDelta negative_delta = clock_->GetPhysicalComponentDifference(now1, now2);\n ASSERT_EQ(100, delta.ToMicroseconds());\n ASSERT_EQ(-100, negative_delta.ToMicroseconds());\n}\n\nTEST_F(HybridClockTest, TestRideOverNtpInterruption) {\n Timestamp timestamps[3];\n uint64_t max_error_usec[3];\n\n \/\/ Get the clock once, with a working NTP.\n clock_->NowWithError(×tamps[0], &max_error_usec[0]);\n\n \/\/ Try to read the clock again a second later, but with an error\n \/\/ injected. It should extrapolate from the first read.\n SleepFor(MonoDelta::FromSeconds(1));\n FLAGS_inject_unsync_time_errors = true;\n clock_->NowWithError(×tamps[1], &max_error_usec[1]);\n\n \/\/ The new clock reading should be a second or longer from the\n \/\/ first one, since SleepFor guarantees sleeping at least as long\n \/\/ as specified.\n MonoDelta phys_diff = clock_->GetPhysicalComponentDifference(\n timestamps[1], timestamps[0]);\n ASSERT_GE(phys_diff.ToSeconds(), 1);\n\n \/\/ The new clock reading should have higher error than the first.\n \/\/ The error should have increased based on the clock skew.\n int64_t error_diff = max_error_usec[1] - max_error_usec[0];\n ASSERT_NEAR(error_diff, clock_->time_service()->skew_ppm() * phys_diff.ToSeconds(),\n 10);\n\n \/\/ Now restore the ability to read the system clock, and\n \/\/ read it again.\n FLAGS_inject_unsync_time_errors = false;\n clock_->NowWithError(×tamps[2], &max_error_usec[2]);\n\n ASSERT_LT(timestamps[0].ToUint64(), timestamps[1].ToUint64());\n ASSERT_LT(timestamps[1].ToUint64(), timestamps[2].ToUint64());\n}\n\n#ifndef __APPLE__\nTEST_F(HybridClockTest, TestNtpDiagnostics) {\n vector log;\n clock_->time_service()->DumpDiagnostics(&log);\n string s = JoinStrings(log, \"\\n\");\n SCOPED_TRACE(s);\n ASSERT_STR_MATCHES(s, \"(ntp_gettime\\\\(\\\\) returns code |chronyc -n tracking)\");\n ASSERT_STR_MATCHES(s, \"(ntpq -n |chronyc -n sources)\");\n}\n#endif\n\n} \/\/ namespace clock\n} \/\/ namespace kudu\n[test] fix HybridClockTest.TestWaitUntilAfter_TestCase2\/\/ Licensed to the Apache Software Foundation (ASF) under one\n\/\/ or more contributor license agreements. See the NOTICE file\n\/\/ distributed with this work for additional information\n\/\/ regarding copyright ownership. The ASF licenses this file\n\/\/ to you under the Apache License, Version 2.0 (the\n\/\/ \"License\"); you may not use this file except in compliance\n\/\/ with the License. You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing,\n\/\/ software distributed under the License is distributed on an\n\/\/ \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n\/\/ KIND, either express or implied. See the License for the\n\/\/ specific language governing permissions and limitations\n\/\/ under the License.\n\n#include \"kudu\/clock\/hybrid_clock.h\"\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"kudu\/clock\/mock_ntp.h\"\n#include \"kudu\/clock\/time_service.h\"\n#include \"kudu\/common\/timestamp.h\"\n#include \"kudu\/gutil\/casts.h\"\n#include \"kudu\/gutil\/ref_counted.h\"\n#include \"kudu\/gutil\/strings\/join.h\"\n#include \"kudu\/util\/atomic.h\"\n#include \"kudu\/util\/monotime.h\"\n#include \"kudu\/util\/random.h\"\n#include \"kudu\/util\/random_util.h\"\n#include \"kudu\/util\/scoped_cleanup.h\"\n#include \"kudu\/util\/status.h\"\n#include \"kudu\/util\/test_macros.h\"\n#include \"kudu\/util\/test_util.h\"\n#include \"kudu\/util\/thread.h\"\n\n\nDECLARE_bool(inject_unsync_time_errors);\nDECLARE_string(time_source);\n\nusing std::string;\nusing std::vector;\n\nnamespace kudu {\nnamespace clock {\n\nclass HybridClockTest : public KuduTest {\n public:\n HybridClockTest()\n : clock_(new HybridClock) {\n }\n\n void SetUp() override {\n KuduTest::SetUp();\n ASSERT_OK(clock_->Init());\n }\n\n protected:\n scoped_refptr clock_;\n};\n\nclock::MockNtp* mock_ntp(HybridClock* clock) {\n return down_cast(clock->time_service());\n}\n\nTEST(MockHybridClockTest, TestMockedSystemClock) {\n google::FlagSaver saver;\n FLAGS_time_source = \"mock\";\n scoped_refptr clock(new HybridClock);\n ASSERT_OK(clock->Init());\n Timestamp timestamp;\n uint64_t max_error_usec;\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(), 0);\n ASSERT_EQ(max_error_usec, 0);\n \/\/ If we read the clock again we should see the logical component be incremented.\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(), 1);\n \/\/ Now set an arbitrary time and check that is the time returned by the clock.\n uint64_t time = 1234 * 1000;\n uint64_t error = 100 * 1000;\n mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);\n mock_ntp(clock.get())->SetMockMaxClockErrorForTests(error);\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(),\n HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 0).ToUint64());\n ASSERT_EQ(max_error_usec, error);\n \/\/ Perform another read, we should observe the logical component increment, again.\n clock->NowWithError(×tamp, &max_error_usec);\n ASSERT_EQ(timestamp.ToUint64(),\n HybridClock::TimestampFromMicrosecondsAndLogicalValue(time, 1).ToUint64());\n}\n\n\/\/ Test that, if the rate at which the clock is read is greater than the maximum\n\/\/ resolution of the logical counter (12 bits in our implementation), it properly\n\/\/ \"overflows\" into the physical portion of the clock, and maintains all ordering\n\/\/ guarantees even as the physical clock continues to increase.\n\/\/\n\/\/ This is a regression test for KUDU-1345.\nTEST(MockHybridClockTest, TestClockDealsWithWrapping) {\n google::FlagSaver saver;\n FLAGS_time_source = \"mock\";\n scoped_refptr clock(new HybridClock);\n ASSERT_OK(clock->Init());\n mock_ntp(clock.get())->SetMockClockWallTimeForTests(1000);\n\n Timestamp prev = clock->Now();\n\n \/\/ Update the clock from 10us in the future\n ASSERT_OK(clock->Update(HybridClock::TimestampFromMicroseconds(1010)));\n\n \/\/ Now read the clock value enough times so that the logical value wraps\n \/\/ over, and should increment the _physical_ portion of the clock.\n for (int i = 0; i < 10000; i++) {\n Timestamp now = clock->Now();\n ASSERT_GT(now.value(), prev.value());\n prev = now;\n }\n ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(prev));\n\n \/\/ Advance the time microsecond by microsecond, and ensure the clock never\n \/\/ goes backwards.\n for (int time = 1001; time < 1020; time++) {\n mock_ntp(clock.get())->SetMockClockWallTimeForTests(time);\n Timestamp now = clock->Now();\n\n \/\/ Clock should run strictly forwards.\n ASSERT_GT(now.value(), prev.value());\n\n \/\/ Additionally, once the physical time surpasses the logical time, we should\n \/\/ be running on the physical clock. Otherwise, we should stick with the physical\n \/\/ time we had rolled forward to above.\n if (time > 1012) {\n ASSERT_EQ(time, HybridClock::GetPhysicalValueMicros(now));\n } else {\n ASSERT_EQ(1012, HybridClock::GetPhysicalValueMicros(now));\n }\n\n prev = now;\n }\n}\n\n\/\/ Test that two subsequent time reads are monotonically increasing.\nTEST_F(HybridClockTest, TestNow_ValuesIncreaseMonotonically) {\n const Timestamp now1 = clock_->Now();\n const Timestamp now2 = clock_->Now();\n ASSERT_LT(now1.value(), now2.value());\n}\n\n\/\/ Tests the clock updates with the incoming value if it is higher.\nTEST_F(HybridClockTest, TestUpdate_LogicalValueIncreasesByAmount) {\n Timestamp now = clock_->Now();\n uint64_t now_micros = HybridClock::GetPhysicalValueMicros(now);\n\n \/\/ increase the logical value\n uint64_t logical = HybridClock::GetLogicalValue(now);\n logical += 10;\n\n \/\/ increase the physical value so that we're sure the clock will take this\n \/\/ one, 200 msecs should be more than enough.\n now_micros += 200000;\n\n Timestamp now_increased = HybridClock::TimestampFromMicrosecondsAndLogicalValue(now_micros,\n logical);\n\n ASSERT_OK(clock_->Update(now_increased));\n\n Timestamp now2 = clock_->Now();\n ASSERT_EQ(logical + 1, HybridClock::GetLogicalValue(now2));\n ASSERT_EQ(HybridClock::GetPhysicalValueMicros(now) + 200000,\n HybridClock::GetPhysicalValueMicros(now2));\n}\n\n\/\/ Test that the incoming event is in the past, i.e. less than now - max_error\nTEST_F(HybridClockTest, TestWaitUntilAfter_TestCase1) {\n MonoTime no_deadline;\n MonoTime before = MonoTime::Now();\n\n Timestamp past_ts;\n uint64_t max_error;\n clock_->NowWithError(&past_ts, &max_error);\n\n \/\/ make the event 3 * the max. possible error in the past\n Timestamp past_ts_changed = HybridClock::AddPhysicalTimeToTimestamp(\n past_ts,\n MonoDelta::FromMicroseconds(-3 * static_cast(max_error)));\n ASSERT_OK(clock_->WaitUntilAfter(past_ts_changed, no_deadline));\n\n MonoTime after = MonoTime::Now();\n MonoDelta delta = after - before;\n \/\/ The delta should be close to 0, but it takes some time for the hybrid\n \/\/ logical clock to decide that it doesn't need to wait.\n ASSERT_LT(delta.ToMicroseconds(), 25000);\n}\n\n\/\/ The normal case for transactions. Obtain a timestamp and then wait until\n\/\/ we're sure that tx_latest < now_earliest.\nTEST_F(HybridClockTest, TestWaitUntilAfter_TestCase2) {\n const MonoTime before = MonoTime::Now();\n\n \/\/ we do no time adjustment, this event should fall right within the possible\n \/\/ error interval\n Timestamp past_ts;\n uint64_t past_max_error;\n clock_->NowWithError(&past_ts, &past_max_error);\n \/\/ Make sure the error is at least a small number of microseconds, to ensure\n \/\/ that we always have to wait.\n past_max_error = std::max(past_max_error, static_cast(2000));\n Timestamp wait_until = HybridClock::AddPhysicalTimeToTimestamp(\n past_ts,\n MonoDelta::FromMicroseconds(past_max_error));\n\n Timestamp current_ts;\n uint64_t current_max_error;\n clock_->NowWithError(¤t_ts, ¤t_max_error);\n\n \/\/ Check waiting with a deadline which already expired.\n {\n MonoTime deadline = before;\n Status s = clock_->WaitUntilAfter(wait_until, deadline);\n ASSERT_TRUE(s.IsTimedOut()) << s.ToString();\n }\n\n \/\/ Wait with a deadline well in the future. This should succeed.\n {\n MonoTime deadline = before + MonoDelta::FromSeconds(60);\n ASSERT_OK(clock_->WaitUntilAfter(wait_until, deadline));\n }\n\n MonoTime after = MonoTime::Now();\n MonoDelta delta = after - before;\n\n \/\/ In the common case current_max_error >= past_max_error and we should have waited\n \/\/ 2 * past_max_error, but if the clock's error is reset between the two reads we might\n \/\/ have waited less time, but always more than 'past_max_error'.\n if (current_max_error >= past_max_error) {\n ASSERT_GE(delta.ToMicroseconds(), 2 * past_max_error);\n } else {\n ASSERT_GE(delta.ToMicroseconds(), past_max_error);\n }\n}\n\nTEST_F(HybridClockTest, TestIsAfter) {\n Timestamp ts1 = clock_->Now();\n ASSERT_TRUE(clock_->IsAfter(ts1));\n\n \/\/ Update the clock in the future, make sure it still\n \/\/ handles \"IsAfter\" properly even when it's running in\n \/\/ \"logical\" mode.\n Timestamp now_increased = HybridClock::TimestampFromMicroseconds(\n HybridClock::GetPhysicalValueMicros(ts1) + 1 * 1000 * 1000);\n ASSERT_OK(clock_->Update(now_increased));\n Timestamp ts2 = clock_->Now();\n\n ASSERT_TRUE(clock_->IsAfter(ts1));\n ASSERT_TRUE(clock_->IsAfter(ts2));\n}\n\n\/\/ Thread which loops polling the clock and updating it slightly\n\/\/ into the future.\nvoid StresserThread(HybridClock* clock, AtomicBool* stop) {\n Random rng(GetRandomSeed32());\n Timestamp prev(0);\n while (!stop->Load()) {\n Timestamp t = clock->Now();\n CHECK_GT(t.value(), prev.value());\n prev = t;\n\n \/\/ Add a random bit of offset to the clock, and perform an update.\n Timestamp new_ts = HybridClock::AddPhysicalTimeToTimestamp(\n t, MonoDelta::FromMicroseconds(rng.Uniform(10000)));\n CHECK_OK(clock->Update(new_ts));\n }\n}\n\n\/\/ Regression test for KUDU-953: if threads are updating and polling the\n\/\/ clock concurrently, the clock should still never run backwards.\nTEST_F(HybridClockTest, TestClockDoesntGoBackwardsWithUpdates) {\n vector> threads;\n AtomicBool stop(false);\n\n SCOPED_CLEANUP({\n stop.Store(true);\n for (const auto& t : threads) {\n t->Join();\n }\n });\n\n for (int i = 0; i < 4; i++) {\n scoped_refptr thread;\n ASSERT_OK(Thread::Create(\"test\", \"stresser\",\n &StresserThread, clock_.get(), &stop,\n &thread));\n threads.push_back(thread);\n }\n\n SleepFor(MonoDelta::FromSeconds(1));\n}\n\nTEST_F(HybridClockTest, TestGetPhysicalComponentDifference) {\n Timestamp now1 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(100, 100);\n SleepFor(MonoDelta::FromMilliseconds(1));\n Timestamp now2 = HybridClock::TimestampFromMicrosecondsAndLogicalValue(200, 0);\n MonoDelta delta = clock_->GetPhysicalComponentDifference(now2, now1);\n MonoDelta negative_delta = clock_->GetPhysicalComponentDifference(now1, now2);\n ASSERT_EQ(100, delta.ToMicroseconds());\n ASSERT_EQ(-100, negative_delta.ToMicroseconds());\n}\n\nTEST_F(HybridClockTest, TestRideOverNtpInterruption) {\n Timestamp timestamps[3];\n uint64_t max_error_usec[3];\n\n \/\/ Get the clock once, with a working NTP.\n clock_->NowWithError(×tamps[0], &max_error_usec[0]);\n\n \/\/ Try to read the clock again a second later, but with an error\n \/\/ injected. It should extrapolate from the first read.\n SleepFor(MonoDelta::FromSeconds(1));\n FLAGS_inject_unsync_time_errors = true;\n clock_->NowWithError(×tamps[1], &max_error_usec[1]);\n\n \/\/ The new clock reading should be a second or longer from the\n \/\/ first one, since SleepFor guarantees sleeping at least as long\n \/\/ as specified.\n MonoDelta phys_diff = clock_->GetPhysicalComponentDifference(\n timestamps[1], timestamps[0]);\n ASSERT_GE(phys_diff.ToSeconds(), 1);\n\n \/\/ The new clock reading should have higher error than the first.\n \/\/ The error should have increased based on the clock skew.\n int64_t error_diff = max_error_usec[1] - max_error_usec[0];\n ASSERT_NEAR(error_diff, clock_->time_service()->skew_ppm() * phys_diff.ToSeconds(),\n 10);\n\n \/\/ Now restore the ability to read the system clock, and\n \/\/ read it again.\n FLAGS_inject_unsync_time_errors = false;\n clock_->NowWithError(×tamps[2], &max_error_usec[2]);\n\n ASSERT_LT(timestamps[0].ToUint64(), timestamps[1].ToUint64());\n ASSERT_LT(timestamps[1].ToUint64(), timestamps[2].ToUint64());\n}\n\n#ifndef __APPLE__\nTEST_F(HybridClockTest, TestNtpDiagnostics) {\n vector log;\n clock_->time_service()->DumpDiagnostics(&log);\n string s = JoinStrings(log, \"\\n\");\n SCOPED_TRACE(s);\n ASSERT_STR_MATCHES(s, \"(ntp_gettime\\\\(\\\\) returns code |chronyc -n tracking)\");\n ASSERT_STR_MATCHES(s, \"(ntpq -n |chronyc -n sources)\");\n}\n#endif\n\n} \/\/ namespace clock\n} \/\/ namespace kudu\n<|endoftext|>"} {"text":"#include \n#include \n#include \"Myexception.h\"\n#include \"chain.h\"\n\n\nusing namespace std;\n\n\nvoid chain :: readAndStoreFromFile(char* fileName)\n{\n\t\/\/This function reads integers from the file given by fileName then store them in the chain\n\n\tifstream in;\n\tin.open(filename.c_str());\n\tif (!in) return; \/\/ file doesn't exist\n\n\tint line;\n\twhile(in >> line) {\n\t\tinsert(listSize, line);\n\t}\n\n\t\/*int line;\n\n\twhile(std::getline(data, line)) \n\t\tstd::stringstream str(line);\n\t\tstd::string text;\n\n\t\tstd::getline(str,text,'=');\n\n\t\tdouble value;\n\t\tstr >> value;\n\t}*\/\n\n}\n\n\n\nvoid chain :: eraseModuloValue(int theInt)\n{\n\t\/\/This function erases all the entries from the list which are multiple of theInt\n\n\tfor(int i=0; iget(i);\n \tif (value\/theInt > 0 && value != theInt) remove(i);\n\t}\n\n\n}\n\nvoid chain :: oddAndEvenOrdering()\n{\n\t\/\/This function reorders the list such a way that all odd numbers precede all even numbers. \n\t\/\/Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.\n\n\n\n\n}\n\nvoid chain :: reverse()\n{\n\t\/\/Reverses the list\n\n\n}\n\n \n\nchain :: chain(int initialCapacity)\n{\n\t\/\/Constructor\n\tif(initialCapacity < 1)\n\t{\n\t\tostringstream s;\n\t\ts << \"Initial capacity = \" << initialCapacity << \" Must be > 0\";\n\t\tthrow illegalParameterValue(s.str());\n\t}\n\t\n\tfirstNode = NULL;\n\tlistSize = 0;\n\n}\n\n\nchain :: ~chain()\n{\n\t\/\/Destructor. Delete all nodes in chain\n\t\n\twhile(firstNode != NULL)\n\t{\n\t\t\/\/delete firstNode\n\t\tchainNode* nextNode = firstNode->next;\n\t\tdelete firstNode;\n\t\tfirstNode = nextNode;\n\t\n\t}\n\t\n}\n\nint* chain :: get(int theIndex) const\n{\n\t\/\/Return element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn NULL;\n\t}\n\t\n\tchainNode* currentNode = firstNode;\n\tfor(int i=0;inext;\n\t\n\treturn ¤tNode->element;\n\n\n}\n\n\nint chain :: indexOf(const int& theElement) const\n{\n\t\/\/Return index of first occurrence of theElement.\n\t\/\/Return -1 of theElement not in list.\n\t\n\t\n\tchainNode* currentNode = firstNode;\n\tint index = 0;\n\twhile(currentNode != NULL && currentNode->element != theElement)\n\t{\n\t\t\/\/move to the next node\n\t\tcurrentNode = currentNode->next;\n\t\tindex++;\n\t\n\t}\n\t\n\t\n\t\/\/make sure we found matching element\n\tif(currentNode == NULL)\n\t\treturn -1;\n\n\telse\n\t\treturn index;\n\n}\n\n\nvoid chain :: erase(int theIndex)\n{\n\t\/\/Delete the element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\t\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tchainNode* deleteNode;\n\tif(theIndex == 0)\n\t{\n\t\t\/\/remove first node from chain\n\t\tdeleteNode = firstNode;\n\t\tfirstNode = firstNode->next;\n\n\t}\n\telse\n\t{\n\t\t\/\/use p to get to predecessor of desired node\n\t\tchainNode* p = firstNode;\n\t\tfor(int i=0;inext;\n\t\t\t\n\t\tdeleteNode = p->next;\n\t\tp->next = p->next->next; \/\/remove deleteNode from chain\n\t\n\t}\n\n\tlistSize--;\n\tdelete deleteNode;\n\n\n}\n\nvoid chain :: insert(int theIndex, const int& theElement)\n{\n\t\/\/Insert theElement so that its index is theIndex.\n\ttry{\n \t\tif (theIndex < 0 || theIndex > listSize)\n \t\t{\/\/ invalid index\n \t\t\n\t\t\tostringstream s;\n \t\t\ts << \"index = \" << theIndex << \" size = \" << listSize;\n \t\t\tthrow illegalIndex(s.str());\n\t\t}\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tif(theIndex == 0)\n\t\t\/\/insert at front\n\t\tfirstNode = new chainNode(theElement, firstNode);\n\telse\n\t{\n\t\tchainNode *p = firstNode;\n\t\tfor(int i=0;inext;\n\t\n\t\t\/\/insert after p\n\t\tp->next = new chainNode(theElement, p->next);\n\t\n\t\n\t}\n\n\tlistSize++;\n\n}\n\n\nvoid chain :: output() const\n{\n\t\/\/Put the list into the output.\n\n\tfor(int i=0;iget(i) << \" \";\n\tcout<= listSize){\n\t\tostringstream s;\n \t\ts << \"index = \" << theIndex << \" size = \" \n << listSize<<\", the input index is invalid\";\n \t\tthrow illegalIndex(s.str());\n\t}\n \n}\nUpdate chain.cpp#include \n#include \n#include \"Myexception.h\"\n#include \"chain.h\"\n\n\nusing namespace std;\n\n\nvoid chain :: readAndStoreFromFile(char* fileName)\n{\n\t\/\/This function reads integers from the file given by fileName then store them in the chain\n\n\t\/*ifstream in;\n\tifstream infile(\"input.txt\");\n\tstringstream \n\tin.open(filename.c_str());\n\tif (!in) return; \/\/ file doesn't exist\n\n\tint line;\n\twhile(in >> line) {\n\t\tinsert(listSize, line);\n\t}*\/\n\n\tifstream infile(fileName.c_str()) ;\n\tstring line;\n\n\twhile(getline(infile, line)) {\n\t\tistringstream iss(line);\n\t\tint n;\n\t\tiss > n;\n\t}\n\n\t\/*int line;\n\n\twhile(std::getline(data, line)) \n\t\tstd::stringstream str(line);\n\t\tstd::string text;\n\n\t\tstd::getline(str,text,'=');\n\n\t\tdouble value;\n\t\tstr >> value;\n\t}*\/\n\n}\n\n\n\nvoid chain :: eraseModuloValue(int theInt)\n{\n\t\/\/This function erases all the entries from the list which are multiple of theInt\n\n\tfor(int i=0; iget(i);\n \tif (value\/theInt > 0 && value != theInt) remove(i);\n\t}\n\n\n}\n\nvoid chain :: oddAndEvenOrdering()\n{\n\t\/\/This function reorders the list such a way that all odd numbers precede all even numbers. \n\t\/\/Note that for two odd (even) numbers i and j, the ordering between i and j should be intact after reordering.\n\n\n\n\n}\n\nvoid chain :: reverse()\n{\n\t\/\/Reverses the list\n\n\n}\n\n \n\nchain :: chain(int initialCapacity)\n{\n\t\/\/Constructor\n\tif(initialCapacity < 1)\n\t{\n\t\tostringstream s;\n\t\ts << \"Initial capacity = \" << initialCapacity << \" Must be > 0\";\n\t\tthrow illegalParameterValue(s.str());\n\t}\n\t\n\tfirstNode = NULL;\n\tlistSize = 0;\n\n}\n\n\nchain :: ~chain()\n{\n\t\/\/Destructor. Delete all nodes in chain\n\t\n\twhile(firstNode != NULL)\n\t{\n\t\t\/\/delete firstNode\n\t\tchainNode* nextNode = firstNode->next;\n\t\tdelete firstNode;\n\t\tfirstNode = nextNode;\n\t\n\t}\n\t\n}\n\nint* chain :: get(int theIndex) const\n{\n\t\/\/Return element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn NULL;\n\t}\n\t\n\tchainNode* currentNode = firstNode;\n\tfor(int i=0;inext;\n\t\n\treturn ¤tNode->element;\n\n\n}\n\n\nint chain :: indexOf(const int& theElement) const\n{\n\t\/\/Return index of first occurrence of theElement.\n\t\/\/Return -1 of theElement not in list.\n\t\n\t\n\tchainNode* currentNode = firstNode;\n\tint index = 0;\n\twhile(currentNode != NULL && currentNode->element != theElement)\n\t{\n\t\t\/\/move to the next node\n\t\tcurrentNode = currentNode->next;\n\t\tindex++;\n\t\n\t}\n\t\n\t\n\t\/\/make sure we found matching element\n\tif(currentNode == NULL)\n\t\treturn -1;\n\n\telse\n\t\treturn index;\n\n}\n\n\nvoid chain :: erase(int theIndex)\n{\n\t\/\/Delete the element whose index is theIndex.\n\t\/\/Throw illegalIndex exception if no such element.\n\t\n\ttry{\n\t\tcheckIndex(theIndex);\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tchainNode* deleteNode;\n\tif(theIndex == 0)\n\t{\n\t\t\/\/remove first node from chain\n\t\tdeleteNode = firstNode;\n\t\tfirstNode = firstNode->next;\n\n\t}\n\telse\n\t{\n\t\t\/\/use p to get to predecessor of desired node\n\t\tchainNode* p = firstNode;\n\t\tfor(int i=0;inext;\n\t\t\t\n\t\tdeleteNode = p->next;\n\t\tp->next = p->next->next; \/\/remove deleteNode from chain\n\t\n\t}\n\n\tlistSize--;\n\tdelete deleteNode;\n\n\n}\n\nvoid chain :: insert(int theIndex, const int& theElement)\n{\n\t\/\/Insert theElement so that its index is theIndex.\n\ttry{\n \t\tif (theIndex < 0 || theIndex > listSize)\n \t\t{\/\/ invalid index\n \t\t\n\t\t\tostringstream s;\n \t\t\ts << \"index = \" << theIndex << \" size = \" << listSize;\n \t\t\tthrow illegalIndex(s.str());\n\t\t}\n\t}\n\tcatch(illegalIndex &e){\n\t\te.outputMessage();\n\t\treturn;\n\t}\n\t\n\tif(theIndex == 0)\n\t\t\/\/insert at front\n\t\tfirstNode = new chainNode(theElement, firstNode);\n\telse\n\t{\n\t\tchainNode *p = firstNode;\n\t\tfor(int i=0;inext;\n\t\n\t\t\/\/insert after p\n\t\tp->next = new chainNode(theElement, p->next);\n\t\n\t\n\t}\n\n\tlistSize++;\n\n}\n\n\nvoid chain :: output() const\n{\n\t\/\/Put the list into the output.\n\n\tfor(int i=0;iget(i) << \" \";\n\tcout<= listSize){\n\t\tostringstream s;\n \t\ts << \"index = \" << theIndex << \" size = \" \n << listSize<<\", the input index is invalid\";\n \t\tthrow illegalIndex(s.str());\n\t}\n \n}\n<|endoftext|>"} {"text":"\/* descriptor.cpp\n\nCopyright (c) 2015, Nikolaj Schlej. All rights reserved.\nThis program and the accompanying materials\nare licensed and made available under the terms and conditions of the BSD License\nwhich accompanies this distribution. The full text of the license may be found at\nhttp:\/\/opensource.org\/licenses\/bsd-license.php\n\nTHE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\nWITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\n*\/\n\n#include \"descriptor.h\"\n\n\/\/ Calculate address of data structure addressed by descriptor address format\n\/\/ 8 bit base or limit\nconst UINT8* calculateAddress8(const UINT8* baseAddress, const UINT8 baseOrLimit)\n{\n return baseAddress + baseOrLimit * 0x10;\n}\n\n\/\/ 16 bit base or limit\nconst UINT8* calculateAddress16(const UINT8* baseAddress, const UINT16 baseOrLimit)\n{\n return baseAddress + baseOrLimit * 0x1000;\n}\n\n\/\/ Calculate offset of region using its base\nUINT32 calculateRegionOffset(const UINT16 base)\n{\n return base * 0x1000;\n}\n\n\/\/Calculate size of region using its base and limit\nUINT32 calculateRegionSize(const UINT16 base, const UINT16 limit)\n{\n if (limit)\n return (limit + 1 - base) * 0x1000;\n return 0;\n}\n\n\/\/ Return human-readable chip name for given JEDEC ID\nUString jedecIdToUString(UINT8 vendorId, UINT8 deviceId0, UINT8 deviceId1)\n{\n UINT32 jedecId = (UINT32)deviceId1 + ((UINT32)deviceId0 << 8) + ((UINT32)vendorId << 16);\n switch (jedecId) {\n \/\/ Winbond\n case 0xEF3013: return UString(\"Winbond W25X40\");\n case 0xEF3014: return UString(\"Winbond W25X80\");\n case 0xEF3015: return UString(\"Winbond W25X16\");\n case 0xEF3016: return UString(\"Winbond W25X32\");\n case 0xEF3017: return UString(\"Winbond W25X64\");\n case 0xEF4013: return UString(\"Winbond W25Q40\");\n case 0xEF4014: return UString(\"Winbond W25Q80\");\n case 0xEF4015: return UString(\"Winbond W25Q16\");\n case 0xEF4016: return UString(\"Winbond W25Q32\");\n case 0xEF4017: return UString(\"Winbond W25Q64\");\n case 0xEF4018: return UString(\"Winbond W25Q128\");\n case 0xEF4019: return UString(\"Winbond W25Q256\");\n case 0xEF6015: return UString(\"Winbond W25Q16\");\n case 0xEF6016: return UString(\"Winbond W25Q32\");\n case 0xEF6017: return UString(\"Winbond W25Q64\");\n case 0xEF6018: return UString(\"Winbond W25Q128\");\n\n \/\/ Macronix\n case 0xC22013: return UString(\"Macronix MX25L40\");\n case 0xC22014: return UString(\"Macronix MX25L80\");\n case 0xC22015: \n case 0xC22415:\n case 0xC22515: return UString(\"Macronix MX25L16\");\n case 0xC22016:\n case 0xC22535: return UString(\"Macronix MX25U16\");\n case 0xC22536: return UString(\"Macronix MX25U32\");\n case 0xC22537: return UString(\"Macronix MX25U64\");\n case 0xC22538: return UString(\"Macronix MX25U128\");\n case 0xC22539: return UString(\"Macronix MX25U256\");\n case 0xC25E16: return UString(\"Macronix MX25L32\");\n case 0xC22017: \n case 0xC29517: return UString(\"Macronix MX25L64\");\n case 0xC22018: return UString(\"Macronix MX25L128\");\n case 0xC22019: return UString(\"Macronix MX25L256\");\n \n \/\/ Micron\n case 0x202014: return UString(\"Micron M25P80\");\n case 0x202015: return UString(\"Micron M25P16\");\n case 0x202016: return UString(\"Micron M25P32\");\n case 0x202017: return UString(\"Micron M25P64\");\n case 0x202018: return UString(\"Micron M25P128\");\n case 0x204011: return UString(\"Micron M45PE10\");\n case 0x204012: return UString(\"Micron M45PE20\");\n case 0x204013: return UString(\"Micron M45PE40\");\n case 0x204014: return UString(\"Micron M45PE80\");\n case 0x204015: return UString(\"Micron M45PE16\");\n case 0x207114: return UString(\"Micron M25PX80\");\n case 0x207115: return UString(\"Micron M25PX16\");\n case 0x207116: return UString(\"Micron M25PX32\");\n case 0x207117: return UString(\"Micron M25PX64\");\n case 0x208011: return UString(\"Micron M25PE10\");\n case 0x208012: return UString(\"Micron M25PE20\");\n case 0x208013: return UString(\"Micron M25PE40\");\n case 0x208014: return UString(\"Micron M25PE80\");\n case 0x208015: return UString(\"Micron M25PE16\");\n case 0x20BA15: return UString(\"Micron N25Q016\");\n case 0x20BA16: return UString(\"Micron N25Q032\");\n case 0x20BA17: return UString(\"Micron N25Q064\");\n case 0x20BA18: return UString(\"Micron N25Q128\");\n case 0x20BA19: return UString(\"Micron N25Q256\");\n case 0x20BA20: return UString(\"Micron N25Q512\");\n case 0x20BA21: return UString(\"Micron N25Q00A\");\n case 0x20BB15: return UString(\"Micron N25Q016\");\n case 0x20BB16: return UString(\"Micron N25Q032\");\n case 0x20BB17: return UString(\"Micron N25Q064\");\n case 0x20BB18: return UString(\"Micron MT25Q128\");\n case 0x20BB19: return UString(\"Micron MT25Q256\");\n case 0x20BB20: return UString(\"Micron MT25Q512\");\n\n \/\/ Intel\n case 0x898911: return UString(\"Intel 25F160S33B8\");\n case 0x898912: return UString(\"Intel 25F320S33B8\");\n case 0x898913: return UString(\"Intel 25F640S33B8\");\n case 0x898915: return UString(\"Intel 25F160S33T8\");\n case 0x898916: return UString(\"Intel 25F320S33T8\");\n case 0x898917: return UString(\"Intel 25F640S33T8\");\n\n \/\/ Atmel\n case 0x1F4500: return UString(\"Atmel AT26DF081\");\n case 0x1F4501: return UString(\"Atmel AT26DF081A\");\n case 0x1F4502: return UString(\"Atmel AT25DF081\");\n case 0x1F4600: return UString(\"Atmel AT26DF161\");\n case 0x1F4601: return UString(\"Atmel AT26DF161A\");\n case 0x1F4602: return UString(\"Atmel AT25DF161\");\n case 0x1F8600: return UString(\"Atmel AT25DQ161\");\n case 0x1F4700: return UString(\"Atmel AT25DF321\");\n case 0x1F4701: return UString(\"Atmel AT25DF321A\");\n case 0x1F4800: return UString(\"Atmel AT25DF641\");\n case 0x1F8800: return UString(\"Atmel AT25DQ641\");\n\n \/\/ Microchip\n case 0xBF2541: return UString(\"Microchip SST25VF016B\");\n case 0xBF254A: return UString(\"Microchip SST25VF032B\");\n case 0xBF258D: return UString(\"Microchip SST25VF040B\");\n case 0xBF258E: return UString(\"Microchip SST25VF080B\");\n case 0xBF254B: return UString(\"Microchip SST25VF064C\");\n\n \/\/ EON\n case 0x1C3013: return UString(\"EON EN25Q40\");\n case 0x1C3014: return UString(\"EON EN25Q80\");\n case 0x1C3015: return UString(\"EON EN25Q16\");\n case 0x1C3016: return UString(\"EON EN25Q32\");\n case 0x1C3017: return UString(\"EON EN25Q64\");\n case 0x1C3018: return UString(\"EON EN25Q128\");\n case 0x1C3114: return UString(\"EON EN25F80\");\n case 0x1C3115: return UString(\"EON EN25F16\");\n case 0x1C3116: return UString(\"EON EN25F32\");\n case 0x1C3117: return UString(\"EON EN25F64\");\n case 0x1C7015: return UString(\"EON EN25QH16\");\n case 0x1C7016: return UString(\"EON EN25QH32\");\n case 0x1C7017: return UString(\"EON EN25QH64\");\n case 0x1C7018: return UString(\"EON EN25QH128\");\n case 0x1C7019: return UString(\"EON EN25QH256\");\n\n \/\/ GigaDevice\n case 0xC84014: return UString(\"GigaDevice GD25x80\");\n case 0xC84015: return UString(\"GigaDevice GD25x16\");\n case 0xC84016: return UString(\"GigaDevice GD25x32\");\n case 0xC84017: return UString(\"GigaDevice GD25x64\");\n case 0xC84018: return UString(\"GigaDevice GD25x128\");\n case 0xC86017: return UString(\"GigaDevice GD25Lx64\");\n case 0xC86018: return UString(\"GigaDevice GD25Lx128\");\n\n \/\/ Fidelix\n case 0xF83215: return UString(\"Fidelix FM25Q16\");\n case 0xF83216: return UString(\"Fidelix FM25Q32\");\n case 0xF83217: return UString(\"Fidelix FM25Q64\");\n case 0xF83218: return UString(\"Fidelix FM25Q128\");\n\n \/\/ Spansion\n case 0x014015: return UString(\"Spansion S25FL116K\");\n case 0x014016: return UString(\"Spansion S25FL132K\");\n case 0x014017: return UString(\"Spansion S25FL164K\");\n \n \/\/ Amic\n case 0x373015: return UString(\"Amic A25L016\");\n case 0x373016: return UString(\"Amic A25L032\");\n case 0x374016: return UString(\"Amic A25L032A\");\n\n \/\/ PMC\n case 0x9DF713: return UString(\"PMC Pm25LV080B\");\n case 0x9DF714: return UString(\"PMC Pm25LV016B\");\n case 0x9DF744: return UString(\"PMC Pm25LQ080C\");\n case 0x9DF745: return UString(\"PMC Pm25LQ016C\");\n case 0x9DF746: return UString(\"PMC Pm25LQ032C\");\n case 0x9DF77B: return UString(\"PMC Pm25LV512A\");\n case 0x9DF77C: return UString(\"PMC Pm25LV010A\");\n case 0x9DF77D: return UString(\"PMC Pm25LV020\");\n case 0x9DF77E: return UString(\"PMC Pm25LV040\");\n\n \/\/ ISSI\n case 0x9D6017: return UString(\"ISSI Ix25LP064\");\n case 0x9D6018: return UString(\"ISSI Ix25LP128\");\n case 0x9D7018: return UString(\"ISSI Ix25WP128\");\n }\n\n return UString(\"Unknown\");\n}\nAdd more chip IDs, thank you Google\/* descriptor.cpp\n\nCopyright (c) 2015, Nikolaj Schlej. All rights reserved.\nThis program and the accompanying materials\nare licensed and made available under the terms and conditions of the BSD License\nwhich accompanies this distribution. The full text of the license may be found at\nhttp:\/\/opensource.org\/licenses\/bsd-license.php\n\nTHE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS,\nWITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.\n*\/\n\n#include \"descriptor.h\"\n\n\/\/ Calculate address of data structure addressed by descriptor address format\n\/\/ 8 bit base or limit\nconst UINT8* calculateAddress8(const UINT8* baseAddress, const UINT8 baseOrLimit)\n{\n return baseAddress + baseOrLimit * 0x10;\n}\n\n\/\/ 16 bit base or limit\nconst UINT8* calculateAddress16(const UINT8* baseAddress, const UINT16 baseOrLimit)\n{\n return baseAddress + baseOrLimit * 0x1000;\n}\n\n\/\/ Calculate offset of region using its base\nUINT32 calculateRegionOffset(const UINT16 base)\n{\n return base * 0x1000;\n}\n\n\/\/Calculate size of region using its base and limit\nUINT32 calculateRegionSize(const UINT16 base, const UINT16 limit)\n{\n if (limit)\n return (limit + 1 - base) * 0x1000;\n return 0;\n}\n\n\/\/ Return human-readable chip name for given JEDEC ID\nUString jedecIdToUString(UINT8 vendorId, UINT8 deviceId0, UINT8 deviceId1)\n{\n UINT32 jedecId = (UINT32)deviceId1 + ((UINT32)deviceId0 << 8) + ((UINT32)vendorId << 16);\n switch (jedecId) {\n \/\/ Winbond\n case 0xEF3013: return UString(\"Winbond W25X40\");\n case 0xEF3014: return UString(\"Winbond W25X80\");\n case 0xEF3015: return UString(\"Winbond W25X16\");\n case 0xEF3016: return UString(\"Winbond W25X32\");\n case 0xEF3017: return UString(\"Winbond W25X64\");\n case 0xEF4013: return UString(\"Winbond W25Q40\");\n case 0xEF4014: return UString(\"Winbond W25Q80\");\n case 0xEF4015: return UString(\"Winbond W25Q16\");\n case 0xEF4016: return UString(\"Winbond W25Q32\");\n case 0xEF4017: return UString(\"Winbond W25Q64\");\n case 0xEF4018: return UString(\"Winbond W25Q128\");\n case 0xEF4019: return UString(\"Winbond W25Q256\");\n case 0xEF6011: return UString(\"Winbond W25Q10\");\n case 0xEF6012: return UString(\"Winbond W25Q20\");\n case 0xEF6013: return UString(\"Winbond W25Q40\");\n case 0xEF6014: return UString(\"Winbond W25Q80\");\n case 0xEF6015: return UString(\"Winbond W25Q16\");\n case 0xEF6016: return UString(\"Winbond W25Q32\");\n case 0xEF6017: return UString(\"Winbond W25Q64\");\n case 0xEF6018: return UString(\"Winbond W25Q128\");\n\n \/\/ Macronix\n case 0xC22013: return UString(\"Macronix MX25L40\");\n case 0xC22014: return UString(\"Macronix MX25L80\");\n case 0xC22015: \n case 0xC22415:\n case 0xC22515: return UString(\"Macronix MX25L16\");\n case 0xC22016:\n case 0xC22535: return UString(\"Macronix MX25U16\");\n case 0xC2201A: return UString(\"Macronix MX66L512\");\n case 0xC22536: return UString(\"Macronix MX25U32\");\n case 0xC22537: return UString(\"Macronix MX25U64\");\n case 0xC22538: return UString(\"Macronix MX25U128\");\n case 0xC22539: return UString(\"Macronix MX25U256\");\n case 0xC25E16: return UString(\"Macronix MX25L32\");\n case 0xC22017: \n case 0xC29517:\n case 0xC22617: return UString(\"Macronix MX25L64\");\n case 0xC22018:\n case 0xC22618: return UString(\"Macronix MX25L128\");\n case 0xC22019: return UString(\"Macronix MX25L256\");\n \n \/\/ Micron\n case 0x202014: return UString(\"Micron M25P80\");\n case 0x202015: return UString(\"Micron M25P16\");\n case 0x202016: return UString(\"Micron M25P32\");\n case 0x202017: return UString(\"Micron M25P64\");\n case 0x202018: return UString(\"Micron M25P128\");\n case 0x204011: return UString(\"Micron M45PE10\");\n case 0x204012: return UString(\"Micron M45PE20\");\n case 0x204013: return UString(\"Micron M45PE40\");\n case 0x204014: return UString(\"Micron M45PE80\");\n case 0x204015: return UString(\"Micron M45PE16\");\n case 0x207114: return UString(\"Micron M25PX80\");\n case 0x207115: return UString(\"Micron M25PX16\");\n case 0x207116: return UString(\"Micron M25PX32\");\n case 0x207117: return UString(\"Micron M25PX64\");\n case 0x208011: return UString(\"Micron M25PE10\");\n case 0x208012: return UString(\"Micron M25PE20\");\n case 0x208013: return UString(\"Micron M25PE40\");\n case 0x208014: return UString(\"Micron M25PE80\");\n case 0x208015: return UString(\"Micron M25PE16\");\n case 0x20BA15: return UString(\"Micron N25Q016\");\n case 0x20BA16: return UString(\"Micron N25Q032\");\n case 0x20BA17: return UString(\"Micron N25Q064\");\n case 0x20BA18: return UString(\"Micron N25Q128\");\n case 0x20BA19: return UString(\"Micron N25Q256\");\n case 0x20BA20: return UString(\"Micron N25Q512\");\n case 0x20BA21: return UString(\"Micron N25Q00A\");\n case 0x20BB15: return UString(\"Micron N25Q016\");\n case 0x20BB16: return UString(\"Micron N25Q032\");\n case 0x20BB17: return UString(\"Micron N25Q064\");\n case 0x20BB18: return UString(\"Micron MT25Q128\");\n case 0x20BB19: return UString(\"Micron MT25Q256\");\n case 0x20BB20: return UString(\"Micron MT25Q512\");\n\n \/\/ Intel\n case 0x898911: return UString(\"Intel 25F160S33B8\");\n case 0x898912: return UString(\"Intel 25F320S33B8\");\n case 0x898913: return UString(\"Intel 25F640S33B8\");\n case 0x898915: return UString(\"Intel 25F160S33T8\");\n case 0x898916: return UString(\"Intel 25F320S33T8\");\n case 0x898917: return UString(\"Intel 25F640S33T8\");\n\n \/\/ Atmel\n case 0x1F3217: return UString(\"Atmel AT25SF641\");\n case 0x1F4216: return UString(\"Atmel AT25SL321\");\n case 0x1F4218: return UString(\"Atmel AT25SL128A\");\n case 0x1F4317: return UString(\"Atmel AT25SL641\");\n case 0x1F4500: return UString(\"Atmel AT26DF081\");\n case 0x1F4501: return UString(\"Atmel AT26DF081A\");\n case 0x1F4502: return UString(\"Atmel AT25DF081\");\n case 0x1F4600: return UString(\"Atmel AT26DF161\");\n case 0x1F4601: return UString(\"Atmel AT26DF161A\");\n case 0x1F4602: return UString(\"Atmel AT25DF161\");\n case 0x1F8600: return UString(\"Atmel AT25DQ161\");\n case 0x1F4700: return UString(\"Atmel AT25DF321\");\n case 0x1F4701: return UString(\"Atmel AT25DF321A\");\n case 0x1F4800: return UString(\"Atmel AT25DF641\");\n case 0x1F8800: return UString(\"Atmel AT25DQ641\");\n\n \/\/ Microchip\n case 0xBF2541: return UString(\"Microchip SST25VF016B\");\n case 0xBF254A: return UString(\"Microchip SST25VF032B\");\n case 0xBF258D: return UString(\"Microchip SST25VF040B\");\n case 0xBF258E: return UString(\"Microchip SST25VF080B\");\n case 0xBF254B: return UString(\"Microchip SST25VF064C\");\n\n \/\/ EON\n case 0x1C3013: return UString(\"EON EN25Q40\");\n case 0x1C3014: return UString(\"EON EN25Q80\");\n case 0x1C3015: return UString(\"EON EN25Q16\");\n case 0x1C3016: return UString(\"EON EN25Q32\");\n case 0x1C3017: return UString(\"EON EN25Q64\");\n case 0x1C3018: return UString(\"EON EN25Q128\");\n case 0x1C3114: return UString(\"EON EN25F80\");\n case 0x1C3115: return UString(\"EON EN25F16\");\n case 0x1C3116: return UString(\"EON EN25F32\");\n case 0x1C3117: return UString(\"EON EN25F64\");\n case 0x1C7014: return UString(\"EON EN25QH80\");\n case 0x1C7015: return UString(\"EON EN25QH16\");\n case 0x1C7016: return UString(\"EON EN25QH32\");\n case 0x1C7017: return UString(\"EON EN25QH64\");\n case 0x1C7018: return UString(\"EON EN25QH128\");\n case 0x1C7019: return UString(\"EON EN25QH256\");\n\n \/\/ GigaDevice\n case 0xC84014: return UString(\"GigaDevice GD25x80\");\n case 0xC84015: return UString(\"GigaDevice GD25x16\");\n case 0xC84016: return UString(\"GigaDevice GD25x32\");\n case 0xC84017: return UString(\"GigaDevice GD25x64\");\n case 0xC84018: return UString(\"GigaDevice GD25x128\");\n case 0xC84019: return UString(\"GigaDevice GD25x256C\");\n case 0xC86017: return UString(\"GigaDevice GD25Lx64\");\n case 0xC86018: return UString(\"GigaDevice GD25Lx128\");\n case 0xC86019: return UString(\"GigaDevice GD25LQ256C\");\n\n \/\/ Fidelix\n case 0xF83215: return UString(\"Fidelix FM25Q16\");\n case 0xF83216: return UString(\"Fidelix FM25Q32\");\n case 0xF83217: return UString(\"Fidelix FM25Q64\");\n case 0xF83218: return UString(\"Fidelix FM25Q128\");\n\n \/\/ Spansion\n case 0x014015: return UString(\"Spansion S25FL116K\");\n case 0x014016: return UString(\"Spansion S25FL132K\");\n case 0x014017: return UString(\"Spansion S25FL164K\");\n \n \/\/ Amic\n case 0x373015: return UString(\"Amic A25L016\");\n case 0x373016: return UString(\"Amic A25L032\");\n case 0x374016: return UString(\"Amic A25L032A\");\n\n \/\/ PMC\n case 0x9DF713: return UString(\"PMC Pm25LV080B\");\n case 0x9DF714: return UString(\"PMC Pm25LV016B\");\n case 0x9DF744: return UString(\"PMC Pm25LQ080C\");\n case 0x9DF745: return UString(\"PMC Pm25LQ016C\");\n case 0x9DF746: return UString(\"PMC Pm25LQ032C\");\n case 0x9DF77B: return UString(\"PMC Pm25LV512A\");\n case 0x9DF77C: return UString(\"PMC Pm25LV010A\");\n case 0x9DF77D: return UString(\"PMC Pm25LV020\");\n case 0x9DF77E: return UString(\"PMC Pm25LV040\");\n\n \/\/ ISSI\n case 0x9D6017: return UString(\"ISSI Ix25LP064\");\n case 0x9D6018: return UString(\"ISSI Ix25LP128\");\n case 0x9D6019: return UString(\"ISSI Ix25LP256\");\n case 0x9D7017: return UString(\"ISSI Ix25WP064\");\n case 0x9D7018: return UString(\"ISSI Ix25WP128\");\n case 0x9D7019: return UString(\"ISSI Ix25WP256\");\n }\n\n return UString(\"Unknown\");\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"logging\/logger.h\"\n#include \"sequence\/io\/ptb_parser.h\"\n\nnamespace meta\n{\nnamespace sequence\n{\n\nstd::vector extract_sequences(const std::string& filename)\n{\n std::regex regex{\"=====+\\\\s*$\"};\n\n std::vector results;\n std::ifstream file{filename};\n std::string line;\n sequence seq;\n while (std::getline(file, line))\n {\n if (seq.size() > 0)\n {\n if (std::regex_match(line, regex))\n {\n results.emplace_back(std::move(seq));\n continue;\n }\n\n if (line.length() == 0)\n {\n if (seq[seq.size() - 1].tag() == tag_t{\".\"})\n results.emplace_back(std::move(seq));\n continue;\n }\n }\n\n std::stringstream ss{line};\n std::string word;\n while (ss >> word)\n {\n if (word == \"]\" || word == \"[\")\n continue;\n auto pos = word.rfind('\/');\n if (pos == word.npos)\n {\n LOG(warning) << \"could not find '\/' in word\/tag pair\" << ENDLG;\n continue;\n }\n auto sym = symbol_t{word.substr(0, pos)};\n auto tag = tag_t{word.substr(pos + 1)};\n seq.add_observation({sym, tag});\n }\n }\n if (seq.size() > 0)\n results.emplace_back(std::move(seq));\n\n return results;\n}\n\n}\n}\nFix bug where the regex was unused in extract_sequences.#include \n#include \n\n#include \"logging\/logger.h\"\n#include \"sequence\/io\/ptb_parser.h\"\n\nnamespace meta\n{\nnamespace sequence\n{\n\nstd::vector extract_sequences(const std::string& filename)\n{\n std::regex regex{\"=====+\\\\s*$\"};\n\n std::vector results;\n std::ifstream file{filename};\n std::string line;\n sequence seq;\n while (std::getline(file, line))\n {\n \/\/ blank line\n if (line.length() == 0)\n {\n if (seq.size() > 0)\n {\n if (seq[seq.size() - 1].tag() == tag_t{\".\"})\n results.emplace_back(std::move(seq));\n }\n continue;\n }\n\n \/\/ paragraph divider\n if (std::regex_match(line, regex))\n {\n if (seq.size() > 0)\n results.emplace_back(std::move(seq));\n continue;\n }\n\n std::stringstream ss{line};\n std::string word;\n while (ss >> word)\n {\n if (word == \"]\" || word == \"[\")\n continue;\n auto pos = word.rfind('\/');\n if (pos == word.npos)\n {\n LOG(warning) << \"could not find '\/' in word\/tag pair\" << ENDLG;\n LOG(warning) << \"word\/tag pair is: \" << word << ENDLG;\n continue;\n }\n auto sym = symbol_t{word.substr(0, pos)};\n auto tag = tag_t{word.substr(pos + 1)};\n seq.add_observation({sym, tag});\n }\n }\n if (seq.size() > 0)\n results.emplace_back(std::move(seq));\n\n return results;\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ shared_statement.cc for saw\n\/\/ Made by nicuveo \n\/\/\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Includes\n\n#include \n#include \"shared\/shared_statement.hh\"\n#include \"error.hh\"\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Implementation\n\nnamespace saw\n{\n\n\n \/\/ -tors\n\n SharedStatement::SharedStatement(Database db, const char* statement)\n : row_index_(-1)\n {\n check(db, sqlite3_prepare_v2(db.raw_data(), statement, -1, &data_, 0));\n resize(sqlite3_column_count(data_));\n }\n\n SharedStatement::~SharedStatement()\n {\n sqlite3_finalize(data_);\n }\n\n\n\n \/\/ mutators\n\n bool\n SharedStatement::step(const Statement& parent)\n {\n Database db = parent.database();\n\n row_invalidity_.raise();\n switch (sqlite3_step(data()))\n {\n case SQLITE_DONE:\n reset();\n return false;\n\n case SQLITE_ROW:\n row_ = Row(parent, ++row_index_, row_invalidity_);\n return true;\n\n default:\n check(db, reset());\n }\n\n return false;\n\n }\n\n int\n SharedStatement::reset()\n {\n row_ = Row();\n row_index_ = -1;\n return sqlite3_reset(data_);\n }\n\n\n\n \/\/ helpers\n\n std::string\n SharedStatement::fetch(int i) const\n {\n return sqlite3_column_name(data(), i);\n }\n\n\n\n}\nRemoved useless include.\/\/\n\/\/ shared_statement.cc for saw\n\/\/ Made by nicuveo \n\/\/\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Includes\n\n#include \"shared\/shared_statement.hh\"\n#include \"error.hh\"\n\n\n\n\/\/HHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH\n\/\/ Implementation\n\nnamespace saw\n{\n\n\n \/\/ -tors\n\n SharedStatement::SharedStatement(Database db, const char* statement)\n : row_index_(-1)\n {\n check(db, sqlite3_prepare_v2(db.raw_data(), statement, -1, &data_, 0));\n resize(sqlite3_column_count(data_));\n }\n\n SharedStatement::~SharedStatement()\n {\n sqlite3_finalize(data_);\n }\n\n\n\n \/\/ mutators\n\n bool\n SharedStatement::step(const Statement& parent)\n {\n Database db = parent.database();\n\n row_invalidity_.raise();\n switch (sqlite3_step(data()))\n {\n case SQLITE_DONE:\n reset();\n return false;\n\n case SQLITE_ROW:\n row_ = Row(parent, ++row_index_, row_invalidity_);\n return true;\n\n default:\n check(db, reset());\n }\n\n return false;\n\n }\n\n int\n SharedStatement::reset()\n {\n row_ = Row();\n row_index_ = -1;\n return sqlite3_reset(data_);\n }\n\n\n\n \/\/ helpers\n\n std::string\n SharedStatement::fetch(int i) const\n {\n return sqlite3_column_name(data(), i);\n }\n\n\n\n}\n<|endoftext|>"} {"text":"#include \"ys_sockdata.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ys {\n\nsock_module::sock_module(char* host, int port) {\n struct sockaddr_in local;\n bzero(&local, sizeof(local));\n local.sin_family = AF_INET;\n local.sin_port = htons(port);\n inet_pton(AF_INET, host, &local.sin_addr);\n if ((listen.sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {\n return -1;\n }\n if (-1 == bind(lsock, (struct sockaddr*)&local, sizeof(local))) {\n return -1;\n }\n if (-1 == listen(lsock, LISTEN_NUM)) {\n return -1;\n }\n listen.sock = lsock;\n listen.pos = -1;\n listen.close = 0;\n connList = 0;\n}\n\nsock_module::~sock_module() {\n\n}\n\nvoid sock_module::prepare(struct pollfd *psock, int& nsock) {\n connect_meta* p = connList;\n int pos = nsock;\n if (!listen.close) {\n psock[pos].fd = listen.sock;\n listen.pos = pos;\n psock[pos++].events = POLLIN;\n }\n while (p) {\n if (p->close) {\n\t\t\tp = p->link;\n\t\t\tcontinue;\n\t\t}\n\t\tpsock[pos].fd = p->sock;\n p->pos = pos;\n psock[pos].events = POLLERR | POLLHUP;\n\t\tpthread_mutex_lock(&p->lock);\n\t\tif (p->getStateCanRead()) {\n\t\t\tpsock[pos].events |= POLLIN;\n\t\t}\n\t\tif (p->getStateCanWrite()) {\n\t\t\tpsock[pos].events |= POLLOUT;\n\t\t}\n\t\tpos ++;\n p = p->link;\n }\n nsock = pos;\n}\n\nvoid sock_module::process(struct pollfd *psock) {\n\tprocessL(psock);\n\tprocessC(psock);\n}\n\nvoid sock_module::processL(struct pollfd * psock) {\n\tif (listen.pos < 0 || !(psock[listen.pos] & POLLIN)) {\n\t\treturn;\n\t}\n int dsock = accept(listen.sock, (struct sockaddr*)0, 0);\n if (dsock < 0) {\n printf (\"error!\\n\");\n }\n else {\n connect_meta* tmp = new connect_meta();\n tmp->sock = dsock;\n tmp->pos = -1;\n\t\ttmp->close = 0;\n\t\ttmp->state = 0;\n\t\ttmp->setStateCanRead();\n\t\ttmp->setStateCanWrite();\n tmp->link = connList;\n connList->link = tmp;\n }\n}\n\nvoid sock_module::processC(struct pollfd * psodk) {\n\tconnect_meta *cusor = connList;\n\twhile (cusor) {\n\t\tif (cusor->pos < 0) {\n\t\t\tcusor = cusor->link;\n\t\t\tcontinue;\n\t\t}\n\t\tif (psodk[cusor->pos].revents & POLLERR ||\n\t\t\tpsodk[cusor->pos].revents & POLLHUP) {\n\t\t\tclose (cusor->sock);\n\t\t\tcusor->close = 1;\n\t\t}\n\t\tif (psodk[cusor->pos].revents\n\t\tif (psodk[cusor->pos].revents & POLLIN) {\n\t\t\tcusor->setStateNoRead();\n\t\t\treadEvent event = new readEvent();\n\t\t\tevent->args = (void*)cusor;\n\t\t\t\/\/ TODO\n\t\t}\n\t\tif (psodk[cusor->pos].revents & POLLOUT) {\n\t\t\tcusor->setStateNoWrite();\n\t\t\twriteEvent event = new writeEvent();\n\t\t\tevent->args = (void*)cusor;\n\t\t\t\/\/ TODO\n\t\t}\n\t\tcusor = cusor->link;\n\t}\n\n\tconnect_meta **delcusor = connList;\n\twhile (*delcusor) {\n\t\tif (1 == (*delcusor)->close) {\n\t\t\tconnect_meta *tmp = *delcusor;\n\t\t\t*delcusor = (*delcusor)->link;\n\t\t\tdelete tmp;\n\t\t}\n\t\telse {\n\t\t\tdelcusor = &(*delcusor)->link;\n\t\t}\n\t}\n}\n\n}\n\n\nformat#include \"ys_sockdata.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace ys {\n\nsock_module::sock_module(char* host, int port) {\n struct sockaddr_in local;\n bzero(&local, sizeof(local));\n local.sin_family = AF_INET;\n local.sin_port = htons(port);\n inet_pton(AF_INET, host, &local.sin_addr);\n if ((listen.sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {\n return -1;\n }\n if (-1 == bind(lsock, (struct sockaddr*)&local, sizeof(local))) {\n return -1;\n }\n if (-1 == listen(lsock, LISTEN_NUM)) {\n return -1;\n }\n listen.sock = lsock;\n listen.pos = -1;\n listen.close = 0;\n connList = 0;\n}\n\nsock_module::~sock_module() {\n\n}\n\nvoid sock_module::prepare(struct pollfd *psock, int& nsock) {\n connect_meta* p = connList;\n int pos = nsock;\n if (!listen.close) {\n psock[pos].fd = listen.sock;\n listen.pos = pos;\n psock[pos++].events = POLLIN;\n }\n while (p) {\n if (p->close) {\n p = p->link;\n continue;\n\t\t}\n psock[pos].fd = p->sock;\n p->pos = pos;\n psock[pos].events = POLLERR | POLLHUP;\n pthread_mutex_lock(&p->lock);\n if (p->getStateCanRead()) {\n psock[pos].events |= POLLIN;\n }\n if (p->getStateCanWrite()) {\n psock[pos].events |= POLLOUT;\n }\n pos ++;\n p = p->link;\n }\n nsock = pos;\n}\n\nvoid sock_module::process(struct pollfd *psock) {\n processL(psock);\n processC(psock);\n}\n\nvoid sock_module::processL(struct pollfd * psock) {\n if (listen.pos < 0 || !(psock[listen.pos] & POLLIN)) {\n return;\n }\n int dsock = accept(listen.sock, (struct sockaddr*)0, 0);\n if (dsock < 0) {\n printf (\"error!\\n\");\n }\n else {\n connect_meta* tmp = new connect_meta();\n tmp->sock = dsock;\n tmp->pos = -1;\n tmp->close = 0;\n tmp->state = 0;\n tmp->setStateCanRead();\n tmp->setStateCanWrite();\n tmp->link = connList;\n connList->link = tmp;\n }\n}\n\nvoid sock_module::processC(struct pollfd * psodk) {\n connect_meta *cusor = connList;\n while (cusor) {\n if (cusor->pos < 0) {\n cusor = cusor->link;\n continue;\n }\n if (psodk[cusor->pos].revents & POLLERR ||\n psodk[cusor->pos].revents & POLLHUP) {\n close (cusor->sock);\n cusor->close = 1;\n\t\t}\n if (psodk[cusor->pos].revents & POLLIN) {\n cusor->setStateNoRead();\n readEvent event = new readEvent();\n event->args = (void*)cusor;\n \/\/ TODO\n\t\t}\n if (psodk[cusor->pos].revents & POLLOUT) {\n cusor->setStateNoWrite();\n writeEvent event = new writeEvent();\n event->args = (void*)cusor;\n \/\/ TODO\n }\n cusor = cusor->link;\n }\n\n connect_meta **delcusor = connList;\n while (*delcusor) {\n if (1 == (*delcusor)->close) {\n connect_meta *tmp = *delcusor;\n *delcusor = (*delcusor)->link;\n delete tmp;\n }\n else {\n delcusor = &(*delcusor)->link;\n }\n }\n}\n\n}\n\n\n<|endoftext|>"} {"text":"#include \"start_game_state.hpp\"\n\n#include \"game_state.hpp\"\n#include \"main_menu_state.hpp\"\n#include \"logger.hpp\"\n#include \"exception.hpp\"\n\n\nstatic boost::log::sources::severity_logger lg;\n\nnamespace Quoridor {\n\nstd::string StartGameState::name_(\"Start Game\");\n\nStartGameState::StartGameState(std::shared_ptr stm)\n : stm_(stm), player_types_(), player_num_(2)\n{\n win_ = std::shared_ptr(\n CEGUI::WindowManager::getSingleton().\n loadLayoutFromFile(\"start_game.layout\"),\n [=](CEGUI::Window *w) {\n BOOST_LOG_SEV(lg, boost::log::trivial::debug) << \"removing window \" << w;\n CEGUI::WindowManager::getSingleton().destroyWindow(w);\n }\n );\n\n init_player_num_();\n\n subscribe_for_events_();\n\n player_types_.push_back(\"fake\");\n player_types_.push_back(\"fake\");\n}\n\nStartGameState::~StartGameState()\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::debug) << \"destroying state \" << name_;\n}\n\nstd::shared_ptr StartGameState::window() const\n{\n return win_;\n}\n\nconst std::string &StartGameState::name() const\n{\n return name_;\n}\n\nvoid StartGameState::init_player_num_()\n{\n CEGUI::Combobox *cbpn = static_cast(win_->getChild(\"playerNum\"));\n\n std::vector> num_str_list = {\n {2, \"two players\"},\n {4, \"four players\"}\n };\n for (auto num : num_str_list) {\n auto item = new CEGUI::ListboxTextItem(num.second);\n item->setUserData(reinterpret_cast(num.first));\n cbpn->addItem(item);\n }\n\n if (auto item = cbpn->getListboxItemFromIndex(0)) {\n cbpn->setItemSelectState(item, true);\n update_player_num_();\n }\n else {\n throw Exception(\"failed to set player number\");\n }\n}\n\nint StartGameState::update_player_num_()\n{\n CEGUI::Combobox *cbpn = static_cast(win_->getChild(\"playerNum\"));\n if (auto item = cbpn->getSelectedItem()) {\n player_num_ = reinterpret_cast(item->getUserData());\n BOOST_LOG_SEV(lg, boost::log::trivial::info)\n << \"set player number to \" << player_num_;\n set_player_list_();\n return 0;\n }\n return -1;\n}\n\nvoid StartGameState::set_player_list_()\n{\n CEGUI::DefaultWindow *plist_win = static_cast(\n win_->getChild(\"playerList\"));\n for (size_t i = 0; i < player_num_; ++i) {\n auto ptype_win = CEGUI::WindowManager::getSingleton().createWindow(\"GlossySerpent\/Combobox\");\n ptype_win->setPosition(CEGUI::UVector2(\n CEGUI::UDim(0, 20),\n CEGUI::UDim(0.1 * i, 0)));\n ptype_win->setSize(CEGUI::USize(\n CEGUI::UDim(0.5, 20),\n CEGUI::UDim(0.8, 0)));\n plist_win->addChild(ptype_win);\n }\n}\n\nvoid StartGameState::subscribe_for_events_()\n{\n win_->getChild(\"startGame\")->subscribeEvent(\n CEGUI::Window::EventMouseClick,\n CEGUI::Event::Subscriber(\n &StartGameState::handle_start_game_, this\n )\n );\n win_->getChild(\"returnToMainMenu\")->subscribeEvent(\n CEGUI::Window::EventMouseClick,\n CEGUI::Event::Subscriber(\n &StartGameState::handle_return_, this\n )\n );\n win_->getChild(\"playerNum\")->subscribeEvent(\n CEGUI::Combobox::EventListSelectionAccepted,\n CEGUI::Event::Subscriber(\n &StartGameState::handle_player_num_, this\n )\n );\n}\n\nbool StartGameState::handle_start_game_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"starting game\";\n stm_->change_state(std::shared_ptr(new GameState(stm_, player_types_)));\n return true;\n}\n\nbool StartGameState::handle_return_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"returning to main menu\";\n stm_->change_state(std::shared_ptr(new MainMenuState(stm_)));\n return true;\n}\n\nbool StartGameState::handle_player_num_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"changing player number\";\n if (update_player_num_() == 0) {\n return true;\n }\n return false;\n}\n\n} \/* namespace Quoridor *\/\nSet player types empty on init#include \"start_game_state.hpp\"\n\n#include \"game_state.hpp\"\n#include \"main_menu_state.hpp\"\n#include \"logger.hpp\"\n#include \"exception.hpp\"\n\n\nstatic boost::log::sources::severity_logger lg;\n\nnamespace Quoridor {\n\nstd::string StartGameState::name_(\"Start Game\");\n\nStartGameState::StartGameState(std::shared_ptr stm)\n : stm_(stm), player_types_(), player_num_(0)\n{\n win_ = std::shared_ptr(\n CEGUI::WindowManager::getSingleton().\n loadLayoutFromFile(\"start_game.layout\"),\n [=](CEGUI::Window *w) {\n BOOST_LOG_SEV(lg, boost::log::trivial::debug) << \"removing window \" << w;\n CEGUI::WindowManager::getSingleton().destroyWindow(w);\n }\n );\n\n init_player_num_();\n\n subscribe_for_events_();\n}\n\nStartGameState::~StartGameState()\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::debug) << \"destroying state \" << name_;\n}\n\nstd::shared_ptr StartGameState::window() const\n{\n return win_;\n}\n\nconst std::string &StartGameState::name() const\n{\n return name_;\n}\n\nvoid StartGameState::init_player_num_()\n{\n CEGUI::Combobox *cbpn = static_cast(win_->getChild(\"playerNum\"));\n\n std::vector> num_str_list = {\n {2, \"two players\"},\n {4, \"four players\"}\n };\n for (auto num : num_str_list) {\n auto item = new CEGUI::ListboxTextItem(num.second);\n item->setUserData(reinterpret_cast(num.first));\n cbpn->addItem(item);\n }\n\n if (auto item = cbpn->getListboxItemFromIndex(0)) {\n cbpn->setItemSelectState(item, true);\n update_player_num_();\n }\n else {\n throw Exception(\"failed to set player number\");\n }\n}\n\nint StartGameState::update_player_num_()\n{\n CEGUI::Combobox *cbpn = static_cast(win_->getChild(\"playerNum\"));\n if (auto item = cbpn->getSelectedItem()) {\n player_num_ = reinterpret_cast(item->getUserData());\n BOOST_LOG_SEV(lg, boost::log::trivial::info)\n << \"set player number to \" << player_num_;\n set_player_list_();\n return 0;\n }\n return -1;\n}\n\nvoid StartGameState::set_player_list_()\n{\n CEGUI::DefaultWindow *plist_win = static_cast(\n win_->getChild(\"playerList\"));\n for (size_t i = 0; i < player_num_; ++i) {\n auto ptype_win = CEGUI::WindowManager::getSingleton().createWindow(\"GlossySerpent\/Combobox\");\n ptype_win->setPosition(CEGUI::UVector2(\n CEGUI::UDim(0, 20),\n CEGUI::UDim(0.1 * i, 0)));\n ptype_win->setSize(CEGUI::USize(\n CEGUI::UDim(0.5, 20),\n CEGUI::UDim(0.8, 0)));\n plist_win->addChild(ptype_win);\n }\n}\n\nvoid StartGameState::subscribe_for_events_()\n{\n win_->getChild(\"startGame\")->subscribeEvent(\n CEGUI::Window::EventMouseClick,\n CEGUI::Event::Subscriber(\n &StartGameState::handle_start_game_, this\n )\n );\n win_->getChild(\"returnToMainMenu\")->subscribeEvent(\n CEGUI::Window::EventMouseClick,\n CEGUI::Event::Subscriber(\n &StartGameState::handle_return_, this\n )\n );\n win_->getChild(\"playerNum\")->subscribeEvent(\n CEGUI::Combobox::EventListSelectionAccepted,\n CEGUI::Event::Subscriber(\n &StartGameState::handle_player_num_, this\n )\n );\n}\n\nbool StartGameState::handle_start_game_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"starting game\";\n stm_->change_state(std::shared_ptr(new GameState(stm_, player_types_)));\n return true;\n}\n\nbool StartGameState::handle_return_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"returning to main menu\";\n stm_->change_state(std::shared_ptr(new MainMenuState(stm_)));\n return true;\n}\n\nbool StartGameState::handle_player_num_(const CEGUI::EventArgs &\/* e *\/)\n{\n BOOST_LOG_SEV(lg, boost::log::trivial::info) << \"changing player number\";\n if (update_player_num_() == 0) {\n return true;\n }\n return false;\n}\n\n} \/* namespace Quoridor *\/\n<|endoftext|>"} {"text":"\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 2012 Unvanquished Developers\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see .\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n#include \n#include \"client.h\"\n#include \"rocket.h\"\n#include \"..\/qcommon\/q_unicode.h\"\n\nusing namespace Rocket::Core::Input;\n\nstatic std::map< int, int > keyMap;\nstatic bool init = false;\n\nvoid Rocket_InitKeys( void )\n{\n\tkeyMap[ K_TAB ] = KI_TAB;\n\tkeyMap[ K_ENTER ] = KI_RETURN;\n\tkeyMap[ K_ESCAPE ] = KI_ESCAPE;\n\tkeyMap[ K_SPACE ] = KI_SPACE;\n\n\tkeyMap[ K_BACKSPACE ] = KI_BACK;\n\n\tkeyMap[ K_COMMAND ] = KI_LWIN;\n\tkeyMap[ K_CAPSLOCK ] = KI_CAPITAL;\n\tkeyMap[ K_POWER ] = KI_POWER;\n\tkeyMap[ K_PAUSE ] = KI_PAUSE;\n\n\tkeyMap[ K_UPARROW ] = KI_UP;\n\tkeyMap[ K_DOWNARROW ] = KI_DOWN;\n\tkeyMap[ K_LEFTARROW ] = KI_LEFT;\n\tkeyMap[ K_RIGHTARROW ] = KI_RIGHT;\n\n\tkeyMap[ K_ALT ] = KI_LMETA;\n\tkeyMap[ K_CTRL ] = KI_LCONTROL;\n\tkeyMap[ K_SHIFT ] = KI_LSHIFT;\n\tkeyMap[ K_INS ] = KI_INSERT;\n\tkeyMap[ K_DEL ] = KI_DELETE;\n\tkeyMap[ K_PGDN ] = KI_NEXT;\n\tkeyMap[ K_PGUP ] = KI_PRIOR;\n\tkeyMap[ K_HOME ] = KI_HOME;\n\tkeyMap[ K_END ] = KI_END;\n\n\tkeyMap[ K_F1 ] = KI_F1;\n\tkeyMap[ K_F2 ] = KI_F2;\n\tkeyMap[ K_F3 ] = KI_F3;\n\tkeyMap[ K_F4 ] = KI_F4;\n\tkeyMap[ K_F5 ] = KI_F5;\n\tkeyMap[ K_F6 ] = KI_F6;\n\tkeyMap[ K_F7 ] = KI_F7;\n\tkeyMap[ K_F8 ] = KI_F8;\n\tkeyMap[ K_F9 ] = KI_F9;\n\tkeyMap[ K_F10 ] = KI_F10;\n\tkeyMap[ K_F11 ] = KI_F11;\n\tkeyMap[ K_F12 ] = KI_F12;\n\tkeyMap[ K_F13 ] = KI_F13;\n\tkeyMap[ K_F14 ] = KI_F14;\n\tkeyMap[ K_F15 ] = KI_F15;\n\n\tkeyMap[ K_KP_HOME ] = KI_NUMPAD7;\n\tkeyMap[ K_KP_UPARROW ] = KI_NUMPAD8;\n\tkeyMap[ K_KP_PGUP ] = KI_NUMPAD9;\n\tkeyMap[ K_KP_LEFTARROW ] = KI_NUMPAD4;\n\tkeyMap[ K_KP_5 ] = KI_NUMPAD5;\n\tkeyMap[ K_KP_RIGHTARROW ] = KI_NUMPAD6;\n\tkeyMap[ K_KP_END ] = KI_NUMPAD1;\n\tkeyMap[ K_KP_DOWNARROW ] = KI_NUMPAD2;\n\tkeyMap[ K_KP_PGDN ] = KI_NUMPAD3;\n\tkeyMap[ K_KP_ENTER ] = KI_NUMPADENTER;\n\tkeyMap[ K_KP_INS ] = KI_NUMPAD0;\n\tkeyMap[ K_KP_DEL ] = KI_DECIMAL;\n\tkeyMap[ K_KP_SLASH ] = KI_DIVIDE;\n\tkeyMap[ K_KP_MINUS ] = KI_SUBTRACT;\n\tkeyMap[ K_KP_PLUS ] = KI_ADD;\n\tkeyMap[ K_KP_NUMLOCK ] = KI_NUMLOCK;\n\tkeyMap[ K_KP_STAR ] = KI_MULTIPLY;\n\/\/ \tkeyMap[ K_KP_EQUALS ] = KI_KP_EQUALS;\n\n\tkeyMap[ K_SUPER ] = KI_LWIN;\n\/\/ \tkeyMap[ K_COMPOSE ] = KI_COMPOSE;\n\/\/ \tkeyMap[ K_MODE ] = KI_MODE;\n\tkeyMap[ K_HELP ] = KI_HELP;\n\tkeyMap[ K_PRINT ] = KI_PRINT;\n\/\/ \tkeyMap[ K_SYSREQ ] = KI_SYSREQ;\n\tkeyMap[ K_SCROLLOCK ] = KI_SCROLL;\n\/\/ \tkeyMap[ K_BREAK ] = KI_BREAK;\n\tkeyMap[ K_MENU ] = KI_APPS;\n\/\/ \tkeyMap[ K_EURO ] = KI_EURO;\n\/\/ \tkeyMap[ K_UNDO ] = KI_UNDO;\n\n\t\/\/ Corresponds to 0 - 9\n\tfor ( int i = '0'; i < '9' + 1; ++i )\n\t{\n\t\tkeyMap[ i ] = KI_0 + ( i - '0' );\n\t}\n\n\t\/\/ Corresponds to a - z\n\tfor ( int i = 'a'; i < 'z' + 1; ++i )\n\t{\n\t\tkeyMap[ i ] = KI_A + ( i - 'a' );\n\t}\n\n\n\t\/\/ Other keyMap that out of ascii order and are handled separately\n\tkeyMap[ ';' ] = KI_OEM_1; \/\/ US standard keyboard; the ';:' key.\n\tkeyMap[ '=' ] = KI_OEM_PLUS; \/\/ Any region; the '=+' key.\n\tkeyMap[ ',' ] = KI_OEM_COMMA; \/\/ Any region; the ',<' key.\n\tkeyMap[ '-' ] = KI_OEM_MINUS; \/\/ Any region; the '-_' key.\n\tkeyMap[ '.' ] = KI_OEM_PERIOD; \/\/ Any region; the '.>' key.\n\tkeyMap[ '\/' ] = KI_OEM_2; \/\/ Any region; the '\/?' key.\n\tkeyMap[ '`' ] = KI_OEM_3; \/\/ Any region; the '`~' key.\n\tkeyMap[ K_CONSOLE ] = KI_OEM_3;\n\n\tkeyMap[ '[' ] = KI_OEM_4; \/\/ US standard keyboard; the '[{' key.\n\tkeyMap[ '\\\\' ] = KI_OEM_5; \/\/ US standard keyboard; the '\\|' key.\n\tkeyMap[ ']' ] = KI_OEM_6; \/\/ US standard keyboard; the ']}' key.\n\tkeyMap[ '\\'' ] = KI_OEM_7; \/\/ US standard keyboard; the ''\"' key.\n\n\tinit = true;\n}\n\nKeyIdentifier Rocket_FromQuake( int key )\n{\n\tif ( !init )\n\t{\n\t\tCom_Log( LOG_WARN, \"Tried to convert keyMap before key array initialized.\" );\n\t\treturn KI_UNKNOWN;\n\t}\n\tstd::map< int, int >::iterator it;\n\tit = keyMap.find( key );\n\tif ( it != keyMap.end() )\n\t{\n\t\treturn static_cast< KeyIdentifier >( it->second );\n\t}\n\n\tCom_Logf( LOG_WARN, \"Rocket_FromQuake: Could not find keynum %d\", key );\n\treturn KI_UNKNOWN;\n}\n\nkeyNum_t Rocket_ToQuake( int key )\n{\n\tif ( !init )\n\t{\n\t\tCom_Log( LOG_WARN, \"Tried to convert keyMap before key array initialized.\" );\n\t\treturn K_NONE;\n\t}\n\tstd::map< int, int >::iterator it;\n\tfor ( it = keyMap.begin(); it != keyMap.end(); ++it )\n\t{\n\t\tif ( it->second == key )\n\t\t{\n\t\t\treturn static_cast< keyNum_t>( it->first );\n\t\t}\n\t}\n\n\tCom_Logf( LOG_WARN, \"Rocket_ToQuake: Could not find keynum %d\", key );\n\treturn K_NONE;\n}\n\nKeyModifier Rocket_GetKeyModifiers( void )\n{\n\tint mod = 0;\n\n\tif ( Key_IsDown( K_CTRL ) )\n\t{\n\t\tmod |= KM_CTRL;\n\t}\n\tif ( Key_IsDown( K_SHIFT ) )\n\t{\n\t\tmod |= KM_SHIFT;\n\t}\n\tif ( Key_IsDown( K_ALT ) )\n\t{\n\t\tmod |= KM_ALT;\n\t}\n\tif ( Key_IsDown( K_SUPER ) )\n\t{\n\t\tmod |= KM_META;\n\t}\n\tif ( Key_IsDown( K_CAPSLOCK ) )\n\t{\n\t\tmod |= KM_CAPSLOCK;\n\t}\n\tif ( Sys_IsNumLockDown() )\n\t{\n\t\tmod |= KM_NUMLOCK;\n\t}\n\n\treturn static_cast< KeyModifier >( mod );\n}\n\nvoid Rocket_ProcessMouseClick( int button, qboolean down )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )\n\t{\n\t\treturn;\n\t}\n\n\tint idx = 0;\n\tif ( button <= K_MOUSE5 )\n\t{\n\t\tidx = button - K_MOUSE1;\n\t}\n\telse\n\t{\n\t\tidx = button - K_AUX1 + 5; \/\/ Start at 5 because of K_MOUSE5\n\t}\n\n\tif ( down )\n\t{\n\t\tmenuContext->ProcessMouseButtonDown( idx, Rocket_GetKeyModifiers() );\n\t}\n\telse\n\t{\n\t\tmenuContext->ProcessMouseButtonUp( idx, Rocket_GetKeyModifiers() );\n\t}\n}\n\n#define MOUSEWHEEL_DELTA 5\nvoid Rocket_ProcessKeyInput( int key, qboolean down )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Our input system sends mouse events as key presses.\n\tif ( ( key >= K_MOUSE1 && key <= K_MOUSE5 ) || ( key >= K_AUX1 && key <= K_AUX16 ) )\n\t{\n\t\tRocket_ProcessMouseClick( key, down );\n\t\treturn;\n\t}\n\n\tif ( ( key == K_MWHEELDOWN || key == K_MWHEELUP ) )\n\t{\n\t\t\/\/ Our input system sends an up event right after a down event\n\t\t\/\/ We only want to catch one of these.\n\t\tif ( !down )\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tmenuContext->ProcessMouseWheel( key == K_MWHEELDOWN ? MOUSEWHEEL_DELTA : -MOUSEWHEEL_DELTA, Rocket_GetKeyModifiers() );\n\t\treturn;\n\t}\n\tif ( down )\n\t{\n\t\tmenuContext->ProcessKeyDown( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );\n\t}\n\telse\n\t{\n\t\tmenuContext->ProcessKeyUp( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );\n\t}\n}\n\nint utf8_to_ucs2( const unsigned char *input )\n{\n\tif ( input[0] == 0 )\n\t\treturn -1;\n\n\tif ( input[0] < 0x80 )\n\t{\n\t\treturn input[0];\n\t}\n\n\tif ( ( input[0] & 0xE0 ) == 0xE0 )\n\t{\n\t\tif ( input[1] == 0 || input[2] == 0 )\n\t\t\treturn -1;\n\n\t\treturn\n\t\t ( input[0] & 0x0F ) << 12 |\n\t\t ( input[1] & 0x3F ) << 6 |\n\t\t ( input[2] & 0x3F );\n\t}\n\n\tif ( ( input[0] & 0xC0 ) == 0xC0 )\n\t{\n\t\tif ( input[1] == 0 )\n\t\t\treturn -1;\n\n\t\treturn\n\t\t ( input[0] & 0x1F ) << 6 |\n\t\t ( input[1] & 0x3F );\n\t}\n\n\treturn -1;\n}\n\n\nvoid Rocket_ProcessTextInput( int key )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/\n\t\/\/ ignore any non printable chars\n\t\/\/\n\tconst char *s = Q_UTF8_Unstore( key );\n\tif ( ( unsigned char )*s < 32 || ( unsigned char )*s == 0x7f )\n\t{\n\t\treturn;\n\t}\n\n\tmenuContext->ProcessTextInput( utf8_to_ucs2( ( unsigned char* )s ) );\n}\n\nvoid Rocket_MouseMove( int x, int y )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE )\n\t{\n\t\treturn;\n\t}\n\n\tmenuContext->ProcessMouseMove( x, y, Rocket_GetKeyModifiers() );\n}\nDon't inject input to rocket when it doesn't have focus\/*\n===========================================================================\n\nDaemon GPL Source Code\nCopyright (C) 2012 Unvanquished Developers\n\nThis file is part of the Daemon GPL Source Code (Daemon Source Code).\n\nDaemon Source Code is free software: you can redistribute it and\/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nDaemon Source Code is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with Daemon Source Code. If not, see .\n\nIn addition, the Daemon Source Code is also subject to certain additional terms.\nYou should have received a copy of these additional terms immediately following the\nterms and conditions of the GNU General Public License which accompanied the Daemon\nSource Code. If not, please request a copy in writing from id Software at the address\nbelow.\n\nIf you have questions concerning this license or the applicable additional terms, you\nmay contact in writing id Software LLC, c\/o ZeniMax Media Inc., Suite 120, Rockville,\nMaryland 20850 USA.\n\n===========================================================================\n*\/\n#include \n#include \"client.h\"\n#include \"rocket.h\"\n#include \"..\/qcommon\/q_unicode.h\"\n\nusing namespace Rocket::Core::Input;\n\nstatic std::map< int, int > keyMap;\nstatic bool init = false;\n\nvoid Rocket_InitKeys( void )\n{\n\tkeyMap[ K_TAB ] = KI_TAB;\n\tkeyMap[ K_ENTER ] = KI_RETURN;\n\tkeyMap[ K_ESCAPE ] = KI_ESCAPE;\n\tkeyMap[ K_SPACE ] = KI_SPACE;\n\n\tkeyMap[ K_BACKSPACE ] = KI_BACK;\n\n\tkeyMap[ K_COMMAND ] = KI_LWIN;\n\tkeyMap[ K_CAPSLOCK ] = KI_CAPITAL;\n\tkeyMap[ K_POWER ] = KI_POWER;\n\tkeyMap[ K_PAUSE ] = KI_PAUSE;\n\n\tkeyMap[ K_UPARROW ] = KI_UP;\n\tkeyMap[ K_DOWNARROW ] = KI_DOWN;\n\tkeyMap[ K_LEFTARROW ] = KI_LEFT;\n\tkeyMap[ K_RIGHTARROW ] = KI_RIGHT;\n\n\tkeyMap[ K_ALT ] = KI_LMETA;\n\tkeyMap[ K_CTRL ] = KI_LCONTROL;\n\tkeyMap[ K_SHIFT ] = KI_LSHIFT;\n\tkeyMap[ K_INS ] = KI_INSERT;\n\tkeyMap[ K_DEL ] = KI_DELETE;\n\tkeyMap[ K_PGDN ] = KI_NEXT;\n\tkeyMap[ K_PGUP ] = KI_PRIOR;\n\tkeyMap[ K_HOME ] = KI_HOME;\n\tkeyMap[ K_END ] = KI_END;\n\n\tkeyMap[ K_F1 ] = KI_F1;\n\tkeyMap[ K_F2 ] = KI_F2;\n\tkeyMap[ K_F3 ] = KI_F3;\n\tkeyMap[ K_F4 ] = KI_F4;\n\tkeyMap[ K_F5 ] = KI_F5;\n\tkeyMap[ K_F6 ] = KI_F6;\n\tkeyMap[ K_F7 ] = KI_F7;\n\tkeyMap[ K_F8 ] = KI_F8;\n\tkeyMap[ K_F9 ] = KI_F9;\n\tkeyMap[ K_F10 ] = KI_F10;\n\tkeyMap[ K_F11 ] = KI_F11;\n\tkeyMap[ K_F12 ] = KI_F12;\n\tkeyMap[ K_F13 ] = KI_F13;\n\tkeyMap[ K_F14 ] = KI_F14;\n\tkeyMap[ K_F15 ] = KI_F15;\n\n\tkeyMap[ K_KP_HOME ] = KI_NUMPAD7;\n\tkeyMap[ K_KP_UPARROW ] = KI_NUMPAD8;\n\tkeyMap[ K_KP_PGUP ] = KI_NUMPAD9;\n\tkeyMap[ K_KP_LEFTARROW ] = KI_NUMPAD4;\n\tkeyMap[ K_KP_5 ] = KI_NUMPAD5;\n\tkeyMap[ K_KP_RIGHTARROW ] = KI_NUMPAD6;\n\tkeyMap[ K_KP_END ] = KI_NUMPAD1;\n\tkeyMap[ K_KP_DOWNARROW ] = KI_NUMPAD2;\n\tkeyMap[ K_KP_PGDN ] = KI_NUMPAD3;\n\tkeyMap[ K_KP_ENTER ] = KI_NUMPADENTER;\n\tkeyMap[ K_KP_INS ] = KI_NUMPAD0;\n\tkeyMap[ K_KP_DEL ] = KI_DECIMAL;\n\tkeyMap[ K_KP_SLASH ] = KI_DIVIDE;\n\tkeyMap[ K_KP_MINUS ] = KI_SUBTRACT;\n\tkeyMap[ K_KP_PLUS ] = KI_ADD;\n\tkeyMap[ K_KP_NUMLOCK ] = KI_NUMLOCK;\n\tkeyMap[ K_KP_STAR ] = KI_MULTIPLY;\n\/\/ \tkeyMap[ K_KP_EQUALS ] = KI_KP_EQUALS;\n\n\tkeyMap[ K_SUPER ] = KI_LWIN;\n\/\/ \tkeyMap[ K_COMPOSE ] = KI_COMPOSE;\n\/\/ \tkeyMap[ K_MODE ] = KI_MODE;\n\tkeyMap[ K_HELP ] = KI_HELP;\n\tkeyMap[ K_PRINT ] = KI_PRINT;\n\/\/ \tkeyMap[ K_SYSREQ ] = KI_SYSREQ;\n\tkeyMap[ K_SCROLLOCK ] = KI_SCROLL;\n\/\/ \tkeyMap[ K_BREAK ] = KI_BREAK;\n\tkeyMap[ K_MENU ] = KI_APPS;\n\/\/ \tkeyMap[ K_EURO ] = KI_EURO;\n\/\/ \tkeyMap[ K_UNDO ] = KI_UNDO;\n\n\t\/\/ Corresponds to 0 - 9\n\tfor ( int i = '0'; i < '9' + 1; ++i )\n\t{\n\t\tkeyMap[ i ] = KI_0 + ( i - '0' );\n\t}\n\n\t\/\/ Corresponds to a - z\n\tfor ( int i = 'a'; i < 'z' + 1; ++i )\n\t{\n\t\tkeyMap[ i ] = KI_A + ( i - 'a' );\n\t}\n\n\n\t\/\/ Other keyMap that out of ascii order and are handled separately\n\tkeyMap[ ';' ] = KI_OEM_1; \/\/ US standard keyboard; the ';:' key.\n\tkeyMap[ '=' ] = KI_OEM_PLUS; \/\/ Any region; the '=+' key.\n\tkeyMap[ ',' ] = KI_OEM_COMMA; \/\/ Any region; the ',<' key.\n\tkeyMap[ '-' ] = KI_OEM_MINUS; \/\/ Any region; the '-_' key.\n\tkeyMap[ '.' ] = KI_OEM_PERIOD; \/\/ Any region; the '.>' key.\n\tkeyMap[ '\/' ] = KI_OEM_2; \/\/ Any region; the '\/?' key.\n\tkeyMap[ '`' ] = KI_OEM_3; \/\/ Any region; the '`~' key.\n\tkeyMap[ K_CONSOLE ] = KI_OEM_3;\n\n\tkeyMap[ '[' ] = KI_OEM_4; \/\/ US standard keyboard; the '[{' key.\n\tkeyMap[ '\\\\' ] = KI_OEM_5; \/\/ US standard keyboard; the '\\|' key.\n\tkeyMap[ ']' ] = KI_OEM_6; \/\/ US standard keyboard; the ']}' key.\n\tkeyMap[ '\\'' ] = KI_OEM_7; \/\/ US standard keyboard; the ''\"' key.\n\n\tinit = true;\n}\n\nKeyIdentifier Rocket_FromQuake( int key )\n{\n\tif ( !init )\n\t{\n\t\tCom_Log( LOG_WARN, \"Tried to convert keyMap before key array initialized.\" );\n\t\treturn KI_UNKNOWN;\n\t}\n\tstd::map< int, int >::iterator it;\n\tit = keyMap.find( key );\n\tif ( it != keyMap.end() )\n\t{\n\t\treturn static_cast< KeyIdentifier >( it->second );\n\t}\n\n\tCom_Logf( LOG_WARN, \"Rocket_FromQuake: Could not find keynum %d\", key );\n\treturn KI_UNKNOWN;\n}\n\nkeyNum_t Rocket_ToQuake( int key )\n{\n\tif ( !init )\n\t{\n\t\tCom_Log( LOG_WARN, \"Tried to convert keyMap before key array initialized.\" );\n\t\treturn K_NONE;\n\t}\n\tstd::map< int, int >::iterator it;\n\tfor ( it = keyMap.begin(); it != keyMap.end(); ++it )\n\t{\n\t\tif ( it->second == key )\n\t\t{\n\t\t\treturn static_cast< keyNum_t>( it->first );\n\t\t}\n\t}\n\n\tCom_Logf( LOG_WARN, \"Rocket_ToQuake: Could not find keynum %d\", key );\n\treturn K_NONE;\n}\n\nKeyModifier Rocket_GetKeyModifiers( void )\n{\n\tint mod = 0;\n\n\tif ( Key_IsDown( K_CTRL ) )\n\t{\n\t\tmod |= KM_CTRL;\n\t}\n\tif ( Key_IsDown( K_SHIFT ) )\n\t{\n\t\tmod |= KM_SHIFT;\n\t}\n\tif ( Key_IsDown( K_ALT ) )\n\t{\n\t\tmod |= KM_ALT;\n\t}\n\tif ( Key_IsDown( K_SUPER ) )\n\t{\n\t\tmod |= KM_META;\n\t}\n\tif ( Key_IsDown( K_CAPSLOCK ) )\n\t{\n\t\tmod |= KM_CAPSLOCK;\n\t}\n\tif ( Sys_IsNumLockDown() )\n\t{\n\t\tmod |= KM_NUMLOCK;\n\t}\n\n\treturn static_cast< KeyModifier >( mod );\n}\n\nvoid Rocket_ProcessMouseClick( int button, qboolean down )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )\n\t{\n\t\treturn;\n\t}\n\n\tint idx = 0;\n\tif ( button <= K_MOUSE5 )\n\t{\n\t\tidx = button - K_MOUSE1;\n\t}\n\telse\n\t{\n\t\tidx = button - K_AUX1 + 5; \/\/ Start at 5 because of K_MOUSE5\n\t}\n\n\tif ( down )\n\t{\n\t\tmenuContext->ProcessMouseButtonDown( idx, Rocket_GetKeyModifiers() );\n\t}\n\telse\n\t{\n\t\tmenuContext->ProcessMouseButtonUp( idx, Rocket_GetKeyModifiers() );\n\t}\n}\n\n#define MOUSEWHEEL_DELTA 5\nvoid Rocket_ProcessKeyInput( int key, qboolean down )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/ Our input system sends mouse events as key presses.\n\tif ( ( key >= K_MOUSE1 && key <= K_MOUSE5 ) || ( key >= K_AUX1 && key <= K_AUX16 ) )\n\t{\n\t\tRocket_ProcessMouseClick( key, down );\n\t\treturn;\n\t}\n\n\tif ( ( key == K_MWHEELDOWN || key == K_MWHEELUP ) )\n\t{\n\t\t\/\/ Our input system sends an up event right after a down event\n\t\t\/\/ We only want to catch one of these.\n\t\tif ( !down )\n\t\t{\n\t\t\treturn;\n\t\t}\n\n\t\tmenuContext->ProcessMouseWheel( key == K_MWHEELDOWN ? MOUSEWHEEL_DELTA : -MOUSEWHEEL_DELTA, Rocket_GetKeyModifiers() );\n\t\treturn;\n\t}\n\tif ( down )\n\t{\n\t\tmenuContext->ProcessKeyDown( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );\n\t}\n\telse\n\t{\n\t\tmenuContext->ProcessKeyUp( Rocket_FromQuake( key ), Rocket_GetKeyModifiers() );\n\t}\n}\n\nint utf8_to_ucs2( const unsigned char *input )\n{\n\tif ( input[0] == 0 )\n\t\treturn -1;\n\n\tif ( input[0] < 0x80 )\n\t{\n\t\treturn input[0];\n\t}\n\n\tif ( ( input[0] & 0xE0 ) == 0xE0 )\n\t{\n\t\tif ( input[1] == 0 || input[2] == 0 )\n\t\t\treturn -1;\n\n\t\treturn\n\t\t ( input[0] & 0x0F ) << 12 |\n\t\t ( input[1] & 0x3F ) << 6 |\n\t\t ( input[2] & 0x3F );\n\t}\n\n\tif ( ( input[0] & 0xC0 ) == 0xC0 )\n\t{\n\t\tif ( input[1] == 0 )\n\t\t\treturn -1;\n\n\t\treturn\n\t\t ( input[0] & 0x1F ) << 6 |\n\t\t ( input[1] & 0x3F );\n\t}\n\n\treturn -1;\n}\n\n\nvoid Rocket_ProcessTextInput( int key )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )\n\t{\n\t\treturn;\n\t}\n\n\t\/\/\n\t\/\/ ignore any non printable chars\n\t\/\/\n\tconst char *s = Q_UTF8_Unstore( key );\n\tif ( ( unsigned char )*s < 32 || ( unsigned char )*s == 0x7f )\n\t{\n\t\treturn;\n\t}\n\n\tmenuContext->ProcessTextInput( utf8_to_ucs2( ( unsigned char* )s ) );\n}\n\nvoid Rocket_MouseMove( int x, int y )\n{\n\tif ( !menuContext || cls.keyCatchers & KEYCATCH_CONSOLE || !cls.keyCatchers )\n\t{\n\t\treturn;\n\t}\n\n\tmenuContext->ProcessMouseMove( x, y, Rocket_GetKeyModifiers() );\n}\n<|endoftext|>"} {"text":"\/\/\r\n\/\/ Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/ accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#ifndef OPENCLAM_FOR_EACH_HPP_INCLUDED\r\n#define OPENCLAM_FOR_EACH_HPP_INCLUDED\r\n\r\n#include \"kernel.hpp\"\r\n#include \r\n\r\nnamespace openclam\r\n{\r\nnamespace detail\r\n{\r\n template< class RandomAccessIterator, class Kernel >\r\n void for_each_dispatch( RandomAccessIterator& first, RandomAccessIterator& last, Kernel& k, std::random_access_iterator_tag )\r\n {\r\n k( &*first, std::distance( first, last ) );\r\n }\r\n\r\n template< class InputIterator, class Kernel >\r\n void for_each_dispatch( InputIterator& first, InputIterator& last, Kernel& k, std::input_iterator_tag )\r\n {\r\n std::vector< InputIterator::value_type* > data_references;\r\n std::vector< InputIterator::value_type > data;\r\n for( ; first != last; ++first )\r\n {\r\n data.push_back( *first );\r\n data_references.push_back( &*first );\r\n }\r\n k( &data[ 0 ], data.size() );\r\n for( unsigned int i = 0; i < data.size(); ++i )\r\n *data_references[ i ] = data[ i ];\r\n }\r\n}\r\n\r\n template< class InputIterator, class Kernel >\r\n void for_each( InputIterator first, InputIterator last, Kernel& k )\r\n {\r\n typename std::iterator_traits< InputIterator >::iterator_category category;\r\n detail::for_each_dispatch( first, last, k, category );\r\n }\r\n}\r\n\r\n#endif \/\/ #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED\r\nclean up\/\/\r\n\/\/ Copyright Silvin Lubecki 2010\r\n\/\/\r\n\/\/ Distributed under the Boost Software License, Version 1.0. (See\r\n\/\/ accompanying file LICENSE_1_0.txt or copy at\r\n\/\/ http:\/\/www.boost.org\/LICENSE_1_0.txt)\r\n\/\/\r\n\r\n#ifndef OPENCLAM_FOR_EACH_HPP_INCLUDED\r\n#define OPENCLAM_FOR_EACH_HPP_INCLUDED\r\n\r\n#include \r\n\r\nnamespace openclam\r\n{\r\nnamespace detail\r\n{\r\n template< class RandomAccessIterator, class Kernel >\r\n void for_each_dispatch( RandomAccessIterator& first, RandomAccessIterator& last, Kernel& k, std::random_access_iterator_tag )\r\n {\r\n k( &*first, std::distance( first, last ) );\r\n }\r\n\r\n template< class InputIterator, class Kernel >\r\n void for_each_dispatch( InputIterator& first, InputIterator& last, Kernel& k, std::input_iterator_tag )\r\n {\r\n std::vector< InputIterator::value_type* > data_references;\r\n std::vector< InputIterator::value_type > data;\r\n for( ; first != last; ++first )\r\n {\r\n data.push_back( *first );\r\n data_references.push_back( &*first );\r\n }\r\n k( &data[ 0 ], data.size() );\r\n for( unsigned int i = 0; i < data.size(); ++i )\r\n *data_references[ i ] = data[ i ];\r\n }\r\n}\r\n\r\n template< class InputIterator, class Kernel >\r\n void for_each( InputIterator first, InputIterator last, Kernel& k )\r\n {\r\n typename std::iterator_traits< InputIterator >::iterator_category category;\r\n detail::for_each_dispatch( first, last, k, category );\r\n }\r\n}\r\n\r\n#endif \/\/ #ifndef OPENCLAM_CONTEXT_HPP_INCLUDED\r\n<|endoftext|>"} {"text":"\/**\n * Copyright (c) 2016 DeepCortex GmbH \n * Authors:\n * - Paul Asmuth \n * - Laura Schlimmer \n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \n#include \n#include \n\n#include \"eventql\/eventql.h\"\n\nnamespace csql {\n\nJoinNode::JoinNode(\n JoinType join_type,\n RefPtr base_table,\n RefPtr joined_table) :\n join_type_(join_type),\n base_table_(base_table),\n joined_table_(joined_table) {\n addChild(&base_table_);\n addChild(&joined_table_);\n}\n\nJoinNode::JoinNode(\n JoinType join_type,\n RefPtr base_table,\n RefPtr joined_table,\n Vector> select_list,\n Option> where_expr,\n Option> join_cond) :\n join_type_(join_type),\n base_table_(base_table),\n joined_table_(joined_table),\n select_list_(select_list),\n where_expr_(where_expr),\n join_cond_(join_cond) {\n for (const auto& sl : select_list_) {\n column_names_.emplace_back(sl->columnName());\n }\n\n addChild(&base_table_);\n addChild(&joined_table_);\n}\n\nJoinNode::JoinNode(\n const JoinNode& other) :\n join_type_(other.join_type_),\n base_table_(other.base_table_->deepCopy()),\n joined_table_(other.joined_table_->deepCopy()),\n input_map_(other.input_map_),\n column_names_(other.column_names_),\n join_cond_(other.join_cond_) {\n for (const auto& e : other.select_list_) {\n select_list_.emplace_back(e->deepCopyAs());\n }\n\n if (!other.where_expr_.isEmpty()) {\n where_expr_ = Some(\n other.where_expr_.get()->deepCopyAs());\n }\n\n addChild(&base_table_);\n addChild(&joined_table_);\n}\n\nJoinType JoinNode::joinType() const {\n return join_type_;\n}\n\nRefPtr JoinNode::baseTable() const {\n return base_table_;\n}\n\nRefPtr JoinNode::joinedTable() const {\n return joined_table_;\n}\n\nVector> JoinNode::selectList() const {\n return select_list_;\n}\n\nVector JoinNode::getResultColumns() const {\n return column_names_;\n}\n\nVector JoinNode::getAvailableColumns() const {\n Vector cols;\n\n for (const auto& c :\n base_table_.asInstanceOf()->getAvailableColumns()) {\n cols.emplace_back(c);\n }\n\n for (const auto& c :\n joined_table_.asInstanceOf()->getAvailableColumns()) {\n cols.emplace_back(c);\n }\n\n return cols;\n}\n\nsize_t JoinNode::getComputedColumnIndex(\n const String& column_name,\n bool allow_add \/* = false *\/) {\n for (int i = 0; i < column_names_.size(); ++i) {\n if (column_names_[i] == column_name) {\n return i;\n }\n }\n\n auto input_idx = getInputColumnIndex(column_name);\n if (input_idx != size_t(-1)) {\n auto slnode = new SelectListNode(\n new ColumnReferenceNode(input_idx, getInputColumnType(input_idx)));\n slnode->setAlias(column_name);\n select_list_.emplace_back(slnode);\n return select_list_.size() - 1;\n }\n\n return -1; \/\/ FIXME\n}\n\nsize_t JoinNode::getNumComputedColumns() const {\n return select_list_.size();\n}\n\nSType JoinNode::getColumnType(size_t idx) const {\n assert(idx < select_list_.size());\n return select_list_[idx]->expression()->getReturnType();\n}\n\nsize_t JoinNode::getInputColumnIndex(\n const String& column_name,\n bool allow_add \/* = false *\/) {\n for (int i = 0; i < input_map_.size(); ++i) {\n if (input_map_[i].column == column_name) {\n return i;\n }\n }\n\n auto base_table_idx = base_table_\n .asInstanceOf()\n ->getComputedColumnIndex(column_name, allow_add);\n\n auto joined_table_idx = joined_table_\n .asInstanceOf()\n ->getComputedColumnIndex(column_name, allow_add);\n\n if (base_table_idx != size_t(-1) && joined_table_idx != size_t(-1)) {\n RAISEF(\n kRuntimeError,\n \"ambiguous column reference: '$0'\",\n column_name);\n }\n\n if (base_table_idx != size_t(-1)) {\n input_map_.emplace_back(InputColumnRef{\n .column = column_name,\n .table_idx = 0,\n .column_idx = base_table_idx\n });\n\n return input_map_.size() - 1;\n }\n\n if (joined_table_idx != size_t(-1)) {\n input_map_.emplace_back(InputColumnRef{\n .column = column_name,\n .table_idx = 1,\n .column_idx = joined_table_idx\n });\n\n return input_map_.size() - 1;\n }\n\n return -1;\n}\n\nOption> JoinNode::whereExpression() const {\n return where_expr_;\n}\n\nOption> JoinNode::joinCondition() const {\n return join_cond_;\n}\n\nRefPtr JoinNode::deepCopy() const {\n return new JoinNode(*this);\n}\n\nconst Vector& JoinNode::inputColumnMap() const {\n return input_map_;\n}\n\nString JoinNode::toString() const {\n auto str = StringUtil::format(\n \"(join (base-table $0) (joined-table $0) (select-list\",\n base_table_->toString(),\n joined_table_->toString());\n\n for (const auto& e : select_list_) {\n str += \" \" + e->toString();\n }\n str += \")\";\n\n if (!where_expr_.isEmpty()) {\n str += StringUtil::format(\" (where $0)\", where_expr_.get()->toString());\n }\n\n if (!join_cond_.isEmpty()) {\n str += StringUtil::format(\" (join-cond $0)\", join_cond_.get()->toString());\n }\n\n str += \")\";\n return str;\n};\n\nvoid JoinNode::encode(\n QueryTreeCoder* coder,\n const JoinNode& node,\n OutputStream* os) {\n os->appendUInt8((uint8_t) node.join_type_);\n\n os->appendVarUInt(node.select_list_.size());\n for (const auto& e : node.select_list_) {\n coder->encode(e.get(), os);\n }\n\n uint8_t flags = 0;\n if (!node.where_expr_.isEmpty()) {\n flags |= kHasWhereExprFlag;\n }\n if (!node.join_cond_.isEmpty()) {\n flags |= kHasJoinExprFlag;\n }\n\n os->appendUInt8(flags);\n\n if (!node.where_expr_.isEmpty()) {\n coder->encode(node.where_expr_.get().get(), os);\n }\n\n if (!node.join_cond_.isEmpty()) {\n coder->encode(node.join_cond_.get().get(), os);\n }\n\n coder->encode(node.base_table_.get(), os);\n coder->encode(node.joined_table_.get(), os);\n}\n\nRefPtr JoinNode::decode (\n QueryTreeCoder* coder,\n InputStream* is) {\n auto join_type = (JoinType) is->readUInt8();\n\n Vector> select_list;\n auto select_list_size = is->readVarUInt();\n for (auto i = 0; i < select_list_size; ++i) {\n select_list.emplace_back(coder->decode(is).asInstanceOf());\n }\n\n Option> where_expr;\n Option> join_cond;\n auto flags = is->readUInt8();\n\n if ((flags & kHasWhereExprFlag) > 0) {\n where_expr = coder->decode(is).asInstanceOf();\n }\n\n if ((flags & kHasJoinExprFlag) > 0) {\n join_cond = coder->decode(is).asInstanceOf();\n }\n\n auto base_tbl = coder->decode(is);\n auto joined_tbl = coder->decode(is);\n\n return new JoinNode(\n join_type,\n base_tbl,\n joined_tbl,\n select_list,\n where_expr,\n join_cond);\n}\n\n} \/\/ namespace csql\n\nimplement new JoinNode methods\/**\n * Copyright (c) 2016 DeepCortex GmbH \n * Authors:\n * - Paul Asmuth \n * - Laura Schlimmer \n *\n * This program is free software: you can redistribute it and\/or modify it under\n * the terms of the GNU Affero General Public License (\"the license\") as\n * published by the Free Software Foundation, either version 3 of the License,\n * or any later version.\n *\n * In accordance with Section 7(e) of the license, the licensing of the Program\n * under the license does not imply a trademark license. Therefore any rights,\n * title and interest in our trademarks remain entirely with us.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n * FOR A PARTICULAR PURPOSE. See the license for more details.\n *\n * You can be released from the requirements of the license by purchasing a\n * commercial license. Buying such a license is mandatory as soon as you develop\n * commercial activities involving this program without disclosing the source\n * code of your own applications\n *\/\n#include \n#include \n#include \n\n#include \"eventql\/eventql.h\"\n\nnamespace csql {\n\nJoinNode::JoinNode(\n JoinType join_type,\n RefPtr base_table,\n RefPtr joined_table) :\n join_type_(join_type),\n base_table_(base_table),\n joined_table_(joined_table) {\n addChild(&base_table_);\n addChild(&joined_table_);\n}\n\nJoinNode::JoinNode(\n JoinType join_type,\n RefPtr base_table,\n RefPtr joined_table,\n Vector> select_list,\n Option> where_expr,\n Option> join_cond) :\n join_type_(join_type),\n base_table_(base_table),\n joined_table_(joined_table),\n select_list_(select_list),\n where_expr_(where_expr),\n join_cond_(join_cond) {\n for (const auto& sl : select_list_) {\n column_names_.emplace_back(sl->columnName());\n }\n\n addChild(&base_table_);\n addChild(&joined_table_);\n}\n\nJoinNode::JoinNode(\n const JoinNode& other) :\n join_type_(other.join_type_),\n base_table_(other.base_table_->deepCopy()),\n joined_table_(other.joined_table_->deepCopy()),\n input_map_(other.input_map_),\n column_names_(other.column_names_),\n join_cond_(other.join_cond_) {\n for (const auto& e : other.select_list_) {\n select_list_.emplace_back(e->deepCopyAs());\n }\n\n if (!other.where_expr_.isEmpty()) {\n where_expr_ = Some(\n other.where_expr_.get()->deepCopyAs());\n }\n\n addChild(&base_table_);\n addChild(&joined_table_);\n}\n\nJoinType JoinNode::joinType() const {\n return join_type_;\n}\n\nvoid JoinNode::setJoinType(JoinType type) {\n join_type_ = type;\n}\n\nRefPtr JoinNode::baseTable() const {\n return base_table_;\n}\n\nRefPtr JoinNode::joinedTable() const {\n return joined_table_;\n}\n\nVector> JoinNode::selectList() const {\n return select_list_;\n}\n\nvoid JoinNode::addSelectList(RefPtr sl) {\n column_names_.emplace_back(sl->columnName());\n select_list_.emplace_back(sl);\n}\n\nVector JoinNode::getResultColumns() const {\n return column_names_;\n}\n\nVector JoinNode::getAvailableColumns() const {\n Vector cols;\n\n for (const auto& c :\n base_table_.asInstanceOf()->getAvailableColumns()) {\n cols.emplace_back(c);\n }\n\n for (const auto& c :\n joined_table_.asInstanceOf()->getAvailableColumns()) {\n cols.emplace_back(c);\n }\n\n return cols;\n}\n\nsize_t JoinNode::getComputedColumnIndex(\n const String& column_name,\n bool allow_add \/* = false *\/) {\n for (int i = 0; i < column_names_.size(); ++i) {\n if (column_names_[i] == column_name) {\n return i;\n }\n }\n\n auto input_idx = getInputColumnIndex(column_name);\n if (input_idx != size_t(-1)) {\n auto slnode = new SelectListNode(\n new ColumnReferenceNode(input_idx, getInputColumnType(input_idx)));\n slnode->setAlias(column_name);\n select_list_.emplace_back(slnode);\n return select_list_.size() - 1;\n }\n\n return -1; \/\/ FIXME\n}\n\nsize_t JoinNode::getNumComputedColumns() const {\n return select_list_.size();\n}\n\nSType JoinNode::getColumnType(size_t idx) const {\n assert(idx < select_list_.size());\n return select_list_[idx]->expression()->getReturnType();\n}\n\nsize_t JoinNode::getInputColumnIndex(\n const String& column_name,\n bool allow_add \/* = false *\/) {\n for (int i = 0; i < input_map_.size(); ++i) {\n if (input_map_[i].column == column_name) {\n return i;\n }\n }\n\n auto base_table_idx = base_table_\n .asInstanceOf()\n ->getComputedColumnIndex(column_name, allow_add);\n\n auto joined_table_idx = joined_table_\n .asInstanceOf()\n ->getComputedColumnIndex(column_name, allow_add);\n\n if (base_table_idx != size_t(-1) && joined_table_idx != size_t(-1)) {\n RAISEF(\n kRuntimeError,\n \"ambiguous column reference: '$0'\",\n column_name);\n }\n\n if (base_table_idx != size_t(-1)) {\n input_map_.emplace_back(InputColumnRef{\n .column = column_name,\n .table_idx = 0,\n .column_idx = base_table_idx\n });\n\n return input_map_.size() - 1;\n }\n\n if (joined_table_idx != size_t(-1)) {\n input_map_.emplace_back(InputColumnRef{\n .column = column_name,\n .table_idx = 1,\n .column_idx = joined_table_idx\n });\n\n return input_map_.size() - 1;\n }\n\n return -1;\n}\n\nSType JoinNode::getInputColumnType(size_t idx) const {\n if (idx >= input_map_.size()) {\n RAISEF(\n kRuntimeError,\n \"invalid column index: '$0'\",\n idx);\n }\n\n switch (input_map_[idx].table_idx) {\n case 0:\n return base_table_.asInstanceOf()->getColumnType(\n input_map_[idx].column_idx);\n case 1:\n return joined_table_.asInstanceOf()->getColumnType(\n input_map_[idx].column_idx);\n default:\n return SType::NIL;\n }\n}\n\nstd::pair JoinNode::getInputColumnInfo(\n const String& column_name,\n bool allow_add) {\n auto idx = getInputColumnIndex(column_name, allow_add);\n if (idx == size_t(-1)) {\n return std::make_pair(idx, SType::NIL);\n } else {\n return std::make_pair(idx, getInputColumnType(idx));\n }\n}\n\n\nOption> JoinNode::whereExpression() const {\n return where_expr_;\n}\n\nvoid JoinNode::setWhereExpression(RefPtr expr) {\n where_expr_ = Some(expr);\n}\n\nOption> JoinNode::joinCondition() const {\n return join_cond_;\n}\n\nvoid JoinNode::setJoinCondition(RefPtr expr) {\n join_cond_ = Some(expr);\n}\n\nRefPtr JoinNode::deepCopy() const {\n return new JoinNode(*this);\n}\n\nconst Vector& JoinNode::inputColumnMap() const {\n return input_map_;\n}\n\nString JoinNode::toString() const {\n auto str = StringUtil::format(\n \"(join (base-table $0) (joined-table $0) (select-list\",\n base_table_->toString(),\n joined_table_->toString());\n\n for (const auto& e : select_list_) {\n str += \" \" + e->toString();\n }\n str += \")\";\n\n if (!where_expr_.isEmpty()) {\n str += StringUtil::format(\" (where $0)\", where_expr_.get()->toString());\n }\n\n if (!join_cond_.isEmpty()) {\n str += StringUtil::format(\" (join-cond $0)\", join_cond_.get()->toString());\n }\n\n str += \")\";\n return str;\n};\n\nvoid JoinNode::encode(\n QueryTreeCoder* coder,\n const JoinNode& node,\n OutputStream* os) {\n os->appendUInt8((uint8_t) node.join_type_);\n\n os->appendVarUInt(node.select_list_.size());\n for (const auto& e : node.select_list_) {\n coder->encode(e.get(), os);\n }\n\n uint8_t flags = 0;\n if (!node.where_expr_.isEmpty()) {\n flags |= kHasWhereExprFlag;\n }\n if (!node.join_cond_.isEmpty()) {\n flags |= kHasJoinExprFlag;\n }\n\n os->appendUInt8(flags);\n\n if (!node.where_expr_.isEmpty()) {\n coder->encode(node.where_expr_.get().get(), os);\n }\n\n if (!node.join_cond_.isEmpty()) {\n coder->encode(node.join_cond_.get().get(), os);\n }\n\n coder->encode(node.base_table_.get(), os);\n coder->encode(node.joined_table_.get(), os);\n}\n\nRefPtr JoinNode::decode (\n QueryTreeCoder* coder,\n InputStream* is) {\n auto join_type = (JoinType) is->readUInt8();\n\n Vector> select_list;\n auto select_list_size = is->readVarUInt();\n for (auto i = 0; i < select_list_size; ++i) {\n select_list.emplace_back(coder->decode(is).asInstanceOf());\n }\n\n Option> where_expr;\n Option> join_cond;\n auto flags = is->readUInt8();\n\n if ((flags & kHasWhereExprFlag) > 0) {\n where_expr = coder->decode(is).asInstanceOf();\n }\n\n if ((flags & kHasJoinExprFlag) > 0) {\n join_cond = coder->decode(is).asInstanceOf();\n }\n\n auto base_tbl = coder->decode(is);\n auto joined_tbl = coder->decode(is);\n\n return new JoinNode(\n join_type,\n base_tbl,\n joined_tbl,\n select_list,\n where_expr,\n join_cond);\n}\n\n} \/\/ namespace csql\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \"gen-cpp\/DataHub.h\"\n#include \n#include \n#include \n\n\/**\n * Sample DataHub C++ Client\n *\n * @author anantb\n * @author stephentu\n * @date 11\/07\/2013\n *\n *\/\n\nusing namespace std;\nusing namespace boost;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\n\nusing namespace datahub;\n\nint main () {\n try {\n shared_ptr transport(new THttpClient(\"datahub.csail.mit.edu\", 80, \"\/service\"));\n shared_ptr protocol(new TBinaryProtocol(transport));\n DataHubClient client(protocol);\n\n transport->open();\n double version = client.get_version();\n cout << version << endl;\n\n ConnectionParams params = ConnectionParams();\n params.__set_user(\"anantb\");\n params.__set_password(\"anant\");\n\n Connection conn;\n client.open_connection(conn, params);\n\n ResultSet res;\n client.execute_sql(\n res, conn, \"select * from anantb.test.demo\", vector());\n for(vector::const_iterator tuple_it = res.tuples.begin();\n tuple_it != res.tuples.end();\n ++tuple_it) {\n for(vector::const_iterator cell_it = (*tuple_it).cells.begin();\n cell_it != (*tuple_it).cells.end(); \n ++cell_it) {\n cout << *cell_it << \"\\t\";\n }\n cout << std::endl;\n }\n\n transport->close();\n } catch (TException &tx) {\n cout << \"ERROR: \" << tx.what();\n }\n\n return 0;\n}\ncpp sample#include \n#include \n#include \n\n#include \"gen-cpp\/DataHub.h\"\n#include \n#include \n#include \n\n\/**\n * Sample DataHub C++ Client\n *\n * @author anantb\n * @author stephentu\n * @date 11\/07\/2013\n *\n *\/\n\nusing namespace std;\nusing namespace boost;\nusing namespace apache::thrift;\nusing namespace apache::thrift::protocol;\nusing namespace apache::thrift::transport;\n\nusing namespace datahub;\n\nint main () {\n try {\n shared_ptr transport(\n new THttpClient(\"datahub.csail.mit.edu\", 80, \"\/service\"));\n shared_ptr protocol(new TBinaryProtocol(transport));\n DataHubClient client(protocol);\n\n transport->open();\n double version = client.get_version();\n cout << \"Version: \" << version << endl;\n\n ConnectionParams params = ConnectionParams();\n params.__set_user(\"anantb\");\n params.__set_password(\"anant\");\n\n Connection conn;\n client.open_connection(conn, params);\n\n ResultSet res;\n client.execute_sql(\n res, conn, \"select * from anantb.test.demo\", vector());\n\n \/\/ print field names\n for(vector::const_iterator field_it = res.field_names.begin();\n field_it != res.field_names.end(); \n ++field_it) {\n cout << *field_it << \"\\t\";\n }\n\n \/\/ print tuple values\n for(vector::const_iterator tuple_it = res.tuples.begin();\n tuple_it != res.tuples.end();\n ++tuple_it) {\n for(vector::const_iterator cell_it = (*tuple_it).cells.begin();\n cell_it != (*tuple_it).cells.end(); \n ++cell_it) {\n cout << *cell_it << \"\\t\";\n }\n cout << std::endl;\n }\n\n transport->close();\n } catch (TException &tx) {\n cout << \"ERROR: \" << tx.what();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"MatrixSlicingTest.h\"\n#include \n#include \n#include \n#include \n#include \n\nconst size_t ROWS = 910;\nconst size_t COLS = 735;\nconst size_t NODE_COUNTS[] = { 3, 1, 2, 3, 5, 7, 12, 25, 80, 110 };\n\ntypedef Matrix TestGrid;\n\nusing namespace std;\ntypedef MatrixSlicer::SliceList SliceList;\n\nostream& operator<<(ostream& stream, const MatrixSlice& slice)\n{\n return stream\n << \"(\"\n << slice.getStartX() << \", \"\n << slice.getStartY() << \", \"\n << slice.getColumns() << \", \"\n << slice.getRows() << \")\";\n}\n\nostream& operator<<(ostream& stream, const SliceList& slices)\n{\n stream << \"[\";\n bool first = true;\n for (const auto& slice : slices)\n {\n if (!first)\n stream << \", \";\n stream << slice;\n first = false;\n }\n stream << \"]\";\n\n return stream;\n}\n\nBenchmarkResult makeUniformRatings(size_t number)\n{\n BenchmarkResult ratings;\n for (size_t i=0; irows()) << \"Row\" << makeErrorMsg(nodeCount, slice);\n ASSERT_LT(col, grid->columns()) << \"Column\" << makeErrorMsg(nodeCount, slice);\n (*grid)(row, col) += 1.0f;\n }\n }\n}\n\nTestGrid fillTestGrid(size_t rows, size_t cols, const SliceList& slices, const BenchmarkResult& ratings)\n{\n TestGrid testGrid = setupTestGrid(rows, cols);\n for (const MatrixSlice& slice : slices)\n {\n applySliceToTestGrid(slice, &testGrid, ratings.size());\n if (testing::Test::HasFatalFailure()) break;\n }\n\n return testGrid;\n}\n\nTestGrid makeTestGrid(size_t nodeCount, const MatrixSlicer& slicer)\n{\n auto ratings = makeUniformRatings(nodeCount);\n auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);\n return fillTestGrid(ROWS, COLS, slices, ratings);\n}\n\nvoid checkTestGrid(const TestGrid& testGrid, const SliceList& slices)\n{\n for(size_t i=0; iRemoved bogus node count from NODE_COUNTS#include \"MatrixSlicingTest.h\"\n#include \n#include \n#include \n#include \n#include \n\nconst size_t ROWS = 910;\nconst size_t COLS = 735;\nconst size_t NODE_COUNTS[] = { 1, 2, 3, 5, 7, 12, 25, 80, 110, 127 };\n\ntypedef Matrix TestGrid;\n\nusing namespace std;\ntypedef MatrixSlicer::SliceList SliceList;\n\nostream& operator<<(ostream& stream, const MatrixSlice& slice)\n{\n return stream\n << \"(\"\n << slice.getStartX() << \", \"\n << slice.getStartY() << \", \"\n << slice.getColumns() << \", \"\n << slice.getRows() << \")\";\n}\n\nostream& operator<<(ostream& stream, const SliceList& slices)\n{\n stream << \"[\";\n bool first = true;\n for (const auto& slice : slices)\n {\n if (!first)\n stream << \", \";\n stream << slice;\n first = false;\n }\n stream << \"]\";\n\n return stream;\n}\n\nBenchmarkResult makeUniformRatings(size_t number)\n{\n BenchmarkResult ratings;\n for (size_t i=0; irows()) << \"Row\" << makeErrorMsg(nodeCount, slice);\n ASSERT_LT(col, grid->columns()) << \"Column\" << makeErrorMsg(nodeCount, slice);\n (*grid)(row, col) += 1.0f;\n }\n }\n}\n\nTestGrid fillTestGrid(size_t rows, size_t cols, const SliceList& slices, const BenchmarkResult& ratings)\n{\n TestGrid testGrid = setupTestGrid(rows, cols);\n for (const MatrixSlice& slice : slices)\n {\n applySliceToTestGrid(slice, &testGrid, ratings.size());\n if (testing::Test::HasFatalFailure()) break;\n }\n\n return testGrid;\n}\n\nTestGrid makeTestGrid(size_t nodeCount, const MatrixSlicer& slicer)\n{\n auto ratings = makeUniformRatings(nodeCount);\n auto slices = slicer.sliceAndDice(ratings, ROWS, COLS);\n return fillTestGrid(ROWS, COLS, slices, ratings);\n}\n\nvoid checkTestGrid(const TestGrid& testGrid, const SliceList& slices)\n{\n for(size_t i=0; i"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"liblocationwrapper_p.h\"\n\nusing namespace std;\n\nQTM_BEGIN_NAMESPACE\n\nQ_GLOBAL_STATIC(LiblocationWrapper, LocationEngine)\n \nLiblocationWrapper *LiblocationWrapper::instance()\n{\n return LocationEngine();\n}\n\nLiblocationWrapper::~LiblocationWrapper() \n{\n if (locationDevice)\n g_object_unref(locationDevice);\n if (locationControl)\n g_object_unref(locationControl);\n}\n\nbool LiblocationWrapper::inited()\n{\n int retval = false;\n if (!(locationState & LiblocationWrapper::Inited)) {\n g_type_init();\n\n locationControl = location_gpsd_control_get_default();\n\n if (locationControl) {\n g_object_set(G_OBJECT(locationControl),\n \"preferred-method\", LOCATION_METHOD_USER_SELECTED,\n \"preferred-interval\", LOCATION_INTERVAL_1S,\n NULL);\n locationDevice = \n (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, \n NULL);\n \n if (locationDevice) {\n errorHandlerId =\n g_signal_connect(G_OBJECT(locationControl), \"error-verbose\",\n G_CALLBACK(&locationError), \n static_cast(this));\n posChangedId =\n g_signal_connect(G_OBJECT(locationDevice), \"changed\",\n G_CALLBACK(&locationChanged), \n static_cast(this));\n locationState = LiblocationWrapper::Inited;\n retval = true;\n startcounter = 0;\n }\n }\n } else {\n retval = true;\n }\n return retval;\n}\n\nvoid LiblocationWrapper::locationError(LocationGPSDevice *device,\n gint errorCode, gpointer data)\n{\n Q_UNUSED(device);\n QString locationError;\n\n switch (errorCode) {\n case LOCATION_ERROR_USER_REJECTED_DIALOG:\n locationError = \"User didn't enable requested methods\";\n break;\n case LOCATION_ERROR_USER_REJECTED_SETTINGS:\n locationError = \"User changed settings, which disabled location.\";\n break;\n case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE:\n locationError = \"Problems with BT GPS\";\n break;\n case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE:\n locationError = \"Requested method is not allowed in offline mode\";\n break;\n case LOCATION_ERROR_SYSTEM:\n locationError = \"System error.\";\n break;\n default:\n locationError = \"Unknown error.\";\n }\n\n qDebug() << \"Location error:\" << locationError;\n\n LiblocationWrapper *object;\n object = (LiblocationWrapper *)data;\n emit object->error();\n}\n\nvoid LiblocationWrapper::locationChanged(LocationGPSDevice *device,\n gpointer data)\n{\n QGeoPositionInfo posInfo;\n QGeoCoordinate coordinate;\n QGeoSatelliteInfo satInfo;\n int satellitesInUseCount = 0;\n LiblocationWrapper *object;\n \n if (!data || !device) {\n return;\n }\n \n object = (LiblocationWrapper *)data;\n\n if (device) {\n if (device->fix) {\n if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) {\n posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time));\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) {\n coordinate.setLatitude(device->fix->latitude);\n coordinate.setLongitude(device->fix->longitude);\n posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy,\n device->fix->eph);\n posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy,\n device->fix->epv);\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) {\n coordinate.setAltitude(device->fix->altitude);\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) {\n posInfo.setAttribute(QGeoPositionInfo::GroundSpeed,\n device->fix->speed);\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) {\n posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed,\n device->fix->climb);\n }\n \n if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) {\n posInfo.setAttribute(QGeoPositionInfo::Direction,\n device->fix->track);\n }\n }\n \n if (device->satellites_in_view) {\n QList satsInView;\n QList satsInUse;\n unsigned int i;\n for (i=0;isatellites->len;i++) {\n LocationGPSDeviceSatellite *satData =\n (LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites,\n i);\n satInfo.setSignalStrength(satData->signal_strength);\n satInfo.setPrnNumber(satData->prn);\n satInfo.setAttribute(QGeoSatelliteInfo::Elevation, \n satData->elevation);\n satInfo.setAttribute(QGeoSatelliteInfo::Azimuth, \n satData->azimuth);\n \n satsInView.append(satInfo);\n if (satData->in_use) {\n satellitesInUseCount++;\n satsInUse.append(satInfo);\n }\n }\n \n if (!satsInView.isEmpty())\n object->satellitesInViewUpdated(satsInView);\n \n if (!satsInUse.isEmpty())\n object->satellitesInUseUpdated(satsInUse);\n } \n }\n \n posInfo.setCoordinate(coordinate);\n\n if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) && \n ((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) || \n (device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) {\n object->setLocation(posInfo, true);\n } else {\n object->setLocation(posInfo, false);\n }\n}\n\nvoid LiblocationWrapper::setLocation(const QGeoPositionInfo &update, \n bool locationValid)\n{\n validLastSatUpdate = locationValid;\n lastSatUpdate = update;\n}\n\nQGeoPositionInfo LiblocationWrapper::position() {\n return lastSatUpdate;\n}\n\nbool LiblocationWrapper::fixIsValid()\n{\n return validLastSatUpdate;\n}\n\nQGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const\n{\n QGeoPositionInfo posInfo;\n QGeoCoordinate coordinate;\n double time;\n double latitude;\n double longitude;\n double altitude;\n double speed;\n double track;\n double climb;\n \n GConfItem lastKnownPositionTime(\"\/system\/nokia\/location\/lastknown\/time\");\n GConfItem lastKnownPositionLatitude(\"\/system\/nokia\/location\/lastknown\/latitude\");\n GConfItem lastKnownPositionLongitude(\"\/system\/nokia\/location\/lastknown\/longitude\");\n GConfItem lastKnownPositionAltitude(\"\/system\/nokia\/location\/lastknown\/altitude\");\n GConfItem lastKnownPositionSpeed(\"\/system\/nokia\/location\/lastknown\/speed\");\n GConfItem lastKnownPositionTrack(\"\/system\/nokia\/location\/lastknown\/track\");\n GConfItem lastKnownPositionClimb(\"\/system\/nokia\/location\/lastknown\/climb\");\n \n if (validLastSatUpdate)\n return lastSatUpdate;\n\n if (!fromSatellitePositioningMethodsOnly)\n if (validLastUpdate)\n return lastUpdate;\n \n time = lastKnownPositionTime.value().toDouble();\n latitude = lastKnownPositionLatitude.value().toDouble();\n longitude = lastKnownPositionLongitude.value().toDouble();\n altitude = lastKnownPositionAltitude.value().toDouble();\n speed = lastKnownPositionSpeed.value().toDouble();\n track = lastKnownPositionTrack.value().toDouble();\n climb = lastKnownPositionClimb.value().toDouble();\n \n if (longitude && latitude) {\n coordinate.setLongitude(longitude);\n coordinate.setLatitude(latitude);\n if (altitude) {\n coordinate.setAltitude(altitude);\n }\n posInfo.setCoordinate(coordinate);\n }\n \n if (speed) {\n posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed);\n }\n \n if (track) {\n posInfo.setAttribute(QGeoPositionInfo::Direction, track);\n }\n \n if (climb) {\n posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb); \n }\n\n \/\/ Only positions with time (3D) are provided.\n if (time) {\n posInfo.setTimestamp(QDateTime::fromTime_t(time));\n return posInfo;\n }\n\n return QGeoPositionInfo();\n}\n\nvoid LiblocationWrapper::satellitesInViewUpdated(const QList &satellites)\n{\n satsInView = satellites;\n}\n\nvoid LiblocationWrapper::satellitesInUseUpdated(const QList &satellites)\n{\n satsInUse = satellites;\n}\n\nQList LiblocationWrapper::satellitesInView()\n{\n return satsInView;\n}\n\nQList LiblocationWrapper::satellitesInUse()\n{\n return satsInUse;\n}\n\nvoid LiblocationWrapper::start() {\n startcounter++;\n\n if ((locationState & LiblocationWrapper::Inited) &&\n !(locationState & LiblocationWrapper::Started)) {\n if (!errorHandlerId) {\n errorHandlerId =\n g_signal_connect(G_OBJECT(locationControl), \"error-verbose\",\n G_CALLBACK(&locationError), \n static_cast(this));\n }\n\n if (!posChangedId) {\n posChangedId =\n g_signal_connect(G_OBJECT(locationDevice), \"changed\",\n G_CALLBACK(&locationChanged), \n static_cast(this));\n }\n\n location_gpsd_control_start(locationControl);\n \n locationState |= LiblocationWrapper::Started;\n locationState &= ~LiblocationWrapper::Stopped;\n }\n}\n\nvoid LiblocationWrapper::stop() {\n startcounter--;\n\n if (startcounter > 0)\n return;\n \n if ((locationState & (LiblocationWrapper::Started |\n LiblocationWrapper::Inited)) &&\n !(locationState & LiblocationWrapper::Stopped)) {\n if (errorHandlerId)\n g_signal_handler_disconnect(G_OBJECT(locationControl), \n errorHandlerId);\n if (posChangedId)\n g_signal_handler_disconnect(G_OBJECT(locationDevice), \n posChangedId);\n errorHandlerId = 0;\n posChangedId = 0;\n startcounter = 0;\n location_gpsd_control_stop(locationControl);\n\n locationState &= ~LiblocationWrapper::Started;\n locationState |= LiblocationWrapper::Stopped;\n }\n}\n\nbool LiblocationWrapper::isActive() {\n if (locationState & LiblocationWrapper::Started)\n return true;\n else\n return false;\n}\n\n#include \"moc_liblocationwrapper_p.cpp\"\nQTM_END_NAMESPACE\n\nFix for bug in Maemo 5 Location regarding position accuracy.\/****************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"liblocationwrapper_p.h\"\n\nusing namespace std;\n\nQTM_BEGIN_NAMESPACE\n\nQ_GLOBAL_STATIC(LiblocationWrapper, LocationEngine)\n \nLiblocationWrapper *LiblocationWrapper::instance()\n{\n return LocationEngine();\n}\n\nLiblocationWrapper::~LiblocationWrapper() \n{\n if (locationDevice)\n g_object_unref(locationDevice);\n if (locationControl)\n g_object_unref(locationControl);\n}\n\nbool LiblocationWrapper::inited()\n{\n int retval = false;\n if (!(locationState & LiblocationWrapper::Inited)) {\n g_type_init();\n\n locationControl = location_gpsd_control_get_default();\n\n if (locationControl) {\n g_object_set(G_OBJECT(locationControl),\n \"preferred-method\", LOCATION_METHOD_USER_SELECTED,\n \"preferred-interval\", LOCATION_INTERVAL_1S,\n NULL);\n locationDevice = \n (LocationGPSDevice*)g_object_new(LOCATION_TYPE_GPS_DEVICE, \n NULL);\n \n if (locationDevice) {\n errorHandlerId =\n g_signal_connect(G_OBJECT(locationControl), \"error-verbose\",\n G_CALLBACK(&locationError), \n static_cast(this));\n posChangedId =\n g_signal_connect(G_OBJECT(locationDevice), \"changed\",\n G_CALLBACK(&locationChanged), \n static_cast(this));\n locationState = LiblocationWrapper::Inited;\n retval = true;\n startcounter = 0;\n }\n }\n } else {\n retval = true;\n }\n return retval;\n}\n\nvoid LiblocationWrapper::locationError(LocationGPSDevice *device,\n gint errorCode, gpointer data)\n{\n Q_UNUSED(device);\n QString locationError;\n\n switch (errorCode) {\n case LOCATION_ERROR_USER_REJECTED_DIALOG:\n locationError = \"User didn't enable requested methods\";\n break;\n case LOCATION_ERROR_USER_REJECTED_SETTINGS:\n locationError = \"User changed settings, which disabled location.\";\n break;\n case LOCATION_ERROR_BT_GPS_NOT_AVAILABLE:\n locationError = \"Problems with BT GPS\";\n break;\n case LOCATION_ERROR_METHOD_NOT_ALLOWED_IN_OFFLINE_MODE:\n locationError = \"Requested method is not allowed in offline mode\";\n break;\n case LOCATION_ERROR_SYSTEM:\n locationError = \"System error.\";\n break;\n default:\n locationError = \"Unknown error.\";\n }\n\n qDebug() << \"Location error:\" << locationError;\n\n LiblocationWrapper *object;\n object = (LiblocationWrapper *)data;\n emit object->error();\n}\n\nvoid LiblocationWrapper::locationChanged(LocationGPSDevice *device,\n gpointer data)\n{\n QGeoPositionInfo posInfo;\n QGeoCoordinate coordinate;\n QGeoSatelliteInfo satInfo;\n int satellitesInUseCount = 0;\n LiblocationWrapper *object;\n \n if (!data || !device) {\n return;\n }\n \n object = (LiblocationWrapper *)data;\n\n if (device) {\n if (device->fix) {\n if (device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) {\n posInfo.setTimestamp(QDateTime::fromTime_t(device->fix->time));\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_LATLONG_SET) {\n coordinate.setLatitude(device->fix->latitude);\n coordinate.setLongitude(device->fix->longitude);\n posInfo.setAttribute(QGeoPositionInfo::HorizontalAccuracy,\n device->fix->eph * 100);\n posInfo.setAttribute(QGeoPositionInfo::VerticalAccuracy,\n device->fix->epv);\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_ALTITUDE_SET) {\n coordinate.setAltitude(device->fix->altitude);\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_SPEED_SET) {\n posInfo.setAttribute(QGeoPositionInfo::GroundSpeed,\n device->fix->speed);\n }\n\n if (device->fix->fields & LOCATION_GPS_DEVICE_CLIMB_SET) {\n posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed,\n device->fix->climb);\n }\n \n if (device->fix->fields & LOCATION_GPS_DEVICE_TRACK_SET) {\n posInfo.setAttribute(QGeoPositionInfo::Direction,\n device->fix->track);\n }\n }\n \n if (device->satellites_in_view) {\n QList satsInView;\n QList satsInUse;\n unsigned int i;\n for (i=0;isatellites->len;i++) {\n LocationGPSDeviceSatellite *satData =\n (LocationGPSDeviceSatellite *)g_ptr_array_index(device->satellites,\n i);\n satInfo.setSignalStrength(satData->signal_strength);\n satInfo.setPrnNumber(satData->prn);\n satInfo.setAttribute(QGeoSatelliteInfo::Elevation, \n satData->elevation);\n satInfo.setAttribute(QGeoSatelliteInfo::Azimuth, \n satData->azimuth);\n \n satsInView.append(satInfo);\n if (satData->in_use) {\n satellitesInUseCount++;\n satsInUse.append(satInfo);\n }\n }\n \n if (!satsInView.isEmpty())\n object->satellitesInViewUpdated(satsInView);\n \n if (!satsInUse.isEmpty())\n object->satellitesInUseUpdated(satsInUse);\n } \n }\n \n posInfo.setCoordinate(coordinate);\n\n if ((device->fix->fields & LOCATION_GPS_DEVICE_TIME_SET) && \n ((device->fix->mode == LOCATION_GPS_DEVICE_MODE_3D) || \n (device->fix->mode == LOCATION_GPS_DEVICE_MODE_2D))) {\n object->setLocation(posInfo, true);\n } else {\n object->setLocation(posInfo, false);\n }\n}\n\nvoid LiblocationWrapper::setLocation(const QGeoPositionInfo &update, \n bool locationValid)\n{\n validLastSatUpdate = locationValid;\n lastSatUpdate = update;\n}\n\nQGeoPositionInfo LiblocationWrapper::position() {\n return lastSatUpdate;\n}\n\nbool LiblocationWrapper::fixIsValid()\n{\n return validLastSatUpdate;\n}\n\nQGeoPositionInfo LiblocationWrapper::lastKnownPosition(bool fromSatellitePositioningMethodsOnly) const\n{\n QGeoPositionInfo posInfo;\n QGeoCoordinate coordinate;\n double time;\n double latitude;\n double longitude;\n double altitude;\n double speed;\n double track;\n double climb;\n \n GConfItem lastKnownPositionTime(\"\/system\/nokia\/location\/lastknown\/time\");\n GConfItem lastKnownPositionLatitude(\"\/system\/nokia\/location\/lastknown\/latitude\");\n GConfItem lastKnownPositionLongitude(\"\/system\/nokia\/location\/lastknown\/longitude\");\n GConfItem lastKnownPositionAltitude(\"\/system\/nokia\/location\/lastknown\/altitude\");\n GConfItem lastKnownPositionSpeed(\"\/system\/nokia\/location\/lastknown\/speed\");\n GConfItem lastKnownPositionTrack(\"\/system\/nokia\/location\/lastknown\/track\");\n GConfItem lastKnownPositionClimb(\"\/system\/nokia\/location\/lastknown\/climb\");\n \n if (validLastSatUpdate)\n return lastSatUpdate;\n\n if (!fromSatellitePositioningMethodsOnly)\n if (validLastUpdate)\n return lastUpdate;\n \n time = lastKnownPositionTime.value().toDouble();\n latitude = lastKnownPositionLatitude.value().toDouble();\n longitude = lastKnownPositionLongitude.value().toDouble();\n altitude = lastKnownPositionAltitude.value().toDouble();\n speed = lastKnownPositionSpeed.value().toDouble();\n track = lastKnownPositionTrack.value().toDouble();\n climb = lastKnownPositionClimb.value().toDouble();\n \n if (longitude && latitude) {\n coordinate.setLongitude(longitude);\n coordinate.setLatitude(latitude);\n if (altitude) {\n coordinate.setAltitude(altitude);\n }\n posInfo.setCoordinate(coordinate);\n }\n \n if (speed) {\n posInfo.setAttribute(QGeoPositionInfo::GroundSpeed, speed);\n }\n \n if (track) {\n posInfo.setAttribute(QGeoPositionInfo::Direction, track);\n }\n \n if (climb) {\n posInfo.setAttribute(QGeoPositionInfo::VerticalSpeed, climb); \n }\n\n \/\/ Only positions with time (3D) are provided.\n if (time) {\n posInfo.setTimestamp(QDateTime::fromTime_t(time));\n return posInfo;\n }\n\n return QGeoPositionInfo();\n}\n\nvoid LiblocationWrapper::satellitesInViewUpdated(const QList &satellites)\n{\n satsInView = satellites;\n}\n\nvoid LiblocationWrapper::satellitesInUseUpdated(const QList &satellites)\n{\n satsInUse = satellites;\n}\n\nQList LiblocationWrapper::satellitesInView()\n{\n return satsInView;\n}\n\nQList LiblocationWrapper::satellitesInUse()\n{\n return satsInUse;\n}\n\nvoid LiblocationWrapper::start() {\n startcounter++;\n\n if ((locationState & LiblocationWrapper::Inited) &&\n !(locationState & LiblocationWrapper::Started)) {\n if (!errorHandlerId) {\n errorHandlerId =\n g_signal_connect(G_OBJECT(locationControl), \"error-verbose\",\n G_CALLBACK(&locationError), \n static_cast(this));\n }\n\n if (!posChangedId) {\n posChangedId =\n g_signal_connect(G_OBJECT(locationDevice), \"changed\",\n G_CALLBACK(&locationChanged), \n static_cast(this));\n }\n\n location_gpsd_control_start(locationControl);\n \n locationState |= LiblocationWrapper::Started;\n locationState &= ~LiblocationWrapper::Stopped;\n }\n}\n\nvoid LiblocationWrapper::stop() {\n startcounter--;\n\n if (startcounter > 0)\n return;\n \n if ((locationState & (LiblocationWrapper::Started |\n LiblocationWrapper::Inited)) &&\n !(locationState & LiblocationWrapper::Stopped)) {\n if (errorHandlerId)\n g_signal_handler_disconnect(G_OBJECT(locationControl), \n errorHandlerId);\n if (posChangedId)\n g_signal_handler_disconnect(G_OBJECT(locationDevice), \n posChangedId);\n errorHandlerId = 0;\n posChangedId = 0;\n startcounter = 0;\n location_gpsd_control_stop(locationControl);\n\n locationState &= ~LiblocationWrapper::Started;\n locationState |= LiblocationWrapper::Stopped;\n }\n}\n\nbool LiblocationWrapper::isActive() {\n if (locationState & LiblocationWrapper::Started)\n return true;\n else\n return false;\n}\n\n#include \"moc_liblocationwrapper_p.cpp\"\nQTM_END_NAMESPACE\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic QHash qmlTypeByCppName;\nstatic QHash cppToQml;\n\nQByteArray convertToQmlType(const QByteArray &cppName)\n{\n QByteArray qmlName = cppToQml.value(cppName, cppName);\n qmlName.replace(\"::\", \".\");\n qmlName.replace(\"\/\", \".\");\n return qmlName;\n}\n\nvoid erasure(QByteArray *typeName, bool *isList, bool *isPointer)\n{\n static QByteArray declListPrefix = \"QDeclarativeListProperty<\";\n\n if (typeName->endsWith('*')) {\n *isPointer = true;\n typeName->truncate(typeName->length() - 1);\n erasure(typeName, isList, isPointer);\n } else if (typeName->startsWith(declListPrefix)) {\n *isList = true;\n typeName->truncate(typeName->length() - 1); \/\/ get rid of the suffix '>'\n *typeName = typeName->mid(declListPrefix.size());\n erasure(typeName, isList, isPointer);\n }\n\n *typeName = convertToQmlType(*typeName);\n}\n\nvoid processMetaObject(const QMetaObject *meta, QSet *metas)\n{\n if (! meta || metas->contains(meta))\n return;\n\n metas->insert(meta);\n processMetaObject(meta->superClass(), metas);\n}\n\nvoid processObject(QObject *object, QSet *metas)\n{\n if (! object)\n return;\n\n const QMetaObject *meta = object->metaObject();\n processMetaObject(meta, metas);\n\n for (int index = 0; index < meta->propertyCount(); ++index) {\n QMetaProperty prop = meta->property(index);\n if (QDeclarativeMetaType::isQObject(prop.userType())) {\n QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));\n if (oo && !metas->contains(oo->metaObject()))\n processObject(oo, metas);\n }\n }\n}\n\nvoid processDeclarativeType(const QDeclarativeType *ty, QSet *metas)\n{\n processMetaObject(ty->metaObject(), metas);\n}\n\nvoid writeType(QXmlStreamAttributes *attrs, QByteArray typeName)\n{\n bool isList = false, isPointer = false;\n erasure(&typeName, &isList, &isPointer);\n attrs->append(QXmlStreamAttribute(\"type\", typeName));\n if (isList)\n attrs->append(QXmlStreamAttribute(\"isList\", \"true\"));\n}\n\nvoid dump(const QMetaProperty &prop, QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"property\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", QString::fromUtf8(prop.name())));\n\n writeType(&attributes, prop.typeName());\n\n xml->writeAttributes(attributes);\n xml->writeEndElement();\n}\n\nvoid dump(const QMetaMethod &meth, QXmlStreamWriter *xml)\n{\n if (meth.methodType() == QMetaMethod::Signal) {\n if (meth.access() != QMetaMethod::Protected)\n return; \/\/ nothing to do.\n } else if (meth.access() != QMetaMethod::Public) {\n return; \/\/ nothing to do.\n }\n\n QByteArray name = meth.signature();\n int lparenIndex = name.indexOf('(');\n if (lparenIndex == -1) {\n return; \/\/ invalid signature\n }\n\n name = name.left(lparenIndex);\n\n\n QString elementName = QLatin1String(\"method\");\n\n QXmlStreamAttributes attributes;\n if (meth.methodType() == QMetaMethod::Signal)\n elementName = QLatin1String(\"signal\");\n\n xml->writeStartElement(elementName);\n\n attributes.append(QXmlStreamAttribute(\"name\", name));\n\n const QString typeName = convertToQmlType(meth.typeName());\n if (! typeName.isEmpty())\n attributes.append(QXmlStreamAttribute(\"type\", typeName));\n\n xml->writeAttributes(attributes);\n\n for (int i = 0; i < meth.parameterTypes().size(); ++i) {\n QByteArray argName = meth.parameterNames().at(i);\n\n xml->writeStartElement(\"param\");\n\n QXmlStreamAttributes attrs;\n\n if (! argName.isEmpty())\n attrs.append(QXmlStreamAttribute(\"name\", argName));\n\n writeType(&attrs, meth.parameterTypes().at(i));\n xml->writeAttributes(attrs);\n\n xml->writeEndElement();\n }\n\n xml->writeEndElement();\n}\n\nvoid dump(const QMetaEnum &e, QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"enum\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", QString::fromUtf8(e.name()))); \/\/ ### FIXME\n xml->writeAttributes(attributes);\n\n for (int index = 0; index < e.keyCount(); ++index) {\n xml->writeStartElement(\"enumerator\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", QString::fromUtf8(e.key(index))));\n attributes.append(QXmlStreamAttribute(\"value\", QString::number(e.value(index))));\n xml->writeAttributes(attributes);\n\n xml->writeEndElement();\n }\n\n xml->writeEndElement();\n}\n\nclass FriendlyQObject: public QObject\n{\npublic:\n static const QMetaObject *qtMeta() { return &staticQtMetaObject; }\n};\n\nvoid dump(const QMetaObject *meta, QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"type\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", convertToQmlType(meta->className())));\n\n if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {\n attributes.append(QXmlStreamAttribute(\"version\", QString(\"%1.%2\").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));\n }\n\n for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {\n QMetaClassInfo classInfo = meta->classInfo(index);\n if (QLatin1String(classInfo.name()) == QLatin1String(\"DefaultProperty\")) {\n attributes.append(QXmlStreamAttribute(\"defaultProperty\", QLatin1String(classInfo.value())));\n break;\n }\n }\n\n QString version;\n\n if (meta->superClass())\n attributes.append(QXmlStreamAttribute(\"extends\", convertToQmlType(meta->superClass()->className())));\n\n if (! version.isEmpty())\n attributes.append(QXmlStreamAttribute(\"version\", version));\n\n xml->writeAttributes(attributes);\n\n for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)\n dump(meta->enumerator(index), xml);\n\n for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)\n dump(meta->property(index), xml);\n\n for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)\n dump(meta->method(index), xml);\n\n xml->writeEndElement();\n}\n\nvoid writeScriptElement(QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"type\");\n {\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", \"Script\"));\n xml->writeAttributes(attributes);\n }\n\n xml->writeStartElement(\"property\");\n {\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", \"script\"));\n attributes.append(QXmlStreamAttribute(\"type\", \"string\"));\n xml->writeAttributes(attributes);\n }\n xml->writeEndElement();\n\n xml->writeStartElement(\"property\");\n {\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", \"source\"));\n attributes.append(QXmlStreamAttribute(\"type\", \"QUrl\"));\n xml->writeAttributes(attributes);\n }\n xml->writeEndElement();\n\n xml->writeEndElement();\n}\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n QDeclarativeView view;\n QDeclarativeEngine *engine = view.engine();\n\n {\n QByteArray code;\n code += \"import Qt 4.7;\\n\";\n code += \"import Qt.widgets 4.7;\\n\";\n code += \"import Qt.multimedia 1.0;\\n\";\n code += \"import Qt.labs.particles 4.7;\\n\";\n code += \"import org.webkit 1.0;\\n\";\n code += \"Item {}\";\n QDeclarativeComponent c(engine);\n c.setData(code, QUrl(\"xxx\"));\n c.create();\n }\n\n cppToQml.insert(\"QString\", \"string\");\n cppToQml.insert(\"QEasingCurve\", \"Qt.Easing\");\n cppToQml.insert(\"QDeclarativeEasingValueType::Type\", \"Type\");\n\n QSet metas;\n\n metas.insert(FriendlyQObject::qtMeta());\n\n \/\/ ### TODO: We don't treat extended types correctly. Currently only hits the\n \/\/ QDeclarativeGraphicsWidget extension to QGraphicsWidget\n foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {\n if (ty->isExtendedType())\n continue;\n\n cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());\n qmlTypeByCppName.insert(ty->metaObject()->className(), ty);\n processDeclarativeType(ty, &metas);\n }\n\n foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {\n if (ty->isExtendedType())\n continue;\n\n QByteArray tyName = ty->qmlTypeName();\n tyName = tyName.mid(tyName.lastIndexOf('\/') + 1);\n\n QByteArray code;\n code += \"import Qt 4.7;\\n\";\n code += \"import Qt.widgets 4.7;\\n\";\n code += \"import Qt.multimedia 1.0;\\n\";\n code += \"import Qt.labs.particles 4.7;\\n\";\n code += \"import org.webkit 1.0;\\n\";\n code += tyName;\n code += \" {}\\n\";\n\n QDeclarativeComponent c(engine);\n c.setData(code, QUrl(\"xxx\"));\n processObject(c.create(), &metas);\n }\n\n QByteArray bytes;\n QXmlStreamWriter xml(&bytes);\n xml.setAutoFormatting(true);\n\n xml.writeStartDocument(\"1.0\");\n xml.writeStartElement(\"module\");\n\n QMap nameToMeta;\n foreach (const QMetaObject *meta, metas) {\n nameToMeta.insert(convertToQmlType(meta->className()), meta);\n }\n foreach (const QMetaObject *meta, nameToMeta) {\n dump(meta, &xml);\n }\n\n writeScriptElement(&xml);\n\n xml.writeEndElement();\n xml.writeEndDocument();\n\n std::cout << bytes.constData();\n\n QTimer timer;\n timer.setSingleShot(true);\n timer.setInterval(0);\n QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));\n\n timer.start();\n\n return app.exec();\n}\nQmlJS: Make the qmldump tool treat extended types correctly.#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nstatic QHash qmlTypeByCppName;\nstatic QHash cppToQml;\n\nQByteArray convertToQmlType(const QByteArray &cppName)\n{\n QByteArray qmlName = cppToQml.value(cppName, cppName);\n qmlName.replace(\"::\", \".\");\n qmlName.replace(\"\/\", \".\");\n return qmlName;\n}\n\nvoid erasure(QByteArray *typeName, bool *isList, bool *isPointer)\n{\n static QByteArray declListPrefix = \"QDeclarativeListProperty<\";\n\n if (typeName->endsWith('*')) {\n *isPointer = true;\n typeName->truncate(typeName->length() - 1);\n erasure(typeName, isList, isPointer);\n } else if (typeName->startsWith(declListPrefix)) {\n *isList = true;\n typeName->truncate(typeName->length() - 1); \/\/ get rid of the suffix '>'\n *typeName = typeName->mid(declListPrefix.size());\n erasure(typeName, isList, isPointer);\n }\n\n *typeName = convertToQmlType(*typeName);\n}\n\nvoid processMetaObject(const QMetaObject *meta, QSet *metas)\n{\n if (! meta || metas->contains(meta))\n return;\n\n metas->insert(meta);\n processMetaObject(meta->superClass(), metas);\n}\n\nvoid processObject(QObject *object, QSet *metas)\n{\n if (! object)\n return;\n\n const QMetaObject *meta = object->metaObject();\n processMetaObject(meta, metas);\n\n for (int index = 0; index < meta->propertyCount(); ++index) {\n QMetaProperty prop = meta->property(index);\n if (QDeclarativeMetaType::isQObject(prop.userType())) {\n QObject *oo = QDeclarativeMetaType::toQObject(prop.read(object));\n if (oo && !metas->contains(oo->metaObject()))\n processObject(oo, metas);\n }\n }\n}\n\nvoid processDeclarativeType(const QDeclarativeType *ty, QSet *metas)\n{\n processMetaObject(ty->metaObject(), metas);\n}\n\nvoid writeType(QXmlStreamAttributes *attrs, QByteArray typeName)\n{\n bool isList = false, isPointer = false;\n erasure(&typeName, &isList, &isPointer);\n attrs->append(QXmlStreamAttribute(\"type\", typeName));\n if (isList)\n attrs->append(QXmlStreamAttribute(\"isList\", \"true\"));\n}\n\nvoid dump(const QMetaProperty &prop, QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"property\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", QString::fromUtf8(prop.name())));\n\n writeType(&attributes, prop.typeName());\n\n xml->writeAttributes(attributes);\n xml->writeEndElement();\n}\n\nvoid dump(const QMetaMethod &meth, QXmlStreamWriter *xml)\n{\n if (meth.methodType() == QMetaMethod::Signal) {\n if (meth.access() != QMetaMethod::Protected)\n return; \/\/ nothing to do.\n } else if (meth.access() != QMetaMethod::Public) {\n return; \/\/ nothing to do.\n }\n\n QByteArray name = meth.signature();\n int lparenIndex = name.indexOf('(');\n if (lparenIndex == -1) {\n return; \/\/ invalid signature\n }\n\n name = name.left(lparenIndex);\n\n\n QString elementName = QLatin1String(\"method\");\n\n QXmlStreamAttributes attributes;\n if (meth.methodType() == QMetaMethod::Signal)\n elementName = QLatin1String(\"signal\");\n\n xml->writeStartElement(elementName);\n\n attributes.append(QXmlStreamAttribute(\"name\", name));\n\n const QString typeName = convertToQmlType(meth.typeName());\n if (! typeName.isEmpty())\n attributes.append(QXmlStreamAttribute(\"type\", typeName));\n\n xml->writeAttributes(attributes);\n\n for (int i = 0; i < meth.parameterTypes().size(); ++i) {\n QByteArray argName = meth.parameterNames().at(i);\n\n xml->writeStartElement(\"param\");\n\n QXmlStreamAttributes attrs;\n\n if (! argName.isEmpty())\n attrs.append(QXmlStreamAttribute(\"name\", argName));\n\n writeType(&attrs, meth.parameterTypes().at(i));\n xml->writeAttributes(attrs);\n\n xml->writeEndElement();\n }\n\n xml->writeEndElement();\n}\n\nvoid dump(const QMetaEnum &e, QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"enum\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", QString::fromUtf8(e.name()))); \/\/ ### FIXME\n xml->writeAttributes(attributes);\n\n for (int index = 0; index < e.keyCount(); ++index) {\n xml->writeStartElement(\"enumerator\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", QString::fromUtf8(e.key(index))));\n attributes.append(QXmlStreamAttribute(\"value\", QString::number(e.value(index))));\n xml->writeAttributes(attributes);\n\n xml->writeEndElement();\n }\n\n xml->writeEndElement();\n}\n\nclass FriendlyQObject: public QObject\n{\npublic:\n static const QMetaObject *qtMeta() { return &staticQtMetaObject; }\n};\n\nvoid dump(const QMetaObject *meta, QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"type\");\n\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", convertToQmlType(meta->className())));\n\n if (const QDeclarativeType *qmlTy = qmlTypeByCppName.value(meta->className())) {\n attributes.append(QXmlStreamAttribute(\"version\", QString(\"%1.%2\").arg(qmlTy->majorVersion()).arg(qmlTy->minorVersion())));\n }\n\n for (int index = meta->classInfoCount() - 1 ; index >= 0 ; --index) {\n QMetaClassInfo classInfo = meta->classInfo(index);\n if (QLatin1String(classInfo.name()) == QLatin1String(\"DefaultProperty\")) {\n attributes.append(QXmlStreamAttribute(\"defaultProperty\", QLatin1String(classInfo.value())));\n break;\n }\n }\n\n QString version;\n\n if (meta->superClass())\n attributes.append(QXmlStreamAttribute(\"extends\", convertToQmlType(meta->superClass()->className())));\n\n if (! version.isEmpty())\n attributes.append(QXmlStreamAttribute(\"version\", version));\n\n xml->writeAttributes(attributes);\n\n for (int index = meta->enumeratorOffset(); index < meta->enumeratorCount(); ++index)\n dump(meta->enumerator(index), xml);\n\n for (int index = meta->propertyOffset(); index < meta->propertyCount(); ++index)\n dump(meta->property(index), xml);\n\n for (int index = meta->methodOffset(); index < meta->methodCount(); ++index)\n dump(meta->method(index), xml);\n\n xml->writeEndElement();\n}\n\nvoid writeScriptElement(QXmlStreamWriter *xml)\n{\n xml->writeStartElement(\"type\");\n {\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", \"Script\"));\n xml->writeAttributes(attributes);\n }\n\n xml->writeStartElement(\"property\");\n {\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", \"script\"));\n attributes.append(QXmlStreamAttribute(\"type\", \"string\"));\n xml->writeAttributes(attributes);\n }\n xml->writeEndElement();\n\n xml->writeStartElement(\"property\");\n {\n QXmlStreamAttributes attributes;\n attributes.append(QXmlStreamAttribute(\"name\", \"source\"));\n attributes.append(QXmlStreamAttribute(\"type\", \"QUrl\"));\n xml->writeAttributes(attributes);\n }\n xml->writeEndElement();\n\n xml->writeEndElement();\n}\n\nint main(int argc, char *argv[])\n{\n QApplication app(argc, argv);\n\n QDeclarativeView view;\n QDeclarativeEngine *engine = view.engine();\n\n {\n QByteArray code;\n code += \"import Qt 4.7;\\n\";\n code += \"import Qt.widgets 4.7;\\n\";\n code += \"import Qt.multimedia 1.0;\\n\";\n code += \"import Qt.labs.particles 4.7;\\n\";\n code += \"import org.webkit 1.0;\\n\";\n code += \"Item {}\";\n QDeclarativeComponent c(engine);\n c.setData(code, QUrl(\"xxx\"));\n c.create();\n }\n\n cppToQml.insert(\"QString\", \"string\");\n cppToQml.insert(\"QEasingCurve\", \"Qt.Easing\");\n cppToQml.insert(\"QDeclarativeEasingValueType::Type\", \"Type\");\n\n QSet metas;\n\n metas.insert(FriendlyQObject::qtMeta());\n\n QMultiHash extensions;\n foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {\n qmlTypeByCppName.insert(ty->metaObject()->className(), ty);\n if (ty->isExtendedType()) {\n extensions.insert(ty->typeName(), ty->metaObject()->className());\n } else {\n cppToQml.insert(ty->metaObject()->className(), ty->qmlTypeName());\n }\n processDeclarativeType(ty, &metas);\n }\n\n \/\/ Adjust qml names of extended objects.\n \/\/ The chain ends up being:\n \/\/ __extended__.originalname - the base object\n \/\/ __extension_0_.originalname - first extension\n \/\/ ..\n \/\/ __extension_n-2_.originalname - second to last extension\n \/\/ originalname - last extension\n foreach (const QByteArray &extendedCpp, extensions.keys()) {\n const QByteArray extendedQml = cppToQml.value(extendedCpp);\n cppToQml.insert(extendedCpp, \"__extended__.\" + extendedQml);\n QList extensionCppNames = extensions.values(extendedCpp);\n for (int i = 0; i < extensionCppNames.size() - 1; ++i) {\n QByteArray adjustedName = QString(\"__extension__%1.%2\").arg(QString::number(i), QString(extendedQml)).toAscii();\n cppToQml.insert(extensionCppNames.value(i), adjustedName);\n }\n cppToQml.insert(extensionCppNames.last(), extendedQml);\n }\n\n foreach (const QDeclarativeType *ty, QDeclarativeMetaType::qmlTypes()) {\n if (ty->isExtendedType())\n continue;\n\n QByteArray tyName = ty->qmlTypeName();\n tyName = tyName.mid(tyName.lastIndexOf('\/') + 1);\n\n QByteArray code;\n code += \"import Qt 4.7;\\n\";\n code += \"import Qt.widgets 4.7;\\n\";\n code += \"import Qt.multimedia 1.0;\\n\";\n code += \"import Qt.labs.particles 4.7;\\n\";\n code += \"import org.webkit 1.0;\\n\";\n code += tyName;\n code += \" {}\\n\";\n\n QDeclarativeComponent c(engine);\n c.setData(code, QUrl(\"xxx\"));\n processObject(c.create(), &metas);\n }\n\n QByteArray bytes;\n QXmlStreamWriter xml(&bytes);\n xml.setAutoFormatting(true);\n\n xml.writeStartDocument(\"1.0\");\n xml.writeStartElement(\"module\");\n\n QMap nameToMeta;\n foreach (const QMetaObject *meta, metas) {\n nameToMeta.insert(convertToQmlType(meta->className()), meta);\n }\n foreach (const QMetaObject *meta, nameToMeta) {\n dump(meta, &xml);\n }\n\n writeScriptElement(&xml);\n\n xml.writeEndElement();\n xml.writeEndDocument();\n\n std::cout << bytes.constData();\n\n QTimer timer;\n timer.setSingleShot(true);\n timer.setInterval(0);\n QObject::connect(&timer, SIGNAL(timeout()), &app, SLOT(quit()));\n\n timer.start();\n\n return app.exec();\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"zlib.h\"\n\n#include \"libtorrent\/tracker_manager.hpp\"\n#include \"libtorrent\/udp_tracker_connection.hpp\"\n#include \"libtorrent\/io.hpp\"\n\nnamespace\n{\n\tenum\n\t{\n\t\tudp_connection_retries = 4,\n\t\tudp_announce_retries = 15,\n\t\tudp_connect_timeout = 15,\n\t\tudp_announce_timeout = 10,\n\t\tudp_buffer_size = 2048\n\t};\n}\n\nusing namespace boost::posix_time;\n\nnamespace libtorrent\n{\n\n\tudp_tracker_connection::udp_tracker_connection(\n\t\ttracker_request const& req\n\t\t, std::string const& hostname\n\t\t, unsigned short port\n\t\t, boost::weak_ptr c\n\t\t, const http_settings& stn)\n\t\t: tracker_connection(c)\n\t\t, m_request_time(second_clock::universal_time())\n\t\t, m_request(req)\n\t\t, m_transaction_id(0)\n\t\t, m_connection_id(0)\n\t\t, m_settings(stn)\n\t\t, m_attempts(0)\n\t{\n\t\t\/\/ TODO: this is a problem. DNS-lookup is blocking!\n\t\t\/\/ (may block up to 5 seconds)\n\t\taddress a(hostname.c_str(), port);\n\t\tif (has_requester()) requester().m_tracker_address = a;\n\t\tm_socket.reset(new socket(socket::udp, false));\n\t\tm_socket->connect(a);\n\n\t\tsend_udp_connect();\n\t}\n\n\tbool udp_tracker_connection::send_finished() const\n\t{\n\t\tusing namespace boost::posix_time;\n\n\t\ttime_duration d = second_clock::universal_time() - m_request_time;\n\t\treturn (m_transaction_id != 0\n\t\t\t&& m_connection_id != 0)\n\t\t\t|| d > seconds(m_settings.tracker_timeout);\n\t}\n\n\tbool udp_tracker_connection::tick()\n\t{\n\t\tusing namespace boost::posix_time;\n\n\t\ttime_duration d = second_clock::universal_time() - m_request_time;\n\t\tif (m_connection_id == 0\n\t\t\t&& d > seconds(udp_connect_timeout))\n\t\t{\n\t\t\tif (m_attempts >= udp_connection_retries)\n\t\t\t{\n\t\t\t\tif (has_requester())\n\t\t\t\t\trequester().tracker_request_timed_out(m_request);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tsend_udp_connect();\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m_connection_id != 0\n\t\t\t&& d > seconds(udp_announce_timeout))\n\t\t{\n\t\t\tif (m_attempts >= udp_announce_retries)\n\t\t\t{\n\t\t\t\tif (has_requester())\n\t\t\t\t\trequester().tracker_request_timed_out(m_request);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (m_request.kind == tracker_request::announce_request)\n\t\t\t\tsend_udp_announce();\n\t\t\telse if (m_request.kind == tracker_request::scrape_request)\n\t\t\t\tsend_udp_scrape();\n\t\t\treturn false;\n\t\t}\n\n\t\tchar buf[udp_buffer_size];\n\t\tint ret = m_socket->receive(buf, udp_buffer_size);\n\n\t\t\/\/ if there was nothing to receive, return\n\t\tif (ret == 0) return false;\n\t\tif (ret < 0)\n\t\t{\n\t\t\tsocket::error_code err = m_socket->last_error();\n\t\t\tif (err == socket::would_block) return false;\n\t\t\tthrow network_error(m_socket->last_error());\n\t\t}\n\t\tif (ret == udp_buffer_size)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, \"tracker reply too big\");\n\t\t\treturn true;\n\t\t}\n\n\t\tif (m_connection_id == 0)\n\t\t{\n\t\t\treturn parse_connect_response(buf, ret);\n\t\t}\n\t\telse if (m_request.kind == tracker_request::announce_request)\n\t\t{\n\t\t\treturn parse_announce_response(buf, ret);\n\t\t}\n\t\telse if (m_request.kind == tracker_request::scrape_request)\n\t\t{\n\t\t\treturn parse_scrape_response(buf, ret);\n\t\t}\n\n\t\tassert(false);\n\t\treturn false;\n\t}\n\n\tvoid udp_tracker_connection::send_udp_announce()\n\t{\n\t\tif (m_transaction_id == 0)\n\t\t\tm_transaction_id = rand() ^ (rand() << 16);\n\n\t\tstd::vector buf;\n\t\tstd::back_insert_iterator > out(buf);\n\n\t\t\/\/ connection_id\n\t\tdetail::write_int64(m_connection_id, out);\n\t\t\/\/ action (announce)\n\t\tdetail::write_int32(announce, out);\n\t\t\/\/ transaction_id\n\t\tdetail::write_int32(m_transaction_id, out);\n\t\t\/\/ info_hash\n\t\tstd::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);\n\t\t\/\/ peer_id\n\t\tstd::copy(m_request.id.begin(), m_request.id.end(), out);\n\t\t\/\/ downloaded\n\t\tdetail::write_int64(m_request.downloaded, out);\n\t\t\/\/ left\n\t\tdetail::write_int64(m_request.left, out);\n\t\t\/\/ uploaded\n\t\tdetail::write_int64(m_request.uploaded, out);\n\t\t\/\/ event\n\t\tdetail::write_int32(m_request.event, out);\n\t\t\/\/ ip address\n\t\tdetail::write_int32(0, out);\n\t\t\/\/ key\n\t\tdetail::write_int32(m_request.key, out);\n\t\t\/\/ num_want\n\t\tdetail::write_int32(m_request.num_want, out);\n\t\t\/\/ port\n\t\tdetail::write_uint16(m_request.listen_port, out);\n\n\t\tm_socket->send(&buf[0], buf.size());\n\t\tm_request_time = second_clock::universal_time();\n\t\t++m_attempts;\n\t}\n\n\tvoid udp_tracker_connection::send_udp_scrape()\n\t{\n\t\tif (m_transaction_id == 0)\n\t\t\tm_transaction_id = rand() ^ (rand() << 16);\n\n\t\tstd::vector buf;\n\t\tstd::back_insert_iterator > out(buf);\n\n\t\t\/\/ connection_id\n\t\tdetail::write_int64(m_connection_id, out);\n\t\t\/\/ action (scrape)\n\t\tdetail::write_int32(scrape, out);\n\t\t\/\/ transaction_id\n\t\tdetail::write_int32(m_transaction_id, out);\n\t\t\/\/ info_hash\n\t\tstd::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);\n\n\t\tm_socket->send(&buf[0], buf.size());\n\t\tm_request_time = second_clock::universal_time();\n\t\t++m_attempts;\n\t}\n\n\tvoid udp_tracker_connection::send_udp_connect()\n\t{\n\t\tchar send_buf[16];\n\t\tchar* ptr = send_buf;\n\n\t\tif (m_transaction_id == 0)\n\t\t\tm_transaction_id = rand() ^ (rand() << 16);\n\n\t\t\/\/ connection_id\n\t\tdetail::write_int64(0x41727101980, ptr);\n\t\t\/\/ action (connect)\n\t\tdetail::write_int32(connect, ptr);\n\t\t\/\/ transaction_id\n\t\tdetail::write_int32(m_transaction_id, ptr);\n\n\t\tm_socket->send(send_buf, 16);\n\t\tm_request_time = second_clock::universal_time();\n\t\t++m_attempts;\n\t}\n\n\tbool udp_tracker_connection::parse_announce_response(const char* buf, int len)\n\t{\n\t\tassert(buf != 0);\n\t\tassert(len > 0);\n\n\t\tif (len < 8)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 8, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\n\t\tint action = detail::read_int32(buf);\n\t\tint transaction = detail::read_int32(buf);\n\t\tif (transaction != m_transaction_id)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tif (action == error)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, std::string(buf, buf + len - 8));\n\t\t\treturn true;\n\t\t}\n\t\tif (action != announce) return false;\n\n\t\tif (len < 20)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 20, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\tint interval = detail::read_int32(buf);\n\t\tint incomplete = detail::read_int32(buf);\n\t\tint complete = detail::read_int32(buf);\n\t\tint num_peers = (len - 20) \/ 6;\n\t\tif ((len - 20) % 6 != 0)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, \"invalid tracker response\");\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!has_requester()) return true;\n\n\t\tstd::vector peer_list;\n\t\tfor (int i = 0; i < num_peers; ++i)\n\t\t{\n\t\t\tpeer_entry e;\n\t\t\tstd::stringstream s;\n\t\t\ts << (int)detail::read_uint8(buf) << \".\";\n\t\t\ts << (int)detail::read_uint8(buf) << \".\";\n\t\t\ts << (int)detail::read_uint8(buf) << \".\";\n\t\t\ts << (int)detail::read_uint8(buf);\n\t\t\te.ip = s.str();\n\t\t\te.port = detail::read_uint16(buf);\n\t\t\te.id.clear();\n\t\t\tpeer_list.push_back(e);\n\t\t}\n\n\t\trequester().tracker_response(m_request, peer_list, interval\n\t\t\t, complete, incomplete);\n\t\treturn true;\n\t}\n\n\tbool udp_tracker_connection::parse_scrape_response(const char* buf, int len)\n\t{\n\t\tassert(buf != 0);\n\t\tassert(len > 0);\n\n\t\tif (len < 8)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 8, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\n\t\tint action = detail::read_int32(buf);\n\t\tint transaction = detail::read_int32(buf);\n\t\tif (transaction != m_transaction_id)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tif (action == error)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, std::string(buf, buf + len - 8));\n\t\t\treturn true;\n\t\t}\n\t\tif (action != scrape) return false;\n\n\t\tif (len < 20)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 20, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\tint complete = detail::read_int32(buf);\n\t\tint completed = detail::read_int32(buf);\n\t\tint incomplete = detail::read_int32(buf);\n\n\t\tif (!has_requester()) return true;\n\n\t\tstd::vector peer_list;\n\t\trequester().tracker_response(m_request, peer_list, 0\n\t\t\t, complete, incomplete);\n\t\treturn true;\n\t}\n\n\n\tbool udp_tracker_connection::parse_connect_response(const char* buf, int len)\n\t{\n\t\tassert(buf != 0);\n\t\tassert(len > 0);\n\n\t\tif (len < 8)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 8, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\tconst char* ptr = buf;\n\t\tint action = detail::read_int32(ptr);\n\t\tint transaction = detail::read_int32(ptr);\n\n\t\tif (action == error)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, std::string(ptr, buf + len));\n\t\t\treturn true;\n\t\t}\n\t\tif (action != connect) return false;\n\t\tif (m_transaction_id != transaction)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with incorrect transaction id, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\n\t\tif (len < 16)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a connection message size < 16, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\/\/ reset transaction\n\t\tm_transaction_id = 0;\n\t\tm_attempts = 0;\n\t\tm_connection_id = detail::read_int64(ptr);\n\n\t\tif (m_request.kind == tracker_request::announce_request)\n\t\t\tsend_udp_announce();\n\t\telse if (m_request.kind == tracker_request::scrape_request)\n\t\t\tsend_udp_scrape();\n\n\t\treturn false;\n\t}\n\n\n}\n\n*** empty log message ***\/*\n\nCopyright (c) 2003, Arvid Norberg\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions\nare met:\n\n * Redistributions of source code must retain the above copyright\n notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright\n notice, this list of conditions and the following disclaimer in\n the documentation and\/or other materials provided with the distribution.\n * Neither the name of the author nor the names of its\n contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\nLIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\nCONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\nSUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\nINTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\nCONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\nARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"zlib.h\"\n\n#include \"libtorrent\/tracker_manager.hpp\"\n#include \"libtorrent\/udp_tracker_connection.hpp\"\n#include \"libtorrent\/io.hpp\"\n\nnamespace\n{\n\tenum\n\t{\n\t\tudp_connection_retries = 4,\n\t\tudp_announce_retries = 15,\n\t\tudp_connect_timeout = 15,\n\t\tudp_announce_timeout = 10,\n\t\tudp_buffer_size = 2048\n\t};\n}\n\nusing namespace boost::posix_time;\n\nnamespace libtorrent\n{\n\n\tudp_tracker_connection::udp_tracker_connection(\n\t\ttracker_request const& req\n\t\t, std::string const& hostname\n\t\t, unsigned short port\n\t\t, boost::weak_ptr c\n\t\t, const http_settings& stn)\n\t\t: tracker_connection(c)\n\t\t, m_request_time(second_clock::universal_time())\n\t\t, m_request(req)\n\t\t, m_transaction_id(0)\n\t\t, m_connection_id(0)\n\t\t, m_settings(stn)\n\t\t, m_attempts(0)\n\t{\n\t\t\/\/ TODO: this is a problem. DNS-lookup is blocking!\n\t\t\/\/ (may block up to 5 seconds)\n\t\taddress a(hostname.c_str(), port);\n\t\tif (has_requester()) requester().m_tracker_address = a;\n\t\tm_socket.reset(new socket(socket::udp, false));\n\t\tm_socket->connect(a);\n\n\t\tsend_udp_connect();\n\t}\n\n\tbool udp_tracker_connection::send_finished() const\n\t{\n\t\tusing namespace boost::posix_time;\n\n\t\ttime_duration d = second_clock::universal_time() - m_request_time;\n\t\treturn (m_transaction_id != 0\n\t\t\t&& m_connection_id != 0)\n\t\t\t|| d > seconds(m_settings.tracker_timeout);\n\t}\n\n\tbool udp_tracker_connection::tick()\n\t{\n\t\tusing namespace boost::posix_time;\n\n\t\ttime_duration d = second_clock::universal_time() - m_request_time;\n\t\tif (m_connection_id == 0\n\t\t\t&& d > seconds(udp_connect_timeout))\n\t\t{\n\t\t\tif (m_attempts >= udp_connection_retries)\n\t\t\t{\n\t\t\t\tif (has_requester())\n\t\t\t\t\trequester().tracker_request_timed_out(m_request);\n\t\t\t\treturn true;\n\t\t\t}\n\t\t\tsend_udp_connect();\n\t\t\treturn false;\n\t\t}\n\n\t\tif (m_connection_id != 0\n\t\t\t&& d > seconds(udp_announce_timeout))\n\t\t{\n\t\t\tif (m_attempts >= udp_announce_retries)\n\t\t\t{\n\t\t\t\tif (has_requester())\n\t\t\t\t\trequester().tracker_request_timed_out(m_request);\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tif (m_request.kind == tracker_request::announce_request)\n\t\t\t\tsend_udp_announce();\n\t\t\telse if (m_request.kind == tracker_request::scrape_request)\n\t\t\t\tsend_udp_scrape();\n\t\t\treturn false;\n\t\t}\n\n\t\tchar buf[udp_buffer_size];\n\t\tint ret = m_socket->receive(buf, udp_buffer_size);\n\n\t\t\/\/ if there was nothing to receive, return\n\t\tif (ret == 0) return false;\n\t\tif (ret < 0)\n\t\t{\n\t\t\tsocket::error_code err = m_socket->last_error();\n\t\t\tif (err == socket::would_block) return false;\n\t\t\tthrow network_error(m_socket->last_error());\n\t\t}\n\t\tif (ret == udp_buffer_size)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, \"tracker reply too big\");\n\t\t\treturn true;\n\t\t}\n\n\t\tif (m_connection_id == 0)\n\t\t{\n\t\t\treturn parse_connect_response(buf, ret);\n\t\t}\n\t\telse if (m_request.kind == tracker_request::announce_request)\n\t\t{\n\t\t\treturn parse_announce_response(buf, ret);\n\t\t}\n\t\telse if (m_request.kind == tracker_request::scrape_request)\n\t\t{\n\t\t\treturn parse_scrape_response(buf, ret);\n\t\t}\n\n\t\tassert(false);\n\t\treturn false;\n\t}\n\n\tvoid udp_tracker_connection::send_udp_announce()\n\t{\n\t\tif (m_transaction_id == 0)\n\t\t\tm_transaction_id = rand() ^ (rand() << 16);\n\n\t\tstd::vector buf;\n\t\tstd::back_insert_iterator > out(buf);\n\n\t\t\/\/ connection_id\n\t\tdetail::write_int64(m_connection_id, out);\n\t\t\/\/ action (announce)\n\t\tdetail::write_int32(announce, out);\n\t\t\/\/ transaction_id\n\t\tdetail::write_int32(m_transaction_id, out);\n\t\t\/\/ info_hash\n\t\tstd::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);\n\t\t\/\/ peer_id\n\t\tstd::copy(m_request.id.begin(), m_request.id.end(), out);\n\t\t\/\/ downloaded\n\t\tdetail::write_int64(m_request.downloaded, out);\n\t\t\/\/ left\n\t\tdetail::write_int64(m_request.left, out);\n\t\t\/\/ uploaded\n\t\tdetail::write_int64(m_request.uploaded, out);\n\t\t\/\/ event\n\t\tdetail::write_int32(m_request.event, out);\n\t\t\/\/ ip address\n\t\tdetail::write_int32(0, out);\n\t\t\/\/ key\n\t\tdetail::write_int32(m_request.key, out);\n\t\t\/\/ num_want\n\t\tdetail::write_int32(m_request.num_want, out);\n\t\t\/\/ port\n\t\tdetail::write_uint16(m_request.listen_port, out);\n\t\t\/\/ extensions\n\t\tdetail::write_uint16(0, out);\n\n\t\tm_socket->send(&buf[0], buf.size());\n\t\tm_request_time = second_clock::universal_time();\n\t\t++m_attempts;\n\t}\n\n\tvoid udp_tracker_connection::send_udp_scrape()\n\t{\n\t\tif (m_transaction_id == 0)\n\t\t\tm_transaction_id = rand() ^ (rand() << 16);\n\n\t\tstd::vector buf;\n\t\tstd::back_insert_iterator > out(buf);\n\n\t\t\/\/ connection_id\n\t\tdetail::write_int64(m_connection_id, out);\n\t\t\/\/ action (scrape)\n\t\tdetail::write_int32(scrape, out);\n\t\t\/\/ transaction_id\n\t\tdetail::write_int32(m_transaction_id, out);\n\t\t\/\/ info_hash\n\t\tstd::copy(m_request.info_hash.begin(), m_request.info_hash.end(), out);\n\n\t\tm_socket->send(&buf[0], buf.size());\n\t\tm_request_time = second_clock::universal_time();\n\t\t++m_attempts;\n\t}\n\n\tvoid udp_tracker_connection::send_udp_connect()\n\t{\n\t\tchar send_buf[16];\n\t\tchar* ptr = send_buf;\n\n\t\tif (m_transaction_id == 0)\n\t\t\tm_transaction_id = rand() ^ (rand() << 16);\n\n\t\t\/\/ connection_id\n\t\tdetail::write_int64(0x41727101980, ptr);\n\t\t\/\/ action (connect)\n\t\tdetail::write_int32(connect, ptr);\n\t\t\/\/ transaction_id\n\t\tdetail::write_int32(m_transaction_id, ptr);\n\n\t\tm_socket->send(send_buf, 16);\n\t\tm_request_time = second_clock::universal_time();\n\t\t++m_attempts;\n\t}\n\n\tbool udp_tracker_connection::parse_announce_response(const char* buf, int len)\n\t{\n\t\tassert(buf != 0);\n\t\tassert(len > 0);\n\n\t\tif (len < 8)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 8, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\n\t\tint action = detail::read_int32(buf);\n\t\tint transaction = detail::read_int32(buf);\n\t\tif (transaction != m_transaction_id)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tif (action == error)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, std::string(buf, buf + len - 8));\n\t\t\treturn true;\n\t\t}\n\t\tif (action != announce) return false;\n\n\t\tif (len < 20)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 20, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\tint interval = detail::read_int32(buf);\n\t\tint incomplete = detail::read_int32(buf);\n\t\tint complete = detail::read_int32(buf);\n\t\tint num_peers = (len - 20) \/ 6;\n\t\tif ((len - 20) % 6 != 0)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, \"invalid tracker response\");\n\t\t\treturn true;\n\t\t}\n\n\t\tif (!has_requester()) return true;\n\n\t\tstd::vector peer_list;\n\t\tfor (int i = 0; i < num_peers; ++i)\n\t\t{\n\t\t\tpeer_entry e;\n\t\t\tstd::stringstream s;\n\t\t\ts << (int)detail::read_uint8(buf) << \".\";\n\t\t\ts << (int)detail::read_uint8(buf) << \".\";\n\t\t\ts << (int)detail::read_uint8(buf) << \".\";\n\t\t\ts << (int)detail::read_uint8(buf);\n\t\t\te.ip = s.str();\n\t\t\te.port = detail::read_uint16(buf);\n\t\t\te.id.clear();\n\t\t\tpeer_list.push_back(e);\n\t\t}\n\n\t\trequester().tracker_response(m_request, peer_list, interval\n\t\t\t, complete, incomplete);\n\t\treturn true;\n\t}\n\n\tbool udp_tracker_connection::parse_scrape_response(const char* buf, int len)\n\t{\n\t\tassert(buf != 0);\n\t\tassert(len > 0);\n\n\t\tif (len < 8)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 8, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\n\t\tint action = detail::read_int32(buf);\n\t\tint transaction = detail::read_int32(buf);\n\t\tif (transaction != m_transaction_id)\n\t\t{\n\t\t\treturn false;\n\t\t}\n\n\t\tif (action == error)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, std::string(buf, buf + len - 8));\n\t\t\treturn true;\n\t\t}\n\t\tif (action != scrape) return false;\n\n\t\tif (len < 20)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 20, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\tint complete = detail::read_int32(buf);\n\t\tint completed = detail::read_int32(buf);\n\t\tint incomplete = detail::read_int32(buf);\n\n\t\tif (!has_requester()) return true;\n\n\t\tstd::vector peer_list;\n\t\trequester().tracker_response(m_request, peer_list, 0\n\t\t\t, complete, incomplete);\n\t\treturn true;\n\t}\n\n\n\tbool udp_tracker_connection::parse_connect_response(const char* buf, int len)\n\t{\n\t\tassert(buf != 0);\n\t\tassert(len > 0);\n\n\t\tif (len < 8)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with size < 8, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\tconst char* ptr = buf;\n\t\tint action = detail::read_int32(ptr);\n\t\tint transaction = detail::read_int32(ptr);\n\n\t\tif (action == error)\n\t\t{\n\t\t\tif (has_requester())\n\t\t\t\trequester().tracker_request_error(\n\t\t\t\t\tm_request, -1, std::string(ptr, buf + len));\n\t\t\treturn true;\n\t\t}\n\t\tif (action != connect) return false;\n\t\tif (m_transaction_id != transaction)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a message with incorrect transaction id, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\n\t\tif (len < 16)\n\t\t{\n#ifdef TORRENT_VERBOSE_LOGGING\n\t\t\tif (has_requester())\n\t\t\t\trequester().debug_log(\"udp_tracker_connection: \"\n\t\t\t\t\"got a connection message size < 16, ignoring\");\n#endif\n\t\t\treturn false;\n\t\t}\n\t\t\/\/ reset transaction\n\t\tm_transaction_id = 0;\n\t\tm_attempts = 0;\n\t\tm_connection_id = detail::read_int64(ptr);\n\n\t\tif (m_request.kind == tracker_request::announce_request)\n\t\t\tsend_udp_announce();\n\t\telse if (m_request.kind == tracker_request::scrape_request)\n\t\t\tsend_udp_scrape();\n\n\t\treturn false;\n\t}\n\n\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"include\/gpu\/GrContext.h\"\n\n#include \"include\/gpu\/GrContextThreadSafeProxy.h\"\n#include \"src\/gpu\/GrContextPriv.h\"\n#include \"src\/gpu\/GrContextThreadSafeProxyPriv.h\"\n#include \"src\/gpu\/GrGpu.h\"\n\n#include \"src\/gpu\/effects\/GrSkSLFP.h\"\n#include \"src\/gpu\/gl\/GrGLGpu.h\"\n#include \"src\/gpu\/mock\/GrMockGpu.h\"\n#include \"src\/gpu\/text\/GrStrikeCache.h\"\n#ifdef SK_METAL\n#include \"src\/gpu\/mtl\/GrMtlTrampoline.h\"\n#endif\n#ifdef SK_VULKAN\n#include \"src\/gpu\/vk\/GrVkGpu.h\"\n#endif\n\n#ifdef SK_DISABLE_REDUCE_OPLIST_SPLITTING\nstatic const bool kDefaultReduceOpListSplitting = false;\n#else\nstatic const bool kDefaultReduceOpListSplitting = true;\n#endif\n\nclass SK_API GrLegacyDirectContext : public GrContext {\npublic:\n GrLegacyDirectContext(GrBackendApi backend, const GrContextOptions& options)\n : INHERITED(backend, options)\n , fAtlasManager(nullptr) {\n }\n\n ~GrLegacyDirectContext() override {\n \/\/ this if-test protects against the case where the context is being destroyed\n \/\/ before having been fully created\n if (this->priv().getGpu()) {\n this->flush();\n }\n\n delete fAtlasManager;\n }\n\n void abandonContext() override {\n INHERITED::abandonContext();\n fAtlasManager->freeAll();\n }\n\n void releaseResourcesAndAbandonContext() override {\n INHERITED::releaseResourcesAndAbandonContext();\n fAtlasManager->freeAll();\n }\n\n void freeGpuResources() override {\n this->flush();\n fAtlasManager->freeAll();\n\n INHERITED::freeGpuResources();\n }\n\nprotected:\n bool init(sk_sp caps, sk_sp FPFactoryCache) override {\n SkASSERT(caps && !FPFactoryCache);\n SkASSERT(!fThreadSafeProxy);\n\n FPFactoryCache.reset(new GrSkSLFPFactoryCache());\n fThreadSafeProxy = GrContextThreadSafeProxyPriv::Make(this->backend(),\n this->options(),\n this->contextID(),\n caps, FPFactoryCache);\n\n if (!INHERITED::init(std::move(caps), std::move(FPFactoryCache))) {\n return false;\n }\n\n bool reduceOpListSplitting = kDefaultReduceOpListSplitting;\n if (GrContextOptions::Enable::kNo == this->options().fReduceOpListSplitting) {\n reduceOpListSplitting = false;\n } else if (GrContextOptions::Enable::kYes == this->options().fReduceOpListSplitting) {\n reduceOpListSplitting = true;\n }\n\n this->setupDrawingManager(true, reduceOpListSplitting);\n\n SkASSERT(this->caps());\n\n GrDrawOpAtlas::AllowMultitexturing allowMultitexturing;\n if (GrContextOptions::Enable::kNo == this->options().fAllowMultipleGlyphCacheTextures ||\n \/\/ multitexturing supported only if range can represent the index + texcoords fully\n !(this->caps()->shaderCaps()->floatIs32Bits() ||\n this->caps()->shaderCaps()->integerSupport())) {\n allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kNo;\n } else {\n allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kYes;\n }\n\n GrStrikeCache* glyphCache = this->priv().getGrStrikeCache();\n GrProxyProvider* proxyProvider = this->priv().proxyProvider();\n\n fAtlasManager = new GrAtlasManager(proxyProvider, glyphCache,\n this->options().fGlyphCacheTextureMaximumBytes,\n allowMultitexturing);\n this->priv().addOnFlushCallbackObject(fAtlasManager);\n\n return true;\n }\n\n GrAtlasManager* onGetAtlasManager() override { return fAtlasManager; }\n\nprivate:\n GrAtlasManager* fAtlasManager;\n\n typedef GrContext INHERITED;\n};\n\nsk_sp GrContext::MakeGL(sk_sp interface) {\n GrContextOptions defaultOptions;\n return MakeGL(std::move(interface), defaultOptions);\n}\n\nsk_sp GrContext::MakeGL(const GrContextOptions& options) {\n return MakeGL(nullptr, options);\n}\n\nsk_sp GrContext::MakeGL() {\n GrContextOptions defaultOptions;\n return MakeGL(nullptr, defaultOptions);\n}\n\nsk_sp GrContext::MakeGL(sk_sp interface,\n const GrContextOptions& options) {\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kOpenGL, options));\n\n context->fGpu = GrGLGpu::Make(std::move(interface), options, context.get());\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n}\n\nsk_sp GrContext::MakeMock(const GrMockOptions* mockOptions) {\n GrContextOptions defaultOptions;\n return MakeMock(mockOptions, defaultOptions);\n}\n\nsk_sp GrContext::MakeMock(const GrMockOptions* mockOptions,\n const GrContextOptions& options) {\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kMock, options));\n\n context->fGpu = GrMockGpu::Make(mockOptions, options, context.get());\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n}\n\nsk_sp GrContext::MakeVulkan(const GrVkBackendContext& backendContext) {\n#ifdef SK_VULKAN\n GrContextOptions defaultOptions;\n return MakeVulkan(backendContext, defaultOptions);\n#else\n return nullptr;\n#endif\n}\n\nsk_sp GrContext::MakeVulkan(const GrVkBackendContext& backendContext,\n const GrContextOptions& options) {\n#ifdef SK_VULKAN\n GrContextOptions defaultOptions;\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kVulkan, options));\n\n context->fGpu = GrVkGpu::Make(backendContext, options, context.get());\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n#else\n return nullptr;\n#endif\n}\n\n#ifdef SK_METAL\nsk_sp GrContext::MakeMetal(void* device, void* queue) {\n GrContextOptions defaultOptions;\n return MakeMetal(device, queue, defaultOptions);\n}\n\nsk_sp GrContext::MakeMetal(void* device, void* queue, const GrContextOptions& options) {\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kMetal, options));\n\n context->fGpu = GrMtlTrampoline::MakeGpu(context.get(), options, device, queue);\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n}\n#endif\n\nChange opList-splitting reduction default to be off\/*\n * Copyright 2018 Google Inc.\n *\n * Use of this source code is governed by a BSD-style license that can be\n * found in the LICENSE file.\n *\/\n\n\n#include \"include\/gpu\/GrContext.h\"\n\n#include \"include\/gpu\/GrContextThreadSafeProxy.h\"\n#include \"src\/gpu\/GrContextPriv.h\"\n#include \"src\/gpu\/GrContextThreadSafeProxyPriv.h\"\n#include \"src\/gpu\/GrGpu.h\"\n\n#include \"src\/gpu\/effects\/GrSkSLFP.h\"\n#include \"src\/gpu\/gl\/GrGLGpu.h\"\n#include \"src\/gpu\/mock\/GrMockGpu.h\"\n#include \"src\/gpu\/text\/GrStrikeCache.h\"\n#ifdef SK_METAL\n#include \"src\/gpu\/mtl\/GrMtlTrampoline.h\"\n#endif\n#ifdef SK_VULKAN\n#include \"src\/gpu\/vk\/GrVkGpu.h\"\n#endif\n\n#ifdef SK_DISABLE_REDUCE_OPLIST_SPLITTING\nstatic const bool kDefaultReduceOpListSplitting = false;\n#else\nstatic const bool kDefaultReduceOpListSplitting = false;\n#endif\n\nclass SK_API GrLegacyDirectContext : public GrContext {\npublic:\n GrLegacyDirectContext(GrBackendApi backend, const GrContextOptions& options)\n : INHERITED(backend, options)\n , fAtlasManager(nullptr) {\n }\n\n ~GrLegacyDirectContext() override {\n \/\/ this if-test protects against the case where the context is being destroyed\n \/\/ before having been fully created\n if (this->priv().getGpu()) {\n this->flush();\n }\n\n delete fAtlasManager;\n }\n\n void abandonContext() override {\n INHERITED::abandonContext();\n fAtlasManager->freeAll();\n }\n\n void releaseResourcesAndAbandonContext() override {\n INHERITED::releaseResourcesAndAbandonContext();\n fAtlasManager->freeAll();\n }\n\n void freeGpuResources() override {\n this->flush();\n fAtlasManager->freeAll();\n\n INHERITED::freeGpuResources();\n }\n\nprotected:\n bool init(sk_sp caps, sk_sp FPFactoryCache) override {\n SkASSERT(caps && !FPFactoryCache);\n SkASSERT(!fThreadSafeProxy);\n\n FPFactoryCache.reset(new GrSkSLFPFactoryCache());\n fThreadSafeProxy = GrContextThreadSafeProxyPriv::Make(this->backend(),\n this->options(),\n this->contextID(),\n caps, FPFactoryCache);\n\n if (!INHERITED::init(std::move(caps), std::move(FPFactoryCache))) {\n return false;\n }\n\n bool reduceOpListSplitting = kDefaultReduceOpListSplitting;\n if (GrContextOptions::Enable::kNo == this->options().fReduceOpListSplitting) {\n reduceOpListSplitting = false;\n } else if (GrContextOptions::Enable::kYes == this->options().fReduceOpListSplitting) {\n reduceOpListSplitting = true;\n }\n\n this->setupDrawingManager(true, reduceOpListSplitting);\n\n SkASSERT(this->caps());\n\n GrDrawOpAtlas::AllowMultitexturing allowMultitexturing;\n if (GrContextOptions::Enable::kNo == this->options().fAllowMultipleGlyphCacheTextures ||\n \/\/ multitexturing supported only if range can represent the index + texcoords fully\n !(this->caps()->shaderCaps()->floatIs32Bits() ||\n this->caps()->shaderCaps()->integerSupport())) {\n allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kNo;\n } else {\n allowMultitexturing = GrDrawOpAtlas::AllowMultitexturing::kYes;\n }\n\n GrStrikeCache* glyphCache = this->priv().getGrStrikeCache();\n GrProxyProvider* proxyProvider = this->priv().proxyProvider();\n\n fAtlasManager = new GrAtlasManager(proxyProvider, glyphCache,\n this->options().fGlyphCacheTextureMaximumBytes,\n allowMultitexturing);\n this->priv().addOnFlushCallbackObject(fAtlasManager);\n\n return true;\n }\n\n GrAtlasManager* onGetAtlasManager() override { return fAtlasManager; }\n\nprivate:\n GrAtlasManager* fAtlasManager;\n\n typedef GrContext INHERITED;\n};\n\nsk_sp GrContext::MakeGL(sk_sp interface) {\n GrContextOptions defaultOptions;\n return MakeGL(std::move(interface), defaultOptions);\n}\n\nsk_sp GrContext::MakeGL(const GrContextOptions& options) {\n return MakeGL(nullptr, options);\n}\n\nsk_sp GrContext::MakeGL() {\n GrContextOptions defaultOptions;\n return MakeGL(nullptr, defaultOptions);\n}\n\nsk_sp GrContext::MakeGL(sk_sp interface,\n const GrContextOptions& options) {\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kOpenGL, options));\n\n context->fGpu = GrGLGpu::Make(std::move(interface), options, context.get());\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n}\n\nsk_sp GrContext::MakeMock(const GrMockOptions* mockOptions) {\n GrContextOptions defaultOptions;\n return MakeMock(mockOptions, defaultOptions);\n}\n\nsk_sp GrContext::MakeMock(const GrMockOptions* mockOptions,\n const GrContextOptions& options) {\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kMock, options));\n\n context->fGpu = GrMockGpu::Make(mockOptions, options, context.get());\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n}\n\nsk_sp GrContext::MakeVulkan(const GrVkBackendContext& backendContext) {\n#ifdef SK_VULKAN\n GrContextOptions defaultOptions;\n return MakeVulkan(backendContext, defaultOptions);\n#else\n return nullptr;\n#endif\n}\n\nsk_sp GrContext::MakeVulkan(const GrVkBackendContext& backendContext,\n const GrContextOptions& options) {\n#ifdef SK_VULKAN\n GrContextOptions defaultOptions;\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kVulkan, options));\n\n context->fGpu = GrVkGpu::Make(backendContext, options, context.get());\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n#else\n return nullptr;\n#endif\n}\n\n#ifdef SK_METAL\nsk_sp GrContext::MakeMetal(void* device, void* queue) {\n GrContextOptions defaultOptions;\n return MakeMetal(device, queue, defaultOptions);\n}\n\nsk_sp GrContext::MakeMetal(void* device, void* queue, const GrContextOptions& options) {\n sk_sp context(new GrLegacyDirectContext(GrBackendApi::kMetal, options));\n\n context->fGpu = GrMtlTrampoline::MakeGpu(context.get(), options, device, queue);\n if (!context->fGpu) {\n return nullptr;\n }\n\n if (!context->init(context->fGpu->refCaps(), nullptr)) {\n return nullptr;\n }\n return context;\n}\n#endif\n\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mimagewidgetview.h\"\n#include \"mimagewidgetview_p.h\"\n\n#include \n\n#include \"mimagewidget.h\"\n#include \"mimagewidget_p.h\"\n#include \"mviewcreator.h\"\n#include \"private\/mwidgetview_p.h\"\n\nMImageWidgetViewPrivate::MImageWidgetViewPrivate()\n : controller(NULL),\n cachedPixmapSize(0, 0),\n borderOpacity(1.0),\n brush(Qt::transparent),\n leftBorder(0.0),\n topBorder(0.0),\n rightBorder(0.0),\n bottomBorder(0.0)\n{\n}\n\nMImageWidgetViewPrivate::~MImageWidgetViewPrivate()\n{\n}\n\nvoid MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)\n{\n Q_Q(MImageWidgetView);\n\n \/\/ no image, return\n if (imageSize.isEmpty())\n return;\n\n \/\/ get target size, bounded by widget size\n QSizeF widgetSize = q->size();\n QSizeF targetSize = widgetSize;\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ limited by target size\n t = targetSize.boundedTo(t);\n\n \/\/ calculate the rectangle of draw\n qreal dx = (widgetSize.width() - t.width()) \/ 2.0;\n qreal dy = (widgetSize.height() - t.height()) \/ 2.0;\n\n \/\/ calculate draw rect\n drawRect.setRect(dx, dy, t.width(), t.height());\n}\n\nQSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)\n{\n QSizeF sourceSize = imageSize;\n QSizeF targetSize = controller->size();\n\n \/\/ protection codes\n if (sourceSize.width() < 1.0)\n sourceSize.setWidth(1.0);\n if (sourceSize.height() < 1.0)\n sourceSize.setHeight(1.0);\n\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ update sourceSize for crop section by compare with targetSize, simulate zoom effect\n qreal value;\n if (t.width() > targetSize.width()) {\n value = sourceSize.width();\n sourceSize.setWidth(qRound(value * targetSize.width() \/ t.width()));\n }\n if (t.height() > targetSize.height()) {\n value = sourceSize.height();\n sourceSize.setHeight(qRound(value * targetSize.height() \/ t.height()));\n }\n\n return sourceSize;\n}\n\nvoid MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)\n{\n QPointF topLeft = controller->crop().topLeft();\n QSizeF originalSize = controller->imageSize();\n QSizeF sourceSize = calculateSourceSize(imageSize);\n\n if (topLeft == QPointF(-1.0, -1.0)) {\n \/\/ calculate default crop section\n qreal dx = (originalSize.width() - sourceSize.width()) \/ 2.0;\n qreal dy = (originalSize.height() - sourceSize.height()) \/ 2.0;\n\n sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());\n } else {\n \/\/ calculate crop section by given topLeft corner\n qreal dx = topLeft.x();\n qreal dy = topLeft.y();\n\n sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),\n qMin(dy + sourceSize.height(), originalSize.height()));\n }\n}\n\nvoid MImageWidgetViewPrivate::checkPixmapSize()\n{\n Q_Q(MImageWidgetView);\n\n const QPixmap *pixmap = controller->pixmap();\n if (pixmap->size() != cachedPixmapSize) {\n cachedPixmapSize = pixmap->size();\n q->updateGeometry();\n }\n}\n\nvoid MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const\n{\n qreal w = leftBorder + rightBorder;\n qreal h = topBorder + bottomBorder;\n\n if (w > 0 || h > 0) {\n QRectF border;\n\n qreal oldOpacity = painter->opacity();\n painter->setOpacity(borderOpacity);\n\n qreal dx = drawRect.x() - leftBorder;\n qreal dy = drawRect.y() - topBorder;\n\n if (w > 0 && h == 0) {\n \/\/ only have horizontal border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n } else if (w == 0 && h > 0) {\n \/\/ only have vertical border\n border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);\n painter->fillRect(border, brush);\n } else {\n \/\/ draw top border\n border = QRectF(dx, dy, drawRect.width() + w, topBorder);\n painter->fillRect(border, brush);\n\n \/\/ draw left border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw right border\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw bottom border\n border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);\n painter->fillRect(border, brush);\n }\n painter->setOpacity(oldOpacity);\n }\n\n}\n\nvoid MImageWidgetViewPrivate::applyStyle()\n{\n Q_Q(MImageWidgetView);\n\n borderOpacity = q->style()->borderOpacity();\n brush.setColor(q->style()->borderColor());\n\n leftBorder = q->style()->borderLeft();\n topBorder = q->style()->borderTop();\n rightBorder = q->style()->borderRight();\n bottomBorder = q->style()->borderBottom();\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidget *controller) :\n MWidgetView(* new MImageWidgetViewPrivate, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :\n MWidgetView(dd, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::~MImageWidgetView()\n{\n}\n\nvoid MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n\n Q_D(const MImageWidgetView);\n\n const QPixmap *pixmap = d->controller->pixmap(); \n\n d->drawBorders(painter, d->drawRect);\n\n if (pixmap) {\n const_cast(d)->checkPixmapSize();\n painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);\n } else {\n QImage image = d->controller->d_func()->image;\n painter->drawImage(d->drawRect, image, d->sourceRect);\n }\n}\n\nvoid MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n MWidgetView::resizeEvent(event);\n update();\n}\n\nvoid MImageWidgetView::setGeometry(const QRectF &rect)\n{\n Q_D(MImageWidgetView);\n MWidgetView::setGeometry(rect);\n\n QSizeF imageSize = d->controller->d_func()->imageDataSize();\n d->calculateDrawRect(imageSize);\n d->calculateSourceRect(imageSize);\n}\n\nvoid MImageWidgetView::applyStyle()\n{\n Q_D(MImageWidgetView);\n MWidgetView::applyStyle();\n\n d->applyStyle();\n}\n\nvoid MImageWidgetView::updateData(const QList &modifications)\n{\n MWidgetView::updateData(modifications);\n\n const char *member;\n for (int i = 0; i < modifications.count(); i++) {\n member = modifications[i];\n if (member == MImageWidgetModel::ZoomFactorX || member == MImageWidgetModel::ZoomFactorY || member == MImageWidgetModel::Crop) {\n updateGeometry();\n }\n }\n}\n\nQSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n Q_D(const MImageWidgetView);\n\n QSizeF s = MWidgetView::sizeHint(which, constraint);\n if(s.isValid())\n return s;\n\n QSizeF s2;\n if(which == Qt::MinimumSize)\n s2 = QSizeF(0,0);\n else if(which == Qt::MaximumSize)\n s2 = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n else\n s2 = d->controller->imageSize();\n\n if(s.height() < 0)\n s.setHeight(s2.height());\n if(s.width() < 0)\n s.setWidth(s2.width());\n return s;\n}\n\nM_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)\n\nChanges: MImageWidgetView checks if widget has pixmap directly from private object.\/***************************************************************************\n**\n** Copyright (C) 2010 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mimagewidgetview.h\"\n#include \"mimagewidgetview_p.h\"\n\n#include \n\n#include \"mimagewidget.h\"\n#include \"mimagewidget_p.h\"\n#include \"mviewcreator.h\"\n#include \"private\/mwidgetview_p.h\"\n\nMImageWidgetViewPrivate::MImageWidgetViewPrivate()\n : controller(NULL),\n cachedPixmapSize(0, 0),\n borderOpacity(1.0),\n brush(Qt::transparent),\n leftBorder(0.0),\n topBorder(0.0),\n rightBorder(0.0),\n bottomBorder(0.0)\n{\n}\n\nMImageWidgetViewPrivate::~MImageWidgetViewPrivate()\n{\n}\n\nvoid MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)\n{\n Q_Q(MImageWidgetView);\n\n \/\/ no image, return\n if (imageSize.isEmpty())\n return;\n\n \/\/ get target size, bounded by widget size\n QSizeF widgetSize = q->size();\n QSizeF targetSize = widgetSize;\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ limited by target size\n t = targetSize.boundedTo(t);\n\n \/\/ calculate the rectangle of draw\n qreal dx = (widgetSize.width() - t.width()) \/ 2.0;\n qreal dy = (widgetSize.height() - t.height()) \/ 2.0;\n\n \/\/ calculate draw rect\n drawRect.setRect(dx, dy, t.width(), t.height());\n}\n\nQSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)\n{\n QSizeF sourceSize = imageSize;\n QSizeF targetSize = controller->size();\n\n \/\/ protection codes\n if (sourceSize.width() < 1.0)\n sourceSize.setWidth(1.0);\n if (sourceSize.height() < 1.0)\n sourceSize.setHeight(1.0);\n\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ update sourceSize for crop section by compare with targetSize, simulate zoom effect\n qreal value;\n if (t.width() > targetSize.width()) {\n value = sourceSize.width();\n sourceSize.setWidth(qRound(value * targetSize.width() \/ t.width()));\n }\n if (t.height() > targetSize.height()) {\n value = sourceSize.height();\n sourceSize.setHeight(qRound(value * targetSize.height() \/ t.height()));\n }\n\n return sourceSize;\n}\n\nvoid MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)\n{\n QPointF topLeft = controller->crop().topLeft();\n QSizeF originalSize = controller->imageSize();\n QSizeF sourceSize = calculateSourceSize(imageSize);\n\n if (topLeft == QPointF(-1.0, -1.0)) {\n \/\/ calculate default crop section\n qreal dx = (originalSize.width() - sourceSize.width()) \/ 2.0;\n qreal dy = (originalSize.height() - sourceSize.height()) \/ 2.0;\n\n sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());\n } else {\n \/\/ calculate crop section by given topLeft corner\n qreal dx = topLeft.x();\n qreal dy = topLeft.y();\n\n sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),\n qMin(dy + sourceSize.height(), originalSize.height()));\n }\n}\n\nvoid MImageWidgetViewPrivate::checkPixmapSize()\n{\n Q_Q(MImageWidgetView);\n\n const QPixmap *pixmap = controller->pixmap();\n if (pixmap->size() != cachedPixmapSize) {\n cachedPixmapSize = pixmap->size();\n q->updateGeometry();\n }\n}\n\nvoid MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const\n{\n qreal w = leftBorder + rightBorder;\n qreal h = topBorder + bottomBorder;\n\n if (w > 0 || h > 0) {\n QRectF border;\n\n qreal oldOpacity = painter->opacity();\n painter->setOpacity(borderOpacity);\n\n qreal dx = drawRect.x() - leftBorder;\n qreal dy = drawRect.y() - topBorder;\n\n if (w > 0 && h == 0) {\n \/\/ only have horizontal border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n } else if (w == 0 && h > 0) {\n \/\/ only have vertical border\n border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);\n painter->fillRect(border, brush);\n } else {\n \/\/ draw top border\n border = QRectF(dx, dy, drawRect.width() + w, topBorder);\n painter->fillRect(border, brush);\n\n \/\/ draw left border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw right border\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw bottom border\n border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);\n painter->fillRect(border, brush);\n }\n painter->setOpacity(oldOpacity);\n }\n\n}\n\nvoid MImageWidgetViewPrivate::applyStyle()\n{\n Q_Q(MImageWidgetView);\n\n borderOpacity = q->style()->borderOpacity();\n brush.setColor(q->style()->borderColor());\n\n leftBorder = q->style()->borderLeft();\n topBorder = q->style()->borderTop();\n rightBorder = q->style()->borderRight();\n bottomBorder = q->style()->borderBottom();\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidget *controller) :\n MWidgetView(* new MImageWidgetViewPrivate, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :\n MWidgetView(dd, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::~MImageWidgetView()\n{\n}\n\nvoid MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n\n Q_D(const MImageWidgetView);\n\n const QPixmap *pixmap = d->controller->d_func()->pixmap; \n\n d->drawBorders(painter, d->drawRect);\n\n if (pixmap) {\n const_cast(d)->checkPixmapSize();\n painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);\n } else {\n QImage image = d->controller->d_func()->image;\n painter->drawImage(d->drawRect, image, d->sourceRect);\n }\n}\n\nvoid MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n MWidgetView::resizeEvent(event);\n update();\n}\n\nvoid MImageWidgetView::setGeometry(const QRectF &rect)\n{\n Q_D(MImageWidgetView);\n MWidgetView::setGeometry(rect);\n\n QSizeF imageSize = d->controller->d_func()->imageDataSize();\n d->calculateDrawRect(imageSize);\n d->calculateSourceRect(imageSize);\n}\n\nvoid MImageWidgetView::applyStyle()\n{\n Q_D(MImageWidgetView);\n MWidgetView::applyStyle();\n\n d->applyStyle();\n}\n\nvoid MImageWidgetView::updateData(const QList &modifications)\n{\n MWidgetView::updateData(modifications);\n\n const char *member;\n for (int i = 0; i < modifications.count(); i++) {\n member = modifications[i];\n if (member == MImageWidgetModel::ZoomFactorX || member == MImageWidgetModel::ZoomFactorY || member == MImageWidgetModel::Crop) {\n updateGeometry();\n }\n }\n}\n\nQSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n Q_D(const MImageWidgetView);\n\n QSizeF s = MWidgetView::sizeHint(which, constraint);\n if(s.isValid())\n return s;\n\n QSizeF s2;\n if(which == Qt::MinimumSize)\n s2 = QSizeF(0,0);\n else if(which == Qt::MaximumSize)\n s2 = QSizeF(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX);\n else\n s2 = d->controller->imageSize();\n\n if(s.height() < 0)\n s.setHeight(s2.height());\n if(s.width() < 0)\n s.setWidth(s2.width());\n return s;\n}\n\nM_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)\n\n<|endoftext|>"} {"text":"\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mimagewidgetview.h\"\n#include \"mimagewidgetview_p.h\"\n\n#include \n\n#include \"mimagewidget.h\"\n#include \"mimagewidget_p.h\"\n#include \"mviewcreator.h\"\n#include \"private\/mwidgetview_p.h\"\n\nMImageWidgetViewPrivate::MImageWidgetViewPrivate()\n : controller(NULL),\n cachedPixmapSize(0, 0),\n borderOpacity(1.0),\n brush(Qt::transparent),\n leftBorder(0.0),\n topBorder(0.0),\n rightBorder(0.0),\n bottomBorder(0.0)\n{\n}\n\nMImageWidgetViewPrivate::~MImageWidgetViewPrivate()\n{\n}\n\nvoid MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)\n{\n Q_Q(MImageWidgetView);\n\n \/\/ no image, return\n if (imageSize.isEmpty())\n return;\n\n \/\/ get target size, bounded by widget size\n QSizeF widgetSize = q->size();\n QSizeF targetSize = widgetSize;\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ limited by target size\n t = targetSize.boundedTo(t);\n\n \/\/ calculate the rectangle of draw\n qreal dx = (widgetSize.width() - t.width()) \/ 2.f;\n qreal dy = (widgetSize.height() - t.height()) \/ 2.f;\n\n \/\/ calculate draw rect\n drawRect.setRect(dx, dy, t.width(), t.height());\n}\n\nQSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)\n{\n QSizeF sourceSize = imageSize;\n QSizeF targetSize = controller->size();\n\n \/\/ protection codes\n if (sourceSize.width() < 1.0)\n sourceSize.setWidth(1.f);\n if (sourceSize.height() < 1.0)\n sourceSize.setHeight(1.f);\n\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ update sourceSize for crop section by compare with targetSize, simulate zoom effect\n qreal value;\n if (t.width() > targetSize.width()) {\n value = sourceSize.width();\n sourceSize.setWidth(qRound(value * targetSize.width() \/ t.width()));\n }\n if (t.height() > targetSize.height()) {\n value = sourceSize.height();\n sourceSize.setHeight(qRound(value * targetSize.height() \/ t.height()));\n }\n\n return sourceSize;\n}\n\nvoid MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)\n{\n QPointF topLeft = controller->crop().topLeft();\n QSizeF originalSize = controller->imageSize();\n QSizeF sourceSize = calculateSourceSize(imageSize);\n\n if (topLeft == QPointF(-1.0, -1.0)) {\n \/\/ calculate default crop section\n qreal dx = (originalSize.width() - sourceSize.width()) \/ 2.f;\n qreal dy = (originalSize.height() - sourceSize.height()) \/ 2.f;\n\n sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());\n } else {\n \/\/ calculate crop section by given topLeft corner\n qreal dx = topLeft.x();\n qreal dy = topLeft.y();\n\n sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),\n qMin(dy + sourceSize.height(), originalSize.height()));\n }\n}\n\nvoid MImageWidgetViewPrivate::checkPixmapSize()\n{\n Q_Q(MImageWidgetView);\n\n const QPixmap *pixmap = controller->pixmap();\n if (pixmap->size() != cachedPixmapSize) {\n cachedPixmapSize = pixmap->size();\n q->updateGeometry();\n }\n}\n\nvoid MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const\n{\n qreal w = leftBorder + rightBorder;\n qreal h = topBorder + bottomBorder;\n\n if (w > 0 || h > 0) {\n QRectF border;\n\n qreal oldOpacity = painter->opacity();\n painter->setOpacity(borderOpacity);\n\n qreal dx = drawRect.x() - leftBorder;\n qreal dy = drawRect.y() - topBorder;\n\n if (w > 0 && h == 0) {\n \/\/ only have horizontal border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n } else if (w == 0 && h > 0) {\n \/\/ only have vertical border\n border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);\n painter->fillRect(border, brush);\n } else {\n \/\/ draw top border\n border = QRectF(dx, dy, drawRect.width() + w, topBorder);\n painter->fillRect(border, brush);\n\n \/\/ draw left border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw right border\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw bottom border\n border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);\n painter->fillRect(border, brush);\n }\n painter->setOpacity(oldOpacity);\n }\n\n}\n\nvoid MImageWidgetViewPrivate::applyStyle()\n{\n Q_Q(MImageWidgetView);\n\n borderOpacity = q->style()->borderOpacity();\n brush.setColor(q->style()->borderColor());\n\n leftBorder = q->style()->borderLeft();\n topBorder = q->style()->borderTop();\n rightBorder = q->style()->borderRight();\n bottomBorder = q->style()->borderBottom();\n}\n\nconst QPixmap *MImageWidgetViewPrivate::createPixmapFromTheme()\n{\n QSize imageSize = controller->model()->imageSize();\n QString imageId = controller->imageId();\n\n if (!imageSize.isValid() || imageSize.isNull())\n imageSize = preferredImageSize();\n\n if (!imageSize.isValid())\n return MTheme::pixmap(imageId);\n\n return MTheme::pixmap(imageId, imageSize);\n}\n\nQSize MImageWidgetViewPrivate::preferredImageSize()\n{\n Q_Q(MImageWidgetView);\n\n QSize imageSize = controller->preferredSize().toSize();\n imageSize.setWidth(imageSize.width() - (q->marginLeft() + q->marginRight()));\n imageSize.setHeight(imageSize.height() - (q->marginTop() + q->marginBottom()));\n\n return imageSize;\n}\n\nvoid MImageWidgetViewPrivate::updateImageGeometry()\n{\n Q_Q(MImageWidgetView);\n QSizeF imageSize = q->imageDataSize();\n\n calculateDrawRect(imageSize);\n calculateSourceRect(imageSize);\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidget *controller) :\n MWidgetView(* new MImageWidgetViewPrivate, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :\n MWidgetView(dd, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::~MImageWidgetView()\n{\n}\n\nvoid MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n\n Q_D(const MImageWidgetView);\n\n const QPixmap *pixmap = d->controller->d_func()->getPixmap();\n\n d->drawBorders(painter, d->drawRect);\n\n if (pixmap) {\n const_cast(d)->checkPixmapSize();\n painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);\n } else\n painter->drawImage(d->drawRect, d->controller->d_func()->getImage(), d->sourceRect);\n}\n\nvoid MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n MWidgetView::resizeEvent(event);\n update();\n}\n\nvoid MImageWidgetView::setGeometry(const QRectF &rect)\n{\n Q_D(MImageWidgetView);\n MWidgetView::setGeometry(rect);\n\n d->updateImageGeometry();\n}\n\nvoid MImageWidgetView::updateGeometry()\n{\n Q_D(MImageWidgetView);\n\n MWidgetView::updateGeometry();\n\n d->updateImageGeometry();\n}\n\nvoid MImageWidgetView::applyStyle()\n{\n Q_D(MImageWidgetView);\n MWidgetView::applyStyle();\n\n d->applyStyle();\n\n if (!model()->imageId().isEmpty())\n d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);\n}\n\nvoid MImageWidgetView::updateData(const QList &modifications)\n{\n Q_D(MImageWidgetView);\n MWidgetView::updateData(modifications);\n\n bool needsGeometryUpdate = false;\n bool needsPixmap = false;\n const char *member;\n for (int i = 0; i < modifications.count(); i++) {\n member = modifications[i];\n if (member == MImageWidgetModel::ZoomFactorX ||\n member == MImageWidgetModel::ZoomFactorY ||\n member == MImageWidgetModel::Crop ||\n member == MImageWidgetModel::AspectRatioMode) {\n needsGeometryUpdate = true;\n } else if (member == MImageWidgetModel::ImageId ||\n member == MImageWidgetModel::ImageSize) {\n needsPixmap = true;\n }\n }\n\n if (needsPixmap && !model()->imageId().isEmpty())\n d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);\n\n if (needsGeometryUpdate || needsPixmap)\n updateGeometry();\n}\n\nQSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n Q_D(const MImageWidgetView);\n\n if (which == Qt::MinimumSize || which == Qt::MaximumSize)\n return QSizeF(-1,-1);\n\n QSizeF size = d->controller->imageSize();\n\n \/\/ an empty QSize() translates to (-1,-1) which would result in an incorrect size hint\n if (!size.isValid())\n size = QSizeF(0, 0);\n\n if (constraint.width() >= 0 && constraint.width() < size.width())\n size.scale(QSizeF(constraint.width(), QWIDGETSIZE_MAX), Qt::KeepAspectRatio);\n else if (constraint.height() >= 0 && constraint.height() < size.height())\n size.scale(QSizeF(QWIDGETSIZE_MAX, constraint.height()), Qt::KeepAspectRatio);\n return size;\n}\n\nQSize MImageWidgetView::imageDataSize()\n{\n Q_D(MImageWidgetView);\n\n return d->controller->d_func()->imageDataSize(model()->crop()).toSize();\n}\n\nM_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)\n\nFixes: NB#299022 - MImageWidget does not render properly the images when a QPixmap is used Changes: enable smooth transformation in MImageWidget for QPixmap RevBy: Heikki Holstila, Vesa Halttunen Details: when the setPixmap method is used in MImageWidget, the QPixmap is provided without mthedaemon interaction, thus, MScalableImage is not called, and it is a requirement to draw the QPixmap with the same transformation as MThemedaemon does, to avoid any blurriness\/***************************************************************************\n**\n** Copyright (C) 2010, 2011 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (directui@nokia.com)\n**\n** This file is part of libmeegotouch.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at directui@nokia.com.\n**\n** This library is free software; you can redistribute it and\/or\n** modify it under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation\n** and appearing in the file LICENSE.LGPL included in the packaging\n** of this file.\n**\n****************************************************************************\/\n\n#include \"mimagewidgetview.h\"\n#include \"mimagewidgetview_p.h\"\n\n#include \n\n#include \"mimagewidget.h\"\n#include \"mimagewidget_p.h\"\n#include \"mviewcreator.h\"\n#include \"private\/mwidgetview_p.h\"\n\nMImageWidgetViewPrivate::MImageWidgetViewPrivate()\n : controller(NULL),\n cachedPixmapSize(0, 0),\n borderOpacity(1.0),\n brush(Qt::transparent),\n leftBorder(0.0),\n topBorder(0.0),\n rightBorder(0.0),\n bottomBorder(0.0)\n{\n}\n\nMImageWidgetViewPrivate::~MImageWidgetViewPrivate()\n{\n}\n\nvoid MImageWidgetViewPrivate::calculateDrawRect(const QSizeF &imageSize)\n{\n Q_Q(MImageWidgetView);\n\n \/\/ no image, return\n if (imageSize.isEmpty())\n return;\n\n \/\/ get target size, bounded by widget size\n QSizeF widgetSize = q->size();\n QSizeF targetSize = widgetSize;\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ limited by target size\n t = targetSize.boundedTo(t);\n\n \/\/ calculate the rectangle of draw\n qreal dx = (widgetSize.width() - t.width()) \/ 2.f;\n qreal dy = (widgetSize.height() - t.height()) \/ 2.f;\n\n \/\/ calculate draw rect\n drawRect.setRect(dx, dy, t.width(), t.height());\n}\n\nQSizeF MImageWidgetViewPrivate::calculateSourceSize(const QSizeF &imageSize)\n{\n QSizeF sourceSize = imageSize;\n QSizeF targetSize = controller->size();\n\n \/\/ protection codes\n if (sourceSize.width() < 1.0)\n sourceSize.setWidth(1.f);\n if (sourceSize.height() < 1.0)\n sourceSize.setHeight(1.f);\n\n QSizeF t;\n\n \/\/ get the image display size\n qreal fx, fy;\n controller->zoomFactor(&fx, &fy);\n\n t.setWidth(imageSize.width()*fx);\n t.setHeight(imageSize.height()*fy);\n\n \/\/ update sourceSize for crop section by compare with targetSize, simulate zoom effect\n qreal value;\n if (t.width() > targetSize.width()) {\n value = sourceSize.width();\n sourceSize.setWidth(qRound(value * targetSize.width() \/ t.width()));\n }\n if (t.height() > targetSize.height()) {\n value = sourceSize.height();\n sourceSize.setHeight(qRound(value * targetSize.height() \/ t.height()));\n }\n\n return sourceSize;\n}\n\nvoid MImageWidgetViewPrivate::calculateSourceRect(const QSizeF &imageSize)\n{\n QPointF topLeft = controller->crop().topLeft();\n QSizeF originalSize = controller->imageSize();\n QSizeF sourceSize = calculateSourceSize(imageSize);\n\n if (topLeft == QPointF(-1.0, -1.0)) {\n \/\/ calculate default crop section\n qreal dx = (originalSize.width() - sourceSize.width()) \/ 2.f;\n qreal dy = (originalSize.height() - sourceSize.height()) \/ 2.f;\n\n sourceRect = QRectF(dx, dy, sourceSize.width(), sourceSize.height());\n } else {\n \/\/ calculate crop section by given topLeft corner\n qreal dx = topLeft.x();\n qreal dy = topLeft.y();\n\n sourceRect = QRectF(dx, dy, qMin(dx + sourceSize.width(), originalSize.width()),\n qMin(dy + sourceSize.height(), originalSize.height()));\n }\n}\n\nvoid MImageWidgetViewPrivate::checkPixmapSize()\n{\n Q_Q(MImageWidgetView);\n\n const QPixmap *pixmap = controller->pixmap();\n if (pixmap->size() != cachedPixmapSize) {\n cachedPixmapSize = pixmap->size();\n q->updateGeometry();\n }\n}\n\nvoid MImageWidgetViewPrivate::drawBorders(QPainter *painter, const QRectF &drawRect) const\n{\n qreal w = leftBorder + rightBorder;\n qreal h = topBorder + bottomBorder;\n\n if (w > 0 || h > 0) {\n QRectF border;\n\n qreal oldOpacity = painter->opacity();\n painter->setOpacity(borderOpacity);\n\n qreal dx = drawRect.x() - leftBorder;\n qreal dy = drawRect.y() - topBorder;\n\n if (w > 0 && h == 0) {\n \/\/ only have horizontal border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n } else if (w == 0 && h > 0) {\n \/\/ only have vertical border\n border = QRectF(drawRect.x(), dy, drawRect.width(), topBorder);\n painter->fillRect(border, brush);\n\n border = QRectF(drawRect.x(), drawRect.y() + drawRect.height(), drawRect.width(), bottomBorder);\n painter->fillRect(border, brush);\n } else {\n \/\/ draw top border\n border = QRectF(dx, dy, drawRect.width() + w, topBorder);\n painter->fillRect(border, brush);\n\n \/\/ draw left border\n border = QRectF(dx, drawRect.y(), leftBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw right border\n border = QRectF(drawRect.x() + drawRect.width(), drawRect.y(), rightBorder, drawRect.height());\n painter->fillRect(border, brush);\n\n \/\/ draw bottom border\n border = QRectF(dx, drawRect.y() + drawRect.height(), drawRect.width() + w, bottomBorder);\n painter->fillRect(border, brush);\n }\n painter->setOpacity(oldOpacity);\n }\n\n}\n\nvoid MImageWidgetViewPrivate::applyStyle()\n{\n Q_Q(MImageWidgetView);\n\n borderOpacity = q->style()->borderOpacity();\n brush.setColor(q->style()->borderColor());\n\n leftBorder = q->style()->borderLeft();\n topBorder = q->style()->borderTop();\n rightBorder = q->style()->borderRight();\n bottomBorder = q->style()->borderBottom();\n}\n\nconst QPixmap *MImageWidgetViewPrivate::createPixmapFromTheme()\n{\n QSize imageSize = controller->model()->imageSize();\n QString imageId = controller->imageId();\n\n if (!imageSize.isValid() || imageSize.isNull())\n imageSize = preferredImageSize();\n\n if (!imageSize.isValid())\n return MTheme::pixmap(imageId);\n\n return MTheme::pixmap(imageId, imageSize);\n}\n\nQSize MImageWidgetViewPrivate::preferredImageSize()\n{\n Q_Q(MImageWidgetView);\n\n QSize imageSize = controller->preferredSize().toSize();\n imageSize.setWidth(imageSize.width() - (q->marginLeft() + q->marginRight()));\n imageSize.setHeight(imageSize.height() - (q->marginTop() + q->marginBottom()));\n\n return imageSize;\n}\n\nvoid MImageWidgetViewPrivate::updateImageGeometry()\n{\n Q_Q(MImageWidgetView);\n QSizeF imageSize = q->imageDataSize();\n\n calculateDrawRect(imageSize);\n calculateSourceRect(imageSize);\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidget *controller) :\n MWidgetView(* new MImageWidgetViewPrivate, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::MImageWidgetView(MImageWidgetViewPrivate &dd, MImageWidget *controller) :\n MWidgetView(dd, controller)\n{\n Q_D(MImageWidgetView);\n d->controller = controller;\n}\n\nMImageWidgetView::~MImageWidgetView()\n{\n}\n\nvoid MImageWidgetView::drawContents(QPainter *painter, const QStyleOptionGraphicsItem *option) const\n{\n Q_UNUSED(option);\n\n Q_D(const MImageWidgetView);\n\n const QPixmap *pixmap = d->controller->d_func()->getPixmap();\n\n d->drawBorders(painter, d->drawRect);\n\n if (pixmap) {\n const_cast(d)->checkPixmapSize();\n \/\/ Because we are providing the pixmap directly without themedaemon\n \/\/ mscalableimage it is not called, thus, in order to have a smooth\n \/\/ scalation of the pixmap we need to draw it with a smooth transformation\n static bool enabled = painter->renderHints() & QPainter::SmoothPixmapTransform;\n painter->setRenderHint(QPainter::SmoothPixmapTransform);\n painter->drawPixmap(d->drawRect, *pixmap, d->sourceRect);\n painter->setRenderHint(QPainter::SmoothPixmapTransform, enabled);\n } else\n painter->drawImage(d->drawRect, d->controller->d_func()->getImage(), d->sourceRect);\n}\n\nvoid MImageWidgetView::resizeEvent(QGraphicsSceneResizeEvent *event)\n{\n MWidgetView::resizeEvent(event);\n update();\n}\n\nvoid MImageWidgetView::setGeometry(const QRectF &rect)\n{\n Q_D(MImageWidgetView);\n MWidgetView::setGeometry(rect);\n\n d->updateImageGeometry();\n}\n\nvoid MImageWidgetView::updateGeometry()\n{\n Q_D(MImageWidgetView);\n\n MWidgetView::updateGeometry();\n\n d->updateImageGeometry();\n}\n\nvoid MImageWidgetView::applyStyle()\n{\n Q_D(MImageWidgetView);\n MWidgetView::applyStyle();\n\n d->applyStyle();\n\n if (!model()->imageId().isEmpty())\n d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);\n}\n\nvoid MImageWidgetView::updateData(const QList &modifications)\n{\n Q_D(MImageWidgetView);\n MWidgetView::updateData(modifications);\n\n bool needsGeometryUpdate = false;\n bool needsPixmap = false;\n const char *member;\n for (int i = 0; i < modifications.count(); i++) {\n member = modifications[i];\n if (member == MImageWidgetModel::ZoomFactorX ||\n member == MImageWidgetModel::ZoomFactorY ||\n member == MImageWidgetModel::Crop ||\n member == MImageWidgetModel::AspectRatioMode) {\n needsGeometryUpdate = true;\n } else if (member == MImageWidgetModel::ImageId ||\n member == MImageWidgetModel::ImageSize) {\n needsPixmap = true;\n }\n }\n\n if (needsPixmap && !model()->imageId().isEmpty())\n d->controller->d_func()->setPixmap(d->createPixmapFromTheme(), false);\n\n if (needsGeometryUpdate || needsPixmap)\n updateGeometry();\n}\n\nQSizeF MImageWidgetView::sizeHint(Qt::SizeHint which, const QSizeF &constraint) const\n{\n Q_D(const MImageWidgetView);\n\n if (which == Qt::MinimumSize || which == Qt::MaximumSize)\n return QSizeF(-1,-1);\n\n QSizeF size = d->controller->imageSize();\n\n \/\/ an empty QSize() translates to (-1,-1) which would result in an incorrect size hint\n if (!size.isValid())\n size = QSizeF(0, 0);\n\n if (constraint.width() >= 0 && constraint.width() < size.width())\n size.scale(QSizeF(constraint.width(), QWIDGETSIZE_MAX), Qt::KeepAspectRatio);\n else if (constraint.height() >= 0 && constraint.height() < size.height())\n size.scale(QSizeF(QWIDGETSIZE_MAX, constraint.height()), Qt::KeepAspectRatio);\n return size;\n}\n\nQSize MImageWidgetView::imageDataSize()\n{\n Q_D(MImageWidgetView);\n\n return d->controller->d_func()->imageDataSize(model()->crop()).toSize();\n}\n\nM_REGISTER_VIEW_NEW(MImageWidgetView, MImageWidget)\n\n<|endoftext|>"} {"text":"\/\/sg: this is going to be the primary vision node for qubo (or future robots, whatever)\n#include \"vision_node.h\"\n\nusing namespace std;\nusing namespace ros;\nusing namespace AVT::VmbAPI;\n\n\/\/you need to pass in a node handle, and a camera feed, which should be a file path either to a physical device or to a video\nVisionNode::VisionNode(NodeHandle n, NodeHandle np, string feed)\n\t:\tm_buoy_server(n, \"buoy_action\", boost::bind(&VisionNode::findBuoy, this, _1, &m_buoy_server), false),\n\t\tm_gate_server(n, \"gate_action\", boost::bind(&VisionNode::findGate, this, _1, &m_gate_server), false)\n{\n\n\t\/\/ isdigit makes sure checks if we're dealing with a number (like if want to open the default camera by passing a 0). If we are we convert our string to an int (VideoCapture won't correctly open the camera with the string in this case);\n\t\/\/this could give us problems if we pass something like \"0followed_by_string\" but just don't do that.\n\n\t\/\/sgillen@20170429-07:04 we really don't even need this... we can just pass in \/dev\/video0 if we want the web camera... I'll leave it for now though\n\tif(feed == \"IP\") {\n\t\t\/\/ use the mako if feed isn't given\n\t\t\/\/start the camera\n\t\tauto vmb_err = [](const int func_call, const string err_msg) {\n\t\t\tif (func_call != VmbErrorSuccess){\n\t\t\t\tROS_ERROR(\"%s, code: %i\", err_msg.c_str(), func_call);\n\t\t\t\treturn func_call;\n\t\t\t}\n\t\t\treturn func_call;\n\t\t};\n\n\t\tROS_ERROR(\"getting Vimba\");\n\t\tauto& m_vimba_sys = VimbaSystem::GetInstance();\n\t\tif( vmb_err(m_vimba_sys.Startup(), \"Unable to start the Vimba System\") ) { exit(1); }\n\n\t\tROS_ERROR(\"finding cameras\");\n\t\tCameraPtrVector c_vec;\n\t\tif( vmb_err(m_vimba_sys.GetCameras( c_vec ), \"Unable to find cameras\") ) {exit(1); }\n\t\t\/\/ Since we only have one camera currently, we can just use the first thing returned when getting all the cameras\n\t\tm_gige_camera = c_vec[0];\n\t\tstring camera_id;\n\t\tif (vmb_err(m_gige_camera->GetID(camera_id), \"Unable to get a camera ID from Vimba\") ){ exit(1); }\n\t\twhile( !vmb_err(m_gige_camera->Open(VmbAccessModeFull), \"Error opening a camera with Vimba\") ) {}\n\n\t\t\/\/ We need to height, width and pixel format of the camera to convert the images to something OpenCV likes\n\t\tFeaturePtr feat;\n\t\tif(!vmb_err(m_gige_camera->GetFeatureByName( \"Width\", feat), (\"Error getting the camera width\" ))){\n\t\t\tVmbInt64_t width;\n\t\t\tif (!vmb_err(feat->GetValue(width), \"Error getting width\")) {\n\t\t\t\tROS_ERROR(\"Width: %lld\", width);\n\t\t\t\tm_width = width;\n\t\t\t}\n\t\t}\n\t\tif(!vmb_err(m_gige_camera->GetFeatureByName( \"Height\", feat), (\"Error getting the camera height\" ))){\n\t\t\tVmbInt64_t height;\n\t\t\tif (!vmb_err(feat->GetValue(height), \"Error getting height\")) {\n\t\t\t\tROS_ERROR(\"Height: %lld\", height);\n\t\t\t\tm_height = height;\n\t\t\t}\n\t\t}\n\t\tif(!vmb_err(m_gige_camera->GetFeatureByName(\"PixelFormat\", feat), \"Error getting pixel format\")){\n\t\t\tvmb_err(feat->GetValue(m_pixel_format), \"Error getting format\");\n\t\t}\n\t} else {\n\n\t\tif(isdigit(feed.c_str()[0])){\n\t\t\tm_cap = cv::VideoCapture(atoi(feed.c_str()));\n\t\t}\n\t\telse{\n\t\t\tm_cap = cv::VideoCapture(feed);\n\t\t}\n\n\n\t\t\/\/make sure we have something valid\n\t\tif(!m_cap.isOpened()){\n\t\t\tROS_ERROR(\"couldn't open file\/camera %s\\n now exiting\" ,feed.c_str());\n\t\t\texit(0);\n\t\t}\n\t\tm_width = m_cap.get(CV_CAP_PROP_FRAME_WIDTH);\n\t\tm_height = m_cap.get(CV_CAP_PROP_FRAME_HEIGHT);\n\t}\n\n\n\t\/\/TODO give option to user to specify the name of the video\n\t\/\/TODO make sure this doesn't fail when specifying a directory that does not yet exist\n\n\tstring output_dir;\n\tnp.param(\"output_dir\", output_dir, \"\"); \/\/this line will populate the output_dir variable if it's specified in the launch file\n\n\t\/\/TODO change variable names\n\tif(!output_dir.empty()){\n\n\t\tstringstream output_ss;\n\t\tauto t = time(nullptr);\n\t\tauto tm = *localtime(&t);\n\n\t\toutput_ss << output_dir;\n\t\toutput_ss << put_time(&tm, \"%Y%m%d_%H-%M-%S\");\n\t\toutput_ss << \".avi\";\n\n\t\tstring output_str = output_ss.str();\n\n\t\tint ex = static_cast(m_cap.get(CV_CAP_PROP_FOURCC));\n\n\t\tcv::Size S = cv::Size((int) m_width, \/\/ Acquire input size\n\t\t\t\t\t\t\t (int) m_height);\n\n\n\t\t\/\/sgillen@20172107-06:21 I found more problems trying to keep the extension (by passing ex as the second argument) than I did by forcing the output to be CV_FOURCC('M','J','P','G')\n\t\t\/\/m_output_video.open(output_str, ex, m_cap.get(CV_CAP_PROP_FPS), S, true);\n\t\tm_output_video.open(output_str, CV_FOURCC('M','J','P','G'), 20\/* m_cap.get(CV_CAP_PROP_FPS) *\/, S, true);\n\n\n\t\tif(!m_output_video.isOpened()){\n\t\t\tROS_ERROR(\"problem opening output video! we tried saving it as %s, now exiting\" ,output_str.c_str());\n\t\t\texit(0);\n\t\t}\n\n\t\tROS_INFO(\"output video being saved as %s\" , output_str.c_str());\n\t}\n\n\n\t\/\/register all services here\n\t\/\/------------------------------------------------------------------------------\n\tm_test_srv = n.advertiseService(\"service_test\", &VisionNode::serviceTest, this);\n\n\n\t\/\/start your action servers here\n\t\/\/------------------------------------------------------------------------------\n\tm_buoy_server.start();\n\tm_gate_server.start();\n\tROS_INFO(\"servers started\");\n\n}\n\n\nVisionNode::~VisionNode(){\n\t\/\/sg: may need to close the cameras here not sure..\n\tauto& m_vimba_sys = VimbaSystem::GetInstance();\n\tm_gige_camera->Close();\n\tm_vimba_sys.Shutdown();\n}\n\nvoid VisionNode::update(){\n\n\t\/\/ Use the mako if its present\n\tif (m_gige_camera == nullptr){\n\t\tROS_ERROR(\"Get vimba frame\");\n\t\tgetVmbFrame(m_img);\n\t} else {\n\t\tm_cap >> m_img;\n\t}\n\t\/\/if one of our frames was empty it means we ran out of footage, should only happen with test feeds or if a camera breaks I guess\n\tif(m_img.empty()){\n\t\t\/\/ ROS_ERROR(\"ran out of video (one of the frames was empty) exiting node now\");\n\t\t\/\/ exit(0);\n\t\tROS_ERROR(\"Empty Frame\");\n\t}\n\n\t\/\/if the user didn't specify a directory this will not be open\n\tif(m_output_video.isOpened()){\n\t\tROS_ERROR(\"writing image!\");\n\t\tm_output_video << m_img;\n\t}\n\n\tspinOnce();\n}\n\nvoid VisionNode::getVmbFrame(cv::Mat& cv_frame){\n\tif(m_gige_camera == nullptr) {\n\t\tROS_ERROR(\"Attempted to get a frame from a null Vimba camera pointer\");\n\t\treturn;\n\t}\n\n\t\/\/ This is a wrapper for the Vimba error functions\n\t\/\/ call a function in it and give it an error message to print\n\t\/\/ if the function fails\n\t\/\/ it also returns the error code, so you can still fail if you need to\n\tauto vmb_err = [](const int func_call, const string err_msg) {\n\t\tif (func_call != VmbErrorSuccess){\n\t\t\tROS_ERROR(\"%s, code: %i\", err_msg.c_str(), func_call);\n\t\t\treturn func_call;\n\t\t}\n\t\treturn func_call;\n\t};\n\tFramePtr vmb_frame;\n\tif( vmb_err( m_gige_camera->AcquireSingleImage(vmb_frame, 2), \"Error getting single frame\" ) ) { return; }\n\tVmbFrameStatusType status;\n\tvmb_frame->GetReceiveStatus(status);\n\tif(status != VmbFrameStatusComplete) {\n\t\tROS_ERROR(\"Malformed frame received\");\n\t\treturn;\n\t}\n\tVmbUint32_t size;\n\tvmb_frame->GetImageSize(size);\n\tunsigned char* img_buf;\n\tif( vmb_err( vmb_frame->GetImage(img_buf), \"Error getting image buffer\")) { return; }\n\n\tVmbImage img_src, img_dest;\n\timg_src.Size = sizeof( img_src );\n\timg_dest.Size = sizeof( img_dest );\n\n\tVmbSetImageInfoFromPixelFormat( m_pixel_format, m_width, m_height, &img_src);\n\tVmbSetImageInfoFromPixelFormat(VmbPixelFormatBgr8, m_width, m_height, &img_dest);\n\n\timg_src.Data = img_buf;\n\timg_src.Data = cv_frame.data;\n\n\tvmb_err( VmbImageTransform(&img_src, &img_dest, NULL, 0), \"Error transforming image\" );\n}\n\n\/*\n* Past this point is a collection of services and\n* actions that will be able to called from any other node\n* =================================================================================================================\n*\/\nbool VisionNode::serviceTest(ram_msgs::bool_bool::Request &req, ram_msgs::bool_bool::Response &res){\n\tROS_ERROR(\"service called successfully\");\n}\n\n\n\n\/\/There are the definitions for all of our actionlib actions, may be moved to it's own class not sure yet.\n\/\/=================================================================================================================\nvoid VisionNode::testExecute(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer *as){\n\t\/\/ goal->test_feedback = 5;\n\tROS_ERROR(\"You called the action well done!\");\n\tas->setSucceeded();\n}\n\n\n\/\/if a buoy is found on frame finds where it is and returns the center offset\nvoid VisionNode::findBuoy(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer *as){\n\n\tBuoyAction action = BuoyAction(as);\n\n\twhile(true){\n\t\taction.updateAction(m_img); \/\/this will also publish the feedback\n\t}\n\n\tas->setSucceeded();\n}\n\nvoid VisionNode::findGate(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer *as){\n\n\tGateAction action = GateAction();\n\n\twhile(true){\n\t\tROS_ERROR(\"updating action\");\n\t\taction.updateAction(m_img);\n\t}\n\n\tas->setSucceeded();\n}\ntweaks\/\/sg: this is going to be the primary vision node for qubo (or future robots, whatever)\n#include \"vision_node.h\"\n\nusing namespace std;\nusing namespace ros;\nusing namespace AVT::VmbAPI;\n\n\/\/you need to pass in a node handle, and a camera feed, which should be a file path either to a physical device or to a video\nVisionNode::VisionNode(NodeHandle n, NodeHandle np, string feed)\n\t:\tm_buoy_server(n, \"buoy_action\", boost::bind(&VisionNode::findBuoy, this, _1, &m_buoy_server), false),\n\t\tm_gate_server(n, \"gate_action\", boost::bind(&VisionNode::findGate, this, _1, &m_gate_server), false)\n{\n\n\t\/\/ isdigit makes sure checks if we're dealing with a number (like if want to open the default camera by passing a 0). If we are we convert our string to an int (VideoCapture won't correctly open the camera with the string in this case);\n\t\/\/this could give us problems if we pass something like \"0followed_by_string\" but just don't do that.\n\n\t\/\/sgillen@20170429-07:04 we really don't even need this... we can just pass in \/dev\/video0 if we want the web camera... I'll leave it for now though\n\tif(feed == \"IP\") {\n\t\t\/\/ use the mako if feed isn't given\n\t\t\/\/start the camera\n\t\tauto vmb_err = [](const int func_call, const string err_msg) {\n\t\t\tif (func_call != VmbErrorSuccess){\n\t\t\t\tROS_ERROR(\"%s, code: %i\", err_msg.c_str(), func_call);\n\t\t\t\treturn func_call;\n\t\t\t}\n\t\t\treturn func_call;\n\t\t};\n\n\t\tROS_ERROR(\"getting Vimba\");\n\t\tauto& m_vimba_sys = VimbaSystem::GetInstance();\n\t\tif( vmb_err(m_vimba_sys.Startup(), \"Unable to start the Vimba System\") ) { exit(1); }\n\n\t\tROS_ERROR(\"finding cameras\");\n\t\tCameraPtrVector c_vec;\n\t\tif( vmb_err(m_vimba_sys.GetCameras( c_vec ), \"Unable to find cameras\") ) {exit(1); }\n\t\t\/\/ Since we only have one camera currently, we can just use the first thing returned when getting all the cameras\n\t\tm_gige_camera = c_vec[0];\n\t\tstring camera_id;\n\t\tif (vmb_err(m_gige_camera->GetID(camera_id), \"Unable to get a camera ID from Vimba\") ){ exit(1); }\n\t\twhile( !vmb_err(m_gige_camera->Open(VmbAccessModeFull), \"Error opening a camera with Vimba\") ) {}\n\n\t\t\/\/ We need to height, width and pixel format of the camera to convert the images to something OpenCV likes\n\t\tFeaturePtr feat;\n\t\tif(!vmb_err(m_gige_camera->GetFeatureByName( \"Width\", feat), (\"Error getting the camera width\" ))){\n\t\t\tVmbInt64_t width;\n\t\t\tif (!vmb_err(feat->GetValue(width), \"Error getting width\")) {\n\t\t\t\tROS_ERROR(\"Width: %lld\", width);\n\t\t\t\tm_width = width;\n\t\t\t}\n\t\t}\n\t\tif(!vmb_err(m_gige_camera->GetFeatureByName( \"Height\", feat), (\"Error getting the camera height\" ))){\n\t\t\tVmbInt64_t height;\n\t\t\tif (!vmb_err(feat->GetValue(height), \"Error getting height\")) {\n\t\t\t\tROS_ERROR(\"Height: %lld\", height);\n\t\t\t\tm_height = height;\n\t\t\t}\n\t\t}\n\t\tif(!vmb_err(m_gige_camera->GetFeatureByName(\"PixelFormat\", feat), \"Error getting pixel format\")){\n\t\t\tvmb_err(feat->GetValue(m_pixel_format), \"Error getting format\");\n\t\t}\n\t} else {\n\n\t\tif(isdigit(feed.c_str()[0])){\n\t\t\tm_cap = cv::VideoCapture(atoi(feed.c_str()));\n\t\t}\n\t\telse{\n\t\t\tm_cap = cv::VideoCapture(feed);\n\t\t}\n\n\n\t\t\/\/make sure we have something valid\n\t\tif(!m_cap.isOpened()){\n\t\t\tROS_ERROR(\"couldn't open file\/camera %s\\n now exiting\" ,feed.c_str());\n\t\t\texit(0);\n\t\t}\n\t\tm_width = m_cap.get(CV_CAP_PROP_FRAME_WIDTH);\n\t\tm_height = m_cap.get(CV_CAP_PROP_FRAME_HEIGHT);\n\t}\n\n\n\t\/\/TODO give option to user to specify the name of the video\n\t\/\/TODO make sure this doesn't fail when specifying a directory that does not yet exist\n\n\tstring output_dir;\n\tnp.param(\"output_dir\", output_dir, \"\"); \/\/this line will populate the output_dir variable if it's specified in the launch file\n\n\t\/\/TODO change variable names\n\tif(!output_dir.empty()){\n\n\t\tstringstream output_ss;\n\t\tauto t = time(nullptr);\n\t\tauto tm = *localtime(&t);\n\n\t\toutput_ss << output_dir;\n\t\toutput_ss << put_time(&tm, \"%Y%m%d_%H-%M-%S\");\n\t\toutput_ss << \".avi\";\n\n\t\tstring output_str = output_ss.str();\n\n\t\tint ex = static_cast(m_cap.get(CV_CAP_PROP_FOURCC));\n\n\t\tcv::Size S = cv::Size((int) m_width, \/\/ Acquire input size\n\t\t\t\t\t\t\t (int) m_height);\n\n\n\t\t\/\/sgillen@20172107-06:21 I found more problems trying to keep the extension (by passing ex as the second argument) than I did by forcing the output to be CV_FOURCC('M','J','P','G')\n\t\t\/\/m_output_video.open(output_str, ex, m_cap.get(CV_CAP_PROP_FPS), S, true);\n\t\tm_output_video.open(output_str, CV_FOURCC('M','J','P','G'), 20\/* m_cap.get(CV_CAP_PROP_FPS) *\/, S, true);\n\n\n\t\tif(!m_output_video.isOpened()){\n\t\t\tROS_ERROR(\"problem opening output video! we tried saving it as %s, now exiting\" ,output_str.c_str());\n\t\t\texit(0);\n\t\t}\n\n\t\tROS_INFO(\"output video being saved as %s\" , output_str.c_str());\n\t}\n\n\n\t\/\/register all services here\n\t\/\/------------------------------------------------------------------------------\n\tm_test_srv = n.advertiseService(\"service_test\", &VisionNode::serviceTest, this);\n\n\n\t\/\/start your action servers here\n\t\/\/------------------------------------------------------------------------------\n\tm_buoy_server.start();\n\tm_gate_server.start();\n\tROS_INFO(\"servers started\");\n\n}\n\n\nVisionNode::~VisionNode(){\n\t\/\/sg: may need to close the cameras here not sure..\n\tauto& m_vimba_sys = VimbaSystem::GetInstance();\n\tm_gige_camera->Close();\n\tm_vimba_sys.Shutdown();\n}\n\nvoid VisionNode::update(){\n\n\t\/\/ Use the mako if its present\n\tif (m_gige_camera != nullptr){\n\t\tROS_ERROR(\"Get vimba frame\");\n\t\tgetVmbFrame(m_img);\n\t\tROS_ERROR(\"%s\", m_img.data);\n\t} else {\n\t\tm_cap >> m_img;\n\t}\n\t\/\/if one of our frames was empty it means we ran out of footage, should only happen with test feeds or if a camera breaks I guess\n\tif(m_img.empty()){\n\t\t\/\/ ROS_ERROR(\"ran out of video (one of the frames was empty) exiting node now\");\n\t\t\/\/ exit(0);\n\t\tROS_ERROR(\"Empty Frame\");\n\t}\n\n\t\/\/if the user didn't specify a directory this will not be open\n\tif(m_output_video.isOpened()){\n\t\tROS_ERROR(\"writing image!\");\n\t\tm_output_video << m_img;\n\t}\n\n\tspinOnce();\n}\n\nvoid VisionNode::getVmbFrame(cv::Mat& cv_frame){\n\tif(m_gige_camera == nullptr) {\n\t\tROS_ERROR(\"Attempted to get a frame from a null Vimba camera pointer\");\n\t\treturn;\n\t}\n\n\t\/\/ This is a wrapper for the Vimba error functions\n\t\/\/ call a function in it and give it an error message to print\n\t\/\/ if the function fails\n\t\/\/ it also returns the error code, so you can still fail if you need to\n\tauto vmb_err = [](const int func_call, const string err_msg) {\n\t\tif (func_call != VmbErrorSuccess){\n\t\t\tROS_ERROR(\"%s, code: %i\", err_msg.c_str(), func_call);\n\t\t\treturn func_call;\n\t\t}\n\t\treturn func_call;\n\t};\n\tFramePtr vmb_frame;\n\tif( vmb_err( m_gige_camera->AcquireSingleImage(vmb_frame, 2), \"Error getting single frame\" ) ) { return; }\n\tVmbFrameStatusType status;\n\tvmb_frame->GetReceiveStatus(status);\n\tif(status != VmbFrameStatusComplete) {\n\t\tROS_ERROR(\"Malformed frame received\");\n\t\treturn;\n\t}\n\tVmbUint32_t size;\n\tvmb_frame->GetImageSize(size);\n\tunsigned char* img_buf;\n\tif( vmb_err( vmb_frame->GetImage(img_buf), \"Error getting image buffer\")) { return; }\n\n\tVmbImage img_src, img_dest;\n\timg_src.Size = sizeof( img_src );\n\timg_dest.Size = sizeof( img_dest );\n\n\tVmbSetImageInfoFromPixelFormat( m_pixel_format, m_width, m_height, &img_src);\n\tVmbSetImageInfoFromPixelFormat(VmbPixelFormatBgr8, m_width, m_height, &img_dest);\n\n\timg_src.Data = img_buf;\n\timg_src.Data = cv_frame.data;\n\n\tvmb_err( VmbImageTransform(&img_src, &img_dest, NULL, 0), \"Error transforming image\" );\n}\n\n\/*\n* Past this point is a collection of services and\n* actions that will be able to called from any other node\n* =================================================================================================================\n*\/\nbool VisionNode::serviceTest(ram_msgs::bool_bool::Request &req, ram_msgs::bool_bool::Response &res){\n\tROS_ERROR(\"service called successfully\");\n}\n\n\n\n\/\/There are the definitions for all of our actionlib actions, may be moved to it's own class not sure yet.\n\/\/=================================================================================================================\nvoid VisionNode::testExecute(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer *as){\n\t\/\/ goal->test_feedback = 5;\n\tROS_ERROR(\"You called the action well done!\");\n\tas->setSucceeded();\n}\n\n\n\/\/if a buoy is found on frame finds where it is and returns the center offset\nvoid VisionNode::findBuoy(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer *as){\n\n\tBuoyAction action = BuoyAction(as);\n\n\twhile(true){\n\t\taction.updateAction(m_img); \/\/this will also publish the feedback\n\t}\n\n\tas->setSucceeded();\n}\n\nvoid VisionNode::findGate(const ram_msgs::VisionNavGoalConstPtr& goal, actionlib::SimpleActionServer *as){\n\n\tGateAction action = GateAction();\n\n\twhile(true){\n\t\tROS_ERROR(\"updating action\");\n\t\taction.updateAction(m_img);\n\t}\n\n\tas->setSucceeded();\n}\n<|endoftext|>"} {"text":"\n#include \n#include \n#include \n#include \n#include \n#include \"data.h\"\n#include \"maze.h\"\n#include \"menu.h\"\n#include \"story.h\"\n#include \"windows.h\"\n\nusing namespace std;\n\n\n\/\/ forward declarations\nmenu_state game_ui(WINDOW *menu_win, game_data *d, menu_state state);\nstatic void get_new_dims(int& nrows, int& ncols, int level);\n\n\n\/**\n * The game maze GUI.\n *\n * Use arrow keys to navigate the maze or type \"q\" to quit.\n *\/\nmenu_state game_ui(WINDOW *win, game_data *d, menu_state state)\n{\n maze_data *maze = &d->maze;\n player_data *player = &d->player;\n int c;\n int win_y(15);\n int win_x(15);\n int last_win_y, last_win_x;\n\n \/\/ init window at current resolution\n if (maze->level == -1) {\n intro_splash(win);\n }\n init_maze_window(win);\n getmaxyx(stdscr, win_y, win_x);\n last_win_y = win_y;\n last_win_x = win_x;\n\n \/\/ generate a new maze, if necessary\n if (maze->level == -1) {\n \/\/ TODO: Move to data.cpp\n backtracking_maze_gen(maze);\n gen_entrances_opposites(maze);\n std::fill_n(player->visited, maze->max_size * maze->max_size \/ 2, false);\n player->visited[maze->finish[0] * maze->max_size + maze->finish[1]] = true;\n player->loc[0] = maze->start[0];\n player->loc[1] = maze->start[1];\n maze->level = 0;\n maze->difficulty = state;\n }\n\n \/\/ select the appropriate print function\n function maze_print = \\\n state == game_easy ? maze_print_easy : (state == game_medium ? maze_print_medium : maze_print_hard);\n\n \/\/ game loop\n while (true) {\n player->visited[player->loc[0] * maze->max_size + player->loc[1]] = true;\n maze_print(win, *maze, player->loc, player->visited);\n\n \/\/ input and update\n c = wgetch(win);\n switch (c) {\n case KEY_UP:\n if (maze_valid_move(*maze, player->loc[0] - 1, player->loc[1])) {\n player->loc[0] -= 1;\n }\n break;\n case KEY_DOWN:\n if (maze_valid_move(*maze, player->loc[0] + 1, player->loc[1])) {\n player->loc[0] += 1;\n }\n break;\n case KEY_LEFT:\n if (maze_valid_move(*maze, player->loc[0], player->loc[1] - 1)) {\n player->loc[1] -= 1;\n }\n break;\n case KEY_RIGHT:\n if (maze_valid_move(*maze, player->loc[0], player->loc[1] + 1)) {\n player->loc[1] += 1;\n }\n break;\n case 113: \/\/ q\n return menu_cont;\n case KEY_RESIZE:\n getmaxyx(stdscr, win_y, win_x);\n if (last_win_x != win_x || last_win_y != win_y) {\n last_win_y = win_y;\n last_win_x = win_x;\n wresize(win, win_y, win_x);\n wclear(win);\n box(win, 0, 0);\n refresh();\n wrefresh(win);\n }\n break;\n \/\/ no default actions to be taken\n }\n\n \/\/ TODO: How to better check for value equality in arrays?\n \/\/ If you reach the end, start over in a new maze\n if (player->loc[0] == maze->finish[0] && player->loc[1] == maze->finish[1]) {\n success_splash(win, maze->level + 2);\n wclear(win);\n clear();\n box(win, 0, 0);\n refresh();\n wrefresh(win);\n get_new_dims(maze->nrows, maze->ncols, maze->level);\n\n \/\/ generate a new maze\n std::fill_n(player->visited, maze->max_size * maze->max_size \/ 2, false);\n backtracking_maze_gen(maze);\n gen_entrances_opposites(maze);\n player->loc[0] = maze->start[0];\n player->loc[1] = maze->start[1];\n\n maze->level += 1;\n }\n }\n}\n\n\n\/**\n * Randomly generate maze dimensions.\n *\/\nstatic void get_new_dims(int& nrows, int& ncols, int level) {\n level %= 20;\n\n const int bottom_y = 15;\n nrows = bottom_y + level \/ 2 + (rand() % (int)(level \/ 2 + 1));\n if (nrows % 2 == 0) { nrows += 1; }\n\n const int bottom_x = 31;\n ncols = bottom_x + level + (rand() % (int)((level) + 1));\n if (ncols % 2 == 0) { ncols += 1; }\n}\nminor cleanup\n#include \n#include \n#include \n#include \n#include \n#include \"data.h\"\n#include \"maze.h\"\n#include \"menu.h\"\n#include \"story.h\"\n#include \"windows.h\"\n\nusing namespace std;\n\n\n\/\/ forward declarations\nmenu_state game_ui(WINDOW *menu_win, game_data *d, menu_state state);\nstatic void get_new_dims(int& nrows, int& ncols, int level);\n\n\n\/**\n * The game maze GUI.\n *\n * Use arrow keys to navigate the maze or type \"q\" to quit.\n *\/\nmenu_state game_ui(WINDOW *win, game_data *d, menu_state state)\n{\n maze_data *maze = &d->maze;\n player_data *player = &d->player;\n int c;\n int win_y(15);\n int win_x(15);\n int last_win_y, last_win_x;\n\n \/\/ init window at current resolution\n if (maze->level == -1) {\n intro_splash(win);\n }\n init_maze_window(win);\n getmaxyx(stdscr, win_y, win_x);\n last_win_y = win_y;\n last_win_x = win_x;\n\n \/\/ generate a new maze, if necessary\n if (maze->level == -1) {\n \/\/ TODO: Move to data.cpp\n backtracking_maze_gen(maze);\n gen_entrances_opposites(maze);\n std::fill_n(player->visited, maze->max_size * maze->max_size \/ 2, false);\n player->visited[maze->finish[0] * maze->max_size + maze->finish[1]] = true;\n player->loc[0] = maze->start[0];\n player->loc[1] = maze->start[1];\n maze->level = 0;\n maze->difficulty = state;\n }\n\n \/\/ select the appropriate print function\n function maze_print = \\\n state == game_easy ? maze_print_easy : (state == game_medium ? maze_print_medium : maze_print_hard);\n\n \/\/ game loop\n while (true) {\n player->visited[player->loc[0] * maze->max_size + player->loc[1]] = true;\n maze_print(win, *maze, player->loc, player->visited);\n\n \/\/ input and update\n c = wgetch(win);\n switch (c) {\n case KEY_UP:\n if (maze_valid_move(*maze, player->loc[0] - 1, player->loc[1])) {\n player->loc[0] -= 1;\n }\n break;\n case KEY_DOWN:\n if (maze_valid_move(*maze, player->loc[0] + 1, player->loc[1])) {\n player->loc[0] += 1;\n }\n break;\n case KEY_LEFT:\n if (maze_valid_move(*maze, player->loc[0], player->loc[1] - 1)) {\n player->loc[1] -= 1;\n }\n break;\n case KEY_RIGHT:\n if (maze_valid_move(*maze, player->loc[0], player->loc[1] + 1)) {\n player->loc[1] += 1;\n }\n break;\n case 113: \/\/ q\n return menu_cont;\n case KEY_RESIZE:\n getmaxyx(stdscr, win_y, win_x);\n if (last_win_x != win_x || last_win_y != win_y) {\n last_win_y = win_y;\n last_win_x = win_x;\n wresize(win, win_y, win_x);\n wclear(win);\n box(win, 0, 0);\n refresh();\n wrefresh(win);\n }\n break;\n \/\/ no default actions to be taken\n }\n\n \/\/ If you reach the end, start over in a new maze\n if (player->loc[0] == maze->finish[0] && player->loc[1] == maze->finish[1]) {\n success_splash(win, maze->level + 2);\n wclear(win);\n clear();\n box(win, 0, 0);\n refresh();\n wrefresh(win);\n get_new_dims(maze->nrows, maze->ncols, maze->level);\n\n \/\/ generate a new maze\n std::fill_n(player->visited, maze->max_size * maze->max_size \/ 2, false);\n backtracking_maze_gen(maze);\n gen_entrances_opposites(maze);\n player->loc[0] = maze->start[0];\n player->loc[1] = maze->start[1];\n\n maze->level += 1;\n }\n }\n}\n\n\n\/**\n * Randomly generate maze dimensions.\n *\/\nstatic void get_new_dims(int& nrows, int& ncols, int level) {\n level %= 20;\n\n const int bottom_y = 15;\n nrows = bottom_y + level \/ 2 + (rand() % (int)(level \/ 2 + 1));\n if (nrows % 2 == 0) { nrows += 1; }\n\n const int bottom_x = 31;\n ncols = bottom_x + level + (rand() % (int)((level) + 1));\n if (ncols % 2 == 0) { ncols += 1; }\n}\n<|endoftext|>"} {"text":"\/* Copyright 2015 Peter Goodman (peter@trailofbits.com), all rights reserved. *\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mcsema\/Arch\/Arch.h\"\n#include \"mcsema\/BC\/IntrinsicTable.h\"\n#include \"mcsema\/BC\/Translator.h\"\n#include \"mcsema\/CFG\/CFG.h\"\n#include \"mcsema\/OS\/OS.h\"\n\nDEFINE_int32(max_dataflow_analysis_iterations, 0,\n \"Maximum number of iterations of a data flow pass to perform \"\n \"over the control-flow graph being lifted.\");\n\nDEFINE_bool(aggressive_dataflow_analysis, false,\n \"Should data-flow analysis be conservative in their conclusions? \"\n \"If not then the analysis will be really aggressive and make a lot \"\n \"of assumptions about function call behavior.\");\n\nnamespace llvm {\nclass ReturnInst;\n} \/\/ namespace\n\nnamespace mcsema {\nnamespace {\n\n\/\/ Name of some meta-data that we use to distinguish between external symbols\n\/\/ and private symbols.\nstatic std::string NamedSymbolMetaId(std::string func_name) {\n return \"mcsema_external:\" + func_name;\n}\n\n\/\/ Returns the ID for this binary. We prefix every basic block function added to\n\/\/ a module with the ID of the binary, where the ID is a number that increments\n\/\/ linearly.\nstatic int GetBinaryId(llvm::Module *M) {\n for (auto i = 1; ; ++i) {\n std::string id = \"mcsema_binary:\" + std::to_string(i);\n if (!M->getNamedMetadata(id)) {\n M->getOrInsertNamedMetadata(id);\n return i;\n }\n }\n __builtin_unreachable();\n}\n\n} \/\/ namespace\n\nTranslator::Translator(const Arch *arch_, llvm::Module *module_)\n : arch(arch_),\n module(module_),\n blocks(),\n functions(),\n symbols(),\n binary_id(GetBinaryId(module)),\n basic_block(FindFunction(module, \"__mcsema_basic_block\")),\n intrinsics(new IntrinsicTable(module)) {\n\n EnableDeferredInlining();\n IdentifyExistingSymbols();\n}\n\nnamespace {\n\nstatic void DisableInlining(llvm::Function *F) {\n F->removeFnAttr(llvm::Attribute::AlwaysInline);\n F->removeFnAttr(llvm::Attribute::InlineHint);\n F->addFnAttr(llvm::Attribute::NoInline);\n}\n\n} \/\/ namespace\n\n\/\/ Enable deferred inlining. The goal is to support better dead-store\n\/\/ elimination for flags.\nvoid Translator::EnableDeferredInlining(void) {\n if (!intrinsics->defer_inlining) return;\n DisableInlining(intrinsics->defer_inlining);\n\n for (auto U : intrinsics->defer_inlining->users()) {\n if (auto C = llvm::dyn_cast_or_null(U)) {\n auto B = C->getParent();\n auto F = B->getParent();\n DisableInlining(F);\n }\n }\n}\n\n\/\/ Find existing exported functions and variables. This is for the sake of\n\/\/ linking functions of the same names across CFG files.\nvoid Translator::IdentifyExistingSymbols(void) {\n for (auto &F : module->functions()) {\n std::string name = F.getName();\n if (module->getNamedMetadata(NamedSymbolMetaId(name))) {\n functions[name] = &F;\n }\n }\n\n for (auto &V : module->globals()) {\n std::string name = V.getName();\n if (module->getNamedMetadata(NamedSymbolMetaId(name))) {\n symbols[name] = &V;\n }\n }\n}\n\nnamespace {\n\nvoid InitBlockFuncAttributes(llvm::Function *BF, const llvm::Function *TF) {\n BF->setAttributes(TF->getAttributes());\n InitFunctionAttributes(BF);\n auto args = BF->arg_begin();\n (args++)->setName(\"state\");\n args->setName(\"pc\");\n}\n\nllvm::Function *GetBlockFunction(llvm::Module *M,\n const llvm::Function *TF,\n std::string name) {\n auto func_type = TF->getFunctionType();\n auto BF = llvm::dyn_cast(\n M->getOrInsertFunction(name, func_type));\n InitBlockFuncAttributes(BF, TF);\n BF->setLinkage(llvm::GlobalValue::PrivateLinkage);\n return BF;\n}\n\n} \/\/ namespace\n\n\/\/ Create functions for every block in the CFG.\nvoid Translator::CreateFunctionsForBlocks(const cfg::Module *cfg) {\n std::set indirect_blocks;\n for (const auto &block : cfg->indirect_blocks()) {\n indirect_blocks.insert(block.address());\n }\n\n for (const auto &block : cfg->blocks()) {\n auto &BF = blocks[block.address()];\n if (!BF) {\n std::stringstream ss;\n ss << \"__lifted_block_\" << binary_id << \"_0x\"\n << std::hex << block.address();\n\n BF = GetBlockFunction(module, basic_block, ss.str());\n\n \/\/ This block is externally visible so change its linkage and make a new\n \/\/ private block to which other blocks will refer.\n if (indirect_blocks.count(block.address())) {\n std::stringstream ss2;\n ss2 << \"__extern_block_\" << binary_id << \"_0x\"\n << std::hex << block.address();\n\n auto EF = GetBlockFunction(module, basic_block, ss2.str());\n EF->setLinkage(llvm::GlobalValue::ExternalLinkage);\n AddTerminatingTailCall(EF, BF, block.address());\n }\n }\n }\n}\n\nnamespace {\n\n\/\/ On Mac this strips off leading the underscore on symbol names.\n\/\/\n\/\/ TODO(pag): This is really ugly and is probably incorrect. The expectation is\n\/\/ that the leading underscore will be re-added when this code is\n\/\/ compiled.\nstd::string CanonicalName(OSName os_name, const std::string &name) {\n if (kOSMacOSX == os_name && name.length() && '_' == name[0]) {\n return name.substr(1);\n } else {\n return name;\n }\n}\n\n} \/\/ namespace\n\n\/\/ Create functions for every function in the CFG.\nvoid Translator::CreateExternalFunctions(const cfg::Module *cfg) {\n for (const auto &func : cfg->functions()) {\n if (!func.is_exported() && !func.is_imported()) continue;\n\n auto func_name = CanonicalName(arch->os_name, func.name());\n CHECK(!func_name.empty())\n << \"Module contains unnamed function at address \" << func.address();\n\n CHECK(!(func.is_exported() && func.is_imported()))\n << \"Function \" << func_name << \" can't be imported and exported.\";\n\n llvm::Function *&F = functions[func_name];\n if (!F) {\n F = GetBlockFunction(module, basic_block, func_name);\n\n \/\/ To get around some issues that `opt` has.\n F->addFnAttr(llvm::Attribute::NoBuiltin);\n F->addFnAttr(llvm::Attribute::OptimizeNone);\n F->addFnAttr(llvm::Attribute::NoInline);\n F->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);\n }\n\n \/\/ Mark this symbol as external. We do this so that we can pick up on it\n \/\/ if we merge another CFG into this bitcode module.\n module->getOrInsertNamedMetadata(NamedSymbolMetaId(func_name));\n }\n}\n\n\/\/ Link together functions and basic blocks.\nvoid Translator::LinkExternalFunctionsToBlocks(const cfg::Module *cfg) {\n for (const auto &func : cfg->functions()) {\n if (!func.is_exported() && !func.is_imported()) continue;\n if (!func.address()) continue;\n\n auto func_name = CanonicalName(arch->os_name, func.name());\n auto F = functions[func_name];\n auto &BF = blocks[func.address()];\n\n \/\/ In the case of an exported function, redirect the function's\n \/\/ implementation to a locally defined block.\n if (func.is_exported()) {\n\n CHECK(nullptr != BF)\n << \"Exported function \" << func_name << \" has no address!\";\n\n CHECK(F->isDeclaration())\n << \"Function \" << func_name << \" is already defined!\";\n\n AddTerminatingTailCall(F, BF, func.address());\n\n \/\/ In the case of ELF binaries, we tend to see a call to something like\n \/\/ `malloc@plt` that is responsible for finding and invoking the actual\n \/\/ `malloc` implementation. In this case, we want to treat the `malloc@plt`\n \/\/ block address as synonymous with the function.\n \/\/\n \/\/ TODO(pag): What about versioned ELF symbols?\n } else if (func.is_imported()) {\n if (!BF) {\n BF = F;\n } else {\n AddTerminatingTailCall(BF, F);\n }\n }\n }\n}\n\nnamespace {\n\n\/\/ Clone the block method template `TF` into a specific method `BF` that\n\/\/ will contain lifted code.\nstatic std::vector InitBlockFunction(\n llvm::Function *BF, const llvm::Function *TF, const cfg::Block &block) {\n llvm::ValueToValueMapTy var_map;\n auto targs = TF->arg_begin();\n auto bargs = BF->arg_begin();\n for (; targs != TF->arg_end(); ++targs, ++bargs) {\n var_map[&*targs] = &*bargs;\n }\n\n llvm::SmallVector returns;\n llvm::CloneFunctionInto(BF, TF, var_map, false, returns);\n\n InitBlockFuncAttributes(BF, TF);\n\n auto R = returns[0];\n R->removeFromParent();\n delete R;\n\n std::vector instruction_blocks;\n instruction_blocks.reserve(block.instructions_size());\n instruction_blocks.push_back(&(BF->back()));\n for (const auto &instr : block.instructions()) {\n\n \/\/ Name the block according to the instruction's address.\n std::stringstream ss;\n ss << \"0x\" << std::hex << instr.address();\n\n \/\/ Create a block for this instruction.\n auto B = llvm::BasicBlock::Create(BF->getContext(), ss.str(), BF);\n instruction_blocks.push_back(B);\n }\n return instruction_blocks;\n}\n\n\/\/ Fall-through PC for a block.\nstatic uint64_t FallThroughPC(const cfg::Block &block) {\n if (0 < block.instructions_size()) {\n const auto &instr = block.instructions(block.instructions_size() - 1);\n return instr.address() + instr.size();\n\n } else {\n LOG(ERROR) << \"Using block address as fall-through address.\";\n return block.address();\n }\n}\n\n} \/\/ namespace\n\n\/\/ Add a fall-through terminator to the block method just in case one is\n\/\/ missing.\nvoid Translator::TerminateBlockMethod(const cfg::Block &block,\n llvm::Function *BF) {\n auto &B = BF->back();\n if (B.getTerminator()) {\n return;\n }\n if (block.instructions_size()) {\n auto next_pc = FallThroughPC(block);\n AddTerminatingTailCall(BF, GetLiftedBlockForPC(next_pc), next_pc);\n } else {\n AddTerminatingTailCall(BF, intrinsics->missing_block, block.address());\n }\n}\n\n\/\/ Lift code contained in blocks into the block methods.\nvoid Translator::LiftBlocks(const cfg::Module *cfg) {\n llvm::legacy::FunctionPassManager FPM(module);\n FPM.add(llvm::createDeadCodeEliminationPass());\n FPM.add(llvm::createCFGSimplificationPass());\n FPM.add(llvm::createPromoteMemoryToRegisterPass());\n FPM.add(llvm::createReassociatePass());\n FPM.add(llvm::createInstructionCombiningPass());\n FPM.add(llvm::createDeadStoreEliminationPass());\n\n for (const auto &block : cfg->blocks()) {\n LOG_IF(WARNING, !block.instructions_size())\n << \"Block at \" << block.address() << \" has no instructions!\";\n\n auto BF = GetLiftedBlockForPC(block.address());\n if (!BF->isDeclaration()) {\n LOG(WARNING) << \"Ignoring already lifted block at \" << block.address();\n continue;\n }\n\n const auto instruction_blocks = InitBlockFunction(BF, basic_block, block);\n\n \/\/ Lift the instructions into the block in reverse order. This helps for\n \/\/ using the results of backward data-flow analyses.\n for (auto i = block.instructions_size(); i--; ) {\n const auto &instr = block.instructions(i);\n const auto bb = instruction_blocks[i + 1];\n LiftInstructionIntoBlock(block, instr, bb);\n }\n\n \/\/ Connect the internal blocks together with branches.\n if (instruction_blocks.size()) {\n for (auto i = 1; i < instruction_blocks.size(); ++i) {\n llvm::IRBuilder<> ir(instruction_blocks[i - 1]);\n ir.CreateBr(instruction_blocks[i]);\n }\n }\n\n TerminateBlockMethod(block, BF);\n\n \/\/ Perform simple, incremental optimizations on the block functions to\n \/\/ avoid OOMs.\n FPM.run(*BF);\n }\n}\n\n\/\/ Lift an instruction into a basic block. This does some minor sanity checks\n\/\/ then dispatches to the arch-specific translator.\nvoid Translator::LiftInstructionIntoBlock(\n const cfg::Block &block, const cfg::Instr &instr, llvm::BasicBlock *B) {\n\n CHECK(0 < instr.size())\n << \"Can't decode zero-sized instruction at \" << instr.address();\n\n CHECK(instr.size() == instr.bytes().length())\n << \"Instruction size mismatch for instruction at \" << instr.address();\n\n arch->LiftInstructionIntoBlock(*this, block, instr, B);\n}\n\nvoid Translator::LiftCFG(const cfg::Module *cfg) {\n blocks.clear(); \/\/ Just in case we call `LiftCFG` multiple times.\n CreateFunctionsForBlocks(cfg);\n CreateExternalFunctions(cfg);\n LinkExternalFunctionsToBlocks(cfg);\n AnalyzeCFG(cfg);\n LiftBlocks(cfg);\n}\n\n\/\/ Run an architecture-specific data-flow analysis on the module.\nvoid Translator::AnalyzeCFG(const cfg::Module *cfg) {\n if (!FLAGS_max_dataflow_analysis_iterations) return;\n\n AnalysisWorkList wl;\n auto &analysis = arch->CFGAnalyzer();\n\n for (const auto &block : cfg->blocks()) {\n analysis.AddBlock(block);\n }\n\n for (const auto &func : cfg->functions()) {\n analysis.AddFunction(func);\n }\n\n analysis.InitWorkList(wl);\n for (auto i = 0;\n wl.size() && i < FLAGS_max_dataflow_analysis_iterations; ++i) {\n AnalysisWorkList next_wl;\n for (auto item : wl) {\n analysis.AnalyzeBlock(item, next_wl);\n }\n wl.swap(next_wl);\n }\n analysis.Finalize();\n}\n\nllvm::Function *Translator::GetLiftedBlockForPC(uintptr_t pc) const {\n auto F = blocks[pc];\n if (!F) {\n LOG(ERROR) << \"Could not find lifted block for PC \" << pc;\n F = intrinsics->missing_block;\n }\n return F;\n}\n\n} \/\/ namespace mcsema\nAdd in address information to lifted basic block functions in the form of metadata.\/* Copyright 2015 Peter Goodman (peter@trailofbits.com), all rights reserved. *\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n#include \"mcsema\/Arch\/Arch.h\"\n#include \"mcsema\/BC\/IntrinsicTable.h\"\n#include \"mcsema\/BC\/Translator.h\"\n#include \"mcsema\/CFG\/CFG.h\"\n#include \"mcsema\/OS\/OS.h\"\n\nDEFINE_int32(max_dataflow_analysis_iterations, 0,\n \"Maximum number of iterations of a data flow pass to perform \"\n \"over the control-flow graph being lifted.\");\n\nDEFINE_bool(aggressive_dataflow_analysis, false,\n \"Should data-flow analysis be conservative in their conclusions? \"\n \"If not then the analysis will be really aggressive and make a lot \"\n \"of assumptions about function call behavior.\");\n\nnamespace llvm {\nclass ReturnInst;\n} \/\/ namespace\n\nnamespace mcsema {\nnamespace {\n\n\/\/ Name of some meta-data that we use to distinguish between external symbols\n\/\/ and private symbols.\nstatic std::string NamedSymbolMetaId(std::string func_name) {\n return \"mcsema_external:\" + func_name;\n}\n\n\/\/ Returns the ID for this binary. We prefix every basic block function added to\n\/\/ a module with the ID of the binary, where the ID is a number that increments\n\/\/ linearly.\nstatic int GetBinaryId(llvm::Module *M) {\n for (auto i = 1; ; ++i) {\n std::string id = \"mcsema_binary:\" + std::to_string(i);\n if (!M->getNamedMetadata(id)) {\n M->getOrInsertNamedMetadata(id);\n return i;\n }\n }\n __builtin_unreachable();\n}\n\n} \/\/ namespace\n\nTranslator::Translator(const Arch *arch_, llvm::Module *module_)\n : arch(arch_),\n module(module_),\n blocks(),\n functions(),\n symbols(),\n binary_id(GetBinaryId(module)),\n basic_block(FindFunction(module, \"__mcsema_basic_block\")),\n intrinsics(new IntrinsicTable(module)) {\n\n EnableDeferredInlining();\n IdentifyExistingSymbols();\n}\n\nnamespace {\n\nstatic void DisableInlining(llvm::Function *F) {\n F->removeFnAttr(llvm::Attribute::AlwaysInline);\n F->removeFnAttr(llvm::Attribute::InlineHint);\n F->addFnAttr(llvm::Attribute::NoInline);\n}\n\n} \/\/ namespace\n\n\/\/ Enable deferred inlining. The goal is to support better dead-store\n\/\/ elimination for flags.\nvoid Translator::EnableDeferredInlining(void) {\n if (!intrinsics->defer_inlining) return;\n DisableInlining(intrinsics->defer_inlining);\n\n for (auto U : intrinsics->defer_inlining->users()) {\n if (auto C = llvm::dyn_cast_or_null(U)) {\n auto B = C->getParent();\n auto F = B->getParent();\n DisableInlining(F);\n }\n }\n}\n\n\/\/ Find existing exported functions and variables. This is for the sake of\n\/\/ linking functions of the same names across CFG files.\nvoid Translator::IdentifyExistingSymbols(void) {\n for (auto &F : module->functions()) {\n std::string name = F.getName();\n if (module->getNamedMetadata(NamedSymbolMetaId(name))) {\n functions[name] = &F;\n }\n }\n\n for (auto &V : module->globals()) {\n std::string name = V.getName();\n if (module->getNamedMetadata(NamedSymbolMetaId(name))) {\n symbols[name] = &V;\n }\n }\n}\n\nnamespace {\n\nvoid InitBlockFuncAttributes(llvm::Function *BF, const llvm::Function *TF) {\n BF->setAttributes(TF->getAttributes());\n InitFunctionAttributes(BF);\n auto args = BF->arg_begin();\n (args++)->setName(\"state\");\n args->setName(\"pc\");\n}\n\nllvm::Function *GetBlockFunction(llvm::Module *M,\n const llvm::Function *TF,\n std::string name) {\n auto func_type = TF->getFunctionType();\n auto BF = llvm::dyn_cast(\n M->getOrInsertFunction(name, func_type));\n InitBlockFuncAttributes(BF, TF);\n BF->setLinkage(llvm::GlobalValue::PrivateLinkage);\n return BF;\n}\n\n\/\/ Add the address of the block as a special meta-data flag.\nstatic void SetMetaDataAddress(llvm::Module *M, const std::string &block_name,\n uint64_t block_address) {\n std::stringstream ss;\n ss << \"mcsema_address:\" << block_name;\n auto &C = M->getContext();\n auto Int64Ty = llvm::Type::getInt64Ty(C);\n auto CI = llvm::ConstantInt::get(Int64Ty, block_address, false);\n auto CM = llvm::ConstantAsMetadata::get(CI);\n M->addModuleFlag(llvm::Module::Warning, ss.str(), CM);\n}\n\n} \/\/ namespace\n\n\/\/ Create functions for every block in the CFG.\nvoid Translator::CreateFunctionsForBlocks(const cfg::Module *cfg) {\n std::set indirect_blocks;\n for (const auto &block : cfg->indirect_blocks()) {\n indirect_blocks.insert(block.address());\n }\n\n for (const auto &block : cfg->blocks()) {\n auto &BF = blocks[block.address()];\n if (!BF) {\n std::stringstream ss;\n ss << \"__lifted_block_\" << binary_id << \"_0x\"\n << std::hex << block.address();\n\n BF = GetBlockFunction(module, basic_block, ss.str());\n SetMetaDataAddress(module, ss.str(), block.address());\n\n \/\/ This block is externally visible so change its linkage and make a new\n \/\/ private block to which other blocks will refer.\n if (indirect_blocks.count(block.address())) {\n std::stringstream ss2;\n ss2 << \"__extern_block_\" << binary_id << \"_0x\"\n << std::hex << block.address();\n\n auto EF = GetBlockFunction(module, basic_block, ss2.str());\n EF->setLinkage(llvm::GlobalValue::ExternalLinkage);\n AddTerminatingTailCall(EF, BF, block.address());\n }\n }\n }\n}\n\nnamespace {\n\n\/\/ On Mac this strips off leading the underscore on symbol names.\n\/\/\n\/\/ TODO(pag): This is really ugly and is probably incorrect. The expectation is\n\/\/ that the leading underscore will be re-added when this code is\n\/\/ compiled.\nstd::string CanonicalName(OSName os_name, const std::string &name) {\n if (kOSMacOSX == os_name && name.length() && '_' == name[0]) {\n return name.substr(1);\n } else {\n return name;\n }\n}\n\n} \/\/ namespace\n\n\/\/ Create functions for every function in the CFG.\nvoid Translator::CreateExternalFunctions(const cfg::Module *cfg) {\n for (const auto &func : cfg->functions()) {\n if (!func.is_exported() && !func.is_imported()) continue;\n\n auto func_name = CanonicalName(arch->os_name, func.name());\n CHECK(!func_name.empty())\n << \"Module contains unnamed function at address \" << func.address();\n\n CHECK(!(func.is_exported() && func.is_imported()))\n << \"Function \" << func_name << \" can't be imported and exported.\";\n\n llvm::Function *&F = functions[func_name];\n if (!F) {\n F = GetBlockFunction(module, basic_block, func_name);\n\n \/\/ To get around some issues that `opt` has.\n F->addFnAttr(llvm::Attribute::NoBuiltin);\n F->addFnAttr(llvm::Attribute::OptimizeNone);\n F->addFnAttr(llvm::Attribute::NoInline);\n F->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);\n }\n\n \/\/ Mark this symbol as external. We do this so that we can pick up on it\n \/\/ if we merge another CFG into this bitcode module.\n module->getOrInsertNamedMetadata(NamedSymbolMetaId(func_name));\n }\n}\n\n\/\/ Link together functions and basic blocks.\nvoid Translator::LinkExternalFunctionsToBlocks(const cfg::Module *cfg) {\n for (const auto &func : cfg->functions()) {\n if (!func.is_exported() && !func.is_imported()) continue;\n if (!func.address()) continue;\n\n auto func_name = CanonicalName(arch->os_name, func.name());\n auto F = functions[func_name];\n auto &BF = blocks[func.address()];\n\n \/\/ In the case of an exported function, redirect the function's\n \/\/ implementation to a locally defined block.\n if (func.is_exported()) {\n\n CHECK(nullptr != BF)\n << \"Exported function \" << func_name << \" has no address!\";\n\n CHECK(F->isDeclaration())\n << \"Function \" << func_name << \" is already defined!\";\n\n AddTerminatingTailCall(F, BF, func.address());\n\n \/\/ In the case of ELF binaries, we tend to see a call to something like\n \/\/ `malloc@plt` that is responsible for finding and invoking the actual\n \/\/ `malloc` implementation. In this case, we want to treat the `malloc@plt`\n \/\/ block address as synonymous with the function.\n \/\/\n \/\/ TODO(pag): What about versioned ELF symbols?\n } else if (func.is_imported()) {\n if (!BF) {\n BF = F;\n } else {\n AddTerminatingTailCall(BF, F);\n }\n }\n }\n}\n\nnamespace {\n\n\/\/ Clone the block method template `TF` into a specific method `BF` that\n\/\/ will contain lifted code.\nstatic std::vector InitBlockFunction(\n llvm::Function *BF, const llvm::Function *TF, const cfg::Block &block) {\n llvm::ValueToValueMapTy var_map;\n auto targs = TF->arg_begin();\n auto bargs = BF->arg_begin();\n for (; targs != TF->arg_end(); ++targs, ++bargs) {\n var_map[&*targs] = &*bargs;\n }\n\n llvm::SmallVector returns;\n llvm::CloneFunctionInto(BF, TF, var_map, false, returns);\n\n InitBlockFuncAttributes(BF, TF);\n\n auto R = returns[0];\n R->removeFromParent();\n delete R;\n\n std::vector instruction_blocks;\n instruction_blocks.reserve(block.instructions_size());\n instruction_blocks.push_back(&(BF->back()));\n for (const auto &instr : block.instructions()) {\n\n \/\/ Name the block according to the instruction's address.\n std::stringstream ss;\n ss << \"0x\" << std::hex << instr.address();\n\n \/\/ Create a block for this instruction.\n auto B = llvm::BasicBlock::Create(BF->getContext(), ss.str(), BF);\n instruction_blocks.push_back(B);\n }\n return instruction_blocks;\n}\n\n\/\/ Fall-through PC for a block.\nstatic uint64_t FallThroughPC(const cfg::Block &block) {\n if (0 < block.instructions_size()) {\n const auto &instr = block.instructions(block.instructions_size() - 1);\n return instr.address() + instr.size();\n\n } else {\n LOG(ERROR) << \"Using block address as fall-through address.\";\n return block.address();\n }\n}\n\n} \/\/ namespace\n\n\/\/ Add a fall-through terminator to the block method just in case one is\n\/\/ missing.\nvoid Translator::TerminateBlockMethod(const cfg::Block &block,\n llvm::Function *BF) {\n auto &B = BF->back();\n if (B.getTerminator()) {\n return;\n }\n if (block.instructions_size()) {\n auto next_pc = FallThroughPC(block);\n AddTerminatingTailCall(BF, GetLiftedBlockForPC(next_pc), next_pc);\n } else {\n AddTerminatingTailCall(BF, intrinsics->missing_block, block.address());\n }\n}\n\n\/\/ Lift code contained in blocks into the block methods.\nvoid Translator::LiftBlocks(const cfg::Module *cfg) {\n llvm::legacy::FunctionPassManager FPM(module);\n FPM.add(llvm::createDeadCodeEliminationPass());\n FPM.add(llvm::createCFGSimplificationPass());\n FPM.add(llvm::createPromoteMemoryToRegisterPass());\n FPM.add(llvm::createReassociatePass());\n FPM.add(llvm::createInstructionCombiningPass());\n FPM.add(llvm::createDeadStoreEliminationPass());\n\n for (const auto &block : cfg->blocks()) {\n LOG_IF(WARNING, !block.instructions_size())\n << \"Block at \" << block.address() << \" has no instructions!\";\n\n auto BF = GetLiftedBlockForPC(block.address());\n if (!BF->isDeclaration()) {\n LOG(WARNING) << \"Ignoring already lifted block at \" << block.address();\n continue;\n }\n\n const auto instruction_blocks = InitBlockFunction(BF, basic_block, block);\n\n \/\/ Lift the instructions into the block in reverse order. This helps for\n \/\/ using the results of backward data-flow analyses.\n for (auto i = block.instructions_size(); i--; ) {\n const auto &instr = block.instructions(i);\n const auto bb = instruction_blocks[i + 1];\n LiftInstructionIntoBlock(block, instr, bb);\n }\n\n \/\/ Connect the internal blocks together with branches.\n if (instruction_blocks.size()) {\n for (auto i = 1; i < instruction_blocks.size(); ++i) {\n llvm::IRBuilder<> ir(instruction_blocks[i - 1]);\n ir.CreateBr(instruction_blocks[i]);\n }\n }\n\n TerminateBlockMethod(block, BF);\n\n \/\/ Perform simple, incremental optimizations on the block functions to\n \/\/ avoid OOMs.\n FPM.run(*BF);\n }\n}\n\n\/\/ Lift an instruction into a basic block. This does some minor sanity checks\n\/\/ then dispatches to the arch-specific translator.\nvoid Translator::LiftInstructionIntoBlock(\n const cfg::Block &block, const cfg::Instr &instr, llvm::BasicBlock *B) {\n\n CHECK(0 < instr.size())\n << \"Can't decode zero-sized instruction at \" << instr.address();\n\n CHECK(instr.size() == instr.bytes().length())\n << \"Instruction size mismatch for instruction at \" << instr.address();\n\n arch->LiftInstructionIntoBlock(*this, block, instr, B);\n}\n\nvoid Translator::LiftCFG(const cfg::Module *cfg) {\n blocks.clear(); \/\/ Just in case we call `LiftCFG` multiple times.\n CreateFunctionsForBlocks(cfg);\n CreateExternalFunctions(cfg);\n LinkExternalFunctionsToBlocks(cfg);\n AnalyzeCFG(cfg);\n LiftBlocks(cfg);\n}\n\n\/\/ Run an architecture-specific data-flow analysis on the module.\nvoid Translator::AnalyzeCFG(const cfg::Module *cfg) {\n if (!FLAGS_max_dataflow_analysis_iterations) return;\n\n AnalysisWorkList wl;\n auto &analysis = arch->CFGAnalyzer();\n\n for (const auto &block : cfg->blocks()) {\n analysis.AddBlock(block);\n }\n\n for (const auto &func : cfg->functions()) {\n analysis.AddFunction(func);\n }\n\n analysis.InitWorkList(wl);\n for (auto i = 0;\n wl.size() && i < FLAGS_max_dataflow_analysis_iterations; ++i) {\n AnalysisWorkList next_wl;\n for (auto item : wl) {\n analysis.AnalyzeBlock(item, next_wl);\n }\n wl.swap(next_wl);\n }\n analysis.Finalize();\n}\n\nllvm::Function *Translator::GetLiftedBlockForPC(uintptr_t pc) const {\n auto F = blocks[pc];\n if (!F) {\n LOG(ERROR) << \"Could not find lifted block for PC \" << pc;\n F = intrinsics->missing_block;\n }\n return F;\n}\n\n} \/\/ namespace mcsema\n<|endoftext|>"} {"text":"\/*\n *\n * Copyright (c) 2020 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"qvCHIP.h\"\n\n#if CHIP_ENABLE_OPENTHREAD\nextern \"C\" {\n#include \n}\n#endif \/\/ CHIP_ENABLE_OPENTHREAD\n\nusing namespace chip;\nusing namespace chip::Shell;\n\nnamespace {\n\nconst size_t kShellTaskStackSize = 2048;\nconst int kShellTaskPriority = 1;\nTaskHandle_t sShellTaskHandle;\n\nvoid ShellCLIMain(void * pvParameter)\n{\n \/\/ Initialize the default streamer that was linked.\n const int rc = streamer_init(streamer_get());\n\n if (rc != 0)\n {\n ChipLogError(Shell, \"Streamer initialization failed: %d\", rc);\n return;\n }\n\n ChipLogDetail(Shell, \"Initializing CHIP shell commands\", rc);\n\n cmd_device_init();\n cmd_base64_init();\n cmd_misc_init();\n cmd_btp_init();\n cmd_otcli_init();\n\n ChipLogDetail(Shell, \"Run CHIP shell Task\", rc);\n\n shell_task(nullptr);\n}\n\n} \/\/ namespace\n\nint StartShellTask(void)\n{\n int ret = 0;\n\n \/\/ Start Shell task.\n if (xTaskCreate(ShellCLIMain, \"SHELL\", kShellTaskStackSize \/ sizeof(StackType_t), NULL, kShellTaskPriority,\n &sShellTaskHandle) != pdPASS)\n {\n ret = -1;\n }\n\n return ret;\n}\n\nint main(void)\n{\n \/* Initialize platform *\/\n qvCHIP_init();\n\n \/* Launch shell task *\/\n StartShellTask();\n\n \/* Start FreeRTOS *\/\n vTaskStartScheduler();\n return 0;\n}\nCodeQL: Too many arguments to formatting function in examples\/shell\/qpg6100\/main.cpp (#3775)\/*\n *\n * Copyright (c) 2020 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"FreeRTOS.h\"\n#include \"task.h\"\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \"qvCHIP.h\"\n\n#if CHIP_ENABLE_OPENTHREAD\nextern \"C\" {\n#include \n}\n#endif \/\/ CHIP_ENABLE_OPENTHREAD\n\nusing namespace chip;\nusing namespace chip::Shell;\n\nnamespace {\n\nconst size_t kShellTaskStackSize = 2048;\nconst int kShellTaskPriority = 1;\nTaskHandle_t sShellTaskHandle;\n\nvoid ShellCLIMain(void * pvParameter)\n{\n \/\/ Initialize the default streamer that was linked.\n const int rc = streamer_init(streamer_get());\n\n if (rc != 0)\n {\n ChipLogError(Shell, \"Streamer initialization failed: %d\", rc);\n return;\n }\n\n ChipLogDetail(Shell, \"Initializing CHIP shell commands: %d\", rc);\n\n cmd_device_init();\n cmd_base64_init();\n cmd_misc_init();\n cmd_btp_init();\n cmd_otcli_init();\n\n ChipLogDetail(Shell, \"Run CHIP shell Task: %d\", rc);\n\n shell_task(nullptr);\n}\n\n} \/\/ namespace\n\nint StartShellTask(void)\n{\n int ret = 0;\n\n \/\/ Start Shell task.\n if (xTaskCreate(ShellCLIMain, \"SHELL\", kShellTaskStackSize \/ sizeof(StackType_t), NULL, kShellTaskPriority,\n &sShellTaskHandle) != pdPASS)\n {\n ret = -1;\n }\n\n return ret;\n}\n\nint main(void)\n{\n \/* Initialize platform *\/\n qvCHIP_init();\n\n \/* Launch shell task *\/\n StartShellTask();\n\n \/* Start FreeRTOS *\/\n vTaskStartScheduler();\n return 0;\n}\n<|endoftext|>"} {"text":"\/* \n * File: Composite.cpp\n * Author: Benedikt Vogler\n * \n * Created on 21. August 2014, 10:51\n *\/\n\n#include \"Composite.hpp\"\n#include \"Intersection.hpp\"\n#include \n\nvoid Composite::add_child(std::shared_ptr const& child) {\n children.push_back(child);\n}\n\n\nIntersection Composite::intersect(Ray const& ray) const {\n Ray ray_t;\n if (isTransformed())\n ray_t = Ray(\n glm::vec3(getWorldTransfInv() * glm::vec4(ray.origin, 1)),\n glm::vec3(getWorldTransfInv() * glm::vec4(ray.direction, 0))\n );\n else\n ray_t = ray;\n \n \n std::vector intersections;\n \n \/\/collect every intersection\n for(auto child = children.begin(); child != children.end(); ++child) {\/\/every children\n auto intersection = (*child)->intersect(ray_t);\n if (intersection.hit && ray.mintintersection.distance)\n intersections.push_back(intersection);\n }\n \n if (intersections.size()==0) return Intersection();\/\/no intersection\n \n \/\/return only intersection with nearest point\n return *std::min_element(\n intersections.begin(),\n intersections.end(),\n [](Intersection const& a, Intersection const& b)->bool { return a.distance < b.distance;}\n );\n\n}for each loop\/* \n * File: Composite.cpp\n * Author: Benedikt Vogler\n * \n * Created on 21. August 2014, 10:51\n *\/\n\n#include \"Composite.hpp\"\n#include \"Intersection.hpp\"\n#include \n\nvoid Composite::add_child(std::shared_ptr const& child) {\n children.push_back(child);\n}\n\n\nIntersection Composite::intersect(Ray const& ray) const {\n Ray ray_t;\n if (isTransformed())\n ray_t = Ray(\n glm::vec3(getWorldTransfInv() * glm::vec4(ray.origin, 1)),\n glm::vec3(getWorldTransfInv() * glm::vec4(ray.direction, 0))\n );\n else\n ray_t = ray;\n \n \n std::vector intersections;\n \n \/\/collect every intersection\n for(auto& child : children) {\/\/every children\n auto intersection = child->intersect(ray_t);\n if (intersection.hit && ray.mintintersection.distance)\n intersections.push_back(intersection);\n }\n \n if (intersections.size()==0) return Intersection();\/\/no intersection\n \n \/\/return only intersection with nearest point\n return *std::min_element(\n intersections.begin(),\n intersections.end(),\n [](Intersection const& a, Intersection const& b)->bool { return a.distance < b.distance;}\n );\n\n}<|endoftext|>"} {"text":"#include \"sdfloader.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"color.hpp\"\n#include \"material.hpp\"\n#include \"box.hpp\"\n#include \"sphere.hpp\"\n#include \"light.hpp\"\n#include \"camera.hpp\"\n\/\/#include \"scene.hpp\"\n\nvoid load_scene() {\n std::string line;\n std::ifstream myfile (\"..\/..\/..\/scene\/scene1.txt\");\n std::map> materials;\n std::vector> shapes;\n std::vector> lights;\n int xres,yres;\n Color amblight, background;\n std::string filename;\n Camera cam;\n\/\/ Scene scene1;\n if (myfile.is_open())\n {\n while ( getline (myfile,line) )\n {\n \/\/std::cout << line << '\\n';\n std::stringstream ss;\n \t ss << line;\n \t \n \t std::string keyword;\n \n \t ss>>keyword;\n if(keyword == \"#\"){continue;}\n if(keyword == \"define\"){\n \t ss>>keyword;\n if(keyword == \"material\"){\n Material mat;\n ss>>mat.name;\n \t ss>>mat.ka.r;\n \t ss>>mat.ka.g;\n ss>>mat.ka.b;\n \n ss>>mat.ks.r;\n \t ss>>mat.ks.g;\n ss>>mat.ks.b;\n \t \n ss>>mat.kd.r;\n \t ss>>mat.kd.g;\n ss>>mat.kd.b;\n \t ss>>mat.m;\n \n std::shared_ptr temp_ptr = std::make_shared(mat);\n materials.insert({mat.name, temp_ptr});\n \/\/materials[mat.name]= mat;\n std::cout << mat;\n }\n if(keyword == \"shape\"){\n ss>>keyword;\n\n\n if(keyword == \"box\"){\n std::string name;\n std::string mat_namebox;\n float minx,miny,minz,maxx,maxy,maxz;\n \n ss>>minx;\n ss>>miny;\n ss>>minz;\n ss>>maxx;\n ss>>maxy;\n ss>>maxz;\n\n glm::vec3 min{minx,miny,minz};\n glm::vec3 max{maxx,maxy,maxz};\n ss>>name;\n ss>>mat_namebox; \n \/\/std::string mat_namebox;\n \n std::shared_ptr temp_ptr = std::make_shared\n (\n Box{min,max,name,*materials[mat_namebox]}\n );\n std::cout << *temp_ptr;\n shapes.push_back(temp_ptr);\n\n }\n else if(keyword == \"sphere\"){\n std::string name;\n float x,y,z,r;\n ss>>name;\n ss>>x;\n ss>>y;\n ss>>z;\n glm::vec3 middle{x,y,z};\n ss>>r;\n std::string mat_name;\n ss>>mat_name; \n \/\/alternative\n \n \/*std::cout <>sph.name_;\n ss>>sph.middle_.x;\n ss>>sph.middle_.y;\n ss>>sph.middle_.z;\n ss>>sph.r_;\n ss>>sph.mat_;\n std::cout << sph;sph.mat_=*materials(mat_name);*\/\n std::shared_ptr temp_ptr = std::make_shared\n (\n Sphere{middle,r,name,*materials[mat_name]}\n );\n std::cout << *temp_ptr; \n shapes.push_back(temp_ptr);\n \/\/ std::cout << sph;\n }\n\n }\n if(keyword == \"light\"){\n std::string name;\n std::string mat_namelight;\n float posx, posy, posz, ldr, ldg, ldb;\n ss>>name;\n ss>>posx;\n ss>>posy;\n ss>>posz;\n glm::vec3 pos{posx,posy,posz};\n ss>>ldr;\n ss>>ldg;\n ss>>ldb;\n Color ld{ldr,ldg,ldb};\n \n std::shared_ptr temp_ptr = std::make_shared\n (\n Light{name, pos, ld}\n );\n std::cout << *temp_ptr;\n lights.push_back(temp_ptr);\n\n\n }\n \n if(keyword == \"camera\"){\n std::string name;\n float angle, posx, posy, posz;\n ss>>name;\n ss>>posx;\n ss>>posy;\n ss>>posz;\n glm::vec3 pos{posx,posy,posz};\n ss>>angle;\n\n\n \/*std::shared_ptr cam_ptr = std::make_shared\n (\n Camera{name,pos,angle}\n );*\/\n Camera camera; \n \/\/cam.name_=name;\n \/\/cam.pos_=pos;\n \/\/cam.angle_=angle; \n \/\/Camera cam{name,pos,angle};\n std::cout << cam;\n cam=camera; \n \n }\n if(keyword == \"amblight\"){\n ss>>ambr;\n ss>>ambg;\n ss>>ambb;\n Color amb{ambr,ambg,ambb};\n amblight=amb;\n }\n if(keyword == \"background\"){\n ss>>backr;\n ss>>backg;\n ss>>backb;\n Color back{backr,backg,backb};\n background=back;\n }\n if(keyword == \"renderer\"){\n ss>>keyword;\n ss>>filename;\n ss>>xres;\n ss>>yres; \n std::shared_ptr scene_ptr = std::make_shared\n (\n Scene{filename, xres, yres, cam, amblight, background, materials, shapes, lights}\n );\n }\n }\n\n\n myfile.close();\n }\n\n else std::cout << \"Unable to open file\"; \n}\ntryin to find out da damn issuse, bad voodo that is ma friend...#include \"sdfloader.hpp\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"color.hpp\"\n#include \"material.hpp\"\n#include \"box.hpp\"\n#include \"sphere.hpp\"\n#include \"light.hpp\"\n#include \"camera.hpp\"\n#include \"scene.hpp\"\n\nvoid load_scene() {\n std::string line;\n std::ifstream myfile (\"..\/..\/..\/scene\/scene1.txt\");\n std::map> materials;\n std::vector> shapes;\n std::vector> lights;\n int xres,yres;\n Color amblight, background;\n std::string filename;\n Camera cam;\n\/\/ Scene scene1;\n if (myfile.is_open())\n {\n while ( getline (myfile,line) )\n {\n \/\/std::cout << line << '\\n';\n std::stringstream ss;\n \t ss << line;\n \t \n \t std::string keyword;\n \n \t ss>>keyword;\n if(keyword == \"#\"){continue;}\n if(keyword == \"define\"){\n \t ss>>keyword;\n if(keyword == \"material\"){\n Material mat;\n ss>>mat.name;\n \t ss>>mat.ka.r;\n \t ss>>mat.ka.g;\n ss>>mat.ka.b;\n \n ss>>mat.ks.r;\n \t ss>>mat.ks.g;\n ss>>mat.ks.b;\n \t \n ss>>mat.kd.r;\n \t ss>>mat.kd.g;\n ss>>mat.kd.b;\n \t ss>>mat.m;\n \n std::shared_ptr temp_ptr = std::make_shared(mat);\n materials.insert({mat.name, temp_ptr});\n \/\/materials[mat.name]= mat;\n std::cout << mat;\n }\n if(keyword == \"shape\"){\n ss>>keyword;\n\n\n if(keyword == \"box\"){\n std::string name;\n std::string mat_namebox;\n float minx,miny,minz,maxx,maxy,maxz;\n \n ss>>minx;\n ss>>miny;\n ss>>minz;\n ss>>maxx;\n ss>>maxy;\n ss>>maxz;\n\n glm::vec3 min{minx,miny,minz};\n glm::vec3 max{maxx,maxy,maxz};\n ss>>name;\n ss>>mat_namebox; \n \/\/std::string mat_namebox;\n \n std::shared_ptr temp_ptr = std::make_shared\n (\n Box{min,max,name,*materials[mat_namebox]}\n );\n std::cout << *temp_ptr;\n shapes.push_back(temp_ptr);\n\n }\n else if(keyword == \"sphere\"){\n std::string name;\n float x,y,z,r;\n ss>>name;\n ss>>x;\n ss>>y;\n ss>>z;\n glm::vec3 middle{x,y,z};\n ss>>r;\n std::string mat_name;\n ss>>mat_name; \n \/\/alternative\n \n \/*std::cout <>sph.name_;\n ss>>sph.middle_.x;\n ss>>sph.middle_.y;\n ss>>sph.middle_.z;\n ss>>sph.r_;\n ss>>sph.mat_;\n std::cout << sph;sph.mat_=*materials(mat_name);*\/\n std::shared_ptr temp_ptr = std::make_shared\n (\n Sphere{middle,r,name,*materials[mat_name]}\n );\n std::cout << *temp_ptr; \n shapes.push_back(temp_ptr);\n \/\/ std::cout << sph;\n }\n\n }\n if(keyword == \"light\"){\n std::string name;\n std::string mat_namelight;\n float posx, posy, posz, ldr, ldg, ldb;\n ss>>name;\n ss>>posx;\n ss>>posy;\n ss>>posz;\n glm::vec3 pos{posx,posy,posz};\n ss>>ldr;\n ss>>ldg;\n ss>>ldb;\n Color ld{ldr,ldg,ldb};\n \n std::shared_ptr temp_ptr = std::make_shared\n (\n Light{name, pos, ld}\n );\n std::cout << *temp_ptr;\n lights.push_back(temp_ptr);\n\n\n }\n \n if(keyword == \"camera\"){\n std::string name;\n float angle, posx, posy, posz;\n ss>>name;\n ss>>posx;\n ss>>posy;\n ss>>posz;\n glm::vec3 pos{posx,posy,posz};\n ss>>angle;\n\n\n \/*std::shared_ptr cam_ptr = std::make_shared\n (\n Camera{name,pos,angle}\n );*\/\n Camera camera; \n \/\/cam.name_=name;\n \/\/cam.pos_=pos;\n \/\/cam.angle_=angle; \n \/\/Camera cam{name,pos,angle};\n std::cout << cam;\n cam=camera; \n \n }\n if(keyword == \"amblight\"){\n float ambr,ambg,ambb;\n ss>>ambr;\n ss>>ambg;\n ss>>ambb;\n Color amb{ambr,ambg,ambb};\n amblight=amb;\n }\n if(keyword == \"background\"){\n float backr, backg, backb;\n ss>>backr;\n ss>>backg;\n ss>>backb;\n Color back{backr,backg,backb};\n background=back;\n }\n if(keyword == \"renderer\"){\n ss>>keyword;\n ss>>filename;\n ss>>xres;\n ss>>yres; \n std::shared_ptr scene_ptr = std::make_shared\n (\n Scene{filename, xres, yres, cam, amblight, background, materials, shapes, lights}\n );\n }\n }\n\n\n myfile.close();\n }\n\n else std::cout << \"Unable to open file\"; \n}\n<|endoftext|>"} {"text":"#include \n\nnamespace Bull\n{\n namespace prv\n {\n \/*! \\brief Constructor\n *\n * \\param mode The VideoMode to use to create the window\n * \\param title The title of the window\n * \\param style The style to use to create the window\n *\n *\/\n WindowImplX11::WindowImplX11(const VideoMode& mode, const String& title, Uint32 style) :\n m_display(Display::get()),\n m_handler(0)\n {\n XSetWindowAttributes attribs;\n attribs.event_mask = KeyPressMask | KeyReleaseMask;\n\n m_handler = XCreateWindow(m_display->getHandler(),\n m_display->getRootWindow(),\n 0, 0,\n mode.width, mode.height,\n 0,\n CopyFromParent,\n InputOutput,\n nullptr,\n CWEventMask | CWBackPixel,\n &attribs);\n\n setTitle(title);\n\n XMapWindow(m_display->getHandler(), m_handler);\n m_display->flush();\n }\n\n \/*! \\brief Destructor\n *\n *\/\n WindowImplX11::~WindowImplX11()\n {\n XDestroyWindow(m_display->getHandler(), m_handler);\n }\n\n \/*! \\brief Start to process events to fill event queue\n *\n *\/\n void WindowImplX11::startProcessEvents()\n {\n XEvent e;\n while(XPending(m_display->getHandler()))\n {\n XNextEvent(m_display->getHandler(), &e);\n switch(e.type)\n {\n case KeyPress:\n {\n Window::Event event;\n\n event.type = Window::Event::KeyDown;\n\n pushEvent(event);\n }\n break;\n\n case KeyRelease:\n {\n Window::Event event;\n\n event.type = Window::Event::KeyUp;\n\n pushEvent(event);\n }\n break;\n }\n }\n }\n\n \/*! \\brief Minimize a window\n *\n *\/\n void WindowImplX11::minimize()\n {\n\n }\n\n \/*! \\brief Check if the window is minimized\n *\n * \\return Return true if the window is minimized, false otherwise\n *\n *\/\n bool WindowImplX11::isMinimized() const\n {\n\n }\n\n \/*! \\brief Maximize a window\n *\n *\/\n void WindowImplX11::maximize()\n {\n\n }\n\n \/*! \\brief Check if the window is maximized\n *\n * \\return Return true if the window is maximized, false otherwise\n *\n *\/\n bool WindowImplX11::isMaximized() const\n {\n\n }\n\n \/*! \\brief Enable or disable the capture of the cursor inside the window\n *\n * \\param enable The state of the capture\n *\n *\/\n void WindowImplX11::enableCaptureCursor(bool capture)\n {\n\n }\n\n \/*! \\brief Hide or show the cursor\n *\n * \\param enable The state of the cursor\n *\n *\/\n void WindowImplX11::showCursor(bool enable)\n {\n\n }\n\n \/*! \\brief Set the size of the window\n *\n * \\param size The new size of the window\n *\n *\/\n void WindowImplX11::setPosition(const Vector2I& position)\n {\n\n }\n\n \/*! \\brief Set the size of the window\n *\n * \\param x The new width of the window\n * \\param y The new height of the window\n *\n *\/\n Vector2I WindowImplX11::getPosition() const\n {\n\n }\n\n \/*! \\brief Set the size of the window\n *\n * \\param size The new size of the window\n *\n *\/\n void WindowImplX11::setSize(const Vector2UI& size)\n {\n\n }\n\n \/*! \\brief Get the size of the window\n *\n * \\return Return the size of the window\n *\n *\/\n Vector2UI WindowImplX11::getSize() const\n {\n\n }\n\n \/*! \\brief Set the title of the window\n *\n * \\param title The title to set to the window\n *\n *\/\n void WindowImplX11::setTitle(const String& title)\n {\n XStoreName(m_display->getHandler(), m_handler, title);\n }\n\n \/*! \\brief Get the title of the window\n *\n * \\return Return the title of the window\n *\n *\/\n String WindowImplX11::getTitle() const\n {\n\n }\n\n \/*! \\brief Check if the window has the focus\n *\n * \\param Return true if the window has the focus, false otherwise\n *\n *\/\n bool WindowImplX11::hasFocus() const\n {\n\n }\n\n \/*! \\brief Enter or leave the fullscreen mode\n *\n * \\param mode The VideoMode to use\n * \\param fullscreen False to leave the fullscreen mode, true to enter the fullscreen mode\n *\n * \\return Return true if the switch was done successfully, false otherwise\n *\n *\/\n bool WindowImplX11::switchFullscreen(const VideoMode& mode, bool fullscreen)\n {\n\n }\n\n \/*! \\brief Show or hide the window\n *\n * \\param visible True to show the window, false to hide the window\n *\n *\/\n void WindowImplX11::setVisible(bool visible)\n {\n\n }\n\n \/*! \\brief Get the window system handler\n *\n * \\return Return the native window system handler\n *\n *\/\n WindowHandler WindowImplX11::getSystemHandler() const\n {\n return m_handler;\n }\n }\n}\n[WIndow\/Window\/X11] Handle mouse events#include \n\n#ifndef Button6\n #define Button6 6\n#endif \/\/ Button6\n\n#ifndef Button7\n #define Button7 7\n#endif \/\/ Button6\n\n#ifndef Button8\n #define Button8 8\n#endif \/\/ Button6\n\n#ifndef Button9\n #define Button9 9\n#endif \/\/ Button6\n\nnamespace Bull\n{\n namespace prv\n {\n namespace\n {\n const long eventMasks = KeyPressMask | KeyReleaseMask | \/\/\/ Keyboard events\n PointerMotionMask | \/\/\/ Mouse move event\n ButtonPressMask | ButtonReleaseMask;\n\n }\n \/*! \\brief Constructor\n *\n * \\param mode The VideoMode to use to create the window\n * \\param title The title of the window\n * \\param style The style to use to create the window\n *\n *\/\n WindowImplX11::WindowImplX11(const VideoMode& mode, const String& title, Uint32 style) :\n m_display(Display::get()),\n m_handler(0)\n {\n XSetWindowAttributes attribs;\n attribs.event_mask = eventMasks;\n\n m_handler = XCreateWindow(m_display->getHandler(),\n m_display->getRootWindow(),\n 0, 0,\n mode.width, mode.height,\n 0,\n CopyFromParent,\n InputOutput,\n nullptr,\n CWEventMask | CWBackPixel,\n &attribs);\n\n setTitle(title);\n\n XMapWindow(m_display->getHandler(), m_handler);\n m_display->flush();\n }\n\n \/*! \\brief Destructor\n *\n *\/\n WindowImplX11::~WindowImplX11()\n {\n XDestroyWindow(m_display->getHandler(), m_handler);\n }\n\n \/*! \\brief Start to process events to fill event queue\n *\n *\/\n void WindowImplX11::startProcessEvents()\n {\n XEvent e;\n while(XPending(m_display->getHandler()))\n {\n XNextEvent(m_display->getHandler(), &e);\n switch(e.type)\n {\n case KeyPress:\n {\n Window::Event event;\n\n event.type = Window::Event::KeyDown;\n\n pushEvent(event);\n }\n break;\n\n case KeyRelease:\n {\n Window::Event event;\n\n event.type = Window::Event::KeyUp;\n\n pushEvent(event);\n }\n break;\n\n case MotionNotify:\n {\n Window::Event event;\n\n event.type = Window::Event::MouseMoved;\n event.mouseMove.x = e.xmotion.x;\n event.mouseMove.y = e.xmotion.y;\n\n pushEvent(event);\n }\n break;\n\n case ButtonPress:\n {\n Window::Event event;\n\n if(e.xbutton.button <= Button3 || e.xbutton.button >= Button8)\n {\n event.type = Window::Event::MouseButtonDown;\n event.mouseButton.x = e.xbutton.x;\n event.mouseButton.y = e.xbutton.y;\n\n }\n else\n {\n event.type = Window::Event::MouseWheel;\n event.mouseWheel.x = e.xbutton.x;\n event.mouseWheel.y = e.xbutton.y;\n }\n\n switch(e.xbutton.button)\n {\n case Button1:\n event.mouseButton.button = Mouse::Left;\n break;\n case Button2:\n event.mouseButton.button = Mouse::Middle;\n break;\n case Button3:\n event.mouseButton.button = Mouse::Right;\n break;\n case Button4:\n event.mouseWheel.up = true;\n event.mouseWheel.wheel = Mouse::Vertical;\n break;\n case Button5:\n event.mouseWheel.up = false;\n event.mouseWheel.wheel = Mouse::Vertical;\n break;\n case Button6:\n event.mouseWheel.up = true;\n event.mouseWheel.wheel = Mouse::Horizontal;\n break;\n case Button7:\n event.mouseWheel.up = false;\n event.mouseWheel.wheel = Mouse::Horizontal;\n break;\n case Button8:\n event.mouseButton.button = Mouse::Extra1;\n break;\n case Button9:\n event.mouseButton.button = Mouse::Extra2;\n break;\n }\n\n pushEvent(event);\n }\n break;\n\n case ButtonRelease:\n {\n if(e.xbutton.button <= Button3 || e.xbutton.button >= Button8)\n {\n Window::Event event;\n event.type = Window::Event::MouseButtonUp;\n\n switch(e.xbutton.button)\n {\n case Button1:\n event.mouseButton.button = Mouse::Left;\n break;\n case Button2:\n event.mouseButton.button = Mouse::Middle;\n break;\n case Button3:\n event.mouseButton.button = Mouse::Right;\n break;\n case Button8:\n event.mouseButton.button = Mouse::Extra1;\n break;\n case Button9:\n event.mouseButton.button = Mouse::Extra2;\n break;\n }\n\n event.mouseButton.x = e.xbutton.x;\n event.mouseButton.y = e.xbutton.y;\n\n pushEvent(event);\n }\n }\n break;\n }\n }\n }\n\n \/*! \\brief Minimize a window\n *\n *\/\n void WindowImplX11::minimize()\n {\n\n }\n\n \/*! \\brief Check if the window is minimized\n *\n * \\return Return true if the window is minimized, false otherwise\n *\n *\/\n bool WindowImplX11::isMinimized() const\n {\n\n }\n\n \/*! \\brief Maximize a window\n *\n *\/\n void WindowImplX11::maximize()\n {\n\n }\n\n \/*! \\brief Check if the window is maximized\n *\n * \\return Return true if the window is maximized, false otherwise\n *\n *\/\n bool WindowImplX11::isMaximized() const\n {\n\n }\n\n \/*! \\brief Enable or disable the capture of the cursor inside the window\n *\n * \\param enable The state of the capture\n *\n *\/\n void WindowImplX11::enableCaptureCursor(bool capture)\n {\n\n }\n\n \/*! \\brief Hide or show the cursor\n *\n * \\param enable The state of the cursor\n *\n *\/\n void WindowImplX11::showCursor(bool enable)\n {\n\n }\n\n \/*! \\brief Set the size of the window\n *\n * \\param size The new size of the window\n *\n *\/\n void WindowImplX11::setPosition(const Vector2I& position)\n {\n\n }\n\n \/*! \\brief Set the size of the window\n *\n * \\param x The new width of the window\n * \\param y The new height of the window\n *\n *\/\n Vector2I WindowImplX11::getPosition() const\n {\n\n }\n\n \/*! \\brief Set the size of the window\n *\n * \\param size The new size of the window\n *\n *\/\n void WindowImplX11::setSize(const Vector2UI& size)\n {\n\n }\n\n \/*! \\brief Get the size of the window\n *\n * \\return Return the size of the window\n *\n *\/\n Vector2UI WindowImplX11::getSize() const\n {\n\n }\n\n \/*! \\brief Set the title of the window\n *\n * \\param title The title to set to the window\n *\n *\/\n void WindowImplX11::setTitle(const String& title)\n {\n XStoreName(m_display->getHandler(), m_handler, title);\n }\n\n \/*! \\brief Get the title of the window\n *\n * \\return Return the title of the window\n *\n *\/\n String WindowImplX11::getTitle() const\n {\n\n }\n\n \/*! \\brief Check if the window has the focus\n *\n * \\param Return true if the window has the focus, false otherwise\n *\n *\/\n bool WindowImplX11::hasFocus() const\n {\n\n }\n\n \/*! \\brief Enter or leave the fullscreen mode\n *\n * \\param mode The VideoMode to use\n * \\param fullscreen False to leave the fullscreen mode, true to enter the fullscreen mode\n *\n * \\return Return true if the switch was done successfully, false otherwise\n *\n *\/\n bool WindowImplX11::switchFullscreen(const VideoMode& mode, bool fullscreen)\n {\n\n }\n\n \/*! \\brief Show or hide the window\n *\n * \\param visible True to show the window, false to hide the window\n *\n *\/\n void WindowImplX11::setVisible(bool visible)\n {\n\n }\n\n \/*! \\brief Get the window system handler\n *\n * \\return Return the native window system handler\n *\n *\/\n WindowHandler WindowImplX11::getSystemHandler() const\n {\n return m_handler;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"CombFilterProject.h\"\n#include \"FilterAudio.h\"\n\n\/\/# define TEST_MODE\n\nusing namespace std;\n\n\/\/function\nint testZeroInput();\nfloat *sinOsc(float, float, float, unsigned);\nint testFIRFeedforward();\nint testIIRFeedforward();\n\n\n\/\/ main function\nint main(int argc, char* argv[])\n{\n \/\/decalare local variables\n CombFilterProject *pCombFilterProject;\n \n string sInputFilePath, sOutputFilePath, sInputFileName, sOutputFileName;\n\n float fFIRCoeff = 0.0;\n float fIIRCoeff = 0.0;\n float fDelayInMSec = 0.0;\n int iBlockSize = 2048; \/\/default blockSize\n bool bOutputResultToTextFile = false; \/\/default\n int iFileOpenStatus;\n\n \n \/\/ Parse command line arguments\n if( argc == 7 || argc == 8) {\n \/\/File path and name\n sInputFilePath = argv[1];\n sInputFileName = argv[2];\n \n \/\/Gain\n fFIRCoeff = atof(argv[3]);\n fIIRCoeff = atof(argv[4]);\n \n \/\/Check for boundary conditions\n if (fFIRCoeff > 1 || fFIRCoeff < -1 || fIIRCoeff > 1 || fFIRCoeff < -1) {\n cout<<\"\\nFIR\/IIR Co-efficient should be between -1 and 1.\\n\";\n return 0;\n }\n \/\/Delay time\n fDelayInMSec = atof(argv[5]);\n \n \/\/Check that delay time is positive\n if (fDelayInMSec < 0 ) {\n cout<<\"\\nDelay time must be positive.\\n\";\n return 0;\n }\n \n \/\/enable write to Text file\n if (argv[6] != NULL) {\n int temp = atoi(argv[6]);\n if (temp == 1) {\n bOutputResultToTextFile = true;\n }\n }\n \n \/\/Optional argument to set blockSize\n if (argv[7] != NULL) {\n iBlockSize = atoi(argv[7]);\n }\n }\n else if( argc > 8 ) {\n printf(\"Too many arguments supplied.\\n\");\n return 0;\n }\n else {\n printf(\"Please provide the following\\n 1.file path\\n 2.audio file name\\n 3.FIR gain\\n 4.IIR gain\\n 5.delay time in milliseconds\\n 6.write to text file (yes - 1, no - any value)\\n 7.[OPTIONAL] block size\\n \");\n return 0;\n }\n \n \n \/\/Create Comb Filter\n CombFilterProject::create(pCombFilterProject, iBlockSize);\n \n \/\/Print Information\n cout<<\"CombFilter V\"<getVersion(CombFilterProject::kMajor)\n <<\".\"<getVersion(CombFilterProject::kMinor)\n <<\".\"<getVersion(CombFilterProject::kPatch)<getBuildDate()<init(sInputFilePath, sInputFileName, sOutputFilePath, sOutputFileName, fFIRCoeff, fIIRCoeff, fDelayInMSec, bOutputResultToTextFile);\n \n if (iFileOpenStatus != 0) {\n \/*File open error*\/\n return 0;\n }\n \n cout<<\"\\nDelay in samples: \"<getDelayinSamples()<processAudio();\n \n pCombFilterProject->destroy(pCombFilterProject);\n \n cout<<\"Success!\\n\";\n \n testZeroInput();\n testFIRFeedforward();\n testIIRFeedforward();\n \n return 0;\n}\n\nint testZeroInput() {\n FilterAudio *pFilter;\n float fFIRCoeff = 1.0;\n float fIIRCoeff = 0.0;\n int iDelayInSamples = 10;\n int iNumChannels = 1;\n int iBlockSize = 1024;\n int iNumBlocks = 50; \/\/Test for 10 blocks\n float **ppfAudioData = new float *[iNumChannels];\n \n for (int n=0; n 0) {\n pFilter->combFilterBlock(ppfAudioData, iBlockSize, iNumChannels);\n \n for (int n=0; n 0.001) {\n \n cout<<\"\\nZero Input Test: failed!\\n\";\n return -1;\n }\n }\n }\n iNumBlocks--;\n }\n\n cout<<\"\\nZero Input Test: Success!\\n\";\n return 0;\n}\n\nint testFIRFeedforward() {\n \n FilterAudio *pFilter;\n float fFIRCoeff = 1.0;\n float fIIRCoeff = 0.0;\n int iDelayInSamples = 50;\n int iNumChannels = 1;\n int iBlockSize = 1024;\n int iNumBlocks;\n \n float fFreq = 441.0; \/\/Hz\n float fTimeInSecs = 2.0;\n unsigned uSampleRate = 44100;\n \n float **buffer = new float *[iNumChannels];\n for (int i=0;i iLengthInSamples) {\n memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n }\n else {\n memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n }\n \n buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);\n\n start = 0;\n if (n == 0){\n start = iDelayInSamples+1;\n }\n \n for (int m=start; m 0.001) {\n cout<<\"\\nFIR Feedforward Test: failed!\\n\";\n return -1;\n }\n }\n \n }\n \n cout<<\"\\nFIR Feedforward Test: Success!\\n\";\n }\n \n return 0;\n}\n\nint testIIRFeedforward() {\n \n FilterAudio *pFilter;\n float fFIRCoeff = 0.0;\n float fIIRCoeff = 0.1;\n int iDelayInSamples = 100;\n int iNumChannels = 1;\n int iBlockSize = 1024;\n int iNumBlocks;\n \n float fFreq = 441.0; \/\/Hz\n float fTimeInSecs = 2.0;\n unsigned uSampleRate = 44100;\n \n float **buffer = new float *[iNumChannels];\n for (int i=0;i iLengthInSamples) {\n memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n }\n else {\n memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n memcpy(origBuffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n }\n \n buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);\n \n float* temp = buffer[c];\n float* origTemp = origBuffer[c];\n\/\/ float* diff = new float[iBlockSize];\n \n\/\/ for (int m=iPeriodInSamples+iPeriodInSamples\/4; mAll test functions updated#include \n#include \n#include \n#include \"CombFilterProject.h\"\n#include \"FilterAudio.h\"\n\n# define TEST_MODE\n\nusing namespace std;\n\n\/\/function declarations\nfloat *sinOsc(float, float, float, unsigned);\nint testZeroInput();\nint testFIRFeedforward();\nint testIIRDestructiveFeedforward();\nint testIIRConstructiveFeedforward();\nint testDifferntBlockSizes();\nint testZeroDelay(int, float, float);\nint testFIRImpulseResponse();\nint testIIRImpulseResponse();\n\n\/\/ main function\nint main(int argc, char* argv[])\n{\n \/\/decalare local variables\n CombFilterProject *pCombFilterProject;\n \n string sInputFilePath, sOutputFilePath, sInputFileName, sOutputFileName;\n\n float fFIRCoeff = 0.0;\n float fIIRCoeff = 0.0;\n float fDelayInMSec = 0.0;\n int iBlockSize = 2048; \/\/default blockSize\n bool bOutputResultToTextFile = false; \/\/default\n int iFileOpenStatus;\n\n \n \/\/ Parse command line arguments\n if( argc == 7 || argc == 8) {\n \/\/File path and name\n sInputFilePath = argv[1];\n sInputFileName = argv[2];\n \n \/\/Gain\n fFIRCoeff = atof(argv[3]);\n fIIRCoeff = atof(argv[4]);\n \n \/\/Check for boundary conditions\n if (fFIRCoeff > 1 || fFIRCoeff < -1 || fIIRCoeff > 1 || fFIRCoeff < -1) {\n cout<<\"\\nFIR\/IIR Co-efficient should be between -1 and 1.\\n\";\n return 0;\n }\n \/\/Delay time\n fDelayInMSec = atof(argv[5]);\n \n \/\/Check that delay time is positive\n if (fDelayInMSec < 0 ) {\n cout<<\"\\nDelay time must be positive.\\n\";\n return 0;\n }\n \n \/\/enable write to Text file\n if (argv[6] != NULL) {\n int temp = atoi(argv[6]);\n if (temp == 1) {\n bOutputResultToTextFile = true;\n }\n }\n \n \/\/Optional argument to set blockSize\n if (argv[7] != NULL) {\n iBlockSize = atoi(argv[7]);\n }\n }\n else if( argc > 8 ) {\n printf(\"Too many arguments supplied.\\n\");\n return 0;\n }\n else {\n printf(\"Please provide the following\\n 1.file path\\n 2.audio file name\\n 3.FIR gain\\n 4.IIR gain\\n 5.delay time in milliseconds\\n 6.write to text file (yes - 1, no - any value)\\n 7.[OPTIONAL] block size\\n \");\n return 0;\n }\n \n \n \/\/Create Comb Filter\n CombFilterProject::create(pCombFilterProject, iBlockSize);\n \n \/\/Print Information\n cout<<\"CombFilter V\"<getVersion(CombFilterProject::kMajor)\n <<\".\"<getVersion(CombFilterProject::kMinor)\n <<\".\"<getVersion(CombFilterProject::kPatch)<getBuildDate()<init(sInputFilePath, sInputFileName, sOutputFilePath, sOutputFileName, fFIRCoeff, fIIRCoeff, fDelayInMSec, bOutputResultToTextFile);\n \n if (iFileOpenStatus != 0) {\n \/*File open error*\/\n return 0;\n }\n \n cout<<\"\\nDelay in samples: \"<getDelayinSamples()<processAudio();\n \n pCombFilterProject->destroy(pCombFilterProject);\n \n cout<<\"Success!\\n\";\n \n#ifdef TEST_MODE\n \n cout<<\"\\n====== Test Results ======\\n\";\n testFIRFeedforward();\n testIIRDestructiveFeedforward();\n testIIRConstructiveFeedforward();\n testDifferntBlockSizes();\n testZeroInput();\n \n \/\/--- Some extra tests --- \/\/\n if (testZeroDelay(1024, 1.0, 0)==0) {\n cout<<\"\\nZero Delay Test: Success!\\n\";\n }\n testFIRImpulseResponse();\n testIIRImpulseResponse();\n \n#endif\n \n return 0;\n}\n\nint testZeroInput() {\n FilterAudio *pFilter;\n float fFIRCoeff = 1.0;\n float fIIRCoeff = 0.0;\n int iDelayInSamples = 10;\n int iNumChannels = 1;\n int iBlockSize = 1024;\n int iNumBlocks = 50; \/\/Length of sample is 50 blocks\n \n \/\/Allocate memory\n float **ppfAudioData = new float *[iNumChannels];\n for (int n=0; n 0) {\n \n \/\/Get filtered data\n ppfAudioData = pFilter->combFilterBlock(ppfAudioData, iBlockSize, iNumChannels);\n \n for (int n=0; n 0.001) {\n cout<<\"\\nZero Input Test: failed!\\n\";\n return -1;\n }\n }\n }\n iNumBlocks--;\n }\n\n cout<<\"\\nZero Input Test: Success!\\n\";\n \n \/\/Free memory\n delete pFilter;\n pFilter = 0;\n for (int n=0; n iLengthInSamples) {\n memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n }\n else {\n memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n }\n \n buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);\n\n \/\/Ignore first part of the first block\n start = 0;\n if (n == 0){\n start = iDelayInSamples+1;\n }\n \n for (int m=start; m 0.001) {\n cout<<\"\\nFIR Feedforward Test: failed!\\n\";\n return -1;\n }\n }\n \n }\n \n cout<<\"\\nFIR Feedforward Test: Success!\\n\";\n }\n \n \/\/Free memory\n delete pFilter;\n pFilter = 0;\n for (int i=0;i iLengthInSamples) {\n memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n }\n else {\n memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n }\n \n buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);\n \n if (n == 0){\n start = iPeriodInSamples+1;\n }\n \n for (int m=0+start; m= fMaxAmp) {\n fMaxAmp = buffer[c][m];\n }\n }\n \n \/\/Max amplitude of output should always be less than input\n if (fMaxAmp >= fAmp) {\n cout<<\"\\nIIR Desructive Feedforward Test: failed!\\n\";\n return -1;\n }\n \n }\n \n cout<<\"\\nIIR Destructive Feedforward Test: Success!\\n\";\n }\n \n \/\/Free memory\n delete pFilter;\n pFilter = 0;\n for (int i=0;i iLengthInSamples) {\n memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n }\n else {\n memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n }\n \n buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);\n \n if (n == 0){\n start = iPeriodInSamples+1;\n }\n \n for (int m=0+start; m= fMaxAmp) {\n fMaxAmp = buffer[c][m];\n }\n }\n \n \/\/Max amplitude of output should always be greater than input\n if (fMaxAmp <= fAmp) {\n cout<<\"\\nIIR Constructive Feedforward Test: failed!\\n\";\n return -1;\n }\n }\n cout<<\"\\nIIR Constructive Feedforward Test: Success!\\n\";\n }\n \n \/\/Free memory\n delete pFilter;\n pFilter = 0;\n for (int i=0;i iLengthInSamples) {\n memcpy(buffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n memcpy(origBuffer[c], &sinWave[n*iBlockSize], (iLengthInSamples-n*iBlockSize)*sizeof(float));\n }\n else {\n memcpy(buffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n memcpy(origBuffer[c], &sinWave[n*iBlockSize], iBlockSize*sizeof(float));\n }\n \n buffer = pFilter->combFilterBlock(buffer, iBlockSize, iNumChannels);\n \n for (int m=0; mcombFilterBlock(ppfAudioData, iBlockSize, iNumChannels);\n \n for (int n=0; n 0.001) {\n cout<<\"\\nFIR Impulse Response Test: failed!\\n\";\n return -1;\n }\n \n }\n }\n }\n }\n \n cout<<\"\\nFIR Impulse Response Test: Success!\\n\";\n \n \n \/\/Free memory\n delete pFilter;\n pFilter = 0;\n for (int i=0;icombFilterBlock(ppfAudioData, iBlockSize, iNumChannels);\n \n for (int n=0; n 0.001) {\n cout<<\"\\nIIR Impulse Response Test: failed!\\n\";\n return -1;\n }\n \n }\n }\n }\n }\n \n cout<<\"\\nIIR Impulse Response Test: Success!\\n\";\n \n \n \/\/Free memory\n delete pFilter;\n pFilter = 0;\n for (int i=0;i"} {"text":"#include \"PhysicsManager.hpp\"\n\n#include \n#include \n#include \"..\/Component\/RigidBody.hpp\"\n#include \"..\/Component\/Shape.hpp\"\n#include \"..\/Entity\/Entity.hpp\"\n#include \"..\/Physics\/GlmConversion.hpp\"\n#include \"..\/Physics\/Shape.hpp\"\n#include \"..\/Physics\/Trigger.hpp\"\n#include \"..\/Physics\/TriggerObserver.hpp\"\n#include \"..\/Util\/Json.hpp\"\n\nPhysicsManager::PhysicsManager() {\n \/\/ The broadphase is used to quickly cull bodies that will not collide with\n \/\/ each other, normally by leveraging some simpler (and rough) test such as\n \/\/ bounding boxes.\n broadphase = new btDbvtBroadphase;\n\n \/\/ With the collision configuration one can configure collision detection\n \/\/ algorithms.\n collisionConfiguration = new btDefaultCollisionConfiguration;\n dispatcher = new btCollisionDispatcher(collisionConfiguration);\n\n \/\/ The solver makes objects interact by making use of gravity, collisions,\n \/\/ game logic supplied forces, and constraints.\n solver = new btSequentialImpulseConstraintSolver;\n\n \/\/ The dynamics world encompasses objects included in the simulation.\n dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);\n\n \/\/ Y axis up\n dynamicsWorld->setGravity(btVector3(0, -9.82, 0));\n\n \/\/ Set the lockbox key we will use for lockboxes created in here.\n triggerLockBoxKey.reset(new Utility::LockBox::Key());\n}\n\nPhysicsManager::~PhysicsManager() {\n delete dynamicsWorld;\n delete solver;\n delete dispatcher;\n delete collisionConfiguration;\n delete broadphase;\n\n for (auto t : triggers) {\n delete t;\n }\n}\n\nvoid PhysicsManager::Update(float deltaTime) {\n for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {\n if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) {\n continue;\n }\n\n rigidBodyComp->Position(rigidBodyComp->entity->position);\n dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody());\n dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody());\n rigidBodyComp->GetBulletRigidBody()->setGravity(btVector3(0, 0, 0));\n }\n\n dynamicsWorld->stepSimulation(deltaTime, 10);\n\n for (auto trigger : triggers) {\n trigger->Process(*dynamicsWorld);\n }\n}\n\nvoid PhysicsManager::UpdateEntityTransforms() {\n for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {\n if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled)\n continue;\n\n Entity* entity = rigidBodyComp->entity;\n\n auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform();\n entity->position = Physics::btToGlm(trans.getOrigin());\n entity->SetLocalOrientation(Physics::btToGlm(trans.getRotation()));\n }\n}\n\nvoid PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function callback) {\n auto t = CreateTrigger(trigger);\n \/\/ Add the callback to the trigger observer\n t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {\n trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) {\n observer.OnEnter(callback);\n });\n });\n}\n\nvoid PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function callback) {\n auto t = CreateTrigger(trigger);\n \/\/ Add the callback to the trigger observer\n t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {\n trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {\n observer.OnRetain(callback);\n });\n });\n}\n\nvoid PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function callback) {\n auto t = CreateTrigger(trigger);\n \/\/ Add the callback to the trigger observer\n t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {\n trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {\n observer.OnLeave(callback);\n });\n });\n}\n\nComponent::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) {\n auto comp = rigidBodyComponents.Create();\n comp->entity = owner;\n\n comp->NewBulletRigidBody(1.0f);\n\n auto shapeComp = comp->entity->GetComponent();\n if (shapeComp) {\n comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nComponent::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) {\n auto comp = rigidBodyComponents.Create();\n comp->entity = owner;\n\n auto mass = node.get(\"mass\", 1.0f).asFloat();\n comp->NewBulletRigidBody(mass);\n\n auto shapeComp = comp->entity->GetComponent();\n if (shapeComp) {\n comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nComponent::Shape* PhysicsManager::CreateShape(Entity* owner) {\n auto comp = shapeComponents.Create();\n comp->entity = owner;\n\n auto shape = std::shared_ptr(new Physics::Shape(Physics::Shape::Sphere(1.0f)));\n comp->SetShape(shape);\n\n auto rigidBodyComp = comp->entity->GetComponent();\n if (rigidBodyComp) {\n rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nComponent::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) {\n auto comp = shapeComponents.Create();\n comp->entity = owner;\n\n if (node.isMember(\"sphere\")) {\n auto sphere = node.get(\"sphere\", {});\n auto radius = sphere.get(\"radius\", 1.0f).asFloat();\n auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Sphere(radius)));\n comp->SetShape(shape);\n }\n else if (node.isMember(\"plane\")) {\n auto plane = node.get(\"plane\", {});\n auto normal = Json::LoadVec3(plane.get(\"normal\", {}));\n auto planeCoeff = plane.get(\"planeCoeff\", 0.0f).asFloat();\n auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Plane(normal, planeCoeff)));\n comp->SetShape(shape);\n }\n\n auto rigidBodyComp = comp->entity->GetComponent();\n if (rigidBodyComp) {\n rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nUtility::LockBox PhysicsManager::CreateTrigger(Component::RigidBody* comp) {\n btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position));\n Physics::Trigger* trigger = new Physics::Trigger(trans);\n auto shapeComp = comp->entity->GetComponent();\n trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr);\n triggers.push_back(trigger);\n return Utility::LockBox(triggerLockBoxKey, trigger);\n}\n\nvoid PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) {\n comp->SetShape(shape);\n}\n\nvoid PhysicsManager::SetMass(Component::RigidBody* comp, float mass) {\n \/\/ Setting mass is only valid with a shape because it also sets inertia.\n auto shapeComp = comp->entity->GetComponent();\n if (shapeComp)\n comp->Mass(mass);\n}\n\nconst std::vector& PhysicsManager::GetShapeComponents() const {\n return shapeComponents.GetAll();\n}\n\nvoid PhysicsManager::ClearKilledComponents() {\n rigidBodyComponents.ClearKilled(\n [this](Component::RigidBody* body) {\n dynamicsWorld->removeRigidBody(body->GetBulletRigidBody());\n });\n shapeComponents.ClearKilled();\n}\nRemove braces around single statement for.#include \"PhysicsManager.hpp\"\n\n#include \n#include \n#include \"..\/Component\/RigidBody.hpp\"\n#include \"..\/Component\/Shape.hpp\"\n#include \"..\/Entity\/Entity.hpp\"\n#include \"..\/Physics\/GlmConversion.hpp\"\n#include \"..\/Physics\/Shape.hpp\"\n#include \"..\/Physics\/Trigger.hpp\"\n#include \"..\/Physics\/TriggerObserver.hpp\"\n#include \"..\/Util\/Json.hpp\"\n\nPhysicsManager::PhysicsManager() {\n \/\/ The broadphase is used to quickly cull bodies that will not collide with\n \/\/ each other, normally by leveraging some simpler (and rough) test such as\n \/\/ bounding boxes.\n broadphase = new btDbvtBroadphase;\n\n \/\/ With the collision configuration one can configure collision detection\n \/\/ algorithms.\n collisionConfiguration = new btDefaultCollisionConfiguration;\n dispatcher = new btCollisionDispatcher(collisionConfiguration);\n\n \/\/ The solver makes objects interact by making use of gravity, collisions,\n \/\/ game logic supplied forces, and constraints.\n solver = new btSequentialImpulseConstraintSolver;\n\n \/\/ The dynamics world encompasses objects included in the simulation.\n dynamicsWorld = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);\n\n \/\/ Y axis up\n dynamicsWorld->setGravity(btVector3(0, -9.82, 0));\n\n \/\/ Set the lockbox key we will use for lockboxes created in here.\n triggerLockBoxKey.reset(new Utility::LockBox::Key());\n}\n\nPhysicsManager::~PhysicsManager() {\n delete dynamicsWorld;\n delete solver;\n delete dispatcher;\n delete collisionConfiguration;\n delete broadphase;\n\n for (auto t : triggers)\n delete t;\n}\n\nvoid PhysicsManager::Update(float deltaTime) {\n for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {\n if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled) {\n continue;\n }\n\n rigidBodyComp->Position(rigidBodyComp->entity->position);\n dynamicsWorld->removeRigidBody(rigidBodyComp->GetBulletRigidBody());\n dynamicsWorld->addRigidBody(rigidBodyComp->GetBulletRigidBody());\n rigidBodyComp->GetBulletRigidBody()->setGravity(btVector3(0, 0, 0));\n }\n\n dynamicsWorld->stepSimulation(deltaTime, 10);\n\n for (auto trigger : triggers) {\n trigger->Process(*dynamicsWorld);\n }\n}\n\nvoid PhysicsManager::UpdateEntityTransforms() {\n for (auto rigidBodyComp : rigidBodyComponents.GetAll()) {\n if (rigidBodyComp->IsKilled() || !rigidBodyComp->entity->enabled)\n continue;\n\n Entity* entity = rigidBodyComp->entity;\n\n auto trans = rigidBodyComp->GetBulletRigidBody()->getWorldTransform();\n entity->position = Physics::btToGlm(trans.getOrigin());\n entity->SetLocalOrientation(Physics::btToGlm(trans.getRotation()));\n }\n}\n\nvoid PhysicsManager::OnTriggerEnter(Component::RigidBody* trigger, Component::RigidBody* object, std::function callback) {\n auto t = CreateTrigger(trigger);\n \/\/ Add the callback to the trigger observer\n t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {\n trigger.ForObserver(object->GetBulletRigidBody(), [&callback](Physics::TriggerObserver& observer) {\n observer.OnEnter(callback);\n });\n });\n}\n\nvoid PhysicsManager::OnTriggerRetain(Component::RigidBody* trigger, Component::RigidBody* object, std::function callback) {\n auto t = CreateTrigger(trigger);\n \/\/ Add the callback to the trigger observer\n t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {\n trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {\n observer.OnRetain(callback);\n });\n });\n}\n\nvoid PhysicsManager::OnTriggerLeave(Component::RigidBody* trigger, Component::RigidBody* object, std::function callback) {\n auto t = CreateTrigger(trigger);\n \/\/ Add the callback to the trigger observer\n t.Open(triggerLockBoxKey, [object, &callback](Physics::Trigger& trigger) {\n trigger.ForObserver(object->GetBulletRigidBody(), [&callback](::Physics::TriggerObserver& observer) {\n observer.OnLeave(callback);\n });\n });\n}\n\nComponent::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner) {\n auto comp = rigidBodyComponents.Create();\n comp->entity = owner;\n\n comp->NewBulletRigidBody(1.0f);\n\n auto shapeComp = comp->entity->GetComponent();\n if (shapeComp) {\n comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nComponent::RigidBody* PhysicsManager::CreateRigidBody(Entity* owner, const Json::Value& node) {\n auto comp = rigidBodyComponents.Create();\n comp->entity = owner;\n\n auto mass = node.get(\"mass\", 1.0f).asFloat();\n comp->NewBulletRigidBody(mass);\n\n auto shapeComp = comp->entity->GetComponent();\n if (shapeComp) {\n comp->GetBulletRigidBody()->setCollisionShape(shapeComp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nComponent::Shape* PhysicsManager::CreateShape(Entity* owner) {\n auto comp = shapeComponents.Create();\n comp->entity = owner;\n\n auto shape = std::shared_ptr(new Physics::Shape(Physics::Shape::Sphere(1.0f)));\n comp->SetShape(shape);\n\n auto rigidBodyComp = comp->entity->GetComponent();\n if (rigidBodyComp) {\n rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nComponent::Shape* PhysicsManager::CreateShape(Entity* owner, const Json::Value& node) {\n auto comp = shapeComponents.Create();\n comp->entity = owner;\n\n if (node.isMember(\"sphere\")) {\n auto sphere = node.get(\"sphere\", {});\n auto radius = sphere.get(\"radius\", 1.0f).asFloat();\n auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Sphere(radius)));\n comp->SetShape(shape);\n }\n else if (node.isMember(\"plane\")) {\n auto plane = node.get(\"plane\", {});\n auto normal = Json::LoadVec3(plane.get(\"normal\", {}));\n auto planeCoeff = plane.get(\"planeCoeff\", 0.0f).asFloat();\n auto shape = std::shared_ptr<::Physics::Shape>(new ::Physics::Shape(::Physics::Shape::Plane(normal, planeCoeff)));\n comp->SetShape(shape);\n }\n\n auto rigidBodyComp = comp->entity->GetComponent();\n if (rigidBodyComp) {\n rigidBodyComp->GetBulletRigidBody()->setCollisionShape(comp->GetShape()->GetShape());\n }\n\n return comp;\n}\n\nUtility::LockBox PhysicsManager::CreateTrigger(Component::RigidBody* comp) {\n btTransform trans(btQuaternion(0, 0, 0, 1), ::Physics::glmToBt(comp->entity->position));\n Physics::Trigger* trigger = new Physics::Trigger(trans);\n auto shapeComp = comp->entity->GetComponent();\n trigger->SetCollisionShape(shapeComp ? shapeComp->GetShape() : nullptr);\n triggers.push_back(trigger);\n return Utility::LockBox(triggerLockBoxKey, trigger);\n}\n\nvoid PhysicsManager::SetShape(Component::Shape* comp, std::shared_ptr<::Physics::Shape> shape) {\n comp->SetShape(shape);\n}\n\nvoid PhysicsManager::SetMass(Component::RigidBody* comp, float mass) {\n \/\/ Setting mass is only valid with a shape because it also sets inertia.\n auto shapeComp = comp->entity->GetComponent();\n if (shapeComp)\n comp->Mass(mass);\n}\n\nconst std::vector& PhysicsManager::GetShapeComponents() const {\n return shapeComponents.GetAll();\n}\n\nvoid PhysicsManager::ClearKilledComponents() {\n rigidBodyComponents.ClearKilled(\n [this](Component::RigidBody* body) {\n dynamicsWorld->removeRigidBody(body->GetBulletRigidBody());\n });\n shapeComponents.ClearKilled();\n}\n<|endoftext|>"} {"text":"\nusing namespace std;\n#include \"GEOMImpl_ShapeDriver.hxx\"\n#include \"GEOMImpl_IShapes.hxx\"\n#include \"GEOMImpl_IShapesOperations.hxx\"\n#include \"GEOMImpl_Types.hxx\"\n#include \"GEOM_Function.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/=======================================================================\n\/\/function : GetID\n\/\/purpose :\n\/\/=======================================================================\nconst Standard_GUID& GEOMImpl_ShapeDriver::GetID()\n{\n static Standard_GUID aShapeDriver(\"FF1BBB54-5D14-4df2-980B-3A668264EA16\");\n return aShapeDriver;\n}\n\n\n\/\/=======================================================================\n\/\/function : GEOMImpl_ShapeDriver\n\/\/purpose :\n\/\/=======================================================================\nGEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()\n{\n}\n\n\/\/=======================================================================\n\/\/function : Execute\n\/\/purpose :\n\/\/=======================================================================\nStandard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const\n{\n if (Label().IsNull()) return 0;\n Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());\n\n GEOMImpl_IShapes aCI (aFunction);\n Standard_Integer aType = aFunction->GetType();\n\n TopoDS_Shape aShape;\n BRep_Builder B;\n\n if (aType == WIRE_EDGES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n\n \/\/ add edges\n BRepBuilderAPI_MakeWire MW;\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Shape for wire construction is null\");\n }\n if (aShape_i.ShapeType() == TopAbs_EDGE)\n\tMW.Add(TopoDS::Edge(aShape_i));\n else if (aShape_i.ShapeType() == TopAbs_WIRE)\n\tMW.Add(TopoDS::Wire(aShape_i));\n else\n Standard_TypeMismatch::Raise\n (\"Shape for wire construction is neither an edge nor a wire\");\n }\n\n if (!MW.IsDone()) {\n Standard_ConstructionError::Raise(\"Wire construction failed\");\n }\n aShape = MW;\n\n } else if (aType == FACE_WIRE) {\n Handle(GEOM_Function) aRefBase = aCI.GetBase();\n TopoDS_Shape aShapeBase = aRefBase->GetValue();\n if (aShapeBase.IsNull() || aShapeBase.ShapeType() != TopAbs_WIRE) {\n Standard_NullObject::Raise\n (\"Shape for face construction is null or not a wire\");\n }\n TopoDS_Wire W = TopoDS::Wire(aShapeBase);\n BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());\n if (!MF.IsDone()) {\n Standard_ConstructionError::Raise(\"Face construction failed\");\n }\n aShape = MF.Shape();\n\n } else if (aType == FACE_WIRES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n\n \/\/ first wire\n Handle(GEOM_Function) aRefWire = Handle(GEOM_Function)::DownCast(aShapes->Value(1));\n TopoDS_Shape aWire = aRefWire->GetValue();\n if (aWire.IsNull() || aWire.ShapeType() != TopAbs_WIRE) {\n Standard_NullObject::Raise(\"Shape for face construction is null or not a wire\");\n }\n TopoDS_Wire W = TopoDS::Wire(aWire);\n\n \/\/ basic face\n BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());\n if (!MF.IsDone()) {\n Standard_ConstructionError::Raise(\"Face construction failed\");\n }\n TopoDS_Shape FFace = MF.Shape();\n if (!FFace.IsNull()) {\n unsigned int ind, nbshapes = aShapes->Length();\n if (nbshapes == 1) {\n\taShape = FFace;\n\n } else if (nbshapes >= 2) {\n\tTopoDS_Compound C;\n\tBRep_Builder aBuilder;\n\taBuilder.MakeCompound(C);\n\tBRepAlgo_FaceRestrictor FR;\n\n\tTopAbs_Orientation OriF = FFace.Orientation();\n\tTopoDS_Shape aLocalS = FFace.Oriented(TopAbs_FORWARD);\n\tFR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);\n\n\tfor (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefWire_i =\n Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aWire_i = aRefWire_i->GetValue();\n if (aWire_i.IsNull() || aWire_i.ShapeType() != TopAbs_WIRE) {\n Standard_NullObject::Raise(\"Shape for face construction is null or not a wire\");\n }\n\n\t FR.Add(TopoDS::Wire(aWire_i));\n\t}\n\n\tFR.Perform();\n\n\tif (FR.IsDone()) {\n\t int k = 0;\n\t TopoDS_Shape aFace;\n\t for (; FR.More(); FR.Next()) {\n\t aFace = FR.Current().Oriented(OriF);\n\t aBuilder.Add(C, aFace);\n\t k++;\n\t }\n\t if (k == 1) {\n\t aShape = aFace;\n\t } else {\n\t aShape = C;\n\t }\n\t}\n }\n }\n } else if (aType == SHELL_FACES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n\n \/\/ add faces\n BRepAlgo_Sewing aSewing(Precision::Confusion()*10.0);\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Face for shell construction is null\");\n }\n aSewing.Add(aShape_i);\n }\n\n aSewing.Perform();\n\n TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);\n Standard_Integer ish = 0;\n for (; exp.More(); exp.Next()) {\n aShape = exp.Current();\n ish++;\n }\n\n if (ish != 1)\n aShape = aSewing.SewedShape();\n\n } else if (aType == SOLID_SHELL) {\n Handle(GEOM_Function) aRefShell = aCI.GetBase();\n TopoDS_Shape aShapeShell = aRefShell->GetValue();\n if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {\n Standard_NullObject::Raise(\"Shape for solid construction is null or not a shell\");\n }\n\n BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));\n if(chkShell.Closed() == BRepCheck_NotClosed) return 0;\n\n TopoDS_Solid Sol;\n B.MakeSolid(Sol);\n B.Add(Sol, aShapeShell);\n BRepClass3d_SolidClassifier SC (Sol);\n SC.PerformInfinitePoint(Precision::Confusion());\n if (SC.State() == TopAbs_IN) {\n B.MakeSolid(Sol);\n B.Add(Sol, aShapeShell.Reversed());\n }\n\n aShape = Sol;\n\n } else if (aType == SOLID_SHELLS) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n Standard_Integer ish = 0;\n TopoDS_Solid Sol;\n TopoDS_Compound Res;\n B.MakeCompound(Res);\n\n \/\/ add shapes\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShapeShell = aRefShape->GetValue();\n if (aShapeShell.IsNull()) {\n Standard_NullObject::Raise(\"Shell for solid construction is null\");\n }\n if (aShapeShell.ShapeType() == TopAbs_SHELL) {\n B.MakeSolid(Sol);\n B.Add(Sol, aShapeShell);\n BRepClass3d_SolidClassifier SC (Sol);\n SC.PerformInfinitePoint(Precision::Confusion());\n if (SC.State() == TopAbs_IN) {\n B.MakeSolid(Sol);\n B.Add(Sol, aShapeShell.Reversed());\n }\n B.Add(Res, Sol);\n ish++;\n }\n }\n if (ish == 1) aShape = Sol;\n else aShape = Res;\n\n } else if (aType == COMPOUND_SHAPES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n\n \/\/ add shapes\n TopoDS_Compound C;\n B.MakeCompound(C);\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Shape for compound construction is null\");\n }\n B.Add(C, aShape_i);\n }\n\n aShape = C;\n\n } else if (aType == REVERSE_ORIENTATION) {\n Handle(GEOM_Function) aRefShape = aCI.GetBase();\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Shape for reverse is null\");\n }\n \n BRepBuilderAPI_Copy Copy(aShape_i);\n if( Copy.IsDone() ) {\n TopoDS_Shape tds = Copy.Shape();\n if( tds.IsNull() ) {\n\tStandard_ConstructionError::Raise(\"Orientation aborted : Can not reverse the shape\");\n }\n\n if( tds.Orientation() == TopAbs_FORWARD)\n\ttds.Orientation(TopAbs_REVERSED) ;\n else\n\ttds.Orientation(TopAbs_FORWARD) ;\n\n aShape = tds;\n } \n }\n\n if (aShape.IsNull()) return 0;\n\n \/\/ Check shape validity\n BRepCheck_Analyzer ana (aShape, false);\n if (!ana.IsValid()) {\n Standard_ConstructionError::Raise(\"Algorithm have produced an invalid shape result\");\n }\n\n aFunction->SetValue(aShape);\n\n log.SetTouched(Label());\n\n return 1;\n}\n\n\n\/\/=======================================================================\n\/\/function : GEOMImpl_ShapeDriver_Type_\n\/\/purpose :\n\/\/=======================================================================\nStandard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()\n{\n\n static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);\n if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);\n static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);\n if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);\n static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);\n if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);\n\n\n static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};\n static Handle_Standard_Type _aType = new Standard_Type(\"GEOMImpl_ShapeDriver\",\n\t\t\t sizeof(GEOMImpl_ShapeDriver),\n\t\t\t 1,\n\t\t\t (Standard_Address)_Ancestors,\n\t\t\t (Standard_Address)NULL);\n\n return _aType;\n}\n\n\/\/=======================================================================\n\/\/function : DownCast\n\/\/purpose :\n\/\/=======================================================================\nconst Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)\n{\n Handle(GEOMImpl_ShapeDriver) _anOtherObject;\n\n if (!AnObject.IsNull()) {\n if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {\n _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);\n }\n }\n\n return _anOtherObject ;\n}\nPAL9074. Now MakeSolidShells() makes one solid of all given shells like OCC MakeSolid() does\nusing namespace std;\n#include \"GEOMImpl_ShapeDriver.hxx\"\n#include \"GEOMImpl_IShapes.hxx\"\n#include \"GEOMImpl_IShapesOperations.hxx\"\n#include \"GEOMImpl_Types.hxx\"\n#include \"GEOM_Function.hxx\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n\n\/\/=======================================================================\n\/\/function : GetID\n\/\/purpose :\n\/\/=======================================================================\nconst Standard_GUID& GEOMImpl_ShapeDriver::GetID()\n{\n static Standard_GUID aShapeDriver(\"FF1BBB54-5D14-4df2-980B-3A668264EA16\");\n return aShapeDriver;\n}\n\n\n\/\/=======================================================================\n\/\/function : GEOMImpl_ShapeDriver\n\/\/purpose :\n\/\/=======================================================================\nGEOMImpl_ShapeDriver::GEOMImpl_ShapeDriver()\n{\n}\n\n\/\/=======================================================================\n\/\/function : Execute\n\/\/purpose :\n\/\/=======================================================================\nStandard_Integer GEOMImpl_ShapeDriver::Execute(TFunction_Logbook& log) const\n{\n if (Label().IsNull()) return 0;\n Handle(GEOM_Function) aFunction = GEOM_Function::GetFunction(Label());\n\n GEOMImpl_IShapes aCI (aFunction);\n Standard_Integer aType = aFunction->GetType();\n\n TopoDS_Shape aShape;\n BRep_Builder B;\n\n if (aType == WIRE_EDGES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n\n \/\/ add edges\n BRepBuilderAPI_MakeWire MW;\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Shape for wire construction is null\");\n }\n if (aShape_i.ShapeType() == TopAbs_EDGE)\n\tMW.Add(TopoDS::Edge(aShape_i));\n else if (aShape_i.ShapeType() == TopAbs_WIRE)\n\tMW.Add(TopoDS::Wire(aShape_i));\n else\n Standard_TypeMismatch::Raise\n (\"Shape for wire construction is neither an edge nor a wire\");\n }\n\n if (!MW.IsDone()) {\n Standard_ConstructionError::Raise(\"Wire construction failed\");\n }\n aShape = MW;\n\n } else if (aType == FACE_WIRE) {\n Handle(GEOM_Function) aRefBase = aCI.GetBase();\n TopoDS_Shape aShapeBase = aRefBase->GetValue();\n if (aShapeBase.IsNull() || aShapeBase.ShapeType() != TopAbs_WIRE) {\n Standard_NullObject::Raise\n (\"Shape for face construction is null or not a wire\");\n }\n TopoDS_Wire W = TopoDS::Wire(aShapeBase);\n BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());\n if (!MF.IsDone()) {\n Standard_ConstructionError::Raise(\"Face construction failed\");\n }\n aShape = MF.Shape();\n\n } else if (aType == FACE_WIRES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n\n \/\/ first wire\n Handle(GEOM_Function) aRefWire = Handle(GEOM_Function)::DownCast(aShapes->Value(1));\n TopoDS_Shape aWire = aRefWire->GetValue();\n if (aWire.IsNull() || aWire.ShapeType() != TopAbs_WIRE) {\n Standard_NullObject::Raise(\"Shape for face construction is null or not a wire\");\n }\n TopoDS_Wire W = TopoDS::Wire(aWire);\n\n \/\/ basic face\n BRepBuilderAPI_MakeFace MF (W, aCI.GetIsPlanar());\n if (!MF.IsDone()) {\n Standard_ConstructionError::Raise(\"Face construction failed\");\n }\n TopoDS_Shape FFace = MF.Shape();\n if (!FFace.IsNull()) {\n unsigned int ind, nbshapes = aShapes->Length();\n if (nbshapes == 1) {\n\taShape = FFace;\n\n } else if (nbshapes >= 2) {\n\tTopoDS_Compound C;\n\tBRep_Builder aBuilder;\n\taBuilder.MakeCompound(C);\n\tBRepAlgo_FaceRestrictor FR;\n\n\tTopAbs_Orientation OriF = FFace.Orientation();\n\tTopoDS_Shape aLocalS = FFace.Oriented(TopAbs_FORWARD);\n\tFR.Init(TopoDS::Face(aLocalS), Standard_False, Standard_True);\n\n\tfor (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefWire_i =\n Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aWire_i = aRefWire_i->GetValue();\n if (aWire_i.IsNull() || aWire_i.ShapeType() != TopAbs_WIRE) {\n Standard_NullObject::Raise(\"Shape for face construction is null or not a wire\");\n }\n\n\t FR.Add(TopoDS::Wire(aWire_i));\n\t}\n\n\tFR.Perform();\n\n\tif (FR.IsDone()) {\n\t int k = 0;\n\t TopoDS_Shape aFace;\n\t for (; FR.More(); FR.Next()) {\n\t aFace = FR.Current().Oriented(OriF);\n\t aBuilder.Add(C, aFace);\n\t k++;\n\t }\n\t if (k == 1) {\n\t aShape = aFace;\n\t } else {\n\t aShape = C;\n\t }\n\t}\n }\n }\n } else if (aType == SHELL_FACES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n\n \/\/ add faces\n BRepAlgo_Sewing aSewing(Precision::Confusion()*10.0);\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Face for shell construction is null\");\n }\n aSewing.Add(aShape_i);\n }\n\n aSewing.Perform();\n\n TopExp_Explorer exp (aSewing.SewedShape(), TopAbs_SHELL);\n Standard_Integer ish = 0;\n for (; exp.More(); exp.Next()) {\n aShape = exp.Current();\n ish++;\n }\n\n if (ish != 1)\n aShape = aSewing.SewedShape();\n\n } else if (aType == SOLID_SHELL) {\n Handle(GEOM_Function) aRefShell = aCI.GetBase();\n TopoDS_Shape aShapeShell = aRefShell->GetValue();\n if (aShapeShell.IsNull() || aShapeShell.ShapeType() != TopAbs_SHELL) {\n Standard_NullObject::Raise(\"Shape for solid construction is null or not a shell\");\n }\n\n BRepCheck_Shell chkShell(TopoDS::Shell(aShapeShell));\n if(chkShell.Closed() == BRepCheck_NotClosed) return 0;\n\n TopoDS_Solid Sol;\n B.MakeSolid(Sol);\n B.Add(Sol, aShapeShell);\n BRepClass3d_SolidClassifier SC (Sol);\n SC.PerformInfinitePoint(Precision::Confusion());\n if (SC.State() == TopAbs_IN) {\n B.MakeSolid(Sol);\n B.Add(Sol, aShapeShell.Reversed());\n }\n\n aShape = Sol;\n\n } else if (aType == SOLID_SHELLS) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n Standard_Integer ish = 0;\n TopoDS_Solid Sol;\n B.MakeSolid(Sol);\n\n \/\/ add shapes\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShapeShell = aRefShape->GetValue();\n if (aShapeShell.IsNull()) {\n Standard_NullObject::Raise(\"Shell for solid construction is null\");\n }\n if (aShapeShell.ShapeType() == TopAbs_SHELL) {\n B.Add(Sol, aShapeShell);\n ish++;\n }\n }\n if ( ish == 0 ) return 0;\n BRepClass3d_SolidClassifier SC (Sol);\n SC.PerformInfinitePoint(Precision::Confusion());\n switch (SC.State()) {\n case TopAbs_IN:\n aShape = Sol.Reversed(); break;\n case TopAbs_OUT:\n aShape = Sol; break;\n default: \/\/ not closed shell?\n return 0;\n }\n\n } else if (aType == COMPOUND_SHAPES) {\n Handle(TColStd_HSequenceOfTransient) aShapes = aCI.GetShapes();\n unsigned int ind, nbshapes = aShapes->Length();\n\n \/\/ add shapes\n TopoDS_Compound C;\n B.MakeCompound(C);\n for (ind = 1; ind <= nbshapes; ind++) {\n Handle(GEOM_Function) aRefShape = Handle(GEOM_Function)::DownCast(aShapes->Value(ind));\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Shape for compound construction is null\");\n }\n B.Add(C, aShape_i);\n }\n\n aShape = C;\n\n } else if (aType == REVERSE_ORIENTATION) {\n Handle(GEOM_Function) aRefShape = aCI.GetBase();\n TopoDS_Shape aShape_i = aRefShape->GetValue();\n if (aShape_i.IsNull()) {\n Standard_NullObject::Raise(\"Shape for reverse is null\");\n }\n \n BRepBuilderAPI_Copy Copy(aShape_i);\n if( Copy.IsDone() ) {\n TopoDS_Shape tds = Copy.Shape();\n if( tds.IsNull() ) {\n\tStandard_ConstructionError::Raise(\"Orientation aborted : Can not reverse the shape\");\n }\n\n if( tds.Orientation() == TopAbs_FORWARD)\n\ttds.Orientation(TopAbs_REVERSED) ;\n else\n\ttds.Orientation(TopAbs_FORWARD) ;\n\n aShape = tds;\n } \n }\n\n if (aShape.IsNull()) return 0;\n\n \/\/ Check shape validity\n BRepCheck_Analyzer ana (aShape, false);\n if (!ana.IsValid()) {\n Standard_ConstructionError::Raise(\"Algorithm have produced an invalid shape result\");\n }\n\n aFunction->SetValue(aShape);\n\n log.SetTouched(Label());\n\n return 1;\n}\n\n\n\/\/=======================================================================\n\/\/function : GEOMImpl_ShapeDriver_Type_\n\/\/purpose :\n\/\/=======================================================================\nStandard_EXPORT Handle_Standard_Type& GEOMImpl_ShapeDriver_Type_()\n{\n\n static Handle_Standard_Type aType1 = STANDARD_TYPE(TFunction_Driver);\n if ( aType1.IsNull()) aType1 = STANDARD_TYPE(TFunction_Driver);\n static Handle_Standard_Type aType2 = STANDARD_TYPE(MMgt_TShared);\n if ( aType2.IsNull()) aType2 = STANDARD_TYPE(MMgt_TShared);\n static Handle_Standard_Type aType3 = STANDARD_TYPE(Standard_Transient);\n if ( aType3.IsNull()) aType3 = STANDARD_TYPE(Standard_Transient);\n\n\n static Handle_Standard_Transient _Ancestors[]= {aType1,aType2,aType3,NULL};\n static Handle_Standard_Type _aType = new Standard_Type(\"GEOMImpl_ShapeDriver\",\n\t\t\t sizeof(GEOMImpl_ShapeDriver),\n\t\t\t 1,\n\t\t\t (Standard_Address)_Ancestors,\n\t\t\t (Standard_Address)NULL);\n\n return _aType;\n}\n\n\/\/=======================================================================\n\/\/function : DownCast\n\/\/purpose :\n\/\/=======================================================================\nconst Handle(GEOMImpl_ShapeDriver) Handle(GEOMImpl_ShapeDriver)::DownCast(const Handle(Standard_Transient)& AnObject)\n{\n Handle(GEOMImpl_ShapeDriver) _anOtherObject;\n\n if (!AnObject.IsNull()) {\n if (AnObject->IsKind(STANDARD_TYPE(GEOMImpl_ShapeDriver))) {\n _anOtherObject = Handle(GEOMImpl_ShapeDriver)((Handle(GEOMImpl_ShapeDriver)&)AnObject);\n }\n }\n\n return _anOtherObject ;\n}\n<|endoftext|>"} {"text":"Sketcher: Ellipse trim, handle multiple intersection<|endoftext|>"} {"text":"\/*\n * NotebookAlternateEngines.cpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n#include \"SessionRmdNotebook.hpp\"\n#include \"SessionExecuteChunkOperation.hpp\"\n#include \"NotebookCache.hpp\"\n#include \"NotebookAlternateEngines.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace notebook {\n\nnamespace {\n\nclass ChunkExecCompletedScope : boost::noncopyable\n{\npublic:\n ChunkExecCompletedScope(const std::string& docId,\n const std::string& chunkId)\n : docId_(docId), chunkId_(chunkId)\n {\n }\n \n ~ChunkExecCompletedScope()\n {\n events().onChunkExecCompleted(\n docId_,\n chunkId_,\n notebookCtxId());\n }\n \nprivate:\n std::string docId_;\n std::string chunkId_;\n};\n\nError prepareCacheConsoleOutputFile(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n FilePath* pChunkOutputFile)\n{\n \/\/ forward declare error\n Error error;\n \n \/\/ prepare chunk directory\n FilePath cachePath = notebook::chunkOutputPath(\n docId,\n chunkId,\n notebook::ContextExact);\n \n error = cachePath.resetDirectory();\n if (error)\n return error;\n \n \/\/ prepare cache console output file\n *pChunkOutputFile =\n notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputText);\n \n return Success();\n}\n\nvoid chunkConsoleOutputHandler(module_context::ConsoleOutputType type,\n const std::string& output,\n const FilePath& targetPath)\n{\n using namespace module_context;\n \n Error error = appendConsoleOutput(\n type == ConsoleOutputNormal ? kChunkConsoleOutput : kChunkConsoleError,\n output,\n targetPath);\n if (error)\n LOG_ERROR(error);\n}\n\nvoid reportChunkExecutionError(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& message,\n const FilePath& targetPath)\n{\n \/\/ emit chunk error\n chunkConsoleOutputHandler(\n module_context::ConsoleOutputError,\n message,\n targetPath);\n \n \/\/ forward failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n nbCtxId,\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n targetPath);\n}\n\nError executeRcppEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& code,\n const std::map& options)\n{\n \/\/ forward declare error\n Error error;\n \n \/\/ always ensure we emit a 'execution complete' event on exit\n ChunkExecCompletedScope execScope(docId, chunkId);\n \n \/\/ prepare cache output file (use tempfile on failure)\n FilePath targetPath = module_context::tempFile(\"rcpp-cache\", \"\");\n error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ capture console output, error\n boost::signals::scoped_connection consoleHandler =\n module_context::events().onConsoleOutput.connect(\n boost::bind(chunkConsoleOutputHandler,\n _1,\n _2,\n targetPath));\n\n \/\/ call Rcpp::sourceCpp on code\n std::string escaped = boost::regex_replace(\n code,\n boost::regex(\"(\\\\\\\\|\\\")\"),\n \"\\\\\\\\$1\");\n \n std::string execCode =\n \"Rcpp::sourceCpp(code = \\\"\" + escaped + \"\\\")\";\n \n \/\/ write input code to cache\n error = appendConsoleOutput(\n kChunkConsoleInput,\n code,\n targetPath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ execute code (output captured on success; on failure we\n \/\/ explicitly forward the error message returned)\n error = r::exec::executeString(execCode);\n if (error)\n {\n chunkConsoleOutputHandler(module_context::ConsoleOutputError,\n r::endUserErrorMessage(error),\n targetPath);\n }\n\n \/\/ forward success \/ failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n nbCtxId,\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n targetPath);\n \n return error;\n}\n\nvoid reportStanExecutionError(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const FilePath& targetPath)\n{\n std::string message =\n \"engine.opts$output.var must be a character string providing a \"\n \"name for the returned `stanmodel` object\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath);\n}\n\n\nError executeStanEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& code,\n const std::map& options)\n{\n \/\/ forward-declare error\n Error error;\n \n \/\/ ensure we always emit an execution complete event on exit\n ChunkExecCompletedScope execScope(docId, chunkId);\n \n \/\/ prepare console output file -- use tempfile on failure\n FilePath targetPath = module_context::tempFile(\"stan-cache-\", \"\");\n error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ capture console output, error\n boost::signals::scoped_connection consoleHandler =\n module_context::events().onConsoleOutput.connect(\n boost::bind(chunkConsoleOutputHandler,\n _1,\n _2,\n targetPath)); \n \n \/\/ write code to file\n FilePath tempFile = module_context::tempFile(\"stan-\", \".stan\");\n error = writeStringToFile(tempFile, code);\n if (error)\n {\n reportChunkExecutionError(\n docId,\n chunkId,\n nbCtxId,\n r::endUserErrorMessage(error),\n targetPath);\n LOG_ERROR(error);\n return Success();\n }\n RemoveOnExitScope removeOnExitScope(tempFile, ERROR_LOCATION);\n \n \/\/ ensure existence of 'engine.opts' with 'output.var' parameter\n \/\/ ('x' also allowed for backwards compatibility)\n if (!options.count(\"engine.opts\"))\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n \n \/\/ evaluate engine options (so we can pass them through to stan call)\n r::sexp::Protect protect;\n SEXP engineOptsSEXP = R_NilValue;\n error = r::exec::evaluateString(\n options.at(\"engine.opts\"),\n &engineOptsSEXP,\n &protect);\n \n if (error)\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n \n \/\/ construct call to 'stan_model'\n r::exec::RFunction fStanEngine(\"rstan:::stan_model\");\n std::vector engineOptsNames;\n error = r::sexp::getNames(engineOptsSEXP, &engineOptsNames);\n if (error)\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n \n \/\/ build parameters\n std::string modelName;\n for (std::size_t i = 0, n = r::sexp::length(engineOptsSEXP); i < n; ++i)\n {\n \/\/ skip 'output.var' engine option (this is the variable we wish to assign to\n \/\/ after evaluating the stan model)\n if (engineOptsNames[i] == \"output.var\" || engineOptsNames[i] == \"x\")\n {\n modelName = r::sexp::asString(VECTOR_ELT(engineOptsSEXP, i));\n continue;\n }\n \n fStanEngine.addParam(\n engineOptsNames[i],\n VECTOR_ELT(engineOptsSEXP, i));\n }\n \n \/\/ if no model name was set, return error message\n if (modelName.empty())\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n \n \/\/ if the 'file' option was not set, set it explicitly\n if (!core::algorithm::contains(engineOptsNames, \"file\"))\n fStanEngine.addParam(\"file\", string_utils::utf8ToSystem(tempFile.absolutePath()));\n \n \/\/ evaluate stan_model call\n SEXP stanModelSEXP = R_NilValue;\n error = fStanEngine.call(&stanModelSEXP, &protect);\n if (error)\n {\n std::string msg = r::endUserErrorMessage(error);\n reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);\n return Success();\n }\n \n \/\/ assign in global env on success\n if (stanModelSEXP != R_NilValue)\n {\n r::exec::RFunction assign(\"base:::assign\");\n assign.addParam(\"x\", modelName);\n assign.addParam(\"value\", stanModelSEXP);\n error = assign.call();\n if (error)\n {\n std::string msg = r::endUserErrorMessage(error);\n reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);\n LOG_ERROR(error);\n return Success();\n }\n }\n \n \/\/ forward success \/ failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n notebookCtxId(),\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n targetPath);\n \n return Success();\n}\n\nError executeSqlEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& code,\n const json::Object& options)\n{\n Error error;\n \n \/\/ ensure we always emit an execution complete event on exit\n ChunkExecCompletedScope execScope(docId, chunkId);\n\n \/\/ prepare console output file -- use tempfile on failure\n FilePath consolePath = module_context::tempFile(\"data-console-\", \"\");\n error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &consolePath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ capture console output, error\n boost::signals::scoped_connection consoleHandler =\n module_context::events().onConsoleOutput.connect(\n boost::bind(chunkConsoleOutputHandler,\n _1,\n _2,\n consolePath)); \n\n FilePath parentPath = notebook::chunkOutputPath(\n docId, chunkId, nbCtxId, ContextSaved);\n error = parentPath.ensureDirectory();\n if (error)\n {\n std::string message = \"Failed to create SQL chunk directory\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, parentPath);\n \n return Success();\n }\n \n FilePath dataPath =\n notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputData);\n\n \/\/ check package dependencies\n if (!module_context::isPackageVersionInstalled(\"DBI\", \"0.4\"))\n {\n std::string message = \"Executing SQL chunks requires version 0.4 or \"\n \"later of the DBI package\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);\n return Success();\n }\n\n \/\/ run sql and save result\n error = r::exec::RFunction(\n \".rs.runSqlForDataCapture\",\n code,\n string_utils::utf8ToSystem(dataPath.absolutePath()),\n options).call();\n if (error)\n {\n std::string message = \"Failed to execute SQL chunk\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);\n\n return Success();\n }\n\n if (dataPath.exists()) {\n \/\/ forward success \/ failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n notebookCtxId(),\n 0, \/\/ no ordinal needed\n ChunkOutputData,\n dataPath);\n }\n\n \/\/ forward console output\n enqueueChunkOutput(\n docId,\n chunkId,\n notebookCtxId(),\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n consolePath);\n\n return Success();\n}\n\nError interruptEngineChunk(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string docId, chunkId;\n Error error = json::readParams(request.params,\n &docId,\n &chunkId);\n if (error)\n {\n LOG_ERROR(error);\n return error;\n }\n \n interruptChunk(docId, chunkId);\n return Success();\n}\n\n} \/\/ anonymous namespace\n\nError executeAlternateEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& engine,\n const std::string& code,\n const json::Object& jsonChunkOptions)\n{\n \/\/ read json chunk options\n std::map options;\n for (json::Object::const_iterator it = jsonChunkOptions.begin();\n it != jsonChunkOptions.end();\n ++it)\n {\n if (it->second.type() == json::StringType)\n options[it->first] = it->second.get_str();\n }\n \n \/\/ handle some engines with their own custom routines\n if (engine == \"Rcpp\")\n return executeRcppEngineChunk(docId, chunkId, nbCtxId, code, options);\n else if (engine == \"stan\")\n return executeStanEngineChunk(docId, chunkId, nbCtxId, code, options);\n else if (engine == \"sql\")\n return executeSqlEngineChunk(docId, chunkId, nbCtxId, code, jsonChunkOptions);\n\n runChunk(docId, chunkId, nbCtxId, engine, code, options);\n return Success();\n}\n\nError initAlternateEngines()\n{\n using namespace module_context;\n\n ExecBlock initBlock;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"interrupt_chunk\", interruptEngineChunk));\n return initBlock.execute();\n}\n\n} \/\/ namespace notebook\n} \/\/ namespace rmarkdown\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n\n\nrespect use of 'output.var' in chunk header\/*\n * NotebookAlternateEngines.cpp\n *\n * Copyright (C) 2009-16 by RStudio, Inc.\n *\n * Unless you have received this program directly from RStudio pursuant\n * to the terms of a commercial license agreement with RStudio, then\n * this program is licensed to you under the terms of version 3 of the\n * GNU Affero General Public License. This program is distributed WITHOUT\n * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,\n * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the\n * AGPL (http:\/\/www.gnu.org\/licenses\/agpl-3.0.txt) for more details.\n *\n *\/\n\n\n#include \"SessionRmdNotebook.hpp\"\n#include \"SessionExecuteChunkOperation.hpp\"\n#include \"NotebookCache.hpp\"\n#include \"NotebookAlternateEngines.hpp\"\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n\nusing namespace rstudio::core;\n\nnamespace rstudio {\nnamespace session {\nnamespace modules {\nnamespace rmarkdown {\nnamespace notebook {\n\nnamespace {\n\nclass ChunkExecCompletedScope : boost::noncopyable\n{\npublic:\n ChunkExecCompletedScope(const std::string& docId,\n const std::string& chunkId)\n : docId_(docId), chunkId_(chunkId)\n {\n }\n \n ~ChunkExecCompletedScope()\n {\n events().onChunkExecCompleted(\n docId_,\n chunkId_,\n notebookCtxId());\n }\n \nprivate:\n std::string docId_;\n std::string chunkId_;\n};\n\nError prepareCacheConsoleOutputFile(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n FilePath* pChunkOutputFile)\n{\n \/\/ forward declare error\n Error error;\n \n \/\/ prepare chunk directory\n FilePath cachePath = notebook::chunkOutputPath(\n docId,\n chunkId,\n notebook::ContextExact);\n \n error = cachePath.resetDirectory();\n if (error)\n return error;\n \n \/\/ prepare cache console output file\n *pChunkOutputFile =\n notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputText);\n \n return Success();\n}\n\nvoid chunkConsoleOutputHandler(module_context::ConsoleOutputType type,\n const std::string& output,\n const FilePath& targetPath)\n{\n using namespace module_context;\n \n Error error = appendConsoleOutput(\n type == ConsoleOutputNormal ? kChunkConsoleOutput : kChunkConsoleError,\n output,\n targetPath);\n if (error)\n LOG_ERROR(error);\n}\n\nvoid reportChunkExecutionError(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& message,\n const FilePath& targetPath)\n{\n \/\/ emit chunk error\n chunkConsoleOutputHandler(\n module_context::ConsoleOutputError,\n message,\n targetPath);\n \n \/\/ forward failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n nbCtxId,\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n targetPath);\n}\n\nError executeRcppEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& code,\n const std::map& options)\n{\n \/\/ forward declare error\n Error error;\n \n \/\/ always ensure we emit a 'execution complete' event on exit\n ChunkExecCompletedScope execScope(docId, chunkId);\n \n \/\/ prepare cache output file (use tempfile on failure)\n FilePath targetPath = module_context::tempFile(\"rcpp-cache\", \"\");\n error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ capture console output, error\n boost::signals::scoped_connection consoleHandler =\n module_context::events().onConsoleOutput.connect(\n boost::bind(chunkConsoleOutputHandler,\n _1,\n _2,\n targetPath));\n\n \/\/ call Rcpp::sourceCpp on code\n std::string escaped = boost::regex_replace(\n code,\n boost::regex(\"(\\\\\\\\|\\\")\"),\n \"\\\\\\\\$1\");\n \n std::string execCode =\n \"Rcpp::sourceCpp(code = \\\"\" + escaped + \"\\\")\";\n \n \/\/ write input code to cache\n error = appendConsoleOutput(\n kChunkConsoleInput,\n code,\n targetPath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ execute code (output captured on success; on failure we\n \/\/ explicitly forward the error message returned)\n error = r::exec::executeString(execCode);\n if (error)\n {\n chunkConsoleOutputHandler(module_context::ConsoleOutputError,\n r::endUserErrorMessage(error),\n targetPath);\n }\n\n \/\/ forward success \/ failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n nbCtxId,\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n targetPath);\n \n return error;\n}\n\nvoid reportStanExecutionError(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const FilePath& targetPath)\n{\n std::string message =\n \"engine.opts$output.var must be a character string providing a \"\n \"name for the returned `stanmodel` object\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, targetPath);\n}\n\n\nError executeStanEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& code,\n const std::map& options)\n{\n \/\/ forward-declare error\n Error error;\n \n \/\/ ensure we always emit an execution complete event on exit\n ChunkExecCompletedScope execScope(docId, chunkId);\n \n \/\/ prepare console output file -- use tempfile on failure\n FilePath targetPath = module_context::tempFile(\"stan-cache-\", \"\");\n error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &targetPath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ capture console output, error\n boost::signals::scoped_connection consoleHandler =\n module_context::events().onConsoleOutput.connect(\n boost::bind(chunkConsoleOutputHandler,\n _1,\n _2,\n targetPath)); \n \n \/\/ write code to file\n FilePath tempFile = module_context::tempFile(\"stan-\", \".stan\");\n error = writeStringToFile(tempFile, code + \"\\n\");\n if (error)\n {\n reportChunkExecutionError(\n docId,\n chunkId,\n nbCtxId,\n r::endUserErrorMessage(error),\n targetPath);\n LOG_ERROR(error);\n return Success();\n }\n RemoveOnExitScope removeOnExitScope(tempFile, ERROR_LOCATION);\n \n \/\/ evaluate engine options (so we can pass them through to stan call)\n r::sexp::Protect protect;\n SEXP engineOptsSEXP = R_NilValue;\n if (options.count(\"engine.opts\"))\n {\n error = r::exec::evaluateString(\n options.at(\"engine.opts\"),\n &engineOptsSEXP,\n &protect);\n\n if (error)\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n }\n else\n {\n \/\/ if no engine.opts available, just use a plain empty list\n engineOptsSEXP = r::sexp::createList(std::vector(), &protect);\n }\n \n \/\/ construct call to 'stan_model'\n r::exec::RFunction fStanEngine(\"rstan:::stan_model\");\n std::vector engineOptsNames;\n error = r::sexp::getNames(engineOptsSEXP, &engineOptsNames);\n if (error)\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n \n \/\/ build parameters\n std::string modelName;\n for (std::size_t i = 0, n = r::sexp::length(engineOptsSEXP); i < n; ++i)\n {\n \/\/ skip 'output.var' engine option (this is the variable we wish to assign to\n \/\/ after evaluating the stan model)\n if (engineOptsNames[i] == \"output.var\" || engineOptsNames[i] == \"x\")\n {\n modelName = r::sexp::asString(VECTOR_ELT(engineOptsSEXP, i));\n continue;\n }\n \n fStanEngine.addParam(\n engineOptsNames[i],\n VECTOR_ELT(engineOptsSEXP, i));\n }\n \n \/\/ if 'output.var' was provided as part of the chunk parameters\n \/\/ (not as part of 'engine.opts') then use that here\n if (options.count(\"output.var\"))\n modelName = options.at(\"output.var\");\n \n \/\/ if no model name was set, return error message\n if (modelName.empty())\n {\n reportStanExecutionError(docId, chunkId, nbCtxId, targetPath);\n return Success();\n }\n \n \/\/ if the 'file' option was not set, set it explicitly\n if (!core::algorithm::contains(engineOptsNames, \"file\"))\n fStanEngine.addParam(\"file\", string_utils::utf8ToSystem(tempFile.absolutePath()));\n \n \/\/ evaluate stan_model call\n SEXP stanModelSEXP = R_NilValue;\n error = fStanEngine.call(&stanModelSEXP, &protect);\n if (error)\n {\n std::string msg = r::endUserErrorMessage(error);\n reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);\n return Success();\n }\n \n \/\/ assign in global env on success\n if (stanModelSEXP != R_NilValue)\n {\n r::exec::RFunction assign(\"base:::assign\");\n assign.addParam(\"x\", modelName);\n assign.addParam(\"value\", stanModelSEXP);\n error = assign.call();\n if (error)\n {\n std::string msg = r::endUserErrorMessage(error);\n reportChunkExecutionError(docId, chunkId, nbCtxId, msg, targetPath);\n LOG_ERROR(error);\n return Success();\n }\n }\n \n \/\/ forward success \/ failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n notebookCtxId(),\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n targetPath);\n \n return Success();\n}\n\nError executeSqlEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& code,\n const json::Object& options)\n{\n Error error;\n \n \/\/ ensure we always emit an execution complete event on exit\n ChunkExecCompletedScope execScope(docId, chunkId);\n\n \/\/ prepare console output file -- use tempfile on failure\n FilePath consolePath = module_context::tempFile(\"data-console-\", \"\");\n error = prepareCacheConsoleOutputFile(docId, chunkId, nbCtxId, &consolePath);\n if (error)\n LOG_ERROR(error);\n \n \/\/ capture console output, error\n boost::signals::scoped_connection consoleHandler =\n module_context::events().onConsoleOutput.connect(\n boost::bind(chunkConsoleOutputHandler,\n _1,\n _2,\n consolePath)); \n\n FilePath parentPath = notebook::chunkOutputPath(\n docId, chunkId, nbCtxId, ContextSaved);\n error = parentPath.ensureDirectory();\n if (error)\n {\n std::string message = \"Failed to create SQL chunk directory\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, parentPath);\n \n return Success();\n }\n \n FilePath dataPath =\n notebook::chunkOutputFile(docId, chunkId, nbCtxId, ChunkOutputData);\n\n \/\/ check package dependencies\n if (!module_context::isPackageVersionInstalled(\"DBI\", \"0.4\"))\n {\n std::string message = \"Executing SQL chunks requires version 0.4 or \"\n \"later of the DBI package\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);\n return Success();\n }\n\n \/\/ run sql and save result\n error = r::exec::RFunction(\n \".rs.runSqlForDataCapture\",\n code,\n string_utils::utf8ToSystem(dataPath.absolutePath()),\n options).call();\n if (error)\n {\n std::string message = \"Failed to execute SQL chunk\";\n reportChunkExecutionError(docId, chunkId, nbCtxId, message, consolePath);\n\n return Success();\n }\n\n if (dataPath.exists()) {\n \/\/ forward success \/ failure to chunk\n enqueueChunkOutput(\n docId,\n chunkId,\n notebookCtxId(),\n 0, \/\/ no ordinal needed\n ChunkOutputData,\n dataPath);\n }\n\n \/\/ forward console output\n enqueueChunkOutput(\n docId,\n chunkId,\n notebookCtxId(),\n 0, \/\/ no ordinal needed\n ChunkOutputText,\n consolePath);\n\n return Success();\n}\n\nError interruptEngineChunk(const json::JsonRpcRequest& request,\n json::JsonRpcResponse* pResponse)\n{\n std::string docId, chunkId;\n Error error = json::readParams(request.params,\n &docId,\n &chunkId);\n if (error)\n {\n LOG_ERROR(error);\n return error;\n }\n \n interruptChunk(docId, chunkId);\n return Success();\n}\n\n} \/\/ anonymous namespace\n\nError executeAlternateEngineChunk(const std::string& docId,\n const std::string& chunkId,\n const std::string& nbCtxId,\n const std::string& engine,\n const std::string& code,\n const json::Object& jsonChunkOptions)\n{\n \/\/ read json chunk options\n std::map options;\n for (json::Object::const_iterator it = jsonChunkOptions.begin();\n it != jsonChunkOptions.end();\n ++it)\n {\n if (it->second.type() == json::StringType)\n options[it->first] = it->second.get_str();\n }\n \n \/\/ handle some engines with their own custom routines\n if (engine == \"Rcpp\")\n return executeRcppEngineChunk(docId, chunkId, nbCtxId, code, options);\n else if (engine == \"stan\")\n return executeStanEngineChunk(docId, chunkId, nbCtxId, code, options);\n else if (engine == \"sql\")\n return executeSqlEngineChunk(docId, chunkId, nbCtxId, code, jsonChunkOptions);\n\n runChunk(docId, chunkId, nbCtxId, engine, code, options);\n return Success();\n}\n\nError initAlternateEngines()\n{\n using namespace module_context;\n\n ExecBlock initBlock;\n initBlock.addFunctions()\n (bind(registerRpcMethod, \"interrupt_chunk\", interruptEngineChunk));\n return initBlock.execute();\n}\n\n} \/\/ namespace notebook\n} \/\/ namespace rmarkdown\n} \/\/ namespace modules\n} \/\/ namespace session\n} \/\/ namespace rstudio\n\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nclass ShowImage {\npublic:\n ShowImage()\n : m_gamma(2048),\n RGB_WINDOW_NAME {\"RGB image\"},\n DEPTH_WINDOW_NAME {\"Depth image\"},\n BINARY_WINDOW_NAME {\"Binary image\"}\n {\n for(int i = 0; i < 2048; i++) {\n float v = i \/ 2048.0;\n v = std::pow(v, 3) * 6;\n m_gamma[i] = v * 6 * 256;\n }\n\n cv::namedWindow(RGB_WINDOW_NAME);\n cv::namedWindow(DEPTH_WINDOW_NAME);\n cv::namedWindow(BINARY_WINDOW_NAME);\n }\n\n ~ShowImage() {\n cv::destroyWindow(RGB_WINDOW_NAME);\n cv::destroyWindow(DEPTH_WINDOW_NAME);\n cv::destroyWindow(BINARY_WINDOW_NAME);\n }\n\n void showRGB(const cv::Mat& rgb) {\n imshow(RGB_WINDOW_NAME, rgb);\n }\n\n void showBinary(const cv::Mat& binary) {\n imshow(BINARY_WINDOW_NAME, binary);\n }\n\n void showDepth(const cv::Mat& depth) {\n cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);\n cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);\n cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);\n\n for (int i = 0; i < depth.rows * depth.cols; i++) {\n int y = (int)(i \/ depth.cols);\n int x = (int)(i % depth.cols);\n int pval = m_gamma[buf.at(i)];\n int lb = pval & 0xff;\n\n switch(pval >> 8) {\n case 0:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255-lb;\n break;\n case 1:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = lb;\n output.at(y,x)[0] = 0;\n break;\n case 2:\n output.at(y,x)[2] = 255-lb;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = 0;\n break;\n case 3:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = lb;\n break;\n case 4:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255;\n break;\n case 5:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 255-lb;\n break;\n default:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 0;\n break;\n }\n }\n imshow(DEPTH_WINDOW_NAME, output);\n }\n\nprivate:\n std::vector m_gamma;\n const std::string RGB_WINDOW_NAME;\n const std::string DEPTH_WINDOW_NAME;\n const std::string BINARY_WINDOW_NAME;\n};\n\n\nclass SearchTomato\n{\npublic:\n SearchTomato()\n : tomato_contours {},\n siObj {},\n server {},\n f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))\n {\n server.setCallback(f);\n }\n\n void update(const cv::Mat& capture_rgb) {\n siObj.showRGB(capture_rgb);\n cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);\n imageProsessing(capture_rgb, binary_mat);\n siObj.showBinary(binary_mat);\n searchTomatoContours(binary_mat, tomato_contours);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n return findClosePoint(maskedDepth, tomato_point);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {\n tomato_poses.poses.clear();\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n for (std::size_t i {0}; i < tomato_contours.size(); ++i) {\n cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n findClosePoint(maskedDepth, tomato_poses);\n }\n return tomato_poses.poses.empty() ? false : true;\n }\n\nprivate:\n static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)\n {\n h_min_ = config.h_min;\n h_max_ = config.h_max;\n s_min_ = config.s_min;\n s_max_ = config.s_max;\n v_min_ = config.v_min;\n v_max_ = config.v_max;\n }\n\n void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {\n cv::Mat blur, hsv;\n cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);\n cv::cvtColor(blur, hsv, CV_BGR2HSV);\n redFilter(hsv, binary);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);\n }\n\n void searchTomatoContours(const cv::Mat& binary, std::vector >& tomato_contours) {\n std::vector > contours;\n std::vector contour;\n cv::Rect bounding_box;\n float ratio_balance;\n\n cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);\n\n tomato_contours.clear();\n while (!contours.empty()) {\n contour = contours.back();\n contours.pop_back();\n\n bounding_box = cv::boundingRect(contour);\n ratio_balance = (float)bounding_box.width \/ (float)bounding_box.height;\n if (ratio_balance > 1.0f) ratio_balance = 1.0f \/ ratio_balance;\n\n \/\/ delete mismach. that is smaller or spier or empty\n if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)\n tomato_contours.push_back(contour);\n }\n }\n\n void redFilter(const cv::Mat& hsv, cv::Mat& binary) {\n int a, x, y;\n for(y = 0; y < hsv.rows; y++) {\n for(x = 0; x < hsv.cols; x++) {\n a = hsv.step*y+(x*3);\n if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&\n (hsv.data[a+1] >= s_min_ || hsv.data[a+1] <= s_max_) &&\n (hsv.data[a+2] >= v_min_ || hsv.data[a+2] <= v_max_))\n binary.at(y,x) = 255;\n else\n binary.at(y,x) = 0;\n }\n }\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {\n uint16_t depth;\n constexpr uint16_t OVER_RANGE = 3000;\n uint16_t close_depth = OVER_RANGE;\n\n for (int y = 0; y < maskedDepth.rows; y++) {\n const uint16_t* line_point = maskedDepth.ptr(y);\n for (int x = 0; x < maskedDepth.cols; x++) {\n depth = line_point[x];\n if (512 < depth && depth < close_depth) {\n tomato_point.x = depth; \/\/ for ros coordinate system\n tomato_point.y = x - maskedDepth.cols \/ 2; \/\/ for ros coordinate system\n tomato_point.z = -(y - maskedDepth.rows \/ 2); \/\/ for ros coordinate system\n close_depth = depth;\n }\n }\n }\n return (close_depth != OVER_RANGE ? true : false);\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {\n geometry_msgs::Point tomato_point {};\n if (findClosePoint(maskedDepth, tomato_point)) {\n geometry_msgs::Pose tomato_pose {};\n tomato_pose.position = tomato_point;\n tomato_pose.orientation.w = 1.0;\n tomato_poses.poses.push_back(tomato_pose);\n return true;\n }\n return false;\n }\n\n static uint16_t h_min_;\n static uint16_t h_max_;\n static uint16_t s_min_;\n static uint16_t s_max_;\n static uint16_t v_min_;\n static uint16_t v_max_;\n\n std::vector > tomato_contours;\n ShowImage siObj;\n dynamic_reconfigure::Server server;\n dynamic_reconfigure::Server::CallbackType f;\n};\nuint16_t SearchTomato::h_min_;\nuint16_t SearchTomato::h_max_;\nuint16_t SearchTomato::s_min_;\nuint16_t SearchTomato::s_max_;\nuint16_t SearchTomato::v_min_;\nuint16_t SearchTomato::v_max_;\n\n\nclass ImageConverter {\nprivate:\n ros::NodeHandle nh;\n ros::NodeHandle tomapo_nh;\n ros::Publisher poses_pub;\n geometry_msgs::PoseArray pub_msg;\n image_transport::ImageTransport it;\n image_transport::Subscriber rgb_sub;\n image_transport::Subscriber depth_sub;\n cv_bridge::CvImageConstPtr rgb_ptr;\n cv_bridge::CvImageConstPtr depth_ptr;\n SearchTomato stObj;\n const std::size_t height_;\n const double angle_x_per_piccell_;\n const double angle_y_per_piccell_;\n static constexpr double PI {3.141592653589793};\n\npublic:\n ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)\n : nh {},\n tomapo_nh {nh, \"tomato_point\"},\n poses_pub {tomapo_nh.advertise(\"array\", 1)},\n it {nh},\n rgb_sub {it.subscribe(\"color\", 1, &ImageConverter::rgbCb, this)},\n depth_sub {it.subscribe(\"depth\", 1, &ImageConverter::depthCb, this)},\n stObj {},\n height_ {height},\n angle_x_per_piccell_ {(angle_of_view_x * PI \/ 180.0) \/ width},\n angle_y_per_piccell_ {(angle_of_view_y * PI \/ 180.0) \/ height}\n {\n pub_msg.header.frame_id = \"kinect\";\n }\n\n \/**\n * search tomato function.\n * get rgb image, and search tomato.\n * will tomato_point have data.\n *\n * @author Yusuke Doi\n *\/\n void rgbCb(const sensor_msgs::ImageConstPtr& msg) {\n \/\/ get rgb image on kinect\n try {\n rgb_ptr = cv_bridge::toCvShare(msg, \"bgr8\");\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by rgb: %s\", e.what());\n }\n\n stObj.update(rgb_ptr->image);\n\n cv::waitKey(100);\n }\n\n void depthCb(const sensor_msgs::ImageConstPtr& msg) {\n try {\n depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by depth: %s\", e.what());\n }\n\n if (stObj.searchTomato(depth_ptr->image, pub_msg)) {\n pub_msg.header.stamp = ros::Time::now();\n for (auto& tomato_pose : pub_msg.poses) {\n tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.x = tomato_pose.position.x \/ 1000.0; \/\/ convert to m\n }\n poses_pub.publish(pub_msg);\n }\n\n cv::waitKey(100);\n }\n};\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"kinect_tomato_searcher_node\");\n ImageConverter ic {512, 424, 70, 60};\n ros::spin();\n return 0;\n}\nFix bug of boolean#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\nclass ShowImage {\npublic:\n ShowImage()\n : m_gamma(2048),\n RGB_WINDOW_NAME {\"RGB image\"},\n DEPTH_WINDOW_NAME {\"Depth image\"},\n BINARY_WINDOW_NAME {\"Binary image\"}\n {\n for(int i = 0; i < 2048; i++) {\n float v = i \/ 2048.0;\n v = std::pow(v, 3) * 6;\n m_gamma[i] = v * 6 * 256;\n }\n\n cv::namedWindow(RGB_WINDOW_NAME);\n cv::namedWindow(DEPTH_WINDOW_NAME);\n cv::namedWindow(BINARY_WINDOW_NAME);\n }\n\n ~ShowImage() {\n cv::destroyWindow(RGB_WINDOW_NAME);\n cv::destroyWindow(DEPTH_WINDOW_NAME);\n cv::destroyWindow(BINARY_WINDOW_NAME);\n }\n\n void showRGB(const cv::Mat& rgb) {\n imshow(RGB_WINDOW_NAME, rgb);\n }\n\n void showBinary(const cv::Mat& binary) {\n imshow(BINARY_WINDOW_NAME, binary);\n }\n\n void showDepth(const cv::Mat& depth) {\n cv::Mat buf = cv::Mat::zeros(depth.size(), CV_16UC1);\n cv::Mat output = cv::Mat::zeros(depth.size(), CV_8UC3);\n cv::normalize(depth, buf, 0, 2013, cv::NORM_MINMAX);\n\n for (int i = 0; i < depth.rows * depth.cols; i++) {\n int y = (int)(i \/ depth.cols);\n int x = (int)(i % depth.cols);\n int pval = m_gamma[buf.at(i)];\n int lb = pval & 0xff;\n\n switch(pval >> 8) {\n case 0:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255-lb;\n break;\n case 1:\n output.at(y,x)[2] = 255;\n output.at(y,x)[1] = lb;\n output.at(y,x)[0] = 0;\n break;\n case 2:\n output.at(y,x)[2] = 255-lb;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = 0;\n break;\n case 3:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255;\n output.at(y,x)[0] = lb;\n break;\n case 4:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 255-lb;\n output.at(y,x)[0] = 255;\n break;\n case 5:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 255-lb;\n break;\n default:\n output.at(y,x)[2] = 0;\n output.at(y,x)[1] = 0;\n output.at(y,x)[0] = 0;\n break;\n }\n }\n imshow(DEPTH_WINDOW_NAME, output);\n }\n\nprivate:\n std::vector m_gamma;\n const std::string RGB_WINDOW_NAME;\n const std::string DEPTH_WINDOW_NAME;\n const std::string BINARY_WINDOW_NAME;\n};\n\n\nclass SearchTomato\n{\npublic:\n SearchTomato()\n : tomato_contours {},\n siObj {},\n server {},\n f(std::bind(&dynamic_reconfigure_callback, std::placeholders::_1, std::placeholders::_2))\n {\n server.setCallback(f);\n }\n\n void update(const cv::Mat& capture_rgb) {\n siObj.showRGB(capture_rgb);\n cv::Mat binary_mat = cv::Mat::zeros(capture_rgb.size(), CV_8UC1);\n imageProsessing(capture_rgb, binary_mat);\n siObj.showBinary(binary_mat);\n searchTomatoContours(binary_mat, tomato_contours);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::Point& tomato_point) {\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n cv::drawContours(mask, tomato_contours, -1, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n return findClosePoint(maskedDepth, tomato_point);\n }\n\n bool searchTomato(const cv::Mat& capture_depth, geometry_msgs::PoseArray& tomato_poses) {\n tomato_poses.poses.clear();\n siObj.showDepth(capture_depth);\n cv::Mat maskedDepth = cv::Mat::zeros(capture_depth.size(), CV_16UC1);\n cv::Mat mask = cv::Mat::zeros(capture_depth.size(), CV_8UC1);\n for (std::size_t i {0}; i < tomato_contours.size(); ++i) {\n cv::drawContours(mask, tomato_contours, i, cv::Scalar(255), CV_FILLED, 8);\n siObj.showBinary(mask);\n\n capture_depth.copyTo(maskedDepth, mask);\n findClosePoint(maskedDepth, tomato_poses);\n }\n return tomato_poses.poses.empty() ? false : true;\n }\n\nprivate:\n static void dynamic_reconfigure_callback(kinect_tomato_searcher::SearchConfig& config, uint32_t level)\n {\n h_min_ = config.h_min;\n h_max_ = config.h_max;\n s_min_ = config.s_min;\n s_max_ = config.s_max;\n v_min_ = config.v_min;\n v_max_ = config.v_max;\n }\n\n void imageProsessing(const cv::Mat& rgb, cv::Mat& binary) {\n cv::Mat blur, hsv;\n cv::GaussianBlur(rgb, blur, cv::Size(5, 5), 4.0, 4.0);\n cv::cvtColor(blur, hsv, CV_BGR2HSV);\n redFilter(hsv, binary);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 2);\n cv::erode(binary, binary, cv::Mat(), cv::Point(-1, -1), 4);\n cv::dilate(binary, binary, cv::Mat(), cv::Point(-1, -1), 1);\n }\n\n void searchTomatoContours(const cv::Mat& binary, std::vector >& tomato_contours) {\n std::vector > contours;\n std::vector contour;\n cv::Rect bounding_box;\n float ratio_balance;\n\n cv::findContours(binary, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE);\n\n tomato_contours.clear();\n while (!contours.empty()) {\n contour = contours.back();\n contours.pop_back();\n\n bounding_box = cv::boundingRect(contour);\n ratio_balance = (float)bounding_box.width \/ (float)bounding_box.height;\n if (ratio_balance > 1.0f) ratio_balance = 1.0f \/ ratio_balance;\n\n \/\/ delete mismach. that is smaller or spier or empty\n if (bounding_box.area() >= 400 && bounding_box.area() < cv::contourArea(contour)*2 && ratio_balance > 0.4f)\n tomato_contours.push_back(contour);\n }\n }\n\n void redFilter(const cv::Mat& hsv, cv::Mat& binary) {\n int a, x, y;\n for(y = 0; y < hsv.rows; y++) {\n for(x = 0; x < hsv.cols; x++) {\n a = hsv.step*y+(x*3);\n if((hsv.data[a] <= h_min_ || hsv.data[a] >= h_max_) &&\n (hsv.data[a+1] >= s_min_ && hsv.data[a+1] <= s_max_) &&\n (hsv.data[a+2] >= v_min_ && hsv.data[a+2] <= v_max_))\n binary.at(y,x) = 255;\n else\n binary.at(y,x) = 0;\n }\n }\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::Point& tomato_point) {\n uint16_t depth;\n constexpr uint16_t OVER_RANGE = 3000;\n uint16_t close_depth = OVER_RANGE;\n\n for (int y = 0; y < maskedDepth.rows; y++) {\n const uint16_t* line_point = maskedDepth.ptr(y);\n for (int x = 0; x < maskedDepth.cols; x++) {\n depth = line_point[x];\n if (512 < depth && depth < close_depth) {\n tomato_point.x = depth; \/\/ for ros coordinate system\n tomato_point.y = x - maskedDepth.cols \/ 2; \/\/ for ros coordinate system\n tomato_point.z = -(y - maskedDepth.rows \/ 2); \/\/ for ros coordinate system\n close_depth = depth;\n }\n }\n }\n return (close_depth != OVER_RANGE ? true : false);\n }\n\n bool findClosePoint(const cv::Mat& maskedDepth, geometry_msgs::PoseArray& tomato_poses) {\n geometry_msgs::Point tomato_point {};\n if (findClosePoint(maskedDepth, tomato_point)) {\n geometry_msgs::Pose tomato_pose {};\n tomato_pose.position = tomato_point;\n tomato_pose.orientation.w = 1.0;\n tomato_poses.poses.push_back(tomato_pose);\n return true;\n }\n return false;\n }\n\n static uint16_t h_min_;\n static uint16_t h_max_;\n static uint16_t s_min_;\n static uint16_t s_max_;\n static uint16_t v_min_;\n static uint16_t v_max_;\n\n std::vector > tomato_contours;\n ShowImage siObj;\n dynamic_reconfigure::Server server;\n dynamic_reconfigure::Server::CallbackType f;\n};\nuint16_t SearchTomato::h_min_;\nuint16_t SearchTomato::h_max_;\nuint16_t SearchTomato::s_min_;\nuint16_t SearchTomato::s_max_;\nuint16_t SearchTomato::v_min_;\nuint16_t SearchTomato::v_max_;\n\n\nclass ImageConverter {\nprivate:\n ros::NodeHandle nh;\n ros::NodeHandle tomapo_nh;\n ros::Publisher poses_pub;\n geometry_msgs::PoseArray pub_msg;\n image_transport::ImageTransport it;\n image_transport::Subscriber rgb_sub;\n image_transport::Subscriber depth_sub;\n cv_bridge::CvImageConstPtr rgb_ptr;\n cv_bridge::CvImageConstPtr depth_ptr;\n SearchTomato stObj;\n const std::size_t height_;\n const double angle_x_per_piccell_;\n const double angle_y_per_piccell_;\n static constexpr double PI {3.141592653589793};\n\npublic:\n ImageConverter(const std::size_t width, const std::size_t height, const double angle_of_view_x, const double angle_of_view_y)\n : nh {},\n tomapo_nh {nh, \"tomato_point\"},\n poses_pub {tomapo_nh.advertise(\"array\", 1)},\n it {nh},\n rgb_sub {it.subscribe(\"color\", 1, &ImageConverter::rgbCb, this)},\n depth_sub {it.subscribe(\"depth\", 1, &ImageConverter::depthCb, this)},\n stObj {},\n height_ {height},\n angle_x_per_piccell_ {(angle_of_view_x * PI \/ 180.0) \/ width},\n angle_y_per_piccell_ {(angle_of_view_y * PI \/ 180.0) \/ height}\n {\n pub_msg.header.frame_id = \"kinect\";\n }\n\n \/**\n * search tomato function.\n * get rgb image, and search tomato.\n * will tomato_point have data.\n *\n * @author Yusuke Doi\n *\/\n void rgbCb(const sensor_msgs::ImageConstPtr& msg) {\n \/\/ get rgb image on kinect\n try {\n rgb_ptr = cv_bridge::toCvShare(msg, \"bgr8\");\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by rgb: %s\", e.what());\n }\n\n stObj.update(rgb_ptr->image);\n\n cv::waitKey(100);\n }\n\n void depthCb(const sensor_msgs::ImageConstPtr& msg) {\n try {\n depth_ptr = cv_bridge::toCvShare(msg, sensor_msgs::image_encodings::TYPE_16UC1);\n } catch (cv_bridge::Exception& e) {\n ROS_ERROR(\"cv_bridge exception by depth: %s\", e.what());\n }\n\n if (stObj.searchTomato(depth_ptr->image, pub_msg)) {\n pub_msg.header.stamp = ros::Time::now();\n for (auto& tomato_pose : pub_msg.poses) {\n tomato_pose.position.y = tomato_pose.position.x * tan(angle_x_per_piccell_ * tomato_pose.position.y) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.z = tomato_pose.position.x * tan(angle_y_per_piccell_ * tomato_pose.position.z) \/ 1000.0; \/\/ convert to m\n tomato_pose.position.x = tomato_pose.position.x \/ 1000.0; \/\/ convert to m\n }\n poses_pub.publish(pub_msg);\n }\n\n cv::waitKey(100);\n }\n};\n\nint main(int argc, char** argv) {\n ros::init(argc, argv, \"kinect_tomato_searcher_node\");\n ImageConverter ic {512, 424, 70, 60};\n ros::spin();\n return 0;\n}\n<|endoftext|>"} {"text":" \n\/* ========================================\n\n * File Name : 15.cpp\n\n * Creation Date : 12-08-2020\n\n * Last Modified : St 12. srpna 2020, 14:28:48\n\n * Created By : Karel Ha \n\n * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2018\/round-1\/problems\/A\n\n * Points Gained (in case of online contest) :\n\n ==========================================*\/\n\n#include \n\nusing namespace std;\n\n#define REP(I,N) FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A) (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate \nstring NumberToString ( T Number ) {\n ostringstream ss;\n ss << Number;\n return ss.str();\n}\n\n#define ERR(args...) { vector _v = split(#args, ','); err(_v.begin(), args); }\nvector split(const string& s, char c) {\n vector v;\n stringstream ss(s);\n string x;\n while (getline(ss, x, c))\n v.emplace_back(x);\n return move(v);\n}\nvoid err(vector::iterator it) {}\ntemplate\nvoid err(vector::iterator it, T a, Args... args) {\n cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n err(++it, args...);\n}\n\nint main() {\n return 0;\n}\nRead input \n\/* ========================================\n\n * File Name : 15.cpp\n\n * Creation Date : 12-08-2020\n\n * Last Modified : St 12. srpna 2020, 14:36:32\n\n * Created By : Karel Ha \n\n * URL : https:\/\/www.facebook.com\/codingcompetitions\/hacker-cup\/2018\/round-1\/problems\/A\n\n * Points Gained (in case of online contest) :\n\n ==========================================*\/\n\n#include \n\nusing namespace std;\n\n#define REP(I,N) FOR(I,0,N)\n#define FOR(i, begin, end) for (__typeof(end) i = (begin) - ((begin) > (end)); i != (end) - ((begin) > (end)); i += 1 - 2 * ((begin) > (end)))\n#define ALL(A) (A).begin(), (A).end()\n#define MSG(a) cout << #a << \" == \" << (a) << endl;\n\nconst int CLEAN = -1;\n\ntemplate \nstring NumberToString ( T Number ) {\n ostringstream ss;\n ss << Number;\n return ss.str();\n}\n\n#define ERR(args...) { vector _v = split(#args, ','); err(_v.begin(), args); }\nvector split(const string& s, char c) {\n vector v;\n stringstream ss(s);\n string x;\n while (getline(ss, x, c))\n v.emplace_back(x);\n return move(v);\n}\nvoid err(vector::iterator it) {}\ntemplate\nvoid err(vector::iterator it, T a, Args... args) {\n cout << it -> substr((*it)[0] == ' ', it -> length()) << \" = \" << a << endl;\n err(++it, args...);\n}\n\n#define MOD 1000000007\n\nint main() {\n int T;\n cin >> T;\n\/\/ MSG(T);\n\n REP(t,T) {\n int N;\n cin >> N;\n\/\/ cout << endl; MSG(N);\n\n vector G(3);\n REP(l,3) {\n cin >> G[l];\n\/\/ MSG(G[l]);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n#include \n#include \n#include \"po.hxx\"\n\n\/\/ Translated style names must be unique\nstatic void checkStyleNames(OString aLanguage)\n{\n std::map aLocalizedStyleNames;\n std::map aLocalizedNumStyleNames;\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage + \"\/sw\/source\/ui\/utlui.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == \"poolfmt.src\" &&\n aPoEntry.getGroupId().startsWith(\"STR_POOLCOLL\") )\n {\n OString aMsgStr = aPoEntry.getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedStyleNames.find(aMsgStr) == aLocalizedStyleNames.end() )\n aLocalizedStyleNames[aMsgStr] = 1;\n else\n aLocalizedStyleNames[aMsgStr]++;\n }\n if( !aPoEntry.isFuzzy() && aPoEntry.getSourceFile() == \"poolfmt.src\" &&\n aPoEntry.getGroupId().startsWith(\"STR_POOLNUMRULE\") )\n {\n OString aMsgStr = aPoEntry.getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedNumStyleNames.find(aMsgStr) == aLocalizedNumStyleNames.end() )\n aLocalizedNumStyleNames[aMsgStr] = 1;\n else\n aLocalizedNumStyleNames[aMsgStr]++;\n }\n }\n aPoInput.close();\n\n for( std::map::iterator it=aLocalizedStyleNames.begin(); it!=aLocalizedStyleNames.end(); ++it)\n {\n if( it->second > 1 )\n {\n std::cout << \"ERROR: Style name translations must be unique in:\\n\" <<\n aPoPath << \"\\nLanguage: \" << aLanguage << \"\\nDuplicated translation is: \" << it->first <<\n \"\\nSee STR_POOLCOLL_*\\n\\n\";\n }\n }\n for( std::map::iterator it=aLocalizedNumStyleNames.begin(); it!=aLocalizedNumStyleNames.end(); ++it)\n {\n if( it->second > 1 )\n {\n std::cout << \"ERROR: Style name translations must be unique in:\\n\" <<\n aPoPath << \"\\nLanguage: \" << aLanguage << \"\\nDuplicated translation is: \" << it->first <<\n \"\\nSee STR_POOLNUMRULE_*\\n\\n\";\n }\n }\n}\n\n\/\/ Translated spreadsheet function names must be unique\nstatic void checkFunctionNames(OString aLanguage)\n{\n std::map aLocalizedFunctionNames;\n std::map aLocalizedCoreFunctionNames;\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/formula\/source\/core\/resource.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == \"RID_STRLIST_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry.getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) == aLocalizedCoreFunctionNames.end() )\n aLocalizedCoreFunctionNames[aMsgStr] = 1;\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )\n aLocalizedFunctionNames[aMsgStr] = 1;\n else\n aLocalizedFunctionNames[aMsgStr]++;\n }\n }\n aPoInput.close();\n\n aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/scaddins\/source\/analysis.po\";\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == \"RID_ANALYSIS_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry.getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )\n aMsgStr += \"_ADD\";\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )\n aLocalizedFunctionNames[aMsgStr] = 1;\n else\n aLocalizedFunctionNames[aMsgStr]++;\n }\n }\n aPoInput.close();\n\n aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/scaddins\/source\/datefunc.po\";\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == \"RID_DATE_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry.getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )\n aMsgStr += \"_ADD\";\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )\n aLocalizedFunctionNames[aMsgStr] = 1;\n else\n aLocalizedFunctionNames[aMsgStr]++;\n }\n }\n aPoInput.close();\n\n aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/scaddins\/source\/pricing.po\";\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == \"RID_PRICING_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry.getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )\n aMsgStr += \"_ADD\";\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() )\n aLocalizedFunctionNames[aMsgStr] = 1;\n else\n aLocalizedFunctionNames[aMsgStr]++;\n }\n }\n aPoInput.close();\n for( std::map::iterator it=aLocalizedFunctionNames.begin(); it!=aLocalizedFunctionNames.end(); ++it)\n {\n if( it->second > 1 )\n {\n std::cout << \"ERROR: Spreadsheet function name translations must be unique.\\n\" <<\n \"Language: \" << aLanguage <<\n \"\\nDuplicated translation is: \" << it->first << \"\\n\\n\";\n }\n }\n}\n\n\/\/ In instsetoo_native\/inc_openoffice\/windows\/msi_languages.po\n\/\/ where an en-US string ends with '|', translation must end\n\/\/ with '|', too.\nstatic void checkVerticalBar(OString aLanguage)\n{\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/instsetoo_native\/inc_openoffice\/windows\/msi_languages.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getMsgId().endsWith(\"|\") &&\n !aPoEntry.getMsgStr().isEmpty() && !aPoEntry.getMsgStr().endsWith(\"|\") )\n {\n std::cout << \"ERROR: Missing '|' character at the end of translated string.\\n\" <<\n \"It causes runtime error in installer.\\n\" <<\n \"File: \" << aPoPath << std::endl <<\n \"Language: \" << aLanguage << std::endl <<\n \"English: \" << aPoEntry.getMsgId() << std::endl <<\n \"Localized: \" << aPoEntry.getMsgStr() << std::endl << std::endl;\n }\n }\n aPoInput.close();\n}\n\n\/\/ In starmath\/source.po Math symbol names (from symbol.src)\n\/\/ must not contain spaces\nstatic void checkMathSymbolNames(OString aLanguage)\n{\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/starmath\/source.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == \"RID_UI_SYMBOL_NAMES\" &&\n !aPoEntry.getMsgStr().isEmpty() && (aPoEntry.getMsgStr().indexOf(\" \") != -1) )\n {\n std::cout << \"ERROR: Math symbol names must not contain spaces.\\n\" <<\n \"File: \" << aPoPath << std::endl <<\n \"Language: \" << aLanguage << std::endl <<\n \"English: \" << aPoEntry.getMsgId() << std::endl <<\n \"Localized: \" << aPoEntry.getMsgStr() << std::endl << std::endl;\n }\n }\n aPoInput.close();\n}\n\nint main()\n{\n OString aLanguages(getenv(\"ALL_LANGS\"));\n if( aLanguages.isEmpty() )\n {\n std::cerr << \"Usage: make cmd cmd=solver\/*\/bin\/pocheck\\n\";\n return 1;\n }\n for(sal_Int32 i = 1;;++i) \/\/ skip en-US\n {\n OString aLanguage = aLanguages.getToken(i,' ');\n if( aLanguage.isEmpty() )\n break;\n if( aLanguage == \"qtz\" )\n continue;\n checkStyleNames(aLanguage);\n checkFunctionNames(aLanguage);\n checkVerticalBar(aLanguage);\n checkMathSymbolNames(aLanguage);\n }\n return 0;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\npocheck now removes entries from .po files which are incorrect\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*\n * This file is part of the LibreOffice project.\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"po.hxx\"\n\n\/\/ Translated style names must be unique\nstatic void checkStyleNames(OString aLanguage)\n{\n std::map aLocalizedStyleNames;\n std::map aLocalizedNumStyleNames;\n std::list repeatedEntries;\n\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage + \"\/sw\/source\/ui\/utlui.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n\n for(;;)\n {\n PoEntry* aPoEntry = new PoEntry();\n aPoInput.readEntry(*aPoEntry);\n bool bRepeated = false;\n if( aPoInput.eof() )\n break;\n if( !aPoEntry->isFuzzy() && aPoEntry->getSourceFile() == \"poolfmt.src\" &&\n aPoEntry->getGroupId().startsWith(\"STR_POOLCOLL\") )\n {\n OString aMsgStr = aPoEntry->getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedStyleNames.find(aMsgStr) == aLocalizedStyleNames.end() )\n aLocalizedStyleNames[aMsgStr] = 1;\n else {\n aLocalizedStyleNames[aMsgStr]++;\n bRepeated = true;\n }\n }\n if( !aPoEntry->isFuzzy() && aPoEntry->getSourceFile() == \"poolfmt.src\" &&\n aPoEntry->getGroupId().startsWith(\"STR_POOLNUMRULE\") )\n {\n OString aMsgStr = aPoEntry->getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedNumStyleNames.find(aMsgStr) == aLocalizedNumStyleNames.end() )\n aLocalizedNumStyleNames[aMsgStr] = 1;\n else {\n aLocalizedNumStyleNames[aMsgStr]++;\n bRepeated = true;\n }\n }\n if (bRepeated)\n repeatedEntries.push_back(aPoEntry);\n else\n delete aPoEntry;\n\n }\n aPoInput.close();\n\n for( std::map::iterator it=aLocalizedStyleNames.begin(); it!=aLocalizedStyleNames.end(); ++it)\n {\n if( it->second > 1 )\n {\n std::cout << \"ERROR: Style name translations must be unique in:\\n\" <<\n aPoPath << \"\\nLanguage: \" << aLanguage << \"\\nDuplicated translation is: \" << it->first <<\n \"\\nSee STR_POOLCOLL_*\\n\\n\";\n }\n }\n for( std::map::iterator it=aLocalizedNumStyleNames.begin(); it!=aLocalizedNumStyleNames.end(); ++it)\n {\n if( it->second > 1 )\n {\n std::cout << \"ERROR: Style name translations must be unique in:\\n\" <<\n aPoPath << \"\\nLanguage: \" << aLanguage << \"\\nDuplicated translation is: \" << it->first <<\n \"\\nSee STR_POOLNUMRULE_*\\n\\n\";\n }\n }\n aPoInput.open(aPoPath);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n PoOfstream aPoOutput;\n aPoOutput.open(aPoPath+\".new\");\n PoHeader aTmp(\"sw\/source\/ui\/utlui\");\n aPoOutput.writeHeader(aTmp);\n bool bAnyError = false;\n\n for(;;)\n {\n PoEntry aPoEntry;\n bool bError = false;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n for ( std::list::iterator it=repeatedEntries.begin(); it!=repeatedEntries.end(); ++it) {\n if ((*it)->getMsgId() == aPoEntry.getMsgId() && (*it)->getGroupId() == aPoEntry.getGroupId()) {\n bError = true;\n break;\n }\n }\n if (bError) {\n bAnyError = true;\n } else {\n aPoOutput.writeEntry(aPoEntry);\n }\n }\n aPoInput.close();\n aPoOutput.close();\n OUString aPoPathURL;\n osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPath, RTL_TEXTENCODING_UTF8), aPoPathURL);\n if( bAnyError )\n osl::File::move(aPoPathURL + \".new\", aPoPathURL);\n else\n osl::File::remove(aPoPathURL + \".new\");\n\n}\n\n\/\/ Translated spreadsheet function names must be unique\nstatic void checkFunctionNames(OString aLanguage)\n{\n std::map aLocalizedFunctionNames;\n std::map aLocalizedCoreFunctionNames;\n \/\/\n std::list repeatedEntries;\n\n OString aPoPaths[4];\n OUString aPoPathURL;\n\n aPoPaths[0] = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/formula\/source\/core\/resource.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPaths[0]);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPaths[0] << std::endl;\n\n for(;;)\n {\n PoEntry* aPoEntry = new PoEntry();\n aPoInput.readEntry(*aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == \"RID_STRLIST_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry->getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) == aLocalizedCoreFunctionNames.end() )\n aLocalizedCoreFunctionNames[aMsgStr] = 1;\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {\n aLocalizedFunctionNames[aMsgStr] = 1;\n delete aPoEntry;\n } else {\n aLocalizedFunctionNames[aMsgStr]++;\n repeatedEntries.push_back(aPoEntry);\n }\n }\n }\n aPoInput.close();\n\n aPoPaths[1] = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/scaddins\/source\/analysis.po\";\n aPoInput.open(aPoPaths[1]);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPaths[1] << std::endl;\n\n for(;;)\n {\n PoEntry* aPoEntry = new PoEntry();\n aPoInput.readEntry(*aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == \"RID_ANALYSIS_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry->getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )\n aMsgStr += \"_ADD\";\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {\n aLocalizedFunctionNames[aMsgStr] = 1;\n delete aPoEntry;\n } else {\n aLocalizedFunctionNames[aMsgStr]++;\n repeatedEntries.push_back(aPoEntry);\n }\n }\n }\n aPoInput.close();\n\n\n aPoPaths[2] = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/scaddins\/source\/datefunc.po\";\n aPoInput.open(aPoPaths[2]);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPaths[2] << std::endl;\n\n for(;;)\n {\n PoEntry* aPoEntry = new PoEntry();\n aPoInput.readEntry(*aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == \"RID_DATE_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry->getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )\n aMsgStr += \"_ADD\";\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {\n aLocalizedFunctionNames[aMsgStr] = 1;\n delete aPoEntry;\n } else {\n aLocalizedFunctionNames[aMsgStr]++;\n repeatedEntries.push_back(aPoEntry);\n }\n }\n }\n aPoInput.close();\n\n aPoPaths[3] = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/scaddins\/source\/pricing.po\";\n aPoInput.open(aPoPaths[3]);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPaths[3] << std::endl;\n\n for(;;)\n {\n PoEntry* aPoEntry = new PoEntry();\n aPoInput.readEntry(*aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry->isFuzzy() && aPoEntry->getGroupId() == \"RID_PRICING_FUNCTION_NAMES\" )\n {\n OString aMsgStr = aPoEntry->getMsgStr();\n if( aMsgStr.isEmpty() )\n continue;\n if( aLocalizedCoreFunctionNames.find(aMsgStr) != aLocalizedCoreFunctionNames.end() )\n aMsgStr += \"_ADD\";\n if( aLocalizedFunctionNames.find(aMsgStr) == aLocalizedFunctionNames.end() ) {\n aLocalizedFunctionNames[aMsgStr] = 1;\n delete aPoEntry;\n } else {\n aLocalizedFunctionNames[aMsgStr]++;\n repeatedEntries.push_back(aPoEntry);\n }\n }\n }\n aPoInput.close();\n for( std::map::iterator it=aLocalizedFunctionNames.begin(); it!=aLocalizedFunctionNames.end(); ++it)\n {\n if( it->second > 1 )\n {\n std::cout << \"ERROR: Spreadsheet function name translations must be unique.\\n\" <<\n \"Language: \" << aLanguage <<\n \"\\nDuplicated translation is: \" << it->first << \"\\n\\n\";\n }\n }\n \/\/\n for (int i=0;i<4;i++) {\n aPoInput.open(aPoPaths[i]);\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPaths[i] << std::endl;\n PoOfstream aPoOutput;\n aPoOutput.open(aPoPaths[i]+\".new\");\n\n switch (i) {\n case 0:\n aPoOutput.writeHeader(PoHeader(\"formula\/source\/core\/resource\"));\n break;\n case 1:\n aPoOutput.writeHeader(PoHeader(\"scaddins\/source\/analysis\"));\n break;\n case 2:\n aPoOutput.writeHeader(PoHeader(\"scaddins\/source\/datefunc\"));\n break;\n case 3:\n aPoOutput.writeHeader(PoHeader(\"scaddins\/source\/pricing\"));\n }\n bool bAnyError = false;\n\n for(;;)\n {\n PoEntry aPoEntry;\n bool bError = false;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n for ( std::list::iterator it=repeatedEntries.begin(); it!=repeatedEntries.end(); ++it) {\n if ((*it)->getMsgId() == aPoEntry.getMsgId() && (*it)->getGroupId() == aPoEntry.getGroupId()) {\n bError = true;\n break;\n }\n }\n if (bError) {\n bAnyError = true;\n } else {\n aPoOutput.writeEntry(aPoEntry);\n }\n }\n aPoInput.close();\n aPoOutput.close();\n osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPaths[i], RTL_TEXTENCODING_UTF8), aPoPathURL);\n if( bAnyError )\n osl::File::move(aPoPathURL + \".new\", aPoPathURL);\n else\n osl::File::remove(aPoPathURL + \".new\");\n }\n}\n\n\/\/ In instsetoo_native\/inc_openoffice\/windows\/msi_languages.po\n\/\/ where an en-US string ends with '|', translation must end\n\/\/ with '|', too.\nstatic void checkVerticalBar(OString aLanguage)\n{\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/instsetoo_native\/inc_openoffice\/windows\/msi_languages.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n PoOfstream aPoOutput;\n aPoOutput.open(aPoPath+\".new\");\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n PoHeader aTmp(\"instsetoo_native\/inc_openoffice\/windows\/msi_languages\");\n aPoOutput.writeHeader(aTmp);\n bool bError = false;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getMsgId().endsWith(\"|\") &&\n !aPoEntry.getMsgStr().isEmpty() && !aPoEntry.getMsgStr().endsWith(\"|\") )\n {\n std::cout << \"ERROR: Missing '|' character at the end of translated string.\\n\" <<\n \"It causes runtime error in installer.\\n\" <<\n \"File: \" << aPoPath << std::endl <<\n \"Language: \" << aLanguage << std::endl <<\n \"English: \" << aPoEntry.getMsgId() << std::endl <<\n \"Localized: \" << aPoEntry.getMsgStr() << std::endl << std::endl;\n bError = true;\n }\n else\n aPoOutput.writeEntry(aPoEntry);\n }\n aPoInput.close();\n aPoOutput.close();\n OUString aPoPathURL;\n osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPath, RTL_TEXTENCODING_UTF8), aPoPathURL);\n if( bError )\n osl::File::move(aPoPathURL + \".new\", aPoPathURL);\n else\n osl::File::remove(aPoPathURL + \".new\");\n}\n\n\/\/ In starmath\/source.po Math symbol names (from symbol.src)\n\/\/ must not contain spaces\nstatic void checkMathSymbolNames(OString aLanguage)\n{\n OString aPoPath = OString(getenv(\"SRC_ROOT\")) +\n \"\/translations\/source\/\" +\n aLanguage +\n \"\/starmath\/source.po\";\n PoIfstream aPoInput;\n aPoInput.open(aPoPath);\n PoOfstream aPoOutput;\n aPoOutput.open(aPoPath+\".new\");\n if( !aPoInput.isOpen() )\n std::cerr << \"Warning: Cannot open \" << aPoPath << std::endl;\n PoHeader aTmp(\"starmath\/source\");\n aPoOutput.writeHeader(aTmp);\n bool bError = false;\n\n for(;;)\n {\n PoEntry aPoEntry;\n aPoInput.readEntry(aPoEntry);\n if( aPoInput.eof() )\n break;\n if( !aPoEntry.isFuzzy() && aPoEntry.getGroupId() == \"RID_UI_SYMBOL_NAMES\" &&\n !aPoEntry.getMsgStr().isEmpty() && (aPoEntry.getMsgStr().indexOf(\" \") != -1) )\n {\n std::cout << \"ERROR: Math symbol names must not contain spaces.\\n\" <<\n \"File: \" << aPoPath << std::endl <<\n \"Language: \" << aLanguage << std::endl <<\n \"English: \" << aPoEntry.getMsgId() << std::endl <<\n \"Localized: \" << aPoEntry.getMsgStr() << std::endl << std::endl;\n bError = true;\n }\n else\n aPoOutput.writeEntry(aPoEntry);\n }\n aPoInput.close();\n aPoOutput.close();\n OUString aPoPathURL;\n osl::FileBase::getFileURLFromSystemPath(OStringToOUString(aPoPath, RTL_TEXTENCODING_UTF8), aPoPathURL);\n if( bError )\n osl::File::move(aPoPathURL + \".new\", aPoPathURL);\n else\n osl::File::remove(aPoPathURL + \".new\");\n}\n\nint main()\n{\n OString aLanguages(getenv(\"ALL_LANGS\"));\n if( aLanguages.isEmpty() )\n {\n std::cerr << \"Usage: make cmd cmd=solver\/*\/bin\/pocheck\\n\";\n return 1;\n }\n for(sal_Int32 i = 1;;++i) \/\/ skip en-US\n {\n OString aLanguage = aLanguages.getToken(i,' ');\n if( aLanguage.isEmpty() )\n break;\n if( aLanguage == \"qtz\" )\n continue;\n checkStyleNames(aLanguage);\n checkFunctionNames(aLanguage);\n checkVerticalBar(aLanguage);\n checkMathSymbolNames(aLanguage);\n }\n return 0;\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ Author: Junyang\n\n#define DEBUG_TYPE \"dyn-aa\"\n\n#include \n#include \n\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n\n#include \"rcs\/IDAssigner.h\"\n\n#include \"dyn-aa\/LogCounter.h\"\n#include \"dyn-aa\/TraceSlicer.h\"\n\nusing namespace std;\nusing namespace llvm;\nusing namespace rcs;\nusing namespace dyn_aa;\n\nstatic cl::opt FirstPointerRecordID(\n \"pt1\",\n cl::desc(\"RecordID of the first pointer\"));\n\nstatic cl::opt SecondPointerRecordID(\n \"pt2\",\n cl::desc(\"RecordID of the second pointer\"));\n\nstatic RegisterPass X(\"slice-trace\",\n \"Slice trace of two input pointers\",\n false, \/\/ Is CFG Only?\n true); \/\/ Is Analysis?\n\nchar TraceSlicer::ID = 0;\n\nbool TraceSlicer::runOnModule(Module &M) {\n LogCounter LC;\n LC.processLog();\n CurrentRecordID = LC.getNumLogRecords();\n\n CurrentState[0].StartRecordID = FirstPointerRecordID;\n CurrentState[1].StartRecordID = SecondPointerRecordID;\n\n processLog(true);\n\n return false;\n}\n\nvoid TraceSlicer::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n AU.addRequired();\n}\n\nvoid TraceSlicer::printTrace(raw_ostream &O,\n pair TraceRecord,\n int PointerLabel) const {\n unsigned RecordID = TraceRecord.first;\n unsigned ValueID = TraceRecord.second;\n IDAssigner &IDA = getAnalysis();\n Value *V = IDA.getValue(ValueID);\n O << RecordID << \"\\t\";\n O << \"ptr\" << PointerLabel + 1 << \"\\t\";\n O << ValueID << \"\\t\";\n DynAAUtils::PrintValue(O, V);\n\/\/ if (Argument *A = dyn_cast(V)) {\n\/\/ O << \" (argNo \" << A->getArgNo() << \")\";\n\/\/ }\n O << \"\\n\";\n}\n\nvoid TraceSlicer::print(raw_ostream &O, const Module *M) const {\n O << \"RecID\\tPtr\\tValueID\\tFunc: Inst\/Arg\\n\\n\";\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n O << \"ptr\" << PointerLabel + 1 << \": \\n\";\n for (int i = CurrentState[PointerLabel].Trace.size() - 1; i >= 0; --i) {\n printTrace(O, CurrentState[PointerLabel].Trace[i], PointerLabel);\n }\n O << \"\\n\";\n }\n\n O << \"Merged: \\n\";\n int Index[2];\n Index[0] = CurrentState[0].Trace.size() - 1;\n Index[1] = CurrentState[1].Trace.size() - 1;\n while (true) {\n unsigned Min;\n int PointerLabel = -1;\n for (int i = 0; i < 2; ++i) {\n if (Index[i] >= 0 &&\n (PointerLabel == -1 || CurrentState[i].Trace[Index[i]].first < Min)) {\n Min = CurrentState[i].Trace[Index[i]].first;\n PointerLabel = i;\n }\n }\n if (PointerLabel != -1) {\n printTrace(O,\n CurrentState[PointerLabel].Trace[Index[PointerLabel]],\n PointerLabel);\n Index[PointerLabel]--;\n } else\n break;\n }\n}\n\nbool TraceSlicer::isLive(int PointerLabel) {\n if (CurrentState[PointerLabel].StartRecordID < CurrentRecordID ||\n CurrentState[PointerLabel].End) {\n return false;\n }\n return true;\n}\n\nvoid TraceSlicer::processAddrTakenDecl(const AddrTakenDeclLogRecord &Record) {\n CurrentRecordID--;\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n }\n}\n\nvoid TraceSlicer::processTopLevelPointTo(\n const TopLevelPointToLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n if (CurrentState[PointerLabel].StartRecordID == CurrentRecordID) {\n Value *V = IDA.getValue(Record.PointerValueID);\n assert(V->getType()->isPointerTy());\n CurrentState[PointerLabel].ValueID = Record.PointerValueID;\n }\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action != TopLevelPointTo) {\n continue;\n }\n\n if (!CurrentState[PointerLabel].ValueIDCandidates.empty()) {\n \/\/ For select and PHI, find current ID according to Address and\n \/\/ ValueIDCandidates.\n \/\/ If two variables of select have the same value, we follow the one\n \/\/ occurs latter, this is just a temporary method.\n if (Record.PointeeAddress == CurrentState[PointerLabel].Address &&\n CurrentState[PointerLabel].ValueIDCandidates.count(\n Record.PointerValueID)) {\n CurrentState[PointerLabel].ValueIDCandidates.clear();\n CurrentState[PointerLabel].ValueID = Record.PointerValueID;\n\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, CurrentState[PointerLabel].ValueID));\n trackSourcePointer(CurrentState[PointerLabel], Record);\n }\n } else {\n if (Record.PointerValueID == CurrentState[PointerLabel].ValueID) {\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, CurrentState[PointerLabel].ValueID));\n trackSourcePointer(CurrentState[PointerLabel], Record);\n }\n }\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n\nvoid TraceSlicer::trackSourcePointer(TraceState &TS,\n const TopLevelPointToLogRecord &Record) {\n IDAssigner &IDA = getAnalysis();\n Value *V = IDA.getValue(TS.ValueID);\n if (LoadInst *LI = dyn_cast(V)) {\n TS.Address = Record.LoadedFrom;\n TS.Action = AddrTakenPointTo;\n } else if (GetElementPtrInst *GEPI = dyn_cast(V)) {\n TS.ValueID = IDA.getValueID(GEPI->getPointerOperand());\n } else if (BitCastInst *BCI = dyn_cast(V)) {\n TS.ValueID = IDA.getValueID(BCI->getOperand(0));\n } else if (SelectInst *SI = dyn_cast(V)) {\n TS.ValueIDCandidates.insert(IDA.getValueID(SI->getTrueValue()));\n TS.ValueIDCandidates.insert(IDA.getValueID(SI->getFalseValue()));\n TS.Address = Record.PointeeAddress;\n } else if (PHINode *PN = dyn_cast(V)) {\n unsigned NumIncomingValues = PN->getNumIncomingValues();\n for (unsigned VI = 0; VI != NumIncomingValues; ++VI) {\n TS.ValueIDCandidates.insert(IDA.getValueID(PN->getIncomingValue(VI)));\n }\n TS.Address = Record.PointeeAddress;\n } else if (Argument *A = dyn_cast(V)) {\n TS.Action = CallInstruction;\n TS.ArgNo = A->getArgNo();\n \/\/ errs() << \"(argument of @\" << A->getParent()->getName() << \")\\n\";\n } else if (CallInst *CI = dyn_cast(V)) {\n TS.Action = ReturnInstruction;\n \/\/ errs() << \"(call @\" << CI->getCalledFunction()->getName() << \")\\n\";\n } else if (InvokeInst *II = dyn_cast(V)) {\n TS.Action = ReturnInstruction;\n \/\/ errs() << \"(call @\" << II->getCalledFunction()->getName() << \")\\n\";\n } else if (AllocaInst *AI = dyn_cast(V)) {\n TS.End = true;\n } else if (isa(V)) {\n TS.End = true;\n } else {\n errs() << \"Unknown instruction \\'\" << *V << \"\\'\\n\";\n TS.End = true;\n }\n}\n\nvoid TraceSlicer::processAddrTakenPointTo(\n const AddrTakenPointToLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n Instruction *I = IDA.getInstruction(Record.InstructionID);\n assert(isa(I));\n\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action != AddrTakenPointTo) {\n continue;\n }\n if (Record.PointerAddress == CurrentState[PointerLabel].Address) {\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, IDA.getValueID(I)));\n CurrentState[PointerLabel].Action = TopLevelPointTo;\n StoreInst *SI = dyn_cast(I);\n CurrentState[PointerLabel].ValueID =\n IDA.getValueID(SI->getValueOperand());\n }\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n\nvoid TraceSlicer::processCallInstruction(\n const CallInstructionLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n Instruction *I = IDA.getInstruction(Record.InstructionID);\n CallSite CS(I);\n assert(CS);\n\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action == ReturnInstruction) {\n \/\/ this callee is an external function, the trace ends\n CurrentState[PointerLabel].End = true;\n continue;\n }\n if (CurrentState[PointerLabel].Action != CallInstruction) {\n continue;\n }\n\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, IDA.getValueID(I)));\n CurrentState[PointerLabel].Action = TopLevelPointTo;\n CurrentState[PointerLabel].ValueID =\n IDA.getValueID(CS.getArgument(CurrentState[PointerLabel].ArgNo));\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n\nvoid TraceSlicer::processReturnInstruction(\n const ReturnInstructionLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n Instruction *I = IDA.getInstruction(Record.InstructionID);\n assert(isa(I) || isa(I));\n\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action != ReturnInstruction) {\n continue;\n }\n\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, IDA.getValueID(I)));\n CurrentState[PointerLabel].Action = TopLevelPointTo;\n if (ReturnInst *RI = dyn_cast(I)) {\n CurrentState[PointerLabel].ValueID = IDA.getValueID(RI->getReturnValue());\n } else if (ResumeInst *RI = dyn_cast(I)) {\n assert(false);\n \/\/ CurrentState[PointerLabel].ValueID = IDA.getValueID(RI->getValue());\n } else {\n assert(false);\n }\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\nWarnings fixed.\/\/ Author: Junyang\n\n#define DEBUG_TYPE \"dyn-aa\"\n\n#include \n#include \n\n#include \"llvm\/Pass.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n\n#include \"rcs\/IDAssigner.h\"\n\n#include \"dyn-aa\/LogCounter.h\"\n#include \"dyn-aa\/TraceSlicer.h\"\n\nusing namespace std;\nusing namespace llvm;\nusing namespace rcs;\nusing namespace dyn_aa;\n\nstatic cl::opt FirstPointerRecordID(\n \"pt1\",\n cl::desc(\"RecordID of the first pointer\"));\n\nstatic cl::opt SecondPointerRecordID(\n \"pt2\",\n cl::desc(\"RecordID of the second pointer\"));\n\nstatic RegisterPass X(\"slice-trace\",\n \"Slice trace of two input pointers\",\n false, \/\/ Is CFG Only?\n true); \/\/ Is Analysis?\n\nchar TraceSlicer::ID = 0;\n\nbool TraceSlicer::runOnModule(Module &M) {\n LogCounter LC;\n LC.processLog();\n CurrentRecordID = LC.getNumLogRecords();\n\n CurrentState[0].StartRecordID = FirstPointerRecordID;\n CurrentState[1].StartRecordID = SecondPointerRecordID;\n\n processLog(true);\n\n return false;\n}\n\nvoid TraceSlicer::getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesAll();\n AU.addRequired();\n}\n\nvoid TraceSlicer::printTrace(raw_ostream &O,\n pair TraceRecord,\n int PointerLabel) const {\n unsigned RecordID = TraceRecord.first;\n unsigned ValueID = TraceRecord.second;\n IDAssigner &IDA = getAnalysis();\n Value *V = IDA.getValue(ValueID);\n O << RecordID << \"\\t\";\n O << \"ptr\" << PointerLabel + 1 << \"\\t\";\n O << ValueID << \"\\t\";\n DynAAUtils::PrintValue(O, V);\n\/\/ if (Argument *A = dyn_cast(V)) {\n\/\/ O << \" (argNo \" << A->getArgNo() << \")\";\n\/\/ }\n O << \"\\n\";\n}\n\nvoid TraceSlicer::print(raw_ostream &O, const Module *M) const {\n O << \"RecID\\tPtr\\tValueID\\tFunc: Inst\/Arg\\n\\n\";\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n O << \"ptr\" << PointerLabel + 1 << \": \\n\";\n for (int i = CurrentState[PointerLabel].Trace.size() - 1; i >= 0; --i) {\n printTrace(O, CurrentState[PointerLabel].Trace[i], PointerLabel);\n }\n O << \"\\n\";\n }\n\n O << \"Merged: \\n\";\n int Index[2];\n Index[0] = CurrentState[0].Trace.size() - 1;\n Index[1] = CurrentState[1].Trace.size() - 1;\n while (true) {\n unsigned Min;\n int PointerLabel = -1;\n for (int i = 0; i < 2; ++i) {\n if (Index[i] >= 0 &&\n (PointerLabel == -1 || CurrentState[i].Trace[Index[i]].first < Min)) {\n Min = CurrentState[i].Trace[Index[i]].first;\n PointerLabel = i;\n }\n }\n if (PointerLabel != -1) {\n printTrace(O,\n CurrentState[PointerLabel].Trace[Index[PointerLabel]],\n PointerLabel);\n Index[PointerLabel]--;\n } else\n break;\n }\n}\n\nbool TraceSlicer::isLive(int PointerLabel) {\n if (CurrentState[PointerLabel].StartRecordID < CurrentRecordID ||\n CurrentState[PointerLabel].End) {\n return false;\n }\n return true;\n}\n\nvoid TraceSlicer::processAddrTakenDecl(const AddrTakenDeclLogRecord &Record) {\n CurrentRecordID--;\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n }\n}\n\nvoid TraceSlicer::processTopLevelPointTo(\n const TopLevelPointToLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n if (CurrentState[PointerLabel].StartRecordID == CurrentRecordID) {\n Value *V = IDA.getValue(Record.PointerValueID);\n assert(V->getType()->isPointerTy());\n CurrentState[PointerLabel].ValueID = Record.PointerValueID;\n }\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action != TopLevelPointTo) {\n continue;\n }\n\n if (!CurrentState[PointerLabel].ValueIDCandidates.empty()) {\n \/\/ For select and PHI, find current ID according to Address and\n \/\/ ValueIDCandidates.\n \/\/ If two variables of select have the same value, we follow the one\n \/\/ occurs latter, this is just a temporary method.\n if (Record.PointeeAddress == CurrentState[PointerLabel].Address &&\n CurrentState[PointerLabel].ValueIDCandidates.count(\n Record.PointerValueID)) {\n CurrentState[PointerLabel].ValueIDCandidates.clear();\n CurrentState[PointerLabel].ValueID = Record.PointerValueID;\n\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, CurrentState[PointerLabel].ValueID));\n trackSourcePointer(CurrentState[PointerLabel], Record);\n }\n } else {\n if (Record.PointerValueID == CurrentState[PointerLabel].ValueID) {\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, CurrentState[PointerLabel].ValueID));\n trackSourcePointer(CurrentState[PointerLabel], Record);\n }\n }\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n\nvoid TraceSlicer::trackSourcePointer(TraceState &TS,\n const TopLevelPointToLogRecord &Record) {\n IDAssigner &IDA = getAnalysis();\n Value *V = IDA.getValue(TS.ValueID);\n if (isa(V)) {\n TS.Address = Record.LoadedFrom;\n TS.Action = AddrTakenPointTo;\n } else if (GetElementPtrInst *GEPI = dyn_cast(V)) {\n TS.ValueID = IDA.getValueID(GEPI->getPointerOperand());\n } else if (BitCastInst *BCI = dyn_cast(V)) {\n TS.ValueID = IDA.getValueID(BCI->getOperand(0));\n } else if (SelectInst *SI = dyn_cast(V)) {\n TS.ValueIDCandidates.insert(IDA.getValueID(SI->getTrueValue()));\n TS.ValueIDCandidates.insert(IDA.getValueID(SI->getFalseValue()));\n TS.Address = Record.PointeeAddress;\n } else if (PHINode *PN = dyn_cast(V)) {\n unsigned NumIncomingValues = PN->getNumIncomingValues();\n for (unsigned VI = 0; VI != NumIncomingValues; ++VI) {\n TS.ValueIDCandidates.insert(IDA.getValueID(PN->getIncomingValue(VI)));\n }\n TS.Address = Record.PointeeAddress;\n } else if (Argument *A = dyn_cast(V)) {\n TS.Action = CallInstruction;\n TS.ArgNo = A->getArgNo();\n \/\/ errs() << \"(argument of @\" << A->getParent()->getName() << \")\\n\";\n } else if (isa(V) || isa(V)) {\n TS.Action = ReturnInstruction;\n } else if (isa(V)) {\n TS.End = true;\n } else if (isa(V)) {\n TS.End = true;\n } else {\n errs() << \"Unknown instruction \\'\" << *V << \"\\'\\n\";\n TS.End = true;\n }\n}\n\nvoid TraceSlicer::processAddrTakenPointTo(\n const AddrTakenPointToLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n Instruction *I = IDA.getInstruction(Record.InstructionID);\n assert(isa(I));\n\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action != AddrTakenPointTo) {\n continue;\n }\n if (Record.PointerAddress == CurrentState[PointerLabel].Address) {\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, IDA.getValueID(I)));\n CurrentState[PointerLabel].Action = TopLevelPointTo;\n StoreInst *SI = dyn_cast(I);\n CurrentState[PointerLabel].ValueID =\n IDA.getValueID(SI->getValueOperand());\n }\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n\nvoid TraceSlicer::processCallInstruction(\n const CallInstructionLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n Instruction *I = IDA.getInstruction(Record.InstructionID);\n CallSite CS(I);\n assert(CS);\n\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action == ReturnInstruction) {\n \/\/ this callee is an external function, the trace ends\n CurrentState[PointerLabel].End = true;\n continue;\n }\n if (CurrentState[PointerLabel].Action != CallInstruction) {\n continue;\n }\n\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, IDA.getValueID(I)));\n CurrentState[PointerLabel].Action = TopLevelPointTo;\n CurrentState[PointerLabel].ValueID =\n IDA.getValueID(CS.getArgument(CurrentState[PointerLabel].ArgNo));\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n\nvoid TraceSlicer::processReturnInstruction(\n const ReturnInstructionLogRecord &Record) {\n CurrentRecordID--;\n int NumContainingSlices = 0;\n IDAssigner &IDA = getAnalysis();\n Instruction *I = IDA.getInstruction(Record.InstructionID);\n assert(isa(I) || isa(I));\n\n for (int PointerLabel = 0; PointerLabel < 2; ++PointerLabel) {\n \/\/ Starting record must be a TopLevelPointTo record\n assert(CurrentState[PointerLabel].StartRecordID != CurrentRecordID);\n if (isLive(PointerLabel)) {\n if (CurrentState[PointerLabel].Action != ReturnInstruction) {\n continue;\n }\n\n NumContainingSlices++;\n CurrentState[PointerLabel].Trace.push_back(pair(\n CurrentRecordID, IDA.getValueID(I)));\n CurrentState[PointerLabel].Action = TopLevelPointTo;\n if (ReturnInst *RI = dyn_cast(I)) {\n CurrentState[PointerLabel].ValueID =\n IDA.getValueID(RI->getReturnValue());\n } else if (isa(I)) {\n assert(false);\n } else {\n assert(false);\n }\n }\n }\n \/\/ If two sliced traces meet, we stop tracking\n if (NumContainingSlices == 2) {\n CurrentState[0].End = true;\n CurrentState[1].End = true;\n }\n}\n<|endoftext|>"} {"text":"\/\/===-- OptimizeExts.cpp - Optimize sign \/ zero extension instrs -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass performs optimization of sign \/ zero extension instructions. It\n\/\/ may be extended to handle other instructions of similar property.\n\/\/\n\/\/ On some targets, some instructions, e.g. X86 sign \/ zero extension, may\n\/\/ leave the source value in the lower part of the result. This pass will\n\/\/ replace (some) uses of the pre-extension value with uses of the sub-register\n\/\/ of the results.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"ext-opt\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineDominators.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\nusing namespace llvm;\n\nstatic cl::opt Aggressive(\"aggressive-ext-opt\", cl::Hidden,\n cl::desc(\"Aggressive extension optimization\"));\n\nSTATISTIC(NumReuse, \"Number of extension results reused\");\n\nnamespace {\n class OptimizeExts : public MachineFunctionPass {\n const TargetMachine *TM;\n const TargetInstrInfo *TII;\n MachineRegisterInfo *MRI;\n MachineDominatorTree *DT; \/\/ Machine dominator tree\n\n public:\n static char ID; \/\/ Pass identification\n OptimizeExts() : MachineFunctionPass(&ID) {}\n\n virtual bool runOnMachineFunction(MachineFunction &MF);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n MachineFunctionPass::getAnalysisUsage(AU);\n if (Aggressive) {\n AU.addRequired();\n AU.addPreserved();\n }\n }\n\n private:\n bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,\n SmallPtrSet &LocalMIs);\n };\n}\n\nchar OptimizeExts::ID = 0;\nINITIALIZE_PASS(OptimizeExts, \"opt-exts\",\n \"Optimize sign \/ zero extensions\", false, false);\n\nFunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }\n\n\/\/\/ OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads\n\/\/\/ a single register and writes a single register and it does not modify\n\/\/\/ the source, and if the source value is preserved as a sub-register of\n\/\/\/ the result, then replace all reachable uses of the source with the subreg\n\/\/\/ of the result.\n\/\/\/ Do not generate an EXTRACT that is used only in a debug use, as this\n\/\/\/ changes the code. Since this code does not currently share EXTRACTs, just\n\/\/\/ ignore all debug uses.\nbool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,\n SmallPtrSet &LocalMIs) {\n bool Changed = false;\n LocalMIs.insert(MI);\n\n unsigned SrcReg, DstReg, SubIdx;\n if (TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) {\n if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||\n TargetRegisterInfo::isPhysicalRegister(SrcReg))\n return false;\n\n MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);\n if (++UI == MRI->use_nodbg_end())\n \/\/ No other uses.\n return false;\n\n \/\/ Ok, the source has other uses. See if we can replace the other uses\n \/\/ with use of the result of the extension.\n SmallPtrSet ReachedBBs;\n UI = MRI->use_nodbg_begin(DstReg);\n for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();\n UI != UE; ++UI)\n ReachedBBs.insert(UI->getParent());\n\n bool ExtendLife = true;\n \/\/ Uses that are in the same BB of uses of the result of the instruction.\n SmallVector Uses;\n \/\/ Uses that the result of the instruction can reach.\n SmallVector ExtendedUses;\n\n UI = MRI->use_nodbg_begin(SrcReg);\n for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();\n UI != UE; ++UI) {\n MachineOperand &UseMO = UI.getOperand();\n MachineInstr *UseMI = &*UI;\n if (UseMI == MI)\n continue;\n if (UseMI->isPHI()) {\n ExtendLife = false;\n continue;\n }\n\n \/\/ It's an error to translate this:\n \/\/\n \/\/ %reg1025 = %reg1024\n \/\/ ...\n \/\/ %reg1026 = SUBREG_TO_REG 0, %reg1024, 4\n \/\/\n \/\/ into this:\n \/\/\n \/\/ %reg1025 = %reg1024\n \/\/ ...\n \/\/ %reg1027 = COPY %reg1025:4\n \/\/ %reg1026 = SUBREG_TO_REG 0, %reg1027, 4\n \/\/\n \/\/ The problem here is that SUBREG_TO_REG is there to assert that an\n \/\/ implicit zext occurs. It doesn't insert a zext instruction. If we allow\n \/\/ the COPY here, it will give us the value after the ,\n \/\/ not the original value of %reg1024 before .\n if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)\n continue;\n\n MachineBasicBlock *UseMBB = UseMI->getParent();\n if (UseMBB == MBB) {\n \/\/ Local uses that come after the extension.\n if (!LocalMIs.count(UseMI))\n Uses.push_back(&UseMO);\n } else if (ReachedBBs.count(UseMBB))\n \/\/ Non-local uses where the result of extension is used. Always\n \/\/ replace these unless it's a PHI.\n Uses.push_back(&UseMO);\n else if (Aggressive && DT->dominates(MBB, UseMBB))\n \/\/ We may want to extend live range of the extension result in order\n \/\/ to replace these uses.\n ExtendedUses.push_back(&UseMO);\n else {\n \/\/ Both will be live out of the def MBB anyway. Don't extend live\n \/\/ range of the extension result.\n ExtendLife = false;\n break;\n }\n }\n\n if (ExtendLife && !ExtendedUses.empty())\n \/\/ Ok, we'll extend the liveness of the extension result.\n std::copy(ExtendedUses.begin(), ExtendedUses.end(),\n std::back_inserter(Uses));\n\n \/\/ Now replace all uses.\n if (!Uses.empty()) {\n SmallPtrSet PHIBBs;\n \/\/ Look for PHI uses of the extended result, we don't want to extend the\n \/\/ liveness of a PHI input. It breaks all kinds of assumptions down\n \/\/ stream. A PHI use is expected to be the kill of its source values.\n UI = MRI->use_nodbg_begin(DstReg);\n for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();\n UI != UE; ++UI)\n if (UI->isPHI())\n PHIBBs.insert(UI->getParent());\n\n const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);\n for (unsigned i = 0, e = Uses.size(); i != e; ++i) {\n MachineOperand *UseMO = Uses[i];\n MachineInstr *UseMI = UseMO->getParent();\n MachineBasicBlock *UseMBB = UseMI->getParent();\n if (PHIBBs.count(UseMBB))\n continue;\n unsigned NewVR = MRI->createVirtualRegister(RC);\n BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),\n TII->get(TargetOpcode::COPY), NewVR)\n .addReg(DstReg, 0, SubIdx);\n UseMO->setReg(NewVR);\n ++NumReuse;\n Changed = true;\n }\n }\n }\n\n return Changed;\n}\n\nbool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {\n TM = &MF.getTarget();\n TII = TM->getInstrInfo();\n MRI = &MF.getRegInfo();\n DT = Aggressive ? &getAnalysis() : 0;\n\n bool Changed = false;\n\n SmallPtrSet LocalMIs;\n for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {\n MachineBasicBlock *MBB = &*I;\n LocalMIs.clear();\n for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;\n ++MII) {\n MachineInstr *MI = &*MII;\n Changed |= OptimizeInstr(MI, MBB, LocalMIs);\n }\n }\n\n return Changed;\n}\nEarly exit and reduce indentation. No functionality change.\/\/===-- OptimizeExts.cpp - Optimize sign \/ zero extension instrs -----===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass performs optimization of sign \/ zero extension instructions. It\n\/\/ may be extended to handle other instructions of similar property.\n\/\/\n\/\/ On some targets, some instructions, e.g. X86 sign \/ zero extension, may\n\/\/ leave the source value in the lower part of the result. This pass will\n\/\/ replace (some) uses of the pre-extension value with uses of the sub-register\n\/\/ of the results.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#define DEBUG_TYPE \"ext-opt\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineDominators.h\"\n#include \"llvm\/CodeGen\/MachineInstrBuilder.h\"\n#include \"llvm\/CodeGen\/MachineRegisterInfo.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetRegisterInfo.h\"\n#include \"llvm\/Support\/CommandLine.h\"\n#include \"llvm\/ADT\/SmallPtrSet.h\"\n#include \"llvm\/ADT\/Statistic.h\"\nusing namespace llvm;\n\nstatic cl::opt Aggressive(\"aggressive-ext-opt\", cl::Hidden,\n cl::desc(\"Aggressive extension optimization\"));\n\nSTATISTIC(NumReuse, \"Number of extension results reused\");\n\nnamespace {\n class OptimizeExts : public MachineFunctionPass {\n const TargetMachine *TM;\n const TargetInstrInfo *TII;\n MachineRegisterInfo *MRI;\n MachineDominatorTree *DT; \/\/ Machine dominator tree\n\n public:\n static char ID; \/\/ Pass identification\n OptimizeExts() : MachineFunctionPass(&ID) {}\n\n virtual bool runOnMachineFunction(MachineFunction &MF);\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.setPreservesCFG();\n MachineFunctionPass::getAnalysisUsage(AU);\n if (Aggressive) {\n AU.addRequired();\n AU.addPreserved();\n }\n }\n\n private:\n bool OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,\n SmallPtrSet &LocalMIs);\n };\n}\n\nchar OptimizeExts::ID = 0;\nINITIALIZE_PASS(OptimizeExts, \"opt-exts\",\n \"Optimize sign \/ zero extensions\", false, false);\n\nFunctionPass *llvm::createOptimizeExtsPass() { return new OptimizeExts(); }\n\n\/\/\/ OptimizeInstr - If instruction is a copy-like instruction, i.e. it reads\n\/\/\/ a single register and writes a single register and it does not modify\n\/\/\/ the source, and if the source value is preserved as a sub-register of\n\/\/\/ the result, then replace all reachable uses of the source with the subreg\n\/\/\/ of the result.\n\/\/\/ Do not generate an EXTRACT that is used only in a debug use, as this\n\/\/\/ changes the code. Since this code does not currently share EXTRACTs, just\n\/\/\/ ignore all debug uses.\nbool OptimizeExts::OptimizeInstr(MachineInstr *MI, MachineBasicBlock *MBB,\n SmallPtrSet &LocalMIs) {\n LocalMIs.insert(MI);\n\n unsigned SrcReg, DstReg, SubIdx;\n if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))\n return false;\n\n if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||\n TargetRegisterInfo::isPhysicalRegister(SrcReg))\n return false;\n\n MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);\n if (++UI == MRI->use_nodbg_end())\n \/\/ No other uses.\n return false;\n\n \/\/ Ok, the source has other uses. See if we can replace the other uses\n \/\/ with use of the result of the extension.\n SmallPtrSet ReachedBBs;\n UI = MRI->use_nodbg_begin(DstReg);\n for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();\n UI != UE; ++UI)\n ReachedBBs.insert(UI->getParent());\n\n bool ExtendLife = true;\n \/\/ Uses that are in the same BB of uses of the result of the instruction.\n SmallVector Uses;\n \/\/ Uses that the result of the instruction can reach.\n SmallVector ExtendedUses;\n\n UI = MRI->use_nodbg_begin(SrcReg);\n for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();\n UI != UE; ++UI) {\n MachineOperand &UseMO = UI.getOperand();\n MachineInstr *UseMI = &*UI;\n if (UseMI == MI)\n continue;\n if (UseMI->isPHI()) {\n ExtendLife = false;\n continue;\n }\n\n \/\/ It's an error to translate this:\n \/\/\n \/\/ %reg1025 = %reg1024\n \/\/ ...\n \/\/ %reg1026 = SUBREG_TO_REG 0, %reg1024, 4\n \/\/\n \/\/ into this:\n \/\/\n \/\/ %reg1025 = %reg1024\n \/\/ ...\n \/\/ %reg1027 = COPY %reg1025:4\n \/\/ %reg1026 = SUBREG_TO_REG 0, %reg1027, 4\n \/\/\n \/\/ The problem here is that SUBREG_TO_REG is there to assert that an\n \/\/ implicit zext occurs. It doesn't insert a zext instruction. If we allow\n \/\/ the COPY here, it will give us the value after the , not the\n \/\/ original value of %reg1024 before .\n if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)\n continue;\n\n MachineBasicBlock *UseMBB = UseMI->getParent();\n if (UseMBB == MBB) {\n \/\/ Local uses that come after the extension.\n if (!LocalMIs.count(UseMI))\n Uses.push_back(&UseMO);\n } else if (ReachedBBs.count(UseMBB))\n \/\/ Non-local uses where the result of extension is used. Always replace\n \/\/ these unless it's a PHI.\n Uses.push_back(&UseMO);\n else if (Aggressive && DT->dominates(MBB, UseMBB))\n \/\/ We may want to extend live range of the extension result in order to\n \/\/ replace these uses.\n ExtendedUses.push_back(&UseMO);\n else {\n \/\/ Both will be live out of the def MBB anyway. Don't extend live range of\n \/\/ the extension result.\n ExtendLife = false;\n break;\n }\n }\n\n if (ExtendLife && !ExtendedUses.empty())\n \/\/ Ok, we'll extend the liveness of the extension result.\n std::copy(ExtendedUses.begin(), ExtendedUses.end(),\n std::back_inserter(Uses));\n\n \/\/ Now replace all uses.\n bool Changed = false;\n if (!Uses.empty()) {\n SmallPtrSet PHIBBs;\n \/\/ Look for PHI uses of the extended result, we don't want to extend the\n \/\/ liveness of a PHI input. It breaks all kinds of assumptions down\n \/\/ stream. A PHI use is expected to be the kill of its source values.\n UI = MRI->use_nodbg_begin(DstReg);\n for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();\n UI != UE; ++UI)\n if (UI->isPHI())\n PHIBBs.insert(UI->getParent());\n\n const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);\n for (unsigned i = 0, e = Uses.size(); i != e; ++i) {\n MachineOperand *UseMO = Uses[i];\n MachineInstr *UseMI = UseMO->getParent();\n MachineBasicBlock *UseMBB = UseMI->getParent();\n if (PHIBBs.count(UseMBB))\n continue;\n unsigned NewVR = MRI->createVirtualRegister(RC);\n BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),\n TII->get(TargetOpcode::COPY), NewVR)\n .addReg(DstReg, 0, SubIdx);\n UseMO->setReg(NewVR);\n ++NumReuse;\n Changed = true;\n }\n }\n\n return Changed;\n}\n\nbool OptimizeExts::runOnMachineFunction(MachineFunction &MF) {\n TM = &MF.getTarget();\n TII = TM->getInstrInfo();\n MRI = &MF.getRegInfo();\n DT = Aggressive ? &getAnalysis() : 0;\n\n bool Changed = false;\n\n SmallPtrSet LocalMIs;\n for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {\n MachineBasicBlock *MBB = &*I;\n LocalMIs.clear();\n for (MachineBasicBlock::iterator MII = I->begin(), ME = I->end(); MII != ME;\n ++MII) {\n MachineInstr *MI = &*MII;\n Changed |= OptimizeInstr(MI, MBB, LocalMIs);\n }\n }\n\n return Changed;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nDECLARE_int32(num_client_connections);\nDECLARE_string(transport); \/\/ ConnectionManager depends on this flag.\n\nnamespace apache {\nnamespace thrift {\n\nusing namespace testutil::testservice;\nusing namespace apache::thrift::transport;\n\nclass RSCompatibilityTest\n : public testing::Test,\n public testing::WithParamInterface {\n public:\n RSCompatibilityTest() {\n FLAGS_transport = \"rocket\";\n\n compatibilityTest_ = std::make_unique();\n compatibilityTest_->addRoutingHandler(\n std::make_unique());\n compatibilityTest_->startServer();\n }\n\n protected:\n std::unique_ptr compatibilityTest_;\n};\n\nTEST_F(RSCompatibilityTest, RequestResponse_Simple) {\n compatibilityTest_->TestRequestResponse_Simple();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Sync) {\n compatibilityTest_->TestRequestResponse_Sync();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Destruction) {\n compatibilityTest_->TestRequestResponse_Destruction();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_MultipleClients) {\n compatibilityTest_->TestRequestResponse_MultipleClients();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_ExpectedException) {\n compatibilityTest_->TestRequestResponse_ExpectedException();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_UnexpectedException) {\n compatibilityTest_->TestRequestResponse_UnexpectedException();\n}\n\n\/\/ Warning: This test may be flaky due to use of timeouts.\nTEST_F(RSCompatibilityTest, RequestResponse_Timeout) {\n compatibilityTest_->TestRequestResponse_Timeout();\n}\n\nTEST_F(RSCompatibilityTest, DefaultTimeoutValueTest) {\n compatibilityTest_->connectToServer([](auto client) {\n \/\/ Opts with no timeout value\n RpcOptions opts;\n\n \/\/ Ok to sleep for 100msec\n auto cb = std::make_unique(false, false);\n client->sleep(opts, std::move(cb), 100);\n\n \/* Sleep to give time for all callbacks to be completed *\/\n \/* sleep override *\/\n std::this_thread::sleep_for(std::chrono::milliseconds(200));\n\n auto* channel = dynamic_cast(client->getChannel());\n EXPECT_TRUE(channel);\n channel->getEventBase()->runInEventBaseThreadAndWait([&]() {\n channel->setTimeout(1); \/\/ 1ms\n });\n\n \/\/ Now it should timeout\n cb = std::make_unique(false, true);\n client->sleep(opts, std::move(cb), 100);\n\n \/* Sleep to give time for all callbacks to be completed *\/\n \/* sleep override *\/\n std::this_thread::sleep_for(std::chrono::milliseconds(200));\n });\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header) {\n compatibilityTest_->TestRequestResponse_Header();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header_Load) {\n compatibilityTest_->TestRequestResponse_Header_Load();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header_ExpectedException) {\n compatibilityTest_->TestRequestResponse_Header_ExpectedException();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header_UnexpectedException) {\n compatibilityTest_->TestRequestResponse_Header_UnexpectedException();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Saturation) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), add_(3)).Times(2);\n \/\/ note that no EXPECT_CALL for add_(5)\n auto* channel = dynamic_cast(client->getChannel());\n ASSERT_NE(nullptr, channel);\n\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(0u); });\n EXPECT_THROW(client->future_add(5).get(), TTransportException);\n\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(1u); });\n\n EXPECT_EQ(3, client->future_add(3).get());\n EXPECT_EQ(6, client->future_add(3).get());\n });\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Connection_CloseNow) {\n compatibilityTest_->TestRequestResponse_Connection_CloseNow();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_ServerQueueTimeout) {\n compatibilityTest_->TestRequestResponse_ServerQueueTimeout();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_ResponseSizeTooBig) {\n compatibilityTest_->TestRequestResponse_ResponseSizeTooBig();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Checksumming) {\n compatibilityTest_->TestRequestResponse_Checksumming();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_CompressRequest) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));\n auto* channel = dynamic_cast(client->getChannel());\n ASSERT_NE(nullptr, channel);\n\n \/\/ set the channel to compress requests\n channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);\n channel->setAutoCompressSizeLimit(0);\n\n std::string name(\"snoopy\");\n auto result =\n client->future_hello(RpcOptions().setEnableChecksum(true), name).get();\n EXPECT_EQ(\"Hello, snoopy\", result);\n });\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Simple) {\n compatibilityTest_->TestOneway_Simple();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_WithDelay) {\n compatibilityTest_->TestOneway_WithDelay();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Saturation) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(100, 5));\n EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(50, 5));\n\n if (auto* channel =\n dynamic_cast(client->getChannel())) {\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(0u); });\n EXPECT_THROW(\n client->future_addAfterDelay(0, 5).get(), TTransportException);\n\n \/\/ the first call is not completed as the connection was saturated\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(1u); });\n } else {\n FAIL() << \"Test run with unexpected channel type\";\n }\n\n \/\/ Client should be able to issue both of these functions as\n \/\/ SINGLE_REQUEST_NO_RESPONSE doesn't need to wait for server response\n client->future_addAfterDelay(100, 5).get();\n client->future_addAfterDelay(50, 5).get(); \/\/ TODO: H2 fails in this call.\n });\n}\n\nTEST_F(RSCompatibilityTest, Oneway_UnexpectedException) {\n compatibilityTest_->TestOneway_UnexpectedException();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Connection_CloseNow) {\n compatibilityTest_->TestOneway_Connection_CloseNow();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_ServerQueueTimeout) {\n compatibilityTest_->TestOneway_ServerQueueTimeout();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Checksumming) {\n compatibilityTest_->TestOneway_Checksumming();\n}\n\nTEST_F(RSCompatibilityTest, RequestContextIsPreserved) {\n compatibilityTest_->TestRequestContextIsPreserved();\n}\n\nTEST_F(RSCompatibilityTest, BadPayload) {\n compatibilityTest_->TestBadPayload();\n}\n\nTEST_F(RSCompatibilityTest, EvbSwitch) {\n compatibilityTest_->TestEvbSwitch();\n}\n\nTEST_F(RSCompatibilityTest, EvbSwitch_Failure) {\n compatibilityTest_->TestEvbSwitch_Failure();\n}\n\nTEST_F(RSCompatibilityTest, CloseCallback) {\n compatibilityTest_->TestCloseCallback();\n}\n\nTEST_F(RSCompatibilityTest, ConnectionStats) {\n compatibilityTest_->TestConnectionStats();\n}\n\nTEST_F(RSCompatibilityTest, ObserverSendReceiveRequests) {\n compatibilityTest_->TestObserverSendReceiveRequests();\n}\n\nTEST_F(RSCompatibilityTest, ConnectionContext) {\n compatibilityTest_->TestConnectionContext();\n}\n\nTEST_F(RSCompatibilityTest, ClientIdentityHook) {\n compatibilityTest_->TestClientIdentityHook();\n}\n\n\/**\n * This is a test class with customized RoutingHandler. The main purpose is to\n * set compression on the server-side and test the behavior.\n *\/\nclass RSCompatibilityTest2 : public testing::Test {\n class TestRoutingHandler : public RSRoutingHandler {\n public:\n TestRoutingHandler() = default;\n TestRoutingHandler(const TestRoutingHandler&) = delete;\n TestRoutingHandler& operator=(const TestRoutingHandler&) = delete;\n void handleConnection(\n wangle::ConnectionManager* connectionManager,\n folly::AsyncTransportWrapper::UniquePtr sock,\n folly::SocketAddress const* address,\n wangle::TransportInfo const& \/*tinfo*\/,\n std::shared_ptr worker) override {\n auto sockPtr = sock.get();\n\n auto* const server = worker->getServer();\n auto* const connection = new rocket::RocketServerConnection(\n std::move(sock),\n std::make_shared(\n worker, *address, sockPtr, setupFrameHandlers),\n server->getStreamExpireTime());\n connection->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);\n connection->setMinCompressBytes(server->getMinCompressBytes());\n connectionManager->addConnection(connection);\n\n if (auto* observer = server->getObserver()) {\n observer->connAccepted();\n observer->activeConnections(\n connectionManager->getNumConnections() *\n server->getNumIOWorkerThreads());\n }\n }\n\n private:\n std::vector> setupFrameHandlers;\n };\n\n public:\n RSCompatibilityTest2() {\n FLAGS_transport = \"rocket\";\n\n compatibilityTest_ = std::make_unique();\n compatibilityTest_->addRoutingHandler(\n std::make_unique());\n compatibilityTest_->startServer();\n }\n\n protected:\n std::unique_ptr compatibilityTest_;\n};\n\nTEST_F(RSCompatibilityTest2, RequestResponse_CompressRequestResponse) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));\n auto* channel = dynamic_cast(client->getChannel());\n ASSERT_NE(nullptr, channel);\n\n \/\/ set the channel to compress requests\n channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);\n channel->setAutoCompressSizeLimit(0);\n\n std::string name(\"snoopy\");\n auto result =\n client->future_hello(RpcOptions().setEnableChecksum(true), name).get();\n EXPECT_EQ(\"Hello, snoopy\", result);\n });\n}\n\n} \/\/ namespace thrift\n} \/\/ namespace apache\nclean up unused bool for rocket tests\/*\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nDECLARE_int32(num_client_connections);\nDECLARE_string(transport); \/\/ ConnectionManager depends on this flag.\n\nnamespace apache {\nnamespace thrift {\n\nusing namespace testutil::testservice;\nusing namespace apache::thrift::transport;\n\nclass RSCompatibilityTest : public testing::Test {\n public:\n RSCompatibilityTest() {\n FLAGS_transport = \"rocket\";\n\n compatibilityTest_ = std::make_unique();\n compatibilityTest_->addRoutingHandler(\n std::make_unique());\n compatibilityTest_->startServer();\n }\n\n protected:\n std::unique_ptr compatibilityTest_;\n};\n\nTEST_F(RSCompatibilityTest, RequestResponse_Simple) {\n compatibilityTest_->TestRequestResponse_Simple();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Sync) {\n compatibilityTest_->TestRequestResponse_Sync();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Destruction) {\n compatibilityTest_->TestRequestResponse_Destruction();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_MultipleClients) {\n compatibilityTest_->TestRequestResponse_MultipleClients();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_ExpectedException) {\n compatibilityTest_->TestRequestResponse_ExpectedException();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_UnexpectedException) {\n compatibilityTest_->TestRequestResponse_UnexpectedException();\n}\n\n\/\/ Warning: This test may be flaky due to use of timeouts.\nTEST_F(RSCompatibilityTest, RequestResponse_Timeout) {\n compatibilityTest_->TestRequestResponse_Timeout();\n}\n\nTEST_F(RSCompatibilityTest, DefaultTimeoutValueTest) {\n compatibilityTest_->connectToServer([](auto client) {\n \/\/ Opts with no timeout value\n RpcOptions opts;\n\n \/\/ Ok to sleep for 100msec\n auto cb = std::make_unique(false, false);\n client->sleep(opts, std::move(cb), 100);\n\n \/* Sleep to give time for all callbacks to be completed *\/\n \/* sleep override *\/\n std::this_thread::sleep_for(std::chrono::milliseconds(200));\n\n auto* channel = dynamic_cast(client->getChannel());\n EXPECT_TRUE(channel);\n channel->getEventBase()->runInEventBaseThreadAndWait([&]() {\n channel->setTimeout(1); \/\/ 1ms\n });\n\n \/\/ Now it should timeout\n cb = std::make_unique(false, true);\n client->sleep(opts, std::move(cb), 100);\n\n \/* Sleep to give time for all callbacks to be completed *\/\n \/* sleep override *\/\n std::this_thread::sleep_for(std::chrono::milliseconds(200));\n });\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header) {\n compatibilityTest_->TestRequestResponse_Header();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header_Load) {\n compatibilityTest_->TestRequestResponse_Header_Load();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header_ExpectedException) {\n compatibilityTest_->TestRequestResponse_Header_ExpectedException();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Header_UnexpectedException) {\n compatibilityTest_->TestRequestResponse_Header_UnexpectedException();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Saturation) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), add_(3)).Times(2);\n \/\/ note that no EXPECT_CALL for add_(5)\n auto* channel = dynamic_cast(client->getChannel());\n ASSERT_NE(nullptr, channel);\n\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(0u); });\n EXPECT_THROW(client->future_add(5).get(), TTransportException);\n\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(1u); });\n\n EXPECT_EQ(3, client->future_add(3).get());\n EXPECT_EQ(6, client->future_add(3).get());\n });\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Connection_CloseNow) {\n compatibilityTest_->TestRequestResponse_Connection_CloseNow();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_ServerQueueTimeout) {\n compatibilityTest_->TestRequestResponse_ServerQueueTimeout();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_ResponseSizeTooBig) {\n compatibilityTest_->TestRequestResponse_ResponseSizeTooBig();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_Checksumming) {\n compatibilityTest_->TestRequestResponse_Checksumming();\n}\n\nTEST_F(RSCompatibilityTest, RequestResponse_CompressRequest) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));\n auto* channel = dynamic_cast(client->getChannel());\n ASSERT_NE(nullptr, channel);\n\n \/\/ set the channel to compress requests\n channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);\n channel->setAutoCompressSizeLimit(0);\n\n std::string name(\"snoopy\");\n auto result =\n client->future_hello(RpcOptions().setEnableChecksum(true), name).get();\n EXPECT_EQ(\"Hello, snoopy\", result);\n });\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Simple) {\n compatibilityTest_->TestOneway_Simple();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_WithDelay) {\n compatibilityTest_->TestOneway_WithDelay();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Saturation) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(100, 5));\n EXPECT_CALL(*compatibilityTest_->handler_.get(), addAfterDelay_(50, 5));\n\n if (auto* channel =\n dynamic_cast(client->getChannel())) {\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(0u); });\n EXPECT_THROW(\n client->future_addAfterDelay(0, 5).get(), TTransportException);\n\n \/\/ the first call is not completed as the connection was saturated\n channel->getEventBase()->runInEventBaseThreadAndWait(\n [&]() { channel->setMaxPendingRequests(1u); });\n } else {\n FAIL() << \"Test run with unexpected channel type\";\n }\n\n \/\/ Client should be able to issue both of these functions as\n \/\/ SINGLE_REQUEST_NO_RESPONSE doesn't need to wait for server response\n client->future_addAfterDelay(100, 5).get();\n client->future_addAfterDelay(50, 5).get(); \/\/ TODO: H2 fails in this call.\n });\n}\n\nTEST_F(RSCompatibilityTest, Oneway_UnexpectedException) {\n compatibilityTest_->TestOneway_UnexpectedException();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Connection_CloseNow) {\n compatibilityTest_->TestOneway_Connection_CloseNow();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_ServerQueueTimeout) {\n compatibilityTest_->TestOneway_ServerQueueTimeout();\n}\n\nTEST_F(RSCompatibilityTest, Oneway_Checksumming) {\n compatibilityTest_->TestOneway_Checksumming();\n}\n\nTEST_F(RSCompatibilityTest, RequestContextIsPreserved) {\n compatibilityTest_->TestRequestContextIsPreserved();\n}\n\nTEST_F(RSCompatibilityTest, BadPayload) {\n compatibilityTest_->TestBadPayload();\n}\n\nTEST_F(RSCompatibilityTest, EvbSwitch) {\n compatibilityTest_->TestEvbSwitch();\n}\n\nTEST_F(RSCompatibilityTest, EvbSwitch_Failure) {\n compatibilityTest_->TestEvbSwitch_Failure();\n}\n\nTEST_F(RSCompatibilityTest, CloseCallback) {\n compatibilityTest_->TestCloseCallback();\n}\n\nTEST_F(RSCompatibilityTest, ConnectionStats) {\n compatibilityTest_->TestConnectionStats();\n}\n\nTEST_F(RSCompatibilityTest, ObserverSendReceiveRequests) {\n compatibilityTest_->TestObserverSendReceiveRequests();\n}\n\nTEST_F(RSCompatibilityTest, ConnectionContext) {\n compatibilityTest_->TestConnectionContext();\n}\n\nTEST_F(RSCompatibilityTest, ClientIdentityHook) {\n compatibilityTest_->TestClientIdentityHook();\n}\n\n\/**\n * This is a test class with customized RoutingHandler. The main purpose is to\n * set compression on the server-side and test the behavior.\n *\/\nclass RSCompatibilityTest2 : public testing::Test {\n class TestRoutingHandler : public RSRoutingHandler {\n public:\n TestRoutingHandler() = default;\n TestRoutingHandler(const TestRoutingHandler&) = delete;\n TestRoutingHandler& operator=(const TestRoutingHandler&) = delete;\n void handleConnection(\n wangle::ConnectionManager* connectionManager,\n folly::AsyncTransportWrapper::UniquePtr sock,\n folly::SocketAddress const* address,\n wangle::TransportInfo const& \/*tinfo*\/,\n std::shared_ptr worker) override {\n auto sockPtr = sock.get();\n\n auto* const server = worker->getServer();\n auto* const connection = new rocket::RocketServerConnection(\n std::move(sock),\n std::make_shared(\n worker, *address, sockPtr, setupFrameHandlers),\n server->getStreamExpireTime());\n connection->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);\n connection->setMinCompressBytes(server->getMinCompressBytes());\n connectionManager->addConnection(connection);\n\n if (auto* observer = server->getObserver()) {\n observer->connAccepted();\n observer->activeConnections(\n connectionManager->getNumConnections() *\n server->getNumIOWorkerThreads());\n }\n }\n\n private:\n std::vector> setupFrameHandlers;\n };\n\n public:\n RSCompatibilityTest2() {\n FLAGS_transport = \"rocket\";\n\n compatibilityTest_ = std::make_unique();\n compatibilityTest_->addRoutingHandler(\n std::make_unique());\n compatibilityTest_->startServer();\n }\n\n protected:\n std::unique_ptr compatibilityTest_;\n};\n\nTEST_F(RSCompatibilityTest2, RequestResponse_CompressRequestResponse) {\n compatibilityTest_->connectToServer([this](auto client) {\n EXPECT_CALL(*compatibilityTest_->handler_.get(), hello_(testing::_));\n auto* channel = dynamic_cast(client->getChannel());\n ASSERT_NE(nullptr, channel);\n\n \/\/ set the channel to compress requests\n channel->setNegotiatedCompressionAlgorithm(CompressionAlgorithm::ZSTD);\n channel->setAutoCompressSizeLimit(0);\n\n std::string name(\"snoopy\");\n auto result =\n client->future_hello(RpcOptions().setEnableChecksum(true), name).get();\n EXPECT_EQ(\"Hello, snoopy\", result);\n });\n}\n\n} \/\/ namespace thrift\n} \/\/ namespace apache\n<|endoftext|>"} {"text":"\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n\/\/ Simple test for a fuzzer: find interesting value of array index.\n#include \n#include \n#include \n#include \n#include \n\nstatic volatile int Sink;\nconst int kArraySize = 1234567;\nint array[kArraySize];\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size < 8) return 0;\n size_t a = 0;\n memcpy(&a, Data, 8);\n Sink = array[a % (kArraySize + 1)];\n return 0;\n}\n\n[libFuzzer] Update Load test to work on 32 bits.\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\n\/\/ Simple test for a fuzzer: find interesting value of array index.\n#include \n#include \n#include \n#include \n#include \n\nstatic volatile int Sink;\nconst int kArraySize = 1234567;\nint array[kArraySize];\n\nextern \"C\" int LLVMFuzzerTestOneInput(const uint8_t *Data, size_t Size) {\n if (Size < 8) return 0;\n uint64_t a = 0;\n memcpy(&a, Data, 8);\n Sink = array[a % (kArraySize + 1)];\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"DeferredRenderer.hpp\"\n#include \"scene\/lights\/Light.hpp\"\n#include \"scene\/Sky.hpp\"\n#include \"system\/System.hpp\"\n#include \"graphics\/GLUtilities.hpp\"\n\nDeferredRenderer::DeferredRenderer(const glm::vec2 & resolution, ShadowMode mode, bool ssao) :\n\t_applySSAO(ssao), _shadowMode(mode) {\n\n\tconst uint renderWidth\t = uint(resolution[0]);\n\tconst uint renderHeight\t = uint(resolution[1]);\n\n\t\/\/ G-buffer setup.\n\tconst Descriptor albedoDesc\t\t\t= {Layout::RGBA16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor normalDesc\t\t\t= {Layout::RGB16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor effectsDesc\t\t= {Layout::RGB8, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor depthDesc\t\t\t= {Layout::DEPTH_COMPONENT32F, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor desc = {Layout::RGB16F, Filter::LINEAR_LINEAR, Wrap::CLAMP};\n\n\tconst std::vector descs = {albedoDesc, normalDesc, effectsDesc, depthDesc};\n\t_gbuffer\t\t\t\t\t\t\t= std::unique_ptr(new Framebuffer(renderWidth, renderHeight, descs, false, \"G-buffer\"));\n\t_ssaoPass\t\t\t\t\t\t\t= std::unique_ptr(new SSAO(renderWidth, renderHeight, 2, 0.5f));\n\t_lightBuffer\t\t\t\t\t\t= std::unique_ptr(new Framebuffer(renderWidth, renderHeight, desc, false, \"Deferred lighting\"));\n\t_preferredFormat.push_back(desc);\n\t_needsDepth = false;\n\n\t_skyboxProgram\t\t= Resources::manager().getProgram(\"skybox_gbuffer\", \"skybox_infinity\", \"skybox_gbuffer\");\n\t_bgProgram\t\t\t= Resources::manager().getProgram(\"background_gbuffer\", \"background_infinity\", \"background_gbuffer\");\n\t_atmoProgram\t\t= Resources::manager().getProgram(\"atmosphere_gbuffer\", \"background_infinity\", \"atmosphere_gbuffer\");\n\t_parallaxProgram\t= Resources::manager().getProgram(\"object_parallax_gbuffer\");\n\t_objectProgram\t\t= Resources::manager().getProgram(\"object_gbuffer\");\n\t_emissiveProgram\t= Resources::manager().getProgram(\"object_emissive_gbuffer\");\n\n\t\/\/ Lighting passes.\n\t_ambientScreen = std::unique_ptr(new AmbientQuad(_gbuffer->texture(0), _gbuffer->texture(1),\n\t\t_gbuffer->texture(2), _gbuffer->depthBuffer(), _ssaoPass->texture()));\n\t_lightRenderer = std::unique_ptr(new DeferredLight(_gbuffer->texture(0), _gbuffer->texture(1), _gbuffer->depthBuffer(), _gbuffer->texture(2)));\n\tcheckGLError();\n}\n\nvoid DeferredRenderer::setScene(const std::shared_ptr & scene) {\n\t\/\/ Do not accept a null scene.\n\tif(!scene) {\n\t\treturn;\n\t}\n\t_scene = scene;\n\t_culler.reset(new Culler(_scene->objects));\n\tcheckGLError();\n}\n\nvoid DeferredRenderer::renderScene(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos) {\n\tGLUtilities::setDepthState(true, TestFunction::LESS, true);\n\t\n\t\/\/ Bind the full scene framebuffer.\n\t_gbuffer->bind();\n\t\/\/ Set screen viewport\n\t_gbuffer->setViewport();\n\t\/\/ Clear the depth buffer (we know we will draw everywhere, no need to clear color).\n\tGLUtilities::clearDepth(1.0f);\n\n\t\/\/ Request list of visible objects from culler.\n\tconst auto & visibles = _culler->cullAndSort(view, proj, pos);\n\n\t\/\/ Scene objects.\n\tfor(const long & objectId : visibles) {\n\t\t\/\/ Once we get a -1, there is no other object to render.\n\t\tif(objectId == -1){\n\t\t\tbreak;\n\t\t}\n\t\tconst Object & object = _scene->objects[objectId];\n\n\t\t\/\/ Combine the three matrices.\n\t\tconst glm::mat4 MV = view * object.model();\n\t\tconst glm::mat4 MVP = proj * MV;\n\t\t\/\/ Compute the normal matrix\n\t\tconst glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV)));\n\n\t\t\/\/ Select the program (and shaders).\n\t\tswitch(object.type()) {\n\t\t\tcase Object::Parallax:\n\t\t\t\t_parallaxProgram->use();\n\t\t\t\t\/\/ Upload the MVP matrix.\n\t\t\t\t_parallaxProgram->uniform(\"mvp\", MVP);\n\t\t\t\t\/\/ Upload the projection matrix.\n\t\t\t\t_parallaxProgram->uniform(\"p\", proj);\n\t\t\t\t\/\/ Upload the MV matrix.\n\t\t\t\t_parallaxProgram->uniform(\"mv\", MV);\n\t\t\t\t\/\/ Upload the normal matrix.\n\t\t\t\t_parallaxProgram->uniform(\"normalMatrix\", normalMatrix);\n\t\t\t\tbreak;\n\t\t\tcase Object::Regular:\n\t\t\t\t_objectProgram->use();\n\t\t\t\t\/\/ Upload the MVP matrix.\n\t\t\t\t_objectProgram->uniform(\"mvp\", MVP);\n\t\t\t\t\/\/ Upload the normal matrix.\n\t\t\t\t_objectProgram->uniform(\"normalMatrix\", normalMatrix);\n\t\t\t\t_objectProgram->uniform(\"hasUV\", object.useTexCoords());\n\t\t\t\tbreak;\n\t\t\tcase Object::Emissive:\n\t\t\t\t_emissiveProgram->use();\n\t\t\t\t\/\/ Upload the MVP matrix.\n\t\t\t\t_emissiveProgram->uniform(\"mvp\", MVP);\n\t\t\t\t\/\/ Are UV available. Note: we might want to decouple UV use from their existence.\n\t\t\t\t_emissiveProgram->uniform(\"hasUV\", object.useTexCoords());\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Backface culling state.\n\t\tif(object.twoSided()) {\n\t\t\tGLUtilities::setCullState(false);\n\t\t}\n\n\t\t\/\/ Bind the textures.\n\t\tGLUtilities::bindTextures(object.textures());\n\t\tGLUtilities::drawMesh(*object.mesh());\n\t\t\/\/ Restore state.\n\t\tGLUtilities::setCullState(true);\n\t}\n\t\n\trenderBackground(view, proj, pos);\n\n\tGLUtilities::setDepthState(false);\n}\n\nvoid DeferredRenderer::renderBackground(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos){\n\t\/\/ Background.\n\t\/\/ No need to write the skybox depth to the framebuffer.\n\t\/\/ Accept a depth of 1.0 (far plane).\n\tGLUtilities::setDepthState(true, TestFunction::LEQUAL, false);\n\tconst Object * background\t= _scene->background.get();\n\tconst Scene::Background mode = _scene->backgroundMode;\n\t\n\tif(mode == Scene::Background::SKYBOX) {\n\t\t\/\/ Skybox.\n\t\tconst glm::mat4 backgroundMVP = proj * view * background->model();\n\t\t\/\/ Draw background.\n\t\t_skyboxProgram->use();\n\t\t\/\/ Upload the MVP matrix.\n\t\t_skyboxProgram->uniform(\"mvp\", backgroundMVP);\n\t\tGLUtilities::bindTextures(background->textures());\n\t\tGLUtilities::drawMesh(*background->mesh());\n\t\t\n\t} else if(mode == Scene::Background::ATMOSPHERE) {\n\t\t\/\/ Atmosphere screen quad.\n\t\t_atmoProgram->use();\n\t\t\/\/ Revert the model to clip matrix, removing the translation part.\n\t\tconst glm::mat4 worldToClipNoT = proj * glm::mat4(glm::mat3(view));\n\t\tconst glm::mat4 clipToWorldNoT = glm::inverse(worldToClipNoT);\n\t\tconst glm::vec3 & sunDir\t = dynamic_cast(background)->direction();\n\t\t\/\/ Send and draw.\n\t\t_atmoProgram->uniform(\"clipToWorld\", clipToWorldNoT);\n\t\t_atmoProgram->uniform(\"viewPos\", pos);\n\t\t_atmoProgram->uniform(\"lightDirection\", sunDir);\n\t\tGLUtilities::bindTextures(background->textures());\n\t\tGLUtilities::drawMesh(*background->mesh());\n\t\t\n\t} else {\n\t\t\/\/ Background color or 2D image.\n\t\t_bgProgram->use();\n\t\tif(mode == Scene::Background::IMAGE) {\n\t\t\t_bgProgram->uniform(\"useTexture\", 1);\n\t\t\tGLUtilities::bindTextures(background->textures());\n\t\t} else {\n\t\t\t_bgProgram->uniform(\"useTexture\", 0);\n\t\t\t_bgProgram->uniform(\"bgColor\", _scene->backgroundColor);\n\t\t}\n\t\tGLUtilities::drawMesh(*background->mesh());\n\t}\n\tGLUtilities::setDepthState(true, TestFunction::LESS, true);\n}\n\nvoid DeferredRenderer::draw(const Camera & camera, Framebuffer & framebuffer, size_t layer) {\n\n\tconst glm::mat4 & view = camera.view();\n\tconst glm::mat4 & proj = camera.projection();\n\tconst glm::vec3 & pos = camera.position();\n\n\t\/\/ --- Scene pass -------\n\trenderScene(view, proj, pos);\n\n\t\/\/ --- SSAO pass\n\tif(_applySSAO) {\n\t\t_ssaoPass->process(proj, _gbuffer->depthBuffer(), _gbuffer->texture(int(TextureType::Normal)));\n\t} else {\n\t\t_ssaoPass->clear();\n\t}\n\n\t\/\/ --- Gbuffer composition pass\n\t_lightRenderer->updateCameraInfos(view, proj);\n\t_lightRenderer->updateShadowMapInfos(_shadowMode, 0.002f);\n\t_lightBuffer->bind();\n\t_lightBuffer->setViewport();\n\t_ambientScreen->draw(view, proj, _scene->environment);\n\tGLUtilities::setBlendState(true, BlendEquation::ADD, BlendFunction::ONE, BlendFunction::ONE);\n\tfor(auto & light : _scene->lights) {\n\t\tlight->draw(*_lightRenderer);\n\t}\n\tGLUtilities::setBlendState(false);\n\t\/\/ Copy to the final framebuffer.\n\tGLUtilities::blit(*_lightBuffer, framebuffer, 0, layer, Filter::NEAREST);\n\n}\n\nvoid DeferredRenderer::resize(unsigned int width, unsigned int height) {\n\t\/\/ Resize the framebuffers.\n\t_gbuffer->resize(glm::vec2(width, height));\n\t_lightBuffer->resize(glm::vec2(width, height));\n\t_ssaoPass->resize(width, height);\n\tcheckGLError();\n\t\n}\n\nvoid DeferredRenderer::interface(){\n\tImGui::Checkbox(\"Freeze culling\", &_freezeFrustum);\n\tImGui::Combo(\"Shadow technique\", reinterpret_cast(&_shadowMode), \"None\\0Basic\\0Variance\\0\\0\");\n\tImGui::Checkbox(\"SSAO\", &_applySSAO);\n\tif(_applySSAO) {\n\t\tImGui::SameLine();\n\t\tImGui::Combo(\"Blur quality\", reinterpret_cast(&_ssaoPass->quality()), \"Low\\0Medium\\0High\\0\\0\");\n\t\tImGui::InputFloat(\"Radius\", &_ssaoPass->radius(), 0.5f);\n\t}\n}\n\nconst Framebuffer * DeferredRenderer::sceneDepth() const {\n\treturn _gbuffer.get();\n}\n\nconst Texture * DeferredRenderer::sceneNormal() const {\n\treturn _gbuffer->texture(1);\n}\nDeferredRenderer: add missing culler interface.#include \"DeferredRenderer.hpp\"\n#include \"scene\/lights\/Light.hpp\"\n#include \"scene\/Sky.hpp\"\n#include \"system\/System.hpp\"\n#include \"graphics\/GLUtilities.hpp\"\n\nDeferredRenderer::DeferredRenderer(const glm::vec2 & resolution, ShadowMode mode, bool ssao) :\n\t_applySSAO(ssao), _shadowMode(mode) {\n\n\tconst uint renderWidth\t = uint(resolution[0]);\n\tconst uint renderHeight\t = uint(resolution[1]);\n\n\t\/\/ G-buffer setup.\n\tconst Descriptor albedoDesc\t\t\t= {Layout::RGBA16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor normalDesc\t\t\t= {Layout::RGB16F, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor effectsDesc\t\t= {Layout::RGB8, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor depthDesc\t\t\t= {Layout::DEPTH_COMPONENT32F, Filter::NEAREST_NEAREST, Wrap::CLAMP};\n\tconst Descriptor desc = {Layout::RGB16F, Filter::LINEAR_LINEAR, Wrap::CLAMP};\n\n\tconst std::vector descs = {albedoDesc, normalDesc, effectsDesc, depthDesc};\n\t_gbuffer\t\t\t\t\t\t\t= std::unique_ptr(new Framebuffer(renderWidth, renderHeight, descs, false, \"G-buffer\"));\n\t_ssaoPass\t\t\t\t\t\t\t= std::unique_ptr(new SSAO(renderWidth, renderHeight, 2, 0.5f));\n\t_lightBuffer\t\t\t\t\t\t= std::unique_ptr(new Framebuffer(renderWidth, renderHeight, desc, false, \"Deferred lighting\"));\n\t_preferredFormat.push_back(desc);\n\t_needsDepth = false;\n\n\t_skyboxProgram\t\t= Resources::manager().getProgram(\"skybox_gbuffer\", \"skybox_infinity\", \"skybox_gbuffer\");\n\t_bgProgram\t\t\t= Resources::manager().getProgram(\"background_gbuffer\", \"background_infinity\", \"background_gbuffer\");\n\t_atmoProgram\t\t= Resources::manager().getProgram(\"atmosphere_gbuffer\", \"background_infinity\", \"atmosphere_gbuffer\");\n\t_parallaxProgram\t= Resources::manager().getProgram(\"object_parallax_gbuffer\");\n\t_objectProgram\t\t= Resources::manager().getProgram(\"object_gbuffer\");\n\t_emissiveProgram\t= Resources::manager().getProgram(\"object_emissive_gbuffer\");\n\n\t\/\/ Lighting passes.\n\t_ambientScreen = std::unique_ptr(new AmbientQuad(_gbuffer->texture(0), _gbuffer->texture(1),\n\t\t_gbuffer->texture(2), _gbuffer->depthBuffer(), _ssaoPass->texture()));\n\t_lightRenderer = std::unique_ptr(new DeferredLight(_gbuffer->texture(0), _gbuffer->texture(1), _gbuffer->depthBuffer(), _gbuffer->texture(2)));\n\tcheckGLError();\n}\n\nvoid DeferredRenderer::setScene(const std::shared_ptr & scene) {\n\t\/\/ Do not accept a null scene.\n\tif(!scene) {\n\t\treturn;\n\t}\n\t_scene = scene;\n\t_culler.reset(new Culler(_scene->objects));\n\tcheckGLError();\n}\n\nvoid DeferredRenderer::renderScene(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos) {\n\tGLUtilities::setDepthState(true, TestFunction::LESS, true);\n\t\n\t\/\/ Bind the full scene framebuffer.\n\t_gbuffer->bind();\n\t\/\/ Set screen viewport\n\t_gbuffer->setViewport();\n\t\/\/ Clear the depth buffer (we know we will draw everywhere, no need to clear color).\n\tGLUtilities::clearDepth(1.0f);\n\n\t\/\/ Request list of visible objects from culler.\n\tconst auto & visibles = _culler->cullAndSort(view, proj, pos);\n\n\t\/\/ Scene objects.\n\tfor(const long & objectId : visibles) {\n\t\t\/\/ Once we get a -1, there is no other object to render.\n\t\tif(objectId == -1){\n\t\t\tbreak;\n\t\t}\n\t\tconst Object & object = _scene->objects[objectId];\n\n\t\t\/\/ Combine the three matrices.\n\t\tconst glm::mat4 MV = view * object.model();\n\t\tconst glm::mat4 MVP = proj * MV;\n\t\t\/\/ Compute the normal matrix\n\t\tconst glm::mat3 normalMatrix = glm::transpose(glm::inverse(glm::mat3(MV)));\n\n\t\t\/\/ Select the program (and shaders).\n\t\tswitch(object.type()) {\n\t\t\tcase Object::Parallax:\n\t\t\t\t_parallaxProgram->use();\n\t\t\t\t\/\/ Upload the MVP matrix.\n\t\t\t\t_parallaxProgram->uniform(\"mvp\", MVP);\n\t\t\t\t\/\/ Upload the projection matrix.\n\t\t\t\t_parallaxProgram->uniform(\"p\", proj);\n\t\t\t\t\/\/ Upload the MV matrix.\n\t\t\t\t_parallaxProgram->uniform(\"mv\", MV);\n\t\t\t\t\/\/ Upload the normal matrix.\n\t\t\t\t_parallaxProgram->uniform(\"normalMatrix\", normalMatrix);\n\t\t\t\tbreak;\n\t\t\tcase Object::Regular:\n\t\t\t\t_objectProgram->use();\n\t\t\t\t\/\/ Upload the MVP matrix.\n\t\t\t\t_objectProgram->uniform(\"mvp\", MVP);\n\t\t\t\t\/\/ Upload the normal matrix.\n\t\t\t\t_objectProgram->uniform(\"normalMatrix\", normalMatrix);\n\t\t\t\t_objectProgram->uniform(\"hasUV\", object.useTexCoords());\n\t\t\t\tbreak;\n\t\t\tcase Object::Emissive:\n\t\t\t\t_emissiveProgram->use();\n\t\t\t\t\/\/ Upload the MVP matrix.\n\t\t\t\t_emissiveProgram->uniform(\"mvp\", MVP);\n\t\t\t\t\/\/ Are UV available. Note: we might want to decouple UV use from their existence.\n\t\t\t\t_emissiveProgram->uniform(\"hasUV\", object.useTexCoords());\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tbreak;\n\t\t}\n\n\t\t\/\/ Backface culling state.\n\t\tif(object.twoSided()) {\n\t\t\tGLUtilities::setCullState(false);\n\t\t}\n\n\t\t\/\/ Bind the textures.\n\t\tGLUtilities::bindTextures(object.textures());\n\t\tGLUtilities::drawMesh(*object.mesh());\n\t\t\/\/ Restore state.\n\t\tGLUtilities::setCullState(true);\n\t}\n\t\n\trenderBackground(view, proj, pos);\n\n\tGLUtilities::setDepthState(false);\n}\n\nvoid DeferredRenderer::renderBackground(const glm::mat4 & view, const glm::mat4 & proj, const glm::vec3 & pos){\n\t\/\/ Background.\n\t\/\/ No need to write the skybox depth to the framebuffer.\n\t\/\/ Accept a depth of 1.0 (far plane).\n\tGLUtilities::setDepthState(true, TestFunction::LEQUAL, false);\n\tconst Object * background\t= _scene->background.get();\n\tconst Scene::Background mode = _scene->backgroundMode;\n\t\n\tif(mode == Scene::Background::SKYBOX) {\n\t\t\/\/ Skybox.\n\t\tconst glm::mat4 backgroundMVP = proj * view * background->model();\n\t\t\/\/ Draw background.\n\t\t_skyboxProgram->use();\n\t\t\/\/ Upload the MVP matrix.\n\t\t_skyboxProgram->uniform(\"mvp\", backgroundMVP);\n\t\tGLUtilities::bindTextures(background->textures());\n\t\tGLUtilities::drawMesh(*background->mesh());\n\t\t\n\t} else if(mode == Scene::Background::ATMOSPHERE) {\n\t\t\/\/ Atmosphere screen quad.\n\t\t_atmoProgram->use();\n\t\t\/\/ Revert the model to clip matrix, removing the translation part.\n\t\tconst glm::mat4 worldToClipNoT = proj * glm::mat4(glm::mat3(view));\n\t\tconst glm::mat4 clipToWorldNoT = glm::inverse(worldToClipNoT);\n\t\tconst glm::vec3 & sunDir\t = dynamic_cast(background)->direction();\n\t\t\/\/ Send and draw.\n\t\t_atmoProgram->uniform(\"clipToWorld\", clipToWorldNoT);\n\t\t_atmoProgram->uniform(\"viewPos\", pos);\n\t\t_atmoProgram->uniform(\"lightDirection\", sunDir);\n\t\tGLUtilities::bindTextures(background->textures());\n\t\tGLUtilities::drawMesh(*background->mesh());\n\t\t\n\t} else {\n\t\t\/\/ Background color or 2D image.\n\t\t_bgProgram->use();\n\t\tif(mode == Scene::Background::IMAGE) {\n\t\t\t_bgProgram->uniform(\"useTexture\", 1);\n\t\t\tGLUtilities::bindTextures(background->textures());\n\t\t} else {\n\t\t\t_bgProgram->uniform(\"useTexture\", 0);\n\t\t\t_bgProgram->uniform(\"bgColor\", _scene->backgroundColor);\n\t\t}\n\t\tGLUtilities::drawMesh(*background->mesh());\n\t}\n\tGLUtilities::setDepthState(true, TestFunction::LESS, true);\n}\n\nvoid DeferredRenderer::draw(const Camera & camera, Framebuffer & framebuffer, size_t layer) {\n\n\tconst glm::mat4 & view = camera.view();\n\tconst glm::mat4 & proj = camera.projection();\n\tconst glm::vec3 & pos = camera.position();\n\n\t\/\/ --- Scene pass -------\n\trenderScene(view, proj, pos);\n\n\t\/\/ --- SSAO pass\n\tif(_applySSAO) {\n\t\t_ssaoPass->process(proj, _gbuffer->depthBuffer(), _gbuffer->texture(int(TextureType::Normal)));\n\t} else {\n\t\t_ssaoPass->clear();\n\t}\n\n\t\/\/ --- Gbuffer composition pass\n\t_lightRenderer->updateCameraInfos(view, proj);\n\t_lightRenderer->updateShadowMapInfos(_shadowMode, 0.002f);\n\t_lightBuffer->bind();\n\t_lightBuffer->setViewport();\n\t_ambientScreen->draw(view, proj, _scene->environment);\n\tGLUtilities::setBlendState(true, BlendEquation::ADD, BlendFunction::ONE, BlendFunction::ONE);\n\tfor(auto & light : _scene->lights) {\n\t\tlight->draw(*_lightRenderer);\n\t}\n\tGLUtilities::setBlendState(false);\n\t\/\/ Copy to the final framebuffer.\n\tGLUtilities::blit(*_lightBuffer, framebuffer, 0, layer, Filter::NEAREST);\n\n}\n\nvoid DeferredRenderer::resize(unsigned int width, unsigned int height) {\n\t\/\/ Resize the framebuffers.\n\t_gbuffer->resize(glm::vec2(width, height));\n\t_lightBuffer->resize(glm::vec2(width, height));\n\t_ssaoPass->resize(width, height);\n\tcheckGLError();\n\t\n}\n\nvoid DeferredRenderer::interface(){\n\n\tImGui::Combo(\"Shadow technique\", reinterpret_cast(&_shadowMode), \"None\\0Basic\\0Variance\\0\\0\");\n\tImGui::Checkbox(\"SSAO\", &_applySSAO);\n\tif(_applySSAO) {\n\t\tImGui::SameLine();\n\t\tImGui::Combo(\"Blur quality\", reinterpret_cast(&_ssaoPass->quality()), \"Low\\0Medium\\0High\\0\\0\");\n\t\tImGui::InputFloat(\"Radius\", &_ssaoPass->radius(), 0.5f);\n\t}\n\tif(_culler){\n\t\t_culler->interface();\n\t}\n\t\n}\n\nconst Framebuffer * DeferredRenderer::sceneDepth() const {\n\treturn _gbuffer.get();\n}\n\nconst Texture * DeferredRenderer::sceneNormal() const {\n\treturn _gbuffer->texture(1);\n}\n<|endoftext|>"} {"text":"\/\/===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the MemoryBuffer interface.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/Process.h\"\n#include \"llvm\/System\/Program.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include \n#include \n#else\n#include \n#endif\n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBuffer implementation itself.\n\/\/===----------------------------------------------------------------------===\/\/\n\nMemoryBuffer::~MemoryBuffer() {\n if (MustDeleteBuffer)\n free((void*)BufferStart);\n}\n\n\/\/\/ initCopyOf - Initialize this source buffer with a copy of the specified\n\/\/\/ memory range. We make the copy so that we can null terminate it\n\/\/\/ successfully.\nvoid MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {\n size_t Size = BufEnd-BufStart;\n BufferStart = (char *)malloc((Size+1) * sizeof(char));\n BufferEnd = BufferStart+Size;\n memcpy(const_cast(BufferStart), BufStart, Size);\n *const_cast(BufferEnd) = 0; \/\/ Null terminate buffer.\n MustDeleteBuffer = true;\n}\n\n\/\/\/ init - Initialize this MemoryBuffer as a reference to externally allocated\n\/\/\/ memory, memory that we know is already null terminated.\nvoid MemoryBuffer::init(const char *BufStart, const char *BufEnd) {\n assert(BufEnd[0] == 0 && \"Buffer is not null terminated!\");\n BufferStart = BufStart;\n BufferEnd = BufEnd;\n MustDeleteBuffer = false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBufferMem implementation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nclass MemoryBufferMem : public MemoryBuffer {\n std::string FileID;\npublic:\n MemoryBufferMem(const char *Start, const char *End, StringRef FID,\n bool Copy = false)\n : FileID(FID) {\n if (!Copy)\n init(Start, End);\n else\n initCopyOf(Start, End);\n }\n \n virtual const char *getBufferIdentifier() const {\n return FileID.c_str();\n }\n};\n}\n\n\/\/\/ getMemBuffer - Open the specified memory range as a MemoryBuffer. Note\n\/\/\/ that EndPtr[0] must be a null byte and be accessible!\nMemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr, \n const char *EndPtr,\n const char *BufferName) {\n return new MemoryBufferMem(StartPtr, EndPtr, BufferName);\n}\n\n\/\/\/ getMemBufferCopy - Open the specified memory range as a MemoryBuffer,\n\/\/\/ copying the contents and taking ownership of it. This has no requirements\n\/\/\/ on EndPtr[0].\nMemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr, \n const char *EndPtr,\n const char *BufferName) {\n return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);\n}\n\n\/\/\/ getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size\n\/\/\/ that is completely initialized to zeros. Note that the caller should\n\/\/\/ initialize the memory allocated by this method. The memory is owned by\n\/\/\/ the MemoryBuffer object.\nMemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,\n StringRef BufferName) {\n char *Buf = (char *)malloc((Size+1) * sizeof(char));\n if (!Buf) return 0;\n Buf[Size] = 0;\n MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);\n \/\/ The memory for this buffer is owned by the MemoryBuffer.\n SB->MustDeleteBuffer = true;\n return SB;\n}\n\n\/\/\/ getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that\n\/\/\/ is completely initialized to zeros. Note that the caller should\n\/\/\/ initialize the memory allocated by this method. The memory is owned by\n\/\/\/ the MemoryBuffer object.\nMemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,\n const char *BufferName) {\n MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);\n if (!SB) return 0;\n memset(const_cast(SB->getBufferStart()), 0, Size+1);\n return SB;\n}\n\n\n\/\/\/ getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin\n\/\/\/ if the Filename is \"-\". If an error occurs, this returns null and fills\n\/\/\/ in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)\n\/\/\/ returns an empty buffer.\nMemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,\n std::string *ErrStr,\n int64_t FileSize) {\n if (Filename == \"-\")\n return getSTDIN();\n return getFile(Filename, ErrStr, FileSize);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBuffer::getFile implementation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\n\/\/\/ MemoryBufferMMapFile - This represents a file that was mapped in with the\n\/\/\/ sys::Path::MapInFilePages method. When destroyed, it calls the\n\/\/\/ sys::Path::UnMapFilePages method.\nclass MemoryBufferMMapFile : public MemoryBuffer {\n std::string Filename;\npublic:\n MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)\n : Filename(filename) {\n init(Pages, Pages+Size);\n }\n \n virtual const char *getBufferIdentifier() const {\n return Filename.c_str();\n }\n \n ~MemoryBufferMMapFile() {\n sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());\n }\n};\n}\n\nMemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,\n int64_t FileSize) {\n int OpenFlags = 0;\n#ifdef O_BINARY\n OpenFlags |= O_BINARY; \/\/ Open input file in binary mode on win32.\n#endif\n int FD = ::open(Filename.str().c_str(), O_RDONLY|OpenFlags);\n if (FD == -1) {\n if (ErrStr) *ErrStr = strerror(errno);\n return 0;\n }\n \n \/\/ If we don't know the file size, use fstat to find out. fstat on an open\n \/\/ file descriptor is cheaper than stat on a random path.\n if (FileSize == -1) {\n struct stat FileInfo;\n \/\/ TODO: This should use fstat64 when available.\n if (fstat(FD, &FileInfo) == -1) {\n if (ErrStr) *ErrStr = strerror(errno);\n ::close(FD);\n return 0;\n }\n FileSize = FileInfo.st_size;\n }\n \n \n \/\/ If the file is large, try to use mmap to read it in. We don't use mmap\n \/\/ for small files, because this can severely fragment our address space. Also\n \/\/ don't try to map files that are exactly a multiple of the system page size,\n \/\/ as the file would not have the required null terminator.\n \/\/\n \/\/ FIXME: Can we just mmap an extra page in the latter case?\n if (FileSize >= 4096*4 &&\n (FileSize & (sys::Process::GetPageSize()-1)) != 0) {\n if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {\n \/\/ Close the file descriptor, now that the whole file is in memory.\n ::close(FD);\n return new MemoryBufferMMapFile(Filename, Pages, FileSize);\n }\n }\n\n MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);\n if (!Buf) {\n \/\/ Failed to create a buffer.\n if (ErrStr) *ErrStr = \"could not allocate buffer\";\n ::close(FD);\n return 0;\n }\n\n OwningPtr SB(Buf);\n char *BufPtr = const_cast(SB->getBufferStart());\n \n size_t BytesLeft = FileSize;\n while (BytesLeft) {\n ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);\n if (NumRead > 0) {\n BytesLeft -= NumRead;\n BufPtr += NumRead;\n } else if (NumRead == -1 && errno == EINTR) {\n \/\/ try again\n } else {\n \/\/ error reading.\n if (ErrStr) *ErrStr = strerror(errno);\n close(FD);\n return 0;\n }\n }\n close(FD);\n \n return SB.take();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBuffer::getSTDIN implementation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nclass STDINBufferFile : public MemoryBuffer {\npublic:\n virtual const char *getBufferIdentifier() const {\n return \"\";\n }\n};\n}\n\nMemoryBuffer *MemoryBuffer::getSTDIN() {\n char Buffer[4096*4];\n\n std::vector FileData;\n\n \/\/ Read in all of the data from stdin, we cannot mmap stdin.\n \/\/\n \/\/ FIXME: That isn't necessarily true, we should try to mmap stdin and\n \/\/ fallback if it fails.\n sys::Program::ChangeStdinToBinary();\n size_t ReadBytes;\n do {\n ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);\n FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);\n } while (ReadBytes == sizeof(Buffer));\n\n FileData.push_back(0); \/\/ &FileData[Size] is invalid. So is &*FileData.end().\n size_t Size = FileData.size();\n MemoryBuffer *B = new STDINBufferFile();\n B->initCopyOf(&FileData[0], &FileData[Size-1]);\n return B;\n}\nsizeof(char) is always 1.\/\/===--- MemoryBuffer.cpp - Memory Buffer implementation ------------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file implements the MemoryBuffer interface.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \"llvm\/ADT\/OwningPtr.h\"\n#include \"llvm\/ADT\/SmallString.h\"\n#include \"llvm\/System\/Path.h\"\n#include \"llvm\/System\/Process.h\"\n#include \"llvm\/System\/Program.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#if !defined(_MSC_VER) && !defined(__MINGW32__)\n#include \n#include \n#else\n#include \n#endif\n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBuffer implementation itself.\n\/\/===----------------------------------------------------------------------===\/\/\n\nMemoryBuffer::~MemoryBuffer() {\n if (MustDeleteBuffer)\n free((void*)BufferStart);\n}\n\n\/\/\/ initCopyOf - Initialize this source buffer with a copy of the specified\n\/\/\/ memory range. We make the copy so that we can null terminate it\n\/\/\/ successfully.\nvoid MemoryBuffer::initCopyOf(const char *BufStart, const char *BufEnd) {\n size_t Size = BufEnd-BufStart;\n BufferStart = (char *)malloc(Size+1);\n BufferEnd = BufferStart+Size;\n memcpy(const_cast(BufferStart), BufStart, Size);\n *const_cast(BufferEnd) = 0; \/\/ Null terminate buffer.\n MustDeleteBuffer = true;\n}\n\n\/\/\/ init - Initialize this MemoryBuffer as a reference to externally allocated\n\/\/\/ memory, memory that we know is already null terminated.\nvoid MemoryBuffer::init(const char *BufStart, const char *BufEnd) {\n assert(BufEnd[0] == 0 && \"Buffer is not null terminated!\");\n BufferStart = BufStart;\n BufferEnd = BufEnd;\n MustDeleteBuffer = false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBufferMem implementation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nclass MemoryBufferMem : public MemoryBuffer {\n std::string FileID;\npublic:\n MemoryBufferMem(const char *Start, const char *End, StringRef FID,\n bool Copy = false)\n : FileID(FID) {\n if (!Copy)\n init(Start, End);\n else\n initCopyOf(Start, End);\n }\n \n virtual const char *getBufferIdentifier() const {\n return FileID.c_str();\n }\n};\n}\n\n\/\/\/ getMemBuffer - Open the specified memory range as a MemoryBuffer. Note\n\/\/\/ that EndPtr[0] must be a null byte and be accessible!\nMemoryBuffer *MemoryBuffer::getMemBuffer(const char *StartPtr, \n const char *EndPtr,\n const char *BufferName) {\n return new MemoryBufferMem(StartPtr, EndPtr, BufferName);\n}\n\n\/\/\/ getMemBufferCopy - Open the specified memory range as a MemoryBuffer,\n\/\/\/ copying the contents and taking ownership of it. This has no requirements\n\/\/\/ on EndPtr[0].\nMemoryBuffer *MemoryBuffer::getMemBufferCopy(const char *StartPtr, \n const char *EndPtr,\n const char *BufferName) {\n return new MemoryBufferMem(StartPtr, EndPtr, BufferName, true);\n}\n\n\/\/\/ getNewUninitMemBuffer - Allocate a new MemoryBuffer of the specified size\n\/\/\/ that is completely initialized to zeros. Note that the caller should\n\/\/\/ initialize the memory allocated by this method. The memory is owned by\n\/\/\/ the MemoryBuffer object.\nMemoryBuffer *MemoryBuffer::getNewUninitMemBuffer(size_t Size,\n StringRef BufferName) {\n char *Buf = (char *)malloc(Size+1);\n if (!Buf) return 0;\n Buf[Size] = 0;\n MemoryBufferMem *SB = new MemoryBufferMem(Buf, Buf+Size, BufferName);\n \/\/ The memory for this buffer is owned by the MemoryBuffer.\n SB->MustDeleteBuffer = true;\n return SB;\n}\n\n\/\/\/ getNewMemBuffer - Allocate a new MemoryBuffer of the specified size that\n\/\/\/ is completely initialized to zeros. Note that the caller should\n\/\/\/ initialize the memory allocated by this method. The memory is owned by\n\/\/\/ the MemoryBuffer object.\nMemoryBuffer *MemoryBuffer::getNewMemBuffer(size_t Size,\n const char *BufferName) {\n MemoryBuffer *SB = getNewUninitMemBuffer(Size, BufferName);\n if (!SB) return 0;\n memset(const_cast(SB->getBufferStart()), 0, Size+1);\n return SB;\n}\n\n\n\/\/\/ getFileOrSTDIN - Open the specified file as a MemoryBuffer, or open stdin\n\/\/\/ if the Filename is \"-\". If an error occurs, this returns null and fills\n\/\/\/ in *ErrStr with a reason. If stdin is empty, this API (unlike getSTDIN)\n\/\/\/ returns an empty buffer.\nMemoryBuffer *MemoryBuffer::getFileOrSTDIN(StringRef Filename,\n std::string *ErrStr,\n int64_t FileSize) {\n if (Filename == \"-\")\n return getSTDIN();\n return getFile(Filename, ErrStr, FileSize);\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBuffer::getFile implementation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\n\/\/\/ MemoryBufferMMapFile - This represents a file that was mapped in with the\n\/\/\/ sys::Path::MapInFilePages method. When destroyed, it calls the\n\/\/\/ sys::Path::UnMapFilePages method.\nclass MemoryBufferMMapFile : public MemoryBuffer {\n std::string Filename;\npublic:\n MemoryBufferMMapFile(StringRef filename, const char *Pages, uint64_t Size)\n : Filename(filename) {\n init(Pages, Pages+Size);\n }\n \n virtual const char *getBufferIdentifier() const {\n return Filename.c_str();\n }\n \n ~MemoryBufferMMapFile() {\n sys::Path::UnMapFilePages(getBufferStart(), getBufferSize());\n }\n};\n}\n\nMemoryBuffer *MemoryBuffer::getFile(StringRef Filename, std::string *ErrStr,\n int64_t FileSize) {\n int OpenFlags = 0;\n#ifdef O_BINARY\n OpenFlags |= O_BINARY; \/\/ Open input file in binary mode on win32.\n#endif\n int FD = ::open(Filename.str().c_str(), O_RDONLY|OpenFlags);\n if (FD == -1) {\n if (ErrStr) *ErrStr = strerror(errno);\n return 0;\n }\n \n \/\/ If we don't know the file size, use fstat to find out. fstat on an open\n \/\/ file descriptor is cheaper than stat on a random path.\n if (FileSize == -1) {\n struct stat FileInfo;\n \/\/ TODO: This should use fstat64 when available.\n if (fstat(FD, &FileInfo) == -1) {\n if (ErrStr) *ErrStr = strerror(errno);\n ::close(FD);\n return 0;\n }\n FileSize = FileInfo.st_size;\n }\n \n \n \/\/ If the file is large, try to use mmap to read it in. We don't use mmap\n \/\/ for small files, because this can severely fragment our address space. Also\n \/\/ don't try to map files that are exactly a multiple of the system page size,\n \/\/ as the file would not have the required null terminator.\n \/\/\n \/\/ FIXME: Can we just mmap an extra page in the latter case?\n if (FileSize >= 4096*4 &&\n (FileSize & (sys::Process::GetPageSize()-1)) != 0) {\n if (const char *Pages = sys::Path::MapInFilePages(FD, FileSize)) {\n \/\/ Close the file descriptor, now that the whole file is in memory.\n ::close(FD);\n return new MemoryBufferMMapFile(Filename, Pages, FileSize);\n }\n }\n\n MemoryBuffer *Buf = MemoryBuffer::getNewUninitMemBuffer(FileSize, Filename);\n if (!Buf) {\n \/\/ Failed to create a buffer.\n if (ErrStr) *ErrStr = \"could not allocate buffer\";\n ::close(FD);\n return 0;\n }\n\n OwningPtr SB(Buf);\n char *BufPtr = const_cast(SB->getBufferStart());\n \n size_t BytesLeft = FileSize;\n while (BytesLeft) {\n ssize_t NumRead = ::read(FD, BufPtr, BytesLeft);\n if (NumRead > 0) {\n BytesLeft -= NumRead;\n BufPtr += NumRead;\n } else if (NumRead == -1 && errno == EINTR) {\n \/\/ try again\n } else {\n \/\/ error reading.\n if (ErrStr) *ErrStr = strerror(errno);\n close(FD);\n return 0;\n }\n }\n close(FD);\n \n return SB.take();\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ MemoryBuffer::getSTDIN implementation.\n\/\/===----------------------------------------------------------------------===\/\/\n\nnamespace {\nclass STDINBufferFile : public MemoryBuffer {\npublic:\n virtual const char *getBufferIdentifier() const {\n return \"\";\n }\n};\n}\n\nMemoryBuffer *MemoryBuffer::getSTDIN() {\n char Buffer[4096*4];\n\n std::vector FileData;\n\n \/\/ Read in all of the data from stdin, we cannot mmap stdin.\n \/\/\n \/\/ FIXME: That isn't necessarily true, we should try to mmap stdin and\n \/\/ fallback if it fails.\n sys::Program::ChangeStdinToBinary();\n size_t ReadBytes;\n do {\n ReadBytes = fread(Buffer, sizeof(char), sizeof(Buffer), stdin);\n FileData.insert(FileData.end(), Buffer, Buffer+ReadBytes);\n } while (ReadBytes == sizeof(Buffer));\n\n FileData.push_back(0); \/\/ &FileData[Size] is invalid. So is &*FileData.end().\n size_t Size = FileData.size();\n MemoryBuffer *B = new STDINBufferFile();\n B->initCopyOf(&FileData[0], &FileData[Size-1]);\n return B;\n}\n<|endoftext|>"} {"text":"#include \"..\/bart_builder.h\"\n#include \"..\/problem_definition.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"..\/..\/test_helpers\/bart_test_helper.h\"\n\nclass BARTBuilderTest : public ::testing::Test {\n protected:\n void SetUp ();\n\n \/\/ FE builder test\n template \n void FEBuilderTest ();\n\n \/\/ AQ builder test\n template \n void AQBuilderTest ();\n\n dealii::ParameterHandler prm;\n};\n\nvoid BARTBuilderTest::SetUp () {\n prm.declare_entry(\"have reflective BC\", \"false\",\n dealii::Patterns::Bool(), \"\");\n prm.declare_entry(\"angular quadrature order\", \"4\",\n dealii::Patterns::Integer(), \"\");\n prm.declare_entry(\"angular quadrature name\", \"gl\",\n dealii::Patterns::Selection(\"gl\"), \"\");\n prm.declare_entry(\"number of groups\", \"1\", dealii::Patterns::Integer(), \"\");\n prm.declare_entry(\"transport model\", \"regular\",\n dealii::Patterns::Selection(\"regular|ep\"), \"\");\n\n prm.declare_entry(\"finite element polynomial degree\", \"1\",\n dealii::Patterns::Integer(), \"\");\n prm.declare_entry(\"do nda\", \"true\",\n dealii::Patterns::Bool(), \"\");\n prm.declare_entry(\"ho spatial discretization\", \"\",\n dealii::Patterns::Anything(), \"\");\n prm.declare_entry(\"nda spatial discretization\", \"\",\n dealii::Patterns::Anything(), \"\");\n\n}\n\ntemplate \nvoid BARTBuilderTest::FEBuilderTest () {\n BARTBuilder builders (prm);\n\n \/\/ set values to parameters\n prm.set (\"ho spatial discretization\", \"cfem\");\n prm.set (\"nda spatial discretization\", \"cfem\");\n builders.SetParams (prm);\n std::vector*> fe_ptrs;\n builders.BuildFESpaces (fe_ptrs);\n\n \/\/ testing for FE names\n EXPECT_EQ (fe_ptrs.front()->get_name(),\n \"FE_Q<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_Q<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n\n \/\/ changing FE types\n prm.set (\"ho spatial discretization\", \"dfem\");\n prm.set (\"nda spatial discretization\", \"dfem\");\n builders.SetParams (prm);\n fe_ptrs.clear ();\n builders.BuildFESpaces (fe_ptrs);\n EXPECT_EQ (fe_ptrs.front()->get_name(),\n \"FE_DGQ<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_DGQ<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n\n \/\/ changing NDA FE type\n prm.set (\"nda spatial discretization\", \"cmfd\");\n builders.SetParams (prm);\n fe_ptrs.clear ();\n builders.BuildFESpaces (fe_ptrs);\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_DGQ<\"+dealii::Utilities::int_to_string(dim)+\">(0)\");\n\n \/\/ changing NDA FE type\n prm.set (\"nda spatial discretization\", \"rtk\");\n builders.SetParams (prm);\n fe_ptrs.clear ();\n builders.BuildFESpaces (fe_ptrs);\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_RaviartThomas<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n}\n\nTEST_F (BARTBuilderTest, FEBuilder2DTest) {\n FEBuilderTest<2> ();\n}\n\nTEST_F (BARTBuilderTest, FEBuilder3DTest) {\n FEBuilderTest<3> ();\n}\n\ntemplate \nvoid BARTBuilderTest::AQBuilderTest () {\n BARTBuilder builders (prm);\n std::unique_ptr> aq_ptr;\n std::string aq_name = (dim==1) ? \"gl\" : \"lsgc\";\n prm.set (\"angular quadrature name\", aq_name);\n prm.set (\"angular quadrature order\", \"4\");\n\n \/\/ call builder function to build aq\n builders.BuildAQ (prm, aq_ptr);\n aq_ptr->MakeAQ();\n auto wi = aq_ptr->GetAQWeights();\n auto omega_i = aq_ptr->GetAQDirs();\n\n \/\/ check output\n std::string filename = \"aq_builder_\"+dealii::Utilities::int_to_string(dim)+\"d\";\n btest::GoldTestInit(filename);\n for (unsigned int i=0; i ();\n}\n\nTEST_F (BARTBuilderTest, AQBuilder2DTest) {\n AQBuilderTest<2> ();\n}\n\nTEST_F (BARTBuilderTest, AQBuilder3DTest) {\n AQBuilderTest<3> ();\n}\nFixed aq builder test failure #80#include \"..\/bart_builder.h\"\n#include \"..\/problem_definition.h\"\n\n#include \"gtest\/gtest.h\"\n#include \"..\/..\/test_helpers\/bart_test_helper.h\"\n\nclass BARTBuilderTest : public ::testing::Test {\n protected:\n void SetUp ();\n\n \/\/ FE builder test\n template \n void FEBuilderTest ();\n\n \/\/ AQ builder test\n template \n void AQBuilderTest ();\n\n dealii::ParameterHandler prm;\n};\n\nvoid BARTBuilderTest::SetUp () {\n prm.declare_entry(\"have reflective BC\", \"false\",\n dealii::Patterns::Bool(), \"\");\n prm.declare_entry(\"angular quadrature order\", \"4\",\n dealii::Patterns::Integer(), \"\");\n prm.declare_entry(\"angular quadrature name\", \"gl\",\n dealii::Patterns::Selection(\"gl|lsgc\"), \"\");\n prm.declare_entry(\"number of groups\", \"1\", dealii::Patterns::Integer(), \"\");\n prm.declare_entry(\"transport model\", \"regular\",\n dealii::Patterns::Selection(\"regular|ep\"), \"\");\n\n prm.declare_entry(\"finite element polynomial degree\", \"1\",\n dealii::Patterns::Integer(), \"\");\n prm.declare_entry(\"do nda\", \"true\",\n dealii::Patterns::Bool(), \"\");\n prm.declare_entry(\"ho spatial discretization\", \"\",\n dealii::Patterns::Anything(), \"\");\n prm.declare_entry(\"nda spatial discretization\", \"\",\n dealii::Patterns::Anything(), \"\");\n\n}\n\ntemplate \nvoid BARTBuilderTest::FEBuilderTest () {\n BARTBuilder builders (prm);\n\n \/\/ set values to parameters\n prm.set (\"ho spatial discretization\", \"cfem\");\n prm.set (\"nda spatial discretization\", \"cfem\");\n builders.SetParams (prm);\n std::vector*> fe_ptrs;\n builders.BuildFESpaces (fe_ptrs);\n\n \/\/ testing for FE names\n EXPECT_EQ (fe_ptrs.front()->get_name(),\n \"FE_Q<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_Q<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n\n \/\/ changing FE types\n prm.set (\"ho spatial discretization\", \"dfem\");\n prm.set (\"nda spatial discretization\", \"dfem\");\n builders.SetParams (prm);\n fe_ptrs.clear ();\n builders.BuildFESpaces (fe_ptrs);\n EXPECT_EQ (fe_ptrs.front()->get_name(),\n \"FE_DGQ<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_DGQ<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n\n \/\/ changing NDA FE type\n prm.set (\"nda spatial discretization\", \"cmfd\");\n builders.SetParams (prm);\n fe_ptrs.clear ();\n builders.BuildFESpaces (fe_ptrs);\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_DGQ<\"+dealii::Utilities::int_to_string(dim)+\">(0)\");\n\n \/\/ changing NDA FE type\n prm.set (\"nda spatial discretization\", \"rtk\");\n builders.SetParams (prm);\n fe_ptrs.clear ();\n builders.BuildFESpaces (fe_ptrs);\n EXPECT_EQ (fe_ptrs.back()->get_name(),\n \"FE_RaviartThomas<\"+dealii::Utilities::int_to_string(dim)+\">(1)\");\n}\n\nTEST_F (BARTBuilderTest, FEBuilder2DTest) {\n FEBuilderTest<2> ();\n}\n\nTEST_F (BARTBuilderTest, FEBuilder3DTest) {\n FEBuilderTest<3> ();\n}\n\ntemplate \nvoid BARTBuilderTest::AQBuilderTest () {\n BARTBuilder builders (prm);\n std::unique_ptr> aq_ptr;\n std::string aq_name = (dim==1) ? \"gl\" : \"lsgc\";\n prm.set (\"angular quadrature name\", aq_name);\n prm.set (\"angular quadrature order\", \"4\");\n\n \/\/ call builder function to build aq\n builders.BuildAQ (prm, aq_ptr);\n aq_ptr->MakeAQ();\n auto wi = aq_ptr->GetAQWeights();\n auto omega_i = aq_ptr->GetAQDirs();\n\n \/\/ check output\n std::string filename = \"aq_builder_\"+dealii::Utilities::int_to_string(dim)+\"d\";\n btest::GoldTestInit(filename);\n for (unsigned int i=0; i ();\n}\n\nTEST_F (BARTBuilderTest, AQBuilder2DTest) {\n AQBuilderTest<2> ();\n}\n\nTEST_F (BARTBuilderTest, AQBuilder3DTest) {\n AQBuilderTest<3> ();\n}\n<|endoftext|>"} {"text":"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\/\/ This is a wrapper program that we use for things we launch via glexec,\n\/\/ in order to get around glexec's inability to pass environment variables.\n\/\/ The basic procedure is:\n\/\/ 1) Condor sets up a UNIX domain socket pair\n\/\/ 2) Condor invokes this wrapper via glexec, passing one of the sockets\n\/\/ to the wrapper as it's standard input stream.\n\/\/ 3) A stream of environment variables is sent over the socket pair and\n\/\/ merged into the environment that will be used for the job.\n\/\/ 4) The job's \"real\" standard input FD is sent over the socket pair. The\n\/\/ wrapper's socket end is dup'ed and FD 0 is then set to use the\n\/\/ received FD.\n\/\/ 5) The wrapper's socket end is set close-on-exec, and the wrapper then\n\/\/ exec's the job.\n\n#define _CONDOR_ALLOW_OPEN\n\n#include \"condor_common.h\"\n#include \"MyString.h\"\n#include \"env.h\"\n#include \"fdpass.h\"\n\nstatic char* read_env(int);\nstatic int read_fd(int);\n\nint\nmain(int, char* argv[])\n{\n\tMyString err;\n\n\t\/\/ dup FD 0 since well will later replace FD 0 with the job's stdin\n\t\/\/\n\tint sock_fd = dup(0);\n\tif (sock_fd == -1) {\n\t\terr.sprintf(\"dup error on FD 0: %s\", strerror(errno));\n\t\twrite(0, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\n\t\/\/ set up an Env object that we'll use for the job. we'll initialize\n\t\/\/ it with the environment that glexec prepared for us then merge on\n\t\/\/ top of that the environment that Condor sends us\n\t\/\/\n\tEnv env;\n\tenv.MergeFrom(environ);\n\tchar* env_buf = read_env(sock_fd);\n\tenv.MergeFrom(env_buf);\n\tdelete[] env_buf;\n\n\t\/\/ now receive an FD on our stdin (which is a UNIX domain socket)\n\t\/\/ that we'll use as the job's stdin\n\t\/\/\n\tint job_fd = read_fd(sock_fd);\n\tif (dup2(job_fd, 0) == -1) {\n\t\terr.sprintf(\"dup2 to FD 0 error: %s\", strerror(errno));\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tclose(job_fd);\n\tif (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) {\n\t\terr.sprintf(\"fcntl error setting close-on-exec: %s\",\n\t\t strerror(errno));\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\n\t\/\/ now we can exec the job. for arguments, we shift this wrappers\n\t\/\/ arguments by one. similarly, the job's executable path is taken\n\t\/\/ as our argv[1]\n\t\/\/\n\tchar** envp = env.getStringArray();\n\texecve(argv[1], &argv[1], envp);\n\terr.sprintf(\"execve error: %s\", strerror(errno));\n\twrite(sock_fd, err.Value(), err.Length() + 1);\n\texit(1);\n}\n\nstatic char*\nread_env(int sock_fd)\n{\n\tMyString err;\n\tint env_len;\n\tif (fread(&env_len, sizeof(env_len), 1, stdin) != 1) {\n\t\tif (feof(stdin)) {\n\t\t\terr = \"unexpected EOF reading env size\";\n\t\t}\n\t\telse {\n\t\t\terr.sprintf(\"fread error reading env size: %s\",\n\t\t\t strerror(errno));\n\t\t}\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tif (env_len <= 0) {\n\t\terr.sprintf(\"invalid env size %d read from stdin\", env_len);\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tchar* env_buf = new char[env_len];\n\tif (env_buf == NULL) {\n\t\terr.sprintf(\"failure to allocate %d bytes\", env_len);\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tif (fread(env_buf, env_len, 1, stdin) != 1) {\n\t\tif (feof(stdin)) {\n\t\t\terr = \"unexpected EOF reading env\";\n\t\t}\n\t\telse {\n\t\t\terr.sprintf(\"fread error reading env: %s\",\n\t\t\t strerror(errno));\n\t\t}\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\treturn env_buf;\n}\n\nstatic int\nread_fd(int sock_fd)\n{\n\tMyString err;\n\tint flag;\n\tif (fread(&flag, sizeof(flag), 1, stdin) != 1) {\n\t\tif (feof(stdin)) {\n\t\t\terr = \"unexpected EOF reading FD flag\";\n\t\t}\n\t\telse {\n\t\t\terr.sprintf(\"fread error reading FD flag: %s\",\n\t\t\t strerror(errno));\n\t\t}\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tint fd;\n\tif (flag) {\n\t\tfd = fdpass_recv(sock_fd);\n\t\tif (fd == -1) {\n\t\t\terr.sprintf(\"fdpass_recv failed\\n\");\n\t\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\t\texit(1);\n\t\t}\n\t}\n\telse {\n\t\tfd = open(\"\/dev\/null\", O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\terr.sprintf(\"error opening \/dev\/null: %s\",\n\t\t\t strerror(errno));\n\t\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\t\texit(1);\n\t\t}\n\t}\n\treturn fd;\n}\nRevert \"Changed environment precedence in condor_glexec_wrapper\"\/***************************************************************\n *\n * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,\n * University of Wisconsin-Madison, WI.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\"); you\n * may not use this file except in compliance with the License. You may\n * obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n ***************************************************************\/\n\n\/\/ This is a wrapper program that we use for things we launch via glexec,\n\/\/ in order to get around glexec's inability to pass environment variables.\n\/\/ The basic procedure is:\n\/\/ 1) Condor sets up a UNIX domain socket pair\n\/\/ 2) Condor invokes this wrapper via glexec, passing one of the sockets\n\/\/ to the wrapper as it's standard input stream.\n\/\/ 3) A stream of environment variables is sent over the socket pair and\n\/\/ merged into the environment that will be used for the job.\n\/\/ 4) The job's \"real\" standard input FD is sent over the socket pair. The\n\/\/ wrapper's socket end is dup'ed and FD 0 is then set to use the\n\/\/ received FD.\n\/\/ 5) The wrapper's socket end is set close-on-exec, and the wrapper then\n\/\/ exec's the job.\n\n#define _CONDOR_ALLOW_OPEN\n\n#include \"condor_common.h\"\n#include \"MyString.h\"\n#include \"env.h\"\n#include \"fdpass.h\"\n\nstatic char* read_env(int);\nstatic int read_fd(int);\n\nint\nmain(int, char* argv[])\n{\n\tMyString err;\n\n\t\/\/ dup FD 0 since well will later replace FD 0 with the job's stdin\n\t\/\/\n\tint sock_fd = dup(0);\n\tif (sock_fd == -1) {\n\t\terr.sprintf(\"dup error on FD 0: %s\", strerror(errno));\n\t\twrite(0, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\n\t\/\/ set up an Env object that we'll use for the job. we'll initialize\n\t\/\/ it with the environment that Condor sends us then merge on top of\n\t\/\/ that the environment that glexec prepared for us\n\t\/\/\n\tEnv env;\n\tchar* env_buf = read_env(sock_fd);\n\tenv.MergeFrom(env_buf);\n\tenv.MergeFrom(environ);\n\tdelete[] env_buf;\n\n\t\/\/ now receive an FD on our stdin (which is a UNIX domain socket)\n\t\/\/ that we'll use as the job's stdin\n\t\/\/\n\tint job_fd = read_fd(sock_fd);\n\tif (dup2(job_fd, 0) == -1) {\n\t\terr.sprintf(\"dup2 to FD 0 error: %s\", strerror(errno));\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tclose(job_fd);\n\tif (fcntl(sock_fd, F_SETFD, FD_CLOEXEC) == -1) {\n\t\terr.sprintf(\"fcntl error setting close-on-exec: %s\",\n\t\t strerror(errno));\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\n\t\/\/ now we can exec the job. for arguments, we shift this wrappers\n\t\/\/ arguments by one. similarly, the job's executable path is taken\n\t\/\/ as our argv[1]\n\t\/\/\n\tchar** envp = env.getStringArray();\n\texecve(argv[1], &argv[1], envp);\n\terr.sprintf(\"execve error: %s\", strerror(errno));\n\twrite(sock_fd, err.Value(), err.Length() + 1);\n\texit(1);\n}\n\nstatic char*\nread_env(int sock_fd)\n{\n\tMyString err;\n\tint env_len;\n\tif (fread(&env_len, sizeof(env_len), 1, stdin) != 1) {\n\t\tif (feof(stdin)) {\n\t\t\terr = \"unexpected EOF reading env size\";\n\t\t}\n\t\telse {\n\t\t\terr.sprintf(\"fread error reading env size: %s\",\n\t\t\t strerror(errno));\n\t\t}\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tif (env_len <= 0) {\n\t\terr.sprintf(\"invalid env size %d read from stdin\", env_len);\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tchar* env_buf = new char[env_len];\n\tif (env_buf == NULL) {\n\t\terr.sprintf(\"failure to allocate %d bytes\", env_len);\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tif (fread(env_buf, env_len, 1, stdin) != 1) {\n\t\tif (feof(stdin)) {\n\t\t\terr = \"unexpected EOF reading env\";\n\t\t}\n\t\telse {\n\t\t\terr.sprintf(\"fread error reading env: %s\",\n\t\t\t strerror(errno));\n\t\t}\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\treturn env_buf;\n}\n\nstatic int\nread_fd(int sock_fd)\n{\n\tMyString err;\n\tint flag;\n\tif (fread(&flag, sizeof(flag), 1, stdin) != 1) {\n\t\tif (feof(stdin)) {\n\t\t\terr = \"unexpected EOF reading FD flag\";\n\t\t}\n\t\telse {\n\t\t\terr.sprintf(\"fread error reading FD flag: %s\",\n\t\t\t strerror(errno));\n\t\t}\n\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\texit(1);\n\t}\n\tint fd;\n\tif (flag) {\n\t\tfd = fdpass_recv(sock_fd);\n\t\tif (fd == -1) {\n\t\t\terr.sprintf(\"fdpass_recv failed\\n\");\n\t\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\t\texit(1);\n\t\t}\n\t}\n\telse {\n\t\tfd = open(\"\/dev\/null\", O_RDONLY);\n\t\tif (fd == -1) {\n\t\t\terr.sprintf(\"error opening \/dev\/null: %s\",\n\t\t\t strerror(errno));\n\t\t\twrite(sock_fd, err.Value(), err.Length() + 1);\n\t\t\texit(1);\n\t\t}\n\t}\n\treturn fd;\n}\n<|endoftext|>"} {"text":"#ifndef WEAKPOINTER_HPP\n#define WEAKPOINTER_HPP\n\n#include \"List.hpp\"\n\nnamespace org_pqrs_Karabiner {\n\n#define DECLARE_WEAKPOINTER(TYPENAME) \\\n class TYPENAME; \\\n class WeakPointerManager_##TYPENAME final { \\\n public: \\\n \/* Call WeakPointerManager::add in constructor. *\/ \\\n \/* For example: *\/ \\\n \\\n \/* ----------------------------------------------- *\/ \\\n \/* DECLARE_WEAKPOINTER(TestClass); *\/ \\\n \/* *\/ \\\n \/* class TestClass final { *\/ \\\n \/* public: *\/ \\\n \/* TestClass(void) { *\/ \\\n \/* WeakPointerManager_TestClass::add(this); *\/ \\\n \/* } *\/ \\\n \/* ~TestClass(void) { *\/ \\\n \/* WeakPointerManager_TestClass::remove(this); *\/ \\\n \/* } *\/ \\\n \/* }; *\/ \\\n \/* ----------------------------------------------- *\/ \\\n \\\n \/* Note: *\/ \\\n \/* DO NOT call WeakPointerManager::add twice with same pointer. *\/ \\\n \/* If you call WeakPointerManager::add twice, *\/ \\\n \/* WeakPointerManager::expired will return false with deleted pointer. *\/ \\\n \\\n static void add(const TYPENAME* p) { \\\n auto item = new WeakPointerManagerItem(p); \\\n if (item) { \\\n list_.push_back(item); \\\n } \\\n } \\\n \\\n static void remove(const TYPENAME* pointer) { \\\n for (WeakPointerManagerItem* p = static_cast(list_.safe_front()); \\\n p; \\\n p = static_cast(p->getnext())) { \\\n if (p->pointer == pointer) { \\\n list_.erase_and_delete(p); \\\n break; \\\n } \\\n } \\\n } \\\n \\\n static bool expired(const TYPENAME* pointer) { \\\n for (WeakPointerManagerItem* p = static_cast(list_.safe_front()); \\\n p; \\\n p = static_cast(p->getnext())) { \\\n if (p->pointer == pointer) { \\\n return false; \\\n } \\\n } \\\n return true; \\\n } \\\n \\\n private: \\\n class WeakPointerManagerItem : public List::Item { \\\n public: \\\n WeakPointerManagerItem(const TYPENAME* p) : pointer(p) {} \\\n virtual ~WeakPointerManagerItem(void) {} \\\n \\\n const TYPENAME* pointer; \\\n }; \\\n \\\n static List list_; \\\n }; \\\n \\\n class WeakPointer_##TYPENAME final { \\\n public: \\\n WeakPointer_##TYPENAME(TYPENAME* p) : pointer_(p) {} \\\n bool expired(void) const { return WeakPointerManager_##TYPENAME::expired(pointer_); } \\\n \\\n TYPENAME* operator->(void) const { return pointer_; } \\\n TYPENAME* get(void) const { return pointer_; } \\\n \\\n private: \\\n TYPENAME* pointer_; \\\n };\n\n#define DEFINE_WEAKPOINTER(TYPENAME) \\\n List WeakPointerManager_##TYPENAME::list_;\n\n#define DEFINE_WEAKPOINTER_IN_CLASS(CLASS, TYPENAME) \\\n List CLASS::WeakPointerManager_##TYPENAME::list_;\n}\n\n#endif\nimproved WeakPointer for reuse address#ifndef WEAKPOINTER_HPP\n#define WEAKPOINTER_HPP\n\n#include \"List.hpp\"\n\nnamespace org_pqrs_Karabiner {\n\n#define DECLARE_WEAKPOINTER(TYPENAME) \\\n class TYPENAME; \\\n class WeakPointerManager_##TYPENAME final { \\\n public: \\\n \/* Call WeakPointerManager::add in constructor. *\/ \\\n \/* For example: *\/ \\\n \\\n \/* ----------------------------------------------- *\/ \\\n \/* DECLARE_WEAKPOINTER(TestClass); *\/ \\\n \/* *\/ \\\n \/* class TestClass final { *\/ \\\n \/* public: *\/ \\\n \/* TestClass(void) { *\/ \\\n \/* WeakPointerManager_TestClass::add(this); *\/ \\\n \/* } *\/ \\\n \/* ~TestClass(void) { *\/ \\\n \/* WeakPointerManager_TestClass::remove(this); *\/ \\\n \/* } *\/ \\\n \/* }; *\/ \\\n \/* ----------------------------------------------- *\/ \\\n \\\n \/* Note: *\/ \\\n \/* DO NOT call WeakPointerManager::add twice with same pointer. *\/ \\\n \/* If you call WeakPointerManager::add twice, *\/ \\\n \/* WeakPointerManager::expired will return false with deleted pointer. *\/ \\\n \\\n static void add(const TYPENAME* p) { \\\n auto item = new WeakPointerManagerItem(p, ++lastid_); \\\n if (item) { \\\n list_.push_back(item); \\\n } \\\n } \\\n \\\n static void remove(const TYPENAME* pointer) { \\\n for (WeakPointerManagerItem* p = static_cast(list_.safe_front()); \\\n p; \\\n p = static_cast(p->getnext())) { \\\n if (p->pointer == pointer) { \\\n list_.erase_and_delete(p); \\\n break; \\\n } \\\n } \\\n } \\\n \\\n static bool expired(const TYPENAME* pointer, int id) { \\\n for (WeakPointerManagerItem* p = static_cast(list_.safe_front()); \\\n p; \\\n p = static_cast(p->getnext())) { \\\n if (p->pointer == pointer && p->id == id) { \\\n return false; \\\n } \\\n } \\\n return true; \\\n } \\\n \\\n static int getid(const TYPENAME* pointer) { \\\n for (WeakPointerManagerItem* p = static_cast(list_.safe_front()); \\\n p; \\\n p = static_cast(p->getnext())) { \\\n if (p->pointer == pointer) { \\\n return p->id; \\\n } \\\n } \\\n return -1; \\\n } \\\n \\\n private: \\\n class WeakPointerManagerItem final : public List::Item { \\\n public: \\\n WeakPointerManagerItem(const TYPENAME* p, int c) : pointer(p), id(c) {} \\\n ~WeakPointerManagerItem(void) {} \\\n \\\n const TYPENAME* pointer; \\\n int id; \\\n }; \\\n \\\n static List list_; \\\n static int lastid_; \\\n }; \\\n \\\n class WeakPointer_##TYPENAME final { \\\n public: \\\n WeakPointer_##TYPENAME(TYPENAME* p) : pointer_(p), \\\n id_(WeakPointerManager_##TYPENAME::getid(p)) {} \\\n bool expired(void) const { return WeakPointerManager_##TYPENAME::expired(pointer_, id_); } \\\n \\\n TYPENAME* operator->(void) const { return pointer_; } \\\n TYPENAME* get(void) const { return pointer_; } \\\n \\\n bool operator==(WeakPointer_##TYPENAME other) const { \\\n return pointer_ == other.pointer_ && id_ == other.id_; \\\n } \\\n \\\n private: \\\n TYPENAME* pointer_; \\\n int id_; \\\n };\n\n#define DEFINE_WEAKPOINTER(TYPENAME) \\\n List WeakPointerManager_##TYPENAME::list_; \\\n int WeakPointerManager_##TYPENAME::lastid_ = 0;\n\n#define DEFINE_WEAKPOINTER_IN_CLASS(CLASS, TYPENAME) \\\n List CLASS::WeakPointerManager_##TYPENAME::list_; \\\n int CLASS::WeakPointerManager_##TYPENAME::lastid_ = 0;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * FilePath.cpp\n *\n * Copyright (C) 2020 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement\n * with RStudio, then this program is licensed to you under the following terms:\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \n\n#include \n\nnamespace rstudio {\nnamespace core {\n\nTEST_CASE(\"Empty File Path tests\")\n{\n SECTION(\"Construction\")\n {\n FilePath f;\n CHECK(f.getAbsolutePath().empty());\n }\n\n SECTION(\"Comparison (equal, true)\")\n {\n FilePath f1, f2;\n\n CHECK(f1 == f2);\n CHECK(f2 == f1);\n CHECK(f1 == f1);\n }\n\n SECTION(\"Comparison (equal, false)\")\n {\n FilePath f1, f2(\"\/a\/different\/path\");\n\n CHECK_FALSE(f1 == f2);\n CHECK_FALSE(f2 == f1);\n }\n\n SECTION(\"Comparison (inequal, false)\")\n {\n FilePath f1, f2;\n\n CHECK_FALSE(f1 != f2);\n CHECK_FALSE(f2 != f1);\n CHECK_FALSE(f1 != f1);\n }\n\n SECTION(\"Comparison (inequal, true)\")\n {\n FilePath f1, f2(\"\/a\/different\/path\");\n\n CHECK(f1 != f2);\n CHECK(f2 != f1);\n }\n\n SECTION(\"Comparison (lt)\")\n {\n FilePath f1, f2(\"\/a\/different\/path\");\n\n CHECK(f1 < f2);\n CHECK_FALSE(f2 < f1);\n }\n\n SECTION(\"Retrieval methods\")\n {\n FilePath f;\n std::vector children;\n\n CHECK_FALSE(f.exists());\n CHECK(f.getAbsolutePath().empty());\n CHECK(f.getAbsolutePathNative().empty());\n#ifdef _WIN32\n CHECK(f.getAbsolutePathW().empty());\n#endif\n CHECK(f.getCanonicalPath().empty());\n CHECK(f.getChildren(children)); \/\/ Returns error.\n CHECK(children.empty());\n CHECK(f.getExtension().empty());\n CHECK(f.getExtensionLowerCase().empty());\n CHECK(f.getFilename().empty());\n CHECK(f.getLastWriteTime() == 0);\n CHECK(f.getLexicallyNormalPath().empty());\n CHECK(f.getMimeContentType() == \"text\/plain\"); \/\/ text\/plain is the default.\n CHECK(f.getParent() == f); \/\/ Error on getting the parent, so self should be returned.\n CHECK(f.getRelativePath(FilePath(\"\/a\/parent\/path\")) == \"\");\n CHECK(f.getSize() == 0);\n CHECK(f.getSizeRecursive() == 0);\n CHECK(f.getStem().empty());\n CHECK_FALSE(f.hasExtension(\"ext\"));\n CHECK_FALSE(f.hasTextMimeType()); \/\/ has text mime type sets the default mime type as \"application\/octet-stream\"\n CHECK_FALSE(f.isDirectory());\n CHECK(f.isEmpty());\n CHECK_FALSE(f.isHidden());\n CHECK_FALSE(f.isJunction());\n CHECK_FALSE(f.isRegularFile());\n CHECK_FALSE(f.isSymlink());\n CHECK(f.isWithin(f));\n CHECK_FALSE(f.isWithin(FilePath(\"\/some\/path\")));\n }\n}\n\n} \/\/ namespace core\n} \/\/ namespace rstudio\nclean up clang tidy warning about str.empty\/*\n * FilePath.cpp\n *\n * Copyright (C) 2020 by RStudio, PBC\n *\n * Unless you have received this program directly from RStudio pursuant to the terms of a commercial license agreement\n * with RStudio, then this program is licensed to you under the following terms:\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n * documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the\n * rights to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the\n * Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR\n * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\n *\/\n\n#include \n\n#include \n\nnamespace rstudio {\nnamespace core {\n\nTEST_CASE(\"Empty File Path tests\")\n{\n SECTION(\"Construction\")\n {\n FilePath f;\n CHECK(f.getAbsolutePath().empty());\n }\n\n SECTION(\"Comparison (equal, true)\")\n {\n FilePath f1, f2;\n\n CHECK(f1 == f2);\n CHECK(f2 == f1);\n CHECK(f1 == f1);\n }\n\n SECTION(\"Comparison (equal, false)\")\n {\n FilePath f1, f2(\"\/a\/different\/path\");\n\n CHECK_FALSE(f1 == f2);\n CHECK_FALSE(f2 == f1);\n }\n\n SECTION(\"Comparison (inequal, false)\")\n {\n FilePath f1, f2;\n\n CHECK_FALSE(f1 != f2);\n CHECK_FALSE(f2 != f1);\n CHECK_FALSE(f1 != f1);\n }\n\n SECTION(\"Comparison (inequal, true)\")\n {\n FilePath f1, f2(\"\/a\/different\/path\");\n\n CHECK(f1 != f2);\n CHECK(f2 != f1);\n }\n\n SECTION(\"Comparison (lt)\")\n {\n FilePath f1, f2(\"\/a\/different\/path\");\n\n CHECK(f1 < f2);\n CHECK_FALSE(f2 < f1);\n }\n\n SECTION(\"Retrieval methods\")\n {\n FilePath f;\n std::vector children;\n\n CHECK_FALSE(f.exists());\n CHECK(f.getAbsolutePath().empty());\n CHECK(f.getAbsolutePathNative().empty());\n#ifdef _WIN32\n CHECK(f.getAbsolutePathW().empty());\n#endif\n CHECK(f.getCanonicalPath().empty());\n CHECK(f.getChildren(children)); \/\/ Returns error.\n CHECK(children.empty());\n CHECK(f.getExtension().empty());\n CHECK(f.getExtensionLowerCase().empty());\n CHECK(f.getFilename().empty());\n CHECK(f.getLastWriteTime() == 0);\n CHECK(f.getLexicallyNormalPath().empty());\n CHECK(f.getMimeContentType() == \"text\/plain\"); \/\/ text\/plain is the default.\n CHECK(f.getParent() == f); \/\/ Error on getting the parent, so self should be returned.\n CHECK(f.getRelativePath(FilePath(\"\/a\/parent\/path\")).empty());\n CHECK(f.getSize() == 0);\n CHECK(f.getSizeRecursive() == 0);\n CHECK(f.getStem().empty());\n CHECK_FALSE(f.hasExtension(\"ext\"));\n CHECK_FALSE(f.hasTextMimeType()); \/\/ has text mime type sets the default mime type as \"application\/octet-stream\"\n CHECK_FALSE(f.isDirectory());\n CHECK(f.isEmpty());\n CHECK_FALSE(f.isHidden());\n CHECK_FALSE(f.isJunction());\n CHECK_FALSE(f.isRegularFile());\n CHECK_FALSE(f.isSymlink());\n CHECK(f.isWithin(f));\n CHECK_FALSE(f.isWithin(FilePath(\"\/some\/path\")));\n }\n}\n\n} \/\/ namespace core\n} \/\/ namespace rstudio\n<|endoftext|>"} {"text":"\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#include \"precompiled.hpp\"\n#include \"static\/main_config.hpp\"\n#include \"static\/async_logger.hpp\"\n#include \"static\/timer_driver.hpp\"\n#include \"static\/network_driver.hpp\"\n#include \"utilities.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace poseidon;\n\nnamespace {\n\n[[noreturn]]\nint\ndo_print_help_and_exit(const char* self)\n {\n ::printf(\n\/\/ 1 2 3 4 5 6 7 |\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" R\"'''''''''''''''(\nUsage: %s [OPTIONS] [[--] DIRECTORY]\n\n -d daemonize\n -h show help message then exit\n -V show version information then exit\n -v enable verbose mode\n\nDaemonization, if requested, is performed after loading config files. Early\nfailues are printed to standard error.\n\nIf DIRECTORY is specified, the working directory is switched there before\ndoing everything else.\n\nVisit the homepage at <%s>.\nReport bugs to <%s>.\n)'''''''''''''''\" \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"+1,\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\/\/ 1 2 3 4 5 6 7 |\n self,\n PACKAGE_URL,\n PACKAGE_BUGREPORT);\n\n ::fflush(stdout);\n ::quick_exit(0);\n }\n\nconst char*\ndo_tell_build_time()\n {\n static char s_time_str[64];\n if(ROCKET_EXPECT(s_time_str[0]))\n return s_time_str;\n\n \/\/ Convert the build time to ISO 8601 format.\n ::tm tr;\n ::std::memset(&tr, 0, sizeof(tr));\n ::strptime(__DATE__ \" \" __TIME__, \"%b %d %Y %H:%M:%S\", &tr);\n ::strftime(s_time_str, sizeof(s_time_str), \"%Y-%m-%d %H:%M:%S\", &tr);\n return s_time_str;\n }\n\n[[noreturn]]\nint\ndo_print_version_and_exit()\n {\n ::printf(\n\/\/ 1 2 3 4 5 6 7 |\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" R\"'''''''''''''''(\n%s [built on %s]\n\nVisit the homepage at <%s>.\nReport bugs to <%s>.\n)'''''''''''''''\" \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"+1,\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\/\/ 1 2 3 4 5 6 7 |\n PACKAGE_STRING, do_tell_build_time(),\n PACKAGE_URL,\n PACKAGE_BUGREPORT);\n\n ::fflush(stdout);\n ::quick_exit(0);\n }\n\n\/\/ We want to detect Ctrl-C.\n::std::atomic exit_now;\n\nvoid\ndo_trap_exit_signal(int sig)\nnoexcept\n {\n \/\/ Trap Ctrl-C. Failure to set the signal handler is ignored.\n struct ::sigaction sigx = { };\n sigx.sa_handler = [](int) { exit_now = 1; };\n ::sigaction(sig, &sigx, nullptr);\n }\n\n\/\/ Define command-line options here.\nstruct Command_Line_Options\n {\n \/\/ options\n bool daemonize = false;\n bool verbose = false;\n\n \/\/ non-options\n cow_string cd_here;\n };\n\n\/\/ This may also be automatic objects. It is declared here for convenience.\nCommand_Line_Options cmdline;\n\n\/\/ These are process exit status codes.\nenum Exit_Code : uint8_t\n {\n exit_success = 0,\n exit_system_error = 1,\n exit_invalid_argument = 2,\n };\n\n[[noreturn]]\nint\ndo_exit(Exit_Code code, const char* fmt = nullptr, ...)\nnoexcept\n {\n \/\/ Output the string to standard error.\n if(fmt) {\n ::va_list ap;\n va_start(ap, fmt);\n ::vfprintf(stderr, fmt, ap);\n va_end(ap);\n }\n\n \/\/ Perform fast exit.\n ::fflush(nullptr);\n ::quick_exit(static_cast(code));\n }\n\nvoid\ndo_parse_command_line(int argc, char** argv)\n {\n bool help = false;\n bool version = false;\n\n opt daemonize;\n opt verbose;\n opt cd_here;\n\n \/\/ Check for some common options before calling `getopt()`.\n if(argc > 1) {\n if(::strcmp(argv[1], \"--help\") == 0)\n do_print_help_and_exit(argv[0]);\n\n if(::strcmp(argv[1], \"--version\") == 0)\n do_print_version_and_exit();\n }\n\n \/\/ Parse command-line options.\n int ch;\n while((ch = ::getopt(argc, argv, \"+dhVv\")) != -1) {\n \/\/ Identify a single option.\n switch(ch) {\n case 'd':\n daemonize = true;\n continue;\n\n case 'h':\n help = true;\n continue;\n\n case 'V':\n version = true;\n continue;\n\n case 'v':\n verbose = true;\n continue;\n }\n\n \/\/ `getopt()` will have written an error message to standard error.\n do_exit(exit_invalid_argument, \"Try `%s -h` for help.\\n\",\n argv[0]);\n }\n\n \/\/ Check for early exit conditions.\n if(help)\n do_print_help_and_exit(argv[0]);\n\n if(version)\n do_print_version_and_exit();\n\n \/\/ If more arguments follow, they denote the working directory.\n if(argc - optind > 1)\n do_exit(exit_invalid_argument, \"%s: too many arguments -- '%s'\\n\"\n \"Try `%s -h` for help.\\n\",\n argv[0], argv[optind+1],\n argv[0]);\n\n if(argc - optind > 0)\n cd_here = cow_string(argv[optind]);\n\n \/\/ Daemonization mode is off by default.\n if(daemonize)\n cmdline.daemonize = *daemonize;\n\n \/\/ Verbose mode is off by default.\n if(verbose)\n cmdline.verbose = *verbose;\n\n \/\/ The default working directory is empty which means 'do not switch'.\n if(cd_here)\n cmdline.cd_here = ::std::move(*cd_here);\n }\n\n} \/\/ namespace\n\nint\nmain(int argc, char** argv)\n try {\n \/\/ Select the C locale.\n \/\/ UTF-8 is required for wide-oriented standard streams.\n ::setlocale(LC_ALL, \"C.UTF-8\");\n\n \/\/ Note that this function shall not return in case of errors.\n do_parse_command_line(argc, argv);\n\n \/\/ Set current working directory if one is specified.\n if(cmdline.cd_here.size())\n if(::chdir(cmdline.cd_here.safe_c_str()) != 0)\n POSEIDON_THROW(\"could not set working directory to '$2'\\n\"\n \"[`chdir()` failed: $1]\",\n noadl::format_errno(errno), cmdline.cd_here);\n\n \/\/ Load 'main.conf' before daemonization, so any earlier failures are\n \/\/ visible to the user.\n Main_Config::reload();\n Async_Logger::reload();\n Network_Driver::reload();\n\n \/\/ Daemonize the process before entering modal loop.\n if(cmdline.daemonize)\n if(::daemon(1, 0) != 0)\n POSEIDON_THROW(\"could not daemonize process\\n\"\n \"[`chdir()` failed: $1]\",\n noadl::format_errno(errno));\n\n \/\/ Set name of the main thread. Failure to set the name is ignored.\n ::pthread_setname_np(::pthread_self(), \"poseidon\");\n\n \/\/ Disable cancellation for safety. Failure to set the cancel state is ignored.\n ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);\n\n \/\/ Trap exit signals. Failure to set signal handlers is ignored.\n \/\/ This also makes stdio functions fail immediately.\n do_trap_exit_signal(SIGINT);\n do_trap_exit_signal(SIGTERM);\n do_trap_exit_signal(SIGHUP);\n\n \/\/ Ignore `SIGPIPE` for good.\n ::signal(SIGPIPE, SIG_IGN);\n\n \/\/ Start daemon threads.\n Async_Logger::start();\n Timer_Driver::start();\n Network_Driver::start();\n\n sleep(10000);\n do_exit(exit_success, \"interrupt\\n\");\n }\n catch(exception& stdex) {\n \/\/ Print the message in `stdex`. There isn't much we can do.\n do_exit(exit_system_error, \"%s\\n[exception class `%s`]\\n\",\n stdex.what(), typeid(stdex).name());\n }\nmain: Add startup log\/\/ This file is part of Poseidon.\n\/\/ Copyleft 2020, LH_Mouse. All wrongs reserved.\n\n#include \"precompiled.hpp\"\n#include \"static\/main_config.hpp\"\n#include \"static\/async_logger.hpp\"\n#include \"static\/timer_driver.hpp\"\n#include \"static\/network_driver.hpp\"\n#include \"utilities.hpp\"\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace poseidon;\n\nnamespace {\n\n[[noreturn]]\nint\ndo_print_help_and_exit(const char* self)\n {\n ::printf(\n\/\/ 1 2 3 4 5 6 7 |\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" R\"'''''''''''''''(\nUsage: %s [OPTIONS] [[--] DIRECTORY]\n\n -d daemonize\n -h show help message then exit\n -V show version information then exit\n -v enable verbose mode\n\nDaemonization, if requested, is performed after loading config files. Early\nfailues are printed to standard error.\n\nIf DIRECTORY is specified, the working directory is switched there before\ndoing everything else.\n\nVisit the homepage at <%s>.\nReport bugs to <%s>.\n)'''''''''''''''\" \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"+1,\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\/\/ 1 2 3 4 5 6 7 |\n self,\n PACKAGE_URL,\n PACKAGE_BUGREPORT);\n\n ::fflush(stdout);\n ::quick_exit(0);\n }\n\nconst char*\ndo_tell_build_time()\n {\n static char s_time_str[64];\n if(ROCKET_EXPECT(s_time_str[0]))\n return s_time_str;\n\n \/\/ Convert the build time to ISO 8601 format.\n ::tm tr;\n ::std::memset(&tr, 0, sizeof(tr));\n ::strptime(__DATE__ \" \" __TIME__, \"%b %d %Y %H:%M:%S\", &tr);\n ::strftime(s_time_str, sizeof(s_time_str), \"%Y-%m-%d %H:%M:%S\", &tr);\n return s_time_str;\n }\n\n[[noreturn]]\nint\ndo_print_version_and_exit()\n {\n ::printf(\n\/\/ 1 2 3 4 5 6 7 |\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\" R\"'''''''''''''''(\n%s [built on %s]\n\nVisit the homepage at <%s>.\nReport bugs to <%s>.\n)'''''''''''''''\" \"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"\"+1,\n\/\/ 3456789012345678901234567890123456789012345678901234567890123456789012345|\n\/\/ 1 2 3 4 5 6 7 |\n PACKAGE_STRING, do_tell_build_time(),\n PACKAGE_URL,\n PACKAGE_BUGREPORT);\n\n ::fflush(stdout);\n ::quick_exit(0);\n }\n\n\/\/ We want to detect Ctrl-C.\n::std::atomic exit_now;\n\nvoid\ndo_trap_exit_signal(int sig)\nnoexcept\n {\n \/\/ Trap Ctrl-C. Failure to set the signal handler is ignored.\n struct ::sigaction sigx = { };\n sigx.sa_handler = [](int) { exit_now = 1; };\n ::sigaction(sig, &sigx, nullptr);\n }\n\n\/\/ Define command-line options here.\nstruct Command_Line_Options\n {\n \/\/ options\n bool daemonize = false;\n bool verbose = false;\n\n \/\/ non-options\n cow_string cd_here;\n };\n\n\/\/ This may also be automatic objects. It is declared here for convenience.\nCommand_Line_Options cmdline;\n\n\/\/ These are process exit status codes.\nenum Exit_Code : uint8_t\n {\n exit_success = 0,\n exit_system_error = 1,\n exit_invalid_argument = 2,\n };\n\n[[noreturn]]\nint\ndo_exit(Exit_Code code, const char* fmt = nullptr, ...)\nnoexcept\n {\n \/\/ Output the string to standard error.\n if(fmt) {\n ::va_list ap;\n va_start(ap, fmt);\n ::vfprintf(stderr, fmt, ap);\n va_end(ap);\n }\n\n \/\/ Perform fast exit.\n ::fflush(nullptr);\n ::quick_exit(static_cast(code));\n }\n\nvoid\ndo_parse_command_line(int argc, char** argv)\n {\n bool help = false;\n bool version = false;\n\n opt daemonize;\n opt verbose;\n opt cd_here;\n\n \/\/ Check for some common options before calling `getopt()`.\n if(argc > 1) {\n if(::strcmp(argv[1], \"--help\") == 0)\n do_print_help_and_exit(argv[0]);\n\n if(::strcmp(argv[1], \"--version\") == 0)\n do_print_version_and_exit();\n }\n\n \/\/ Parse command-line options.\n int ch;\n while((ch = ::getopt(argc, argv, \"+dhVv\")) != -1) {\n \/\/ Identify a single option.\n switch(ch) {\n case 'd':\n daemonize = true;\n continue;\n\n case 'h':\n help = true;\n continue;\n\n case 'V':\n version = true;\n continue;\n\n case 'v':\n verbose = true;\n continue;\n }\n\n \/\/ `getopt()` will have written an error message to standard error.\n do_exit(exit_invalid_argument, \"Try `%s -h` for help.\\n\",\n argv[0]);\n }\n\n \/\/ Check for early exit conditions.\n if(help)\n do_print_help_and_exit(argv[0]);\n\n if(version)\n do_print_version_and_exit();\n\n \/\/ If more arguments follow, they denote the working directory.\n if(argc - optind > 1)\n do_exit(exit_invalid_argument, \"%s: too many arguments -- '%s'\\n\"\n \"Try `%s -h` for help.\\n\",\n argv[0], argv[optind+1],\n argv[0]);\n\n if(argc - optind > 0)\n cd_here = cow_string(argv[optind]);\n\n \/\/ Daemonization mode is off by default.\n if(daemonize)\n cmdline.daemonize = *daemonize;\n\n \/\/ Verbose mode is off by default.\n if(verbose)\n cmdline.verbose = *verbose;\n\n \/\/ The default working directory is empty which means 'do not switch'.\n if(cd_here)\n cmdline.cd_here = ::std::move(*cd_here);\n }\n\n} \/\/ namespace\n\nint\nmain(int argc, char** argv)\n try {\n \/\/ Select the C locale.\n \/\/ UTF-8 is required for wide-oriented standard streams.\n ::setlocale(LC_ALL, \"C.UTF-8\");\n\n \/\/ Note that this function shall not return in case of errors.\n do_parse_command_line(argc, argv);\n\n \/\/ Set current working directory if one is specified.\n if(cmdline.cd_here.size())\n if(::chdir(cmdline.cd_here.safe_c_str()) != 0)\n POSEIDON_THROW(\"could not set working directory to '$2'\\n\"\n \"[`chdir()` failed: $1]\",\n noadl::format_errno(errno), cmdline.cd_here);\n\n \/\/ Load 'main.conf' before daemonization, so any earlier failures are\n \/\/ visible to the user.\n Main_Config::reload();\n Async_Logger::reload();\n Network_Driver::reload();\n\n \/\/ Daemonize the process before entering modal loop.\n if(cmdline.daemonize)\n if(::daemon(1, 0) != 0)\n POSEIDON_THROW(\"could not daemonize process\\n\"\n \"[`chdir()` failed: $1]\",\n noadl::format_errno(errno));\n\n \/\/ Set name of the main thread. Failure to set the name is ignored.\n ::pthread_setname_np(::pthread_self(), \"poseidon\");\n\n \/\/ Disable cancellation for safety. Failure to set the cancel state is ignored.\n ::pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);\n\n \/\/ Trap exit signals. Failure to set signal handlers is ignored.\n \/\/ This also makes stdio functions fail immediately.\n do_trap_exit_signal(SIGINT);\n do_trap_exit_signal(SIGTERM);\n do_trap_exit_signal(SIGHUP);\n\n \/\/ Ignore `SIGPIPE` for good.\n ::signal(SIGPIPE, SIG_IGN);\n\n \/\/ Start daemon threads.\n Async_Logger::start();\n Timer_Driver::start();\n Network_Driver::start();\n\n POSEIDON_LOG_INFO(PACKAGE_STRING \" started up successfully (PID $1)\", ::getpid());\n\n sleep(10000);\n do_exit(exit_success, \"interrupt\\n\");\n }\n catch(exception& stdex) {\n \/\/ Print the message in `stdex`. There isn't much we can do.\n do_exit(exit_system_error, \"%s\\n[exception class `%s`]\\n\",\n stdex.what(), typeid(stdex).name());\n }\n<|endoftext|>"} {"text":"#include \"python_plugin.hh\"\n#include \"inifile.hh\"\n\n#include \n#include \n\n#define MAX_ERRMSG_SIZE 256\n\n#define ERRMSG(fmt, args...)\t\t\t\t\t\\\n do {\t\t\t\t\t\t\t\\\n char msgbuf[MAX_ERRMSG_SIZE];\t\t\t\t\\\n snprintf(msgbuf, sizeof(msgbuf) -1, fmt, ##args);\t\\\n error_msg = std::string(msgbuf);\t\t\t\\\n } while(0)\n\n#define logPP(level, fmt, ...)\t\t\t\t\t\t\\\n do {\t\t\t\t\t\t\t\t\\\n ERRMSG(fmt, ## __VA_ARGS__);\t\t\t\t\t\\\n\tif (log_level >= level) {\t\t\t\t\t\\\n\t fprintf(stderr, fmt, ## __VA_ARGS__);\t\t\t\\\n\t fprintf(stderr,\"\\n\");\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n } while (0)\n\nextern const char *strstore(const char *s);\n\n\/\/ http:\/\/hafizpariabi.blogspot.com\/2008\/01\/using-custom-deallocator-in.html\n\/\/ reason: avoid segfaults by del(interp_instance) on program exit\n\/\/ make delete(interp_instance) a noop wrt Interp\n\/\/ static void interpDeallocFunc(Interp *interp) {}\nstatic void interpDeallocFunc(Interp *interp) {}\n\n\nint PythonPlugin::run_string(const char *cmd, bp::object &retval, bool as_file)\n{\n if (reload_on_change)\n\treload();\n try {\n\tif (as_file)\n\t retval = bp::exec_file(cmd, main_namespace, main_namespace);\n\telse\n\t retval = bp::exec(cmd, main_namespace, main_namespace);\n\tstatus = PLUGIN_OK;\n }\n catch (bp::error_already_set) {\n\tif (PyErr_Occurred()) {\n\t exception_msg = handle_pyerror();\n\t} else\n\t exception_msg = \"unknown exception\";\n\tstatus = PLUGIN_EXCEPTION;\n\tbp::handle_exception();\n\tPyErr_Clear();\n }\n if (status == PLUGIN_EXCEPTION) {\n\tlogPP(1, \"run_string(%s): \\n%s\",\n\t cmd, exception_msg.c_str());\n }\n return status;\n}\n\nint PythonPlugin::call(const char *module, const char *callable,\n\t\t bp::object tupleargs, bp::object kwargs, bp::object &retval)\n{\n bp::object function;\n\n if (callable == NULL)\n\treturn PLUGIN_NO_CALLABLE;\n\n if (reload_on_change)\n\treload();\n\n if (status < PLUGIN_OK)\n\treturn status;\n\n try {\n\tif (module == NULL) { \/\/ default to function in toplevel module\n\t function = main_namespace[callable];\n\t} else {\n\t bp::object submod = main_namespace[module];\n\t bp::object submod_namespace = submod.attr(\"__dict__\");\n\t function = submod_namespace[callable];\n\t}\n\tretval = function(*tupleargs, **kwargs);\n\tstatus = PLUGIN_OK;\n }\n catch (bp::error_already_set) {\n\tif (PyErr_Occurred()) {\n\t exception_msg = handle_pyerror();\n\t} else\n\t exception_msg = \"unknown exception\";\n\tstatus = PLUGIN_EXCEPTION;\n\tbp::handle_exception();\n\tPyErr_Clear();\n }\n if (status == PLUGIN_EXCEPTION) {\n\tlogPP(1, \"call(%s.%s): \\n%s\",\n\t module, callable, exception_msg.c_str());\n }\n return status;\n}\n\nbool PythonPlugin::is_callable(const char *module,\n\t\t\t const char *funcname)\n{\n bool unexpected = false;\n bool result = false;\n bp::object function;\n\n if (reload_on_change)\n\treload();\n if ((status != PLUGIN_OK) ||\n\t(funcname == NULL)) {\n\treturn false;\n }\n try {\n\tif (module == NULL) { \/\/ default to function in toplevel module\n\t function = main_namespace[funcname];\n\t} else {\n\t bp::object submod = main_namespace[module];\n\t bp::object submod_namespace = submod.attr(\"__dict__\");\n\t function = submod_namespace[funcname];\n\t}\n\tresult = PyCallable_Check(function.ptr());\n }\n catch (bp::error_already_set) {\n\t\/\/ KeyError expected if not callable\n\tif (!PyErr_ExceptionMatches(PyExc_KeyError)) {\n\t \/\/ something else, strange\n\t exception_msg = handle_pyerror();\n\t unexpected = true;\n\t}\n\tresult = false;\n\tPyErr_Clear();\n }\n if (unexpected)\n\tlogPP(1, \"is_callable(%s.%s): unexpected exception:\\n%s\",module,funcname,exception_msg.c_str());\n\n if (log_level)\n\tlogPP(4, \"is_callable(%s.%s) = %s\", module ? module : \"\",funcname,result ? \"TRUE\":\"FALSE\");\n return result;\n}\n\nint PythonPlugin::reload()\n{\n struct stat st;\n\n if (stat(abs_path, &st)) {\n\tlogPP(1, \"reload: stat(%s) returned %s\", abs_path, strerror(errno));\n\tstatus = PLUGIN_STAT_FAILED;\n\treturn status;\n }\n if (st.st_mtime > module_mtime) {\n\tmodule_mtime = st.st_mtime;\n\tinitialize(true);\n\tlogPP(1, \"reload(): module %s reloaded, status=%d\", module_basename, status);\n } else {\n\tlogPP(5, \"reload: no-op\");\n\tstatus = PLUGIN_OK;\n }\n return status;\n}\n\n\/\/ decode a Python exception into a string.\n\/\/ Free function usable without working plugin instance.\nstd::string handle_pyerror()\n{\n PyObject *exc, *val, *tb;\n bp::object formatted_list, formatted;\n\n PyErr_Fetch(&exc, &val, &tb);\n bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));\n bp::object traceback(bp::import(\"traceback\"));\n if (!tb) {\n\tbp::object format_exception_only(traceback.attr(\"format_exception_only\"));\n\tformatted_list = format_exception_only(hexc, hval);\n } else {\n\tbp::object format_exception(traceback.attr(\"format_exception\"));\n\tformatted_list = format_exception(hexc, hval, htb);\n }\n formatted = bp::str(\"\\n\").join(formatted_list);\n return bp::extract(formatted);\n}\n\nvoid PythonPlugin::initialize(bool reload, Interp *interp )\n{\n std::string msg;\n if (Py_IsInitialized()) {\n\ttry {\n\t bp::object module = bp::import(\"__main__\");\n\t main_namespace = module.attr(\"__dict__\");\n\n\t for(unsigned i = 0; i < inittab_entries.size(); i++) {\n\t\tmain_namespace[inittab_entries[i]] = bp::import(inittab_entries[i].c_str());\n\t }\n\t if (interp != NULL) {\n\t bp::object interp_module = bp::import(\"interpreter\");\n\t bp::scope(interp_module).attr(\"this\") = interp_ptr(interp, interpDeallocFunc);\n\t }\n\t bp::object result = bp::exec_file(abs_path,\n\t\t\t\t\t main_namespace,\n\t\t\t\t\t main_namespace);\n\t status = PLUGIN_OK;\n\t}\n\tcatch (bp::error_already_set) {\n\t if (PyErr_Occurred()) {\n\t\texception_msg = handle_pyerror();\n\t } else\n\t\texception_msg = \"unknown exception\";\n\t bp::handle_exception();\n\t status = PLUGIN_INIT_EXCEPTION;\n\t PyErr_Clear();\n\t}\n\tif (status == PLUGIN_INIT_EXCEPTION) {\n\t logPP(1, \"initialize: module '%s' init failed: \\n%s\",\n\t\t abs_path, exception_msg.c_str());\n\t}\n } else {\n\tstatus = PLUGIN_PYTHON_NOT_INITIALIZED;\n }\n}\n\nPythonPlugin::PythonPlugin(const char *iniFilename,\n\t\t\t const char *section,\n\t\t\t struct _inittab *inittab,\n\t\t\t Interp *interp)\n{\n IniFile inifile;\n const char *inistring;\n\n if (section == NULL) {\n\tlogPP(1, \"no section\");\n\tstatus = PLUGIN_NO_SECTION;\n\treturn;\n }\n if ((iniFilename == NULL) &&\n\t((iniFilename = getenv(\"INI_FILE_NAME\")) == NULL)) {\n\tlogPP(1, \"no inifile\");\n\tstatus = PLUGIN_NO_INIFILE;\n\treturn;\n }\n if (inifile.Open(iniFilename) == false) {\n logPP(1, \"Unable to open inifile:%s:\\n\", iniFilename);\n\t status = PLUGIN_BAD_INIFILE;\n\t return;\n }\n if ((inistring = inifile.Find(\"PLUGIN_DIR\", section)) != NULL)\n\tplugin_dir = strstore(inistring);\n else {\n logPP(1, \"no PLUGIN_DIR in inifile:%s:\\n\", iniFilename);\n\t status = PLUGIN_NO_PLUGIN_DIR;\n\t return;\n }\n if ((inistring = inifile.Find(\"MODULE_BASENAME\", section)) != NULL)\n\tmodule_basename = strstore(inistring);\n else {\n logPP(1, \"no MODULE_BASENAME in inifile:%s:\\n\", iniFilename);\n\t status = PLUGIN_NO_MODULE_BASENAME;\n\t return;\n }\n if ((inistring = inifile.Find(\"RELOAD_ON_CHANGE\", section)) != NULL)\n\treload_on_change = (atoi(inistring) > 0);\n\n if ((inistring = inifile.Find(\"LOG_LEVEL\", section)) != NULL)\n\tlog_level = atoi(inistring);\n\n inifile.Close();\n\n char module_path[PATH_MAX];\n strcpy(module_path, plugin_dir );\n strcat(module_path,\"\/\");\n strcat(module_path, module_basename);\n strcat(module_path,\".py\");\n\n char real_path[PATH_MAX];\n if (realpath(module_path, real_path) == NULL) {\n\tlogPP(1, \"cant resolve path to '%s'\", module_path);\n\tstatus = PLUGIN_BAD_PATH;\n\treturn;\n }\n struct stat st;\n if (stat(real_path, &st)) {\n\tlogPP(1, \"stat(%s) returns %s\", real_path, strerror(errno));\n\tstatus = PLUGIN_STAT_FAILED;\n\treturn;\n }\n abs_path = strstore(real_path);\n\n module_mtime = st.st_mtime; \/\/ record timestamp\n Py_SetProgramName((char *) abs_path);\n if ((inittab != NULL) &&\n\tPyImport_ExtendInittab(inittab)) {\n\tlogPP(1, \"cant extend inittab\");\n\tstatus = PLUGIN_INITTAB_FAILED;\n\treturn;\n }\n Py_Initialize();\n char pathcmd[PATH_MAX];\n sprintf(pathcmd, \"import sys\\nsys.path.insert(0,\\\"%s\\\")\", plugin_dir);\n if (PyRun_SimpleString(pathcmd)) {\n\tlogPP(1, \"exeception running '%s'\", pathcmd);\n\texception_msg = \"exeception running \"; \/\/ + pathcmd;\n\tstatus = PLUGIN_EXCEPTION_DURING_PATH_APPEND;\n\treturn;\n }\n logPP(3,\"PythonPlugin: Python '%s'\", Py_GetVersion());\n initialize(false, interp);\n}\n\n\/\/ the externally visible singleton instance\nPythonPlugin *python_plugin;\n\n\/\/ first caller wins\nPythonPlugin *PythonPlugin::configure(const char *iniFilename,\n\t\t\t\t const char *section,\n\t\t\t\t struct _inittab *inittab,Interp *interp)\n{\n if (python_plugin == NULL) {\n\tpython_plugin = new PythonPlugin(iniFilename, section, inittab, interp);\n }\n return (python_plugin->usable()) ? python_plugin : NULL;\n}\n\npython_plugin: properly init log_level#include \"python_plugin.hh\"\n#include \"inifile.hh\"\n\n#include \n#include \n\n#define MAX_ERRMSG_SIZE 256\n\n#define ERRMSG(fmt, args...)\t\t\t\t\t\\\n do {\t\t\t\t\t\t\t\\\n char msgbuf[MAX_ERRMSG_SIZE];\t\t\t\t\\\n snprintf(msgbuf, sizeof(msgbuf) -1, fmt, ##args);\t\\\n error_msg = std::string(msgbuf);\t\t\t\\\n } while(0)\n\n#define logPP(level, fmt, ...)\t\t\t\t\t\t\\\n do {\t\t\t\t\t\t\t\t\\\n ERRMSG(fmt, ## __VA_ARGS__);\t\t\t\t\t\\\n\tif (log_level >= level) {\t\t\t\t\t\\\n\t fprintf(stderr, fmt, ## __VA_ARGS__);\t\t\t\\\n\t fprintf(stderr,\"\\n\");\t\t\t\t\t\\\n\t}\t\t\t\t\t\t\t\t\\\n } while (0)\n\nextern const char *strstore(const char *s);\n\n\/\/ http:\/\/hafizpariabi.blogspot.com\/2008\/01\/using-custom-deallocator-in.html\n\/\/ reason: avoid segfaults by del(interp_instance) on program exit\n\/\/ make delete(interp_instance) a noop wrt Interp\n\/\/ static void interpDeallocFunc(Interp *interp) {}\nstatic void interpDeallocFunc(Interp *interp) {}\n\n\nint PythonPlugin::run_string(const char *cmd, bp::object &retval, bool as_file)\n{\n if (reload_on_change)\n\treload();\n try {\n\tif (as_file)\n\t retval = bp::exec_file(cmd, main_namespace, main_namespace);\n\telse\n\t retval = bp::exec(cmd, main_namespace, main_namespace);\n\tstatus = PLUGIN_OK;\n }\n catch (bp::error_already_set) {\n\tif (PyErr_Occurred()) {\n\t exception_msg = handle_pyerror();\n\t} else\n\t exception_msg = \"unknown exception\";\n\tstatus = PLUGIN_EXCEPTION;\n\tbp::handle_exception();\n\tPyErr_Clear();\n }\n if (status == PLUGIN_EXCEPTION) {\n\tlogPP(1, \"run_string(%s): \\n%s\",\n\t cmd, exception_msg.c_str());\n }\n return status;\n}\n\nint PythonPlugin::call(const char *module, const char *callable,\n\t\t bp::object tupleargs, bp::object kwargs, bp::object &retval)\n{\n bp::object function;\n\n if (callable == NULL)\n\treturn PLUGIN_NO_CALLABLE;\n\n if (reload_on_change)\n\treload();\n\n if (status < PLUGIN_OK)\n\treturn status;\n\n try {\n\tif (module == NULL) { \/\/ default to function in toplevel module\n\t function = main_namespace[callable];\n\t} else {\n\t bp::object submod = main_namespace[module];\n\t bp::object submod_namespace = submod.attr(\"__dict__\");\n\t function = submod_namespace[callable];\n\t}\n\tretval = function(*tupleargs, **kwargs);\n\tstatus = PLUGIN_OK;\n }\n catch (bp::error_already_set) {\n\tif (PyErr_Occurred()) {\n\t exception_msg = handle_pyerror();\n\t} else\n\t exception_msg = \"unknown exception\";\n\tstatus = PLUGIN_EXCEPTION;\n\tbp::handle_exception();\n\tPyErr_Clear();\n }\n if (status == PLUGIN_EXCEPTION) {\n\tlogPP(1, \"call(%s.%s): \\n%s\",\n\t module, callable, exception_msg.c_str());\n }\n return status;\n}\n\nbool PythonPlugin::is_callable(const char *module,\n\t\t\t const char *funcname)\n{\n bool unexpected = false;\n bool result = false;\n bp::object function;\n\n if (reload_on_change)\n\treload();\n if ((status != PLUGIN_OK) ||\n\t(funcname == NULL)) {\n\treturn false;\n }\n try {\n\tif (module == NULL) { \/\/ default to function in toplevel module\n\t function = main_namespace[funcname];\n\t} else {\n\t bp::object submod = main_namespace[module];\n\t bp::object submod_namespace = submod.attr(\"__dict__\");\n\t function = submod_namespace[funcname];\n\t}\n\tresult = PyCallable_Check(function.ptr());\n }\n catch (bp::error_already_set) {\n\t\/\/ KeyError expected if not callable\n\tif (!PyErr_ExceptionMatches(PyExc_KeyError)) {\n\t \/\/ something else, strange\n\t exception_msg = handle_pyerror();\n\t unexpected = true;\n\t}\n\tresult = false;\n\tPyErr_Clear();\n }\n if (unexpected)\n\tlogPP(1, \"is_callable(%s.%s): unexpected exception:\\n%s\",module,funcname,exception_msg.c_str());\n\n if (log_level)\n\tlogPP(4, \"is_callable(%s.%s) = %s\", module ? module : \"\",funcname,result ? \"TRUE\":\"FALSE\");\n return result;\n}\n\nint PythonPlugin::reload()\n{\n struct stat st;\n\n if (stat(abs_path, &st)) {\n\tlogPP(1, \"reload: stat(%s) returned %s\", abs_path, strerror(errno));\n\tstatus = PLUGIN_STAT_FAILED;\n\treturn status;\n }\n if (st.st_mtime > module_mtime) {\n\tmodule_mtime = st.st_mtime;\n\tinitialize(true);\n\tlogPP(1, \"reload(): module %s reloaded, status=%d\", module_basename, status);\n } else {\n\tlogPP(5, \"reload: no-op\");\n\tstatus = PLUGIN_OK;\n }\n return status;\n}\n\n\/\/ decode a Python exception into a string.\n\/\/ Free function usable without working plugin instance.\nstd::string handle_pyerror()\n{\n PyObject *exc, *val, *tb;\n bp::object formatted_list, formatted;\n\n PyErr_Fetch(&exc, &val, &tb);\n bp::handle<> hexc(exc), hval(bp::allow_null(val)), htb(bp::allow_null(tb));\n bp::object traceback(bp::import(\"traceback\"));\n if (!tb) {\n\tbp::object format_exception_only(traceback.attr(\"format_exception_only\"));\n\tformatted_list = format_exception_only(hexc, hval);\n } else {\n\tbp::object format_exception(traceback.attr(\"format_exception\"));\n\tformatted_list = format_exception(hexc, hval, htb);\n }\n formatted = bp::str(\"\\n\").join(formatted_list);\n return bp::extract(formatted);\n}\n\nvoid PythonPlugin::initialize(bool reload, Interp *interp )\n{\n std::string msg;\n if (Py_IsInitialized()) {\n\ttry {\n\t bp::object module = bp::import(\"__main__\");\n\t main_namespace = module.attr(\"__dict__\");\n\n\t for(unsigned i = 0; i < inittab_entries.size(); i++) {\n\t\tmain_namespace[inittab_entries[i]] = bp::import(inittab_entries[i].c_str());\n\t }\n\t if (interp != NULL) {\n\t bp::object interp_module = bp::import(\"interpreter\");\n\t bp::scope(interp_module).attr(\"this\") = interp_ptr(interp, interpDeallocFunc);\n\t }\n\t bp::object result = bp::exec_file(abs_path,\n\t\t\t\t\t main_namespace,\n\t\t\t\t\t main_namespace);\n\t status = PLUGIN_OK;\n\t}\n\tcatch (bp::error_already_set) {\n\t if (PyErr_Occurred()) {\n\t\texception_msg = handle_pyerror();\n\t } else\n\t\texception_msg = \"unknown exception\";\n\t bp::handle_exception();\n\t status = PLUGIN_INIT_EXCEPTION;\n\t PyErr_Clear();\n\t}\n\tif (status == PLUGIN_INIT_EXCEPTION) {\n\t logPP(1, \"initialize: module '%s' init failed: \\n%s\",\n\t\t abs_path, exception_msg.c_str());\n\t}\n } else {\n\tstatus = PLUGIN_PYTHON_NOT_INITIALIZED;\n }\n}\n\nPythonPlugin::PythonPlugin(const char *iniFilename,\n\t\t\t const char *section,\n\t\t\t struct _inittab *inittab,\n\t\t\t Interp *interp) :\n log_level(0)\n{\n IniFile inifile;\n const char *inistring;\n\n if (section == NULL) {\n\tlogPP(1, \"no section\");\n\tstatus = PLUGIN_NO_SECTION;\n\treturn;\n }\n if ((iniFilename == NULL) &&\n\t((iniFilename = getenv(\"INI_FILE_NAME\")) == NULL)) {\n\tlogPP(1, \"no inifile\");\n\tstatus = PLUGIN_NO_INIFILE;\n\treturn;\n }\n if (inifile.Open(iniFilename) == false) {\n logPP(1, \"Unable to open inifile:%s:\\n\", iniFilename);\n\t status = PLUGIN_BAD_INIFILE;\n\t return;\n }\n if ((inistring = inifile.Find(\"PLUGIN_DIR\", section)) != NULL)\n\tplugin_dir = strstore(inistring);\n else {\n logPP(3, \"no PLUGIN_DIR in inifile:%s:\\n\", iniFilename);\n\t status = PLUGIN_NO_PLUGIN_DIR;\n\t return;\n }\n if ((inistring = inifile.Find(\"MODULE_BASENAME\", section)) != NULL)\n\tmodule_basename = strstore(inistring);\n else {\n logPP(1, \"no MODULE_BASENAME in inifile:%s:\\n\", iniFilename);\n\t status = PLUGIN_NO_MODULE_BASENAME;\n\t return;\n }\n if ((inistring = inifile.Find(\"RELOAD_ON_CHANGE\", section)) != NULL)\n\treload_on_change = (atoi(inistring) > 0);\n\n if ((inistring = inifile.Find(\"LOG_LEVEL\", section)) != NULL)\n\tlog_level = atoi(inistring);\n\n inifile.Close();\n\n char module_path[PATH_MAX];\n strcpy(module_path, plugin_dir );\n strcat(module_path,\"\/\");\n strcat(module_path, module_basename);\n strcat(module_path,\".py\");\n\n char real_path[PATH_MAX];\n if (realpath(module_path, real_path) == NULL) {\n\tlogPP(1, \"cant resolve path to '%s'\", module_path);\n\tstatus = PLUGIN_BAD_PATH;\n\treturn;\n }\n struct stat st;\n if (stat(real_path, &st)) {\n\tlogPP(1, \"stat(%s) returns %s\", real_path, strerror(errno));\n\tstatus = PLUGIN_STAT_FAILED;\n\treturn;\n }\n abs_path = strstore(real_path);\n\n module_mtime = st.st_mtime; \/\/ record timestamp\n Py_SetProgramName((char *) abs_path);\n if ((inittab != NULL) &&\n\tPyImport_ExtendInittab(inittab)) {\n\tlogPP(1, \"cant extend inittab\");\n\tstatus = PLUGIN_INITTAB_FAILED;\n\treturn;\n }\n Py_Initialize();\n char pathcmd[PATH_MAX];\n sprintf(pathcmd, \"import sys\\nsys.path.insert(0,\\\"%s\\\")\", plugin_dir);\n if (PyRun_SimpleString(pathcmd)) {\n\tlogPP(1, \"exeception running '%s'\", pathcmd);\n\texception_msg = \"exeception running \"; \/\/ + pathcmd;\n\tstatus = PLUGIN_EXCEPTION_DURING_PATH_APPEND;\n\treturn;\n }\n logPP(3,\"PythonPlugin: Python '%s'\", Py_GetVersion());\n initialize(false, interp);\n}\n\n\/\/ the externally visible singleton instance\nPythonPlugin *python_plugin;\n\n\/\/ first caller wins\nPythonPlugin *PythonPlugin::configure(const char *iniFilename,\n\t\t\t\t const char *section,\n\t\t\t\t struct _inittab *inittab,Interp *interp)\n{\n if (python_plugin == NULL) {\n\tpython_plugin = new PythonPlugin(iniFilename, section, inittab, interp);\n }\n return (python_plugin->usable()) ? python_plugin : NULL;\n}\n\n<|endoftext|>"} {"text":"\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file Stm32Gpio.hxx\n *\n * Helper declarations for using GPIO pins (both for GPIO and other hardware)\n * on STM32 microcontrollers.\n *\n * @author Balazs Racz\n * @date 24 Aug 2015\n *\/\n\n#ifndef _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_\n#define _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_\n\n#include \"os\/Gpio.hxx\"\n#include \"GpioWrapper.hxx\"\n\n#if defined(STM32F072xB) || defined(STM32F091xC)\n#include \"stm32f0xx_hal_gpio.h\"\n#elif defined(STM32F103xB)\n#include \"stm32f1xx_hal_gpio.h\"\n#elif defined(STM32F303xC)\n#include \"stm32f3xx_hal_gpio.h\"\n#else\n#error Dont know what STM32 chip you have.\n#endif\n\n\/\/\/ Static GPIO implementation for the STM32 microcontrollers. Do not use\n\/\/\/ directly: use @ref GPIO_PIN macro.\n\/\/\/ @param PORT is the port base address pointer (e.g. GPIOC) \n\/\/\/ @param PIN is the GPIO_PIN_# value for the pin number.\n\/\/\/ @param PIN_NUM is the number of the pin in the port. Zero-based.\ntemplate struct Stm32GpioDefs\n{\n \/\/\/ @return the PIO structure of the give gpio port.\n static GPIO_TypeDef *port()\n {\n return (GPIO_TypeDef *)GPIOx;\n }\n\n \/\/\/ @return the pin number within the port.\n static uint16_t pin()\n {\n return PIN;\n }\n\n \/\/\/ Sets the output pin to a given level.\n static void set(bool value)\n {\n if (value)\n {\n#if defined(STM32F303xC)\n port()->BSRRL = pin();\n#else\n port()->BSRR = pin();\n#endif\n }\n else\n {\n#if defined(STM32F303xC)\n port()->BSRRH = pin();\n#else\n port()->BSRR = pin() << 16;\n#endif\n }\n }\n\n \/\/\/ Sets the output pin to a given level.\n static bool get()\n {\n return port()->IDR & pin();\n }\n\n \/\/\/ @return a os-indepentent Gpio abstraction instance for use in\n \/\/\/ libraries.\n static constexpr const Gpio *instance()\n {\n return GpioWrapper>::instance();\n }\n\n \/\/\/ @return whether this pin is configured as an output.\n static bool is_output()\n {\n uint8_t* mode = (uint8_t*)port();\n uint8_t m = mode[PIN_NUM >> 1];\n if (PIN_NUM & 1) { m >>= 4; }\n return (m & 3) != 0;\n }\n\n};\n\ntemplate struct GpioOutputPin : public Defs\n{\n using Defs::port;\n using Defs::pin;\n using Defs::set;\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n GPIO_InitTypeDef gpio_init = {0};\n gpio_init.Pin = pin();\n gpio_init.Mode = GPIO_MODE_OUTPUT_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_LOW;\n HAL_GPIO_Init(port(), &gpio_init);\n }\n \/\/\/ Sets the output pin to a safe value.\n static void hw_set_to_safe()\n {\n hw_init();\n set(SAFE_VALUE);\n }\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with low level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioOutputSafeLow : public GpioOutputPin\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with high level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioOutputSafeHigh : public GpioOutputPin\n{\n};\n\n\/\/\/ Defines a GPIO output pin for driving an LED. The MCU must be in spec for\n\/\/\/ the necessary output current.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate struct LedPin : public GpioOutputPin\n{\n};\n\ntemplate struct GpioInputPin : public Defs\n{\n using Defs::port;\n using Defs::pin;\n using Defs::set;\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n GPIO_InitTypeDef gpio_init = {0};\n gpio_init.Pin = pin();\n gpio_init.Mode = GPIO_MODE_INPUT;\n gpio_init.Pull = PULL_MODE;\n gpio_init.Speed = GPIO_SPEED_FREQ_LOW;\n HAL_GPIO_Init(port(), &gpio_init);\n }\n \/\/\/ Sets the hardware pin to a safe state.\n static void hw_set_to_safe()\n {\n hw_init();\n }\n \/\/\/ @return true if the pin is set to drive an output.\n static bool is_output()\n {\n return false;\n }\n};\n\n\/\/\/ GPIO Input pin with weak pull up.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioInputPU : public GpioInputPin\n{\n};\n\n\/\/\/ GPIO Input pin with weak pull down.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioInputPD : public GpioInputPin\n{\n};\n\n\/\/\/ GPIO Input pin in standard configuration (no pull).\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioInputNP : public GpioInputPin\n{\n};\n\n\/\/\/ Helper macro for defining GPIO pins.\n\/\/\/\n\/\/\/ @param NAME is the basename of the declaration. For NAME==FOO the macro\n\/\/\/ declares FOO_Pin as a structure on which the read-write functions will be\n\/\/\/ available.\n\/\/\/\n\/\/\/ @param BaseClass is the initialization structure, such as @ref LedPin, or\n\/\/\/ @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow.\n\/\/\/\n\/\/\/ @param PORTNAME is a letter defining which port this is (like A, B,\n\/\/\/ C). E.g. for PC8 this is C.\n\/\/\/\n\/\/\/ @param NUM is the pin number, such as 8 for PC8.\n\/\/\/\n\/\/\/ Example:\n\/\/\/ GPIO_PIN(FOO, LedPin, 0, 3);\n\/\/\/ ...\n\/\/\/ FOO_Pin::set(true);\n#define GPIO_PIN(NAME, BaseClass, PORTNAME, NUM) \\\n typedef BaseClass> NAME##_Pin\n\n#endif \/\/ _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_\nFixes bug in STM32 GPIO driver that SafeHIgh and SafeLOw for outputs were not taken into account when booting.\/** \\copyright\n * Copyright (c) 2015, Balazs Racz\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are met:\n *\n * - Redistributions of source code must retain the above copyright notice,\n * this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright notice,\n * this list of conditions and the following disclaimer in the documentation\n * and\/or other materials provided with the distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n * POSSIBILITY OF SUCH DAMAGE.\n *\n * \\file Stm32Gpio.hxx\n *\n * Helper declarations for using GPIO pins (both for GPIO and other hardware)\n * on STM32 microcontrollers.\n *\n * @author Balazs Racz\n * @date 24 Aug 2015\n *\/\n\n#ifndef _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_\n#define _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_\n\n#include \"os\/Gpio.hxx\"\n#include \"GpioWrapper.hxx\"\n\n#if defined(STM32F072xB) || defined(STM32F091xC)\n#include \"stm32f0xx_hal_gpio.h\"\n#elif defined(STM32F103xB)\n#include \"stm32f1xx_hal_gpio.h\"\n#elif defined(STM32F303xC)\n#include \"stm32f3xx_hal_gpio.h\"\n#else\n#error Dont know what STM32 chip you have.\n#endif\n\n\/\/\/ Static GPIO implementation for the STM32 microcontrollers. Do not use\n\/\/\/ directly: use @ref GPIO_PIN macro.\n\/\/\/ @param PORT is the port base address pointer (e.g. GPIOC) \n\/\/\/ @param PIN is the GPIO_PIN_# value for the pin number.\n\/\/\/ @param PIN_NUM is the number of the pin in the port. Zero-based.\ntemplate struct Stm32GpioDefs\n{\n \/\/\/ @return the PIO structure of the give gpio port.\n static GPIO_TypeDef *port()\n {\n return (GPIO_TypeDef *)GPIOx;\n }\n\n \/\/\/ @return the pin number within the port.\n static uint16_t pin()\n {\n return PIN;\n }\n\n \/\/\/ Sets the output pin to a given level.\n static void set(bool value)\n {\n if (value)\n {\n#if defined(STM32F303xC)\n port()->BSRRL = pin();\n#else\n port()->BSRR = pin();\n#endif\n }\n else\n {\n#if defined(STM32F303xC)\n port()->BSRRH = pin();\n#else\n port()->BSRR = pin() << 16;\n#endif\n }\n }\n\n \/\/\/ Sets the output pin to a given level.\n static bool get()\n {\n return port()->IDR & pin();\n }\n\n \/\/\/ @return a os-indepentent Gpio abstraction instance for use in\n \/\/\/ libraries.\n static constexpr const Gpio *instance()\n {\n return GpioWrapper>::instance();\n }\n\n \/\/\/ @return whether this pin is configured as an output.\n static bool is_output()\n {\n uint8_t* mode = (uint8_t*)port();\n uint8_t m = mode[PIN_NUM >> 1];\n if (PIN_NUM & 1) { m >>= 4; }\n return (m & 3) != 0;\n }\n\n};\n\ntemplate struct GpioOutputPin : public Defs\n{\n using Defs::port;\n using Defs::pin;\n using Defs::set;\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n GPIO_InitTypeDef gpio_init = {0};\n gpio_init.Pin = pin();\n gpio_init.Mode = GPIO_MODE_OUTPUT_PP;\n gpio_init.Pull = GPIO_NOPULL;\n gpio_init.Speed = GPIO_SPEED_FREQ_LOW;\n HAL_GPIO_Init(port(), &gpio_init);\n set(SAFE_VALUE);\n }\n \/\/\/ Sets the output pin to a safe value.\n static void hw_set_to_safe()\n {\n hw_init();\n set(SAFE_VALUE);\n }\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with low level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioOutputSafeLow : public GpioOutputPin\n{\n};\n\n\/\/\/ Defines a GPIO output pin, initialized to be an output pin with high level.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioOutputSafeHigh : public GpioOutputPin\n{\n};\n\n\/\/\/ Defines a GPIO output pin for driving an LED. The MCU must be in spec for\n\/\/\/ the necessary output current.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate struct LedPin : public GpioOutputPin\n{\n};\n\ntemplate struct GpioInputPin : public Defs\n{\n using Defs::port;\n using Defs::pin;\n using Defs::set;\n \/\/\/ Initializes the hardware pin.\n static void hw_init()\n {\n GPIO_InitTypeDef gpio_init = {0};\n gpio_init.Pin = pin();\n gpio_init.Mode = GPIO_MODE_INPUT;\n gpio_init.Pull = PULL_MODE;\n gpio_init.Speed = GPIO_SPEED_FREQ_LOW;\n HAL_GPIO_Init(port(), &gpio_init);\n }\n \/\/\/ Sets the hardware pin to a safe state.\n static void hw_set_to_safe()\n {\n hw_init();\n }\n \/\/\/ @return true if the pin is set to drive an output.\n static bool is_output()\n {\n return false;\n }\n};\n\n\/\/\/ GPIO Input pin with weak pull up.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioInputPU : public GpioInputPin\n{\n};\n\n\/\/\/ GPIO Input pin with weak pull down.\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioInputPD : public GpioInputPin\n{\n};\n\n\/\/\/ GPIO Input pin in standard configuration (no pull).\n\/\/\/\n\/\/\/ Do not use this class directly. Use @ref GPIO_PIN instead.\ntemplate \nstruct GpioInputNP : public GpioInputPin\n{\n};\n\n\/\/\/ Helper macro for defining GPIO pins.\n\/\/\/\n\/\/\/ @param NAME is the basename of the declaration. For NAME==FOO the macro\n\/\/\/ declares FOO_Pin as a structure on which the read-write functions will be\n\/\/\/ available.\n\/\/\/\n\/\/\/ @param BaseClass is the initialization structure, such as @ref LedPin, or\n\/\/\/ @ref GpioOutputSafeHigh or @ref GpioOutputSafeLow.\n\/\/\/\n\/\/\/ @param PORTNAME is a letter defining which port this is (like A, B,\n\/\/\/ C). E.g. for PC8 this is C.\n\/\/\/\n\/\/\/ @param NUM is the pin number, such as 8 for PC8.\n\/\/\/\n\/\/\/ Example:\n\/\/\/ GPIO_PIN(FOO, LedPin, 0, 3);\n\/\/\/ ...\n\/\/\/ FOO_Pin::set(true);\n#define GPIO_PIN(NAME, BaseClass, PORTNAME, NUM) \\\n typedef BaseClass> NAME##_Pin\n\n#endif \/\/ _FREERTOS_DRIVERS_ST_STM32GPIO_HXX_\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ncode_common\/src\/common.h\"\n#include \"ncode_common\/src\/map_util.h\"\n#include \"ncode_common\/src\/net\/net_common.h\"\n#include \"ncode_common\/src\/net\/net_gen.h\"\n#include \"ncode_common\/src\/strutil.h\"\n#include \"ncode_common\/src\/viz\/grapher.h\"\n#include \"..\/common.h\"\n#include \"..\/mean_est\/mean_est.h\"\n#include \"..\/routing_system.h\"\n#include \"ctr.h\"\n#include \"path_provider.h\"\n\nDEFINE_double(cd_link_gbps, 1.0, \"Capacity of C->D\");\nDEFINE_double(ab_link_gbps, 1.0, \"Capacity of A->B\");\nDEFINE_double(cd_link_ms, 10, \"Delay of C->D\");\nDEFINE_double(ab_link_ms, 10, \"Delay of A->B\");\nDEFINE_double(cd_aggregate_gbps, 0.9, \"Demand of C->D aggregate\");\nDEFINE_double(ab_aggregate_gbps, 0.9, \"Demand of A->B aggregate\");\nDEFINE_uint64(cd_aggregate_flows, 1000, \"Number of C->D flows\");\nDEFINE_uint64(ab_aggregate_flows, 1000, \"Number of A->B flows\");\nDEFINE_uint64(steps, 20, \"Number of steps\");\nDEFINE_double(decay_factor, 0.0, \"How quickly to decay prediction\");\nDEFINE_string(opt, \"CTR\", \"The optimizer to use\");\nDEFINE_bool(dampen_ratio, false, \"Preserve the flow count \/ volume ratio?\");\n\nnamespace ctr {\n\nstatic constexpr std::chrono::milliseconds kSyntheticBinSize =\n std::chrono::milliseconds(10);\nstatic constexpr size_t kSyntheticBinCount = 600;\n\nclass StabilityEvalHarness {\n public:\n StabilityEvalHarness(TrafficMatrix* initial_tm, RoutingSystem* routing_system,\n size_t cycle_count)\n : initial_tm_(initial_tm),\n routing_system_(routing_system),\n graph_(routing_system_->graph()) {\n Cycle(cycle_count);\n }\n\n const std::vector& deltas() const {\n return deltas_;\n }\n\n void PlotLinkFractions(const std::string& out) const {\n std::vector series;\n for (const auto& path_and_fractions : path_to_fraction_) {\n const nc::net::Walk* walk = path_and_fractions.first;\n\n series.emplace_back();\n nc::viz::DataSeries2D& data_series = series.back();\n data_series.data = path_and_fractions.second;\n data_series.label = walk->ToStringNoPorts(*graph_);\n }\n\n nc::viz::PlotParameters2D params;\n params.x_label = \"timestep\";\n params.y_label = \"fraction\";\n\n nc::viz::PythonGrapher grapher(out);\n grapher.PlotLine(params, series);\n }\n\n void DumpLinkFractions() const {\n std::cout << path_to_fraction_.size() << \"\\n\";\n for (const auto& path_and_fractions : path_to_fraction_) {\n const nc::net::Walk* walk = path_and_fractions.first;\n\n std::vector to_combine;\n for (const auto& times_and_fractions : path_and_fractions.second) {\n to_combine.emplace_back(nc::StrCat(\"(\", times_and_fractions.first, \",\",\n times_and_fractions.second, \")\"));\n }\n\n std::cout << walk->ToStringNoPorts(*graph_) << \" : (\"\n << nc::Join(to_combine, \",\") << \")\\n\";\n }\n }\n\n void DumpAggregateVolumes() const {\n std::cout << volumes_.size() << \"\\n\";\n for (const auto& aggregate_and_volumes : volumes_) {\n const AggregateId& aggregate_id = aggregate_and_volumes.first;\n const std::vector& volumes =\n aggregate_and_volumes.second;\n\n std::string out = nc::Join(volumes, \",\", [](nc::net::Bandwidth v) {\n return std::to_string(v.Mbps());\n });\n std::cout << aggregate_id.ToString(*graph_) << \" : (\" << out << \")\\n\";\n }\n }\n\n private:\n \/\/ Produces a traffic matrix that is scaled based on each flow's shortest path\n \/\/ stretch. If all flows of an aggregate are on a path that is 2x as long as\n \/\/ the shortest path then their demand will be 1\/2 of what it would be if they\n \/\/ were on the shortest path.\n std::unique_ptr ScaleBasedOnOutput(\n const RoutingConfiguration& routing,\n const TrafficMatrix& original_tm) const {\n std::map out;\n for (const auto& aggregate_and_routes : routing.routes()) {\n const AggregateId& aggregate_id = aggregate_and_routes.first;\n\n const DemandAndFlowCount& demand_and_flow_count =\n nc::FindOrDieNoPrint(routing.demands(), aggregate_id);\n const DemandAndFlowCount& initial_demand_and_flow_count =\n nc::FindOrDieNoPrint(initial_tm_->demands(), aggregate_id);\n\n size_t flow_count = demand_and_flow_count.second;\n nc::net::Bandwidth sp_bandwidth = initial_demand_and_flow_count.first;\n nc::net::Delay sp_delay = aggregate_id.GetSPDelay(*graph_);\n\n double total_mbps = 0;\n double per_flow_sp_mbps = sp_bandwidth.Mbps() \/ flow_count;\n const std::vector& routes = aggregate_and_routes.second;\n for (const RouteAndFraction& route_and_fraction : routes) {\n nc::net::Delay path_delay = route_and_fraction.first->delay();\n double sp_ratio =\n static_cast(sp_delay.count()) \/ path_delay.count();\n\n \/\/ Each flow in the aggregate will get bandwidth proportional to how far\n \/\/ away it is from the shortest path.\n total_mbps += route_and_fraction.second * flow_count * sp_ratio *\n per_flow_sp_mbps;\n CHECK(total_mbps == total_mbps);\n }\n\n std::mt19937 rnd(1);\n std::uniform_real_distribution dist(1, 10);\n\n double new_flow_count = flow_count;\n if (FLAGS_dampen_ratio) {\n \/\/ The demand in the output will not be the same as the one in the input\n \/\/ to the optimizer because of prediction. Need to dampen the ratio\n \/\/ based on the original input, not the predicted one.\n const DemandAndFlowCount& original_demand_and_flow_count =\n nc::FindOrDieNoPrint(original_tm.demands(), aggregate_id);\n\n new_flow_count = total_mbps * flow_count \/\n original_demand_and_flow_count.first.Mbps();\n new_flow_count = std::max(1.0, new_flow_count);\n }\n\n out[aggregate_id] = {nc::net::Bandwidth::FromMBitsPerSecond(total_mbps),\n new_flow_count};\n }\n\n return nc::make_unique(graph_, out);\n }\n\n \/\/ Performs a number of runs with the optimizer. Returns n - 1 values, one for\n \/\/ each delta between a run and its following run.\n void Cycle(size_t n) {\n std::unique_ptr prev_tm;\n std::unique_ptr prev_routing;\n for (size_t i = 0; i < n; ++i) {\n const TrafficMatrix* tm = prev_tm ? prev_tm.get() : initial_tm_;\n UpdateVolumes(*tm);\n\n RoutingSystemUpdateResult update_result =\n routing_system_->Update(SyntheticHistoryFromTM(*tm));\n auto& routing = update_result.routing;\n\n for (const auto& aggregate_and_routes : routing->routes()) {\n for (const auto& path_and_fraction : aggregate_and_routes.second) {\n path_to_fraction_[path_and_fraction.first].emplace_back(\n i, path_and_fraction.second);\n }\n }\n\n if (prev_routing) {\n deltas_.emplace_back(prev_routing->GetDifference(*routing));\n }\n prev_tm = ScaleBasedOnOutput(*routing, *tm);\n prev_routing = std::move(routing);\n }\n }\n\n void UpdateVolumes(const TrafficMatrix& tm) {\n for (const auto& aggregate_and_demands : tm.demands()) {\n const AggregateId& aggregate = aggregate_and_demands.first;\n volumes_[aggregate].emplace_back(aggregate_and_demands.second.first);\n }\n }\n\n std::map SyntheticHistoryFromTM(\n const TrafficMatrix& tm) {\n std::map out;\n for (const auto& aggregate_demand_and_flow_count : tm.demands()) {\n const AggregateId& aggregate = aggregate_demand_and_flow_count.first;\n nc::net::Bandwidth demand = aggregate_demand_and_flow_count.second.first;\n size_t flow_count = aggregate_demand_and_flow_count.second.second;\n\n out.emplace(std::piecewise_construct, std::forward_as_tuple(aggregate),\n std::forward_as_tuple(demand, kSyntheticBinCount,\n kSyntheticBinSize, flow_count));\n }\n\n return out;\n }\n\n \/\/ In the initial TM each aggregate's demand is what it would be if it were\n \/\/ routed on its shortest path.\n TrafficMatrix* initial_tm_;\n\n \/\/ The optimizer.\n RoutingSystem* routing_system_;\n\n \/\/ The graph.\n const nc::net::GraphStorage* graph_;\n\n \/\/ N - 1 deltas for each step to the next one.\n std::vector deltas_;\n\n \/\/ Per-aggregate volumes.\n std::map> volumes_;\n\n \/\/ Path to fractions of capacity.\n std::map>>\n path_to_fraction_;\n};\n\nstatic void RunWithSimpleTopologyTwoAggregates() {\n nc::net::GraphBuilder builder;\n std::chrono::microseconds ab_delay(\n static_cast(FLAGS_ab_link_ms * 1000));\n std::chrono::microseconds cd_delay(\n static_cast(FLAGS_cd_link_ms * 1000));\n\n builder.AddLink({\"A\", \"B\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),\n ab_delay});\n builder.AddLink({\"B\", \"A\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),\n ab_delay});\n builder.AddLink({\"A\", \"C\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n builder.AddLink({\"C\", \"A\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n builder.AddLink({\"C\", \"D\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),\n cd_delay});\n builder.AddLink({\"D\", \"C\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),\n cd_delay});\n builder.AddLink({\"B\", \"D\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n builder.AddLink({\"D\", \"B\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n\n nc::net::GraphStorage graph(builder);\n TrafficMatrix initial_tm(&graph);\n AggregateId id_one(\n {graph.NodeFromStringOrDie(\"A\"), graph.NodeFromStringOrDie(\"B\")});\n AggregateId id_two(\n {graph.NodeFromStringOrDie(\"C\"), graph.NodeFromStringOrDie(\"D\")});\n\n initial_tm.AddDemand(\n id_one, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_aggregate_gbps),\n FLAGS_ab_aggregate_flows});\n initial_tm.AddDemand(\n id_two, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_aggregate_gbps),\n FLAGS_cd_aggregate_flows});\n\n PathProvider path_provider(&graph);\n std::unique_ptr opt;\n if (FLAGS_opt == \"CTR\") {\n opt = nc::make_unique(&path_provider, 1.0, true);\n } else if (FLAGS_opt == \"B4\") {\n opt = nc::make_unique(&path_provider, false, 1.0);\n } else if (FLAGS_opt == \"B4(P)\") {\n opt = nc::make_unique(&path_provider, true, 1.0);\n } else if (FLAGS_opt == \"MinMax\") {\n opt = nc::make_unique(&path_provider, 1.0);\n }\n\n MeanScaleEstimatorFactory estimator_factory(\n {1.1, FLAGS_decay_factor, FLAGS_decay_factor, 10});\n RoutingSystemConfig routing_system_config;\n routing_system_config.store_to_metrics = false;\n RoutingSystem routing_system(routing_system_config, opt.get(),\n &estimator_factory);\n StabilityEvalHarness harness(&initial_tm, &routing_system, FLAGS_steps);\n harness.DumpAggregateVolumes();\n harness.DumpLinkFractions();\n}\n\n} \/\/ namespace ctr\n\nint main(int argc, char** argv) {\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n \/\/ ctr::RunWithSimpleTopology();\n ctr::RunWithSimpleTopologyTwoAggregates();\n\n return 0;\n}\nfixed compilation error#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"ncode_common\/src\/common.h\"\n#include \"ncode_common\/src\/map_util.h\"\n#include \"ncode_common\/src\/net\/net_common.h\"\n#include \"ncode_common\/src\/net\/net_gen.h\"\n#include \"ncode_common\/src\/strutil.h\"\n#include \"ncode_common\/src\/viz\/grapher.h\"\n#include \"..\/common.h\"\n#include \"..\/mean_est\/mean_est.h\"\n#include \"..\/routing_system.h\"\n#include \"ctr.h\"\n#include \"path_provider.h\"\n\nDEFINE_double(cd_link_gbps, 1.0, \"Capacity of C->D\");\nDEFINE_double(ab_link_gbps, 1.0, \"Capacity of A->B\");\nDEFINE_double(cd_link_ms, 10, \"Delay of C->D\");\nDEFINE_double(ab_link_ms, 10, \"Delay of A->B\");\nDEFINE_double(cd_aggregate_gbps, 0.9, \"Demand of C->D aggregate\");\nDEFINE_double(ab_aggregate_gbps, 0.9, \"Demand of A->B aggregate\");\nDEFINE_uint64(cd_aggregate_flows, 1000, \"Number of C->D flows\");\nDEFINE_uint64(ab_aggregate_flows, 1000, \"Number of A->B flows\");\nDEFINE_uint64(steps, 20, \"Number of steps\");\nDEFINE_double(decay_factor, 0.0, \"How quickly to decay prediction\");\nDEFINE_string(opt, \"CTR\", \"The optimizer to use\");\nDEFINE_bool(dampen_ratio, false, \"Preserve the flow count \/ volume ratio?\");\n\nnamespace ctr {\n\nstatic constexpr std::chrono::milliseconds kSyntheticBinSize =\n std::chrono::milliseconds(10);\nstatic constexpr size_t kSyntheticBinCount = 600;\n\nclass StabilityEvalHarness {\n public:\n StabilityEvalHarness(TrafficMatrix* initial_tm, RoutingSystem* routing_system,\n size_t cycle_count)\n : initial_tm_(initial_tm),\n routing_system_(routing_system),\n graph_(routing_system_->graph()) {\n Cycle(cycle_count);\n }\n\n const std::vector& deltas() const {\n return deltas_;\n }\n\n void PlotLinkFractions(const std::string& out) const {\n std::vector series;\n for (const auto& path_and_fractions : path_to_fraction_) {\n const nc::net::Walk* walk = path_and_fractions.first;\n\n series.emplace_back();\n nc::viz::DataSeries2D& data_series = series.back();\n data_series.data = path_and_fractions.second;\n data_series.label = walk->ToStringNoPorts(*graph_);\n }\n\n nc::viz::PlotParameters2D params;\n params.x_label = \"timestep\";\n params.y_label = \"fraction\";\n\n nc::viz::PythonGrapher grapher(out);\n grapher.PlotLine(params, series);\n }\n\n void DumpLinkFractions() const {\n std::cout << path_to_fraction_.size() << \"\\n\";\n for (const auto& path_and_fractions : path_to_fraction_) {\n const nc::net::Walk* walk = path_and_fractions.first;\n\n std::vector to_combine;\n for (const auto& times_and_fractions : path_and_fractions.second) {\n to_combine.emplace_back(nc::StrCat(\"(\", times_and_fractions.first, \",\",\n times_and_fractions.second, \")\"));\n }\n\n std::cout << walk->ToStringNoPorts(*graph_) << \" : (\"\n << nc::Join(to_combine, \",\") << \")\\n\";\n }\n }\n\n void DumpAggregateVolumes() const {\n std::cout << volumes_.size() << \"\\n\";\n for (const auto& aggregate_and_volumes : volumes_) {\n const AggregateId& aggregate_id = aggregate_and_volumes.first;\n const std::vector& volumes =\n aggregate_and_volumes.second;\n\n std::function format_f = [](\n const nc::net::Bandwidth& bw) { return std::to_string(bw.Mbps()); };\n\n std::string out = nc::Join(volumes, \",\", format_f);\n std::cout << aggregate_id.ToString(*graph_) << \" : (\" << out << \")\\n\";\n }\n }\n\n private:\n \/\/ Produces a traffic matrix that is scaled based on each flow's shortest path\n \/\/ stretch. If all flows of an aggregate are on a path that is 2x as long as\n \/\/ the shortest path then their demand will be 1\/2 of what it would be if they\n \/\/ were on the shortest path.\n std::unique_ptr ScaleBasedOnOutput(\n const RoutingConfiguration& routing,\n const TrafficMatrix& original_tm) const {\n std::map out;\n for (const auto& aggregate_and_routes : routing.routes()) {\n const AggregateId& aggregate_id = aggregate_and_routes.first;\n\n const DemandAndFlowCount& demand_and_flow_count =\n nc::FindOrDieNoPrint(routing.demands(), aggregate_id);\n const DemandAndFlowCount& initial_demand_and_flow_count =\n nc::FindOrDieNoPrint(initial_tm_->demands(), aggregate_id);\n\n size_t flow_count = demand_and_flow_count.second;\n nc::net::Bandwidth sp_bandwidth = initial_demand_and_flow_count.first;\n nc::net::Delay sp_delay = aggregate_id.GetSPDelay(*graph_);\n\n double total_mbps = 0;\n double per_flow_sp_mbps = sp_bandwidth.Mbps() \/ flow_count;\n const std::vector& routes = aggregate_and_routes.second;\n for (const RouteAndFraction& route_and_fraction : routes) {\n nc::net::Delay path_delay = route_and_fraction.first->delay();\n double sp_ratio =\n static_cast(sp_delay.count()) \/ path_delay.count();\n\n \/\/ Each flow in the aggregate will get bandwidth proportional to how far\n \/\/ away it is from the shortest path.\n total_mbps += route_and_fraction.second * flow_count * sp_ratio *\n per_flow_sp_mbps;\n CHECK(total_mbps == total_mbps);\n }\n\n std::mt19937 rnd(1);\n std::uniform_real_distribution dist(1, 10);\n\n double new_flow_count = flow_count;\n if (FLAGS_dampen_ratio) {\n \/\/ The demand in the output will not be the same as the one in the input\n \/\/ to the optimizer because of prediction. Need to dampen the ratio\n \/\/ based on the original input, not the predicted one.\n const DemandAndFlowCount& original_demand_and_flow_count =\n nc::FindOrDieNoPrint(original_tm.demands(), aggregate_id);\n\n new_flow_count = total_mbps * flow_count \/\n original_demand_and_flow_count.first.Mbps();\n new_flow_count = std::max(1.0, new_flow_count);\n }\n\n out[aggregate_id] = {nc::net::Bandwidth::FromMBitsPerSecond(total_mbps),\n new_flow_count};\n }\n\n return nc::make_unique(graph_, out);\n }\n\n \/\/ Performs a number of runs with the optimizer. Returns n - 1 values, one for\n \/\/ each delta between a run and its following run.\n void Cycle(size_t n) {\n std::unique_ptr prev_tm;\n std::unique_ptr prev_routing;\n for (size_t i = 0; i < n; ++i) {\n const TrafficMatrix* tm = prev_tm ? prev_tm.get() : initial_tm_;\n UpdateVolumes(*tm);\n\n RoutingSystemUpdateResult update_result =\n routing_system_->Update(SyntheticHistoryFromTM(*tm));\n auto& routing = update_result.routing;\n\n for (const auto& aggregate_and_routes : routing->routes()) {\n for (const auto& path_and_fraction : aggregate_and_routes.second) {\n path_to_fraction_[path_and_fraction.first].emplace_back(\n i, path_and_fraction.second);\n }\n }\n\n if (prev_routing) {\n deltas_.emplace_back(prev_routing->GetDifference(*routing));\n }\n prev_tm = ScaleBasedOnOutput(*routing, *tm);\n prev_routing = std::move(routing);\n }\n }\n\n void UpdateVolumes(const TrafficMatrix& tm) {\n for (const auto& aggregate_and_demands : tm.demands()) {\n const AggregateId& aggregate = aggregate_and_demands.first;\n volumes_[aggregate].emplace_back(aggregate_and_demands.second.first);\n }\n }\n\n std::map SyntheticHistoryFromTM(\n const TrafficMatrix& tm) {\n std::map out;\n for (const auto& aggregate_demand_and_flow_count : tm.demands()) {\n const AggregateId& aggregate = aggregate_demand_and_flow_count.first;\n nc::net::Bandwidth demand = aggregate_demand_and_flow_count.second.first;\n size_t flow_count = aggregate_demand_and_flow_count.second.second;\n\n out.emplace(std::piecewise_construct, std::forward_as_tuple(aggregate),\n std::forward_as_tuple(demand, kSyntheticBinCount,\n kSyntheticBinSize, flow_count));\n }\n\n return out;\n }\n\n \/\/ In the initial TM each aggregate's demand is what it would be if it were\n \/\/ routed on its shortest path.\n TrafficMatrix* initial_tm_;\n\n \/\/ The optimizer.\n RoutingSystem* routing_system_;\n\n \/\/ The graph.\n const nc::net::GraphStorage* graph_;\n\n \/\/ N - 1 deltas for each step to the next one.\n std::vector deltas_;\n\n \/\/ Per-aggregate volumes.\n std::map> volumes_;\n\n \/\/ Path to fractions of capacity.\n std::map>>\n path_to_fraction_;\n};\n\nstatic void RunWithSimpleTopologyTwoAggregates() {\n nc::net::GraphBuilder builder;\n std::chrono::microseconds ab_delay(\n static_cast(FLAGS_ab_link_ms * 1000));\n std::chrono::microseconds cd_delay(\n static_cast(FLAGS_cd_link_ms * 1000));\n\n builder.AddLink({\"A\", \"B\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),\n ab_delay});\n builder.AddLink({\"B\", \"A\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_link_gbps),\n ab_delay});\n builder.AddLink({\"A\", \"C\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n builder.AddLink({\"C\", \"A\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n builder.AddLink({\"C\", \"D\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),\n cd_delay});\n builder.AddLink({\"D\", \"C\",\n nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_link_gbps),\n cd_delay});\n builder.AddLink({\"B\", \"D\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n builder.AddLink({\"D\", \"B\", nc::net::Bandwidth::FromGBitsPerSecond(1),\n std::chrono::milliseconds(1)});\n\n nc::net::GraphStorage graph(builder);\n TrafficMatrix initial_tm(&graph);\n AggregateId id_one(\n {graph.NodeFromStringOrDie(\"A\"), graph.NodeFromStringOrDie(\"B\")});\n AggregateId id_two(\n {graph.NodeFromStringOrDie(\"C\"), graph.NodeFromStringOrDie(\"D\")});\n\n initial_tm.AddDemand(\n id_one, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_ab_aggregate_gbps),\n FLAGS_ab_aggregate_flows});\n initial_tm.AddDemand(\n id_two, {nc::net::Bandwidth::FromGBitsPerSecond(FLAGS_cd_aggregate_gbps),\n FLAGS_cd_aggregate_flows});\n\n PathProvider path_provider(&graph);\n std::unique_ptr opt;\n if (FLAGS_opt == \"CTR\") {\n opt = nc::make_unique(&path_provider, 1.0, true);\n } else if (FLAGS_opt == \"B4\") {\n opt = nc::make_unique(&path_provider, false, 1.0);\n } else if (FLAGS_opt == \"B4(P)\") {\n opt = nc::make_unique(&path_provider, true, 1.0);\n } else if (FLAGS_opt == \"MinMax\") {\n opt = nc::make_unique(&path_provider, 1.0);\n }\n\n MeanScaleEstimatorFactory estimator_factory(\n {1.1, FLAGS_decay_factor, FLAGS_decay_factor, 10});\n RoutingSystemConfig routing_system_config;\n routing_system_config.store_to_metrics = false;\n RoutingSystem routing_system(routing_system_config, opt.get(),\n &estimator_factory);\n StabilityEvalHarness harness(&initial_tm, &routing_system, FLAGS_steps);\n harness.DumpAggregateVolumes();\n harness.DumpLinkFractions();\n}\n\n} \/\/ namespace ctr\n\nint main(int argc, char** argv) {\n gflags::ParseCommandLineFlags(&argc, &argv, true);\n \/\/ ctr::RunWithSimpleTopology();\n ctr::RunWithSimpleTopologyTwoAggregates();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ $Id$\n\/\/ -*- C++ -*-\n\n\/\/***************************************************************************\n\/\/\n\/\/ File:\n\/\/ loadmodule.cc\n\/\/\n\/\/ Purpose:\n\/\/ LoadModule class for reading and gathering symbolic information\n\/\/ from a load module. (based on GNU Binutils).\n\/\/\n\/\/ Description:\n\/\/ [The set of functions, macros, etc. defined in the file]\n\/\/\n\/\/ Author:\n\/\/ Written by John Mellor-Crummey and Nathan Tallent, Rice University.\n\/\/\n\/\/ Adapted from parts of The Visual Profiler by Curtis L. Janssen\n\/\/ (exec.cc).\n\/\/\n\/\/***************************************************************************\n\n#ifdef __GNUC__\n#pragma implementation\n#endif\n\n\/\/************************* System Include Files ****************************\n\n#include \n\n\/\/*************************** User Include Files ****************************\n\n#include \"loadmodule.h\"\n\n\/\/*************************** Forward Declarations **************************\n\nusing namespace std;\n\n\/\/*************************** Forward Declarations **************************\n\nbool minisym_is_interesting(bfd *abfd, asymbol *p);\n\n#define valueof(x) ((x)->section->vma + (x)->value)\n\nint val_forward(const void *x, const void *y)\n{\n asymbol *xp = *(asymbol **)x;\n asymbol *yp = *(asymbol **)y;\n long yv = valueof(yp);\n long xv = valueof(xp);\n if (xv < yv) return -1; \n if (xv == yv) return 0; \n return 1;\n}\n\n\/\/***************************************************************************\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LoadModule\n\nLoadModule::LoadModule()\n{\n debug_ = 0;\n type_ = Unknown;\n}\n\nLoadModule::~LoadModule()\n{\n}\n\nbool\nLoadModule::line_info() const\n{\n return true;\n}\n\nbool\nLoadModule::file_info() const\n{\n return true;\n}\n\nbool\nLoadModule::func_info() const\n{\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ BFDLoadModule\n\nextern \"C\" { \n char *cplus_demangle (const char *mangled, int options); \n static int demangle_flags = (1 << 0) | (1 << 1);\n \/* FIXME: DMGL_PARAMS | DMGL_ANSI *\/\n}\n\n\nint BFDLoadModule::bfdinitialized_ = 0;\n\nBFDLoadModule::BFDLoadModule(const string &name)\n{\n if (!bfdinitialized_) {\n bfd_init();\n bfdinitialized_ = 1;\n }\n bfd_ = 0;\n symbols_ = 0;\n\n read(name);\n}\n\nBFDLoadModule::~BFDLoadModule()\n{\n cleanup();\n}\n\nvoid\nBFDLoadModule::cleanup(bool clear_cache)\n{\n name_ = \"\";\n if (bfd_) {\n bfd_close(bfd_);\n bfd_ = 0;\n }\n delete[] (char*)symbols_;\n symbols_ = 0;\n if (clear_cache) locmap_.clear();\n}\n\nextern \"C\" {\n static void\n BFDLoadModule_find_address_in_section(bfd*b, asection* sect, PTR exec)\n {\n BFDLoadModule::find_address_in_section(b, sect, exec);\n }\n}\n\nvoid\nBFDLoadModule::read(const string &name)\n{\n read_file(name);\n}\n\nbool BFDLoadModule::minisyms_;\nint BFDLoadModule::dynoffset_;\n\nvoid\nBFDLoadModule::read_file(const string &name, bool clear_cache)\n{\n cleanup(clear_cache);\n name_ = name;\n\n#if 0\n cerr << \"Reading: \" << name << endl;\n#endif\n bfd_ = bfd_openr(name_.c_str(), 0);\n minisyms_ = false;\n if (!bfd_) {\n cleanup();\n return;\n }\n\n if (!bfd_check_format(bfd_, bfd_object)) {\n cleanup();\n return;\n }\n\n flagword flags = bfd_get_file_flags(bfd_);\n if (flags & EXEC_P) { \/\/ BFD is directly executable\n type_ = Exe;\n } else if (flags & DYNAMIC) { \/\/ BFD is a dynamic object\n type_ = DSO;\n } \n\n if (type_ == DSO) {\n long symcount;\n PTR minisyms;\n unsigned int size;\n struct size_sym *symsizes;\n asymbol *tmp_symbol, *mk_sym;\n int i;\n \n symcount = bfd_read_minisymbols (bfd_, bfd_tttrue, &minisyms, &size);\n symbols_ = (asymbol**)(new char[(symcount+1)*sizeof(asymbol *)]);\n#if 0\n cerr << \"Mini symbols semiloaded: \" << symcount << endl;\n#endif\n tmp_symbol = NULL;\n asymbol *res = NULL;\n int nsyms = 0;\n for (i = 0; i < symcount; i++) {\n if (res == tmp_symbol) {\n\ttmp_symbol = bfd_make_empty_symbol (bfd_);\n }\n res = bfd_minisymbol_to_symbol(bfd_, bfd_tttrue, \n\t\t\t\t (PTR)(((char *)minisyms)+i*size), \n\t\t\t\t tmp_symbol);\n if (minisym_is_interesting(bfd_, res)) {\n\tsymbols_[nsyms++] = res;\n } else {\n\tres = NULL;\n }\n }\n \n qsort(symbols_, nsyms, sizeof(asymbol*), val_forward);\n \n symbols_[nsyms] = NULL;\n#if 0\n cerr << \"Mini symbols loaded: \" << nsyms << endl;\n#endif\n minisyms_ = true;\n }\n else {\n long int symsize = bfd_get_symtab_upper_bound(bfd_);\n if (!symsize) {\n cleanup();\n return;\n }\n \n symbols_ = (asymbol**)(new char[symsize]);\n if (!symbols_) {\n cleanup();\n return;\n }\n \n int numsym = bfd_canonicalize_symtab(bfd_, symbols_);\n#if 0\n cerr << \"Number of symbols loaded: \" << numsym << endl;\n#endif\n \n minisyms_ = false;\n }\n}\n\nbfd_vma BFDLoadModule::pc_ = 0;\nconst char *BFDLoadModule::filename_ = 0;\nconst char *BFDLoadModule::functionname_ = 0;\nunsigned int BFDLoadModule::line_ = 0;\nbool BFDLoadModule::found_ = false;\n\nbool \nminisym_is_interesting(bfd *abfd, asymbol *p)\n{\n symbol_info syminfo;\n bfd_get_symbol_info (abfd, p, &syminfo);\n return (syminfo.type == 'T') || (syminfo.type == 't');\n}\n\nvoid\nBFDLoadModule::find_address_in_section(bfd* abfd, asection* section, PTR exec)\n{\n BFDLoadModule *e = static_cast(exec);\n\n bfd_vma vma;\n bfd_size_type size;\n\n if (!e->debug() && e->found_)\n return;\n\n if ((bfd_get_section_flags (abfd, section) & SEC_ALLOC) == 0) {\n return;\n }\n\n vma = bfd_get_section_vma (abfd, section);\n size = bfd_get_section_size_before_reloc (section);\n\n \/\/ FIXME: these debugging messages should removed or placed within\n \/\/ debug conditionals\n#if 0\n cerr << \"Section: vma=\" << vma << \", size=\" << size << \", dynoffset=\" \n << dynoffset_ << \", flags=\" << bfd_get_section_flags (abfd, section) \n << endl;\n#endif\n\n const char *tmp_filename = 0;\n const char *tmp_funcname = 0;\n unsigned int tmp_line = 0;\n bool tmp_found = false;\n\n#if 0\n cerr << \"Looking for pc_: \" << e->pc_ << endl;\n#endif\n if (minisyms_) {\n asymbol **p;\n unsigned long offset, bestoff;\n asymbol *bestsym;\n \n if (e->pc_ >= vma && e->pc_ < vma + size) {\n bfd_find_nearest_line (abfd, section, e->symbols_, e->pc_ - vma,\n\t\t\t &tmp_filename, &tmp_funcname,\n\t\t\t &tmp_line);\n#if 0\n cerr << \"FNL: pc=\" << e->pc_ << \", funcname=\" << tmp_funcname << endl;\n#endif\n bestsym = (asymbol *)0;\n offset = e->pc_;\n bestoff = 0;\n for (p = e->symbols_; *p != NULL; p++) {\n\tsymbol_info syminfo;\n\tbfd_get_symbol_info (abfd, *p, &syminfo);\n#if 0\n\tcerr << \"symbol: sym=\" << syminfo.value << \" offset=\" << offset \n\t << \" best=\" << bestoff << \" name=\" << syminfo.name << endl;\n#endif\n\tif (offset >= syminfo.value && bestoff < syminfo.value) {\n\t bestoff = syminfo.value;\n#if 0\n\t cerr << \"better symbol match: sym=\"<< offset \n\t << \" best=\" << bestoff << \"name =\" << syminfo.name << endl;\n#endif\n\t bestsym = (*p);\n \t tmp_funcname = syminfo.name;\n\t}\n }\n if (bestsym) {\n tmp_found = true;\n tmp_filename = (char *)0;\n tmp_line = 0;\n#if 0\n cerr << \"pc_: \" << e->pc_ << \", vma: \" << vma << \",size: \" << size \n\t << \", bestoff: \" << bestoff << \", funcname: \" << tmp_funcname\n\t << endl;\n#endif\n }\n }\n dynoffset_ += size;\n }\n else {\n if (e->pc_ >= vma && e->pc_ < vma + size)\n tmp_found = bfd_find_nearest_line (abfd, section, e->symbols_, \n\t\t\t\t\t e->pc_ - vma, &tmp_filename, \n\t\t\t\t\t &tmp_funcname, &tmp_line);\n }\n if (!tmp_found) {\n#if 0\n cerr << \"pc_: \" << (void*)e->pc_ << \" NOT FOUND\" << endl;\n#endif\n }\n \n if (e->debug() && (tmp_found || tmp_filename || tmp_funcname || tmp_line)) {\n cerr << \" { bfd sec find: (\" << tmp_found << \")\"\n\t << \", file = \" << tmp_filename\n\t << \", func = \" << tmp_funcname\n\t << \", line = \" << tmp_line << \" }\" << endl;\n }\n if (!e->found_) {\n e->found_ = tmp_found;\n e->filename_ = tmp_filename;\n e->functionname_ = tmp_funcname;\n e->line_ = tmp_line;\n }\n}\n\ntime_t\nBFDLoadModule::mtime() const\n{\n if (!bfd_) return 0;\n return bfd_get_mtime(bfd_);\n}\n\nstd::string\nBFDLoadModule::name() const\n{\n return name_;\n}\n\npprof_off_t\nBFDLoadModule::textstart() const\n{\n return 0;\n}\n\nstring\nBFDLoadModule::demangle(const string &name) const\n{\n char *demangled = cplus_demangle(name.c_str(), demangle_flags);\n string r;\n if (demangled) {\n r = demangled;\n free(demangled);\n }\n else {\n r = name;\n }\n return r;\n}\n\nvoid\nBFDLoadModule::find_bfd(pprof_off_t pc, const char **filename,\n unsigned int *lineno, const char **funcname) const\n{\n pc_ = pc;\n dynoffset_ = 0;\n found_ = false;\n functionname_ = 0;\n line_ = 0;\n filename_ = 0;\n bfd_map_over_sections(bfd_, BFDLoadModule_find_address_in_section,\n (PTR) this);\n\n if (funcname) *funcname = functionname_;\n if (lineno) *lineno = line_;\n if (filename) *filename = filename_;\n}\n\nint\nBFDLoadModule::find(pprof_off_t pc, const char **filename,\n unsigned int *lineno, const char **funcname) const\n{\n if (!bfd_) return 0;\n\n std::map::iterator ilocmap = locmap_.find(pc);\n if (ilocmap != locmap_.end()) {\n FuncInfo &funcinfo = (*ilocmap).second;\n if (funcinfo.file().size() > 0) *filename = funcinfo.c_file();\n else *filename = 0;\n if (funcinfo.name().size() > 0) *funcname = funcinfo.c_name();\n else *funcname = 0;\n *lineno = funcinfo.index();\n return 1;\n }\n\n find_bfd(pc, filename, lineno, funcname);\n\n if (line_ == 0) {\n \/\/ possible BFD problem--reinitialize and try again\n const_cast(this)->read_file(name(),false);\n find_bfd(pc, filename, lineno, funcname);\n if (debug_ && line_ != 0) {\n cerr << \"WARNING: BFD lineno == 0 problem detected\" << endl;\n }\n }\n\n if (debug_) {\n#if 0\n const char* pre = \" \";\n cerr << pre << \"{ bfd find @ \" << (void*)pc << \": \" << *funcname << endl\n\t << pre << \" [\" << *filename << \":\" << *lineno << \"] }\" << endl;\n#endif\n }\n\n locmap_[pc].set_index(*lineno);\n if (*funcname) locmap_[pc].set_name(*funcname);\n if (*filename) locmap_[pc].set_file(*filename);\n\n return found_;\n}\n\n'(bfd_boolean)true' seems more elegant than 'bfd_tttrue' (Thanks to Nils Smeds)\/\/ $Id$\n\/\/ -*- C++ -*-\n\n\/\/***************************************************************************\n\/\/\n\/\/ File:\n\/\/ loadmodule.cc\n\/\/\n\/\/ Purpose:\n\/\/ LoadModule class for reading and gathering symbolic information\n\/\/ from a load module. (based on GNU Binutils).\n\/\/\n\/\/ Description:\n\/\/ [The set of functions, macros, etc. defined in the file]\n\/\/\n\/\/ Author:\n\/\/ Written by John Mellor-Crummey and Nathan Tallent, Rice University.\n\/\/\n\/\/ Adapted from parts of The Visual Profiler by Curtis L. Janssen\n\/\/ (exec.cc).\n\/\/\n\/\/***************************************************************************\n\n#ifdef __GNUC__\n#pragma implementation\n#endif\n\n\/\/************************* System Include Files ****************************\n\n#include \n\n\/\/*************************** User Include Files ****************************\n\n#include \"loadmodule.h\"\n\n\/\/*************************** Forward Declarations **************************\n\nusing namespace std;\n\n\/\/*************************** Forward Declarations **************************\n\nbool minisym_is_interesting(bfd *abfd, asymbol *p);\n\n#define valueof(x) ((x)->section->vma + (x)->value)\n\nint val_forward(const void *x, const void *y)\n{\n asymbol *xp = *(asymbol **)x;\n asymbol *yp = *(asymbol **)y;\n long yv = valueof(yp);\n long xv = valueof(xp);\n if (xv < yv) return -1; \n if (xv == yv) return 0; \n return 1;\n}\n\n\/\/***************************************************************************\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ LoadModule\n\nLoadModule::LoadModule()\n{\n debug_ = 0;\n type_ = Unknown;\n}\n\nLoadModule::~LoadModule()\n{\n}\n\nbool\nLoadModule::line_info() const\n{\n return true;\n}\n\nbool\nLoadModule::file_info() const\n{\n return true;\n}\n\nbool\nLoadModule::func_info() const\n{\n return true;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ BFDLoadModule\n\nextern \"C\" { \n char *cplus_demangle (const char *mangled, int options); \n static int demangle_flags = (1 << 0) | (1 << 1);\n \/* FIXME: DMGL_PARAMS | DMGL_ANSI *\/\n}\n\n\nint BFDLoadModule::bfdinitialized_ = 0;\n\nBFDLoadModule::BFDLoadModule(const string &name)\n{\n if (!bfdinitialized_) {\n bfd_init();\n bfdinitialized_ = 1;\n }\n bfd_ = 0;\n symbols_ = 0;\n\n read(name);\n}\n\nBFDLoadModule::~BFDLoadModule()\n{\n cleanup();\n}\n\nvoid\nBFDLoadModule::cleanup(bool clear_cache)\n{\n name_ = \"\";\n if (bfd_) {\n bfd_close(bfd_);\n bfd_ = 0;\n }\n delete[] (char*)symbols_;\n symbols_ = 0;\n if (clear_cache) locmap_.clear();\n}\n\nextern \"C\" {\n static void\n BFDLoadModule_find_address_in_section(bfd*b, asection* sect, PTR exec)\n {\n BFDLoadModule::find_address_in_section(b, sect, exec);\n }\n}\n\nvoid\nBFDLoadModule::read(const string &name)\n{\n read_file(name);\n}\n\nbool BFDLoadModule::minisyms_;\nint BFDLoadModule::dynoffset_;\n\nvoid\nBFDLoadModule::read_file(const string &name, bool clear_cache)\n{\n cleanup(clear_cache);\n name_ = name;\n\n#if 0\n cerr << \"Reading: \" << name << endl;\n#endif\n bfd_ = bfd_openr(name_.c_str(), 0);\n minisyms_ = false;\n if (!bfd_) {\n cleanup();\n return;\n }\n\n if (!bfd_check_format(bfd_, bfd_object)) {\n cleanup();\n return;\n }\n\n flagword flags = bfd_get_file_flags(bfd_);\n if (flags & EXEC_P) { \/\/ BFD is directly executable\n type_ = Exe;\n } else if (flags & DYNAMIC) { \/\/ BFD is a dynamic object\n type_ = DSO;\n } \n\n if (type_ == DSO) {\n long symcount;\n PTR minisyms;\n unsigned int size;\n struct size_sym *symsizes;\n asymbol *tmp_symbol, *mk_sym;\n int i;\n \n symcount = bfd_read_minisymbols (bfd_, (bfd_boolean)true, &minisyms, &size);\n symbols_ = (asymbol**)(new char[(symcount+1)*sizeof(asymbol *)]);\n#if 0\n cerr << \"Mini symbols semiloaded: \" << symcount << endl;\n#endif\n tmp_symbol = NULL;\n asymbol *res = NULL;\n int nsyms = 0;\n for (i = 0; i < symcount; i++) {\n if (res == tmp_symbol) {\n\ttmp_symbol = bfd_make_empty_symbol (bfd_);\n }\n res = bfd_minisymbol_to_symbol(bfd_, (bfd_boolean)true, \n\t\t\t\t (PTR)(((char *)minisyms)+i*size), \n\t\t\t\t tmp_symbol);\n if (minisym_is_interesting(bfd_, res)) {\n\tsymbols_[nsyms++] = res;\n } else {\n\tres = NULL;\n }\n }\n \n qsort(symbols_, nsyms, sizeof(asymbol*), val_forward);\n \n symbols_[nsyms] = NULL;\n#if 0\n cerr << \"Mini symbols loaded: \" << nsyms << endl;\n#endif\n minisyms_ = true;\n }\n else {\n long int symsize = bfd_get_symtab_upper_bound(bfd_);\n if (!symsize) {\n cleanup();\n return;\n }\n \n symbols_ = (asymbol**)(new char[symsize]);\n if (!symbols_) {\n cleanup();\n return;\n }\n \n int numsym = bfd_canonicalize_symtab(bfd_, symbols_);\n#if 0\n cerr << \"Number of symbols loaded: \" << numsym << endl;\n#endif\n \n minisyms_ = false;\n }\n}\n\nbfd_vma BFDLoadModule::pc_ = 0;\nconst char *BFDLoadModule::filename_ = 0;\nconst char *BFDLoadModule::functionname_ = 0;\nunsigned int BFDLoadModule::line_ = 0;\nbool BFDLoadModule::found_ = false;\n\nbool \nminisym_is_interesting(bfd *abfd, asymbol *p)\n{\n symbol_info syminfo;\n bfd_get_symbol_info (abfd, p, &syminfo);\n return (syminfo.type == 'T') || (syminfo.type == 't');\n}\n\nvoid\nBFDLoadModule::find_address_in_section(bfd* abfd, asection* section, PTR exec)\n{\n BFDLoadModule *e = static_cast(exec);\n\n bfd_vma vma;\n bfd_size_type size;\n\n if (!e->debug() && e->found_)\n return;\n\n if ((bfd_get_section_flags (abfd, section) & SEC_ALLOC) == 0) {\n return;\n }\n\n vma = bfd_get_section_vma (abfd, section);\n size = bfd_get_section_size_before_reloc (section);\n\n \/\/ FIXME: these debugging messages should removed or placed within\n \/\/ debug conditionals\n#if 0\n cerr << \"Section: vma=\" << vma << \", size=\" << size << \", dynoffset=\" \n << dynoffset_ << \", flags=\" << bfd_get_section_flags (abfd, section) \n << endl;\n#endif\n\n const char *tmp_filename = 0;\n const char *tmp_funcname = 0;\n unsigned int tmp_line = 0;\n bool tmp_found = false;\n\n#if 0\n cerr << \"Looking for pc_: \" << e->pc_ << endl;\n#endif\n if (minisyms_) {\n asymbol **p;\n unsigned long offset, bestoff;\n asymbol *bestsym;\n \n if (e->pc_ >= vma && e->pc_ < vma + size) {\n bfd_find_nearest_line (abfd, section, e->symbols_, e->pc_ - vma,\n\t\t\t &tmp_filename, &tmp_funcname,\n\t\t\t &tmp_line);\n#if 0\n cerr << \"FNL: pc=\" << e->pc_ << \", funcname=\" << tmp_funcname << endl;\n#endif\n bestsym = (asymbol *)0;\n offset = e->pc_;\n bestoff = 0;\n for (p = e->symbols_; *p != NULL; p++) {\n\tsymbol_info syminfo;\n\tbfd_get_symbol_info (abfd, *p, &syminfo);\n#if 0\n\tcerr << \"symbol: sym=\" << syminfo.value << \" offset=\" << offset \n\t << \" best=\" << bestoff << \" name=\" << syminfo.name << endl;\n#endif\n\tif (offset >= syminfo.value && bestoff < syminfo.value) {\n\t bestoff = syminfo.value;\n#if 0\n\t cerr << \"better symbol match: sym=\"<< offset \n\t << \" best=\" << bestoff << \"name =\" << syminfo.name << endl;\n#endif\n\t bestsym = (*p);\n \t tmp_funcname = syminfo.name;\n\t}\n }\n if (bestsym) {\n tmp_found = true;\n tmp_filename = (char *)0;\n tmp_line = 0;\n#if 0\n cerr << \"pc_: \" << e->pc_ << \", vma: \" << vma << \",size: \" << size \n\t << \", bestoff: \" << bestoff << \", funcname: \" << tmp_funcname\n\t << endl;\n#endif\n }\n }\n dynoffset_ += size;\n }\n else {\n if (e->pc_ >= vma && e->pc_ < vma + size)\n tmp_found = bfd_find_nearest_line (abfd, section, e->symbols_, \n\t\t\t\t\t e->pc_ - vma, &tmp_filename, \n\t\t\t\t\t &tmp_funcname, &tmp_line);\n }\n if (!tmp_found) {\n#if 0\n cerr << \"pc_: \" << (void*)e->pc_ << \" NOT FOUND\" << endl;\n#endif\n }\n \n if (e->debug() && (tmp_found || tmp_filename || tmp_funcname || tmp_line)) {\n cerr << \" { bfd sec find: (\" << tmp_found << \")\"\n\t << \", file = \" << tmp_filename\n\t << \", func = \" << tmp_funcname\n\t << \", line = \" << tmp_line << \" }\" << endl;\n }\n if (!e->found_) {\n e->found_ = tmp_found;\n e->filename_ = tmp_filename;\n e->functionname_ = tmp_funcname;\n e->line_ = tmp_line;\n }\n}\n\ntime_t\nBFDLoadModule::mtime() const\n{\n if (!bfd_) return 0;\n return bfd_get_mtime(bfd_);\n}\n\nstd::string\nBFDLoadModule::name() const\n{\n return name_;\n}\n\npprof_off_t\nBFDLoadModule::textstart() const\n{\n return 0;\n}\n\nstring\nBFDLoadModule::demangle(const string &name) const\n{\n char *demangled = cplus_demangle(name.c_str(), demangle_flags);\n string r;\n if (demangled) {\n r = demangled;\n free(demangled);\n }\n else {\n r = name;\n }\n return r;\n}\n\nvoid\nBFDLoadModule::find_bfd(pprof_off_t pc, const char **filename,\n unsigned int *lineno, const char **funcname) const\n{\n pc_ = pc;\n dynoffset_ = 0;\n found_ = false;\n functionname_ = 0;\n line_ = 0;\n filename_ = 0;\n bfd_map_over_sections(bfd_, BFDLoadModule_find_address_in_section,\n (PTR) this);\n\n if (funcname) *funcname = functionname_;\n if (lineno) *lineno = line_;\n if (filename) *filename = filename_;\n}\n\nint\nBFDLoadModule::find(pprof_off_t pc, const char **filename,\n unsigned int *lineno, const char **funcname) const\n{\n if (!bfd_) return 0;\n\n std::map::iterator ilocmap = locmap_.find(pc);\n if (ilocmap != locmap_.end()) {\n FuncInfo &funcinfo = (*ilocmap).second;\n if (funcinfo.file().size() > 0) *filename = funcinfo.c_file();\n else *filename = 0;\n if (funcinfo.name().size() > 0) *funcname = funcinfo.c_name();\n else *funcname = 0;\n *lineno = funcinfo.index();\n return 1;\n }\n\n find_bfd(pc, filename, lineno, funcname);\n\n if (line_ == 0) {\n \/\/ possible BFD problem--reinitialize and try again\n const_cast(this)->read_file(name(),false);\n find_bfd(pc, filename, lineno, funcname);\n if (debug_ && line_ != 0) {\n cerr << \"WARNING: BFD lineno == 0 problem detected\" << endl;\n }\n }\n\n if (debug_) {\n#if 0\n const char* pre = \" \";\n cerr << pre << \"{ bfd find @ \" << (void*)pc << \": \" << *funcname << endl\n\t << pre << \" [\" << *filename << \":\" << *lineno << \"] }\" << endl;\n#endif\n }\n\n locmap_[pc].set_index(*lineno);\n if (*funcname) locmap_[pc].set_name(*funcname);\n if (*filename) locmap_[pc].set_file(*filename);\n\n return found_;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \/\/ DEBUGTOOL\n\n#include \"ingameelements\/weapons\/hammer.h\"\n#include \"renderer.h\"\n#include \"ingameelements\/heroes\/reinhardt.h\"\n#include \"ingameelements\/projectiles\/firestrike.h\"\n\n#include \"engine.h\"\n\nvoid Hammer::init(uint64_t id_, Gamestate &state, EntityPtr owner_)\n{\n Weapon::init(id_, state, owner_);\n\n barrierptr = state.make_entity(state, team, owner_);\n\n firestrikeanim.init(herofolder()+\"firestrikebackarm\/\");\n firestrikeanim.active(false);\n firestrikedelay.init(firestrikeanim.timer.duration * 0.5,\n std::bind(&Hammer::createfirestrike, this, std::placeholders::_1));\n firestrikedelay.active = false;\n \/\/ 6th and 14th frame of an assumed 20 frame animation - ugly but idk better way\n firingdelay1.init(firinganim.timer.duration * 6.0\/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));\n firingdelay1.active = false;\n firingdelay2.init(firinganim.timer.duration * 14.0\/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));\n firingdelay2.active = false;\n}\n\nvoid Hammer::renderbehind(Renderer &renderer, Gamestate &state)\n{\n if (firinganim.active())\n {\n return;\n }\n\n std::string mainsprite;\n Reinhardt &c = state.get(state.get(owner).character);\n if (firestrikeanim.active())\n {\n mainsprite = firestrikeanim.getframepath();\n }\n else if (barrier(state).active)\n {\n mainsprite = herofolder()+\"shield\/back\";\n\n }\n else\n {\n mainsprite = herofolder()+\"arm\/back\";\n }\n ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);\n double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;\n double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;\n double rel_x = (x - renderer.cam_x)*renderer.zoom;\n double rel_y = (y - renderer.cam_y)*renderer.zoom;\n double attachpt_x = getbackattachpoint_x(state)*renderer.zoom;\n double attachpt_y = getbackattachpoint_y(state)*renderer.zoom;\n\n ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);\n ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);\n\n al_set_target_bitmap(renderer.midground);\n if (c.weaponvisible(state))\n {\n if (c.isflipped)\n {\n al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y,\n -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y,\n -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);\n }\n }\n else\n {\n al_draw_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y, aimdirection*barrier(state).active, 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, aimdirection*barrier(state).active, 0);\n }\n }\n }\n}\n\nvoid Hammer::render(Renderer &renderer, Gamestate &state)\n{\n std::string mainsprite;\n Reinhardt &c = state.get(state.get(owner).character);\n if (firinganim.active())\n {\n mainsprite = firinganim.getframepath();\n }\n else if (firestrikeanim.active())\n {\n mainsprite = herofolder()+\"firestrikefrontarm\/\"+std::to_string(firestrikeanim.getframe());\n }\n else if (barrier(state).active)\n {\n mainsprite = herofolder()+\"shield\/front\";\n\n }\n else\n {\n mainsprite = herofolder()+\"arm\/front\";\n }\n ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);\n double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;\n double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;\n double rel_x = (x - renderer.cam_x)*renderer.zoom;\n double rel_y = (y - renderer.cam_y)*renderer.zoom;\n double attachpt_x = getattachpoint_x(state)*renderer.zoom;\n double attachpt_y = getattachpoint_y(state)*renderer.zoom;\n\n ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);\n ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);\n\n al_set_target_bitmap(renderer.midground);\n if (c.weaponvisible(state))\n {\n if (c.isflipped)\n {\n al_draw_scaled_rotated_bitmap(sprite, -attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);\n }\n }\n else\n {\n al_draw_bitmap(sprite, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_bitmap(outline, outlinecolor, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);\n }\n }\n }\n\n barrier(state).render(renderer, state);\n\n al_draw_rectangle(rel_x + renderer.zoom*30 * (c.isflipped ? -1 : 1), rel_y - renderer.zoom*30,\n rel_x + renderer.zoom*59 * (c.isflipped ? -1 : 1), rel_y + renderer.zoom*30, al_map_rgb(255, 0, 0), 0);\n}\n\nvoid Hammer::beginstep(Gamestate &state, double frametime)\n{\n Weapon::beginstep(state, frametime);\n barrier(state).beginstep(state, frametime);\n firestrikeanim.update(state, frametime);\n firestrikedelay.update(state, frametime);\n}\n\nvoid Hammer::midstep(Gamestate &state, double frametime)\n{\n Weapon::midstep(state, frametime);\n barrier(state).midstep(state, frametime);\n}\n\nvoid Hammer::endstep(Gamestate &state, double frametime)\n{\n Weapon::endstep(state, frametime);\n barrier(state).endstep(state, frametime);\n}\n\nvoid Hammer::wantfireprimary(Gamestate &state)\n{\n if (state.engine.isserver and not firinganim.active() and not firestrikeanim.active())\n {\n fireprimary(state);\n state.engine.sendbuffer.write(PRIMARY_FIRED);\n state.engine.sendbuffer.write(state.findplayerid(owner));\n }\n}\n\nvoid Hammer::fireprimary(Gamestate &state)\n{\n firinganim.reset();\n firinganim.active(true);\n}\n\nvoid Hammer::wantfiresecondary(Gamestate &state)\n{\n \/\/ Do nothing\n}\n\nvoid Hammer::firesecondary(Gamestate &state)\n{\n \/\/ Do nothing\n}\n\nvoid Hammer::createfirestrike(Gamestate &state)\n{\n Firestrike &firestrike = state.get(state.make_entity(state, owner));\n firestrike.x = x + std::cos(aimdirection) * 40;\n firestrike.y = y + std::sin(aimdirection) * 40;\n firestrike.hspeed = firestrike.SPEED * std::cos(aimdirection);\n firestrike.vspeed = firestrike.SPEED * std::sin(aimdirection);\n\n if (state.currentmap->collideline(x, y, firestrike.x, firestrike.y))\n {\n firestrike.destroy(state);\n }\n}\n\nvoid Hammer::hitarea(Gamestate &state)\n{\n for (auto &e : state.entitylist)\n {\n auto &entity = *(e.second);\n if (not entity.destroyentity)\n {\n if (entity.damageableby(team))\n {\n Reinhardt &c = state.get(state.get(owner).character);\n int direction = (c.isflipped ? -1 : 1);\n for (int i=0; i<30; ++i)\n {\n for (int j=0; j<60; ++j)\n {\n if (entity.collides(state, x + direction*(30 + i), y - 30 + direction*j))\n {\n Global::logging().print(__FILE__, __LINE__, \"Hit some entity\");\n \/\/ We hit something, check if it's protected\n double tmpx, tmpy;\n if (state.collidelinetarget(state, x, y, state.get(entity.id), team,\n PENETRATE_CHARACTER, &tmpx, &tmpy).id == entity.id)\n {\n Global::logging().print(__FILE__, __LINE__, \"Damage\");\n entity.damage(state, DAMAGE);\n }\n else\n {\n Global::logging().print(__FILE__, __LINE__, \"%i is protected by %i\", entity.id, state.collidelinetarget(state, x, y, state.get(entity.id), team,\n PENETRATE_CHARACTER, &tmpx, &tmpy).id);\n }\n return;\n }\n }\n }\n }\n }\n }\n}\n\ndouble Hammer::getattachpoint_x(Gamestate &state)\n{\n return 0;\n}\n\ndouble Hammer::getattachpoint_y(Gamestate &state)\n{\n return 8;\n}\n\ndouble Hammer::getbackattachpoint_x(Gamestate &state)\n{\n if (barrier(state).active)\n {\n return 6 * (state.get(owner).getcharacter(state).isflipped ? 1:-1);\n }\n else\n {\n return 0;\n }\n}\n\ndouble Hammer::getbackattachpoint_y(Gamestate &state)\n{\n if (barrier(state).active)\n {\n return 10;\n }\n else\n {\n return 8;\n }\n}\n\nReinhardtShield& Hammer::barrier(Gamestate &state)\n{\n return state.get(barrierptr);\n}\n\nvoid Hammer::destroy(Gamestate &state)\n{\n barrier(state).destroy(state);\n Weapon::destroy(state);\n}\n\nvoid Hammer::interpolate(Entity &prev_entity, Entity &next_entity, double alpha)\n{\n Weapon::interpolate(prev_entity, next_entity, alpha);\n\n Hammer &prev_e = static_cast(prev_entity);\n Hammer &next_e = static_cast(next_entity);\n\n firestrikeanim.interpolate(prev_e.firestrikeanim, next_e.firestrikeanim, alpha);\n firestrikedelay.interpolate(prev_e.firestrikedelay, next_e.firestrikedelay, alpha);\n firinganim.interpolate(prev_e.firinganim, next_e.firinganim, alpha);\n firingdelay1.interpolate(prev_e.firingdelay1, next_e.firingdelay1, alpha);\n firingdelay2.interpolate(prev_e.firingdelay2, next_e.firingdelay2, alpha);\n}Finished hammer damage.#include \n\n#include \"ingameelements\/weapons\/hammer.h\"\n#include \"renderer.h\"\n#include \"ingameelements\/heroes\/reinhardt.h\"\n#include \"ingameelements\/projectiles\/firestrike.h\"\n\n#include \"engine.h\"\n\nvoid Hammer::init(uint64_t id_, Gamestate &state, EntityPtr owner_)\n{\n Weapon::init(id_, state, owner_);\n\n barrierptr = state.make_entity(state, team, owner_);\n\n firestrikeanim.init(herofolder()+\"firestrikebackarm\/\");\n firestrikeanim.active(false);\n firestrikedelay.init(firestrikeanim.timer.duration * 0.5,\n std::bind(&Hammer::createfirestrike, this, std::placeholders::_1));\n firestrikedelay.active = false;\n \/\/ 6th and 14th frame of an assumed 20 frame animation - ugly but idk better way\n firingdelay1.init(firinganim.timer.duration * 6.0\/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));\n firingdelay1.active = false;\n firingdelay2.init(firinganim.timer.duration * 14.0\/20.0, std::bind(&Hammer::hitarea, this, std::placeholders::_1));\n firingdelay2.active = false;\n}\n\nvoid Hammer::renderbehind(Renderer &renderer, Gamestate &state)\n{\n if (firinganim.active())\n {\n return;\n }\n\n std::string mainsprite;\n Reinhardt &c = state.get(state.get(owner).character);\n if (firestrikeanim.active())\n {\n mainsprite = firestrikeanim.getframepath();\n }\n else if (barrier(state).active)\n {\n mainsprite = herofolder()+\"shield\/back\";\n\n }\n else\n {\n mainsprite = herofolder()+\"arm\/back\";\n }\n ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);\n double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;\n double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;\n double rel_x = (x - renderer.cam_x)*renderer.zoom;\n double rel_y = (y - renderer.cam_y)*renderer.zoom;\n double attachpt_x = getbackattachpoint_x(state)*renderer.zoom;\n double attachpt_y = getbackattachpoint_y(state)*renderer.zoom;\n\n ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);\n ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);\n\n al_set_target_bitmap(renderer.midground);\n if (c.weaponvisible(state))\n {\n if (c.isflipped)\n {\n al_draw_scaled_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y,\n -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y,\n -1, 1, (aimdirection+3.1415)*barrier(state).active, 0);\n }\n }\n else\n {\n al_draw_rotated_bitmap(sprite, spriteoffset_x, spriteoffset_y, rel_x-attachpt_x, rel_y-attachpt_y, aimdirection*barrier(state).active, 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, aimdirection*barrier(state).active, 0);\n }\n }\n }\n}\n\nvoid Hammer::render(Renderer &renderer, Gamestate &state)\n{\n std::string mainsprite;\n Reinhardt &c = state.get(state.get(owner).character);\n if (firinganim.active())\n {\n mainsprite = firinganim.getframepath();\n }\n else if (firestrikeanim.active())\n {\n mainsprite = herofolder()+\"firestrikefrontarm\/\"+std::to_string(firestrikeanim.getframe());\n }\n else if (barrier(state).active)\n {\n mainsprite = herofolder()+\"shield\/front\";\n\n }\n else\n {\n mainsprite = herofolder()+\"arm\/front\";\n }\n ALLEGRO_BITMAP *sprite = renderer.spriteloader.requestsprite(mainsprite);\n double spriteoffset_x = renderer.spriteloader.get_spriteoffset_x(mainsprite)*renderer.zoom;\n double spriteoffset_y = renderer.spriteloader.get_spriteoffset_y(mainsprite)*renderer.zoom;\n double rel_x = (x - renderer.cam_x)*renderer.zoom;\n double rel_y = (y - renderer.cam_y)*renderer.zoom;\n double attachpt_x = getattachpoint_x(state)*renderer.zoom;\n double attachpt_y = getattachpoint_y(state)*renderer.zoom;\n\n ALLEGRO_BITMAP *outline = renderer.spriteloader.requestspriteoutline(mainsprite);\n ALLEGRO_COLOR outlinecolor = al_map_rgb(225, 17, 17);\n\n al_set_target_bitmap(renderer.midground);\n if (c.weaponvisible(state))\n {\n if (c.isflipped)\n {\n al_draw_scaled_rotated_bitmap(sprite, -attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_scaled_rotated_bitmap(outline, outlinecolor, attachpt_x+spriteoffset_x, attachpt_y+spriteoffset_y, rel_x, rel_y, -1, 1, 0, 0);\n }\n }\n else\n {\n al_draw_bitmap(sprite, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);\n if (state.get(renderer.myself).team != team)\n {\n \/\/ Draw enemy outline\n al_draw_tinted_bitmap(outline, outlinecolor, rel_x - (attachpt_x+spriteoffset_x), rel_y - (attachpt_y+spriteoffset_y), 0);\n }\n }\n }\n\n barrier(state).render(renderer, state);\n}\n\nvoid Hammer::beginstep(Gamestate &state, double frametime)\n{\n Weapon::beginstep(state, frametime);\n barrier(state).beginstep(state, frametime);\n firestrikeanim.update(state, frametime);\n firestrikedelay.update(state, frametime);\n firingdelay1.update(state, frametime);\n firingdelay2.update(state, frametime);\n}\n\nvoid Hammer::midstep(Gamestate &state, double frametime)\n{\n Weapon::midstep(state, frametime);\n barrier(state).midstep(state, frametime);\n}\n\nvoid Hammer::endstep(Gamestate &state, double frametime)\n{\n Weapon::endstep(state, frametime);\n barrier(state).endstep(state, frametime);\n}\n\nvoid Hammer::wantfireprimary(Gamestate &state)\n{\n if (state.engine.isserver and not firinganim.active() and not firestrikeanim.active())\n {\n fireprimary(state);\n state.engine.sendbuffer.write(PRIMARY_FIRED);\n state.engine.sendbuffer.write(state.findplayerid(owner));\n }\n}\n\nvoid Hammer::fireprimary(Gamestate &state)\n{\n firinganim.reset();\n firinganim.active(true);\n firingdelay1.reset();\n firingdelay1.active = true;\n firingdelay2.reset();\n firingdelay2.active = true;\n}\n\nvoid Hammer::wantfiresecondary(Gamestate &state)\n{\n \/\/ Do nothing\n}\n\nvoid Hammer::firesecondary(Gamestate &state)\n{\n \/\/ Do nothing\n}\n\nvoid Hammer::createfirestrike(Gamestate &state)\n{\n Firestrike &firestrike = state.get(state.make_entity(state, owner));\n firestrike.x = x + std::cos(aimdirection) * 40;\n firestrike.y = y + std::sin(aimdirection) * 40;\n firestrike.hspeed = firestrike.SPEED * std::cos(aimdirection);\n firestrike.vspeed = firestrike.SPEED * std::sin(aimdirection);\n\n if (state.currentmap->collideline(x, y, firestrike.x, firestrike.y))\n {\n firestrike.destroy(state);\n }\n}\n\nvoid Hammer::hitarea(Gamestate &state)\n{\n Reinhardt &reinhardt = state.get(state.get(owner).character);\n for (auto &e : state.entitylist)\n {\n auto &entity = *(e.second);\n if (not entity.destroyentity)\n {\n if (entity.damageableby(team))\n {\n int direction = (reinhardt.isflipped ? -1 : 1);\n for (int i=0; i<30; ++i)\n {\n for (int j=0; j<60; ++j)\n {\n if (entity.collides(state, x + direction*(30 + i), y - 30 + j))\n {\n \/\/ We hit something, check if it's protected\n double tmpx, tmpy;\n if (state.collidelinetarget(state, x, y, state.get(entity.id), team,\n PENETRATE_CHARACTER, &tmpx, &tmpy).id == entity.id)\n {\n entity.damage(state, DAMAGE);\n }\n return;\n }\n }\n }\n }\n }\n }\n}\n\ndouble Hammer::getattachpoint_x(Gamestate &state)\n{\n return 0;\n}\n\ndouble Hammer::getattachpoint_y(Gamestate &state)\n{\n return 8;\n}\n\ndouble Hammer::getbackattachpoint_x(Gamestate &state)\n{\n if (barrier(state).active)\n {\n return 6 * (state.get(owner).getcharacter(state).isflipped ? 1:-1);\n }\n else\n {\n return 0;\n }\n}\n\ndouble Hammer::getbackattachpoint_y(Gamestate &state)\n{\n if (barrier(state).active)\n {\n return 10;\n }\n else\n {\n return 8;\n }\n}\n\nReinhardtShield& Hammer::barrier(Gamestate &state)\n{\n return state.get(barrierptr);\n}\n\nvoid Hammer::destroy(Gamestate &state)\n{\n barrier(state).destroy(state);\n Weapon::destroy(state);\n}\n\nvoid Hammer::interpolate(Entity &prev_entity, Entity &next_entity, double alpha)\n{\n Weapon::interpolate(prev_entity, next_entity, alpha);\n\n Hammer &prev_e = static_cast(prev_entity);\n Hammer &next_e = static_cast(next_entity);\n\n firestrikeanim.interpolate(prev_e.firestrikeanim, next_e.firestrikeanim, alpha);\n firestrikedelay.interpolate(prev_e.firestrikedelay, next_e.firestrikedelay, alpha);\n firinganim.interpolate(prev_e.firinganim, next_e.firinganim, alpha);\n firingdelay1.interpolate(prev_e.firingdelay1, next_e.firingdelay1, alpha);\n firingdelay2.interpolate(prev_e.firingdelay2, next_e.firingdelay2, alpha);\n}<|endoftext|>"} {"text":"\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2019 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"keybindingmanager_lua.inl\"\n\nnamespace openspace::interaction {\n\nKeybindingManager::KeybindingManager()\n : DocumentationGenerator(\n \"Documentation\",\n \"keybindings\",\n {\n { \"keybindingTemplate\", \"${WEB}\/keybindings\/keybinding.hbs\" },\n { \"mainTemplate\", \"${WEB}\/keybindings\/main.hbs\" }\n },\n \"${WEB}\/keybindings\/script.js\"\n )\n{}\n\nvoid KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action)\n{\n if (action == KeyAction::Press || action == KeyAction::Repeat) {\n \/\/ iterate over key bindings\n auto ret = _keyLua.equal_range({ key, modifier });\n for (auto it = ret.first; it != ret.second; ++it) {\n using RS = scripting::ScriptEngine::RemoteScripting;\n\n global::scriptEngine.queueScript(\n it->second.command,\n it->second.synchronization ? RS::Yes : RS::No\n );\n }\n }\n}\n\nvoid KeybindingManager::resetKeyBindings() {\n _keyLua.clear();\n}\n\nvoid KeybindingManager::bindKeyLocal(Key key,\n KeyModifier modifier,\n std::string luaCommand,\n std::string documentation,\n std::string name,\n std::string guiPath)\n{\n _keyLua.insert({\n { key, modifier },\n {\n std::move(luaCommand),\n IsSynchronized::No,\n std::move(documentation),\n std::move(name),\n std::move(guiPath)\n }\n });\n}\n\nvoid KeybindingManager::bindKey(Key key,\n KeyModifier modifier,\n std::string luaCommand,\n std::string documentation,\n std::string name,\n std::string guiPath)\n{\n _keyLua.insert({\n { key, modifier },\n {\n std::move(luaCommand),\n IsSynchronized::Yes,\n std::move(documentation),\n std::move(name),\n std::move(guiPath)\n }\n });\n}\n\nvoid KeybindingManager::removeKeyBinding(const std::string& key) {\n \/\/ Erase-remove idiom does not work for std::multimap so we have to do this on foot\n\n KeyWithModifier k = stringToKey(key);\n\n for (auto it = _keyLua.begin(); it != _keyLua.end(); ) {\n \/\/ If the current iterator is the key that we are looking for, delete it\n \/\/ (std::multimap::erase will return the iterator to the next element for us)\n if (it->first == k) {\n it = _keyLua.erase(it);\n }\n else {\n \/\/ We if it is not, we continue iteration\n ++it;\n }\n }\n}\n\nstd::vector>\nKeybindingManager::keyBinding(const std::string& key) const\n{\n std::vector> result;\n\n KeyWithModifier k = stringToKey(key);\n auto itRange = _keyLua.equal_range(k);\n for (auto it = itRange.first; it != itRange.second; ++it) {\n result.emplace_back(it->first, it->second);\n }\n return result;\n}\n\nconst std::multimap&\nKeybindingManager::keyBindings() const\n{\n return _keyLua;\n}\n\nstd::string KeybindingManager::generateJson() const {\n std::stringstream json;\n json << \"[\";\n bool first = true;\n for (const std::pair& p : _keyLua) {\n if (!first) {\n json << \",\";\n }\n first = false;\n json << \"{\";\n json << R\"(\"key\": \")\" << ghoul::to_string(p.first) << \"\\\",\";\n json << R\"(\"script\": \")\" << escapedJson(p.second.command) << \"\\\",\";\n json << R\"(\"remoteScripting: \")\"\n << (p.second.synchronization ? \"true,\" : \"false,\");\n json << R\"(\"documentation\": \")\" << escapedJson(p.second.documentation) << \"\\\",\";\n json << R\"(\"name: \")\" << escapedJson(p.second.name) << \"\\\"\";\n json << \"}\";\n }\n json << \"]\";\n\n return json.str();\n}\n\nscripting::LuaLibrary KeybindingManager::luaLibrary() {\n return {\n \"\",\n {\n {\n \"clearKeys\",\n &luascriptfunctions::clearKeys,\n {},\n \"\",\n \"Clear all key bindings\"\n },\n {\n \"clearKey\",\n &luascriptfunctions::clearKey,\n {},\n \"string or strings\",\n \"Unbinds the key or keys that have been provided. This function can be \"\n \"called with a single key or with an array of keys to remove all of the \"\n \"provided keys at once\"\n },\n {\n \"bindKey\",\n &luascriptfunctions::bindKey,\n {},\n \"string, string [,string]\",\n \"Binds a key by name to a lua string command to execute both locally \"\n \"and to broadcast to clients if this is the host of a parallel session. \"\n \"The first argument is the key, the second argument is the Lua command \"\n \"that is to be executed, and the optional third argument is a human \"\n \"readable description of the command for documentation purposes.\"\n },\n {\n \"bindKeyLocal\",\n &luascriptfunctions::bindKeyLocal,\n {},\n \"string, string [,string]\",\n \"Binds a key by name to a lua string command to execute only locally. \"\n \"The first argument is the key, the second argument is the Lua command \"\n \"that is to be executed, and the optional third argument is a human \"\n \"readable description of the command for documentation purposes.\"\n },\n {\n \"getKeyBinding\",\n &luascriptfunctions::getKeyBindings,\n {},\n \"string\",\n \"Returns a list of information about the keybindings for the provided \"\n \"key. Each element in the list is a table describing the 'Command' that \"\n \"was bound and whether it was a 'Remote' script or not.\"\n\n }\n }\n };\n}\n\n} \/\/ namespace openspace::interaction\nFix keybinding documentation (closes #813)\/*****************************************************************************************\n * *\n * OpenSpace *\n * *\n * Copyright (c) 2014-2019 *\n * *\n * Permission is hereby granted, free of charge, to any person obtaining a copy of this *\n * software and associated documentation files (the \"Software\"), to deal in the Software *\n * without restriction, including without limitation the rights to use, copy, modify, *\n * merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to *\n * permit persons to whom the Software is furnished to do so, subject to the following *\n * conditions: *\n * *\n * The above copyright notice and this permission notice shall be included in all copies *\n * or substantial portions of the Software. *\n * *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, *\n * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A *\n * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT *\n * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF *\n * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE *\n * OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *\n ****************************************************************************************\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#include \"keybindingmanager_lua.inl\"\n\nnamespace openspace::interaction {\n\nKeybindingManager::KeybindingManager()\n : DocumentationGenerator(\n \"Documentation\",\n \"keybindings\",\n {\n { \"keybindingTemplate\", \"${WEB}\/keybindings\/keybinding.hbs\" },\n { \"mainTemplate\", \"${WEB}\/keybindings\/main.hbs\" }\n },\n \"${WEB}\/keybindings\/script.js\"\n )\n{}\n\nvoid KeybindingManager::keyboardCallback(Key key, KeyModifier modifier, KeyAction action)\n{\n if (action == KeyAction::Press || action == KeyAction::Repeat) {\n \/\/ iterate over key bindings\n auto ret = _keyLua.equal_range({ key, modifier });\n for (auto it = ret.first; it != ret.second; ++it) {\n using RS = scripting::ScriptEngine::RemoteScripting;\n\n global::scriptEngine.queueScript(\n it->second.command,\n it->second.synchronization ? RS::Yes : RS::No\n );\n }\n }\n}\n\nvoid KeybindingManager::resetKeyBindings() {\n _keyLua.clear();\n}\n\nvoid KeybindingManager::bindKeyLocal(Key key,\n KeyModifier modifier,\n std::string luaCommand,\n std::string documentation,\n std::string name,\n std::string guiPath)\n{\n _keyLua.insert({\n { key, modifier },\n {\n std::move(luaCommand),\n IsSynchronized::No,\n std::move(documentation),\n std::move(name),\n std::move(guiPath)\n }\n });\n}\n\nvoid KeybindingManager::bindKey(Key key,\n KeyModifier modifier,\n std::string luaCommand,\n std::string documentation,\n std::string name,\n std::string guiPath)\n{\n _keyLua.insert({\n { key, modifier },\n {\n std::move(luaCommand),\n IsSynchronized::Yes,\n std::move(documentation),\n std::move(name),\n std::move(guiPath)\n }\n });\n}\n\nvoid KeybindingManager::removeKeyBinding(const std::string& key) {\n \/\/ Erase-remove idiom does not work for std::multimap so we have to do this on foot\n\n KeyWithModifier k = stringToKey(key);\n\n for (auto it = _keyLua.begin(); it != _keyLua.end(); ) {\n \/\/ If the current iterator is the key that we are looking for, delete it\n \/\/ (std::multimap::erase will return the iterator to the next element for us)\n if (it->first == k) {\n it = _keyLua.erase(it);\n }\n else {\n \/\/ We if it is not, we continue iteration\n ++it;\n }\n }\n}\n\nstd::vector>\nKeybindingManager::keyBinding(const std::string& key) const\n{\n std::vector> result;\n\n KeyWithModifier k = stringToKey(key);\n auto itRange = _keyLua.equal_range(k);\n for (auto it = itRange.first; it != itRange.second; ++it) {\n result.emplace_back(it->first, it->second);\n }\n return result;\n}\n\nconst std::multimap&\nKeybindingManager::keyBindings() const\n{\n return _keyLua;\n}\n\nstd::string KeybindingManager::generateJson() const {\n std::stringstream json;\n json << \"[\";\n bool first = true;\n for (const std::pair& p : _keyLua) {\n if (!first) {\n json << \",\";\n }\n first = false;\n json << \"{\";\n json << R\"(\"key\": \")\" << ghoul::to_string(p.first) << \"\\\",\";\n json << R\"(\"script\": \")\" << escapedJson(p.second.command) << \"\\\",\";\n json << R\"(\"remoteScripting\": )\"\n << (p.second.synchronization ? \"true,\" : \"false,\");\n json << R\"(\"documentation\": \")\" << escapedJson(p.second.documentation) << \"\\\",\";\n json << R\"(\"name\": \")\" << escapedJson(p.second.name) << \"\\\"\";\n json << \"}\";\n }\n json << \"]\";\n\n return json.str();\n}\n\nscripting::LuaLibrary KeybindingManager::luaLibrary() {\n return {\n \"\",\n {\n {\n \"clearKeys\",\n &luascriptfunctions::clearKeys,\n {},\n \"\",\n \"Clear all key bindings\"\n },\n {\n \"clearKey\",\n &luascriptfunctions::clearKey,\n {},\n \"string or strings\",\n \"Unbinds the key or keys that have been provided. This function can be \"\n \"called with a single key or with an array of keys to remove all of the \"\n \"provided keys at once\"\n },\n {\n \"bindKey\",\n &luascriptfunctions::bindKey,\n {},\n \"string, string [,string]\",\n \"Binds a key by name to a lua string command to execute both locally \"\n \"and to broadcast to clients if this is the host of a parallel session. \"\n \"The first argument is the key, the second argument is the Lua command \"\n \"that is to be executed, and the optional third argument is a human \"\n \"readable description of the command for documentation purposes.\"\n },\n {\n \"bindKeyLocal\",\n &luascriptfunctions::bindKeyLocal,\n {},\n \"string, string [,string]\",\n \"Binds a key by name to a lua string command to execute only locally. \"\n \"The first argument is the key, the second argument is the Lua command \"\n \"that is to be executed, and the optional third argument is a human \"\n \"readable description of the command for documentation purposes.\"\n },\n {\n \"getKeyBinding\",\n &luascriptfunctions::getKeyBindings,\n {},\n \"string\",\n \"Returns a list of information about the keybindings for the provided \"\n \"key. Each element in the list is a table describing the 'Command' that \"\n \"was bound and whether it was a 'Remote' script or not.\"\n\n }\n }\n };\n}\n\n} \/\/ namespace openspace::interaction\n<|endoftext|>"} {"text":"#include \"Database.h\"\n#include \"Exception.h\"\n#include \"is_identifier.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst std::map &joedb::Database::get_fields\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id\n) const\n{\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n throw Exception(\"get_fields: invalid table_id\");\n return table_it->second.field_names;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst joedb::Type &joedb::Database::get_field_type\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Field_Id field_id\n) const\n{\n static Type null_type;\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n return null_type;\n auto &fields = table_it->second.get_fields();\n auto field_it = fields.find(field_id);\n if (field_it == fields.end())\n return null_type;\n return field_it->second.get_type();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nRecord_Id joedb::Database::get_last_record_id(Table_Id table_id) const\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n return 0;\n return table_it->second.freedom.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool joedb::Database::is_used\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Record_Id record_id\n) const\n{\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n return false;\n return table_it->second.freedom.is_used(record_id + 1);\n}\n\n#define TYPE_MACRO(type, return_type, type_id, R, W)\\\nreturn_type joedb::Database::get_##type_id(Table_Id table_id,\\\n Record_Id record_id,\\\n Field_Id field_id) const\\\n{\\\n auto table_it = tables.find(table_id);\\\n if (table_it == tables.end())\\\n throw Exception(\"get: invalid table_id\");\\\n return table_it->second.get_##type_id(record_id, field_id);\\\n}\n#include \"TYPE_MACRO.h\"\n#undef TYPE_MACRO\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::create_table(const std::string &name)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n if (!is_identifier(name))\n throw Exception(\"create_table: invalid identifier\");\n if (find_table(name))\n throw Exception(\"create_table: name already used\");\n\n ++current_table_id;\n tables.insert(std::make_pair(current_table_id, Table()));\n table_names[current_table_id] = name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::drop_table(Table_Id table_id)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"drop_table: invalid table_id\");\n table_names.erase(table_id);\n tables.erase(it);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::rename_table\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n const std::string &name\n)\n{\n if (!is_identifier(name))\n throw Exception(\"rename_table: invalid identifier\");\n\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n throw Exception(\"rename_table: invalid table_id\");\n\n if (find_table(name) != 0)\n throw Exception(\"rename_table: name already used\");\n\n table_names[table_id] = name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::add_field\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n const std::string &name,\n Type type\n)\n{\n if (!is_identifier(name))\n throw Exception(\"add_field: invalid identifier\");\n\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"add_field: invalid table_id\");\n\n it->second.add_field(name, type);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::drop_field(Table_Id table_id, Field_Id field_id)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"drop_field: invalid table_id\");\n\n it->second.drop_field(field_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::rename_field\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Field_Id field_id,\n const std::string &name\n)\n{\n if (!is_identifier(name))\n throw Exception(\"rename_field: invalid identifier\");\n\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n throw Exception(\"rename_field: invalid table_id\");\n\n auto &field_names = table_it->second.field_names;\n auto field_it = field_names.find(field_id);\n if (field_it == field_names.end())\n throw Exception(\"rename_field: invalid field_id\");\n\n if (table_it->second.find_field(name))\n throw Exception(\"rename_field: name already used\");\n\n field_it->second = name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::insert_into(Table_Id table_id, Record_Id record_id)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"insert_into: invalid table_id\");\n\n if (record_id <= 0 || (max_record_id && record_id > max_record_id))\n throw Exception(\"insert_into: too big\");\n\n it->second.insert_record(record_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::insert_vector\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Record_Id record_id,\n Record_Id size\n)\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"insert_vector: invalid table_id\");\n if (record_id <= 0 ||\n size <= 0 ||\n (max_record_id && (record_id > max_record_id || size > max_record_id)))\n throw Exception(\"insert_vector: too big\");\n\n for (Record_Id i = 0; i < size; i++)\n it->second.insert_record(record_id + i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::delete_from\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Record_Id record_id\n)\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"delete_from: invalid table_id\");\n\n it->second.delete_record(record_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define TYPE_MACRO(type, return_type, type_id, R, W)\\\nvoid joedb::Database::update_##type_id(Table_Id table_id,\\\n Record_Id record_id,\\\n Field_Id field_id,\\\n return_type value)\\\n{\\\n auto it = tables.find(table_id);\\\n if (it == tables.end())\\\n throw Exception(\"update: invalid table_id\");\\\n it->second.update_##type_id(record_id, field_id, value);\\\n}\\\nvoid joedb::Database::update_vector_##type_id(Table_Id table_id,\\\n Record_Id record_id,\\\n Field_Id field_id,\\\n Record_Id size,\\\n const type *value)\\\n{\\\n auto it = tables.find(table_id);\\\n if (it == tables.end())\\\n throw Exception(\"update_vector: invalid table_id\");\\\n it->second.update_vector_##type_id(record_id, field_id, size, value);\\\n}\n#include \"TYPE_MACRO.h\"\n#undef TYPE_MACRO\nInserting vectors of size zero does nothing, but is allowed.#include \"Database.h\"\n#include \"Exception.h\"\n#include \"is_identifier.h\"\n\n#include \n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst std::map &joedb::Database::get_fields\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id\n) const\n{\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n throw Exception(\"get_fields: invalid table_id\");\n return table_it->second.field_names;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nconst joedb::Type &joedb::Database::get_field_type\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Field_Id field_id\n) const\n{\n static Type null_type;\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n return null_type;\n auto &fields = table_it->second.get_fields();\n auto field_it = fields.find(field_id);\n if (field_it == fields.end())\n return null_type;\n return field_it->second.get_type();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nRecord_Id joedb::Database::get_last_record_id(Table_Id table_id) const\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n return 0;\n return table_it->second.freedom.size();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nbool joedb::Database::is_used\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Record_Id record_id\n) const\n{\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n return false;\n return table_it->second.freedom.is_used(record_id + 1);\n}\n\n#define TYPE_MACRO(type, return_type, type_id, R, W)\\\nreturn_type joedb::Database::get_##type_id(Table_Id table_id,\\\n Record_Id record_id,\\\n Field_Id field_id) const\\\n{\\\n auto table_it = tables.find(table_id);\\\n if (table_it == tables.end())\\\n throw Exception(\"get: invalid table_id\");\\\n return table_it->second.get_##type_id(record_id, field_id);\\\n}\n#include \"TYPE_MACRO.h\"\n#undef TYPE_MACRO\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::create_table(const std::string &name)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n if (!is_identifier(name))\n throw Exception(\"create_table: invalid identifier\");\n if (find_table(name))\n throw Exception(\"create_table: name already used\");\n\n ++current_table_id;\n tables.insert(std::make_pair(current_table_id, Table()));\n table_names[current_table_id] = name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::drop_table(Table_Id table_id)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"drop_table: invalid table_id\");\n table_names.erase(table_id);\n tables.erase(it);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::rename_table\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n const std::string &name\n)\n{\n if (!is_identifier(name))\n throw Exception(\"rename_table: invalid identifier\");\n\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n throw Exception(\"rename_table: invalid table_id\");\n\n if (find_table(name) != 0)\n throw Exception(\"rename_table: name already used\");\n\n table_names[table_id] = name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::add_field\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n const std::string &name,\n Type type\n)\n{\n if (!is_identifier(name))\n throw Exception(\"add_field: invalid identifier\");\n\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"add_field: invalid table_id\");\n\n it->second.add_field(name, type);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::drop_field(Table_Id table_id, Field_Id field_id)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"drop_field: invalid table_id\");\n\n it->second.drop_field(field_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::rename_field\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Field_Id field_id,\n const std::string &name\n)\n{\n if (!is_identifier(name))\n throw Exception(\"rename_field: invalid identifier\");\n\n auto table_it = tables.find(table_id);\n if (table_it == tables.end())\n throw Exception(\"rename_field: invalid table_id\");\n\n auto &field_names = table_it->second.field_names;\n auto field_it = field_names.find(field_id);\n if (field_it == field_names.end())\n throw Exception(\"rename_field: invalid field_id\");\n\n if (table_it->second.find_field(name))\n throw Exception(\"rename_field: name already used\");\n\n field_it->second = name;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::insert_into(Table_Id table_id, Record_Id record_id)\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"insert_into: invalid table_id\");\n\n if (record_id <= 0 || (max_record_id && record_id > max_record_id))\n throw Exception(\"insert_into: too big\");\n\n it->second.insert_record(record_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::insert_vector\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Record_Id record_id,\n Record_Id size\n)\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"insert_vector: invalid table_id\");\n if (record_id <= 0 ||\n (max_record_id && (record_id > max_record_id || size > max_record_id)))\n {\n std::ostringstream error_message;\n error_message << \"insert_vector: \";\n error_message << \"record_id = \" << record_id << \"; \";\n error_message << \"size = \" << size << \"; \";\n error_message << \"max = \" << max_record_id;\n throw Exception(error_message.str());\n }\n\n for (Record_Id i = 0; i < size; i++)\n it->second.insert_record(record_id + i);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nvoid joedb::Database::delete_from\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n(\n Table_Id table_id,\n Record_Id record_id\n)\n{\n auto it = tables.find(table_id);\n if (it == tables.end())\n throw Exception(\"delete_from: invalid table_id\");\n\n it->second.delete_record(record_id);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n#define TYPE_MACRO(type, return_type, type_id, R, W)\\\nvoid joedb::Database::update_##type_id(Table_Id table_id,\\\n Record_Id record_id,\\\n Field_Id field_id,\\\n return_type value)\\\n{\\\n auto it = tables.find(table_id);\\\n if (it == tables.end())\\\n throw Exception(\"update: invalid table_id\");\\\n it->second.update_##type_id(record_id, field_id, value);\\\n}\\\nvoid joedb::Database::update_vector_##type_id(Table_Id table_id,\\\n Record_Id record_id,\\\n Field_Id field_id,\\\n Record_Id size,\\\n const type *value)\\\n{\\\n auto it = tables.find(table_id);\\\n if (it == tables.end())\\\n throw Exception(\"update_vector: invalid table_id\");\\\n it->second.update_vector_##type_id(record_id, field_id, size, value);\\\n}\n#include \"TYPE_MACRO.h\"\n#undef TYPE_MACRO\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2007 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"SDLPlatformFactory.h\"\n#include \"SDLMedia.h\"\n#include \"SDLDisplay.h\"\n#include \"SDLJoystick.h\"\n#include \"EvdevJoystick.h\"\n\nPlatformFactory* PlatformFactory::getInstance()\n{\n if (!instance)\n instance = new SdlPlatformFactory;\n return instance;\n}\n\nSdlPlatformFactory::SdlPlatformFactory()\n{\n \/\/ do nothing\n}\n\nSdlPlatformFactory::~SdlPlatformFactory()\n{\n \/\/ do nothing\n}\n\nBzfDisplay* SdlPlatformFactory::createDisplay(const char*, const char*)\n{\n SDLDisplay* display = new SDLDisplay();\n if (!display || !display->isValid()) {\n delete display;\n return NULL;\n }\n return display;\n}\n\nBzfVisual* SdlPlatformFactory::createVisual(const BzfDisplay* display)\n{\n return new SDLVisual((const SDLDisplay*)display);\n}\n\nBzfWindow* SdlPlatformFactory::createWindow(const BzfDisplay* display,\n\t\t\t\t\t BzfVisual* visual)\n{\n return new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);\n}\n\nBzfMedia* SdlPlatformFactory::createMedia()\n{\n return new SDLMedia;\n}\n\nBzfJoystick* SdlPlatformFactory::createJoystick()\n{\n \/* Use EvdevJoystick instead of SDLJoystick if we can.\n * It has minor improvements in axis mapping and joystick\n * enumeration, but the big selling point so far is that it\n * supports force feedback.\n *\/\n#ifdef HAVE_LINUX_INPUT_H\n if (EvdevJoystick::isEvdevAvailable())\n return new EvdevJoystick;\n#endif\n\n return new SDLJoystick;\n}\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\ninclude necessary headers\/* bzflag\n * Copyright (c) 1993 - 2007 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"SDLPlatformFactory.h\"\n#include \"SDLMedia.h\"\n#include \"SDLDisplay.h\"\n#include \"SDLJoystick.h\"\n#include \"SDLVisual.h\"\n#include \"SDLWindow.h\"\n#include \"EvdevJoystick.h\"\n\nPlatformFactory* PlatformFactory::getInstance()\n{\n if (!instance)\n instance = new SdlPlatformFactory;\n return instance;\n}\n\nSdlPlatformFactory::SdlPlatformFactory()\n{\n \/\/ do nothing\n}\n\nSdlPlatformFactory::~SdlPlatformFactory()\n{\n \/\/ do nothing\n}\n\nBzfDisplay* SdlPlatformFactory::createDisplay(const char*, const char*)\n{\n SDLDisplay* display = new SDLDisplay();\n if (!display || !display->isValid()) {\n delete display;\n return NULL;\n }\n return display;\n}\n\nBzfVisual* SdlPlatformFactory::createVisual(const BzfDisplay* display)\n{\n return new SDLVisual((const SDLDisplay*)display);\n}\n\nBzfWindow* SdlPlatformFactory::createWindow(const BzfDisplay* display,\n\t\t\t\t\t BzfVisual* visual)\n{\n return new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);\n}\n\nBzfMedia* SdlPlatformFactory::createMedia()\n{\n return new SDLMedia;\n}\n\nBzfJoystick* SdlPlatformFactory::createJoystick()\n{\n \/* Use EvdevJoystick instead of SDLJoystick if we can.\n * It has minor improvements in axis mapping and joystick\n * enumeration, but the big selling point so far is that it\n * supports force feedback.\n *\/\n#ifdef HAVE_LINUX_INPUT_H\n if (EvdevJoystick::isEvdevAvailable())\n return new EvdevJoystick;\n#endif\n\n return new SDLJoystick;\n}\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n<|endoftext|>"} {"text":"\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"WinPlatformFactory.h\"\n#ifdef HAVE_SDL\n#include \"SDLMedia.h\"\n#include \"SDLDisplay.h\"\n#include \"SDLJoystick.h\"\n#endif\n#include \"DXJoystick.h\"\n#ifdef HAVE_DSOUND_H\n#include \"WinMedia.h\"\n#endif\n#include \"WinDisplay.h\"\n#include \"WinVisual.h\"\n#include \"WinWindow.h\"\n#include \"WinJoystick.h\"\n#include \"StateDatabase.h\"\n\nPlatformFactory*\tPlatformFactory::getInstance()\n{\n if (!instance) instance = new WinPlatformFactory;\n return instance;\n}\n\n#ifdef HAVE_SDL\nSDLWindow*\t\tWinPlatformFactory::sdlWindow = NULL;\n#endif\nWinWindow*\t\tWinPlatformFactory::winWindow = NULL;\n\nWinPlatformFactory::WinPlatformFactory()\n{\n \/\/ do nothing\n}\n\nWinPlatformFactory::~WinPlatformFactory()\n{\n \/\/ do nothing\n}\n\nBzfDisplay *WinPlatformFactory::createDisplay(const char* name,\n\t\t\t\t\t const char* videoFormat)\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLVideo\") && BZDB.isTrue(\"SDLVideo\"))\n useNative = false;\n#endif\n\n \/\/ Just to stop compiler complaining about un-use of name & videoFormat\n if (name == NULL && videoFormat == NULL)\n ;\n\n BzfDisplay *display;\n if (useNative) {\n WinDisplay* winDisplay = new WinDisplay(name, videoFormat);\n display = winDisplay;\n } else {\n#ifdef HAVE_SDL\n SDLDisplay* sdlDisplay = new SDLDisplay();\n display = sdlDisplay;\n#else\n display = NULL;\n#endif\n }\n if (!display || !display->isValid()) {\n delete display;\n display = NULL;\n }\n return display;\n}\n\nBzfVisual*\t\tWinPlatformFactory::createVisual(\n\t\t\t\tconst BzfDisplay* display)\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLVideo\") && BZDB.isTrue(\"SDLVideo\"))\n useNative = false;\n#endif\n\n if (useNative)\n return new WinVisual((const WinDisplay*)display);\n else\n#ifdef HAVE_SDL\n return new SDLVisual((const SDLDisplay*)display);\n#else\n return NULL;\n#endif\n}\n\nBzfWindow*\t\tWinPlatformFactory::createWindow(\n\t\t\t\tconst BzfDisplay* display, BzfVisual* visual)\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLVideo\") && BZDB.isTrue(\"SDLVideo\"))\n useNative = false;\n#endif\n\n if (useNative) {\n winWindow = new WinWindow((const WinDisplay*)display, (WinVisual*)visual);\n return winWindow;\n } else {\n#ifdef HAVE_SDL\n sdlWindow = new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);\n return sdlWindow;\n#else\n return NULL;\n#endif\n }\n}\n\nBzfMedia*\t\tWinPlatformFactory::createMedia()\n{\n bool useNative = true;\n#ifndef HAVE_DSOUND_H\n useNative = false;\n#endif\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLAudio\") && BZDB.isTrue(\"SDLAudio\"))\n useNative = false;\n#endif\n\n if (useNative) {\n#ifdef HAVE_DSOUND_H\n return new WinMedia(window);\n#else\n return NULL;\n#endif\n } else {\n#ifdef HAVE_SDL\n return new SDLMedia();\n#else\n return NULL;\n#endif\n }\n}\n\nBzfJoystick*\t\tWinPlatformFactory::createJoystick()\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLJoystick\") && BZDB.isTrue(\"SDLJoystick\"))\n useNative = false;\n#endif\n if (useNative) {\n#if defined(USE_DINPUT)\n return new DXJoystick();\n#else\n return new WinJoystick();\n#endif\n } else {\n#if defined(HAVE_SDL)\n return new SDLJoystick();\n#else\n return NULL;\n#endif\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\nwarning\/* bzflag\n * Copyright (c) 1993 - 2005 Tim Riker\n *\n * This package is free software; you can redistribute it and\/or\n * modify it under the terms of the license found in the file\n * named COPYING that should have accompanied this file.\n *\n * THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR\n * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED\n * WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.\n *\/\n\n#include \"WinPlatformFactory.h\"\n#ifdef HAVE_SDL\n#include \"SDLMedia.h\"\n#include \"SDLDisplay.h\"\n#include \"SDLJoystick.h\"\n#endif\n#include \"DXJoystick.h\"\n#ifdef HAVE_DSOUND_H\n#include \"WinMedia.h\"\n#endif\n#include \"WinDisplay.h\"\n#include \"WinVisual.h\"\n#include \"WinWindow.h\"\n#include \"WinJoystick.h\"\n#include \"StateDatabase.h\"\n\nPlatformFactory*\tPlatformFactory::getInstance()\n{\n if (!instance) instance = new WinPlatformFactory;\n return instance;\n}\n\n#ifdef HAVE_SDL\nSDLWindow*\t\tWinPlatformFactory::sdlWindow = NULL;\n#endif\nWinWindow*\t\tWinPlatformFactory::winWindow = NULL;\n\nWinPlatformFactory::WinPlatformFactory()\n{\n \/\/ do nothing\n}\n\nWinPlatformFactory::~WinPlatformFactory()\n{\n \/\/ do nothing\n}\n\nBzfDisplay *WinPlatformFactory::createDisplay(const char* name,\n\t\t\t\t\t const char* videoFormat)\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLVideo\") && BZDB.isTrue(\"SDLVideo\"))\n useNative = false;\n#endif\n\n \/\/ Just to stop compiler complaining about un-use of name & videoFormat\n if (name == NULL && videoFormat == NULL) {};\n\n BzfDisplay *display;\n if (useNative) {\n WinDisplay* winDisplay = new WinDisplay(name, videoFormat);\n display = winDisplay;\n } else {\n#ifdef HAVE_SDL\n SDLDisplay* sdlDisplay = new SDLDisplay();\n display = sdlDisplay;\n#else\n display = NULL;\n#endif\n }\n if (!display || !display->isValid()) {\n delete display;\n display = NULL;\n }\n return display;\n}\n\nBzfVisual*\t\tWinPlatformFactory::createVisual(\n\t\t\t\tconst BzfDisplay* display)\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLVideo\") && BZDB.isTrue(\"SDLVideo\"))\n useNative = false;\n#endif\n\n if (useNative)\n return new WinVisual((const WinDisplay*)display);\n else\n#ifdef HAVE_SDL\n return new SDLVisual((const SDLDisplay*)display);\n#else\n return NULL;\n#endif\n}\n\nBzfWindow*\t\tWinPlatformFactory::createWindow(\n\t\t\t\tconst BzfDisplay* display, BzfVisual* visual)\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLVideo\") && BZDB.isTrue(\"SDLVideo\"))\n useNative = false;\n#endif\n\n if (useNative) {\n winWindow = new WinWindow((const WinDisplay*)display, (WinVisual*)visual);\n return winWindow;\n } else {\n#ifdef HAVE_SDL\n sdlWindow = new SDLWindow((const SDLDisplay*)display, (SDLVisual*)visual);\n return sdlWindow;\n#else\n return NULL;\n#endif\n }\n}\n\nBzfMedia*\t\tWinPlatformFactory::createMedia()\n{\n bool useNative = true;\n#ifndef HAVE_DSOUND_H\n useNative = false;\n#endif\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLAudio\") && BZDB.isTrue(\"SDLAudio\"))\n useNative = false;\n#endif\n\n if (useNative) {\n#ifdef HAVE_DSOUND_H\n return new WinMedia(window);\n#else\n return NULL;\n#endif\n } else {\n#ifdef HAVE_SDL\n return new SDLMedia();\n#else\n return NULL;\n#endif\n }\n}\n\nBzfJoystick*\t\tWinPlatformFactory::createJoystick()\n{\n bool useNative = true;\n#ifdef HAVE_SDL\n if (BZDB.isSet(\"SDLJoystick\") && BZDB.isTrue(\"SDLJoystick\"))\n useNative = false;\n#endif\n if (useNative) {\n#if defined(USE_DINPUT)\n return new DXJoystick();\n#else\n return new WinJoystick();\n#endif\n } else {\n#if defined(HAVE_SDL)\n return new SDLJoystick();\n#else\n return NULL;\n#endif\n }\n}\n\n\/\/ Local Variables: ***\n\/\/ mode:C++ ***\n\/\/ tab-width: 8 ***\n\/\/ c-basic-offset: 2 ***\n\/\/ indent-tabs-mode: t ***\n\/\/ End: ***\n\/\/ ex: shiftwidth=2 tabstop=8\n\n<|endoftext|>"} {"text":"\/* libs\/graphics\/ports\/SkFontHost_fontconfig.cpp\n**\n** Copyright 2008, Google Inc.\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n** you may not use this file except in compliance with the License.\n** You may obtain a copy of the License at\n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n**\n** Unless required by applicable law or agreed to in writing, software\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n** See the License for the specific language governing permissions and\n** limitations under the License.\n*\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ This file provides implementations of the font resolution members of\n\/\/ SkFontHost by using the fontconfig[1] library. Fontconfig is usually found\n\/\/ on Linux systems and handles configuration, parsing and caching issues\n\/\/ involved with enumerating and matching fonts.\n\/\/\n\/\/ [1] http:\/\/fontconfig.org\n\/\/ -----------------------------------------------------------------------------\n\n#include \n#include \n\n#include \n\n#include \"SkFontHost.h\"\n#include \"SkStream.h\"\n\n\/\/ This is an extern from SkFontHost_FreeType\nSkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ The rest of Skia requires that fonts be identified by a unique unsigned id\n\/\/ and that we be able to load them given the id. What we actually get from\n\/\/ fontconfig is the filename of the font so we keep a locked map from\n\/\/ filenames to fileid numbers and back.\n\/\/\n\/\/ Note that there's also a unique id in the SkTypeface. This is unique over\n\/\/ both filename and style. Thus we encode that id as (fileid << 8) | style.\n\/\/ Although truetype fonts can support multiple faces in a single file, at the\n\/\/ moment Skia doesn't.\n\/\/ -----------------------------------------------------------------------------\nstatic SkMutex global_fc_map_lock;\nstatic std::map global_fc_map;\nstatic std::map global_fc_map_inverted;\nstatic std::map global_fc_typefaces;\nstatic unsigned global_fc_map_next_id = 0;\n\n\/\/ This is the maximum size of the font cache.\nstatic const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; \/\/ 2MB\n\nstatic unsigned UniqueIdToFileId(unsigned uniqueid)\n{\n return uniqueid >> 8;\n}\n\nstatic SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)\n{\n return static_cast(uniqueid & 0xff);\n}\n\nstatic unsigned FileIdAndStyleToUniqueId(unsigned fileid,\n SkTypeface::Style style)\n{\n SkASSERT((style & 0xff) == style);\n return (fileid << 8) | static_cast(style);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Normally we only return exactly the font asked for. In last-resort cases,\n\/\/ the request is for one of the basic font names \"Sans\", \"Serif\" or\n\/\/ \"Monospace\". This function tells you whether a given request is for such a\n\/\/ fallback.\n\/\/ -----------------------------------------------------------------------------\nstatic bool IsFallbackFontAllowed(const char* request)\n{\n return strcmp(request, \"Sans\") == 0 ||\n strcmp(request, \"Serif\") == 0 ||\n strcmp(request, \"Monospace\") == 0;\n}\n\nclass FontConfigTypeface : public SkTypeface {\npublic:\n FontConfigTypeface(Style style, uint32_t id)\n : SkTypeface(style, id)\n { }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Find a matching font where @type (one of FC_*) is equal to @value. For a\n\/\/ list of types, see http:\/\/fontconfig.org\/fontconfig-devel\/x19.html#AEN27.\n\/\/ The variable arguments are a list of triples, just like the first three\n\/\/ arguments, and must be NULL terminated.\n\/\/\n\/\/ For example,\n\/\/ FontMatchString(FC_FILE, FcTypeString, \"\/usr\/share\/fonts\/myfont.ttf\",\n\/\/ NULL);\n\/\/ -----------------------------------------------------------------------------\nstatic FcPattern* FontMatch(const char* type, FcType vtype, const void* value,\n ...)\n{\n va_list ap;\n va_start(ap, value);\n\n FcPattern* pattern = FcPatternCreate();\n const char* family_requested = NULL;\n\n for (;;) {\n FcValue fcvalue;\n fcvalue.type = vtype;\n switch (vtype) {\n case FcTypeString:\n fcvalue.u.s = (FcChar8*) value;\n break;\n case FcTypeInteger:\n fcvalue.u.i = (int)(intptr_t)value;\n break;\n default:\n SkASSERT(!\"FontMatch unhandled type\");\n }\n FcPatternAdd(pattern, type, fcvalue, 0);\n\n if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)\n family_requested = (const char*) value;\n\n type = va_arg(ap, const char *);\n if (!type)\n break;\n \/\/ FcType is promoted to int when passed through ...\n vtype = static_cast(va_arg(ap, int));\n value = va_arg(ap, const void *);\n };\n va_end(ap);\n\n FcConfigSubstitute(0, pattern, FcMatchPattern);\n FcDefaultSubstitute(pattern);\n\n \/\/ Font matching:\n \/\/ CSS often specifies a fallback list of families:\n \/\/ font-family: a, b, c, serif;\n \/\/ However, fontconfig will always do its best to find *a* font when asked\n \/\/ for something so we need a way to tell if the match which it has found is\n \/\/ \"good enough\" for us. Otherwise, we can return NULL which gets piped up\n \/\/ and lets WebKit know to try the next CSS family name. However, fontconfig\n \/\/ configs allow substitutions (mapping \"Arial -> Helvetica\" etc) and we\n \/\/ wish to support that.\n \/\/\n \/\/ Thus, if a specific family is requested we set @family_requested. Then we\n \/\/ record two strings: the family name after config processing and the\n \/\/ family name after resolving. If the two are equal, it's a good match.\n \/\/\n \/\/ So consider the case where a user has mapped Arial to Helvetica in their\n \/\/ config.\n \/\/ requested family: \"Arial\"\n \/\/ post_config_family: \"Helvetica\"\n \/\/ post_match_family: \"Helvetica\"\n \/\/ -> good match\n \/\/\n \/\/ and for a missing font:\n \/\/ requested family: \"Monaco\"\n \/\/ post_config_family: \"Monaco\"\n \/\/ post_match_family: \"Times New Roman\"\n \/\/ -> BAD match\n \/\/\n \/\/ However, we special-case fallback fonts; see IsFallbackFontAllowed().\n FcChar8* post_config_family;\n FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);\n\n FcResult result;\n FcPattern* match = FcFontMatch(0, pattern, &result);\n if (!match) {\n FcPatternDestroy(pattern);\n return NULL;\n }\n\n FcChar8* post_match_family;\n FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);\n const bool family_names_match =\n !family_requested ?\n true :\n strcasecmp((char *)post_config_family, (char *)post_match_family) == 0;\n\n FcPatternDestroy(pattern);\n\n if (!family_names_match && !IsFallbackFontAllowed(family_requested)) {\n FcPatternDestroy(match);\n return NULL;\n }\n\n return match;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Check to see if the filename has already been assigned a fileid and, if so,\n\/\/ use it. Otherwise, assign one. Return the resulting fileid.\n\/\/ -----------------------------------------------------------------------------\nstatic unsigned FileIdFromFilename(const char* filename)\n{\n SkAutoMutexAcquire ac(global_fc_map_lock);\n\n std::map::const_iterator i =\n global_fc_map.find(filename);\n if (i == global_fc_map.end()) {\n const unsigned fileid = global_fc_map_next_id++;\n global_fc_map[filename] = fileid;\n global_fc_map_inverted[fileid] = filename;\n return fileid;\n } else {\n return i->second;\n }\n}\n\n\/\/ static\nSkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,\n const char familyName[],\n const void* data, size_t bytelength,\n SkTypeface::Style style)\n{\n const char* resolved_family_name = NULL;\n FcPattern* face_match = NULL;\n\n {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n FcInit();\n }\n\n if (familyFace) {\n \/\/ Here we use the inverted global id map to find the filename from the\n \/\/ SkTypeface object. Given the filename we can ask fontconfig for the\n \/\/ familyname of the font.\n SkAutoMutexAcquire ac(global_fc_map_lock);\n\n const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());\n std::map::const_iterator i =\n global_fc_map_inverted.find(fileid);\n if (i == global_fc_map_inverted.end())\n return NULL;\n\n FcInit();\n face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(),\n NULL);\n\n if (!face_match)\n return NULL;\n FcChar8* family;\n if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {\n FcPatternDestroy(face_match);\n return NULL;\n }\n \/\/ At this point, @family is pointing into the @face_match object so we\n \/\/ cannot release it yet.\n\n resolved_family_name = reinterpret_cast(family);\n } else if (familyName) {\n resolved_family_name = familyName;\n } else {\n return NULL;\n }\n\n \/\/ At this point, we have a resolved_family_name from somewhere\n SkASSERT(resolved_family_name);\n\n const int bold = style & SkTypeface::kBold ?\n FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;\n const int italic = style & SkTypeface::kItalic ?\n FC_SLANT_ITALIC : FC_SLANT_ROMAN;\n FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name,\n FC_WEIGHT, FcTypeInteger, bold,\n FC_SLANT, FcTypeInteger, italic,\n NULL);\n if (face_match)\n FcPatternDestroy(face_match);\n\n if (!match)\n return NULL;\n\n FcChar8* filename;\n if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {\n FcPatternDestroy(match);\n return NULL;\n }\n \/\/ Now @filename is pointing into @match\n\n const unsigned fileid = FileIdFromFilename(reinterpret_cast(filename));\n const unsigned id = FileIdAndStyleToUniqueId(fileid, style);\n SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));\n FcPatternDestroy(match);\n\n {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n global_fc_typefaces[id] = typeface;\n }\n\n return typeface;\n}\n\n\/\/ static\nSkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)\n{\n SkASSERT(!\"SkFontHost::CreateTypefaceFromStream unimplemented\");\n return NULL;\n}\n\n\/\/ static\nSkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])\n{\n SkASSERT(!\"SkFontHost::CreateTypefaceFromFile unimplemented\");\n return NULL;\n}\n\n\/\/ static\nbool SkFontHost::ValidFontID(SkFontID uniqueID) {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end();\n}\n\n\/\/ static\nSkStream* SkFontHost::OpenStream(uint32_t id)\n{\n SkAutoMutexAcquire ac(global_fc_map_lock);\n const unsigned fileid = UniqueIdToFileId(id);\n\n std::map::const_iterator i =\n global_fc_map_inverted.find(fileid);\n if (i == global_fc_map_inverted.end())\n return NULL;\n\n return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));\n}\n\nsize_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,\n int32_t* index) {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n const unsigned fileid = UniqueIdToFileId(id);\n \n std::map::const_iterator i =\n global_fc_map_inverted.find(fileid);\n if (i == global_fc_map_inverted.end()) {\n return 0;\n }\n\n const std::string& str = i->second;\n if (path) {\n memcpy(path, str.c_str(), SkMin32(str.size(), length));\n }\n if (index) { \/\/ TODO: check if we're in a TTC\n *index = 0;\n }\n return str.size();\n}\n\nvoid SkFontHost::Serialize(const SkTypeface*, SkWStream*) {\n SkASSERT(!\"SkFontHost::Serialize unimplemented\");\n}\n\nSkTypeface* SkFontHost::Deserialize(SkStream* stream) {\n SkASSERT(!\"SkFontHost::Deserialize unimplemented\");\n return NULL;\n}\n\n\/\/ static\nuint32_t SkFontHost::NextLogicalFont(SkFontID fontID) {\n \/\/ We don't handle font fallback, WebKit does.\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)\n{\n if (sizeAllocatedSoFar > kFontCacheMemoryBudget)\n return sizeAllocatedSoFar - kFontCacheMemoryBudget;\n else\n return 0; \/\/ nothing to do\n}\nfix compile-error, mismatch between fontID and id\/* libs\/graphics\/ports\/SkFontHost_fontconfig.cpp\n**\n** Copyright 2008, Google Inc.\n**\n** Licensed under the Apache License, Version 2.0 (the \"License\");\n** you may not use this file except in compliance with the License.\n** You may obtain a copy of the License at\n**\n** http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n**\n** Unless required by applicable law or agreed to in writing, software\n** distributed under the License is distributed on an \"AS IS\" BASIS,\n** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n** See the License for the specific language governing permissions and\n** limitations under the License.\n*\/\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ This file provides implementations of the font resolution members of\n\/\/ SkFontHost by using the fontconfig[1] library. Fontconfig is usually found\n\/\/ on Linux systems and handles configuration, parsing and caching issues\n\/\/ involved with enumerating and matching fonts.\n\/\/\n\/\/ [1] http:\/\/fontconfig.org\n\/\/ -----------------------------------------------------------------------------\n\n#include \n#include \n\n#include \n\n#include \"SkFontHost.h\"\n#include \"SkStream.h\"\n\n\/\/ This is an extern from SkFontHost_FreeType\nSkTypeface::Style find_name_and_style(SkStream* stream, SkString* name);\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ The rest of Skia requires that fonts be identified by a unique unsigned id\n\/\/ and that we be able to load them given the id. What we actually get from\n\/\/ fontconfig is the filename of the font so we keep a locked map from\n\/\/ filenames to fileid numbers and back.\n\/\/\n\/\/ Note that there's also a unique id in the SkTypeface. This is unique over\n\/\/ both filename and style. Thus we encode that id as (fileid << 8) | style.\n\/\/ Although truetype fonts can support multiple faces in a single file, at the\n\/\/ moment Skia doesn't.\n\/\/ -----------------------------------------------------------------------------\nstatic SkMutex global_fc_map_lock;\nstatic std::map global_fc_map;\nstatic std::map global_fc_map_inverted;\nstatic std::map global_fc_typefaces;\nstatic unsigned global_fc_map_next_id = 0;\n\n\/\/ This is the maximum size of the font cache.\nstatic const unsigned kFontCacheMemoryBudget = 2 * 1024 * 1024; \/\/ 2MB\n\nstatic unsigned UniqueIdToFileId(unsigned uniqueid)\n{\n return uniqueid >> 8;\n}\n\nstatic SkTypeface::Style UniqueIdToStyle(unsigned uniqueid)\n{\n return static_cast(uniqueid & 0xff);\n}\n\nstatic unsigned FileIdAndStyleToUniqueId(unsigned fileid,\n SkTypeface::Style style)\n{\n SkASSERT((style & 0xff) == style);\n return (fileid << 8) | static_cast(style);\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Normally we only return exactly the font asked for. In last-resort cases,\n\/\/ the request is for one of the basic font names \"Sans\", \"Serif\" or\n\/\/ \"Monospace\". This function tells you whether a given request is for such a\n\/\/ fallback.\n\/\/ -----------------------------------------------------------------------------\nstatic bool IsFallbackFontAllowed(const char* request)\n{\n return strcmp(request, \"Sans\") == 0 ||\n strcmp(request, \"Serif\") == 0 ||\n strcmp(request, \"Monospace\") == 0;\n}\n\nclass FontConfigTypeface : public SkTypeface {\npublic:\n FontConfigTypeface(Style style, uint32_t id)\n : SkTypeface(style, id)\n { }\n};\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Find a matching font where @type (one of FC_*) is equal to @value. For a\n\/\/ list of types, see http:\/\/fontconfig.org\/fontconfig-devel\/x19.html#AEN27.\n\/\/ The variable arguments are a list of triples, just like the first three\n\/\/ arguments, and must be NULL terminated.\n\/\/\n\/\/ For example,\n\/\/ FontMatchString(FC_FILE, FcTypeString, \"\/usr\/share\/fonts\/myfont.ttf\",\n\/\/ NULL);\n\/\/ -----------------------------------------------------------------------------\nstatic FcPattern* FontMatch(const char* type, FcType vtype, const void* value,\n ...)\n{\n va_list ap;\n va_start(ap, value);\n\n FcPattern* pattern = FcPatternCreate();\n const char* family_requested = NULL;\n\n for (;;) {\n FcValue fcvalue;\n fcvalue.type = vtype;\n switch (vtype) {\n case FcTypeString:\n fcvalue.u.s = (FcChar8*) value;\n break;\n case FcTypeInteger:\n fcvalue.u.i = (int)(intptr_t)value;\n break;\n default:\n SkASSERT(!\"FontMatch unhandled type\");\n }\n FcPatternAdd(pattern, type, fcvalue, 0);\n\n if (vtype == FcTypeString && strcmp(type, FC_FAMILY) == 0)\n family_requested = (const char*) value;\n\n type = va_arg(ap, const char *);\n if (!type)\n break;\n \/\/ FcType is promoted to int when passed through ...\n vtype = static_cast(va_arg(ap, int));\n value = va_arg(ap, const void *);\n };\n va_end(ap);\n\n FcConfigSubstitute(0, pattern, FcMatchPattern);\n FcDefaultSubstitute(pattern);\n\n \/\/ Font matching:\n \/\/ CSS often specifies a fallback list of families:\n \/\/ font-family: a, b, c, serif;\n \/\/ However, fontconfig will always do its best to find *a* font when asked\n \/\/ for something so we need a way to tell if the match which it has found is\n \/\/ \"good enough\" for us. Otherwise, we can return NULL which gets piped up\n \/\/ and lets WebKit know to try the next CSS family name. However, fontconfig\n \/\/ configs allow substitutions (mapping \"Arial -> Helvetica\" etc) and we\n \/\/ wish to support that.\n \/\/\n \/\/ Thus, if a specific family is requested we set @family_requested. Then we\n \/\/ record two strings: the family name after config processing and the\n \/\/ family name after resolving. If the two are equal, it's a good match.\n \/\/\n \/\/ So consider the case where a user has mapped Arial to Helvetica in their\n \/\/ config.\n \/\/ requested family: \"Arial\"\n \/\/ post_config_family: \"Helvetica\"\n \/\/ post_match_family: \"Helvetica\"\n \/\/ -> good match\n \/\/\n \/\/ and for a missing font:\n \/\/ requested family: \"Monaco\"\n \/\/ post_config_family: \"Monaco\"\n \/\/ post_match_family: \"Times New Roman\"\n \/\/ -> BAD match\n \/\/\n \/\/ However, we special-case fallback fonts; see IsFallbackFontAllowed().\n FcChar8* post_config_family;\n FcPatternGetString(pattern, FC_FAMILY, 0, &post_config_family);\n\n FcResult result;\n FcPattern* match = FcFontMatch(0, pattern, &result);\n if (!match) {\n FcPatternDestroy(pattern);\n return NULL;\n }\n\n FcChar8* post_match_family;\n FcPatternGetString(match, FC_FAMILY, 0, &post_match_family);\n const bool family_names_match =\n !family_requested ?\n true :\n strcasecmp((char *)post_config_family, (char *)post_match_family) == 0;\n\n FcPatternDestroy(pattern);\n\n if (!family_names_match && !IsFallbackFontAllowed(family_requested)) {\n FcPatternDestroy(match);\n return NULL;\n }\n\n return match;\n}\n\n\/\/ -----------------------------------------------------------------------------\n\/\/ Check to see if the filename has already been assigned a fileid and, if so,\n\/\/ use it. Otherwise, assign one. Return the resulting fileid.\n\/\/ -----------------------------------------------------------------------------\nstatic unsigned FileIdFromFilename(const char* filename)\n{\n SkAutoMutexAcquire ac(global_fc_map_lock);\n\n std::map::const_iterator i =\n global_fc_map.find(filename);\n if (i == global_fc_map.end()) {\n const unsigned fileid = global_fc_map_next_id++;\n global_fc_map[filename] = fileid;\n global_fc_map_inverted[fileid] = filename;\n return fileid;\n } else {\n return i->second;\n }\n}\n\n\/\/ static\nSkTypeface* SkFontHost::CreateTypeface(const SkTypeface* familyFace,\n const char familyName[],\n const void* data, size_t bytelength,\n SkTypeface::Style style)\n{\n const char* resolved_family_name = NULL;\n FcPattern* face_match = NULL;\n\n {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n FcInit();\n }\n\n if (familyFace) {\n \/\/ Here we use the inverted global id map to find the filename from the\n \/\/ SkTypeface object. Given the filename we can ask fontconfig for the\n \/\/ familyname of the font.\n SkAutoMutexAcquire ac(global_fc_map_lock);\n\n const unsigned fileid = UniqueIdToFileId(familyFace->uniqueID());\n std::map::const_iterator i =\n global_fc_map_inverted.find(fileid);\n if (i == global_fc_map_inverted.end())\n return NULL;\n\n FcInit();\n face_match = FontMatch(FC_FILE, FcTypeString, i->second.c_str(),\n NULL);\n\n if (!face_match)\n return NULL;\n FcChar8* family;\n if (FcPatternGetString(face_match, FC_FAMILY, 0, &family)) {\n FcPatternDestroy(face_match);\n return NULL;\n }\n \/\/ At this point, @family is pointing into the @face_match object so we\n \/\/ cannot release it yet.\n\n resolved_family_name = reinterpret_cast(family);\n } else if (familyName) {\n resolved_family_name = familyName;\n } else {\n return NULL;\n }\n\n \/\/ At this point, we have a resolved_family_name from somewhere\n SkASSERT(resolved_family_name);\n\n const int bold = style & SkTypeface::kBold ?\n FC_WEIGHT_BOLD : FC_WEIGHT_NORMAL;\n const int italic = style & SkTypeface::kItalic ?\n FC_SLANT_ITALIC : FC_SLANT_ROMAN;\n FcPattern* match = FontMatch(FC_FAMILY, FcTypeString, resolved_family_name,\n FC_WEIGHT, FcTypeInteger, bold,\n FC_SLANT, FcTypeInteger, italic,\n NULL);\n if (face_match)\n FcPatternDestroy(face_match);\n\n if (!match)\n return NULL;\n\n FcChar8* filename;\n if (FcPatternGetString(match, FC_FILE, 0, &filename) != FcResultMatch) {\n FcPatternDestroy(match);\n return NULL;\n }\n \/\/ Now @filename is pointing into @match\n\n const unsigned fileid = FileIdFromFilename(reinterpret_cast(filename));\n const unsigned id = FileIdAndStyleToUniqueId(fileid, style);\n SkTypeface* typeface = SkNEW_ARGS(FontConfigTypeface, (style, id));\n FcPatternDestroy(match);\n\n {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n global_fc_typefaces[id] = typeface;\n }\n\n return typeface;\n}\n\n\/\/ static\nSkTypeface* SkFontHost::CreateTypefaceFromStream(SkStream* stream)\n{\n SkASSERT(!\"SkFontHost::CreateTypefaceFromStream unimplemented\");\n return NULL;\n}\n\n\/\/ static\nSkTypeface* SkFontHost::CreateTypefaceFromFile(const char path[])\n{\n SkASSERT(!\"SkFontHost::CreateTypefaceFromFile unimplemented\");\n return NULL;\n}\n\n\/\/ static\nbool SkFontHost::ValidFontID(SkFontID uniqueID) {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n return global_fc_typefaces.find(uniqueID) != global_fc_typefaces.end();\n}\n\n\/\/ static\nSkStream* SkFontHost::OpenStream(uint32_t id)\n{\n SkAutoMutexAcquire ac(global_fc_map_lock);\n const unsigned fileid = UniqueIdToFileId(id);\n\n std::map::const_iterator i =\n global_fc_map_inverted.find(fileid);\n if (i == global_fc_map_inverted.end())\n return NULL;\n\n return SkNEW_ARGS(SkFILEStream, (i->second.c_str()));\n}\n\nsize_t SkFontHost::GetFileName(SkFontID fontID, char path[], size_t length,\n int32_t* index) {\n SkAutoMutexAcquire ac(global_fc_map_lock);\n const unsigned fileid = UniqueIdToFileId(fontID);\n\n std::map::const_iterator i =\n global_fc_map_inverted.find(fileid);\n if (i == global_fc_map_inverted.end()) {\n return 0;\n }\n\n const std::string& str = i->second;\n if (path) {\n memcpy(path, str.c_str(), SkMin32(str.size(), length));\n }\n if (index) { \/\/ TODO: check if we're in a TTC\n *index = 0;\n }\n return str.size();\n}\n\nvoid SkFontHost::Serialize(const SkTypeface*, SkWStream*) {\n SkASSERT(!\"SkFontHost::Serialize unimplemented\");\n}\n\nSkTypeface* SkFontHost::Deserialize(SkStream* stream) {\n SkASSERT(!\"SkFontHost::Deserialize unimplemented\");\n return NULL;\n}\n\n\/\/ static\nuint32_t SkFontHost::NextLogicalFont(SkFontID fontID) {\n \/\/ We don't handle font fallback, WebKit does.\n return 0;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nsize_t SkFontHost::ShouldPurgeFontCache(size_t sizeAllocatedSoFar)\n{\n if (sizeAllocatedSoFar > kFontCacheMemoryBudget)\n return sizeAllocatedSoFar - kFontCacheMemoryBudget;\n else\n return 0; \/\/ nothing to do\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/* Total required space (in GB) depending on user choice (prune, not prune) *\/\nstatic uint64_t requiredSpace;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n explicit FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic Q_SLOTS:\n void check();\n\nQ_SIGNALS:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \n\nFreespaceChecker::FreespaceChecker(Intro *_intro)\n{\n this->intro = _intro;\n}\n\nvoid FreespaceChecker::check()\n{\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch (const fs::filesystem_error&)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(nullptr),\n signalled(false),\n m_blockchain_size(blockchain_size),\n m_chain_state_size(chain_state_size)\n{\n ui->setupUi(this);\n ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));\n ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));\n\n ui->lblExplanation1->setText(ui->lblExplanation1->text()\n .arg(tr(PACKAGE_NAME))\n .arg(m_blockchain_size)\n .arg(2017)\n .arg(tr(\"Qtum\"))\n );\n ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));\n\n uint64_t pruneTarget = std::max(0, gArgs.GetArg(\"-prune\", 0));\n requiredSpace = m_blockchain_size;\n QString storageRequiresMsg = tr(\"At least %1 GB of data will be stored in this directory, and it will grow over time.\");\n if (pruneTarget) {\n uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 \/ GB_BYTES);\n if (prunedGBs <= requiredSpace) {\n requiredSpace = prunedGBs;\n storageRequiresMsg = tr(\"Approximately %1 GB of data will be stored in this directory.\");\n }\n ui->lblExplanation3->setVisible(true);\n } else {\n ui->lblExplanation3->setVisible(false);\n }\n requiredSpace += m_chain_state_size;\n ui->sizeWarningLabel->setText(\n tr(\"%1 will download and store a copy of the Qtum block chain.\").arg(tr(PACKAGE_NAME)) + \" \" +\n storageRequiresMsg.arg(requiredSpace) + \" \" +\n tr(\"The wallet will also be stored in this directory.\")\n );\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n thread->quit();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nQString Intro::getDefaultDataDirectory()\n{\n return GUIUtil::boostPathToQString(GetDefaultDataDir());\n}\n\nbool Intro::pickDataDirectory(interfaces::Node& node)\n{\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!gArgs.GetArg(\"-datadir\", \"\").empty())\n return true;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg(\"-choosedatadir\", DEFAULT_CHOOSE_DATADIR) || settings.value(\"fReset\", false).toBool() || gArgs.GetBoolArg(\"-resetguisettings\", false))\n {\n \/* Use selectParams here to guarantee Params() can be used by node interface *\/\n try {\n node.selectParams(gArgs.GetChainName());\n } catch (const std::exception&) {\n return false;\n }\n\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize());\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/bitcoin\"));\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n return false;\n }\n dataDir = intro.getDataDirectory();\n try {\n if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {\n \/\/ If a new data directory has been created, make wallets subdirectory too\n TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) \/ \"wallets\");\n }\n break;\n } catch (const fs::filesystem_error&) {\n QMessageBox::critical(nullptr, tr(PACKAGE_NAME),\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n settings.setValue(\"strDataDir\", dataDir);\n settings.setValue(\"fReset\", false);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the bitcoin.conf file in the default data directory\n * (to be consistent with bitcoind behavior)\n *\/\n if(dataDir != getDefaultDataDirectory()) {\n node.softSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n }\n return true;\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < requiredSpace * GB_BYTES)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n setDataDirectory(QDir::homePath());\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);\n connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);\n \/* make sure executor object is deleted in its own thread *\/\n connect(thread, &QThread::finished, executor, &QObject::deleteLater);\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n Q_EMIT requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\nSet custom datadir to home for OSX only\/\/ Copyright (c) 2011-2018 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#if defined(HAVE_CONFIG_H)\n#include \n#endif\n\n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n\n\/* Total required space (in GB) depending on user choice (prune, not prune) *\/\nstatic uint64_t requiredSpace;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n explicit FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic Q_SLOTS:\n void check();\n\nQ_SIGNALS:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \n\nFreespaceChecker::FreespaceChecker(Intro *_intro)\n{\n this->intro = _intro;\n}\n\nvoid FreespaceChecker::check()\n{\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch (const fs::filesystem_error&)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n Q_EMIT reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent, uint64_t blockchain_size, uint64_t chain_state_size) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(nullptr),\n signalled(false),\n m_blockchain_size(blockchain_size),\n m_chain_state_size(chain_state_size)\n{\n ui->setupUi(this);\n ui->welcomeLabel->setText(ui->welcomeLabel->text().arg(tr(PACKAGE_NAME)));\n ui->storageLabel->setText(ui->storageLabel->text().arg(tr(PACKAGE_NAME)));\n\n ui->lblExplanation1->setText(ui->lblExplanation1->text()\n .arg(tr(PACKAGE_NAME))\n .arg(m_blockchain_size)\n .arg(2017)\n .arg(tr(\"Qtum\"))\n );\n ui->lblExplanation2->setText(ui->lblExplanation2->text().arg(tr(PACKAGE_NAME)));\n\n uint64_t pruneTarget = std::max(0, gArgs.GetArg(\"-prune\", 0));\n requiredSpace = m_blockchain_size;\n QString storageRequiresMsg = tr(\"At least %1 GB of data will be stored in this directory, and it will grow over time.\");\n if (pruneTarget) {\n uint64_t prunedGBs = std::ceil(pruneTarget * 1024 * 1024.0 \/ GB_BYTES);\n if (prunedGBs <= requiredSpace) {\n requiredSpace = prunedGBs;\n storageRequiresMsg = tr(\"Approximately %1 GB of data will be stored in this directory.\");\n }\n ui->lblExplanation3->setVisible(true);\n } else {\n ui->lblExplanation3->setVisible(false);\n }\n requiredSpace += m_chain_state_size;\n ui->sizeWarningLabel->setText(\n tr(\"%1 will download and store a copy of the Qtum block chain.\").arg(tr(PACKAGE_NAME)) + \" \" +\n storageRequiresMsg.arg(requiredSpace) + \" \" +\n tr(\"The wallet will also be stored in this directory.\")\n );\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n thread->quit();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nQString Intro::getDefaultDataDirectory()\n{\n return GUIUtil::boostPathToQString(GetDefaultDataDir());\n}\n\nbool Intro::pickDataDirectory(interfaces::Node& node)\n{\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!gArgs.GetArg(\"-datadir\", \"\").empty())\n return true;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || gArgs.GetBoolArg(\"-choosedatadir\", DEFAULT_CHOOSE_DATADIR) || settings.value(\"fReset\", false).toBool() || gArgs.GetBoolArg(\"-resetguisettings\", false))\n {\n \/* Use selectParams here to guarantee Params() can be used by node interface *\/\n try {\n node.selectParams(gArgs.GetChainName());\n } catch (const std::exception&) {\n return false;\n }\n\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro(0, node.getAssumedBlockchainSize(), node.getAssumedChainStateSize());\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/bitcoin\"));\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n return false;\n }\n dataDir = intro.getDataDirectory();\n try {\n if (TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir))) {\n \/\/ If a new data directory has been created, make wallets subdirectory too\n TryCreateDirectories(GUIUtil::qstringToBoostPath(dataDir) \/ \"wallets\");\n }\n break;\n } catch (const fs::filesystem_error&) {\n QMessageBox::critical(nullptr, tr(PACKAGE_NAME),\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n settings.setValue(\"strDataDir\", dataDir);\n settings.setValue(\"fReset\", false);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the bitcoin.conf file in the default data directory\n * (to be consistent with bitcoind behavior)\n *\/\n if(dataDir != getDefaultDataDirectory()) {\n node.softSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n }\n return true;\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < requiredSpace * GB_BYTES)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", requiredSpace);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(nullptr, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n\t#ifdef MAC_OSX\n\tsetDataDirectory(QDir::homePath()+\"\/Qtum\");\n\t#endif\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, &FreespaceChecker::reply, this, &Intro::setStatus);\n connect(this, &Intro::requestCheck, executor, &FreespaceChecker::check);\n \/* make sure executor object is deleted in its own thread *\/\n connect(thread, &QThread::finished, executor, &QObject::deleteLater);\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n Q_EMIT requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"intro.h\"\n#include \"ui_intro.h\"\n\n#include \"guiutil.h\"\n\n#include \"util.h\"\n\n#include \n\n#include \n#include \n#include \n\n\/* Minimum free space (in bytes) needed for data directory *\/\nstatic const uint64_t GB_BYTES = 1000000000LL;\nstatic const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic slots:\n void check();\n\nsignals:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \"intro.moc\"\n\nFreespaceChecker::FreespaceChecker(Intro *intro)\n{\n this->intro = intro;\n}\n\nvoid FreespaceChecker::check()\n{\n namespace fs = boost::filesystem;\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch(fs::filesystem_error &e)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n emit reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(0),\n signalled(false)\n{\n ui->setupUi(this);\n ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE\/GB_BYTES));\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n emit stopThread();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nQString Intro::getDefaultDataDirectory()\n{\n return GUIUtil::boostPathToQString(GetDefaultDataDir());\n}\n\nvoid Intro::pickDataDirectory()\n{\n namespace fs = boost::filesystem;\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!GetArg(\"-datadir\", \"\").empty())\n return;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg(\"-choosedatadir\", false))\n {\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro;\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/bitcoin\"));\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n exit(0);\n }\n dataDir = intro.getDataDirectory();\n try {\n TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));\n break;\n } catch(fs::filesystem_error &e) {\n QMessageBox::critical(0, tr(\"Fastcoin Core\"),\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n settings.setValue(\"strDataDir\", dataDir);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the bitcoin.conf file in the default data directory\n * (to be consistent with bitcoind behavior)\n *\/\n if(dataDir != getDefaultDataDirectory())\n SoftSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < BLOCK_CHAIN_SIZE)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", BLOCK_CHAIN_SIZE\/GB_BYTES);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));\n connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));\n \/* make sure executor object is deleted in its own thread *\/\n connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));\n connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n emit requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\n\nUpdate intro.cpp\/\/ Copyright (c) 2011-2014 The Bitcoin developers\n\/\/ Distributed under the MIT\/X11 software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"intro.h\"\n#include \"ui_intro.h\"\n\n#include \"guiutil.h\"\n\n#include \"util.h\"\n\n#include \n\n#include \n#include \n#include \n\n\/* Minimum free space (in bytes) needed for data directory *\/\nstatic const uint64_t GB_BYTES = 1000000000LL;\nstatic const uint64_t BLOCK_CHAIN_SIZE = 20LL * GB_BYTES;\n\n\/* Check free space asynchronously to prevent hanging the UI thread.\n\n Up to one request to check a path is in flight to this thread; when the check()\n function runs, the current path is requested from the associated Intro object.\n The reply is sent back through a signal.\n\n This ensures that no queue of checking requests is built up while the user is\n still entering the path, and that always the most recently entered path is checked as\n soon as the thread becomes available.\n*\/\nclass FreespaceChecker : public QObject\n{\n Q_OBJECT\n\npublic:\n FreespaceChecker(Intro *intro);\n\n enum Status {\n ST_OK,\n ST_ERROR\n };\n\npublic slots:\n void check();\n\nsignals:\n void reply(int status, const QString &message, quint64 available);\n\nprivate:\n Intro *intro;\n};\n\n#include \"intro.moc\"\n\nFreespaceChecker::FreespaceChecker(Intro *intro)\n{\n this->intro = intro;\n}\n\nvoid FreespaceChecker::check()\n{\n namespace fs = boost::filesystem;\n QString dataDirStr = intro->getPathToCheck();\n fs::path dataDir = GUIUtil::qstringToBoostPath(dataDirStr);\n uint64_t freeBytesAvailable = 0;\n int replyStatus = ST_OK;\n QString replyMessage = tr(\"A new data directory will be created.\");\n\n \/* Find first parent that exists, so that fs::space does not fail *\/\n fs::path parentDir = dataDir;\n fs::path parentDirOld = fs::path();\n while(parentDir.has_parent_path() && !fs::exists(parentDir))\n {\n parentDir = parentDir.parent_path();\n\n \/* Check if we make any progress, break if not to prevent an infinite loop here *\/\n if (parentDirOld == parentDir)\n break;\n\n parentDirOld = parentDir;\n }\n\n try {\n freeBytesAvailable = fs::space(parentDir).available;\n if(fs::exists(dataDir))\n {\n if(fs::is_directory(dataDir))\n {\n QString separator = \"\" + QDir::toNativeSeparators(\"\/\") + tr(\"name\") + \"<\/code>\";\n replyStatus = ST_OK;\n replyMessage = tr(\"Directory already exists. Add %1 if you intend to create a new directory here.\").arg(separator);\n } else {\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Path already exists, and is not a directory.\");\n }\n }\n } catch(fs::filesystem_error &e)\n {\n \/* Parent directory does not exist or is not accessible *\/\n replyStatus = ST_ERROR;\n replyMessage = tr(\"Cannot create data directory here.\");\n }\n emit reply(replyStatus, replyMessage, freeBytesAvailable);\n}\n\n\nIntro::Intro(QWidget *parent) :\n QDialog(parent),\n ui(new Ui::Intro),\n thread(0),\n signalled(false)\n{\n ui->setupUi(this);\n ui->sizeWarningLabel->setText(ui->sizeWarningLabel->text().arg(BLOCK_CHAIN_SIZE\/GB_BYTES));\n startThread();\n}\n\nIntro::~Intro()\n{\n delete ui;\n \/* Ensure thread is finished before it is deleted *\/\n emit stopThread();\n thread->wait();\n}\n\nQString Intro::getDataDirectory()\n{\n return ui->dataDirectory->text();\n}\n\nvoid Intro::setDataDirectory(const QString &dataDir)\n{\n ui->dataDirectory->setText(dataDir);\n if(dataDir == getDefaultDataDirectory())\n {\n ui->dataDirDefault->setChecked(true);\n ui->dataDirectory->setEnabled(false);\n ui->ellipsisButton->setEnabled(false);\n } else {\n ui->dataDirCustom->setChecked(true);\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n }\n}\n\nQString Intro::getDefaultDataDirectory()\n{\n return GUIUtil::boostPathToQString(GetDefaultDataDir());\n}\n\nvoid Intro::pickDataDirectory()\n{\n namespace fs = boost::filesystem;\n QSettings settings;\n \/* If data directory provided on command line, no need to look at settings\n or show a picking dialog *\/\n if(!GetArg(\"-datadir\", \"\").empty())\n return;\n \/* 1) Default data directory for operating system *\/\n QString dataDir = getDefaultDataDirectory();\n \/* 2) Allow QSettings to override default dir *\/\n dataDir = settings.value(\"strDataDir\", dataDir).toString();\n\n if(!fs::exists(GUIUtil::qstringToBoostPath(dataDir)) || GetBoolArg(\"-choosedatadir\", false))\n {\n \/* If current default data directory does not exist, let the user choose one *\/\n Intro intro;\n intro.setDataDirectory(dataDir);\n intro.setWindowIcon(QIcon(\":icons\/bitcoin\"));\n\n while(true)\n {\n if(!intro.exec())\n {\n \/* Cancel clicked *\/\n exit(0);\n }\n dataDir = intro.getDataDirectory();\n try {\n TryCreateDirectory(GUIUtil::qstringToBoostPath(dataDir));\n break;\n } catch(fs::filesystem_error &e) {\n QMessageBox::critical(0, tr(\"Fastcoin Core\"),\n tr(\"Error: Specified data directory \\\"%1\\\" cannot be created.\").arg(dataDir));\n \/* fall through, back to choosing screen *\/\n }\n }\n\n settings.setValue(\"strDataDir\", dataDir);\n }\n \/* Only override -datadir if different from the default, to make it possible to\n * override -datadir in the bitcoin.conf file in the default data directory\n * (to be consistent with bitcoind behavior)\n *\/\n if(dataDir != getDefaultDataDirectory())\n SoftSetArg(\"-datadir\", GUIUtil::qstringToBoostPath(dataDir).string()); \/\/ use OS locale for path setting\n}\n\nvoid Intro::setStatus(int status, const QString &message, quint64 bytesAvailable)\n{\n switch(status)\n {\n case FreespaceChecker::ST_OK:\n ui->errorMessage->setText(message);\n ui->errorMessage->setStyleSheet(\"\");\n break;\n case FreespaceChecker::ST_ERROR:\n ui->errorMessage->setText(tr(\"Error\") + \": \" + message);\n ui->errorMessage->setStyleSheet(\"QLabel { color: #800000 }\");\n break;\n }\n \/* Indicate number of bytes available *\/\n if(status == FreespaceChecker::ST_ERROR)\n {\n ui->freeSpace->setText(\"\");\n } else {\n QString freeString = tr(\"%n GB of free space available\", \"\", bytesAvailable\/GB_BYTES);\n if(bytesAvailable < BLOCK_CHAIN_SIZE)\n {\n freeString += \" \" + tr(\"(of %n GB needed)\", \"\", BLOCK_CHAIN_SIZE\/GB_BYTES);\n ui->freeSpace->setStyleSheet(\"QLabel { color: #800000 }\");\n } else {\n ui->freeSpace->setStyleSheet(\"\");\n }\n ui->freeSpace->setText(freeString + \".\");\n }\n \/* Don't allow confirm in ERROR state *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(status != FreespaceChecker::ST_ERROR);\n}\n\nvoid Intro::on_dataDirectory_textChanged(const QString &dataDirStr)\n{\n \/* Disable OK button until check result comes in *\/\n ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);\n checkPath(dataDirStr);\n}\n\nvoid Intro::on_ellipsisButton_clicked()\n{\n QString dir = QDir::toNativeSeparators(QFileDialog::getExistingDirectory(0, \"Choose data directory\", ui->dataDirectory->text()));\n if(!dir.isEmpty())\n ui->dataDirectory->setText(dir);\n}\n\nvoid Intro::on_dataDirDefault_clicked()\n{\n setDataDirectory(getDefaultDataDirectory());\n}\n\nvoid Intro::on_dataDirCustom_clicked()\n{\n ui->dataDirectory->setEnabled(true);\n ui->ellipsisButton->setEnabled(true);\n}\n\nvoid Intro::startThread()\n{\n thread = new QThread(this);\n FreespaceChecker *executor = new FreespaceChecker(this);\n executor->moveToThread(thread);\n\n connect(executor, SIGNAL(reply(int,QString,quint64)), this, SLOT(setStatus(int,QString,quint64)));\n connect(this, SIGNAL(requestCheck()), executor, SLOT(check()));\n \/* make sure executor object is deleted in its own thread *\/\n connect(this, SIGNAL(stopThread()), executor, SLOT(deleteLater()));\n connect(this, SIGNAL(stopThread()), thread, SLOT(quit()));\n\n thread->start();\n}\n\nvoid Intro::checkPath(const QString &dataDir)\n{\n mutex.lock();\n pathToCheck = dataDir;\n if(!signalled)\n {\n signalled = true;\n emit requestCheck();\n }\n mutex.unlock();\n}\n\nQString Intro::getPathToCheck()\n{\n QString retval;\n mutex.lock();\n retval = pathToCheck;\n signalled = false; \/* new request can be queued now *\/\n mutex.unlock();\n return retval;\n}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: documentdefinition.hxx,v $\n *\n * $Revision: 1.26 $\n *\n * last change: $Author: rt $ $Date: 2008-01-30 08:34:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_\n#define _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_\n\n#ifndef _CPPUHELPER_PROPSHLP_HXX\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n#ifndef DBA_CONTENTHELPER_HXX\n#include \"ContentHelper.hxx\"\n#endif\n#ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX\n#include \n#endif\n#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_\n#include \n#endif\n#ifndef _DBASHARED_APITOOLS_HXX_\n#include \"apitools.hxx\"\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTATECHANGELISTENER_HPP_\n#include \n#endif\n\n\/\/........................................................................\nnamespace dbaccess\n{\n\/\/........................................................................\n\n class OInterceptor;\n class OEmbeddedClientHelper;\n\/\/==========================================================================\n\/\/= ODocumentDefinition - a database \"document\" which is simply a link to a real\n\/\/= document\n\/\/==========================================================================\n\n typedef ::cppu::ImplHelper1< ::com::sun::star::embed::XComponentSupplier\n > ODocumentDefinition_Base;\n\nclass ODocumentDefinition\n :public OContentHelper\n ,public ::comphelper::OPropertyStateContainer\n ,public ::comphelper::OPropertyArrayUsageHelper< ODocumentDefinition >\n ,public ODocumentDefinition_Base\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject> m_xEmbeddedObject;\n ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStateChangeListener > m_xListener;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFramesSupplier > m_xDesktop;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xLastKnownConnection;\n\n OInterceptor* m_pInterceptor;\n sal_Bool m_bForm; \/\/ if it is a form\n sal_Bool m_bOpenInDesign;\n sal_Bool m_bInExecute;\n OEmbeddedClientHelper* m_pClientHelper;\n\nprotected:\n virtual ~ODocumentDefinition();\n\npublic:\n\n ODocumentDefinition(\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&\n ,const TContentPtr& _pImpl\n ,sal_Bool _bForm\n ,const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()\n );\n\n\/\/ com::sun::star::lang::XTypeProvider\n DECLARE_TYPEPROVIDER( );\n\n\/\/ ::com::sun::star::uno::XInterface\n DECLARE_XINTERFACE( )\n\n\/\/ ::com::sun::star::lang::XServiceInfo\n DECLARE_SERVICE_INFO_STATIC();\n\n\/\/ ::com::sun::star::beans::XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponentSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseable > SAL_CALL getComponent( ) throw (::com::sun::star::uno::RuntimeException);\n\n\/\/ OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n\n \/\/ XCommandProcessor\n virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw (::com::sun::star::uno::Exception, ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException) ;\n\n \/\/ XRename\n virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getStorage() const;\n\n sal_Bool save(sal_Bool _bApprove);\n sal_Bool saveAs();\n void closeObject();\n sal_Bool isModified();\n void fillReportData();\n inline sal_Bool isNewReport() const { return !m_bForm && !m_pImpl->m_aProps.bAsTemplate; }\n\n \/** prepares closing the document component\n\n The method suspends the controller associated with the document, and saves the document\n if necessary.\n\n @return\n if and only if the document component can be closed\n *\/\n bool prepareClose();\n\n static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId();\n\n \/** does necessary initializations after our embedded object has been switched to ACTIVE\n @param _bOpenedInDesignMode\n determines whether the embedded object has been opened for designing it or for data display\n *\/\n void impl_onActivateEmbeddedObject();\n\n \/** initializes a newly created view\/controller which is displaying our embedded object\n\n Has only to be called if the respective embedded object has been loaded for design (and\n not for data entry)\n\n @param _rxController\n the controller which belongs to the XModel of our (active) embedded object\n *\/\n void impl_initObjectEditView( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >& _rxController );\n\n \/** removes the given frame from the desktop's frame collection\n @raises ::com::sun::star::uno::RuntimeException\n *\/\n void impl_removeFrameFromDesktop_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );\n\n static ::rtl::OUString GetDocumentServiceFromMediaType( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage\n ,const ::rtl::OUString& sEntName\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB\n ,::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId\n );\n\nprotected:\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\n\n virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const;\n \/\/ helper\n virtual void SAL_CALL disposing();\n\nprivate:\n \/** fills the load arguments\n *\/\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >\n fillLoadArgs(\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,\n const bool _bSuppressMacros,\n const bool _bReadOnly,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rEmbeddedObjectDescriptor\n );\n\n \/** loads the EmbeddedObject if not already loaded\n @param _aClassID\n If set, it will be used to create the embedded object.\n *\/\n void loadEmbeddedObject(\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,\n const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,\n const bool _bSuppressMacros,\n const bool _bReadOnly\n );\n\n \/** loads the embedded object, if not already loaded. No new object can be created with this method.\n *\/\n void loadEmbeddedObject()\n {\n loadEmbeddedObject(\n NULL,\n ::com::sun::star::uno::Sequence< sal_Int8 >(),\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),\n false,\n false\n );\n }\n\n \/** loads the embedded object for preview. Macros will be suppressed, and the document will\n be read-only.\n *\/\n void loadEmbeddedObjectForPreview()\n {\n loadEmbeddedObject(\n NULL,\n ::com::sun::star::uno::Sequence< sal_Int8 >(),\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),\n true,\n true\n );\n }\n\n \/** searches for read-only flag in the args of the model and sets it to the given value,\n if the value was not found, it will be appended.\n @param _bReadOnly\n If the document will be switched to readonly mode\n *\/\n void updateDocumentTitle();\n\n void registerProperties();\n\n \/\/-------------------------------------------------------------------------\n \/\/- commands\n \/\/-------------------------------------------------------------------------\n\n void onCommandGetDocumentInfo( ::com::sun::star::uno::Any& _rInfo );\n void onCommandInsert( const ::rtl::OUString& _sURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( ::com::sun::star::uno::Exception );\n void onCommandPreview( ::com::sun::star::uno::Any& _rImage );\n void onCommandOpenSomething( const ::com::sun::star::uno::Any& _rArgument, const bool _bActivate,\n const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& _rxEnvironment, ::com::sun::star::uno::Any& _out_rComponent );\n};\n\n\/\/........................................................................\n} \/\/ namespace dbaccess\n\/\/........................................................................\n\n#endif \/\/ _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_\n\nINTEGRATION: CWS custommeta (1.24.26); FILE MERGED 2008\/02\/01 10:33:44 mst 1.24.26.2: RESYNC: (1.24-1.26); FILE MERGED 2008\/01\/29 13:14:59 mst 1.24.26.1: - dbaccess\/source\/ui\/app\/AppDetailPageHelper.cxx: + adapt to ODocumentInfoPreview interface change + use XDocumentProperties instead of XDocumentInfo + incidentally, fixes bug: document information was not displayed at all - dbaccess\/source\/core\/dataaccess\/documentdefinition.{hxx,cxx}: + renamed ODocumentDefinition::onCommandGetDocumentInfo to onCommandGetDocumentProperties\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: documentdefinition.hxx,v $\n *\n * $Revision: 1.27 $\n *\n * last change: $Author: obo $ $Date: 2008-02-26 14:38:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_\n#define _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_\n\n#ifndef _CPPUHELPER_PROPSHLP_HXX\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE1_HXX_\n#include \n#endif\n#ifndef DBA_CONTENTHELPER_HXX\n#include \"ContentHelper.hxx\"\n#endif\n#ifndef COMPHELPER_PROPERTYSTATECONTAINER_HXX\n#include \n#endif\n#ifndef _COMPHELPER_PROPERTY_ARRAY_HELPER_HXX_\n#include \n#endif\n#ifndef _DBASHARED_APITOOLS_HXX_\n#include \"apitools.hxx\"\n#endif\n#ifndef _COMPHELPER_UNO3_HXX_\n#include \n#endif\n#ifndef _COM_SUN_STAR_SDBC_XCONNECTION_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XCOMPONENTLOADER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_EMBED_XSTATECHANGELISTENER_HPP_\n#include \n#endif\n\n\/\/........................................................................\nnamespace dbaccess\n{\n\/\/........................................................................\n\n class OInterceptor;\n class OEmbeddedClientHelper;\n\/\/==========================================================================\n\/\/= ODocumentDefinition - a database \"document\" which is simply a link to a real\n\/\/= document\n\/\/==========================================================================\n\n typedef ::cppu::ImplHelper1< ::com::sun::star::embed::XComponentSupplier\n > ODocumentDefinition_Base;\n\nclass ODocumentDefinition\n :public OContentHelper\n ,public ::comphelper::OPropertyStateContainer\n ,public ::comphelper::OPropertyArrayUsageHelper< ODocumentDefinition >\n ,public ODocumentDefinition_Base\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject> m_xEmbeddedObject;\n ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStateChangeListener > m_xListener;\n ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFramesSupplier > m_xDesktop;\n ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection > m_xLastKnownConnection;\n\n OInterceptor* m_pInterceptor;\n sal_Bool m_bForm; \/\/ if it is a form\n sal_Bool m_bOpenInDesign;\n sal_Bool m_bInExecute;\n OEmbeddedClientHelper* m_pClientHelper;\n\nprotected:\n virtual ~ODocumentDefinition();\n\npublic:\n\n ODocumentDefinition(\n const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxContainer\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >&\n ,const TContentPtr& _pImpl\n ,sal_Bool _bForm\n ,const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID = ::com::sun::star::uno::Sequence< sal_Int8 >()\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection = ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>()\n );\n\n\/\/ com::sun::star::lang::XTypeProvider\n DECLARE_TYPEPROVIDER( );\n\n\/\/ ::com::sun::star::uno::XInterface\n DECLARE_XINTERFACE( )\n\n\/\/ ::com::sun::star::lang::XServiceInfo\n DECLARE_SERVICE_INFO_STATIC();\n\n\/\/ ::com::sun::star::beans::XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo > SAL_CALL getPropertySetInfo( ) throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XComponentSupplier\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::util::XCloseable > SAL_CALL getComponent( ) throw (::com::sun::star::uno::RuntimeException);\n\n\/\/ OPropertySetHelper\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n\n \/\/ XCommandProcessor\n virtual ::com::sun::star::uno::Any SAL_CALL execute( const ::com::sun::star::ucb::Command& aCommand, sal_Int32 CommandId, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw (::com::sun::star::uno::Exception, ::com::sun::star::ucb::CommandAbortedException, ::com::sun::star::uno::RuntimeException) ;\n\n \/\/ XRename\n virtual void SAL_CALL rename( const ::rtl::OUString& newName ) throw (::com::sun::star::sdbc::SQLException, ::com::sun::star::container::ElementExistException, ::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage> getStorage() const;\n\n sal_Bool save(sal_Bool _bApprove);\n sal_Bool saveAs();\n void closeObject();\n sal_Bool isModified();\n void fillReportData();\n inline sal_Bool isNewReport() const { return !m_bForm && !m_pImpl->m_aProps.bAsTemplate; }\n\n \/** prepares closing the document component\n\n The method suspends the controller associated with the document, and saves the document\n if necessary.\n\n @return\n if and only if the document component can be closed\n *\/\n bool prepareClose();\n\n static ::com::sun::star::uno::Sequence< sal_Int8 > getDefaultDocumentTypeClassId();\n\n \/** does necessary initializations after our embedded object has been switched to ACTIVE\n @param _bOpenedInDesignMode\n determines whether the embedded object has been opened for designing it or for data display\n *\/\n void impl_onActivateEmbeddedObject();\n\n \/** initializes a newly created view\/controller which is displaying our embedded object\n\n Has only to be called if the respective embedded object has been loaded for design (and\n not for data entry)\n\n @param _rxController\n the controller which belongs to the XModel of our (active) embedded object\n *\/\n void impl_initObjectEditView( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XController >& _rxController );\n\n \/** removes the given frame from the desktop's frame collection\n @raises ::com::sun::star::uno::RuntimeException\n *\/\n void impl_removeFrameFromDesktop_throw( const ::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame >& _rxFrame );\n\n static ::rtl::OUString GetDocumentServiceFromMediaType( const ::com::sun::star::uno::Reference< ::com::sun::star::embed::XStorage >& xStorage\n ,const ::rtl::OUString& sEntName\n ,const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory >& _xORB\n ,::com::sun::star::uno::Sequence< sal_Int8 >& _rClassId\n );\n\nprotected:\n \/\/ OPropertyArrayUsageHelper\n virtual ::cppu::IPropertyArrayHelper* createArrayHelper( ) const;\n\n virtual void getPropertyDefaultByHandle( sal_Int32 _nHandle, ::com::sun::star::uno::Any& _rDefault ) const;\n \/\/ helper\n virtual void SAL_CALL disposing();\n\nprivate:\n \/** fills the load arguments\n *\/\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >\n fillLoadArgs(\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,\n const bool _bSuppressMacros,\n const bool _bReadOnly,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _out_rEmbeddedObjectDescriptor\n );\n\n \/** loads the EmbeddedObject if not already loaded\n @param _aClassID\n If set, it will be used to create the embedded object.\n *\/\n void loadEmbeddedObject(\n const ::com::sun::star::uno::Reference< ::com::sun::star::sdbc::XConnection>& _xConnection,\n const ::com::sun::star::uno::Sequence< sal_Int8 >& _aClassID,\n const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& _rAdditionalArgs,\n const bool _bSuppressMacros,\n const bool _bReadOnly\n );\n\n \/** loads the embedded object, if not already loaded. No new object can be created with this method.\n *\/\n void loadEmbeddedObject()\n {\n loadEmbeddedObject(\n NULL,\n ::com::sun::star::uno::Sequence< sal_Int8 >(),\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),\n false,\n false\n );\n }\n\n \/** loads the embedded object for preview. Macros will be suppressed, and the document will\n be read-only.\n *\/\n void loadEmbeddedObjectForPreview()\n {\n loadEmbeddedObject(\n NULL,\n ::com::sun::star::uno::Sequence< sal_Int8 >(),\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >(),\n true,\n true\n );\n }\n\n \/** searches for read-only flag in the args of the model and sets it to the given value,\n if the value was not found, it will be appended.\n @param _bReadOnly\n If the document will be switched to readonly mode\n *\/\n void updateDocumentTitle();\n\n void registerProperties();\n\n \/\/-------------------------------------------------------------------------\n \/\/- commands\n \/\/-------------------------------------------------------------------------\n\n void onCommandGetDocumentProperties( ::com::sun::star::uno::Any& _rProps );\n void onCommandInsert( const ::rtl::OUString& _sURL, const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& Environment ) throw( ::com::sun::star::uno::Exception );\n void onCommandPreview( ::com::sun::star::uno::Any& _rImage );\n void onCommandOpenSomething( const ::com::sun::star::uno::Any& _rArgument, const bool _bActivate,\n const ::com::sun::star::uno::Reference< ::com::sun::star::ucb::XCommandEnvironment >& _rxEnvironment, ::com::sun::star::uno::Any& _out_rComponent );\n};\n\n\/\/........................................................................\n} \/\/ namespace dbaccess\n\/\/........................................................................\n\n#endif \/\/ _DBA_COREDATAACCESS_DOCUMENTDEFINITION_HXX_\n\n<|endoftext|>"} {"text":"\/*!\n * Copyright (c) 2017 by Contributors\n * \\file opencl_module.cc\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \".\/opencl_common.h\"\n#include \".\/opencl_module.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass OpenCLWrappedFunc {\n public:\n \/\/ initialize the OpenCL function.\n void Init(OpenCLModuleNode* m,\n std::shared_ptr sptr,\n OpenCLModuleNode::KTRefEntry entry,\n std::string func_name,\n std::vector arg_size,\n const std::vector& thread_axis_tags) {\n w_ = m->GetGlobalWorkspace().get();\n m_ = m;\n sptr_ = sptr;\n entry_ = entry;\n func_name_ = func_name;\n arg_size_ = arg_size;\n thread_axis_cfg_.Init(arg_size.size(), thread_axis_tags);\n }\n \/\/ invoke the function with void arguments\n void operator()(TVMArgs args,\n TVMRetValue* rv,\n void** void_args) const {\n cl::OpenCLThreadEntry* t = w_->GetThreadEntry();\n \/\/ get the kernel from thread local kernel table.\n if (entry_.kernel_id >= t->kernel_table.size()) {\n t->kernel_table.resize(entry_.kernel_id + 1);\n }\n const auto& e = t->kernel_table[entry_.kernel_id];\n cl_kernel kernel = e.kernel;\n if (kernel == nullptr || e.version != entry_.version) {\n kernel = m_->InstallKernel(w_, t, func_name_, entry_);\n }\n \/\/ setup arguments.\n for (cl_uint i = 0; i < arg_size_.size(); ++i) {\n OPENCL_CALL(clSetKernelArg(kernel, i, arg_size_[i], void_args[i]));\n }\n cl_command_queue queue = w_->GetQueue(t->context);\n ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);\n cl_uint work_dim = static_cast(thread_axis_cfg_.work_dim());\n for (cl_uint i = 0; i < work_dim; ++i) {\n wl.work_size[i] *= wl.work_size[i + 3];\n }\n \/\/ launch kernel\n OPENCL_CALL(clEnqueueNDRangeKernel(\n queue, kernel, work_dim, nullptr,\n wl.work_size,\n wl.work_size + 3,\n 0, nullptr, nullptr));\n }\n\n private:\n \/\/ global workspace.\n cl::OpenCLWorkspace* w_;\n \/\/ The module\n OpenCLModuleNode* m_;\n \/\/ resource handle\n std::shared_ptr sptr_;\n \/\/ global kernel id in the kernel table.\n OpenCLModuleNode::KTRefEntry entry_;\n \/\/ The name of the function.\n std::string func_name_;\n \/\/ convert code for void argument\n std::vector arg_size_;\n \/\/ thread axis config\n ThreadAxisConfig thread_axis_cfg_;\n};\n\nOpenCLModuleNode::~OpenCLModuleNode() {\n {\n \/\/ free the kernel ids in global table.\n std::lock_guard lock(workspace_->mu);\n for (auto& kv : kid_map_) {\n workspace_->free_kernel_ids.push_back(kv.second.kernel_id);\n }\n }\n \/\/ free the kernels\n for (cl_kernel k : kernels_) {\n OPENCL_CALL(clReleaseKernel(k));\n }\n if (program_) {\n OPENCL_CALL(clReleaseProgram(program_));\n }\n}\n\nconst std::shared_ptr& OpenCLModuleNode::GetGlobalWorkspace() {\n return cl::OpenCLWorkspace::Global();\n}\n\nconst char* OpenCLModuleNode::type_key() const {\n return \"opencl\";\n}\n\nPackedFunc OpenCLModuleNode::GetFunction(\n const std::string& name,\n const std::shared_ptr& sptr_to_self) {\n CHECK_EQ(sptr_to_self.get(), this);\n CHECK_NE(name, symbol::tvm_module_main)\n << \"Device function do not have main\";\n auto it = fmap_.find(name);\n if (it == fmap_.end()) return PackedFunc();\n const FunctionInfo& info = it->second;\n OpenCLWrappedFunc f;\n std::vector arg_size(info.arg_types.size());\n for (size_t i = 0; i < info.arg_types.size(); ++i) {\n TVMType t = info.arg_types[i];\n CHECK_EQ(t.lanes, 1U);\n if (t.code == kHandle) {\n \/\/ specially store pointer type size in OpenCL driver\n arg_size[i] = sizeof(void*);\n } else {\n uint32_t bits = t.bits;\n CHECK_EQ(bits % 8, 0U);\n arg_size[i] = bits \/ 8;\n }\n }\n \/\/ initialize the wrapped func.\n f.Init(this, sptr_to_self, kid_map_.at(name),\n name, arg_size, info.thread_axis_tags);\n return PackFuncVoidAddr(f, info.arg_types);\n}\n\nvoid OpenCLModuleNode::SaveToFile(const std::string& file_name,\n const std::string& format) {\n std::string fmt = GetFileFormat(file_name, format);\n CHECK_EQ(fmt, fmt_)\n << \"Can only save to format=\" << fmt_;\n std::string meta_file = GetMetaFilePath(file_name);\n SaveMetaDataToFile(meta_file, fmap_);\n SaveBinaryToFile(file_name, data_);\n}\n\nvoid OpenCLModuleNode::SaveToBinary(dmlc::Stream* stream) {\n stream->Write(fmt_);\n stream->Write(fmap_);\n stream->Write(data_);\n}\n\nstd::string OpenCLModuleNode::GetSource(const std::string& format) {\n if (format == fmt_) return data_;\n if (fmt_ == \"cl\") {\n return data_;\n } else {\n return source_;\n }\n}\n\nvoid OpenCLModuleNode::Init() {\n workspace_ = GetGlobalWorkspace();\n workspace_->Init();\n CHECK(workspace_->context != nullptr) << \"No OpenCL device\";\n if (fmt_ == \"cl\") {\n const char* s = data_.c_str();\n size_t len = data_.length();\n cl_int err;\n program_ = clCreateProgramWithSource(\n workspace_->context, 1, &s, &len, &err);\n OPENCL_CHECK_ERROR(err);\n } else if (fmt_ == \"xclbin\" || fmt_ == \"awsxclbin\") {\n const unsigned char* s = (const unsigned char *)data_.c_str();\n size_t len = data_.length();\n cl_int err;\n program_ = clCreateProgramWithBinary(\n workspace_->context, 1, &(workspace_->devices[0]), &len, &s, NULL, &err);\n if (err != CL_SUCCESS) {\n LOG(ERROR) << \"OpenCL Error: \" << cl::CLGetErrorString(err);\n }\n } else {\n LOG(FATAL) << \"Unknown OpenCL format \" << fmt_;\n }\n device_built_flag_.resize(workspace_->devices.size(), false);\n \/\/ initialize the kernel id, need to lock global table.\n std::lock_guard lock(workspace_->mu);\n for (const auto& kv : fmap_) {\n const std::string& key = kv.first;\n KTRefEntry e;\n if (workspace_->free_kernel_ids.size() != 0) {\n e.kernel_id = workspace_->free_kernel_ids.back();\n workspace_->free_kernel_ids.pop_back();\n } else {\n e.kernel_id = workspace_->num_registered_kernels++;\n }\n e.version = workspace_->timestamp++;\n kid_map_[key] = e;\n }\n}\n\ncl_kernel OpenCLModuleNode::InstallKernel(cl::OpenCLWorkspace* w,\n cl::OpenCLThreadEntry* t,\n const std::string& func_name,\n const KTRefEntry& e) {\n std::lock_guard lock(build_lock_);\n int device_id = t->context.device_id;\n if (!device_built_flag_[device_id]) {\n \/\/ build program\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n err = clBuildProgram(program_, 1, &dev, nullptr, nullptr, nullptr);\n if (err != CL_SUCCESS) {\n size_t len;\n std::string log;\n clGetProgramBuildInfo(\n program_, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &len);\n log.resize(len);\n clGetProgramBuildInfo(\n program_, dev, CL_PROGRAM_BUILD_LOG, len, &log[0], nullptr);\n LOG(FATAL) << \"OpenCL build error for device=\" << dev << log;\n }\n device_built_flag_[device_id] = true;\n }\n \/\/ build kernel\n cl_int err;\n cl_kernel kernel = clCreateKernel(program_, func_name.c_str(), &err);\n OPENCL_CHECK_ERROR(err);\n t->kernel_table[e.kernel_id].kernel = kernel;\n t->kernel_table[e.kernel_id].version = e.version;\n kernels_.push_back(kernel);\n return kernel;\n}\n\nModule OpenCLModuleCreate(\n std::string data,\n std::string fmt,\n std::unordered_map fmap,\n std::string source) {\n std::shared_ptr n =\n std::make_shared(data, fmt, fmap, source);\n n->Init();\n return Module(n);\n}\n\n\/\/ Load module from module.\nModule OpenCLModuleLoadFile(const std::string& file_name,\n const std::string& format) {\n std::string data;\n std::unordered_map fmap;\n std::string fmt = GetFileFormat(file_name, format);\n std::string meta_file = GetMetaFilePath(file_name);\n LoadBinaryFromFile(file_name, &data);\n LoadMetaDataFromFile(meta_file, &fmap);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nModule OpenCLModuleLoadBinary(void* strm) {\n dmlc::Stream* stream = static_cast(strm);\n std::string data;\n std::unordered_map fmap;\n std::string fmt;\n stream->Read(&fmt);\n stream->Read(&fmap);\n stream->Read(&data);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nTVM_REGISTER_GLOBAL(\"module.loadfile_cl\")\n.set_body([](TVMArgs args, TVMRetValue* rv) {\n *rv = OpenCLModuleLoadFile(args[0], args[1]);\n });\n\nTVM_REGISTER_GLOBAL(\"module.loadfile_clbin\")\n.set_body([](TVMArgs args, TVMRetValue* rv) {\n *rv = OpenCLModuleLoadFile(args[0], args[1]);\n });\n\nTVM_REGISTER_GLOBAL(\"module.loadbinary_opencl\")\n.set_body([](TVMArgs args, TVMRetValue* rv) {\n *rv = OpenCLModuleLoadBinary(args[0]);\n });\n} \/\/ namespace runtime\n} \/\/ namespace tvm\n[RUNTIME][OPENCL] Create program lazily when the program is built (#1408)\/*!\n * Copyright (c) 2017 by Contributors\n * \\file opencl_module.cc\n *\/\n#include \n#include \n#include \n#include \n#include \n#include \".\/opencl_common.h\"\n#include \".\/opencl_module.h\"\n\nnamespace tvm {\nnamespace runtime {\n\nclass OpenCLWrappedFunc {\n public:\n \/\/ initialize the OpenCL function.\n void Init(OpenCLModuleNode* m,\n std::shared_ptr sptr,\n OpenCLModuleNode::KTRefEntry entry,\n std::string func_name,\n std::vector arg_size,\n const std::vector& thread_axis_tags) {\n w_ = m->GetGlobalWorkspace().get();\n m_ = m;\n sptr_ = sptr;\n entry_ = entry;\n func_name_ = func_name;\n arg_size_ = arg_size;\n thread_axis_cfg_.Init(arg_size.size(), thread_axis_tags);\n }\n \/\/ invoke the function with void arguments\n void operator()(TVMArgs args,\n TVMRetValue* rv,\n void** void_args) const {\n cl::OpenCLThreadEntry* t = w_->GetThreadEntry();\n \/\/ get the kernel from thread local kernel table.\n if (entry_.kernel_id >= t->kernel_table.size()) {\n t->kernel_table.resize(entry_.kernel_id + 1);\n }\n const auto& e = t->kernel_table[entry_.kernel_id];\n cl_kernel kernel = e.kernel;\n if (kernel == nullptr || e.version != entry_.version) {\n kernel = m_->InstallKernel(w_, t, func_name_, entry_);\n }\n \/\/ setup arguments.\n for (cl_uint i = 0; i < arg_size_.size(); ++i) {\n OPENCL_CALL(clSetKernelArg(kernel, i, arg_size_[i], void_args[i]));\n }\n cl_command_queue queue = w_->GetQueue(t->context);\n ThreadWorkLoad wl = thread_axis_cfg_.Extract(args);\n cl_uint work_dim = static_cast(thread_axis_cfg_.work_dim());\n for (cl_uint i = 0; i < work_dim; ++i) {\n wl.work_size[i] *= wl.work_size[i + 3];\n }\n \/\/ launch kernel\n OPENCL_CALL(clEnqueueNDRangeKernel(\n queue, kernel, work_dim, nullptr,\n wl.work_size,\n wl.work_size + 3,\n 0, nullptr, nullptr));\n }\n\n private:\n \/\/ global workspace.\n cl::OpenCLWorkspace* w_;\n \/\/ The module\n OpenCLModuleNode* m_;\n \/\/ resource handle\n std::shared_ptr sptr_;\n \/\/ global kernel id in the kernel table.\n OpenCLModuleNode::KTRefEntry entry_;\n \/\/ The name of the function.\n std::string func_name_;\n \/\/ convert code for void argument\n std::vector arg_size_;\n \/\/ thread axis config\n ThreadAxisConfig thread_axis_cfg_;\n};\n\nOpenCLModuleNode::~OpenCLModuleNode() {\n {\n \/\/ free the kernel ids in global table.\n std::lock_guard lock(workspace_->mu);\n for (auto& kv : kid_map_) {\n workspace_->free_kernel_ids.push_back(kv.second.kernel_id);\n }\n }\n \/\/ free the kernels\n for (cl_kernel k : kernels_) {\n OPENCL_CALL(clReleaseKernel(k));\n }\n if (program_) {\n OPENCL_CALL(clReleaseProgram(program_));\n }\n}\n\nconst std::shared_ptr& OpenCLModuleNode::GetGlobalWorkspace() {\n return cl::OpenCLWorkspace::Global();\n}\n\nconst char* OpenCLModuleNode::type_key() const {\n return \"opencl\";\n}\n\nPackedFunc OpenCLModuleNode::GetFunction(\n const std::string& name,\n const std::shared_ptr& sptr_to_self) {\n CHECK_EQ(sptr_to_self.get(), this);\n CHECK_NE(name, symbol::tvm_module_main)\n << \"Device function do not have main\";\n auto it = fmap_.find(name);\n if (it == fmap_.end()) return PackedFunc();\n const FunctionInfo& info = it->second;\n OpenCLWrappedFunc f;\n std::vector arg_size(info.arg_types.size());\n for (size_t i = 0; i < info.arg_types.size(); ++i) {\n TVMType t = info.arg_types[i];\n CHECK_EQ(t.lanes, 1U);\n if (t.code == kHandle) {\n \/\/ specially store pointer type size in OpenCL driver\n arg_size[i] = sizeof(void*);\n } else {\n uint32_t bits = t.bits;\n CHECK_EQ(bits % 8, 0U);\n arg_size[i] = bits \/ 8;\n }\n }\n \/\/ initialize the wrapped func.\n f.Init(this, sptr_to_self, kid_map_.at(name),\n name, arg_size, info.thread_axis_tags);\n return PackFuncVoidAddr(f, info.arg_types);\n}\n\nvoid OpenCLModuleNode::SaveToFile(const std::string& file_name,\n const std::string& format) {\n std::string fmt = GetFileFormat(file_name, format);\n CHECK_EQ(fmt, fmt_)\n << \"Can only save to format=\" << fmt_;\n std::string meta_file = GetMetaFilePath(file_name);\n SaveMetaDataToFile(meta_file, fmap_);\n SaveBinaryToFile(file_name, data_);\n}\n\nvoid OpenCLModuleNode::SaveToBinary(dmlc::Stream* stream) {\n stream->Write(fmt_);\n stream->Write(fmap_);\n stream->Write(data_);\n}\n\nstd::string OpenCLModuleNode::GetSource(const std::string& format) {\n if (format == fmt_) return data_;\n if (fmt_ == \"cl\") {\n return data_;\n } else {\n return source_;\n }\n}\n\nvoid OpenCLModuleNode::Init() {\n workspace_ = GetGlobalWorkspace();\n workspace_->Init();\n CHECK(workspace_->context != nullptr) << \"No OpenCL device\";\n device_built_flag_.resize(workspace_->devices.size(), false);\n \/\/ initialize the kernel id, need to lock global table.\n std::lock_guard lock(workspace_->mu);\n for (const auto& kv : fmap_) {\n const std::string& key = kv.first;\n KTRefEntry e;\n if (workspace_->free_kernel_ids.size() != 0) {\n e.kernel_id = workspace_->free_kernel_ids.back();\n workspace_->free_kernel_ids.pop_back();\n } else {\n e.kernel_id = workspace_->num_registered_kernels++;\n }\n e.version = workspace_->timestamp++;\n kid_map_[key] = e;\n }\n}\n\ncl_kernel OpenCLModuleNode::InstallKernel(cl::OpenCLWorkspace* w,\n cl::OpenCLThreadEntry* t,\n const std::string& func_name,\n const KTRefEntry& e) {\n std::lock_guard lock(build_lock_);\n int device_id = t->context.device_id;\n if (!device_built_flag_[device_id]) {\n \/\/ create program\n if (fmt_ == \"cl\") {\n if (program_ == nullptr) {\n const char* s = data_.c_str();\n size_t len = data_.length();\n cl_int err;\n program_ = clCreateProgramWithSource(w->context, 1, &s, &len, &err);\n OPENCL_CHECK_ERROR(err);\n }\n } else if (fmt_ == \"xclbin\" || fmt_ == \"awsxclbin\") {\n const unsigned char* s = (const unsigned char *)data_.c_str();\n size_t len = data_.length();\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n program_ = clCreateProgramWithBinary(w->context, 1, &dev, &len, &s, NULL, &err);\n OPENCL_CHECK_ERROR(err);\n } else {\n LOG(FATAL) << \"Unknown OpenCL format \" << fmt_;\n }\n \/\/ build program\n cl_int err;\n cl_device_id dev = w->devices[device_id];\n err = clBuildProgram(program_, 1, &dev, nullptr, nullptr, nullptr);\n if (err != CL_SUCCESS) {\n size_t len;\n std::string log;\n clGetProgramBuildInfo(\n program_, dev, CL_PROGRAM_BUILD_LOG, 0, nullptr, &len);\n log.resize(len);\n clGetProgramBuildInfo(\n program_, dev, CL_PROGRAM_BUILD_LOG, len, &log[0], nullptr);\n LOG(FATAL) << \"OpenCL build error for device=\" << dev << log;\n }\n device_built_flag_[device_id] = true;\n }\n \/\/ build kernel\n cl_int err;\n cl_kernel kernel = clCreateKernel(program_, func_name.c_str(), &err);\n OPENCL_CHECK_ERROR(err);\n t->kernel_table[e.kernel_id].kernel = kernel;\n t->kernel_table[e.kernel_id].version = e.version;\n kernels_.push_back(kernel);\n return kernel;\n}\n\nModule OpenCLModuleCreate(\n std::string data,\n std::string fmt,\n std::unordered_map fmap,\n std::string source) {\n std::shared_ptr n =\n std::make_shared(data, fmt, fmap, source);\n n->Init();\n return Module(n);\n}\n\n\/\/ Load module from module.\nModule OpenCLModuleLoadFile(const std::string& file_name,\n const std::string& format) {\n std::string data;\n std::unordered_map fmap;\n std::string fmt = GetFileFormat(file_name, format);\n std::string meta_file = GetMetaFilePath(file_name);\n LoadBinaryFromFile(file_name, &data);\n LoadMetaDataFromFile(meta_file, &fmap);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nModule OpenCLModuleLoadBinary(void* strm) {\n dmlc::Stream* stream = static_cast(strm);\n std::string data;\n std::unordered_map fmap;\n std::string fmt;\n stream->Read(&fmt);\n stream->Read(&fmap);\n stream->Read(&data);\n return OpenCLModuleCreate(data, fmt, fmap, std::string());\n}\n\nTVM_REGISTER_GLOBAL(\"module.loadfile_cl\")\n.set_body([](TVMArgs args, TVMRetValue* rv) {\n *rv = OpenCLModuleLoadFile(args[0], args[1]);\n });\n\nTVM_REGISTER_GLOBAL(\"module.loadfile_clbin\")\n.set_body([](TVMArgs args, TVMRetValue* rv) {\n *rv = OpenCLModuleLoadFile(args[0], args[1]);\n });\n\nTVM_REGISTER_GLOBAL(\"module.loadbinary_opencl\")\n.set_body([](TVMArgs args, TVMRetValue* rv) {\n *rv = OpenCLModuleLoadBinary(args[0]);\n });\n} \/\/ namespace runtime\n} \/\/ namespace tvm\n<|endoftext|>"} {"text":"#include \"renderer.hpp\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"addr_space.hpp\"\r\n#include \"address.hpp\"\r\n#include \"const.hpp\"\r\n#include \"cpu.hpp\"\r\n#include \"cursor.hpp\"\r\n#include \"instruction.hpp\"\r\n#include \"printer.hpp\"\r\n#include \"ram.hpp\"\r\n#include \"util.hpp\"\r\n\r\nusing namespace std;\r\n\r\n\/*\r\n * Only public method. Also static. It creates new object every time \r\n * it gets called.\r\n *\/\r\nvector> Renderer::renderState(const Printer &printerIn,\r\n const Ram &ramIn, \r\n const Cpu &cpuIn, \r\n const Cursor &cursorIn,\r\n const View &viewIn) {\r\n Renderer instance(printerIn, ramIn, cpuIn, cursorIn, viewIn);\r\n vector> out;\r\n for (vector line : viewIn.lines) {\r\n out.push_back(instance.insertActualValues(line));\r\n }\r\n return out;\r\n}\r\n\r\nvector Renderer::insertActualValues(vector lineIn) {\r\n vector highlightedChars = getHighlightedLocations(lineIn);\r\n vector lineOut;\r\n for (string cIn : lineIn) {\r\n string sOut;\r\n bool charIsALightbulb = ALL_INDICATORS.count(cIn);\r\n if (charIsALightbulb) {\r\n sOut = getLightbulb(cIn);\r\n } else {\r\n sOut = cIn;\r\n }\r\n lineOut.push_back(sOut);\r\n }\r\n return insertEscSeqences(lineOut, highlightedChars);\r\n}\r\n\r\nvector Renderer::insertEscSeqences(\r\n vector lineWithoutEscapeSeqences, vector highlightedChars) {\r\n vector lineOut;\r\n bool insideHighlightBlock = false;\r\n for (size_t i = 0; i < lineWithoutEscapeSeqences.size(); i++) {\r\n bool firstCharInsideBlock = highlightedChars[i] && !insideHighlightBlock;\r\n if (firstCharInsideBlock) {\r\n lineOut.insert(lineOut.end(), HIGHLIGHT_ESC_VEC.begin(), \r\n HIGHLIGHT_ESC_VEC.end());\r\n insideHighlightBlock = true;\r\n }\r\n bool firstCharOutsideBlock = !highlightedChars[i] && insideHighlightBlock;\r\n if (firstCharOutsideBlock) {\r\n lineOut.insert(lineOut.end(), HIGHLIGHT_END_ESC_VEC.begin(), \r\n HIGHLIGHT_END_ESC_VEC.end());\r\n insideHighlightBlock = false;\r\n }\r\n lineOut.push_back(lineWithoutEscapeSeqences[i]);\r\n }\r\n return lineOut;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET HIGHLIGHTED LOCATIONS \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nvector Renderer::getHighlightedLocations(vector lineIn) {\r\n vector highlightedLocations (lineIn.size(), false);\r\n highlightPc(highlightedLocations, lineIn);\r\n if (executionEnded()) {\r\n return highlightedLocations;\r\n }\r\n highlightCursor(highlightedLocations, lineIn);\r\n Instruction *inst = getInstruction();\r\n bool cursorOnData = inst == NULL;\r\n if (cursorOnData) {\r\n highlightPointingInstructions(highlightedLocations, lineIn);\r\n return highlightedLocations;\r\n }\r\n highlightOperator(highlightedLocations, lineIn, inst);\r\n if (inst->adr.space == CODE) {\r\n highlightCodeWord(highlightedLocations, lineIn, inst);\r\n } else if (inst->adr.space == DATA) {\r\n highlightDataWord(highlightedLocations, lineIn, inst);\r\n }\r\n return highlightedLocations;\r\n}\r\n\r\nvoid Renderer::highlightPc(vector &highlightedLocations,\r\n vector &lineIn) {\r\n if (executionHasntStarted() || pcHighlighted) {\r\n return;\r\n }\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_ADR_INDICATOR) {\r\n int index = switchIndex[CODE_ADR_INDICATOR];\r\n if (pcPointingToAddress(index)) {\r\n highlightedLocations[i] = true;\r\n pcHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightCursor(vector &highlightedLocations,\r\n vector &lineIn) {\r\n if (!executionHasntStarted() || cursorHighlighted) {\r\n return;\r\n }\r\n if (cursor.getAddressSpace() == CODE) {\r\n findCursor(highlightedLocations, lineIn, CODE_INDICATOR);\r\n } else if (cursor.getAddressSpace() == DATA) {\r\n findCursor(highlightedLocations, lineIn, DATA_INDICATOR);\r\n }\r\n}\r\n\r\nvoid Renderer::findCursor(vector &highlightedLocations,\r\n vector &lineIn, string c) {\r\n int indexDelta = 0;\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == c) {\r\n int lightbulbIndex = switchIndex[c] + indexDelta++;\r\n if (cursor.getAbsoluteBitIndex() == lightbulbIndex) {\r\n highlightedLocations[i] = true;\r\n cursorHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightPointingInstructions(vector &highlightedLocations,\r\n vector &lineIn) {\r\n set *pointingInstructions = getIndexesOfPointingInstructions();\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_INDICATOR) {\r\n int addressValue = switchIndex[CODE_INDICATOR] \/ WORD_SIZE;\r\n if (pointingInstructions->count(addressValue)) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightOperator(vector &highlightedLocations,\r\n vector &lineIn,\r\n Instruction *inst) {\r\n string exclude;\r\n if (inst->isLogic()) {\r\n exclude = LOGIC_OPS_INDICATOR[min(inst->logicIndex, 8)];\r\n }\r\n if (inst->index == INC_DEC_OPS_INDEX) {\r\n if (inst->logicIndex <= 7) {\r\n exclude = \"INC\";\r\n } else {\r\n exclude = \"DEC\";\r\n }\r\n }\r\n string label = \" \" + inst->label;\r\n label.append(11 - inst->label.length(), ' '); \r\n highlightLabel(highlightedLocations, lineIn, Util::stringToVecOfString(label), \r\n Util::stringToVecOfString(exclude));\r\n}\r\n\r\nvoid Renderer::highlightCodeWord(vector &highlightedLocations,\r\n vector &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector stopLabel = Util::stringToVecOfString(LAST_CODE_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, stopLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, CODE_INDICATOR, CODE);\r\n}\r\n\r\nvoid Renderer::highlightDataWord(vector &highlightedLocations,\r\n vector &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector inOutLabel = Util::stringToVecOfString(LAST_DATA_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, inOutLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, DATA_INDICATOR, DATA);\r\n}\r\n\r\nvoid Renderer::highlightWord(vector &highlightedLocations,\r\n vector &lineIn, string indicator,\r\n AddrSpace addrSpace) {\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == indicator) {\r\n int addressValue = switchIndex[indicator] \/ WORD_SIZE;\r\n Address adr = Address(addrSpace, Util::getBoolNibb(addressValue));\r\n if (instructionPointingToAddress(adr)) {\r\n highlightedLocations[i] = !highlightedLocations[i];\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightLabel(vector &highlightedLocations,\r\n vector &lineIn,\r\n vector label,\r\n vector exclude) {\r\n auto it = search(begin(lineIn), end(lineIn), begin(label), end(label));\r\n int labelPosition = it - lineIn.begin();\r\n bool notFound = it == end(lineIn);\r\n if (notFound) {\r\n return;\r\n }\r\n size_t excludePosition = numeric_limits::max();\r\n if (!exclude.empty()) {\r\n it = search(begin(label), end(label), begin(exclude), end(exclude));\r\n excludePosition = it - label.begin();\r\n }\r\n for (size_t i = labelPosition; i < labelPosition + label.size(); i++) {\r\n bool highlight = (i < labelPosition + excludePosition ||\r\n i >= labelPosition + excludePosition + exclude.size());\r\n if (highlight) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET LIGHTBULB \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nstring Renderer::getLightbulb(string cIn) {\r\n int i = switchIndex[cIn]++;\r\n if (cIn == CODE_INDICATOR) {\r\n return getCodeBit(i);\r\n } else if (cIn == DATA_INDICATOR) {\r\n return getDataBit(i);\r\n } else if (cIn == REGISTER_INDICATOR) {\r\n return view.getLightbulb(cpu.getRegister().at(i));\r\n } else if (cIn == CODE_ADR_INDICATOR) {\r\n return getAdrIndicator(CODE, i);\r\n } else if (cIn == DATA_ADR_INDICATOR) {\r\n return getAdrIndicator(DATA, i);\r\n } else if (cIn == OUTPUT_INDICATOR) {\r\n return getFormattedOutput(i);\r\n }\r\n cerr << \"There was an error parsing a drawing file.\";\r\n cerr << \" Problem with char\" << cIn << \". Will ignore it.\";\r\n return \" \";\r\n}\r\n\r\nstring Renderer::getCodeBit(int i) {\r\n return getBit(CODE, i);\r\n}\r\n\r\nstring Renderer::getDataBit(int i) {\r\n return getBit(DATA, i);\r\n}\r\n\r\nstring Renderer::getBit(AddrSpace space, int i) {\r\n pair coord = convertIndexToCoordinates(i);\r\n bool state = ram.state.at(space).at(coord.second).at(coord.first);\r\n return view.getLightbulb(state);\r\n}\r\n\r\npair Renderer::convertIndexToCoordinates(int index) {\r\n int y = index \/ WORD_SIZE;\r\n int x = index % WORD_SIZE;\r\n return pair(x, y);\r\n}\r\n\r\nbool Renderer::pcPointingToAddress(int adr) {\r\n if (executionHasntStarted()) {\r\n return false;\r\n }\r\n return Util::getInt(cpu.getPc()) == adr;\r\n}\r\n\r\nstring Renderer::getAdrIndicator(AddrSpace addrSpace, int index) {\r\n Address indicatorsAddress = Address(addrSpace, Util::getBoolNibb(index));\r\n bool addressReferenced = isAddressReferencedFirstOrder(indicatorsAddress);\r\n return view.getLightbulb(addressReferenced);\r\n}\r\n\r\nstring Renderer::getFormattedOutput(int i) {\r\n if (printer.getPrinterOutput().length() <= (unsigned) i) {\r\n return \" \";\r\n } else {\r\n return string(1, printer.getPrinterOutput().at(i));\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET INSTRUCTION \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nInstruction* Renderer::getInstruction() {\r\n bool noActiveInstruction = !machineActive() &&\r\n cursor.getAddressSpace() == DATA;\r\n if (noActiveInstruction) {\r\n return NULL;\r\n }\r\n if (instruction.size() == 0) {\r\n instruction.push_back(initializeInstruction());\r\n }\r\n return &instruction[0];\r\n}\r\n\r\nbool Renderer::machineActive() {\r\n return !(executionHasntStarted() || executionEnded());\r\n}\r\n\r\nbool Renderer::executionHasntStarted() {\r\n return cpu.getCycle() == 0;\r\n}\r\n\r\nbool Renderer::executionEnded() {\r\n return Util::getInt(cpu.getPc()) == RAM_SIZE;\r\n}\r\n\r\nInstruction Renderer::initializeInstruction() {\r\n if (machineActive()) {\r\n return cpu.getInstruction();\r\n } else {\r\n return Instruction(cursor.getWord(), EMPTY_WORD, &ram);\r\n }\r\n}\r\n\r\nbool Renderer::instructionHasId(int id) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->index == id;\r\n}\r\n\r\n\/*\r\n * Is instruction pointing to passed address in passed address space.\r\n *\/\r\nbool Renderer::instructionPointingToAddress(Address adr) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->adr == adr;\r\n}\r\n\r\nset* Renderer::getIndexesOfPointingInstructions() {\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions = generatePointingInstructions();\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions.insert(-1);\r\n }\r\n }\r\n return &pointingInstructions;\r\n}\r\n\r\nset Renderer::generatePointingInstructions() {\r\n vector *allInstructions = getEffectiveInstructions();\r\n set out;\r\n int i = 0;\r\n for (Instruction inst : *allInstructions) {\r\n if (inst.adr == cursor.getAddress()) {\r\n out.insert(i);\r\n }\r\n i++;\r\n }\r\n return out;\r\n}\r\n\r\nvector* Renderer::getEffectiveInstructions() {\r\n if (!effectiveInstructionsInitialized) {\r\n vector *allInstructions = getAllInstructions();\r\n int lastNonemptyInst = -1;\r\n int i = 0;\r\n for (Instruction inst : *allInstructions) {\r\n if (inst.val != EMPTY_WORD) {\r\n lastNonemptyInst = i;\r\n }\r\n i++;\r\n }\r\n bool somePresent = lastNonemptyInst != -1;\r\n if (somePresent) {\r\n effectiveInstructions = vector(\r\n allInstructions->begin(), \r\n allInstructions->begin() + lastNonemptyInst+1);\r\n }\r\n effectiveInstructionsInitialized = true;\r\n }\r\n return &effectiveInstructions;\r\n}\r\n\r\nvector* Renderer::getAllInstructions() {\r\n if (allInstructions.empty()) {\r\n for (vector word : ram.state.at(CODE)) {\r\n Instruction inst = Instruction(word, cpu.getRegister(), &ram);\r\n allInstructions.push_back(inst);\r\n }\r\n }\r\n return &allInstructions;\r\n}\r\n\r\nbool Renderer::isAddressReferencedFirstOrder(Address adr) {\r\n vector *instructions = getAllInstructions();\r\n for (Instruction inst : *instructions) {\r\n vector
aaa = inst.firstOrderAdr;\r\n bool isReferenced = find(aaa.begin(), aaa.end(), adr) != aaa.end();\r\n if (isReferenced) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}Address indicator isn't turn on by empty instructions#include \"renderer.hpp\"\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n#include \"addr_space.hpp\"\r\n#include \"address.hpp\"\r\n#include \"const.hpp\"\r\n#include \"cpu.hpp\"\r\n#include \"cursor.hpp\"\r\n#include \"instruction.hpp\"\r\n#include \"printer.hpp\"\r\n#include \"ram.hpp\"\r\n#include \"util.hpp\"\r\n\r\nusing namespace std;\r\n\r\n\/*\r\n * Only public method. Also static. It creates new object every time \r\n * it gets called.\r\n *\/\r\nvector> Renderer::renderState(const Printer &printerIn,\r\n const Ram &ramIn, \r\n const Cpu &cpuIn, \r\n const Cursor &cursorIn,\r\n const View &viewIn) {\r\n Renderer instance(printerIn, ramIn, cpuIn, cursorIn, viewIn);\r\n vector> out;\r\n for (vector line : viewIn.lines) {\r\n out.push_back(instance.insertActualValues(line));\r\n }\r\n return out;\r\n}\r\n\r\nvector Renderer::insertActualValues(vector lineIn) {\r\n vector highlightedChars = getHighlightedLocations(lineIn);\r\n vector lineOut;\r\n for (string cIn : lineIn) {\r\n string sOut;\r\n bool charIsALightbulb = ALL_INDICATORS.count(cIn);\r\n if (charIsALightbulb) {\r\n sOut = getLightbulb(cIn);\r\n } else {\r\n sOut = cIn;\r\n }\r\n lineOut.push_back(sOut);\r\n }\r\n return insertEscSeqences(lineOut, highlightedChars);\r\n}\r\n\r\nvector Renderer::insertEscSeqences(\r\n vector lineWithoutEscapeSeqences, vector highlightedChars) {\r\n vector lineOut;\r\n bool insideHighlightBlock = false;\r\n for (size_t i = 0; i < lineWithoutEscapeSeqences.size(); i++) {\r\n bool firstCharInsideBlock = highlightedChars[i] && !insideHighlightBlock;\r\n if (firstCharInsideBlock) {\r\n lineOut.insert(lineOut.end(), HIGHLIGHT_ESC_VEC.begin(), \r\n HIGHLIGHT_ESC_VEC.end());\r\n insideHighlightBlock = true;\r\n }\r\n bool firstCharOutsideBlock = !highlightedChars[i] && insideHighlightBlock;\r\n if (firstCharOutsideBlock) {\r\n lineOut.insert(lineOut.end(), HIGHLIGHT_END_ESC_VEC.begin(), \r\n HIGHLIGHT_END_ESC_VEC.end());\r\n insideHighlightBlock = false;\r\n }\r\n lineOut.push_back(lineWithoutEscapeSeqences[i]);\r\n }\r\n return lineOut;\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET HIGHLIGHTED LOCATIONS \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nvector Renderer::getHighlightedLocations(vector lineIn) {\r\n vector highlightedLocations (lineIn.size(), false);\r\n highlightPc(highlightedLocations, lineIn);\r\n if (executionEnded()) {\r\n return highlightedLocations;\r\n }\r\n highlightCursor(highlightedLocations, lineIn);\r\n Instruction *inst = getInstruction();\r\n bool cursorOnData = inst == NULL;\r\n if (cursorOnData) {\r\n highlightPointingInstructions(highlightedLocations, lineIn);\r\n return highlightedLocations;\r\n }\r\n highlightOperator(highlightedLocations, lineIn, inst);\r\n if (inst->adr.space == CODE) {\r\n highlightCodeWord(highlightedLocations, lineIn, inst);\r\n } else if (inst->adr.space == DATA) {\r\n highlightDataWord(highlightedLocations, lineIn, inst);\r\n }\r\n return highlightedLocations;\r\n}\r\n\r\nvoid Renderer::highlightPc(vector &highlightedLocations,\r\n vector &lineIn) {\r\n if (executionHasntStarted() || pcHighlighted) {\r\n return;\r\n }\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_ADR_INDICATOR) {\r\n int index = switchIndex[CODE_ADR_INDICATOR];\r\n if (pcPointingToAddress(index)) {\r\n highlightedLocations[i] = true;\r\n pcHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightCursor(vector &highlightedLocations,\r\n vector &lineIn) {\r\n if (!executionHasntStarted() || cursorHighlighted) {\r\n return;\r\n }\r\n if (cursor.getAddressSpace() == CODE) {\r\n findCursor(highlightedLocations, lineIn, CODE_INDICATOR);\r\n } else if (cursor.getAddressSpace() == DATA) {\r\n findCursor(highlightedLocations, lineIn, DATA_INDICATOR);\r\n }\r\n}\r\n\r\nvoid Renderer::findCursor(vector &highlightedLocations,\r\n vector &lineIn, string c) {\r\n int indexDelta = 0;\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == c) {\r\n int lightbulbIndex = switchIndex[c] + indexDelta++;\r\n if (cursor.getAbsoluteBitIndex() == lightbulbIndex) {\r\n highlightedLocations[i] = true;\r\n cursorHighlighted = true;\r\n return;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightPointingInstructions(vector &highlightedLocations,\r\n vector &lineIn) {\r\n set *pointingInstructions = getIndexesOfPointingInstructions();\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == CODE_INDICATOR) {\r\n int addressValue = switchIndex[CODE_INDICATOR] \/ WORD_SIZE;\r\n if (pointingInstructions->count(addressValue)) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightOperator(vector &highlightedLocations,\r\n vector &lineIn,\r\n Instruction *inst) {\r\n string exclude;\r\n if (inst->isLogic()) {\r\n exclude = LOGIC_OPS_INDICATOR[min(inst->logicIndex, 8)];\r\n }\r\n if (inst->index == INC_DEC_OPS_INDEX) {\r\n if (inst->logicIndex <= 7) {\r\n exclude = \"INC\";\r\n } else {\r\n exclude = \"DEC\";\r\n }\r\n }\r\n string label = \" \" + inst->label;\r\n label.append(11 - inst->label.length(), ' '); \r\n highlightLabel(highlightedLocations, lineIn, Util::stringToVecOfString(label), \r\n Util::stringToVecOfString(exclude));\r\n}\r\n\r\nvoid Renderer::highlightCodeWord(vector &highlightedLocations,\r\n vector &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector stopLabel = Util::stringToVecOfString(LAST_CODE_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, stopLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, CODE_INDICATOR, CODE);\r\n}\r\n\r\nvoid Renderer::highlightDataWord(vector &highlightedLocations,\r\n vector &lineIn,\r\n Instruction *inst) {\r\n if (inst->adr.val == LAST_ADDRESS) {\r\n vector inOutLabel = Util::stringToVecOfString(LAST_DATA_ADDR_LABEL);\r\n highlightLabel(highlightedLocations, lineIn, inOutLabel, {});\r\n return;\r\n }\r\n highlightWord(highlightedLocations, lineIn, DATA_INDICATOR, DATA);\r\n}\r\n\r\nvoid Renderer::highlightWord(vector &highlightedLocations,\r\n vector &lineIn, string indicator,\r\n AddrSpace addrSpace) {\r\n for (size_t i = 0; i < lineIn.size(); i++) {\r\n if (lineIn[i] == indicator) {\r\n int addressValue = switchIndex[indicator] \/ WORD_SIZE;\r\n Address adr = Address(addrSpace, Util::getBoolNibb(addressValue));\r\n if (instructionPointingToAddress(adr)) {\r\n highlightedLocations[i] = !highlightedLocations[i];\r\n }\r\n }\r\n }\r\n}\r\n\r\nvoid Renderer::highlightLabel(vector &highlightedLocations,\r\n vector &lineIn,\r\n vector label,\r\n vector exclude) {\r\n auto it = search(begin(lineIn), end(lineIn), begin(label), end(label));\r\n int labelPosition = it - lineIn.begin();\r\n bool notFound = it == end(lineIn);\r\n if (notFound) {\r\n return;\r\n }\r\n size_t excludePosition = numeric_limits::max();\r\n if (!exclude.empty()) {\r\n it = search(begin(label), end(label), begin(exclude), end(exclude));\r\n excludePosition = it - label.begin();\r\n }\r\n for (size_t i = labelPosition; i < labelPosition + label.size(); i++) {\r\n bool highlight = (i < labelPosition + excludePosition ||\r\n i >= labelPosition + excludePosition + exclude.size());\r\n if (highlight) {\r\n highlightedLocations[i] = true;\r\n }\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET LIGHTBULB \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nstring Renderer::getLightbulb(string cIn) {\r\n int i = switchIndex[cIn]++;\r\n if (cIn == CODE_INDICATOR) {\r\n return getCodeBit(i);\r\n } else if (cIn == DATA_INDICATOR) {\r\n return getDataBit(i);\r\n } else if (cIn == REGISTER_INDICATOR) {\r\n return view.getLightbulb(cpu.getRegister().at(i));\r\n } else if (cIn == CODE_ADR_INDICATOR) {\r\n return getAdrIndicator(CODE, i);\r\n } else if (cIn == DATA_ADR_INDICATOR) {\r\n return getAdrIndicator(DATA, i);\r\n } else if (cIn == OUTPUT_INDICATOR) {\r\n return getFormattedOutput(i);\r\n }\r\n cerr << \"There was an error parsing a drawing file.\";\r\n cerr << \" Problem with char\" << cIn << \". Will ignore it.\";\r\n return \" \";\r\n}\r\n\r\nstring Renderer::getCodeBit(int i) {\r\n return getBit(CODE, i);\r\n}\r\n\r\nstring Renderer::getDataBit(int i) {\r\n return getBit(DATA, i);\r\n}\r\n\r\nstring Renderer::getBit(AddrSpace space, int i) {\r\n pair coord = convertIndexToCoordinates(i);\r\n bool state = ram.state.at(space).at(coord.second).at(coord.first);\r\n return view.getLightbulb(state);\r\n}\r\n\r\npair Renderer::convertIndexToCoordinates(int index) {\r\n int y = index \/ WORD_SIZE;\r\n int x = index % WORD_SIZE;\r\n return pair(x, y);\r\n}\r\n\r\nbool Renderer::pcPointingToAddress(int adr) {\r\n if (executionHasntStarted()) {\r\n return false;\r\n }\r\n return Util::getInt(cpu.getPc()) == adr;\r\n}\r\n\r\nstring Renderer::getAdrIndicator(AddrSpace addrSpace, int index) {\r\n Address indicatorsAddress = Address(addrSpace, Util::getBoolNibb(index));\r\n bool addressReferenced = isAddressReferencedFirstOrder(indicatorsAddress);\r\n return view.getLightbulb(addressReferenced);\r\n}\r\n\r\nstring Renderer::getFormattedOutput(int i) {\r\n if (printer.getPrinterOutput().length() <= (unsigned) i) {\r\n return \" \";\r\n } else {\r\n return string(1, printer.getPrinterOutput().at(i));\r\n }\r\n}\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\/ GET INSTRUCTION \/\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\nInstruction* Renderer::getInstruction() {\r\n bool noActiveInstruction = !machineActive() &&\r\n cursor.getAddressSpace() == DATA;\r\n if (noActiveInstruction) {\r\n return NULL;\r\n }\r\n if (instruction.size() == 0) {\r\n instruction.push_back(initializeInstruction());\r\n }\r\n return &instruction[0];\r\n}\r\n\r\nbool Renderer::machineActive() {\r\n return !(executionHasntStarted() || executionEnded());\r\n}\r\n\r\nbool Renderer::executionHasntStarted() {\r\n return cpu.getCycle() == 0;\r\n}\r\n\r\nbool Renderer::executionEnded() {\r\n return Util::getInt(cpu.getPc()) == RAM_SIZE;\r\n}\r\n\r\nInstruction Renderer::initializeInstruction() {\r\n if (machineActive()) {\r\n return cpu.getInstruction();\r\n } else {\r\n return Instruction(cursor.getWord(), EMPTY_WORD, &ram);\r\n }\r\n}\r\n\r\nbool Renderer::instructionHasId(int id) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->index == id;\r\n}\r\n\r\n\/*\r\n * Is instruction pointing to passed address in passed address space.\r\n *\/\r\nbool Renderer::instructionPointingToAddress(Address adr) {\r\n Instruction *inst = getInstruction();\r\n if (inst == NULL) {\r\n return false;\r\n }\r\n return inst->adr == adr;\r\n}\r\n\r\nset* Renderer::getIndexesOfPointingInstructions() {\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions = generatePointingInstructions();\r\n if (pointingInstructions.empty()) {\r\n pointingInstructions.insert(-1);\r\n }\r\n }\r\n return &pointingInstructions;\r\n}\r\n\r\nset Renderer::generatePointingInstructions() {\r\n vector *allInstructions = getEffectiveInstructions();\r\n set out;\r\n int i = 0;\r\n for (Instruction inst : *allInstructions) {\r\n if (inst.adr == cursor.getAddress()) {\r\n out.insert(i);\r\n }\r\n i++;\r\n }\r\n return out;\r\n}\r\n\r\n\/*\r\n * Doesn't include empty instructions from last non-empty on.\r\n *\/\r\nvector* Renderer::getEffectiveInstructions() {\r\n if (!effectiveInstructionsInitialized) {\r\n vector *allInstructions = getAllInstructions();\r\n int lastNonemptyInst = -1;\r\n int i = 0;\r\n for (Instruction inst : *allInstructions) {\r\n if (inst.val != EMPTY_WORD) {\r\n lastNonemptyInst = i;\r\n }\r\n i++;\r\n }\r\n bool somePresent = lastNonemptyInst != -1;\r\n if (somePresent) {\r\n effectiveInstructions = vector(\r\n allInstructions->begin(), \r\n allInstructions->begin() + lastNonemptyInst+1);\r\n }\r\n effectiveInstructionsInitialized = true;\r\n }\r\n return &effectiveInstructions;\r\n}\r\n\r\nvector* Renderer::getAllInstructions() {\r\n if (allInstructions.empty()) {\r\n for (vector word : ram.state.at(CODE)) {\r\n Instruction inst = Instruction(word, cpu.getRegister(), &ram);\r\n allInstructions.push_back(inst);\r\n }\r\n }\r\n return &allInstructions;\r\n}\r\n\r\nbool Renderer::isAddressReferencedFirstOrder(Address adr) {\r\n vector *instructions = getEffectiveInstructions();\r\n for (Instruction inst : *instructions) {\r\n vector
aaa = inst.firstOrderAdr;\r\n bool isReferenced = find(aaa.begin(), aaa.end(), adr) != aaa.end();\r\n if (isReferenced) {\r\n return true;\r\n }\r\n }\r\n return false;\r\n}<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n\n#include \"serve.hpp\"\n#include \"simple_commands.hpp\"\n\nint main(int argc, char * argv[])\n{\n static const char usage[] =\nR\"(Remote SimGrid command-line tool.\n\nUsage:\n rsg serve [--port=] [-- ...]\n rsg add-actor \n [--hostname=] [--port=] [--no-autoconnect]\n [--] [...]\n rsg start [--hostname=] [--port=]\n rsg status [--hostname=] [--port=] [--retry-timeout=]\n rsg kill [--hostname=] [--reason=] [--port=]\n rsg --help\n\nOptions:\n -h --hostname Server's hostname [default: 127.0.0.1].\n -p --port Server's TCP port [default: 35000].\n --retry-timeout If set, retry connection until timeout in milliseconds.\n)\";\n\n \/\/ Parse CLI arguments.\n auto args = docopt::docopt(usage, { argv + 1, argv + argc }, true);\n\n \/\/ Check argument validity\n std::string server_hostname = args[\"--hostname\"].asString();\n int server_port = args[\"--port\"].asLong();\n\n \/\/ Debug printing, should be removed.\n \/*std::cout << \"Arguments:\" << std::endl;\n for(auto const & arg : args) {\n std::cout << \" \" << arg.first << \": \" << arg.second << std::endl;\n }*\/\n\n \/\/ Manage subcommands.\n int return_code = 0;\n if (args[\"serve\"].asBool())\n {\n std::string platform_file = args[\"\"].asString();\n std::vector simgrid_options = args[\"\"].asStringList();\n return_code = serve(platform_file, server_port, simgrid_options);\n }\n else if (args[\"kill\"].asBool())\n {\n std::string kill_reason = \"\";\n if (args[\"--reason\"].isString())\n kill_reason = args[\"--reason\"].asString();\n return_code = kill(server_hostname, server_port, kill_reason);\n }\n else if (args[\"start\"].asBool())\n {\n return_code = start(server_hostname, server_port);\n }\n else if (args[\"status\"].asBool())\n {\n int retry_timeout_ms = 0;\n if (args[\"--retry-timeout\"].isString())\n retry_timeout_ms = args[\"--retry-timeout\"].asLong();\n return_code = status(server_hostname, server_port, retry_timeout_ms);\n }\n else if (args[\"add-actor\"].asBool())\n {\n std::string actor_name = args[\"\"].asString();\n std::string vhost_name = args[\"\"].asString();\n bool autoconnect = !args[\"--no-autoconnect\"].asBool();\n std::string command = args[\"\"].asString();\n std::vector command_args = args[\"\"].asStringList();\n return_code = add_actor(server_hostname, server_port, actor_name, vhost_name,\n autoconnect, command, command_args);\n }\n\n return return_code;\n}\n[rsg] serve --daemon#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"serve.hpp\"\n#include \"simple_commands.hpp\"\n\nint main(int argc, char * argv[])\n{\n static const char usage[] =\nR\"(Remote SimGrid command-line tool.\n\nUsage:\n rsg serve [--port=] [--daemon] [-- ...]\n rsg add-actor \n [--hostname=] [--port=] [--no-autoconnect]\n [--] [...]\n rsg start [--hostname=] [--port=]\n rsg status [--hostname=] [--port=] [--retry-timeout=]\n rsg kill [--hostname=] [--reason=] [--port=]\n rsg --help\n\nOptions:\n -h --hostname Server's hostname [default: 127.0.0.1].\n -p --port Server's TCP port [default: 35000].\n -d --daemon Run as a deamon — i.e., in background.\n --retry-timeout If set, retry connection until timeout in milliseconds.\n)\";\n\n \/\/ Parse CLI arguments.\n auto args = docopt::docopt(usage, { argv + 1, argv + argc }, true);\n\n \/\/ Check argument validity\n std::string server_hostname = args[\"--hostname\"].asString();\n int server_port = args[\"--port\"].asLong();\n\n \/\/ Debug printing, should be removed.\n \/*std::cout << \"Arguments:\" << std::endl;\n for(auto const & arg : args) {\n std::cout << \" \" << arg.first << \": \" << arg.second << std::endl;\n }*\/\n\n \/\/ Manage subcommands.\n int return_code = 0;\n if (args[\"serve\"].asBool())\n {\n std::string platform_file = args[\"\"].asString();\n std::vector simgrid_options = args[\"\"].asStringList();\n\n if (args[\"--daemon\"].asBool()) {\n if (daemon(1, 1) != 0) {\n printf(\"Could not daemon: %s\\n\", strerror(errno));\n return 1;\n }\n }\n\n return_code = serve(platform_file, server_port, simgrid_options);\n }\n else if (args[\"kill\"].asBool())\n {\n std::string kill_reason = \"\";\n if (args[\"--reason\"].isString())\n kill_reason = args[\"--reason\"].asString();\n return_code = kill(server_hostname, server_port, kill_reason);\n }\n else if (args[\"start\"].asBool())\n {\n return_code = start(server_hostname, server_port);\n }\n else if (args[\"status\"].asBool())\n {\n int retry_timeout_ms = 0;\n if (args[\"--retry-timeout\"].isString())\n retry_timeout_ms = args[\"--retry-timeout\"].asLong();\n return_code = status(server_hostname, server_port, retry_timeout_ms);\n }\n else if (args[\"add-actor\"].asBool())\n {\n std::string actor_name = args[\"\"].asString();\n std::string vhost_name = args[\"\"].asString();\n bool autoconnect = !args[\"--no-autoconnect\"].asBool();\n std::string command = args[\"\"].asString();\n std::vector command_args = args[\"\"].asStringList();\n return_code = add_actor(server_hostname, server_port, actor_name, vhost_name,\n autoconnect, command, command_args);\n }\n\n return return_code;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ src\/main_utils\/parse_list_argument.h\n\/\/ tbd\n\/\/\n\/\/ Created by inoahdev on 1\/26\/18.\n\/\/ Copyright © 2018 inoahdev. All rights reserved.\n\/\/\n\n#include \n\n#include \"..\/mach-o\/utils\/tbd.h\"\n\n#include \"..\/misc\/current_directory.h\"\n#include \"..\/misc\/recurse.h\"\n\n#include \"parse_list_argument.h\"\n\n#include \"tbd_print_field_information.h\"\n#include \"tbd_with_options.h\"\n\nnamespace main_utils {\n bool parse_list_argument(const char *argument, int &index, int argc, const char *argv[]) noexcept {\n auto option = &argument[1];\n if (option[0] == '-') {\n option++;\n }\n\n if (strcmp(option, \"list-architectures\") == 0) {\n if (index != 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself or with a path to a mach-o file\\n\", argument);\n return 1;\n }\n\n \/\/ Two modes exist for --list-architectures, either list out the\n \/\/ architecture-info table, or list the architectures of a single\n \/\/ provided path to a mach-o file\n\n if (index == argc - 1) {\n auto architecture_info = macho::get_architecture_info_table();\n\n fputs(architecture_info->name, stdout);\n architecture_info++;\n\n while (architecture_info->name != nullptr) {\n fprintf(stdout, \", %s\", architecture_info->name);\n architecture_info++;\n }\n } else {\n index++;\n\n \/\/ Don't allow other arguments\n \/\/ to --list-architectures\n\n if (index + 2 <= argc) {\n fprintf(stderr, \"Unrecognized argument: %s\\n\", argv[index + 1]);\n return 1;\n }\n\n auto file = macho::file();\n auto path = misc::path_with_current_directory(argv[index]);\n\n struct stat sbuf;\n if (stat(path.c_str(), &sbuf) != 0) {\n fprintf(stderr, \"Failed to retrieve information on object at provided path, failing with error: %s\\n\", strerror(errno));\n return 1;\n }\n\n if (!S_ISREG(sbuf.st_mode)) {\n fputs(\"Object at provided path is not a regular file\\n\", stderr);\n return 1;\n }\n\n switch (file.open(path.c_str())) {\n case macho::file::open_result::ok:\n break;\n\n case macho::file::open_result::not_a_macho:\n fputs(\"File at provided path is not a mach-o\\n\", stderr);\n return 1;\n\n case macho::file::open_result::invalid_macho:\n fputs(\"File at provided path is an invalid mach-o\\n\", stderr);\n return 1;\n\n case macho::file::open_result::failed_to_open_stream:\n fprintf(stderr, \"Failed to open stream for file at provided path, failing with error: %s\\n\", strerror(errno));\n return 1;\n\n case macho::file::open_result::failed_to_retrieve_information:\n fprintf(stderr, \"Failed to retrieve information on object at provided path, failing with error: %s\\n\", strerror(errno));\n return 1;\n\n case macho::file::open_result::stream_seek_error:\n case macho::file::open_result::stream_read_error:\n fputs(\"Encountered an error while parsing file at provided path\\n\", stderr);\n return 1;\n\n case macho::file::open_result::zero_containers:\n fputs(\"Mach-o file at provided path has zero architectures\\n\", stderr);\n return 1;\n\n case macho::file::open_result::too_many_containers:\n fputs(\"Mach-o file at provided path has too many architectures for its file-size\\n\", stderr);\n return 1;\n\n case macho::file::open_result::containers_goes_past_end_of_file:\n fputs(\"Mach-o file at provided path's architectures goes past end of file\\n\", stderr);\n return 1;\n\n case macho::file::open_result::overlapping_containers:\n fputs(\"Mach-o file at provided path has overlapping architectures\\n\", stderr);\n return 1;\n\n case macho::file::open_result::invalid_container:\n fputs(\"Mach-o file at provided path has an invalid architecture\\n\", stderr);\n return 1;\n }\n\n \/\/ Store architecture names in a vector before printing\n \/\/ so we can handle any errors encountered first\n\n auto cndex = 0;\n auto names = std::vector();\n\n for (const auto &container : file.containers) {\n const auto container_subtype = macho::subtype_from_cputype(macho::cputype(container.header.cputype), container.header.cpusubtype);\n if (container_subtype == macho::subtype::none) {\n fprintf(stderr, \"Unrecognized cpu-subtype for architecture at index %d\\n\", cndex);\n return 1;\n }\n\n const auto architecture_info = macho::architecture_info_from_cputype(macho::cputype(container.header.cputype), container_subtype);\n if (!architecture_info) {\n fprintf(stderr, \"Unrecognized cputype information for architecture at index %d\\n\", cndex);\n return 1;\n }\n\n cndex++;\n }\n\n fputs(names.front(), stdout);\n for (auto iter = names.cbegin() + 1; iter != names.cend(); iter++) {\n fprintf(stdout, \", %s\", *iter);\n }\n }\n\n fputc('\\n', stdout);\n return 0;\n } else if (strcmp(option, \"list-macho-dynamic-libraries\") == 0) {\n if (index != 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself or with a path to a mach-o file\\n\", argument);\n return 1;\n }\n\n \/\/ Two different modes exist for --list-macho-dynamic-libraries;\n \/\/ either recurse current-directory with default options, or\n \/\/ recurse provided director(ies) with provided options\n\n index++;\n if (index != argc) {\n auto paths = std::vector>();\n struct main_utils::tbd_with_options::options options;\n\n options.recurse_directories_at_path = true;\n\n for (; index != argc; index++) {\n const auto &argument = argv[index];\n const auto &argument_front = argument[0];\n\n if (argument_front == '-') {\n auto option = &argument[1];\n if (option[0] == '\\0') {\n fputs(\"Please provide a valid option\\n\", stderr);\n }\n\n if (option[0] == '-') {\n option++;\n }\n\n if (strcmp(option, \"dont-print-warnings\") == 0) {\n options.ignore_warnings = true;\n } else if (strcmp(option, \"r\") == 0) {\n if (index + 1 != argc) {\n if (strcmp(argv[index + 1], \"once\") == 0) {\n index++;\n } else if (strcmp(argv[index + 1], \"all\") == 0) {\n options.recurse_subdirectories_at_path = true;\n index++;\n }\n }\n } else {\n fprintf(stderr, \"Unrecognized argument: %s\\n\", argument);\n return 1;\n }\n\n continue;\n }\n\n auto path = misc::path_with_current_directory(argv[index]);\n\n struct stat sbuf;\n if (stat(path.c_str(), &sbuf) != 0) {\n if (index == argc - 1) {\n fprintf(stderr, \"Failed to retrieve information on file at provided path, failing with error: %s\\n\", strerror(errno));\n } else {\n fprintf(stderr, \"Failed to retrieve information on file (at path %s), failing with error: %s\\n\", path.c_str(), strerror(errno));\n }\n\n return 1;\n }\n\n if (!S_ISDIR(sbuf.st_mode)) {\n if (index == argc - 1) {\n fputs(\"Object at provided path is not a directory\\n\", stderr);\n } else {\n fprintf(stderr, \"Object (at path %s) is not a directory\\n\", path.c_str());\n }\n\n return 1;\n }\n\n paths.emplace_back(options, std::move(path));\n options.clear();\n }\n\n if (paths.empty()) {\n fputs(\"No directories have been provided to recurse in\\n\", stderr);\n return 1;\n }\n\n const auto &back = paths.back();\n for (const auto &pair : paths) {\n const auto &options = pair.first;\n const auto &path = pair.second;\n\n auto recurse_options = misc::recurse::options();\n if (!options.ignore_warnings) {\n recurse_options.print_warnings = true;\n }\n\n if (options.recurse_subdirectories_at_path) {\n recurse_options.recurse_subdirectories = true;\n }\n\n auto filetypes = misc::recurse::filetypes();\n filetypes.dynamic_library = true;\n\n const auto recursion_result = misc::recurse::macho_files(path.c_str(), filetypes, recurse_options, [](const macho::file &file, const std::string &path) {\n fprintf(stderr, \"%s\\n\", path.c_str());\n return true;\n });\n\n switch (recursion_result) {\n case misc::recurse::operation_result::ok:\n break;\n\n case misc::recurse::operation_result::failed_to_open_directory:\n if (paths.size() != 1) {\n fprintf(stderr, \"Failed to open directory (at path %s), failing with error: %s\\n\", path.c_str(), strerror(errno));\n } else {\n fprintf(stderr, \"Failed to open directory at provided path, failing with error: %s\\n\", strerror(errno));\n }\n\n break;\n\n case misc::recurse::operation_result::found_no_matching_files:\n if (options.recurse_subdirectories_at_path) {\n if (paths.size() != 1) {\n fprintf(stderr, \"Found no mach-o dynamic library files while recursing through directory and its sub-directories at path: %s\\n\", path.c_str());\n } else {\n fputs(\"Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\\n\", stderr);\n }\n } else {\n if (paths.size() != 1) {\n fprintf(stderr, \"Found no mach-o dynamic library files while recursing through directory at path: %s\\n\", path.c_str());\n } else {\n fputs(\"Found no mach-o dynamic library files while recursing through directory at provided path\\n\", stderr);\n }\n }\n\n break;\n\n default:\n break;\n }\n\n \/\/ Print a newline between each pair\n if (pair != back) {\n fputc('\\n', stdout);\n }\n }\n } else {\n auto path = misc::retrieve_current_directory();\n auto recurse_options = misc::recurse::options();\n\n recurse_options.print_warnings = true;\n recurse_options.recurse_subdirectories = true;\n\n auto filetypes = misc::recurse::filetypes();\n filetypes.dynamic_library = true;\n\n const auto recursion_result = misc::recurse::macho_files(path, filetypes, recurse_options, [](const macho::file &file, const std::string &path) {\n fprintf(stderr, \"%s\\n\", path.c_str());\n return true;\n });\n\n switch (recursion_result) {\n case misc::recurse::operation_result::ok:\n break;\n\n case misc::recurse::operation_result::failed_to_open_directory:\n fprintf(stderr, \"Failed to open directory at current-directory, failing with error: %s\\n\", strerror(errno));\n break;\n\n case misc::recurse::operation_result::found_no_matching_files:\n fputs(\"Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\\n\", stderr);\n break;\n\n default:\n break;\n }\n }\n\n return 0;\n } else if (strcmp(option, \"list-objc-constraint\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n return 1;\n }\n\n fputs(\"none\\nretain_release\\nretain_release_or_gc\\nretain_release_for_simulator\\ngc\\n\", stderr);\n return 0;\n } else if (strcmp(option, \"list-platform\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n return 1;\n }\n\n main_utils::print_tbd_platforms();\n return 0;\n } else if (strcmp(option, \"list-recurse\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n return 1;\n }\n\n fputs(\"once, Recurse through all of a directory's files (default)\\n\", stdout);\n fputs(\"all, Recurse through all of a directory's files and sub-directories\\n\", stdout);\n\n return 0;\n } else if (strcmp(option, \"list-tbd-flags\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n return 1;\n }\n\n fputs(\"flat_namespace\\n\", stdout);\n fputs(\"not_app_extension_safe\\n\", stdout);\n return 0;\n } else if (strcmp(option, \"list-tbd-versions\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n return 1;\n }\n\n main_utils::print_tbd_versions();\n return 0;\n } else {\n return false;\n }\n\n return true;\n }\n}\nFix handling of return values and errors when parsing list arguments\/\/\n\/\/ src\/main_utils\/parse_list_argument.h\n\/\/ tbd\n\/\/\n\/\/ Created by inoahdev on 1\/26\/18.\n\/\/ Copyright © 2018 inoahdev. All rights reserved.\n\/\/\n\n#include \n\n#include \"..\/mach-o\/utils\/tbd.h\"\n\n#include \"..\/misc\/current_directory.h\"\n#include \"..\/misc\/recurse.h\"\n\n#include \"parse_list_argument.h\"\n\n#include \"tbd_print_field_information.h\"\n#include \"tbd_with_options.h\"\n\nnamespace main_utils {\n bool parse_list_argument(const char *argument, int &index, int argc, const char *argv[]) noexcept {\n auto option = &argument[1];\n if (option[0] == '-') {\n option++;\n }\n\n if (strcmp(option, \"list-architectures\") == 0) {\n if (index != 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself or with a path to a mach-o file\\n\", argument);\n exit(1);\n }\n\n \/\/ Two modes exist for --list-architectures, either list out the\n \/\/ architecture-info table, or list the architectures of a single\n \/\/ provided path to a mach-o file\n\n if (index == argc - 1) {\n auto architecture_info = macho::get_architecture_info_table();\n\n fputs(architecture_info->name, stdout);\n architecture_info++;\n\n while (architecture_info->name != nullptr) {\n fprintf(stdout, \", %s\", architecture_info->name);\n architecture_info++;\n }\n } else {\n index++;\n\n \/\/ Don't allow other arguments\n \/\/ to --list-architectures\n\n if (index + 2 <= argc) {\n fprintf(stderr, \"Unrecognized argument: %s\\n\", argv[index + 1]);\n exit(1);\n }\n\n auto file = macho::file();\n auto path = misc::path_with_current_directory(argv[index]);\n\n struct stat sbuf;\n if (stat(path.c_str(), &sbuf) != 0) {\n fprintf(stderr, \"Failed to retrieve information on object at provided path, failing with error: %s\\n\", strerror(errno));\n exit(1);\n }\n\n if (!S_ISREG(sbuf.st_mode)) {\n fputs(\"Object at provided path is not a regular file\\n\", stderr);\n exit(1);\n }\n\n switch (file.open(path.c_str())) {\n case macho::file::open_result::ok:\n break;\n\n case macho::file::open_result::not_a_macho:\n fputs(\"File at provided path is not a mach-o\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::invalid_macho:\n fputs(\"File at provided path is an invalid mach-o\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::failed_to_open_stream:\n fprintf(stderr, \"Failed to open stream for file at provided path, failing with error: %s\\n\", strerror(errno));\n exit(1);\n\n case macho::file::open_result::failed_to_retrieve_information:\n fprintf(stderr, \"Failed to retrieve information on object at provided path, failing with error: %s\\n\", strerror(errno));\n exit(1);\n\n case macho::file::open_result::stream_seek_error:\n case macho::file::open_result::stream_read_error:\n fputs(\"Encountered an error while parsing file at provided path\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::zero_containers:\n fputs(\"Mach-o file at provided path has zero architectures\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::too_many_containers:\n fputs(\"Mach-o file at provided path has too many architectures for its file-size\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::containers_goes_past_end_of_file:\n fputs(\"Mach-o file at provided path's architectures goes past end of file\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::overlapping_containers:\n fputs(\"Mach-o file at provided path has overlapping architectures\\n\", stderr);\n exit(1);\n\n case macho::file::open_result::invalid_container:\n fputs(\"Mach-o file at provided path has an invalid architecture\\n\", stderr);\n exit(1);\n }\n\n \/\/ Store architecture names in a vector before printing\n \/\/ so we can handle any errors encountered first\n\n auto cndex = 0;\n auto names = std::vector();\n\n for (const auto &container : file.containers) {\n const auto container_subtype = macho::subtype_from_cputype(macho::cputype(container.header.cputype), container.header.cpusubtype);\n if (container_subtype == macho::subtype::none) {\n fprintf(stderr, \"Unrecognized cpu-subtype for architecture at index %d\\n\", cndex);\n exit(1);\n }\n\n const auto architecture_info = macho::architecture_info_from_cputype(macho::cputype(container.header.cputype), container_subtype);\n if (!architecture_info) {\n fprintf(stderr, \"Unrecognized cputype information for architecture at index %d\\n\", cndex);\n exit(1);\n }\n\n cndex++;\n }\n\n fputs(names.front(), stdout);\n for (auto iter = names.cbegin() + 1; iter != names.cend(); iter++) {\n fprintf(stdout, \", %s\", *iter);\n }\n }\n\n fputc('\\n', stdout);\n } else if (strcmp(option, \"list-macho-dynamic-libraries\") == 0) {\n if (index != 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself or with a path to a mach-o file\\n\", argument);\n exit(1);\n }\n\n \/\/ Two different modes exist for --list-macho-dynamic-libraries;\n \/\/ either recurse current-directory with default options, or\n \/\/ recurse provided director(ies) with provided options\n\n index++;\n if (index != argc) {\n auto paths = std::vector>();\n struct main_utils::tbd_with_options::options options;\n\n options.recurse_directories_at_path = true;\n\n for (; index != argc; index++) {\n const auto &argument = argv[index];\n const auto &argument_front = argument[0];\n\n if (argument_front == '-') {\n auto option = &argument[1];\n if (option[0] == '\\0') {\n fputs(\"Please provide a valid option\\n\", stderr);\n }\n\n if (option[0] == '-') {\n option++;\n }\n\n if (strcmp(option, \"dont-print-warnings\") == 0) {\n options.ignore_warnings = true;\n } else if (strcmp(option, \"r\") == 0) {\n if (index + 1 != argc) {\n if (strcmp(argv[index + 1], \"once\") == 0) {\n index++;\n } else if (strcmp(argv[index + 1], \"all\") == 0) {\n options.recurse_subdirectories_at_path = true;\n index++;\n }\n }\n } else {\n fprintf(stderr, \"Unrecognized argument: %s\\n\", argument);\n exit(1);\n }\n\n continue;\n }\n\n auto path = misc::path_with_current_directory(argv[index]);\n\n struct stat sbuf;\n if (stat(path.c_str(), &sbuf) != 0) {\n if (index == argc - 1) {\n fprintf(stderr, \"Failed to retrieve information on file at provided path, failing with error: %s\\n\", strerror(errno));\n } else {\n fprintf(stderr, \"Failed to retrieve information on file (at path %s), failing with error: %s\\n\", path.c_str(), strerror(errno));\n }\n\n exit(1);\n }\n\n if (!S_ISDIR(sbuf.st_mode)) {\n if (index == argc - 1) {\n fputs(\"Object at provided path is not a directory\\n\", stderr);\n } else {\n fprintf(stderr, \"Object (at path %s) is not a directory\\n\", path.c_str());\n }\n\n exit(1);\n }\n\n paths.emplace_back(options, std::move(path));\n options.clear();\n }\n\n if (paths.empty()) {\n fputs(\"No directories have been provided to recurse in\\n\", stderr);\n exit(1);\n }\n\n const auto &back = paths.back();\n for (const auto &pair : paths) {\n const auto &options = pair.first;\n const auto &path = pair.second;\n\n auto recurse_options = misc::recurse::options();\n if (!options.ignore_warnings) {\n recurse_options.print_warnings = true;\n }\n\n if (options.recurse_subdirectories_at_path) {\n recurse_options.recurse_subdirectories = true;\n }\n\n auto filetypes = misc::recurse::filetypes();\n filetypes.dynamic_library = true;\n\n const auto recursion_result = misc::recurse::macho_files(path.c_str(), filetypes, recurse_options, [](const macho::file &file, const std::string &path) {\n fprintf(stderr, \"%s\\n\", path.c_str());\n return true;\n });\n\n switch (recursion_result) {\n case misc::recurse::operation_result::ok:\n break;\n\n case misc::recurse::operation_result::failed_to_open_directory:\n if (paths.size() != 1) {\n fprintf(stderr, \"Failed to open directory (at path %s), failing with error: %s\\n\", path.c_str(), strerror(errno));\n } else {\n fprintf(stderr, \"Failed to open directory at provided path, failing with error: %s\\n\", strerror(errno));\n }\n\n break;\n\n case misc::recurse::operation_result::found_no_matching_files:\n if (options.recurse_subdirectories_at_path) {\n if (paths.size() != 1) {\n fprintf(stderr, \"Found no mach-o dynamic library files while recursing through directory and its sub-directories at path: %s\\n\", path.c_str());\n } else {\n fputs(\"Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\\n\", stderr);\n }\n } else {\n if (paths.size() != 1) {\n fprintf(stderr, \"Found no mach-o dynamic library files while recursing through directory at path: %s\\n\", path.c_str());\n } else {\n fputs(\"Found no mach-o dynamic library files while recursing through directory at provided path\\n\", stderr);\n }\n }\n\n break;\n\n default:\n break;\n }\n\n \/\/ Print a newline between each pair\n if (pair != back) {\n fputc('\\n', stdout);\n }\n }\n } else {\n auto path = misc::retrieve_current_directory();\n auto recurse_options = misc::recurse::options();\n\n recurse_options.print_warnings = true;\n recurse_options.recurse_subdirectories = true;\n\n auto filetypes = misc::recurse::filetypes();\n filetypes.dynamic_library = true;\n\n const auto recursion_result = misc::recurse::macho_files(path, filetypes, recurse_options, [](const macho::file &file, const std::string &path) {\n fprintf(stderr, \"%s\\n\", path.c_str());\n return true;\n });\n\n switch (recursion_result) {\n case misc::recurse::operation_result::ok:\n break;\n\n case misc::recurse::operation_result::failed_to_open_directory:\n fprintf(stderr, \"Failed to open directory at current-directory, failing with error: %s\\n\", strerror(errno));\n break;\n\n case misc::recurse::operation_result::found_no_matching_files:\n fputs(\"Found no mach-o dynamic library files while recursing through directory and its sub-directories at provided path\\n\", stderr);\n break;\n\n default:\n break;\n }\n }\n } else if (strcmp(option, \"list-objc-constraint\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n exit(1);\n }\n\n fputs(\"none\\nretain_release\\nretain_release_or_gc\\nretain_release_for_simulator\\ngc\\n\", stderr);\n } else if (strcmp(option, \"list-platform\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n exit(1);\n }\n\n main_utils::print_tbd_platforms();\n } else if (strcmp(option, \"list-recurse\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n exit(1);\n }\n\n fputs(\"once, Recurse through all of a directory's files (default)\\n\", stdout);\n fputs(\"all, Recurse through all of a directory's files and sub-directories\\n\", stdout);\n } else if (strcmp(option, \"list-tbd-flags\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n exit(1);\n }\n\n fputs(\"flat_namespace\\n\", stdout);\n fputs(\"not_app_extension_safe\\n\", stdout);\n } else if (strcmp(option, \"list-tbd-versions\") == 0) {\n if (index != 1 || index != argc - 1) {\n fprintf(stderr, \"Option (%s) needs to be run by itself\\n\", argument);\n exit(1);\n }\n\n main_utils::print_tbd_versions();\n } else {\n return false;\n }\n\n return true;\n }\n}\n<|endoftext|>"} {"text":"#include \"yuyvtoyuv420.h\"\n\nYUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats,\n std::shared_ptr hwResources) :\n Filter(id, \"YUYVtoYUV420\", stats, hwResources, YUYVVIDEO, YUV420VIDEO)\n{}\n\n\nvoid YUYVtoYUV420::process()\n{\n std::unique_ptr input = getInput();\n\n while(input)\n {\n uint32_t finalDataSize = input->width*input->height*2;\n std::unique_ptr yuyv_frame(new uchar[finalDataSize]);\n\n yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height);\n\n input->type = YUYVVIDEO;\n input->data = std::move(yuyv_frame);\n input->data_size = finalDataSize;\n sendOutput(std::move(input));\n\n input = getInput();\n }\n}\n\n\nvoid YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output,\n uint16_t width, uint16_t height)\n{\n\n}\nfeature(Processing): Convert luma pixels from YUYV to YUV420#include \"yuyvtoyuv420.h\"\n\nYUYVtoYUV420::YUYVtoYUV420(QString id, StatisticsInterface *stats,\n std::shared_ptr hwResources) :\n Filter(id, \"YUYVtoYUV420\", stats, hwResources, YUYVVIDEO, YUV420VIDEO)\n{}\n\n\nvoid YUYVtoYUV420::process()\n{\n std::unique_ptr input = getInput();\n\n while(input)\n {\n uint32_t finalDataSize = input->width*input->height + input->width*input->height\/2;\n std::unique_ptr yuyv_frame(new uchar[finalDataSize]);\n\n yuyv2yuv420_cpu(input->data.get(), yuyv_frame.get(), input->width, input->height);\n\n input->type = YUYVVIDEO;\n input->data = std::move(yuyv_frame);\n input->data_size = finalDataSize;\n sendOutput(std::move(input));\n\n input = getInput();\n }\n}\n\n\nvoid YUYVtoYUV420::yuyv2yuv420_cpu(uint8_t* input, uint8_t* output,\n uint16_t width, uint16_t height)\n{\n \/\/ Luma pixels\n for(int i = 0; i < width*height; i += 2)\n {\n output[i] = input[i*2];\n output[i + 1] = input[i*2 + 2];\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \"dialogwindow.h\"\n#include \"editorgui.h\"\n#include \"helper.h\"\n#include \"editorwidget.h\"\n#include \"namedobject.h\"\n#include \"widgetfactory.h\"\n\nDialogWindow::DialogWindow(EditorGUI *screen, nanogui::Theme *theme) : nanogui::Window(screen), gui(screen) {\n\tusing namespace nanogui;\n\tsetTheme(theme);\n\tsetFixedSize(Vector2i(screen->width()\/2, screen->height()\/2));\n\tsetSize(Vector2i(180,240));\n\tsetPosition(Vector2i(screen->width()\/4, screen->height()\/4));\n\tsetTitle(\"Dialog\");\n\tsetVisible(true);\n}\n\nvoid DialogWindow::clear() {\n\tint n = childCount();\n\tint idx = 0;\n\twhile (n--) {\n\t\tNamedObject *no = dynamic_cast(childAt(idx));\n\t\tEditorWidget *ew = dynamic_cast(no);\n\t\tif (ew && ew->getRemote()) {\n\t\t\tew->getRemote()->unlink(ew);\n\t\t}\n\t\tremoveChild(idx);\n\t}\n}\n\nvoid DialogWindow::setStructure( Structure *s) {\n\tif (!s) return;\n\n\tStructureClass *sc = findClass(s->getKind());\n\tif (!sc) {\n\t\tstd::cerr << \"no structure class '\" << s->getKind() << \"' found\\n\";\n\t\treturn;\n\t}\n\tif ( s->getKind() != \"SCREEN\" && (!sc || sc->getBase() != \"SCREEN\") ) return;\n\tclear();\n\tloadStructure(s);\n\tcurrent_structure = s;\n\tgui->performLayout();\n}\n\nvoid DialogWindow::loadStructure(Structure *s) {\n\tStructureClass *sc = findClass(s->getKind());\n\tif (sc && (s->getKind() == \"SCREEN\" || sc->getBase() == \"SCREEN\") ) {\n\t\tif (sc && !s->getStructureDefinition())\n\t\t\ts->setStructureDefinition(sc);\n\t\tint pnum = 0;\n\t\tnanogui::Vector2i offset;\n\t\tnanogui::Vector2i frame_size;\n\t\tfor (auto param : sc->getLocals()) {\n\t\t\t++pnum;\n\t\t\tStructure *element = param.machine;\n\t\t\tif (!element) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstd::string kind = element->getKind();\n\t\t\tif (kind == \"FRAME\") {\n\t\t\t\tauto properties = element->getProperties();\n\t\t\t\tValue vx = properties.find(\"pos_x\");\n\t\t\t\tValue vy = properties.find(\"pos_y\");\n\t\t\t\tValue w = properties.find(\"width\");\n\t\t\t\tValue h = properties.find(\"height\");\n\t\t\t\tlong x, y;\n\t\t\t\tif (vx.asInteger(x) && vy.asInteger(y)) {\n\t\t\t\t\toffset = nanogui::Vector2i(x,y);\n\t\t\t\t}\n\t\t\t\tif (w.asInteger(x) && h.asInteger(y)) {\n\t\t\t\t\tframe_size = nanogui::Vector2i(x, y);\n\t\t\t\t\tsetFixedSize(frame_size);\n\t\t\t\t\tsetSize(frame_size);\n\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tpnum = 0;\n\t\tfor (auto param : sc->getLocals()) {\n\t\t\t++pnum;\n\t\t\tStructure *element = param.machine;\n\t\t\tif (!element) {\n\t\t\t\tstd::cout << \"Warning: no structure for parameter \" << pnum << \"of \" << s->getName() << \"\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstd::string kind = element->getKind();\n\t\t\tStructureClass *element_class = findClass(kind);\n\n\t\t\tWidgetParams params(s, this, element, gui, offset);\n\n\t\t\tif (kind == \"LABEL\") {\n\t\t\t\tcreateLabel(params);\n\t\t\t}\n\t\t\tif (kind == \"IMAGE\") {\n\t\t\t\tcreateImage(params);\n\t\t\t}\n\t\t\tif (kind == \"PROGRESS\") {\n\t\t\t\tcreateProgress(params);\n\t\t\t}\n\t\t\tif (kind == \"TEXT\") {\n\t\t\t\tcreateText(params);\n\t\t\t}\n\t\t\telse if (kind == \"PLOT\" || (element_class &&element_class->getBase() == \"PLOT\") ) {\n\t\t\t\tcreatePlot(params);\n\t\t\t}\n\t\t\telse if (kind == \"BUTTON\" || kind == \"INDICATOR\") {\n\t\t\t\tcreateButton(params);\n\t\t\t}\n\t\t}\n\t}\n}\n\nautomatically centre dialogs within the current window#include \n\n#include \n#include \n\n#include \"dialogwindow.h\"\n#include \"editorgui.h\"\n#include \"helper.h\"\n#include \"editorwidget.h\"\n#include \"namedobject.h\"\n#include \"widgetfactory.h\"\n\nDialogWindow::DialogWindow(EditorGUI *screen, nanogui::Theme *theme) : nanogui::Window(screen), gui(screen) {\n\tusing namespace nanogui;\n\tsetTheme(theme);\n\tsetFixedSize(Vector2i(gui->width()\/2, gui->height()\/2));\n\tsetSize(Vector2i(180,240));\n\tsetPosition(Vector2i(gui->width()\/4, gui->height()\/4));\n\tsetTitle(\"Dialog\");\n\tsetVisible(true);\n}\n\nvoid DialogWindow::clear() {\n\tint n = childCount();\n\tint idx = 0;\n\twhile (n--) {\n\t\tNamedObject *no = dynamic_cast(childAt(idx));\n\t\tEditorWidget *ew = dynamic_cast(no);\n\t\tif (ew && ew->getRemote()) {\n\t\t\tew->getRemote()->unlink(ew);\n\t\t}\n\t\tremoveChild(idx);\n\t}\n}\n\nvoid DialogWindow::setStructure( Structure *s) {\n\tif (!s) return;\n\n\tStructureClass *sc = findClass(s->getKind());\n\tif (!sc) {\n\t\tstd::cerr << \"no structure class '\" << s->getKind() << \"' found\\n\";\n\t\treturn;\n\t}\n\tif ( s->getKind() != \"SCREEN\" && (!sc || sc->getBase() != \"SCREEN\") ) return;\n\tclear();\n\tloadStructure(s);\n\tcurrent_structure = s;\n\tgui->performLayout();\n}\n\nvoid DialogWindow::loadStructure(Structure *s) {\n\tStructureClass *sc = findClass(s->getKind());\n\tif (sc && (s->getKind() == \"SCREEN\" || sc->getBase() == \"SCREEN\") ) {\n\t\tif (sc && !s->getStructureDefinition())\n\t\t\ts->setStructureDefinition(sc);\n\t\tint pnum = 0;\n\t\tnanogui::Vector2i offset;\n\t\tnanogui::Vector2i frame_size;\n\t\tfor (auto param : sc->getLocals()) {\n\t\t\t++pnum;\n\t\t\tStructure *element = param.machine;\n\t\t\tif (!element) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstd::string kind = element->getKind();\n\t\t\tif (kind == \"FRAME\") {\n\t\t\t\tauto properties = element->getProperties();\n\t\t\t\tValue vx = properties.find(\"pos_x\");\n\t\t\t\tValue vy = properties.find(\"pos_y\");\n\t\t\t\tValue w = properties.find(\"width\");\n\t\t\t\tValue h = properties.find(\"height\");\n\t\t\t\tlong x, y;\n\t\t\t\tif (vx.asInteger(x) && vy.asInteger(y)) {\n\t\t\t\t\toffset = nanogui::Vector2i(x,y);\n\t\t\t\t}\n\t\t\t\tif (w.asInteger(x) && h.asInteger(y)) {\n\t\t\t\t\tframe_size = nanogui::Vector2i(x, y);\n\t\t\t\t\tsetFixedSize(frame_size);\n\t\t\t\t\tsetSize(frame_size);\n\t\t\t\t\tauto pos = nanogui::Vector2i((gui->width() - frame_size.x())\/2, (gui->height() - frame_size.y())\/2);\n\t\t\t\t\tsetPosition(pos);\n\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tpnum = 0;\n\t\tfor (auto param : sc->getLocals()) {\n\t\t\t++pnum;\n\t\t\tStructure *element = param.machine;\n\t\t\tif (!element) {\n\t\t\t\tstd::cout << \"Warning: no structure for parameter \" << pnum << \"of \" << s->getName() << \"\\n\";\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tstd::string kind = element->getKind();\n\t\t\tStructureClass *element_class = findClass(kind);\n\n\t\t\tWidgetParams params(s, this, element, gui, offset);\n\n\t\t\tif (kind == \"LABEL\") {\n\t\t\t\tcreateLabel(params);\n\t\t\t}\n\t\t\tif (kind == \"IMAGE\") {\n\t\t\t\tcreateImage(params);\n\t\t\t}\n\t\t\tif (kind == \"PROGRESS\") {\n\t\t\t\tcreateProgress(params);\n\t\t\t}\n\t\t\tif (kind == \"TEXT\") {\n\t\t\t\tcreateText(params);\n\t\t\t}\n\t\t\telse if (kind == \"PLOT\" || (element_class &&element_class->getBase() == \"PLOT\") ) {\n\t\t\t\tcreatePlot(params);\n\t\t\t}\n\t\t\telse if (kind == \"BUTTON\" || kind == \"INDICATOR\") {\n\t\t\t\tcreateButton(params);\n\t\t\t}\n\t\t}\n\t}\n}\n\n<|endoftext|>"} {"text":"\/**\n * @file lars_main.cpp\n * @author Nishant Mehta\n *\n * Executable for LARS.\n *\/\n#include \n\n#include \"lars.hpp\"\n\nPROGRAM_INFO(\"LARS\", \"An implementation of LARS: Least Angle Regression \"\n \"(Stagewise\/laSso). This is a stage-wise homotopy-based algorithm for \"\n \"L1-regularized linear regression (LASSO) and L1+L2-regularized linear \"\n \"regression (Elastic Net).\\n\"\n \"\\n\"\n \"Let X be a matrix where each row is a point and each column is a \"\n \"dimension, and let y be a vector of targets.\\n\"\n \"\\n\"\n \"The Elastic Net problem is to solve\\n\\n\"\n \" min_beta 0.5 || X * beta - y ||_2^2 + lambda_1 ||beta||_1 +\\n\"\n \" 0.5 lambda_2 ||beta||_2^2\\n\\n\"\n \"If lambda_1 > 0 and lambda_2 = 0, the problem is the LASSO.\\n\"\n \"If lambda_1 > 0 and lambda_2 > 0, the problem is the Elastic Net.\\n\"\n \"If lambda_1 = 0 and lambda_2 > 0, the problem is ridge regression.\\n\"\n \"If lambda_1 = 0 and lambda_2 = 0, the problem is unregularized linear \"\n \"regression.\\n\"\n \"\\n\"\n \"For efficiency reasons, it is not recommended to use this algorithm with \"\n \"lambda_1 = 0. In that case, use the 'linear_regression' program, which \"\n \"implements both unregularized linear regression and ridge regression.\\n\");\n\nPARAM_STRING_REQ(\"input_file\", \"File containing covariates (X).\",\n \"i\");\nPARAM_STRING_REQ(\"responses_file\", \"File containing y \"\n \"(responses\/observations).\", \"r\");\n\nPARAM_STRING(\"output_file\", \"File to save beta (linear estimator) to.\", \"o\",\n \"output.csv\");\n\nPARAM_DOUBLE(\"lambda1\", \"Regularization parameter for l1-norm penalty.\", \"l\",\n 0);\nPARAM_DOUBLE(\"lambda2\", \"Regularization parameter for l2-norm penalty.\", \"L\",\n 0);\nPARAM_FLAG(\"use_cholesky\", \"Use Cholesky decomposition during computation \"\n \"rather than explicitly computing the full Gram matrix.\", \"c\");\n\nusing namespace arma;\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::regression;\n\nint main(int argc, char* argv[])\n{\n \/\/ Handle parameters,\n CLI::ParseCommandLine(argc, argv);\n\n double lambda1 = CLI::GetParam(\"lambda1\");\n double lambda2 = CLI::GetParam(\"lambda2\");\n bool useCholesky = CLI::HasParam(\"use_cholesky\");\n\n \/\/ Load covariates. We can avoid LARS transposing our data by choosing to not\n \/\/ transpose this data.\n const string matXFilename = CLI::GetParam(\"input_file\");\n mat matX;\n data::Load(matXFilename, matX, true, false);\n\n \/\/ Load responses. The responses should be a one-dimensional vector, and it\n \/\/ seems more likely that these will be stored with one response per line (one\n \/\/ per row). So we should not transpose upon loading.\n const string yFilename = CLI::GetParam(\"responses_file\");\n mat matY; \/\/ Will be a vector.\n data::Load(yFilename, matY, true, false);\n\n \/\/ Make sure y is oriented the right way.\n if (matY.n_rows == 1)\n matY = trans(matY);\n if (matY.n_cols > 1)\n Log::Fatal << \"Only one column or row allowed in responses file!\" << endl;\n\n if (matY.n_elem != matX.n_rows)\n Log::Fatal << \"Number of responses must be equal to number of rows of X!\"\n << endl;\n\n \/\/ Do LARS.\n LARS lars(useCholesky, lambda1, lambda2);\n vec beta;\n lars.Regress(matX, matY.unsafe_col(0), beta, false \/* do not transpose *\/);\n\n const string betaFilename = CLI::GetParam(\"output_file\");\n beta.save(betaFilename, raw_ascii);\n}\nAdd option to predict values on test points.\/**\n * @file lars_main.cpp\n * @author Nishant Mehta\n *\n * Executable for LARS.\n *\/\n#include \n\n#include \"lars.hpp\"\n\nPROGRAM_INFO(\"LARS\", \"An implementation of LARS: Least Angle Regression \"\n \"(Stagewise\/laSso). This is a stage-wise homotopy-based algorithm for \"\n \"L1-regularized linear regression (LASSO) and L1+L2-regularized linear \"\n \"regression (Elastic Net).\\n\"\n \"\\n\"\n \"Let X be a matrix where each row is a point and each column is a \"\n \"dimension, and let y be a vector of targets.\\n\"\n \"\\n\"\n \"The Elastic Net problem is to solve\\n\\n\"\n \" min_beta 0.5 || X * beta - y ||_2^2 + lambda_1 ||beta||_1 +\\n\"\n \" 0.5 lambda_2 ||beta||_2^2\\n\\n\"\n \"If lambda_1 > 0 and lambda_2 = 0, the problem is the LASSO.\\n\"\n \"If lambda_1 > 0 and lambda_2 > 0, the problem is the Elastic Net.\\n\"\n \"If lambda_1 = 0 and lambda_2 > 0, the problem is ridge regression.\\n\"\n \"If lambda_1 = 0 and lambda_2 = 0, the problem is unregularized linear \"\n \"regression.\\n\"\n \"\\n\"\n \"For efficiency reasons, it is not recommended to use this algorithm with \"\n \"lambda_1 = 0. In that case, use the 'linear_regression' program, which \"\n \"implements both unregularized linear regression and ridge regression.\\n\");\n\nPARAM_STRING_REQ(\"input_file\", \"File containing covariates (X).\",\n \"i\");\nPARAM_STRING_REQ(\"responses_file\", \"File containing y \"\n \"(responses\/observations).\", \"r\");\n\nPARAM_STRING(\"output_file\", \"File to save beta (linear estimator) to.\", \"o\",\n \"output.csv\");\n\nPARAM_STRING(\"test_file\", \"File containing points to regress on (test points).\",\n \"t\", \"\");\nPARAM_STRING(\"output_predictions\", \"If --test_file is specified, this file is \"\n \"where the predicted responses will be saved.\", \"p\", \"predictions.csv\");\n\nPARAM_DOUBLE(\"lambda1\", \"Regularization parameter for l1-norm penalty.\", \"l\",\n 0);\nPARAM_DOUBLE(\"lambda2\", \"Regularization parameter for l2-norm penalty.\", \"L\",\n 0);\nPARAM_FLAG(\"use_cholesky\", \"Use Cholesky decomposition during computation \"\n \"rather than explicitly computing the full Gram matrix.\", \"c\");\n\nusing namespace arma;\nusing namespace std;\nusing namespace mlpack;\nusing namespace mlpack::regression;\n\nint main(int argc, char* argv[])\n{\n \/\/ Handle parameters,\n CLI::ParseCommandLine(argc, argv);\n\n double lambda1 = CLI::GetParam(\"lambda1\");\n double lambda2 = CLI::GetParam(\"lambda2\");\n bool useCholesky = CLI::HasParam(\"use_cholesky\");\n\n \/\/ Load covariates. We can avoid LARS transposing our data by choosing to not\n \/\/ transpose this data.\n const string matXFilename = CLI::GetParam(\"input_file\");\n mat matX;\n data::Load(matXFilename, matX, true, false);\n\n \/\/ Load responses. The responses should be a one-dimensional vector, and it\n \/\/ seems more likely that these will be stored with one response per line (one\n \/\/ per row). So we should not transpose upon loading.\n const string yFilename = CLI::GetParam(\"responses_file\");\n mat matY; \/\/ Will be a vector.\n data::Load(yFilename, matY, true, false);\n\n \/\/ Make sure y is oriented the right way.\n if (matY.n_rows == 1)\n matY = trans(matY);\n if (matY.n_cols > 1)\n Log::Fatal << \"Only one column or row allowed in responses file!\" << endl;\n\n if (matY.n_elem != matX.n_rows)\n Log::Fatal << \"Number of responses must be equal to number of rows of X!\"\n << endl;\n\n \/\/ Do LARS.\n LARS lars(useCholesky, lambda1, lambda2);\n vec beta;\n lars.Regress(matX, matY.unsafe_col(0), beta, false \/* do not transpose *\/);\n\n const string betaFilename = CLI::GetParam(\"output_file\");\n beta.save(betaFilename, raw_ascii);\n\n if (CLI::HasParam(\"test_file\"))\n {\n Log::Info << \"Regressing on test points.\" << endl;\n const string testFile = CLI::GetParam(\"test_file\");\n const string outputPredictionsFile =\n CLI::GetParam(\"output_predictions\");\n\n \/\/ Load test points.\n mat testPoints;\n data::Load(testFile, testPoints, true, false);\n\n arma::vec predictions;\n lars.Predict(testPoints.t(), predictions, false);\n\n \/\/ Save test predictions. One per line, so, we need a rowvec.\n arma::rowvec predToSave = predictions.t();\n data::Save(outputPredictionsFile, predToSave);\n }\n}\n<|endoftext|>"} {"text":"\/\/ sdl_main.cpp\n\n#ifdef _WIN32\n# define WINDOWS_LEAN_AND_MEAN\n# define NOMINMAX\n# include \n#endif\n\n#include \n\n#include \n#include \n#include \n#undef main\n\n#include \n\n#ifdef USE_ANTTWEAKBAR\n# include \n#endif\n\n#include \n#include \n#include \n\n#include \"ShaderFunctions.h\"\n#include \"Timer.h\"\n\nTimer g_timer;\nint winw = 800;\nint winh = 600;\n\nstruct Shadertoy {\n GLuint prog;\n GLint uloc_iResolution;\n GLint uloc_iGlobalTime;\n};\n\nShadertoy g_toy;\n\n\nvoid PollEvents()\n{\n SDL_Event event;\n while (SDL_PollEvent(&event))\n {\n switch(event.type)\n {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n break;\n\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n break;\n\n case SDL_MOUSEMOTION:\n break;\n\n case SDL_MOUSEWHEEL:\n break;\n\n case SDL_WINDOWEVENT:\n break;\n\n case SDL_QUIT:\n exit(0);\n break;\n\n default:\n break;\n }\n }\n}\n\nvoid display()\n{\n glUseProgram(g_toy.prog);\n if (g_toy.uloc_iResolution > -1) glUniform3f(g_toy.uloc_iResolution, (float)winw, (float)winh, 1.f);\n if (g_toy.uloc_iGlobalTime > -1) glUniform1f(g_toy.uloc_iGlobalTime, g_timer.seconds());\n glRecti(-1,-1,1,1);\n}\n\n\nint main(void)\n{\n \/\/\/@todo cmd line aargs\n\n if (SDL_Init(SDL_INIT_EVERYTHING) < 0)\n {\n return false;\n }\n\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n \n int winw = 800;\n int winh = 600;\n\n SDL_Window* pWindow = SDL_CreateWindow(\n \"kinderegg\",\n 100,100,\n winw, winh,\n SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);\n\n \/\/ thank you http:\/\/www.brandonfoltz.com\/2013\/12\/example-using-opengl-3-0-with-sdl2-and-glew\/\n SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);\n if (glContext == NULL)\n {\n printf(\"There was an error creating the OpenGL context!\\n\");\n return 0;\n }\n\n const unsigned char *version = glGetString(GL_VERSION);\n if (version == NULL) \n {\n printf(\"There was an error creating the OpenGL context!\\n\");\n return 1;\n }\n\n SDL_GL_MakeCurrent(pWindow, glContext);\n\n \/\/ Don't forget to initialize Glew, turn glewExperimental on to\n \/\/ avoid problems fetching function pointers...\n glewExperimental = GL_TRUE;\n const GLenum l_Result = glewInit();\n if (l_Result != GLEW_OK)\n {\n exit(EXIT_FAILURE);\n }\n\n g_toy.prog = makeShaderByName(\"basic\");\n g_toy.uloc_iResolution = glGetUniformLocation(g_toy.prog, \"iResolution\");\n g_toy.uloc_iGlobalTime = glGetUniformLocation(g_toy.prog, \"iGlobalTime\");\n\n int quit = 0;\n while (quit == 0)\n {\n PollEvents();\n display();\n SDL_GL_SwapWindow(pWindow);\n }\n\n SDL_GL_DeleteContext(glContext);\n SDL_DestroyWindow(pWindow);\n\n SDL_Quit();\n}\nRemove some extraneous includes.\/\/ sdl_main.cpp\n\n#ifdef _WIN32\n# define WINDOWS_LEAN_AND_MEAN\n# define NOMINMAX\n# include \n#endif\n\n#include \n#include \n#include \n#undef main\n\n#include \"ShaderFunctions.h\"\n#include \"Timer.h\"\n\nTimer g_timer;\nint winw = 800;\nint winh = 600;\n\nstruct Shadertoy {\n GLuint prog;\n GLint uloc_iResolution;\n GLint uloc_iGlobalTime;\n};\n\nShadertoy g_toy;\n\n\nvoid PollEvents()\n{\n SDL_Event event;\n while (SDL_PollEvent(&event))\n {\n switch(event.type)\n {\n case SDL_KEYDOWN:\n case SDL_KEYUP:\n break;\n\n case SDL_MOUSEBUTTONDOWN:\n case SDL_MOUSEBUTTONUP:\n break;\n\n case SDL_MOUSEMOTION:\n break;\n\n case SDL_MOUSEWHEEL:\n break;\n\n case SDL_WINDOWEVENT:\n break;\n\n case SDL_QUIT:\n exit(0);\n break;\n\n default:\n break;\n }\n }\n}\n\nvoid display()\n{\n glUseProgram(g_toy.prog);\n if (g_toy.uloc_iResolution > -1) glUniform3f(g_toy.uloc_iResolution, (float)winw, (float)winh, 1.f);\n if (g_toy.uloc_iGlobalTime > -1) glUniform1f(g_toy.uloc_iGlobalTime, g_timer.seconds());\n glRecti(-1,-1,1,1);\n}\n\n\nint main(void)\n{\n \/\/\/@todo cmd line aargs\n\n if (SDL_Init(SDL_INIT_EVERYTHING) < 0)\n {\n return false;\n }\n\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);\n SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);\n \n int winw = 800;\n int winh = 600;\n\n SDL_Window* pWindow = SDL_CreateWindow(\n \"kinderegg\",\n 100,100,\n winw, winh,\n SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);\n\n \/\/ thank you http:\/\/www.brandonfoltz.com\/2013\/12\/example-using-opengl-3-0-with-sdl2-and-glew\/\n SDL_GLContext glContext = SDL_GL_CreateContext(pWindow);\n if (glContext == NULL)\n {\n printf(\"There was an error creating the OpenGL context!\\n\");\n return 0;\n }\n\n const unsigned char *version = glGetString(GL_VERSION);\n if (version == NULL) \n {\n printf(\"There was an error creating the OpenGL context!\\n\");\n return 1;\n }\n\n SDL_GL_MakeCurrent(pWindow, glContext);\n\n \/\/ Don't forget to initialize Glew, turn glewExperimental on to\n \/\/ avoid problems fetching function pointers...\n glewExperimental = GL_TRUE;\n const GLenum l_Result = glewInit();\n if (l_Result != GLEW_OK)\n {\n exit(EXIT_FAILURE);\n }\n\n g_toy.prog = makeShaderByName(\"basic\");\n g_toy.uloc_iResolution = glGetUniformLocation(g_toy.prog, \"iResolution\");\n g_toy.uloc_iGlobalTime = glGetUniformLocation(g_toy.prog, \"iGlobalTime\");\n\n int quit = 0;\n while (quit == 0)\n {\n PollEvents();\n display();\n SDL_GL_SwapWindow(pWindow);\n }\n\n SDL_GL_DeleteContext(glContext);\n SDL_DestroyWindow(pWindow);\n\n SDL_Quit();\n}\n<|endoftext|>"} {"text":"\/*************************************************\n* Startup Self Tests Source File *\n* (C) 1999-2007 Jack Lloyd *\n*************************************************\/\n\n#include \n#include \n\nnamespace Botan {\n\nnamespace {\n\n\/*************************************************\n* Perform a Known Answer Test *\n*************************************************\/\nvoid do_kat(const std::string& in, const std::string& out,\n const std::string& algo_name, Filter* filter)\n {\n if(out.length())\n {\n Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);\n pipe.process_msg(in);\n\n if(out != pipe.read_all_as_string())\n throw Self_Test_Failure(\"FIPS-140 \" + algo_name + \" test\");\n }\n }\n\n\/*************************************************\n* Perform a KAT for a cipher *\n*************************************************\/\nvoid cipher_kat(const std::string& in, const std::string& out,\n const std::string& key, const std::string& iv,\n const std::string& cipher)\n {\n do_kat(in, out, cipher, get_cipher(cipher, key, iv, ENCRYPTION));\n do_kat(out, in, cipher, get_cipher(cipher, key, iv, DECRYPTION));\n }\n\n\/*************************************************\n* Perform a KAT for a cipher *\n*************************************************\/\nvoid cipher_kat(const std::string& cipher, const std::string& key,\n const std::string& iv, const std::string& in,\n const std::string& ecb_out, const std::string& cbc_out,\n const std::string& cfb_out, const std::string& ofb_out,\n const std::string& ctr_out)\n {\n if(!have_block_cipher(cipher))\n return;\n\n cipher_kat(in, ecb_out, key, \"\", cipher + \"\/ECB\");\n cipher_kat(in, cbc_out, key, iv, cipher + \"\/CBC\/NoPadding\");\n cipher_kat(in, cfb_out, key, iv, cipher + \"\/CFB\");\n cipher_kat(in, ofb_out, key, iv, cipher + \"\/OFB\");\n cipher_kat(in, ctr_out, key, iv, cipher + \"\/CTR-BE\");\n }\n\n\/*************************************************\n* Perform a KAT for a hash *\n*************************************************\/\nvoid hash_kat(const std::string& hash, const std::string& in,\n const std::string& out)\n {\n if(!have_hash(hash))\n return;\n do_kat(in, out, hash, new Hash_Filter(hash));\n }\n\n\/*************************************************\n* Perform a KAT for a MAC *\n*************************************************\/\nvoid mac_kat(const std::string& mac, const std::string& in,\n const std::string& out, const std::string& key)\n {\n if(!have_mac(mac))\n return;\n do_kat(in, out, mac, new MAC_Filter(mac, key));\n }\n\n}\n\n\/*************************************************\n* Perform FIPS 140 Self Tests *\n*************************************************\/\nbool passes_self_tests()\n {\n try {\n cipher_kat(\"DES\", \"0123456789ABCDEF\", \"1234567890ABCDEF\",\n \"4E6F77206973207468652074696D6520666F7220616C6C20\",\n \"3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53\",\n \"E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6\",\n \"F3096249C7F46E51A69E839B1A92F78403467133898EA622\",\n \"F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3\",\n \"F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75\");\n\n cipher_kat(\"TripleDES\",\n \"385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E\",\n \"C141B5FCCD28DC8A\",\n \"6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68\",\n \"64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4\",\n \"6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9\",\n \"E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B\",\n \"E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62\",\n \"E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371\");\n\n cipher_kat(\"AES\",\n \"2B7E151628AED2A6ABF7158809CF4F3C\",\n \"000102030405060708090A0B0C0D0E0F\",\n \"6BC1BEE22E409F96E93D7E117393172A\"\n \"AE2D8A571E03AC9C9EB76FAC45AF8E51\",\n \"3AD77BB40D7A3660A89ECAF32466EF97\"\n \"F5D3D58503B9699DE785895A96FDBAAF\",\n \"7649ABAC8119B246CEE98E9B12E9197D\"\n \"5086CB9B507219EE95DB113A917678B2\",\n \"3B3FD92EB72DAD20333449F8E83CFB4A\"\n \"C8A64537A0B3A93FCDE3CDAD9F1CE58B\",\n \"3B3FD92EB72DAD20333449F8E83CFB4A\"\n \"7789508D16918F03F53C52DAC54ED825\",\n \"3B3FD92EB72DAD20333449F8E83CFB4A\"\n \"010C041999E03F36448624483E582D0E\");\n\n hash_kat(\"SHA-1\", \"\", \"DA39A3EE5E6B4B0D3255BFEF95601890AFD80709\");\n hash_kat(\"SHA-1\", \"616263\", \"A9993E364706816ABA3E25717850C26C9CD0D89D\");\n hash_kat(\"SHA-1\",\n \"6162636462636465636465666465666765666768666768696768696A\"\n \"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071\",\n \"84983E441C3BD26EBAAE4AA1F95129E5E54670F1\");\n\n hash_kat(\"SHA-256\", \"\",\n \"E3B0C44298FC1C149AFBF4C8996FB924\"\n \"27AE41E4649B934CA495991B7852B855\");\n hash_kat(\"SHA-256\", \"616263\",\n \"BA7816BF8F01CFEA414140DE5DAE2223\"\n \"B00361A396177A9CB410FF61F20015AD\");\n hash_kat(\"SHA-256\",\n \"6162636462636465636465666465666765666768666768696768696A\"\n \"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071\",\n \"248D6A61D20638B8E5C026930C3E6039\"\n \"A33CE45964FF2167F6ECEDD419DB06C1\");\n\n mac_kat(\"HMAC(SHA-1)\", \"4869205468657265\",\n \"B617318655057264E28BC0B6FB378C8EF146BE00\",\n \"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B\");\n\n mac_kat(\"HMAC(SHA-256)\", \"4869205468657265\",\n \"198A607EB44BFBC69903A0F1CF2BBDC5\"\n \"BA0AA3F3D9AE3C1C7A3B1696A0B68CF7\",\n \"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B\"\n \"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B\");\n }\n catch(std::exception& e)\n {\n printf(\"%s\\n\", e.what());\n return false;\n }\n\n return true;\n }\n\n}\nRemove printf in catch block\/*************************************************\n* Startup Self Tests Source File *\n* (C) 1999-2007 Jack Lloyd *\n*************************************************\/\n\n#include \n#include \n\nnamespace Botan {\n\nnamespace {\n\n\/*************************************************\n* Perform a Known Answer Test *\n*************************************************\/\nvoid do_kat(const std::string& in, const std::string& out,\n const std::string& algo_name, Filter* filter)\n {\n if(out.length())\n {\n Pipe pipe(new Hex_Decoder, filter, new Hex_Encoder);\n pipe.process_msg(in);\n\n if(out != pipe.read_all_as_string())\n throw Self_Test_Failure(\"FIPS-140 \" + algo_name + \" test\");\n }\n }\n\n\/*************************************************\n* Perform a KAT for a cipher *\n*************************************************\/\nvoid cipher_kat(const std::string& in, const std::string& out,\n const std::string& key, const std::string& iv,\n const std::string& cipher)\n {\n do_kat(in, out, cipher, get_cipher(cipher, key, iv, ENCRYPTION));\n do_kat(out, in, cipher, get_cipher(cipher, key, iv, DECRYPTION));\n }\n\n\/*************************************************\n* Perform a KAT for a cipher *\n*************************************************\/\nvoid cipher_kat(const std::string& cipher, const std::string& key,\n const std::string& iv, const std::string& in,\n const std::string& ecb_out, const std::string& cbc_out,\n const std::string& cfb_out, const std::string& ofb_out,\n const std::string& ctr_out)\n {\n if(!have_block_cipher(cipher))\n return;\n\n cipher_kat(in, ecb_out, key, \"\", cipher + \"\/ECB\");\n cipher_kat(in, cbc_out, key, iv, cipher + \"\/CBC\/NoPadding\");\n cipher_kat(in, cfb_out, key, iv, cipher + \"\/CFB\");\n cipher_kat(in, ofb_out, key, iv, cipher + \"\/OFB\");\n cipher_kat(in, ctr_out, key, iv, cipher + \"\/CTR-BE\");\n }\n\n\/*************************************************\n* Perform a KAT for a hash *\n*************************************************\/\nvoid hash_kat(const std::string& hash, const std::string& in,\n const std::string& out)\n {\n if(!have_hash(hash))\n return;\n do_kat(in, out, hash, new Hash_Filter(hash));\n }\n\n\/*************************************************\n* Perform a KAT for a MAC *\n*************************************************\/\nvoid mac_kat(const std::string& mac, const std::string& in,\n const std::string& out, const std::string& key)\n {\n if(!have_mac(mac))\n return;\n do_kat(in, out, mac, new MAC_Filter(mac, key));\n }\n\n}\n\n\/*************************************************\n* Perform FIPS 140 Self Tests *\n*************************************************\/\nbool passes_self_tests()\n {\n try {\n cipher_kat(\"DES\", \"0123456789ABCDEF\", \"1234567890ABCDEF\",\n \"4E6F77206973207468652074696D6520666F7220616C6C20\",\n \"3FA40E8A984D48156A271787AB8883F9893D51EC4B563B53\",\n \"E5C7CDDE872BF27C43E934008C389C0F683788499A7C05F6\",\n \"F3096249C7F46E51A69E839B1A92F78403467133898EA622\",\n \"F3096249C7F46E5135F24A242EEB3D3F3D6D5BE3255AF8C3\",\n \"F3096249C7F46E51163A8CA0FFC94C27FA2F80F480B86F75\");\n\n cipher_kat(\"TripleDES\",\n \"385D7189A5C3D485E1370AA5D408082B5CCCCB5E19F2D90E\",\n \"C141B5FCCD28DC8A\",\n \"6E1BD7C6120947A464A6AAB293A0F89A563D8D40D3461B68\",\n \"64EAAD4ACBB9CEAD6C7615E7C7E4792FE587D91F20C7D2F4\",\n \"6235A461AFD312973E3B4F7AA7D23E34E03371F8E8C376C9\",\n \"E26BA806A59B0330DE40CA38E77A3E494BE2B212F6DD624B\",\n \"E26BA806A59B03307DE2BCC25A08BA40A8BA335F5D604C62\",\n \"E26BA806A59B03303C62C2EFF32D3ACDD5D5F35EBCC53371\");\n\n cipher_kat(\"AES\",\n \"2B7E151628AED2A6ABF7158809CF4F3C\",\n \"000102030405060708090A0B0C0D0E0F\",\n \"6BC1BEE22E409F96E93D7E117393172A\"\n \"AE2D8A571E03AC9C9EB76FAC45AF8E51\",\n \"3AD77BB40D7A3660A89ECAF32466EF97\"\n \"F5D3D58503B9699DE785895A96FDBAAF\",\n \"7649ABAC8119B246CEE98E9B12E9197D\"\n \"5086CB9B507219EE95DB113A917678B2\",\n \"3B3FD92EB72DAD20333449F8E83CFB4A\"\n \"C8A64537A0B3A93FCDE3CDAD9F1CE58B\",\n \"3B3FD92EB72DAD20333449F8E83CFB4A\"\n \"7789508D16918F03F53C52DAC54ED825\",\n \"3B3FD92EB72DAD20333449F8E83CFB4A\"\n \"010C041999E03F36448624483E582D0E\");\n\n hash_kat(\"SHA-1\", \"\", \"DA39A3EE5E6B4B0D3255BFEF95601890AFD80709\");\n hash_kat(\"SHA-1\", \"616263\", \"A9993E364706816ABA3E25717850C26C9CD0D89D\");\n hash_kat(\"SHA-1\",\n \"6162636462636465636465666465666765666768666768696768696A\"\n \"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071\",\n \"84983E441C3BD26EBAAE4AA1F95129E5E54670F1\");\n\n hash_kat(\"SHA-256\", \"\",\n \"E3B0C44298FC1C149AFBF4C8996FB924\"\n \"27AE41E4649B934CA495991B7852B855\");\n hash_kat(\"SHA-256\", \"616263\",\n \"BA7816BF8F01CFEA414140DE5DAE2223\"\n \"B00361A396177A9CB410FF61F20015AD\");\n hash_kat(\"SHA-256\",\n \"6162636462636465636465666465666765666768666768696768696A\"\n \"68696A6B696A6B6C6A6B6C6D6B6C6D6E6C6D6E6F6D6E6F706E6F7071\",\n \"248D6A61D20638B8E5C026930C3E6039\"\n \"A33CE45964FF2167F6ECEDD419DB06C1\");\n\n mac_kat(\"HMAC(SHA-1)\", \"4869205468657265\",\n \"B617318655057264E28BC0B6FB378C8EF146BE00\",\n \"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B\");\n\n mac_kat(\"HMAC(SHA-256)\", \"4869205468657265\",\n \"198A607EB44BFBC69903A0F1CF2BBDC5\"\n \"BA0AA3F3D9AE3C1C7A3B1696A0B68CF7\",\n \"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B\"\n \"0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B\");\n }\n catch(std::exception& e)\n {\n return false;\n }\n\n return true;\n }\n\n}\n<|endoftext|>"} {"text":"Fixed a crashbug in shutdown command<|endoftext|>"} {"text":"\/*\n *\n * Copyright (c) 2020 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#if CONFIG_DEVICE_LAYER\n#include \n#endif\n\n#if CONFIG_NETWORK_LAYER_BLE\n#include \n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n\nstatic const size_t kMax_SecureSDU_Length = 1024;\nstatic constexpr uint32_t kSpake2p_Iteration_Count = 50000;\nstatic const char * kSpake2pKeyExchangeSalt = \"SPAKE2P Key Exchange Salt\";\n\nnamespace chip {\n\nenum NetworkProvisioningMsgTypes : uint8_t\n{\n kWiFiAssociationRequest = 0,\n kIPAddressAssigned = 1,\n};\n\nCHIP_ERROR RendezvousSession::Init()\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n mParams = params;\n VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);\n VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT);\n\n err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n#if CONFIG_NETWORK_LAYER_BLE\n {\n Transport::BLE * transport = new Transport::BLE();\n err = transport->Init(this, mParams);\n mTransport = transport;\n mTransport->Retain();\n transport->Release();\n }\n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n SuccessOrExit(err);\n\n if (mParams.HasDiscriminator() == false)\n {\n err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n#if CONFIG_DEVICE_LAYER\n DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast(this));\n#endif\n }\n\nexit:\n return err;\n}\n\nRendezvousSession::~RendezvousSession()\n{\n if (mTransport)\n {\n mTransport->Release();\n mTransport = nullptr;\n }\n\n mDelegate = nullptr;\n}\n\nCHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = mPairingInProgress ? SendPairingMessage(msgBuf)\n : SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,\n NetworkProvisioningMsgTypes::kWiFiAssociationRequest, msgBuf);\n SuccessOrExit(err);\n\nexit:\n if (err != CHIP_NO_ERROR)\n {\n mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n }\n return err;\n}\nCHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader header;\n uint16_t headerSize = 0;\n\n VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n SuccessOrExit(err);\n\n msgBuf->ConsumeHead(headerSize);\n err = mTransport->SendMessage(header, Header::Flags::None(), Transport::PeerAddress::BLE(), msgBuf);\n SuccessOrExit(err);\n\nexit:\n return err;\n}\n\nCHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader packetHeader;\n PayloadHeader payloadHeader;\n MessageAuthenticationCode mac;\n const uint16_t headerSize = payloadHeader.EncodeSizeBytes();\n uint16_t actualEncodedHeaderSize;\n uint8_t * data = nullptr;\n uint16_t totalLen = 0;\n uint16_t taglen = 0;\n\n VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n VerifyOrExit(CanCastTo(headerSize + msgBuf->TotalLength()), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n packetHeader\n .SetSourceNodeId(mParams.GetLocalNodeId()) \/\/\n .SetMessageId(mSecureMessageIndex) \/\/\n .SetEncryptionKeyID(mPairingSession.GetLocalKeyId()) \/\/\n .SetPayloadLength(static_cast(headerSize + msgBuf->TotalLength()));\n\n payloadHeader.SetProtocolID(protocol).SetMessageType(msgType);\n\n VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY);\n\n msgBuf->SetStart(msgBuf->Start() - headerSize);\n data = msgBuf->Start();\n totalLen = msgBuf->TotalLength();\n\n err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize);\n SuccessOrExit(err);\n\n err = mSecureSession.Encrypt(data, totalLen, data, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n SuccessOrExit(err);\n\n err = mac.Encode(packetHeader, &data[totalLen], kMaxTagLen, &taglen);\n SuccessOrExit(err);\n\n VerifyOrExit(CanCastTo(totalLen + taglen), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n msgBuf->SetDataLength(static_cast(totalLen + taglen));\n\n err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), Transport::PeerAddress::BLE(), msgBuf);\n SuccessOrExit(err);\n\n mSecureMessageIndex++;\n msgBuf = nullptr;\n\nexit:\n return err;\n}\n\nvoid RendezvousSession::OnPairingError(CHIP_ERROR err)\n{\n mPairingInProgress = false;\n mDelegate->OnRendezvousError(err);\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingFailed);\n}\n\nvoid RendezvousSession::OnPairingComplete()\n{\n mPairingInProgress = false;\n\n CHIP_ERROR err = mPairingSession.DeriveSecureSession((const unsigned char *) kSpake2pI2RSessionInfo,\n strlen(kSpake2pI2RSessionInfo), mSecureSession);\n VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Ble, \"Failed to initialize a secure session: %s\", ErrorStr(err)));\n\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess);\n mDelegate->OnRendezvousConnectionOpened();\n\nexit:\n return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionOpened()\n{\n if (mParams.HasDiscriminator())\n {\n CHIP_ERROR err = Pair(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n }\n\nexit:\n return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionClosed()\n{\n mDelegate->OnRendezvousConnectionClosed();\n\n if (!mParams.HasDiscriminator() && !mParams.HasConnectionObject())\n {\n mSecureSession.Reset();\n CHIP_ERROR err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n }\n\nexit:\n return;\n}\n\nvoid RendezvousSession::OnRendezvousError(CHIP_ERROR err)\n{\n mDelegate->OnRendezvousError(err);\n}\n\nvoid RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n err = mPairingInProgress ? HandlePairingMessage(msgBuf) : HandleSecureMessage(msgBuf);\n SuccessOrExit(err);\n\nexit:\n if (err != CHIP_NO_ERROR)\n {\n mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n }\n}\n\nCHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader packetHeader;\n uint16_t headerSize = 0;\n\n err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n SuccessOrExit(err);\n\n msgBuf->ConsumeHead(headerSize);\n\n err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf);\n SuccessOrExit(err);\n\nexit:\n return err;\n}\n\nCHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader packetHeader;\n PayloadHeader payloadHeader;\n MessageAuthenticationCode mac;\n uint16_t headerSize = 0;\n uint8_t * data = nullptr;\n uint8_t * plainText = nullptr;\n uint16_t len = 0;\n uint16_t decodedSize = 0;\n uint16_t taglen = 0;\n System::PacketBuffer * origMsg = nullptr;\n\n err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n SuccessOrExit(err);\n msgBuf->ConsumeHead(headerSize);\n\n headerSize = payloadHeader.EncodeSizeBytes();\n data = msgBuf->Start();\n len = msgBuf->TotalLength();\n\n#if CHIP_SYSTEM_CONFIG_USE_LWIP\n \/* This is a workaround for the case where PacketBuffer payload is not\n allocated as an inline buffer to PacketBuffer structure *\/\n origMsg = msgBuf;\n msgBuf = PacketBuffer::NewWithAvailableSize(len);\n msgBuf->SetDataLength(len, msgBuf);\n#endif\n plainText = msgBuf->Start();\n\n \/\/ TODO: We need length checks here! https:\/\/github.com\/project-chip\/connectedhomeip\/issues\/2928\n err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen);\n SuccessOrExit(err);\n\n len = static_cast(len - taglen);\n msgBuf->SetDataLength(len);\n\n err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n SuccessOrExit(err);\n\n err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize);\n SuccessOrExit(err);\n VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE);\n\n msgBuf->ConsumeHead(headerSize);\n\n if (payloadHeader.GetProtocolID() == Protocols::kChipProtocol_NetworkProvisioning &&\n payloadHeader.GetMessageType() == NetworkProvisioningMsgTypes::kIPAddressAssigned)\n {\n if (!IPAddress::FromString(Uint8::to_const_char(msgBuf->Start()), msgBuf->DataLength(), mDeviceAddress))\n {\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningFailed);\n ExitNow(err = CHIP_ERROR_INVALID_ADDRESS);\n }\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningSuccess);\n }\n \/\/ else .. TBD once application dependency on this message has been removed, enable the else condition\n {\n mDelegate->OnRendezvousMessageReceived(msgBuf);\n }\n\n msgBuf = nullptr;\n\nexit:\n if (origMsg != nullptr)\n {\n PacketBuffer::Free(origMsg);\n }\n\n return err;\n}\n\nCHIP_ERROR RendezvousSession::WaitForPairing(Optional nodeId, uint32_t setupPINCode)\n{\n mPairingInProgress = true;\n return mPairingSession.WaitForPairing(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n strlen(kSpake2pKeyExchangeSalt), nodeId, 0, this);\n}\n\nCHIP_ERROR RendezvousSession::Pair(Optional nodeId, uint32_t setupPINCode)\n{\n mPairingInProgress = true;\n return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this);\n}\n\nvoid RendezvousSession::SendIPAddress(IPAddress & addr)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n System::PacketBuffer * buffer = System::PacketBuffer::New();\n char * addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());\n\n VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);\n VerifyOrExit(mPairingInProgress == false, err = CHIP_ERROR_INCORRECT_STATE);\n\n buffer->SetDataLength(strlen(addrStr) + 1);\n\n err = SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning, NetworkProvisioningMsgTypes::kIPAddressAssigned, buffer);\n SuccessOrExit(err);\n\nexit:\n if (CHIP_NO_ERROR != err)\n {\n OnRendezvousError(err);\n PacketBuffer::Free(buffer);\n }\n}\n\n#if CONFIG_DEVICE_LAYER\nvoid RendezvousSession::ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)\n{\n RendezvousSession * session = reinterpret_cast(arg);\n\n VerifyOrExit(session != nullptr, \/**\/);\n VerifyOrExit(event->Type == DeviceLayer::DeviceEventType::kInternetConnectivityChange, \/**\/);\n VerifyOrExit(event->InternetConnectivityChange.IPv4 == DeviceLayer::kConnectivity_Established, \/**\/);\n\n IPAddress addr;\n IPAddress::FromString(event->InternetConnectivityChange.address, addr);\n session->SendIPAddress(addr);\n\nexit:\n return;\n}\n#endif\n\n} \/\/ namespace chip\nFix post rebase build issues\/*\n *\n * Copyright (c) 2020 Project CHIP Authors\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#if CONFIG_DEVICE_LAYER\n#include \n#endif\n\n#if CONFIG_NETWORK_LAYER_BLE\n#include \n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n\nstatic const size_t kMax_SecureSDU_Length = 1024;\nstatic constexpr uint32_t kSpake2p_Iteration_Count = 50000;\nstatic const char * kSpake2pKeyExchangeSalt = \"SPAKE2P Key Exchange Salt\";\n\nnamespace chip {\n\nenum NetworkProvisioningMsgTypes : uint8_t\n{\n kWiFiAssociationRequest = 0,\n kIPAddressAssigned = 1,\n};\n\nCHIP_ERROR RendezvousSession::Init(const RendezvousParameters & params)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n mParams = params;\n VerifyOrExit(mDelegate != nullptr, err = CHIP_ERROR_INCORRECT_STATE);\n VerifyOrExit(mParams.HasLocalNodeId(), err = CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrExit(mParams.HasSetupPINCode(), err = CHIP_ERROR_INVALID_ARGUMENT);\n\n err = CHIP_ERROR_UNSUPPORTED_CHIP_FEATURE;\n#if CONFIG_NETWORK_LAYER_BLE\n {\n Transport::BLE * transport = new Transport::BLE();\n err = transport->Init(this, mParams);\n mTransport = transport;\n mTransport->Retain();\n transport->Release();\n }\n#endif \/\/ CONFIG_NETWORK_LAYER_BLE\n SuccessOrExit(err);\n\n if (mParams.HasDiscriminator() == false)\n {\n err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n#if CONFIG_DEVICE_LAYER\n DeviceLayer::PlatformMgr().AddEventHandler(ConnectivityHandler, reinterpret_cast(this));\n#endif\n }\n\nexit:\n return err;\n}\n\nRendezvousSession::~RendezvousSession()\n{\n if (mTransport)\n {\n mTransport->Release();\n mTransport = nullptr;\n }\n\n mDelegate = nullptr;\n}\n\nCHIP_ERROR RendezvousSession::SendMessage(System::PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = mPairingInProgress ? SendPairingMessage(msgBuf)\n : SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning,\n NetworkProvisioningMsgTypes::kWiFiAssociationRequest, msgBuf);\n SuccessOrExit(err);\n\nexit:\n if (err != CHIP_NO_ERROR)\n {\n mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n }\n return err;\n}\nCHIP_ERROR RendezvousSession::SendPairingMessage(System::PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader header;\n uint16_t headerSize = 0;\n\n VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n err = header.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n SuccessOrExit(err);\n\n msgBuf->ConsumeHead(headerSize);\n err = mTransport->SendMessage(header, Header::Flags::None(), Transport::PeerAddress::BLE(), msgBuf);\n SuccessOrExit(err);\n\nexit:\n return err;\n}\n\nCHIP_ERROR RendezvousSession::SendSecureMessage(Protocols::CHIPProtocolId protocol, uint8_t msgType, System::PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader packetHeader;\n PayloadHeader payloadHeader;\n MessageAuthenticationCode mac;\n const uint16_t headerSize = payloadHeader.EncodeSizeBytes();\n uint16_t actualEncodedHeaderSize;\n uint8_t * data = nullptr;\n uint16_t totalLen = 0;\n uint16_t taglen = 0;\n\n VerifyOrExit(msgBuf != nullptr, err = CHIP_ERROR_INVALID_ARGUMENT);\n VerifyOrExit(msgBuf->Next() == nullptr, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n VerifyOrExit(msgBuf->TotalLength() < kMax_SecureSDU_Length, err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n VerifyOrExit(CanCastTo(headerSize + msgBuf->TotalLength()), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n\n packetHeader\n .SetSourceNodeId(mParams.GetLocalNodeId()) \/\/\n .SetMessageId(mSecureMessageIndex) \/\/\n .SetEncryptionKeyID(mPairingSession.GetLocalKeyId()) \/\/\n .SetPayloadLength(static_cast(headerSize + msgBuf->TotalLength()));\n\n payloadHeader.SetProtocolID(protocol).SetMessageType(msgType);\n\n VerifyOrExit(msgBuf->EnsureReservedSize(headerSize), err = CHIP_ERROR_NO_MEMORY);\n\n msgBuf->SetStart(msgBuf->Start() - headerSize);\n data = msgBuf->Start();\n totalLen = msgBuf->TotalLength();\n\n err = payloadHeader.Encode(data, totalLen, &actualEncodedHeaderSize);\n SuccessOrExit(err);\n\n err = mSecureSession.Encrypt(data, totalLen, data, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n SuccessOrExit(err);\n\n err = mac.Encode(packetHeader, &data[totalLen], kMaxTagLen, &taglen);\n SuccessOrExit(err);\n\n VerifyOrExit(CanCastTo(totalLen + taglen), err = CHIP_ERROR_INVALID_MESSAGE_LENGTH);\n msgBuf->SetDataLength(static_cast(totalLen + taglen));\n\n err = mTransport->SendMessage(packetHeader, payloadHeader.GetEncodePacketFlags(), Transport::PeerAddress::BLE(), msgBuf);\n SuccessOrExit(err);\n\n mSecureMessageIndex++;\n msgBuf = nullptr;\n\nexit:\n return err;\n}\n\nvoid RendezvousSession::OnPairingError(CHIP_ERROR err)\n{\n mPairingInProgress = false;\n mDelegate->OnRendezvousError(err);\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingFailed);\n}\n\nvoid RendezvousSession::OnPairingComplete()\n{\n mPairingInProgress = false;\n\n CHIP_ERROR err = mPairingSession.DeriveSecureSession((const unsigned char *) kSpake2pI2RSessionInfo,\n strlen(kSpake2pI2RSessionInfo), mSecureSession);\n VerifyOrExit(err == CHIP_NO_ERROR, ChipLogError(Ble, \"Failed to initialize a secure session: %s\", ErrorStr(err)));\n\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::SecurePairingSuccess);\n mDelegate->OnRendezvousConnectionOpened();\n\nexit:\n return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionOpened()\n{\n if (mParams.HasDiscriminator())\n {\n CHIP_ERROR err = Pair(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n }\n\nexit:\n return;\n}\n\nvoid RendezvousSession::OnRendezvousConnectionClosed()\n{\n mDelegate->OnRendezvousConnectionClosed();\n\n if (!mParams.HasDiscriminator() && !mParams.HasConnectionObject())\n {\n mSecureSession.Reset();\n CHIP_ERROR err = WaitForPairing(mParams.GetLocalNodeId(), mParams.GetSetupPINCode());\n VerifyOrExit(err == CHIP_NO_ERROR, OnPairingError(err));\n }\n\nexit:\n return;\n}\n\nvoid RendezvousSession::OnRendezvousError(CHIP_ERROR err)\n{\n mDelegate->OnRendezvousError(err);\n}\n\nvoid RendezvousSession::OnRendezvousMessageReceived(PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n\n err = mPairingInProgress ? HandlePairingMessage(msgBuf) : HandleSecureMessage(msgBuf);\n SuccessOrExit(err);\n\nexit:\n if (err != CHIP_NO_ERROR)\n {\n mPairingInProgress ? OnPairingError(err) : OnRendezvousError(err);\n }\n}\n\nCHIP_ERROR RendezvousSession::HandlePairingMessage(PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader packetHeader;\n uint16_t headerSize = 0;\n\n err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n SuccessOrExit(err);\n\n msgBuf->ConsumeHead(headerSize);\n\n err = mPairingSession.HandlePeerMessage(packetHeader, msgBuf);\n SuccessOrExit(err);\n\nexit:\n return err;\n}\n\nCHIP_ERROR RendezvousSession::HandleSecureMessage(PacketBuffer * msgBuf)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n PacketHeader packetHeader;\n PayloadHeader payloadHeader;\n MessageAuthenticationCode mac;\n uint16_t headerSize = 0;\n uint8_t * data = nullptr;\n uint8_t * plainText = nullptr;\n uint16_t len = 0;\n uint16_t decodedSize = 0;\n uint16_t taglen = 0;\n System::PacketBuffer * origMsg = nullptr;\n\n err = packetHeader.Decode(msgBuf->Start(), msgBuf->DataLength(), &headerSize);\n SuccessOrExit(err);\n msgBuf->ConsumeHead(headerSize);\n\n headerSize = payloadHeader.EncodeSizeBytes();\n data = msgBuf->Start();\n len = msgBuf->TotalLength();\n\n#if CHIP_SYSTEM_CONFIG_USE_LWIP\n \/* This is a workaround for the case where PacketBuffer payload is not\n allocated as an inline buffer to PacketBuffer structure *\/\n origMsg = msgBuf;\n msgBuf = PacketBuffer::NewWithAvailableSize(len);\n msgBuf->SetDataLength(len, msgBuf);\n#endif\n plainText = msgBuf->Start();\n\n \/\/ TODO: We need length checks here! https:\/\/github.com\/project-chip\/connectedhomeip\/issues\/2928\n err = mac.Decode(packetHeader, &data[packetHeader.GetPayloadLength()], kMaxTagLen, &taglen);\n SuccessOrExit(err);\n\n len = static_cast(len - taglen);\n msgBuf->SetDataLength(len);\n\n err = mSecureSession.Decrypt(data, len, plainText, packetHeader, payloadHeader.GetEncodePacketFlags(), mac);\n SuccessOrExit(err);\n\n err = payloadHeader.Decode(packetHeader.GetFlags(), plainText, headerSize, &decodedSize);\n SuccessOrExit(err);\n VerifyOrExit(headerSize == decodedSize, err = CHIP_ERROR_INCORRECT_STATE);\n\n msgBuf->ConsumeHead(headerSize);\n\n if (payloadHeader.GetProtocolID() == Protocols::kChipProtocol_NetworkProvisioning &&\n payloadHeader.GetMessageType() == NetworkProvisioningMsgTypes::kIPAddressAssigned)\n {\n if (!IPAddress::FromString(Uint8::to_const_char(msgBuf->Start()), msgBuf->DataLength(), mDeviceAddress))\n {\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningFailed);\n ExitNow(err = CHIP_ERROR_INVALID_ADDRESS);\n }\n mDelegate->OnRendezvousStatusUpdate(RendezvousSessionDelegate::NetworkProvisioningSuccess);\n }\n \/\/ else .. TBD once application dependency on this message has been removed, enable the else condition\n {\n mDelegate->OnRendezvousMessageReceived(msgBuf);\n }\n\n msgBuf = nullptr;\n\nexit:\n if (origMsg != nullptr)\n {\n PacketBuffer::Free(origMsg);\n }\n\n return err;\n}\n\nCHIP_ERROR RendezvousSession::WaitForPairing(Optional nodeId, uint32_t setupPINCode)\n{\n mPairingInProgress = true;\n return mPairingSession.WaitForPairing(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n strlen(kSpake2pKeyExchangeSalt), nodeId, 0, this);\n}\n\nCHIP_ERROR RendezvousSession::Pair(Optional nodeId, uint32_t setupPINCode)\n{\n mPairingInProgress = true;\n return mPairingSession.Pair(setupPINCode, kSpake2p_Iteration_Count, (const unsigned char *) kSpake2pKeyExchangeSalt,\n strlen(kSpake2pKeyExchangeSalt), nodeId, mNextKeyId++, this);\n}\n\nvoid RendezvousSession::SendIPAddress(IPAddress & addr)\n{\n CHIP_ERROR err = CHIP_NO_ERROR;\n System::PacketBuffer * buffer = System::PacketBuffer::New();\n char * addrStr = addr.ToString(Uint8::to_char(buffer->Start()), buffer->AvailableDataLength());\n\n VerifyOrExit(addrStr != nullptr, err = CHIP_ERROR_INVALID_ADDRESS);\n VerifyOrExit(mPairingInProgress == false, err = CHIP_ERROR_INCORRECT_STATE);\n\n buffer->SetDataLength(strlen(addrStr) + 1);\n\n err = SendSecureMessage(Protocols::kChipProtocol_NetworkProvisioning, NetworkProvisioningMsgTypes::kIPAddressAssigned, buffer);\n SuccessOrExit(err);\n\nexit:\n if (CHIP_NO_ERROR != err)\n {\n OnRendezvousError(err);\n PacketBuffer::Free(buffer);\n }\n}\n\n#if CONFIG_DEVICE_LAYER\nvoid RendezvousSession::ConnectivityHandler(const DeviceLayer::ChipDeviceEvent * event, intptr_t arg)\n{\n RendezvousSession * session = reinterpret_cast(arg);\n\n VerifyOrExit(session != nullptr, \/**\/);\n VerifyOrExit(event->Type == DeviceLayer::DeviceEventType::kInternetConnectivityChange, \/**\/);\n VerifyOrExit(event->InternetConnectivityChange.IPv4 == DeviceLayer::kConnectivity_Established, \/**\/);\n\n IPAddress addr;\n IPAddress::FromString(event->InternetConnectivityChange.address, addr);\n session->SendIPAddress(addr);\n\nexit:\n return;\n}\n#endif\n\n} \/\/ namespace chip\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2016 Bastien Durix\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n\n\/**\n * \\brief Provides tests for skeleton library\n * \\author Bastien Durix\n *\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace mathtools::affine;\nusing namespace mathtools::geometry::euclidian;\n\nint main()\n{\n\tunsigned int return_value = 0;\n\t\n\t\/\/ frame creation\n\tFrame<2>::Ptr frame = Frame<2>::CreateFrame(Eigen::Vector2d(1.0,0.0),Eigen::Vector2d(2.0,1.0),Eigen::Vector2d(1.0,0.0));\n\n\t\/\/ model creation\n\tskeleton::model::Classic<2>::Ptr modclass(new skeleton::model::Classic<2>{frame});\n\t\n\t\/\/ creating a random node\n\tEigen::Vector3d vec3((double)(rand()%201)\/10.0-1.0,\n\t\t\t\t\t\t (double)(rand()%201)\/10.0-1.0,\n\t\t\t\t\t\t (double)(rand()%201)\/10.0);\n\n\t\/\/ skeleton creation\n\tskeleton::GraphCurveSkeleton > skel(modclass);\n\t\n\tstd::cout << \"Adding Node test... \";\n\n\t\/\/ adding a node\n\tunsigned int ind = skel.addNode(vec3);\n\t\n\t\/\/ getting the node (vector form)\n\tEigen::Vector3d vec3_2 = skel.getNode(ind);\n\t\n\tif(vec3_2.isApprox(vec3,std::numeric_limits::epsilon()))\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\t\n\tstd::cout << \"Getter test... \";\n\n\t\/\/ getting the node (center form)\n\tPoint<2> pt = skel.getNode >(ind);\n\t\n\tif(pt.getCoords().isApprox(frame->getBasis()->getMatrix()*vec3.block<2,1>(0,0)+frame->getOrigin()))\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\n\t\/\/ hypersphere creation\n\tHyperSphere<2> sph(Point<2>(1.0,0.0),5.0,frame);\n\n\tstd::cout << \"Adding Sphere test... \";\n\n\t\/\/ adding a node\n\tunsigned int ind2 = skel.addNode >(sph);\n\t\n\t\/\/ get the vector associated to the node\n\tEigen::Vector3d vecsph = skel.getNode(ind2);\n\t\n\t\/\/ convert the node to a sphere\n\tHyperSphere<2> sphcpy = skel.getModel()->toObj >(vecsph);\n\t\n\tif(sphcpy.getCenter().getCoords().isApprox(sph.getCenter().getCoords(),std::numeric_limits::epsilon() && \n\t sphcpy.getRadius() == sph.getRadius() &&\n\t sphcpy.getFrame()->getBasis()->getMatrix().isApprox(sph.getFrame()->getBasis()->getMatrix(),std::numeric_limits::epsilon())) && \n\t ind != ind2)\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\t\n\t\/\/ get all indices\n\tstd::list listnod;\n\n\tstd::cout << \"Get all nodes... \";\n\tskel.getAllNodes(listnod);\n\n\tlistnod.unique();\n\n\tif(listnod.size() == 2 &&\n\t std::find(listnod.begin(),listnod.end(),ind) != listnod.end() && \n\t std::find(listnod.begin(),listnod.end(),ind2) != listnod.end())\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\n\treturn return_value;\n}\nAdded test to neighbor access in skeleton\/*\nCopyright (c) 2016 Bastien Durix\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n*\/\n\n\n\/**\n * \\brief Provides tests for skeleton library\n * \\author Bastien Durix\n *\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n\nusing namespace mathtools::affine;\nusing namespace mathtools::geometry::euclidian;\n\nint main()\n{\n\tunsigned int return_value = 0;\n\t\n\t\/\/ frame creation\n\tFrame<2>::Ptr frame = Frame<2>::CreateFrame(Eigen::Vector2d(1.0,0.0),Eigen::Vector2d(2.0,1.0),Eigen::Vector2d(1.0,0.0));\n\n\t\/\/ model creation\n\tskeleton::model::Classic<2>::Ptr modclass(new skeleton::model::Classic<2>{frame});\n\t\n\t\/\/ creating a random node\n\tEigen::Vector3d vec3((double)(rand()%201)\/10.0-1.0,\n\t\t\t\t\t\t (double)(rand()%201)\/10.0-1.0,\n\t\t\t\t\t\t (double)(rand()%201)\/10.0);\n\n\t\/\/ skeleton creation\n\tskeleton::GraphCurveSkeleton > skel(modclass);\n\t\n\tstd::cout << \"Adding Node test... \";\n\n\t\/\/ adding a node\n\tunsigned int ind = skel.addNode(vec3);\n\t\n\t\/\/ getting the node (vector form)\n\tEigen::Vector3d vec3_2 = skel.getNode(ind);\n\t\n\tif(vec3_2.isApprox(vec3,std::numeric_limits::epsilon()))\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\t\n\tstd::cout << \"Getter test... \";\n\n\t\/\/ getting the node (center form)\n\tPoint<2> pt = skel.getNode >(ind);\n\t\n\tif(pt.getCoords().isApprox(frame->getBasis()->getMatrix()*vec3.block<2,1>(0,0)+frame->getOrigin()))\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\n\t\/\/ hypersphere creation\n\tHyperSphere<2> sph(Point<2>(1.0,0.0),5.0,frame);\n\n\tstd::cout << \"Adding Sphere test... \";\n\n\t\/\/ adding a node\n\tunsigned int ind2 = skel.addNode >(sph);\n\t\n\t\/\/ get the vector associated to the node\n\tEigen::Vector3d vecsph = skel.getNode(ind2);\n\t\n\t\/\/ convert the node to a sphere\n\tHyperSphere<2> sphcpy = skel.getModel()->toObj >(vecsph);\n\t\n\tif(sphcpy.getCenter().getCoords().isApprox(sph.getCenter().getCoords(),std::numeric_limits::epsilon() && \n\t sphcpy.getRadius() == sph.getRadius() &&\n\t sphcpy.getFrame()->getBasis()->getMatrix().isApprox(sph.getFrame()->getBasis()->getMatrix(),std::numeric_limits::epsilon())) && \n\t ind != ind2)\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\t\n\t\/\/ get all indices\n\tstd::list listnod;\n\n\tstd::cout << \"Get all nodes... \";\n\tskel.getAllNodes(listnod);\n\n\tlistnod.unique();\n\n\tif(listnod.size() == 2 &&\n\t std::find(listnod.begin(),listnod.end(),ind) != listnod.end() && \n\t std::find(listnod.begin(),listnod.end(),ind2) != listnod.end())\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\t\n\tstd::cout << \"Adding edge test... \";\n\n\t\/\/ adding an edge\n\tskel.addEdge(ind, ind2);\n\n\tstd::list neigh;\n\tskel.getNeighbors(ind,neigh);\n\t\n\tif(neigh.size() == 1 && *(neigh.begin()) == ind2)\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\n\tstd::cout << \"Removing edge test... \";\n\n\t\/\/ removing an edge\n\tskel.remEdge(ind, ind2);\n\t\n\tneigh.erase(neigh.begin(),neigh.end());\n\tskel.getNeighbors(ind,neigh);\n\t\n\tif(neigh.size() == 0)\n\t{\n\t\tstd::cout << \"Success!\" << std::endl;\n\t}\n\telse\n\t{\n\t\treturn_value = -1;\n\t\tstd::cout << \"Fail!\" << std::endl;\n\t}\n\n\n\n\treturn return_value;\n}\n<|endoftext|>"} {"text":"\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/diag\/attn\/runtime\/attn_rt.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2014,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n#include \"runtime\/attnsvc.H\"\n#include \"common\/attntrace.H\"\n#include \"common\/attnmem.H\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace TARGETING;\nusing namespace ATTN;\nusing namespace PRDF;\n\nnamespace ATTN_RT\n{\n \/** Enable chip attentions\n *\n * @return 0 on success else return code\n *\/\n int enableAttns(void)\n {\n ATTN_SLOW(ENTER_MRK\"ATTN_RT::enableAttns\");\n\n int rc = 0;\n errlHndl_t err = NULL;\n err = Singleton::instance().enableAttns();\n if(err)\n {\n errlCommit(err, ATTN_COMP_ID);\n rc = -1;\n }\n\n ATTN_SLOW(EXIT_MRK\"ATTN_RT::enableAttns rc: %d\", rc);\n\n return rc;\n }\n\n \/** Disable chip attentions\n *\n * @return 0 on success else return code\n *\/\n int disableAttns(void)\n {\n ATTN_SLOW(ENTER_MRK\"ATTN_RT::disableAttns\");\n\n int rc = 0;\n errlHndl_t err = NULL;\n err = Singleton::instance().disableAttns();\n if(err)\n {\n errlCommit(err, ATTN_COMP_ID);\n rc = -1;\n }\n\n ATTN_SLOW(EXIT_MRK\"ATTN_RT::disableAttns rc: %d\", rc);\n\n return rc;\n }\n\n \/** brief handle chip attentions\n *\n * @param[in] i_proc - processor chip id at attention\n * XSCOM chip id based on devtree defn\n * @param[in] i_ipollStatus - processor chip Ipoll status\n * @param[in] i_ipollMask - processor chip Ipoll mask\n * @return 0 on success else return code\n *\/\n int handleAttns(uint64_t i_proc,\n uint64_t i_ipollStatus,\n uint64_t i_ipollMask)\n {\n ATTN_SLOW(ENTER_MRK\"ATTN_RT::handleAttns RtProc: %llx\"\n \", ipollMask: %llx, ipollStatus: %llx\",\n i_proc, i_ipollMask, i_ipollStatus);\n\n int rc = 0;\n errlHndl_t err = NULL;\n AttentionList attentions;\n MemOps & memOps = getMemOps();\n\n\n do\n {\n \/\/ Convert chipIds to HB targets\n TargetHandle_t proc = NULL;\n err = RT_TARG::getHbTarget(i_proc, proc);\n if(err)\n {\n ATTN_ERR(\"ATTN_RT::handleAttns getHbTarget \"\n \"returned error for RtProc: %llx\", i_proc);\n rc = EINVAL;\n break;\n }\n\n err = Singleton::instance().handleAttentions(proc);\n if(err)\n {\n ATTN_ERR(\"ATTN_RT::handleAttns service::handleAttentions \"\n \"returned error for RtProc: %llx\", i_proc);\n break;\n }\n\n \/\/ On P8,\n \/\/ For host attentions, clear gpio interrupt type register.\n \/\/ If we do not clear gpio register, ipoll status will again\n \/\/ get set and we will end up in infinite loop.\n\n \/\/ For P9,\n \/\/ Host attentions should be coming thru the\n \/\/ normal (IPOLL) Error status reg. Hence, we shouldn't\n \/\/ have to play with the IPR (interrupt presentation register)\n \/\/ which was involved with the gpio\/gpin register where\n \/\/ centaur routed its attentions.\n\n\n } while(0);\n\n if(err)\n {\n errlCommit( err, ATTN_COMP_ID );\n if(0 == rc)\n {\n rc = -1;\n }\n }\n\n\n attentions.clear();\n ATTN_SLOW(EXIT_MRK\"ATTN_RT::handleAttns rc: %d\", rc);\n\n return rc;\n }\n\n \/\/ register runtimeInterfaces\n struct registerAttn\n {\n registerAttn()\n {\n runtimeInterfaces_t * rt_intf = getRuntimeInterfaces();\n if (NULL == rt_intf)\n {\n return;\n }\n\n rt_intf->enable_attns = &enableAttns;\n rt_intf->disable_attns = &disableAttns;\n rt_intf->handle_attns = &handleAttns;\n }\n };\n\n registerAttn g_registerAttn;\n}\n\nRemove unused variable in attn_rt.C\/* IBM_PROLOG_BEGIN_TAG *\/\n\/* This is an automatically generated prolog. *\/\n\/* *\/\n\/* $Source: src\/usr\/diag\/attn\/runtime\/attn_rt.C $ *\/\n\/* *\/\n\/* OpenPOWER HostBoot Project *\/\n\/* *\/\n\/* Contributors Listed Below - COPYRIGHT 2014,2016 *\/\n\/* [+] International Business Machines Corp. *\/\n\/* *\/\n\/* *\/\n\/* Licensed under the Apache License, Version 2.0 (the \"License\"); *\/\n\/* you may not use this file except in compliance with the License. *\/\n\/* You may obtain a copy of the License at *\/\n\/* *\/\n\/* http:\/\/www.apache.org\/licenses\/LICENSE-2.0 *\/\n\/* *\/\n\/* Unless required by applicable law or agreed to in writing, software *\/\n\/* distributed under the License is distributed on an \"AS IS\" BASIS, *\/\n\/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or *\/\n\/* implied. See the License for the specific language governing *\/\n\/* permissions and limitations under the License. *\/\n\/* *\/\n\/* IBM_PROLOG_END_TAG *\/\n\n#include \"runtime\/attnsvc.H\"\n#include \"common\/attntrace.H\"\n#include \"common\/attnmem.H\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\nusing namespace TARGETING;\nusing namespace ATTN;\nusing namespace PRDF;\n\nnamespace ATTN_RT\n{\n \/** Enable chip attentions\n *\n * @return 0 on success else return code\n *\/\n int enableAttns(void)\n {\n ATTN_SLOW(ENTER_MRK\"ATTN_RT::enableAttns\");\n\n int rc = 0;\n errlHndl_t err = NULL;\n err = Singleton::instance().enableAttns();\n if(err)\n {\n errlCommit(err, ATTN_COMP_ID);\n rc = -1;\n }\n\n ATTN_SLOW(EXIT_MRK\"ATTN_RT::enableAttns rc: %d\", rc);\n\n return rc;\n }\n\n \/** Disable chip attentions\n *\n * @return 0 on success else return code\n *\/\n int disableAttns(void)\n {\n ATTN_SLOW(ENTER_MRK\"ATTN_RT::disableAttns\");\n\n int rc = 0;\n errlHndl_t err = NULL;\n err = Singleton::instance().disableAttns();\n if(err)\n {\n errlCommit(err, ATTN_COMP_ID);\n rc = -1;\n }\n\n ATTN_SLOW(EXIT_MRK\"ATTN_RT::disableAttns rc: %d\", rc);\n\n return rc;\n }\n\n \/** brief handle chip attentions\n *\n * @param[in] i_proc - processor chip id at attention\n * XSCOM chip id based on devtree defn\n * @param[in] i_ipollStatus - processor chip Ipoll status\n * @param[in] i_ipollMask - processor chip Ipoll mask\n * @return 0 on success else return code\n *\/\n int handleAttns(uint64_t i_proc,\n uint64_t i_ipollStatus,\n uint64_t i_ipollMask)\n {\n ATTN_SLOW(ENTER_MRK\"ATTN_RT::handleAttns RtProc: %llx\"\n \", ipollMask: %llx, ipollStatus: %llx\",\n i_proc, i_ipollMask, i_ipollStatus);\n\n int rc = 0;\n errlHndl_t err = NULL;\n AttentionList attentions;\n\n do\n {\n \/\/ Convert chipIds to HB targets\n TargetHandle_t proc = NULL;\n err = RT_TARG::getHbTarget(i_proc, proc);\n if(err)\n {\n ATTN_ERR(\"ATTN_RT::handleAttns getHbTarget \"\n \"returned error for RtProc: %llx\", i_proc);\n rc = EINVAL;\n break;\n }\n\n err = Singleton::instance().handleAttentions(proc);\n if(err)\n {\n ATTN_ERR(\"ATTN_RT::handleAttns service::handleAttentions \"\n \"returned error for RtProc: %llx\", i_proc);\n break;\n }\n\n \/\/ On P8,\n \/\/ For host attentions, clear gpio interrupt type register.\n \/\/ If we do not clear gpio register, ipoll status will again\n \/\/ get set and we will end up in infinite loop.\n\n \/\/ For P9,\n \/\/ Host attentions should be coming thru the\n \/\/ normal (IPOLL) Error status reg. Hence, we shouldn't\n \/\/ have to play with the IPR (interrupt presentation register)\n \/\/ which was involved with the gpio\/gpin register where\n \/\/ centaur routed its attentions.\n\n\n } while(0);\n\n if(err)\n {\n errlCommit( err, ATTN_COMP_ID );\n if(0 == rc)\n {\n rc = -1;\n }\n }\n\n\n attentions.clear();\n ATTN_SLOW(EXIT_MRK\"ATTN_RT::handleAttns rc: %d\", rc);\n\n return rc;\n }\n\n \/\/ register runtimeInterfaces\n struct registerAttn\n {\n registerAttn()\n {\n runtimeInterfaces_t * rt_intf = getRuntimeInterfaces();\n if (NULL == rt_intf)\n {\n return;\n }\n\n rt_intf->enable_attns = &enableAttns;\n rt_intf->disable_attns = &disableAttns;\n rt_intf->handle_attns = &handleAttns;\n }\n };\n\n registerAttn g_registerAttn;\n}\n\n<|endoftext|>"} {"text":"\/*\n * httpfileupload.cpp - HTTP File upload\n * Copyright (C) 2017-2019 Aleksey Andreev, Sergey Ilinykh\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"httpfileupload.h\"\n#include \"xmpp_tasks.h\"\n#include \"xmpp_xmlcommon.h\"\n#include \"xmpp_serverinfomanager.h\"\n\nusing namespace XMPP;\n\nstatic QLatin1String xmlns_v0_2_5(\"urn:xmpp:http:upload\");\nstatic QLatin1String xmlns_v0_3_1(\"urn:xmpp:http:upload:0\");\n\n\/\/----------------------------------------------------------------------------\n\/\/ HttpFileUpload\n\/\/----------------------------------------------------------------------------\nclass HttpFileUpload::Private\n{\npublic:\n HttpFileUpload::State state = State::None;\n XMPP::Client *client = nullptr;\n QIODevice *sourceDevice = nullptr;\n QPointer qnam = nullptr;\n quint64 fileSize = 0;\n QString fileName;\n QString mediaType;\n QList httpHosts;\n\n struct {\n HttpFileUpload::ErrorCode statusCode = HttpFileUpload::ErrorCode::NoError;\n QString statusString;\n QString getUrl;\n QString putUrl;\n XEP0363::HttpHeaders putHeaders;\n quint64 sizeLimit = 0;\n } result;\n};\n\nHttpFileUpload::HttpFileUpload(XMPP::Client *client, QIODevice *source, size_t fsize, const QString &dstFilename,\n const QString &mType) :\n QObject(client),\n d(new Private)\n{\n d->client = client;\n d->sourceDevice = source;\n d->fileName = dstFilename;\n d->fileSize = fsize;\n d->mediaType = mType;\n}\n\nHttpFileUpload::~HttpFileUpload()\n{\n qDebug(\"destroying\");\n}\n\nvoid HttpFileUpload::setNetworkAccessManager(QNetworkAccessManager *qnam)\n{\n d->qnam = qnam;\n}\n\nvoid HttpFileUpload::start()\n{\n if (d->state != State::None) \/\/ Attempt to start twice?\n return;\n\n setState(State::GettingSlot);\n\n d->result.statusCode = HttpFileUpload::ErrorCode::NoError;\n static QList> featureOptions;\n if (featureOptions.isEmpty()) {\n featureOptions << (QSet() << xmlns_v0_2_5) << (QSet() << xmlns_v0_3_1);\n }\n d->client->serverInfoManager()->queryServiceInfo(\n QLatin1String(\"store\"), QLatin1String(\"file\"),\n featureOptions, QRegExp(\"^(upload|http|stor|file|dis|drive).*\"), ServerInfoManager::SQ_CheckAllOnNoMatch,\n [this](const QList &items)\n {\n d->httpHosts.clear();\n for (const auto &item: items) {\n const QStringList &l = item.features().list();\n XEP0363::version ver = XEP0363::vUnknown;\n QString xmlns;\n quint64 sizeLimit = 0;\n if (l.contains(xmlns_v0_3_1)) {\n ver = XEP0363::v0_3_1;\n xmlns = xmlns_v0_3_1;\n } else if (l.contains(xmlns_v0_2_5)) {\n ver = XEP0363::v0_2_5;\n xmlns = xmlns_v0_2_5;\n }\n if (ver != XEP0363::vUnknown) {\n QList> hosts;\n const XData::Field field = item.registeredExtension(xmlns).getField(QLatin1String(\"max-file-size\"));\n if (field.isValid() && field.type() == XData::Field::Field_TextSingle)\n sizeLimit = field.value().at(0).toULongLong();\n HttpHost host;\n host.ver = ver;\n host.jid = item.jid();\n host.sizeLimit = sizeLimit;\n QVariant metaProps(d->client->serverInfoManager()->serviceMeta(host.jid, \"httpprops\"));\n if (metaProps.isValid()) {\n host.props = HostProps(metaProps.value());\n } else {\n host.props = SecureGet | SecurePut;\n if (ver == XEP0363::v0_3_1)\n host.props |= NewestVer;\n }\n int value = 0;\n if (host.props & SecureGet) value += 5;\n if (host.props & SecurePut) value += 5;\n if (host.props & NewestVer) value += 3;\n if (host.props & Failure) value -= 15;\n if (!sizeLimit || d->fileSize < sizeLimit)\n hosts.append({host,value});\n\n \/\/ no sorting in preference order. most preferred go first\n std::sort(hosts.begin(), hosts.end(), [](const auto &a, const auto &b){\n return a.second > b.second;\n });\n for (auto &hp: hosts) {\n d->httpHosts.append(hp.first);\n }\n }\n }\n \/\/d->currentHost = d->httpHosts.begin();\n if (d->httpHosts.isEmpty()) { \/\/ if empty as the last resort check all services\n d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;\n d->result.statusString = \"No suitable http upload services were found\";\n done(State::Error);\n } else {\n tryNextServer();\n }\n });\n}\n\nvoid HttpFileUpload::tryNextServer()\n{\n if (d->httpHosts.isEmpty()) { \/\/ if empty as the last resort check all services\n d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;\n d->result.statusString = \"All http services are either non compliant or returned errors\";\n done(State::Error);\n return;\n }\n HttpHost host = std::move(d->httpHosts.takeFirst());\n d->result.sizeLimit = host.sizeLimit;\n auto jt = new JT_HTTPFileUpload(d->client->rootTask());\n connect(jt, &JT_HTTPFileUpload::finished, this, [this, jt, host]() mutable {\n if (!jt->success()) {\n host.props |= Failure;\n int code = jt->statusCode();\n if (code < 300) {\n code++; \/\/ ErrDisc and ErrTimeout. but 0 code is already occupated\n }\n d->result.statusCode = static_cast(jt->statusCode());\n d->result.statusString = jt->statusString();\n d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String(\"httpprops\"), int(host.props));\n if (d->httpHosts.isEmpty())\n done(State::Error);\n else\n tryNextServer();\n return;\n }\n\n d->result.getUrl = jt->url(JT_HTTPFileUpload::GetUrl);\n d->result.putUrl = jt->url(JT_HTTPFileUpload::PutUrl);\n d->result.putHeaders = jt->headers();\n if (d->result.getUrl.startsWith(\"https:\/\/\"))\n host.props |= SecureGet;\n else\n host.props &= ~SecureGet;\n if (d->result.putUrl.startsWith(\"https:\/\/\"))\n host.props |= SecurePut;\n else\n host.props &= ~SecurePut;\n host.props &= ~Failure;\n\n d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String(\"httpprops\"), int(host.props));\n\n if (!d->qnam) { \/\/ w\/o network access manager, it's not more than getting slots\n done(State::Success);\n return;\n }\n\n setState(State::HttpRequest);\n \/\/ time for a http request\n QNetworkRequest req(d->result.putUrl);\n for (auto &h: d->result.putHeaders) {\n req.setRawHeader(h.name.toLatin1(), h.value.toLatin1());\n }\n auto reply = d->qnam->put(req, d->sourceDevice);\n connect(reply, &QNetworkReply::finished, this, [this, reply](){\n if (reply->error() == QNetworkReply::NoError) {\n done(State::Success);\n } else {\n d->result.statusCode = ErrorCode::HttpFailed;\n d->result.statusString = reply->errorString();\n if (d->httpHosts.isEmpty())\n done(State::Error);\n else\n tryNextServer();\n }\n reply->deleteLater();\n });\n\n }, Qt::QueuedConnection);\n jt->request(host.jid, d->fileName, d->fileSize, d->mediaType, host.ver);\n jt->go(true);\n}\n\nbool HttpFileUpload::success() const\n{\n return d->state == State::Success;\n}\n\nHttpFileUpload::ErrorCode HttpFileUpload::statusCode() const\n{\n return d->result.statusCode;\n}\n\nconst QString & HttpFileUpload::statusString() const\n{\n return d->result.statusString;\n}\n\nHttpFileUpload::HttpSlot HttpFileUpload::getHttpSlot()\n{\n HttpSlot slot;\n if (d->state == State::Success) {\n slot.get.url = d->result.getUrl;\n slot.put.url = d->result.putUrl;\n slot.put.headers = d->result.putHeaders;\n slot.limits.fileSize = d->result.sizeLimit;\n }\n return slot;\n}\n\nvoid HttpFileUpload::setState(State state)\n{\n d->state = state;\n if (state == Success) {\n d->result.statusCode = ErrorCode::NoError;\n d->result.statusString.clear();\n }\n emit stateChanged();\n}\n\nvoid HttpFileUpload::done(State state)\n{\n setState(state);\n emit finished();\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ JT_HTTPFileUpload\n\/\/----------------------------------------------------------------------------\nclass JT_HTTPFileUpload::Private\n{\npublic:\n Jid to;\n QDomElement iq;\n QStringList urls;\n XEP0363::version ver;\n XEP0363::HttpHeaders headers;\n};\n\nJT_HTTPFileUpload::JT_HTTPFileUpload(Task *parent)\n : Task(parent)\n{\n d = new Private;\n d->ver = XEP0363::vUnknown;\n d->urls << QString() << QString();\n}\n\nJT_HTTPFileUpload::~JT_HTTPFileUpload()\n{\n delete d;\n}\n\nvoid JT_HTTPFileUpload::request(const Jid &to, const QString &fname,\n quint64 fsize, const QString &ftype, XEP0363::version ver)\n{\n d->to = to;\n d->ver = ver;\n d->iq = createIQ(doc(), \"get\", to.full(), id());\n QDomElement req = doc()->createElement(\"request\");\n switch (ver)\n {\n case XEP0363::v0_2_5:\n req.setAttribute(\"xmlns\", xmlns_v0_2_5);\n req.appendChild(textTag(doc(), \"filename\", fname));\n req.appendChild(textTag(doc(), \"size\", QString::number(fsize)));\n if (!ftype.isEmpty()) {\n req.appendChild(textTag(doc(), \"content-type\", ftype));\n }\n break;\n case XEP0363::v0_3_1:\n req.setAttribute(\"xmlns\", xmlns_v0_3_1);\n req.setAttribute(\"filename\", fname);\n req.setAttribute(\"size\", fsize);\n if (!ftype.isEmpty())\n req.setAttribute(\"content-type\", ftype);\n break;\n default:\n d->ver = XEP0363::vUnknown;\n break;\n }\n d->iq.appendChild(req);\n}\n\nQString JT_HTTPFileUpload::url(UrlType t) const\n{\n return d->urls.value(t);\n}\n\nXEP0363::HttpHeaders JT_HTTPFileUpload::headers() const\n{\n return d->headers;\n}\n\nvoid JT_HTTPFileUpload::onGo()\n{\n if (d->ver != XEP0363::vUnknown)\n send(d->iq);\n}\n\nbool JT_HTTPFileUpload::take(const QDomElement &e)\n{\n if (!iqVerify(e, d->to, id()))\n return false;\n\n if (e.attribute(\"type\") != \"result\") {\n setError(e);\n return true;\n }\n\n bool correct_xmlns = false;\n QString getUrl, putUrl;\n XEP0363::HttpHeaders headers;\n const QDomElement &slot = e.firstChildElement(\"slot\");\n if (!slot.isNull()) {\n const QDomElement &get = slot.firstChildElement(\"get\");\n const QDomElement &put = slot.firstChildElement(\"put\");\n switch (d->ver)\n {\n case XEP0363::v0_2_5:\n correct_xmlns = slot.attribute(\"xmlns\") == xmlns_v0_2_5;\n getUrl = tagContent(get);\n putUrl = tagContent(put);\n break;\n case XEP0363::v0_3_1:\n correct_xmlns = slot.attribute(\"xmlns\") == xmlns_v0_3_1;\n getUrl = get.attribute(\"url\");\n if (!put.isNull()) {\n putUrl = put.attribute(\"url\");\n QDomElement he = put.firstChildElement(\"header\");\n while (!he.isNull()) {\n \/\/ only next are allowed: Authorization, Cookie, Expires\n QString header = he.attribute(\"name\").trimmed().remove(QLatin1Char('\\n'));\n QString value = he.text().trimmed().remove(QLatin1Char('\\n'));\n if (!value.isEmpty() &&\n (header.compare(QLatin1String(\"Authorization\"), Qt::CaseInsensitive) == 0 ||\n header.compare(QLatin1String(\"Cookie\"), Qt::CaseInsensitive) == 0 ||\n header.compare(QLatin1String(\"Expires\"), Qt::CaseInsensitive) == 0))\n {\n headers.append(XEP0363::HttpHeader{header, value});\n }\n he = he.nextSiblingElement(\"header\");\n }\n }\n break;\n default:\n break;\n }\n }\n if (!correct_xmlns) {\n setError(ErrInvalidResponse);\n return true;\n }\n if (!getUrl.isEmpty() && !putUrl.isEmpty()) {\n d->urls[GetUrl] = getUrl;\n d->urls[PutUrl] = putUrl;\n d->headers = headers;\n setSuccess();\n }\n else\n setError(ErrInvalidResponse, \"Either `put` or `get` URL is missing in the server's reply.\");\n return true;\n}\n\n\nclass HttpFileUploadManager::Private {\npublic:\n Client *client = nullptr;\n QPointer qnam;\n QLinkedList hosts;\n};\n\n\n\nHttpFileUploadManager::HttpFileUploadManager(Client *parent) :\n QObject(parent),\n d(new Private)\n{\n d->client = parent;\n}\n\nvoid HttpFileUploadManager::setNetworkAccessManager(QNetworkAccessManager *qnam)\n{\n d->qnam = qnam;\n}\n\nHttpFileUpload* HttpFileUploadManager::upload(const QString &srcFilename, const QString &dstFilename, const QString &mType)\n{\n auto f = new QFile(srcFilename);\n f->open(QIODevice::ReadOnly);\n auto hfu = upload(f, f->size(), dstFilename, mType);\n f->setParent(hfu);\n return hfu;\n}\n\nHttpFileUpload* HttpFileUploadManager::upload(QIODevice *source, size_t fsize, const QString &dstFilename, const QString &mType)\n{\n auto hfu = new HttpFileUpload(d->client, source, fsize, dstFilename, mType);\n hfu->setNetworkAccessManager(d->qnam);\n QMetaObject::invokeMethod(hfu, \"start\", Qt::QueuedConnection);\n return hfu;\n}\nFix clang warning:\/*\n * httpfileupload.cpp - HTTP File upload\n * Copyright (C) 2017-2019 Aleksey Andreev, Sergey Ilinykh\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"httpfileupload.h\"\n#include \"xmpp_tasks.h\"\n#include \"xmpp_xmlcommon.h\"\n#include \"xmpp_serverinfomanager.h\"\n\nusing namespace XMPP;\n\nstatic QLatin1String xmlns_v0_2_5(\"urn:xmpp:http:upload\");\nstatic QLatin1String xmlns_v0_3_1(\"urn:xmpp:http:upload:0\");\n\n\/\/----------------------------------------------------------------------------\n\/\/ HttpFileUpload\n\/\/----------------------------------------------------------------------------\nclass HttpFileUpload::Private\n{\npublic:\n HttpFileUpload::State state = State::None;\n XMPP::Client *client = nullptr;\n QIODevice *sourceDevice = nullptr;\n QPointer qnam = nullptr;\n quint64 fileSize = 0;\n QString fileName;\n QString mediaType;\n QList httpHosts;\n\n struct {\n HttpFileUpload::ErrorCode statusCode = HttpFileUpload::ErrorCode::NoError;\n QString statusString;\n QString getUrl;\n QString putUrl;\n XEP0363::HttpHeaders putHeaders;\n quint64 sizeLimit = 0;\n } result;\n};\n\nHttpFileUpload::HttpFileUpload(XMPP::Client *client, QIODevice *source, size_t fsize, const QString &dstFilename,\n const QString &mType) :\n QObject(client),\n d(new Private)\n{\n d->client = client;\n d->sourceDevice = source;\n d->fileName = dstFilename;\n d->fileSize = fsize;\n d->mediaType = mType;\n}\n\nHttpFileUpload::~HttpFileUpload()\n{\n qDebug(\"destroying\");\n}\n\nvoid HttpFileUpload::setNetworkAccessManager(QNetworkAccessManager *qnam)\n{\n d->qnam = qnam;\n}\n\nvoid HttpFileUpload::start()\n{\n if (d->state != State::None) \/\/ Attempt to start twice?\n return;\n\n setState(State::GettingSlot);\n\n d->result.statusCode = HttpFileUpload::ErrorCode::NoError;\n static QList> featureOptions;\n if (featureOptions.isEmpty()) {\n featureOptions << (QSet() << xmlns_v0_2_5) << (QSet() << xmlns_v0_3_1);\n }\n d->client->serverInfoManager()->queryServiceInfo(\n QLatin1String(\"store\"), QLatin1String(\"file\"),\n featureOptions, QRegExp(\"^(upload|http|stor|file|dis|drive).*\"), ServerInfoManager::SQ_CheckAllOnNoMatch,\n [this](const QList &items)\n {\n d->httpHosts.clear();\n for (const auto &item: items) {\n const QStringList &l = item.features().list();\n XEP0363::version ver = XEP0363::vUnknown;\n QString xmlns;\n quint64 sizeLimit = 0;\n if (l.contains(xmlns_v0_3_1)) {\n ver = XEP0363::v0_3_1;\n xmlns = xmlns_v0_3_1;\n } else if (l.contains(xmlns_v0_2_5)) {\n ver = XEP0363::v0_2_5;\n xmlns = xmlns_v0_2_5;\n }\n if (ver != XEP0363::vUnknown) {\n QList> hosts;\n const XData::Field field = item.registeredExtension(xmlns).getField(QLatin1String(\"max-file-size\"));\n if (field.isValid() && field.type() == XData::Field::Field_TextSingle)\n sizeLimit = field.value().at(0).toULongLong();\n HttpHost host;\n host.ver = ver;\n host.jid = item.jid();\n host.sizeLimit = sizeLimit;\n QVariant metaProps(d->client->serverInfoManager()->serviceMeta(host.jid, \"httpprops\"));\n if (metaProps.isValid()) {\n host.props = HostProps(metaProps.value());\n } else {\n host.props = SecureGet | SecurePut;\n if (ver == XEP0363::v0_3_1)\n host.props |= NewestVer;\n }\n int value = 0;\n if (host.props & SecureGet) value += 5;\n if (host.props & SecurePut) value += 5;\n if (host.props & NewestVer) value += 3;\n if (host.props & Failure) value -= 15;\n if (!sizeLimit || d->fileSize < sizeLimit)\n hosts.append({host,value});\n\n \/\/ no sorting in preference order. most preferred go first\n std::sort(hosts.begin(), hosts.end(), [](const auto &a, const auto &b){\n return a.second > b.second;\n });\n for (auto &hp: hosts) {\n d->httpHosts.append(hp.first);\n }\n }\n }\n \/\/d->currentHost = d->httpHosts.begin();\n if (d->httpHosts.isEmpty()) { \/\/ if empty as the last resort check all services\n d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;\n d->result.statusString = \"No suitable http upload services were found\";\n done(State::Error);\n } else {\n tryNextServer();\n }\n });\n}\n\nvoid HttpFileUpload::tryNextServer()\n{\n if (d->httpHosts.isEmpty()) { \/\/ if empty as the last resort check all services\n d->result.statusCode = HttpFileUpload::ErrorCode::NoUploadService;\n d->result.statusString = \"All http services are either non compliant or returned errors\";\n done(State::Error);\n return;\n }\n HttpHost host = d->httpHosts.takeFirst();\n d->result.sizeLimit = host.sizeLimit;\n auto jt = new JT_HTTPFileUpload(d->client->rootTask());\n connect(jt, &JT_HTTPFileUpload::finished, this, [this, jt, host]() mutable {\n if (!jt->success()) {\n host.props |= Failure;\n int code = jt->statusCode();\n if (code < 300) {\n code++; \/\/ ErrDisc and ErrTimeout. but 0 code is already occupated\n }\n d->result.statusCode = static_cast(jt->statusCode());\n d->result.statusString = jt->statusString();\n d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String(\"httpprops\"), int(host.props));\n if (d->httpHosts.isEmpty())\n done(State::Error);\n else\n tryNextServer();\n return;\n }\n\n d->result.getUrl = jt->url(JT_HTTPFileUpload::GetUrl);\n d->result.putUrl = jt->url(JT_HTTPFileUpload::PutUrl);\n d->result.putHeaders = jt->headers();\n if (d->result.getUrl.startsWith(\"https:\/\/\"))\n host.props |= SecureGet;\n else\n host.props &= ~SecureGet;\n if (d->result.putUrl.startsWith(\"https:\/\/\"))\n host.props |= SecurePut;\n else\n host.props &= ~SecurePut;\n host.props &= ~Failure;\n\n d->client->serverInfoManager()->setServiceMeta(host.jid, QLatin1String(\"httpprops\"), int(host.props));\n\n if (!d->qnam) { \/\/ w\/o network access manager, it's not more than getting slots\n done(State::Success);\n return;\n }\n\n setState(State::HttpRequest);\n \/\/ time for a http request\n QNetworkRequest req(d->result.putUrl);\n for (auto &h: d->result.putHeaders) {\n req.setRawHeader(h.name.toLatin1(), h.value.toLatin1());\n }\n auto reply = d->qnam->put(req, d->sourceDevice);\n connect(reply, &QNetworkReply::finished, this, [this, reply](){\n if (reply->error() == QNetworkReply::NoError) {\n done(State::Success);\n } else {\n d->result.statusCode = ErrorCode::HttpFailed;\n d->result.statusString = reply->errorString();\n if (d->httpHosts.isEmpty())\n done(State::Error);\n else\n tryNextServer();\n }\n reply->deleteLater();\n });\n\n }, Qt::QueuedConnection);\n jt->request(host.jid, d->fileName, d->fileSize, d->mediaType, host.ver);\n jt->go(true);\n}\n\nbool HttpFileUpload::success() const\n{\n return d->state == State::Success;\n}\n\nHttpFileUpload::ErrorCode HttpFileUpload::statusCode() const\n{\n return d->result.statusCode;\n}\n\nconst QString & HttpFileUpload::statusString() const\n{\n return d->result.statusString;\n}\n\nHttpFileUpload::HttpSlot HttpFileUpload::getHttpSlot()\n{\n HttpSlot slot;\n if (d->state == State::Success) {\n slot.get.url = d->result.getUrl;\n slot.put.url = d->result.putUrl;\n slot.put.headers = d->result.putHeaders;\n slot.limits.fileSize = d->result.sizeLimit;\n }\n return slot;\n}\n\nvoid HttpFileUpload::setState(State state)\n{\n d->state = state;\n if (state == Success) {\n d->result.statusCode = ErrorCode::NoError;\n d->result.statusString.clear();\n }\n emit stateChanged();\n}\n\nvoid HttpFileUpload::done(State state)\n{\n setState(state);\n emit finished();\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ JT_HTTPFileUpload\n\/\/----------------------------------------------------------------------------\nclass JT_HTTPFileUpload::Private\n{\npublic:\n Jid to;\n QDomElement iq;\n QStringList urls;\n XEP0363::version ver;\n XEP0363::HttpHeaders headers;\n};\n\nJT_HTTPFileUpload::JT_HTTPFileUpload(Task *parent)\n : Task(parent)\n{\n d = new Private;\n d->ver = XEP0363::vUnknown;\n d->urls << QString() << QString();\n}\n\nJT_HTTPFileUpload::~JT_HTTPFileUpload()\n{\n delete d;\n}\n\nvoid JT_HTTPFileUpload::request(const Jid &to, const QString &fname,\n quint64 fsize, const QString &ftype, XEP0363::version ver)\n{\n d->to = to;\n d->ver = ver;\n d->iq = createIQ(doc(), \"get\", to.full(), id());\n QDomElement req = doc()->createElement(\"request\");\n switch (ver)\n {\n case XEP0363::v0_2_5:\n req.setAttribute(\"xmlns\", xmlns_v0_2_5);\n req.appendChild(textTag(doc(), \"filename\", fname));\n req.appendChild(textTag(doc(), \"size\", QString::number(fsize)));\n if (!ftype.isEmpty()) {\n req.appendChild(textTag(doc(), \"content-type\", ftype));\n }\n break;\n case XEP0363::v0_3_1:\n req.setAttribute(\"xmlns\", xmlns_v0_3_1);\n req.setAttribute(\"filename\", fname);\n req.setAttribute(\"size\", fsize);\n if (!ftype.isEmpty())\n req.setAttribute(\"content-type\", ftype);\n break;\n default:\n d->ver = XEP0363::vUnknown;\n break;\n }\n d->iq.appendChild(req);\n}\n\nQString JT_HTTPFileUpload::url(UrlType t) const\n{\n return d->urls.value(t);\n}\n\nXEP0363::HttpHeaders JT_HTTPFileUpload::headers() const\n{\n return d->headers;\n}\n\nvoid JT_HTTPFileUpload::onGo()\n{\n if (d->ver != XEP0363::vUnknown)\n send(d->iq);\n}\n\nbool JT_HTTPFileUpload::take(const QDomElement &e)\n{\n if (!iqVerify(e, d->to, id()))\n return false;\n\n if (e.attribute(\"type\") != \"result\") {\n setError(e);\n return true;\n }\n\n bool correct_xmlns = false;\n QString getUrl, putUrl;\n XEP0363::HttpHeaders headers;\n const QDomElement &slot = e.firstChildElement(\"slot\");\n if (!slot.isNull()) {\n const QDomElement &get = slot.firstChildElement(\"get\");\n const QDomElement &put = slot.firstChildElement(\"put\");\n switch (d->ver)\n {\n case XEP0363::v0_2_5:\n correct_xmlns = slot.attribute(\"xmlns\") == xmlns_v0_2_5;\n getUrl = tagContent(get);\n putUrl = tagContent(put);\n break;\n case XEP0363::v0_3_1:\n correct_xmlns = slot.attribute(\"xmlns\") == xmlns_v0_3_1;\n getUrl = get.attribute(\"url\");\n if (!put.isNull()) {\n putUrl = put.attribute(\"url\");\n QDomElement he = put.firstChildElement(\"header\");\n while (!he.isNull()) {\n \/\/ only next are allowed: Authorization, Cookie, Expires\n QString header = he.attribute(\"name\").trimmed().remove(QLatin1Char('\\n'));\n QString value = he.text().trimmed().remove(QLatin1Char('\\n'));\n if (!value.isEmpty() &&\n (header.compare(QLatin1String(\"Authorization\"), Qt::CaseInsensitive) == 0 ||\n header.compare(QLatin1String(\"Cookie\"), Qt::CaseInsensitive) == 0 ||\n header.compare(QLatin1String(\"Expires\"), Qt::CaseInsensitive) == 0))\n {\n headers.append(XEP0363::HttpHeader{header, value});\n }\n he = he.nextSiblingElement(\"header\");\n }\n }\n break;\n default:\n break;\n }\n }\n if (!correct_xmlns) {\n setError(ErrInvalidResponse);\n return true;\n }\n if (!getUrl.isEmpty() && !putUrl.isEmpty()) {\n d->urls[GetUrl] = getUrl;\n d->urls[PutUrl] = putUrl;\n d->headers = headers;\n setSuccess();\n }\n else\n setError(ErrInvalidResponse, \"Either `put` or `get` URL is missing in the server's reply.\");\n return true;\n}\n\n\nclass HttpFileUploadManager::Private {\npublic:\n Client *client = nullptr;\n QPointer qnam;\n QLinkedList hosts;\n};\n\n\n\nHttpFileUploadManager::HttpFileUploadManager(Client *parent) :\n QObject(parent),\n d(new Private)\n{\n d->client = parent;\n}\n\nvoid HttpFileUploadManager::setNetworkAccessManager(QNetworkAccessManager *qnam)\n{\n d->qnam = qnam;\n}\n\nHttpFileUpload* HttpFileUploadManager::upload(const QString &srcFilename, const QString &dstFilename, const QString &mType)\n{\n auto f = new QFile(srcFilename);\n f->open(QIODevice::ReadOnly);\n auto hfu = upload(f, f->size(), dstFilename, mType);\n f->setParent(hfu);\n return hfu;\n}\n\nHttpFileUpload* HttpFileUploadManager::upload(QIODevice *source, size_t fsize, const QString &dstFilename, const QString &mType)\n{\n auto hfu = new HttpFileUpload(d->client, source, fsize, dstFilename, mType);\n hfu->setNetworkAccessManager(d->qnam);\n QMetaObject::invokeMethod(hfu, \"start\", Qt::QueuedConnection);\n return hfu;\n}\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP\n#define STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP\n\n#include \n#include \n\nnamespace stan {\n namespace math {\n \/**\n * Struct which holds static function for element-wise type promotion.\n * This specialization promotes Eigen matrix elements of different types.\n *\n * @tparam F type of input element\n * @tparam T type of output element\n *\/\n template \n struct promoter,\n Eigen::Matrix > {\n inline static void promote(const Eigen::Matrix& u,\n Eigen::Matrix& t) {\n t.resize(u.rows(), u.cols());\n for (int i = 0; i < u.size(); ++i)\n promoter::promote(u(i), t(i));\n }\n inline static Eigen::Matrix\n promote_to(const Eigen::Matrix& u) {\n Eigen::Matrix t;\n promoter,\n Eigen::Matrix\n >::promote(u, t);\n return t;\n }\n };\n\n \/**\n * Struct which holds static function for element-wise type promotion.\n * This specialization promotes Eigen matrix elements of same type.\n *\n * @tparam T type of matrix element\n *\/\n template \n struct promoter,\n Eigen::Matrix > {\n inline static void promote(const Eigen::Matrix& u,\n Eigen::Matrix& t) {\n t = u;\n }\n inline static Eigen::Matrix\n promote_to(const Eigen::Matrix& u) {\n return u;\n }\n };\n\n }\n}\n\n#endif\npromoter needs matrix specialization, called from promote_to#ifndef STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP\n#define STAN_MATH_PRIM_MAT_FUN_PROMOTER_HPP\n\n#include \n#include \n\nnamespace stan {\n namespace math {\n \/**\n * Struct which holds static function for element-wise type promotion.\n * This specialization promotes Eigen matrix elements of different types.\n *\n * @tparam F type of input element\n * @tparam T type of output element\n * @tparam R number of rows\n * @tparam C number of columns\n *\/\n template \n struct promoter,\n Eigen::Matrix > {\n inline static void promote(const Eigen::Matrix& u,\n Eigen::Matrix& t) {\n t.resize(u.rows(), u.cols());\n for (int i = 0; i < u.size(); ++i)\n promoter::promote(u(i), t(i));\n }\n inline static Eigen::Matrix\n promote_to(const Eigen::Matrix& u) {\n Eigen::Matrix t;\n promoter,\n Eigen::Matrix\n >::promote(u, t);\n return t;\n }\n };\n\n \/**\n * Struct which holds static function for element-wise type promotion.\n * This specialization promotes Eigen matrix elements of same type.\n *\n * @tparam T type of matrix element\n * @tparam R number of rows\n * @tparam C number of columns\n *\/\n template \n struct promoter,\n Eigen::Matrix > {\n inline static void promote(const Eigen::Matrix& u,\n Eigen::Matrix& t) {\n t = u;\n }\n inline static Eigen::Matrix\n promote_to(const Eigen::Matrix& u) {\n return u;\n }\n };\n\n }\n}\n\n#endif\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP\n#define STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/** \\ingroup prob_dists\n * The log of the normal density for the specified scalar(s) given\n * the specified mean(s) and deviation(s). y, mu, or sigma can\n * each be either a scalar or a vector. Any vector inputs\n * must be the same length.\n *\n *

The result log probability is defined to be the sum of the\n * log probabilities for each observation\/mean\/deviation triple.\n *\n * @tparam T_y type of scalar\n * @tparam T_loc type of location parameter\n * @tparam T_scale type of scale parameter\n * @param y (Sequence of) scalar(s).\n * @param mu (Sequence of) location parameter(s)\n * for the normal distribution.\n * @param sigma (Sequence of) scale parameters for the normal distribution.\n * @return The log of the product of the densities.\n * @throw std::domain_error if the scale is not positive.\n *\/\ntemplate * = nullptr>\ninline return_type_t normal_lpdf(const T_y& y,\n const T_loc& mu,\n const T_scale& sigma) {\n using T_partials_return = partials_return_t;\n using T_y_ref = ref_type_if_t::value, T_y>;\n using T_mu_ref = ref_type_if_t::value, T_loc>;\n using T_sigma_ref = ref_type_if_t::value, T_scale>;\n static const char* function = \"normal_lpdf\";\n check_consistent_sizes(function, \"Random variable\", y, \"Location parameter\",\n mu, \"Scale parameter\", sigma);\n T_y_ref y_ref = y;\n T_mu_ref mu_ref = mu;\n T_sigma_ref sigma_ref = sigma;\n\n decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));\n decltype(auto) mu_val = to_ref(as_value_column_array_or_scalar(mu_ref));\n decltype(auto) sigma_val = to_ref(as_value_column_array_or_scalar(sigma_ref));\n\n check_not_nan(function, \"Random variable\", y_val);\n check_finite(function, \"Location parameter\", mu_val);\n check_positive(function, \"Scale parameter\", sigma_val);\n\n if (size_zero(y, mu, sigma)) {\n return 0.0;\n }\n if (!include_summand::value) {\n return 0.0;\n }\n\n operands_and_partials ops_partials(\n y_ref, mu_ref, sigma_ref);\n\n const auto& inv_sigma\n = to_ref_if::value>(inv(sigma_val));\n const auto& y_scaled = to_ref((y_val - mu_val) * inv_sigma);\n const auto& y_scaled_sq\n = to_ref_if::value>(y_scaled * y_scaled);\n\n size_t N = max_size(y, mu, sigma);\n T_partials_return logp = -0.5 * sum(y_scaled_sq);\n if (include_summand::value) {\n logp += NEG_LOG_SQRT_TWO_PI * N;\n }\n if (include_summand::value) {\n logp -= sum(log(sigma_val)) * N \/ size(sigma);\n }\n\n if (!is_constant_all::value) {\n auto scaled_diff = to_ref_if::value\n + !is_constant_all::value\n + !is_constant_all::value\n >= 2>(inv_sigma * y_scaled);\n if (!is_constant_all::value) {\n ops_partials.edge1_.partials_ = -scaled_diff;\n }\n if (!is_constant_all::value) {\n ops_partials.edge3_.partials_ = inv_sigma * y_scaled_sq - inv_sigma;\n }\n if (!is_constant_all::value) {\n ops_partials.edge2_.partials_ = std::move(scaled_diff);\n }\n }\n return ops_partials.build(logp);\n}\n\ntemplate \ninline return_type_t normal_lpdf(const T_y& y,\n const T_loc& mu,\n const T_scale& sigma) {\n return normal_lpdf(y, mu, sigma);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nAdded some couts. All tests passed.#ifndef STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP\n#define STAN_MATH_PRIM_PROB_NORMAL_LPDF_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/** \\ingroup prob_dists\n * The log of the normal density for the specified scalar(s) given\n * the specified mean(s) and deviation(s). y, mu, or sigma can\n * each be either a scalar or a vector. Any vector inputs\n * must be the same length.\n *\n *

The result log probability is defined to be the sum of the\n * log probabilities for each observation\/mean\/deviation triple.\n *\n * @tparam T_y type of scalar\n * @tparam T_loc type of location parameter\n * @tparam T_scale type of scale parameter\n * @param y (Sequence of) scalar(s).\n * @param mu (Sequence of) location parameter(s)\n * for the normal distribution.\n * @param sigma (Sequence of) scale parameters for the normal distribution.\n * @return The log of the product of the densities.\n * @throw std::domain_error if the scale is not positive.\n *\/\ntemplate * = nullptr>\ninline return_type_t normal_lpdf(const T_y& y,\n const T_loc& mu,\n const T_scale& sigma) {\n using T_partials_return = partials_return_t;\n using T_y_ref = ref_type_if_t::value, T_y>;\n using T_mu_ref = ref_type_if_t::value, T_loc>;\n using T_sigma_ref = ref_type_if_t::value, T_scale>;\n static const char* function = \"normal_lpdf\";\n check_consistent_sizes(function, \"Random variable\", y, \"Location parameter\",\n mu, \"Scale parameter\", sigma);\n T_y_ref y_ref = y;\n T_mu_ref mu_ref = mu;\n T_sigma_ref sigma_ref = sigma;\n\n decltype(auto) y_val = to_ref(as_value_column_array_or_scalar(y_ref));\n decltype(auto) mu_val = to_ref(as_value_column_array_or_scalar(mu_ref));\n decltype(auto) sigma_val = to_ref(as_value_column_array_or_scalar(sigma_ref));\n\n check_not_nan(function, \"Random variable\", y_val);\n check_finite(function, \"Location parameter\", mu_val);\n check_positive(function, \"Scale parameter\", sigma_val);\n\n if (size_zero(y, mu, sigma)) {\n return 0.0;\n }\n if (!include_summand::value) {\n return 0.0;\n }\n\n operands_and_partials ops_partials(\n y_ref, mu_ref, sigma_ref);\n\n const auto& inv_sigma\n = to_ref_if::value>(inv(sigma_val));\n const auto& y_scaled = to_ref((y_val - mu_val) * inv_sigma);\n const auto& y_scaled_sq\n = to_ref_if::value>(y_scaled * y_scaled);\n\n size_t N = max_size(y, mu, sigma);\n T_partials_return logp = -0.5 * sum(y_scaled_sq);\n if (include_summand::value) {\n logp += NEG_LOG_SQRT_TWO_PI * N;\n }\n if (include_summand::value) {\n logp -= sum(log(sigma_val)) * N \/ size(sigma);\n }\n\n if (!is_constant_all::value) {\n auto scaled_diff = to_ref_if::value\n + !is_constant_all::value\n + !is_constant_all::value\n >= 2>(inv_sigma * y_scaled);\n if (!is_constant_all::value) {\n std::cout << \"y partial: \" << -scaled_diff << std::endl;\n ops_partials.edge1_.partials_ = -scaled_diff;\n }\n if (!is_constant_all::value) {\n std::cout << \"mu partial: \" << inv_sigma * y_scaled_sq - inv_sigma << std::endl;\n ops_partials.edge3_.partials_ = inv_sigma * y_scaled_sq - inv_sigma;\n }\n if (!is_constant_all::value) {\n std::cout << \"mu partial: \" << scaled_diff << std::endl;\n ops_partials.edge2_.partials_ = std::move(scaled_diff);\n }\n }\n return ops_partials.build(logp);\n}\n\ntemplate \ninline return_type_t normal_lpdf(const T_y& y,\n const T_loc& mu,\n const T_scale& sigma) {\n return normal_lpdf(y, mu, sigma);\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/*-----------------------------------------------------------------------------\n This source file is part of Hopsan NG\n\n Copyright (c) 2011 \n Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,\n Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack\n\n This file is provided \"as is\", with no guarantee or warranty for the\n functionality or reliability of the contents. All contents in this file is\n the original work of the copyright holders at the Division of Fluid and\n Mechatronic Systems (Flumes) at Linköping University. Modifying, using or\n redistributing any part of this file is prohibited without explicit\n permission from the copyright holders.\n-----------------------------------------------------------------------------*\/\n\n\/\/!\n\/\/! @file HydraulicCylinderQ.hpp\n\/\/! @author Robert Braun \n\/\/! @date 2010-01-21\n\/\/!\n\/\/! @brief Contains a Hydraulic Cylinder of Q type with mass load\n\/\/!\n\/\/$Id$\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ <--------------Stroke---------------> \/\/\n\/\/ \/\/\n\/\/ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX \/\/\n\/\/ X Area1 X X Area2 X X X \/\/\n\/\/ X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X \/\/\n\/\/ X x1,v1,f1 <---O X X Mass O---> x2,v2,f2 \/\/\n\/\/ X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X \/\/\n\/\/ X X X X X X \/\/\n\/\/ XXOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXOXX XXXXXXXX \/\/\n\/\/ | | \/\/\n\/\/ | | \/\/\n\/\/ V p1,q1 V p2,q2 \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef HYDRAULICCYLINDERQ_HPP_INCLUDED\n#define HYDRAULICCYLINDERQ_HPP_INCLUDED\n\n#include \n#include \"..\/..\/ComponentEssentials.h\"\n#include \"..\/..\/ComponentUtilities.h\"\n\nnamespace hopsan {\n\n \/\/!\n \/\/! @brief\n \/\/! @ingroup HydraulicComponents\n \/\/!\n class HydraulicCylinderQ : public ComponentQ\n {\n private:\n double mArea1;\n double mArea2;\n double mStroke;\n double mMass;\n double mBp;\n double mBl;\n double mKl;\n double mTao;\n SecondOrderFilter mPositionFilter;\n SecondOrderFilter mVelocityFilter;\n double posnum[3], posden[3], velnum[3], velden[3];\n double p1, q1, c1, Zc1, p2, q2, c2, Zc2, v1, cx1, Zx1, f2, x2, v2, cx2, Zx2;\n double *mpND_p1, *mpND_q1, *mpND_c1, *mpND_Zc1, *mpND_p2, *mpND_q2, *mpND_c2, *mpND_Zc2, *mpND_f2, *mpND_x2, *mpND_v2, *cmpND_x2, *mpND_Zx2;\n Port *mpP1, *mpP2, *mpP3;\n\n public:\n static Component *Creator()\n {\n return new HydraulicCylinderQ(\"CylinderQ\");\n }\n\n HydraulicCylinderQ(const std::string name) : ComponentQ(name)\n {\n mArea1 = 0.0001;\n mArea2 = 0.0001;\n mStroke = 0.01;\n mMass = 0.05;\n mBp = 0.0;\n mBl = 0;\n mKl = 1000;\n mTao = 3.0\/2.0*mTimestep; \/\/Velocity filter time constant, should be in initialize?\n\n mpP1 = addPowerPort(\"P1\", \"NodeHydraulic\");\n mpP2 = addPowerPort(\"P2\", \"NodeHydraulic\");\n mpP3 = addPowerPort(\"P3\", \"NodeMechanic\");\n\n registerParameter(\"A_1\", \"Piston Area 1\", \"[m^2]\", mArea1);\n registerParameter(\"A_2\", \"Piston Area 2\", \"[m^2]\", mArea2);\n registerParameter(\"s_l\", \"Stroke\", \"[m]\", mStroke);\n registerParameter(\"B_p\", \"Viscous Friction Coefficient of Piston\", \"[Ns\/m]\", mBp);\n registerParameter(\"m_l\", \"Inertia Load\", \"[kg]\", mMass);\n registerParameter(\"B_l\", \"Viscous Friction of Load\", \"[Ns\/m]\", mBl);\n registerParameter(\"k_l\", \"Stiffness of Load\", \"[N\/m]\", mKl);\n }\n\n\n void initialize()\n {\n \/\/Assign node data pointers\n mpND_p1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);\n mpND_q1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);\n mpND_c1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);\n mpND_Zc1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);\n mpND_p2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);\n mpND_q2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);\n mpND_c2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);\n mpND_Zc2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);\n mpND_f2 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);\n mpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);\n mpND_v2 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);\n cmpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);\n mpND_Zx2 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);\n\n \/\/Read data from nodes\n x2 = (*mpND_x2);\n v2 = (*mpND_v2);\n Zc1 = (*mpND_Zc1);\n Zc2 = (*mpND_Zc2);\n cx2 = (*cmpND_x2);\n Zx2 = (*mpND_Zx2);\n\n Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;\n\n \/\/Initialization of filters\n posnum[0] = 0.0;\n posnum[1] = 0.0;\n posnum[2] = 1.0;\n posden[0] = mMass;\n posden[1] = mBl+Zx1+Zx2;\n posden[2] = mKl;\n velnum[0] = 0.0;\n velnum[1] = 1.0;\n velnum[2] = 0.0;\n velden[0] = 0.0;\n velden[1] = mTao;\n velden[2] = 1.0;\n\n mPositionFilter.initialize(mTimestep, posnum, posden, cx2, x2, 0.0, mStroke);\n mVelocityFilter.initialize(mTimestep, velnum, velden, x2, v2);\n }\n\n\n void simulateOneTimestep()\n {\n \/\/Get variable values from nodes\n c1 = (*mpND_c1);\n Zc1 = (*mpND_Zc1);\n c2 = (*mpND_c2);\n Zc2 = (*mpND_Zc2);\n cx2 = (*cmpND_x2);\n Zx2 = (*mpND_Zx2);\n\n \/\/CylinderCtest Equations\n\n \/\/Internal mechanical port\n cx1 = mArea1*c1 - mArea2*c2;\n Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;\n\n \/\/Piston\n posden [1] = mBl+Zx1+Zx2;\n mPositionFilter.setNumDen(posnum, posden);\n mPositionFilter.update(cx1-cx2);\n x2 = mPositionFilter.value();\n\n mVelocityFilter.update(x2);\n v2 = mVelocityFilter.value();\n\n v1 = -v2;\n f2 = cx2 + Zc2*v2;\n\n \/\/Volumes\n q1 = mArea1*v1;\n q2 = mArea2*v2;\n p1 = c1 + Zc1*q1;\n p2 = c2 + Zc2*q2;\n\n \/\/Cavitation check\n if(p1 < 0.0) { p1 = 0.0; }\n if(p2 < 0.0) { p2 = 0.0; }\n\n \/\/Write new values to nodes\n (*mpND_p1) = p1;\n (*mpND_q1) = q1;\n (*mpND_p2) = p2;\n (*mpND_q2) = q2;\n (*mpND_f2) = f2;\n (*mpND_x2) = x2;\n (*mpND_v2) = v2;\n }\n };\n}\n\n#endif \/\/ HYDRAULICCYLINDERQ_HPP_INCLUDED\nchanged filter call in cylinder Q, it does not work. But, it could not had worked before either.\/*-----------------------------------------------------------------------------\n This source file is part of Hopsan NG\n\n Copyright (c) 2011 \n Mikael Axin, Robert Braun, Alessandro Dell'Amico, Björn Eriksson,\n Peter Nordin, Karl Pettersson, Petter Krus, Ingo Staack\n\n This file is provided \"as is\", with no guarantee or warranty for the\n functionality or reliability of the contents. All contents in this file is\n the original work of the copyright holders at the Division of Fluid and\n Mechatronic Systems (Flumes) at Linköping University. Modifying, using or\n redistributing any part of this file is prohibited without explicit\n permission from the copyright holders.\n-----------------------------------------------------------------------------*\/\n\n\/\/!\n\/\/! @file HydraulicCylinderQ.hpp\n\/\/! @author Robert Braun \n\/\/! @date 2010-01-21\n\/\/!\n\/\/! @brief Contains a Hydraulic Cylinder of Q type with mass load\n\/\/!\n\/\/$Id$\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ <--------------Stroke---------------> \/\/\n\/\/ \/\/\n\/\/ XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXXXX \/\/\n\/\/ X Area1 X X Area2 X X X \/\/\n\/\/ X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X \/\/\n\/\/ X x1,v1,f1 <---O X X Mass O---> x2,v2,f2 \/\/\n\/\/ X X XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX X \/\/\n\/\/ X X X X X X \/\/\n\/\/ XXOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXOXX XXXXXXXX \/\/\n\/\/ | | \/\/\n\/\/ | | \/\/\n\/\/ V p1,q1 V p2,q2 \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#ifndef HYDRAULICCYLINDERQ_HPP_INCLUDED\n#define HYDRAULICCYLINDERQ_HPP_INCLUDED\n\n#include \n#include \"..\/..\/ComponentEssentials.h\"\n#include \"..\/..\/ComponentUtilities.h\"\n\nnamespace hopsan {\n\n \/\/!\n \/\/! @brief\n \/\/! @ingroup HydraulicComponents\n \/\/!\n class HydraulicCylinderQ : public ComponentQ\n {\n private:\n double mArea1;\n double mArea2;\n double mStroke;\n double mMass;\n double mBp;\n double mBl;\n double mKl;\n double mTao;\n SecondOrderFilter mPositionFilter;\n SecondOrderFilter mVelocityFilter;\n double posnum[3], posden[3], velnum[3], velden[3];\n double p1, q1, c1, Zc1, p2, q2, c2, Zc2, v1, cx1, Zx1, f2, x2, v2, cx2, Zx2;\n double *mpND_p1, *mpND_q1, *mpND_c1, *mpND_Zc1, *mpND_p2, *mpND_q2, *mpND_c2, *mpND_Zc2, *mpND_f2, *mpND_x2, *mpND_v2, *cmpND_x2, *mpND_Zx2;\n Port *mpP1, *mpP2, *mpP3;\n\n public:\n static Component *Creator()\n {\n return new HydraulicCylinderQ(\"CylinderQ\");\n }\n\n HydraulicCylinderQ(const std::string name) : ComponentQ(name)\n {\n mArea1 = 0.0001;\n mArea2 = 0.0001;\n mStroke = 0.01;\n mMass = 0.05;\n mBp = 0.0;\n mBl = 0;\n mKl = 1000;\n mTao = 3.0\/2.0*mTimestep; \/\/Velocity filter time constant, should be in initialize?\n\n mpP1 = addPowerPort(\"P1\", \"NodeHydraulic\");\n mpP2 = addPowerPort(\"P2\", \"NodeHydraulic\");\n mpP3 = addPowerPort(\"P3\", \"NodeMechanic\");\n\n registerParameter(\"A_1\", \"Piston Area 1\", \"[m^2]\", mArea1);\n registerParameter(\"A_2\", \"Piston Area 2\", \"[m^2]\", mArea2);\n registerParameter(\"s_l\", \"Stroke\", \"[m]\", mStroke);\n registerParameter(\"B_p\", \"Viscous Friction Coefficient of Piston\", \"[Ns\/m]\", mBp);\n registerParameter(\"m_l\", \"Inertia Load\", \"[kg]\", mMass);\n registerParameter(\"B_l\", \"Viscous Friction of Load\", \"[Ns\/m]\", mBl);\n registerParameter(\"k_l\", \"Stiffness of Load\", \"[N\/m]\", mKl);\n }\n\n\n void initialize()\n {\n \/\/Assign node data pointers\n mpND_p1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);\n mpND_q1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);\n mpND_c1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);\n mpND_Zc1 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);\n mpND_p2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::PRESSURE);\n mpND_q2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::FLOW);\n mpND_c2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::WAVEVARIABLE);\n mpND_Zc2 = getSafeNodeDataPtr(mpP1, NodeHydraulic::CHARIMP);\n mpND_f2 = getSafeNodeDataPtr(mpP1, NodeMechanic::FORCE);\n mpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::POSITION);\n mpND_v2 = getSafeNodeDataPtr(mpP1, NodeMechanic::VELOCITY);\n cmpND_x2 = getSafeNodeDataPtr(mpP1, NodeMechanic::WAVEVARIABLE);\n mpND_Zx2 = getSafeNodeDataPtr(mpP1, NodeMechanic::CHARIMP);\n\n \/\/Read data from nodes\n x2 = (*mpND_x2);\n v2 = (*mpND_v2);\n Zc1 = (*mpND_Zc1);\n Zc2 = (*mpND_Zc2);\n cx2 = (*cmpND_x2);\n Zx2 = (*mpND_Zx2);\n\n Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;\n\n \/\/Initialization of filters\n posnum[0] = 0.0;\n posnum[1] = 0.0;\n posnum[2] = 1.0;\n posden[0] = mKl;\n posden[1] = mBl+Zx1+Zx2;\n posden[2] = mMass;\n velnum[0] = 0.0;\n velnum[1] = 1.0;\n velnum[2] = 0.0;\n velden[0] = 1.0;\n velden[1] = mTao;\n velden[2] = 0.0;\n\n mPositionFilter.initialize(mTimestep, posnum, posden, cx2, x2, 0.0, mStroke);\n mVelocityFilter.initialize(mTimestep, velnum, velden, x2, v2);\n }\n\n\n void simulateOneTimestep()\n {\n \/\/Get variable values from nodes\n c1 = (*mpND_c1);\n Zc1 = (*mpND_Zc1);\n c2 = (*mpND_c2);\n Zc2 = (*mpND_Zc2);\n cx2 = (*cmpND_x2);\n Zx2 = (*mpND_Zx2);\n\n \/\/CylinderCtest Equations\n\n \/\/Internal mechanical port\n cx1 = mArea1*c1 - mArea2*c2;\n Zx1 = mArea1*mArea1*Zc1 + mArea2*mArea2*Zc2-mBp;\n\n \/\/Piston\n posden [1] = mBl+Zx1+Zx2;\n mPositionFilter.setNumDen(posnum, posden);\n mPositionFilter.update(cx1-cx2);\n x2 = mPositionFilter.value();\n\n mVelocityFilter.update(x2);\n v2 = mVelocityFilter.value();\n\n v1 = -v2;\n f2 = cx2 + Zc2*v2;\n\n \/\/Volumes\n q1 = mArea1*v1;\n q2 = mArea2*v2;\n p1 = c1 + Zc1*q1;\n p2 = c2 + Zc2*q2;\n\n \/\/Cavitation check\n if(p1 < 0.0) { p1 = 0.0; }\n if(p2 < 0.0) { p2 = 0.0; }\n\n \/\/Write new values to nodes\n (*mpND_p1) = p1;\n (*mpND_q1) = q1;\n (*mpND_p2) = p2;\n (*mpND_q2) = q2;\n (*mpND_f2) = f2;\n (*mpND_x2) = x2;\n (*mpND_v2) = v2;\n }\n };\n}\n\n#endif \/\/ HYDRAULICCYLINDERQ_HPP_INCLUDED\n<|endoftext|>"} {"text":"\/\/\n\/\/ datarecovery.cpp\n\/\/ codeval1\n\/\/\n\/\/ Created by Malcolm Crum on 5\/13\/14.\n\/\/\n\/\/\n\n#include \n#include \n#include \n#include \nusing namespace std;\n\nint main(int argc, char** argv) {\n ifstream fileInput;\n fileInput.open(argv[1]);\n\n \/\/while (fileInput.peek() != EOF) {\n \n string word;\n vector words;\n fileInput >> word;\n while (word.find(';') == string::npos) {\n words.push_back(word);\n fileInput >> word;\n }\n \/\/ the last \"word\" would normally get grabbed as 'word;9'.\n \/\/ special handling is required to split it into 'word' and '9'\n int semicolonIndex = word.find(';');\n words.push_back(word.substr(0, semicolonIndex));\n cout << \"read \" << words.size() << \" words\" << endl;\n \n for (int i = 0; i < words.size(); i++) {\n cout << words[i] << \" \";\n }\n cout << endl;\n \n int value;\n vector orderedWords;\n orderedWords.resize(words.size());\n \/\/ again, special handling required to get the number out of 'word;9'\n value = atoi(word.substr(semicolonIndex, word.size()).c_str());\n orderedWords[0] = words[value];\n for(int i = 1; fileInput.peek() != '\\n'; i++) {\n fileInput >> value;\n cout << \"words[\" << value << \"] = \" << words[value] << endl;\n cout << \"words[\" << i << \"] = \" << words[i] << endl;\n orderedWords[value] = words[i];\n }\n \n for (int i = 0; i < orderedWords.size(); i++) {\n cout << orderedWords[i] << \" \";\n }\n cout << endl;\n \/\/}\n}Forgot to actually finish this one. A hard 'easy'\/\/\n\/\/ datarecovery.cpp\n\/\/ codeval1\n\/\/\n\/\/ Created by Malcolm Crum on 5\/13\/14.\n\/\/\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nvector splitString(string str) {\n vector vec;\n stringstream ss(str);\n string s;\n while (ss >> s) {\n vec.push_back(s);\n }\n return vec;\n}\n\nvector splitIntString(string str) {\n vector vec;\n stringstream ss(str);\n int i;\n while (ss >> i) {\n vec.push_back(i);\n }\n return vec;\n} \n\nint main(int argc, char** argv) {\n ifstream fileInput;\n fileInput.open(argv[1]);\n\n string line;\n while (getline(fileInput, line)) {\n \n string wordString = line.substr(0, line.find(';'));\n vector words = splitString(wordString);\n string orderString = line.substr(line.find(';') + 1);\n vector order = splitIntString(orderString);\n \n vector orderedWords(order.size() + 1);\n for (int i = 0; i < order.size(); ++i) {\n int index = order[i] - 1;\n \/\/cout << words[i] << \" \";\n orderedWords[index] = words[i];\n }\n \n int missingIndex = 1;\n for (int i = 1; i < words.size() + 1; ++i) {\n if (find(order.begin(), order.end(), i) == order.end()) {\n missingIndex = i;\n break;\n }\n }\n orderedWords[missingIndex - 1] = words.back();\n \n for (vector::iterator it = orderedWords.begin(); it != orderedWords.end(); ++it) {\n cout << *it << \" \";\n }\n cout << endl;\n }\n}<|endoftext|>"} {"text":"\/*\n * Copyright 2002-2013 Jose Fonseca\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \"getopt.h\"\n#include \"debugger.h\"\n#include \"symbols.h\"\n#include \"dialog.h\"\n#include \"errmsg.h\"\n#include \"log.h\"\n#include \"outdbg.h\"\n\n\nstatic int process_id_given = 0; \/* Whether process-id was given. *\/\nstatic int install_given = 0; \/* Whether install was given. *\/\nstatic int uninstall_given = 0; \/* Whether uninstall was given. *\/\n\n\nstatic void\nhelp(void)\n{\n MessageBoxA(NULL,\n \"Usage: drmingw [OPTIONS]\\r\\n\"\n \"\\r\\n\"\n \"Options:\\r\\n\"\n \" -h, --help\\tPrint help and exit\\r\\n\"\n \" -V, --version\\tPrint version and exit\\r\\n\"\n \" -i, --install\\tInstall as the default JIT debugger\\r\\n\"\n \" -u, --uninstall\\tUninstall\\r\\n\"\n \" -pLONG, --process-id=LONG\\r\\n\"\n \"\\t\\tAttach to the process with the given identifier\\r\\n\"\n \" -eLONG, --event=LONG\\r\\n\"\n \"\\t\\tSignal an event after process is attached\\r\\n\"\n \" -b, --breakpoint\\tTreat debug breakpoints as exceptions\\r\\n\"\n \" -v, --verbose\\tVerbose output\\r\\n\"\n \" -d, --debug\\tDebug output\\r\\n\",\n PACKAGE, MB_OK | MB_ICONINFORMATION);\n}\n\n\nstatic LSTATUS\nregSetStr(HKEY hKey, LPCSTR lpValueName, LPCSTR szStr)\n{\n return RegSetValueExA(hKey, lpValueName, 0, REG_SZ, reinterpret_cast(szStr),\n strlen(szStr) + 1);\n}\n\n\nstatic DWORD\ninstall(REGSAM samDesired)\n{\n char szFile[MAX_PATH];\n if (!GetModuleFileNameA(NULL, szFile, MAX_PATH)) {\n return GetLastError();\n }\n\n std::string debuggerCommand;\n debuggerCommand += '\"';\n debuggerCommand += szFile;\n debuggerCommand += \"\\\" -p %ld -e %ld\";\n if (debugOptions.verbose_flag)\n debuggerCommand += \" -v\";\n if (debugOptions.breakpoint_flag)\n debuggerCommand += \" -b\";\n if (debugOptions.debug_flag)\n debuggerCommand += \" -d\";\n\n HKEY hKey;\n long lRet;\n DWORD dwDisposition;\n\n lRet =\n RegCreateKeyExA(HKEY_LOCAL_MACHINE,\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AeDebug\", \/\/ The AeDebug\n \/\/ registry key.\n 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | samDesired, NULL, &hKey,\n &dwDisposition);\n if (lRet != ERROR_SUCCESS) {\n return lRet;\n }\n\n \/\/ Write the Debugger value.\n lRet = regSetStr(hKey, \"Debugger\", debuggerCommand.c_str());\n if (lRet == ERROR_SUCCESS) {\n \/\/ Write the Auto value.\n lRet = regSetStr(hKey, \"Auto\", \"1\");\n }\n\n \/\/ Close the key no matter what happened.\n RegCloseKey(hKey);\n\n return lRet;\n}\n\n\nstatic DWORD\nuninstall(REGSAM samDesired)\n{\n HKEY hKey;\n long lRet;\n\n lRet =\n RegOpenKeyExA(HKEY_LOCAL_MACHINE,\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AeDebug\", \/\/ The AeDebug\n \/\/ registry key.\n 0, KEY_ALL_ACCESS | samDesired, &hKey);\n if (lRet != ERROR_SUCCESS) {\n return lRet;\n }\n\n \/\/ Write the Debugger value.\n lRet = regSetStr(hKey, \"Debugger\", \"\");\n\n \/\/ Leave Auto value as \"1\". It is the default\n \/\/ (https:\/\/docs.microsoft.com\/en-us\/windows\/desktop\/Debug\/configuring-automatic-debugging)\n \/\/ and setting it to \"0\" doesn't seem to work as documented on Windows 10\n \/\/ (https:\/\/github.com\/jrfonseca\/drmingw\/issues\/38)\n\n \/\/ Close the key no matter what happened.\n RegCloseKey(hKey);\n\n return lRet;\n}\n\n\nstatic DWORD\ngetProcessIdByName(const char *szProcessName)\n{\n DWORD dwProcessId = 0;\n\n HANDLE hProcessSnap;\n hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n if (hProcessSnap != INVALID_HANDLE_VALUE) {\n PROCESSENTRY32 pe32;\n pe32.dwSize = sizeof pe32;\n if (Process32First(hProcessSnap, &pe32)) {\n do {\n if (stricmp(szProcessName, pe32.szExeFile) == 0) {\n dwProcessId = pe32.th32ProcessID;\n break;\n }\n } while (Process32Next(hProcessSnap, &pe32));\n }\n CloseHandle(hProcessSnap);\n }\n\n return dwProcessId;\n}\n\n\nstatic void\ndebugThread(void *arg)\n{\n DWORD dwProcessId = (DWORD)(UINT_PTR)arg;\n\n \/\/ attach debuggee\n if (!DebugActiveProcess(dwProcessId)) {\n ErrorMessageBox(\"DebugActiveProcess: %s\", LastErrorMessage());\n return;\n }\n\n setDumpCallback(appendText);\n\n SetSymOptions(debugOptions.debug_flag);\n\n DebugMainLoop();\n}\n\n\nint\nmain(int argc, char **argv)\n{\n DWORD dwProcessId = 0;\n int c; \/* Character of the parsed option. *\/\n\n debugOptions.first_chance = 1;\n\n while (1) {\n int option_index = 0;\n static const struct option long_options[] = {{\"help\", 0, NULL, 'h'},\n {\"version\", 0, NULL, 'V'},\n {\"install\", 0, NULL, 'i'},\n {\"uninstall\", 0, NULL, 'u'},\n {\"process-id\", 1, NULL, 'p'},\n {\"event\", 1, NULL, 'e'},\n {\"tid\", 1, NULL, 't'},\n {\"breakpoint\", 0, NULL, 'b'},\n {\"verbose\", 0, NULL, 'v'},\n {\"debug\", 0, NULL, 'd'},\n {NULL, 0, NULL, 0}};\n\n c = getopt_long_only(argc, argv, \"?hViup:e:t:vbd\", long_options, &option_index);\n\n if (c == -1)\n break; \/* Exit from `while (1)' loop. *\/\n\n switch (c) {\n case '?':\n if (optopt != '?') {\n \/* Invalid option. *\/\n char szErrMsg[512];\n sprintf(szErrMsg, \"Invalid option '%c'\", optopt);\n MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);\n return 1;\n }\n \/* fall-through *\/\n case 'h': \/* Print help and exit. *\/\n help();\n return 0;\n\n case 'V': \/* Print version and exit. *\/\n MessageBoxA(NULL, PACKAGE \" \" VERSION, PACKAGE, MB_OK | MB_ICONINFORMATION);\n return 0;\n\n case 'i': \/* Install as the default JIT debugger. *\/\n if (uninstall_given) {\n MessageBoxA(NULL, \"conficting options `--uninstall' (`-u') and `--install' (`-i')\",\n PACKAGE, MB_OK | MB_ICONSTOP);\n return 0;\n }\n install_given = 1;\n break;\n\n case 'u': \/* Uninstall. *\/\n if (install_given) {\n MessageBoxA(NULL, \"conficting options `--install' (`-i') and `--uninstall' (`-u')\",\n PACKAGE, MB_OK | MB_ICONSTOP);\n return 0;\n }\n uninstall_given = 1;\n break;\n\n case 'p': \/* Attach to the process with the given identifier. *\/\n if (process_id_given) {\n MessageBoxA(NULL, \"`--process-id' (`-p') option redeclared\", PACKAGE,\n MB_OK | MB_ICONSTOP);\n return 1;\n }\n process_id_given = 1;\n if (optarg[0] >= '0' && optarg[0] <= '9') {\n dwProcessId = strtoul(optarg, NULL, 0);\n } else {\n debugOptions.breakpoint_flag = true;\n dwProcessId = getProcessIdByName(optarg);\n }\n if (!dwProcessId) {\n MessageBoxA(NULL, \"Invalid process\", PACKAGE, MB_OK | MB_ICONSTOP);\n return 1;\n }\n break;\n\n case 'e': \/* Signal an event after process is attached. *\/\n if (debugOptions.hEvent) {\n MessageBoxA(NULL, \"`--event' (`-e') option redeclared\", PACKAGE,\n MB_OK | MB_ICONSTOP);\n return 1;\n }\n debugOptions.hEvent = (HANDLE)(INT_PTR)atol(optarg);\n break;\n\n case 't': {\n \/* Thread id. Used when debugging WinRT apps. *\/\n debugOptions.dwThreadId = strtoul(optarg, NULL, 0);\n break;\n }\n\n case 'b': \/* Treat debug breakpoints as exceptions *\/\n debugOptions.breakpoint_flag = true;\n break;\n\n case 'v': \/* Verbose output. *\/\n debugOptions.verbose_flag = true;\n break;\n\n case 'd': \/* Debug output. *\/\n debugOptions.debug_flag = true;\n break;\n\n default: \/* bug: option not considered. *\/\n {\n char szErrMsg[512];\n sprintf(szErrMsg, \"Unexpected option '-%c'\", c);\n MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);\n return 1;\n }\n }\n }\n\n if (install_given) {\n DWORD dwRet = install(0);\n#if defined(_WIN64)\n if (dwRet == ERROR_SUCCESS) {\n dwRet = install(KEY_WOW64_32KEY);\n }\n#endif\n if (dwRet != ERROR_SUCCESS) {\n MessageBoxA(NULL,\n dwRet == ERROR_ACCESS_DENIED\n ? \"You must have administrator privileges to install Dr. Mingw as the \"\n \"default application debugger\"\n : \"Unexpected error when trying to install Dr. Mingw as the default \"\n \"application debugger\",\n \"DrMingw\", MB_OK | MB_ICONERROR);\n return 1;\n }\n MessageBoxA(NULL, \"Dr. Mingw has been installed as the default application debugger\",\n \"DrMingw\", MB_OK | MB_ICONINFORMATION);\n return 0;\n }\n\n if (uninstall_given) {\n DWORD dwRet = uninstall(0);\n#if defined(_WIN64)\n if (dwRet == ERROR_SUCCESS) {\n dwRet = uninstall(KEY_WOW64_32KEY);\n }\n#endif\n if (dwRet != ERROR_SUCCESS) {\n MessageBoxA(NULL,\n dwRet == ERROR_ACCESS_DENIED\n ? \"You must have administrator privileges to uninstall Dr. Mingw as \"\n \"the default application debugger\"\n : \"Unexpected error when trying to uninstall Dr. Mingw as the default \"\n \"application debugger\",\n \"DrMingw\", MB_OK | MB_ICONERROR);\n return 1;\n }\n MessageBoxA(NULL, \"Dr. Mingw has been uninstalled\", \"DrMingw\", MB_OK | MB_ICONINFORMATION);\n return 0;\n }\n\n if (process_id_given) {\n SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\n\n if (!ObtainSeDebugPrivilege())\n MessageBoxA(NULL,\n \"An error occurred while obtaining debug privileges.\\nDrMingw will not \"\n \"debug system processes.\",\n \"DrMingw\", MB_OK | MB_ICONERROR);\n\n createDialog();\n\n _beginthread(debugThread, 0, (void *)(UINT_PTR)dwProcessId);\n\n return mainLoop();\n } else {\n help();\n }\n\n return 0;\n}\nShow version and copyright in Dr. Mingw usage dialog\/*\n * Copyright 2002-2013 Jose Fonseca\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n *\/\n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \"getopt.h\"\n#include \"debugger.h\"\n#include \"symbols.h\"\n#include \"dialog.h\"\n#include \"errmsg.h\"\n#include \"log.h\"\n#include \"outdbg.h\"\n#include \"version.h\"\n\n\nstatic int process_id_given = 0; \/* Whether process-id was given. *\/\nstatic int install_given = 0; \/* Whether install was given. *\/\nstatic int uninstall_given = 0; \/* Whether uninstall was given. *\/\n\n\nstatic void\nhelp(void)\n{\n MessageBoxA(NULL,\n VER_PRODUCTNAME_STR \" version \" VER_PRODUCTVERSION_STR \"\\r\\n\"\n VER_LEGALCOPYRIGHT_STR \"\\r\\n\"\n \"\\r\\n\"\n \"Usage: drmingw [OPTIONS]\\r\\n\"\n \"\\r\\n\"\n \"Options:\\r\\n\"\n \" -h, --help\\tPrint help and exit\\r\\n\"\n \" -V, --version\\tPrint version and exit\\r\\n\"\n \" -i, --install\\tInstall as the default JIT debugger\\r\\n\"\n \" -u, --uninstall\\tUninstall\\r\\n\"\n \" -pLONG, --process-id=LONG\\r\\n\"\n \"\\t\\tAttach to the process with the given identifier\\r\\n\"\n \" -eLONG, --event=LONG\\r\\n\"\n \"\\t\\tSignal an event after process is attached\\r\\n\"\n \" -b, --breakpoint\\tTreat debug breakpoints as exceptions\\r\\n\"\n \" -v, --verbose\\tVerbose output\\r\\n\"\n \" -d, --debug\\tDebug output\\r\\n\",\n PACKAGE, MB_OK | MB_ICONINFORMATION);\n}\n\n\nstatic LSTATUS\nregSetStr(HKEY hKey, LPCSTR lpValueName, LPCSTR szStr)\n{\n return RegSetValueExA(hKey, lpValueName, 0, REG_SZ, reinterpret_cast(szStr),\n strlen(szStr) + 1);\n}\n\n\nstatic DWORD\ninstall(REGSAM samDesired)\n{\n char szFile[MAX_PATH];\n if (!GetModuleFileNameA(NULL, szFile, MAX_PATH)) {\n return GetLastError();\n }\n\n std::string debuggerCommand;\n debuggerCommand += '\"';\n debuggerCommand += szFile;\n debuggerCommand += \"\\\" -p %ld -e %ld\";\n if (debugOptions.verbose_flag)\n debuggerCommand += \" -v\";\n if (debugOptions.breakpoint_flag)\n debuggerCommand += \" -b\";\n if (debugOptions.debug_flag)\n debuggerCommand += \" -d\";\n\n HKEY hKey;\n long lRet;\n DWORD dwDisposition;\n\n lRet =\n RegCreateKeyExA(HKEY_LOCAL_MACHINE,\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AeDebug\", \/\/ The AeDebug\n \/\/ registry key.\n 0, NULL, REG_OPTION_NON_VOLATILE, KEY_WRITE | samDesired, NULL, &hKey,\n &dwDisposition);\n if (lRet != ERROR_SUCCESS) {\n return lRet;\n }\n\n \/\/ Write the Debugger value.\n lRet = regSetStr(hKey, \"Debugger\", debuggerCommand.c_str());\n if (lRet == ERROR_SUCCESS) {\n \/\/ Write the Auto value.\n lRet = regSetStr(hKey, \"Auto\", \"1\");\n }\n\n \/\/ Close the key no matter what happened.\n RegCloseKey(hKey);\n\n return lRet;\n}\n\n\nstatic DWORD\nuninstall(REGSAM samDesired)\n{\n HKEY hKey;\n long lRet;\n\n lRet =\n RegOpenKeyExA(HKEY_LOCAL_MACHINE,\n \"Software\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\\\\AeDebug\", \/\/ The AeDebug\n \/\/ registry key.\n 0, KEY_ALL_ACCESS | samDesired, &hKey);\n if (lRet != ERROR_SUCCESS) {\n return lRet;\n }\n\n \/\/ Write the Debugger value.\n lRet = regSetStr(hKey, \"Debugger\", \"\");\n\n \/\/ Leave Auto value as \"1\". It is the default\n \/\/ (https:\/\/docs.microsoft.com\/en-us\/windows\/desktop\/Debug\/configuring-automatic-debugging)\n \/\/ and setting it to \"0\" doesn't seem to work as documented on Windows 10\n \/\/ (https:\/\/github.com\/jrfonseca\/drmingw\/issues\/38)\n\n \/\/ Close the key no matter what happened.\n RegCloseKey(hKey);\n\n return lRet;\n}\n\n\nstatic DWORD\ngetProcessIdByName(const char *szProcessName)\n{\n DWORD dwProcessId = 0;\n\n HANDLE hProcessSnap;\n hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);\n if (hProcessSnap != INVALID_HANDLE_VALUE) {\n PROCESSENTRY32 pe32;\n pe32.dwSize = sizeof pe32;\n if (Process32First(hProcessSnap, &pe32)) {\n do {\n if (stricmp(szProcessName, pe32.szExeFile) == 0) {\n dwProcessId = pe32.th32ProcessID;\n break;\n }\n } while (Process32Next(hProcessSnap, &pe32));\n }\n CloseHandle(hProcessSnap);\n }\n\n return dwProcessId;\n}\n\n\nstatic void\ndebugThread(void *arg)\n{\n DWORD dwProcessId = (DWORD)(UINT_PTR)arg;\n\n \/\/ attach debuggee\n if (!DebugActiveProcess(dwProcessId)) {\n ErrorMessageBox(\"DebugActiveProcess: %s\", LastErrorMessage());\n return;\n }\n\n setDumpCallback(appendText);\n\n SetSymOptions(debugOptions.debug_flag);\n\n DebugMainLoop();\n}\n\n\nint\nmain(int argc, char **argv)\n{\n DWORD dwProcessId = 0;\n int c; \/* Character of the parsed option. *\/\n\n debugOptions.first_chance = 1;\n\n while (1) {\n int option_index = 0;\n static const struct option long_options[] = {{\"help\", 0, NULL, 'h'},\n {\"version\", 0, NULL, 'V'},\n {\"install\", 0, NULL, 'i'},\n {\"uninstall\", 0, NULL, 'u'},\n {\"process-id\", 1, NULL, 'p'},\n {\"event\", 1, NULL, 'e'},\n {\"tid\", 1, NULL, 't'},\n {\"breakpoint\", 0, NULL, 'b'},\n {\"verbose\", 0, NULL, 'v'},\n {\"debug\", 0, NULL, 'd'},\n {NULL, 0, NULL, 0}};\n\n c = getopt_long_only(argc, argv, \"?hViup:e:t:vbd\", long_options, &option_index);\n\n if (c == -1)\n break; \/* Exit from `while (1)' loop. *\/\n\n switch (c) {\n case '?':\n if (optopt != '?') {\n \/* Invalid option. *\/\n char szErrMsg[512];\n sprintf(szErrMsg, \"Invalid option '%c'\", optopt);\n MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);\n return 1;\n }\n \/* fall-through *\/\n case 'h': \/* Print help and exit. *\/\n help();\n return 0;\n\n case 'V': \/* Print version and exit. *\/\n MessageBoxA(NULL, PACKAGE \" \" VERSION, PACKAGE, MB_OK | MB_ICONINFORMATION);\n return 0;\n\n case 'i': \/* Install as the default JIT debugger. *\/\n if (uninstall_given) {\n MessageBoxA(NULL, \"conficting options `--uninstall' (`-u') and `--install' (`-i')\",\n PACKAGE, MB_OK | MB_ICONSTOP);\n return 0;\n }\n install_given = 1;\n break;\n\n case 'u': \/* Uninstall. *\/\n if (install_given) {\n MessageBoxA(NULL, \"conficting options `--install' (`-i') and `--uninstall' (`-u')\",\n PACKAGE, MB_OK | MB_ICONSTOP);\n return 0;\n }\n uninstall_given = 1;\n break;\n\n case 'p': \/* Attach to the process with the given identifier. *\/\n if (process_id_given) {\n MessageBoxA(NULL, \"`--process-id' (`-p') option redeclared\", PACKAGE,\n MB_OK | MB_ICONSTOP);\n return 1;\n }\n process_id_given = 1;\n if (optarg[0] >= '0' && optarg[0] <= '9') {\n dwProcessId = strtoul(optarg, NULL, 0);\n } else {\n debugOptions.breakpoint_flag = true;\n dwProcessId = getProcessIdByName(optarg);\n }\n if (!dwProcessId) {\n MessageBoxA(NULL, \"Invalid process\", PACKAGE, MB_OK | MB_ICONSTOP);\n return 1;\n }\n break;\n\n case 'e': \/* Signal an event after process is attached. *\/\n if (debugOptions.hEvent) {\n MessageBoxA(NULL, \"`--event' (`-e') option redeclared\", PACKAGE,\n MB_OK | MB_ICONSTOP);\n return 1;\n }\n debugOptions.hEvent = (HANDLE)(INT_PTR)atol(optarg);\n break;\n\n case 't': {\n \/* Thread id. Used when debugging WinRT apps. *\/\n debugOptions.dwThreadId = strtoul(optarg, NULL, 0);\n break;\n }\n\n case 'b': \/* Treat debug breakpoints as exceptions *\/\n debugOptions.breakpoint_flag = true;\n break;\n\n case 'v': \/* Verbose output. *\/\n debugOptions.verbose_flag = true;\n break;\n\n case 'd': \/* Debug output. *\/\n debugOptions.debug_flag = true;\n break;\n\n default: \/* bug: option not considered. *\/\n {\n char szErrMsg[512];\n sprintf(szErrMsg, \"Unexpected option '-%c'\", c);\n MessageBoxA(NULL, szErrMsg, PACKAGE, MB_OK | MB_ICONSTOP);\n return 1;\n }\n }\n }\n\n if (install_given) {\n DWORD dwRet = install(0);\n#if defined(_WIN64)\n if (dwRet == ERROR_SUCCESS) {\n dwRet = install(KEY_WOW64_32KEY);\n }\n#endif\n if (dwRet != ERROR_SUCCESS) {\n MessageBoxA(NULL,\n dwRet == ERROR_ACCESS_DENIED\n ? \"You must have administrator privileges to install Dr. Mingw as the \"\n \"default application debugger\"\n : \"Unexpected error when trying to install Dr. Mingw as the default \"\n \"application debugger\",\n \"DrMingw\", MB_OK | MB_ICONERROR);\n return 1;\n }\n MessageBoxA(NULL, \"Dr. Mingw has been installed as the default application debugger\",\n \"DrMingw\", MB_OK | MB_ICONINFORMATION);\n return 0;\n }\n\n if (uninstall_given) {\n DWORD dwRet = uninstall(0);\n#if defined(_WIN64)\n if (dwRet == ERROR_SUCCESS) {\n dwRet = uninstall(KEY_WOW64_32KEY);\n }\n#endif\n if (dwRet != ERROR_SUCCESS) {\n MessageBoxA(NULL,\n dwRet == ERROR_ACCESS_DENIED\n ? \"You must have administrator privileges to uninstall Dr. Mingw as \"\n \"the default application debugger\"\n : \"Unexpected error when trying to uninstall Dr. Mingw as the default \"\n \"application debugger\",\n \"DrMingw\", MB_OK | MB_ICONERROR);\n return 1;\n }\n MessageBoxA(NULL, \"Dr. Mingw has been uninstalled\", \"DrMingw\", MB_OK | MB_ICONINFORMATION);\n return 0;\n }\n\n if (process_id_given) {\n SetErrorMode(SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX | SEM_NOOPENFILEERRORBOX);\n\n if (!ObtainSeDebugPrivilege())\n MessageBoxA(NULL,\n \"An error occurred while obtaining debug privileges.\\nDrMingw will not \"\n \"debug system processes.\",\n \"DrMingw\", MB_OK | MB_ICONERROR);\n\n createDialog();\n\n _beginthread(debugThread, 0, (void *)(UINT_PTR)dwProcessId);\n\n return mainLoop();\n } else {\n help();\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*********************************************************************\n * node-dvbtee for Node.js\n *\n * Copyright (c) 2017 Michael Ira Krufky \n *\n * MIT License \n *\n * See https:\/\/github.com\/mkrufky\/node-dvbtee for more information\n ********************************************************************\/\n\n#include \n#include \"dvbtee-parser.h\" \/\/ NOLINT(build\/include)\n\nTableData::TableData(const uint8_t &tableId,\n const std::string &decoderName,\n const std::string &json)\n: tableId(tableId)\n, decoderName(decoderName)\n, json(json)\n{}\n\nTableData::TableData()\n : tableId(0)\n{}\n\nTableData::TableData(const TableData &t)\n : tableId(t.tableId)\n , decoderName(t.decoderName)\n , json(t.json)\n{}\n\nTableData &TableData::operator=(const TableData &cSource) {\n if (this == &cSource)\n return *this;\n\n tableId = cSource.tableId;\n decoderName = cSource.decoderName;\n json = cSource.json;\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNan::Persistent dvbteeParser::constructor;\n\ndvbteeParser::dvbteeParser() {\n}\n\ndvbteeParser::~dvbteeParser() {\n}\n\nvoid dvbteeParser::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE exports) {\n Nan::HandleScope scope;\n\n v8::Local tpl = Nan::New(New);\n tpl->SetClassName(Nan::New(\"Parser\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(tpl, \"reset\", reset);\n Nan::SetPrototypeMethod(tpl, \"feed\", feed);\n Nan::SetPrototypeMethod(tpl, \"enableEttCollection\", enableEttCollection);\n\n constructor.Reset(tpl->GetFunction());\n exports->Set(Nan::New(\"Parser\").ToLocalChecked(), tpl->GetFunction());\n}\n\nvoid dvbteeParser::New(const Nan::FunctionCallbackInfo& info) {\n if (info.IsConstructCall()) {\n \/\/ Invoked as constructor: `new dvbteeParser(...)`\n dvbteeParser* obj = new dvbteeParser();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ Invoked as plain function `dvbteeParser(...)`, turn into construct call.\n const int argc = 0;\n v8::Local argv[argc] = { };\n v8::Local cons = Nan::New(constructor);\n info.GetReturnValue().Set(cons->NewInstance(argc, argv));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid dvbteeParser::enableEttCollection(\n const Nan::FunctionCallbackInfo& info) {\n dvbteeParser* obj = ObjectWrap::Unwrap(info.Holder());\n\n obj->m_parser.enable_ett_collection();\n\n info.GetReturnValue().Set(info.Holder());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ResetWorker : public Nan::AsyncWorker {\n public:\n ResetWorker(Nan::Callback *callback,\n const Nan::FunctionCallbackInfo& info)\n : Nan::AsyncWorker(callback) {\n m_obj = Nan::ObjectWrap::Unwrap(info.Holder());\n }\n ~ResetWorker() {\n }\n\n void Execute () {\n m_obj->m_parser.cleanup();\n m_obj->m_parser.reset();\n }\n\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local argv[] = {\n Nan::Null()\n , Nan::New(0)\n };\n\n callback->Call(2, argv);\n }\n\n private:\n dvbteeParser* m_obj;\n};\n\nvoid dvbteeParser::reset(const Nan::FunctionCallbackInfo& info) {\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As()\n );\n Nan::AsyncQueueWorker(new ResetWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap(info.Holder());\n\n obj->m_parser.cleanup();\n obj->m_parser.reset();\n\n info.GetReturnValue().Set(info.Holder());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass FeedWorker: public Nan::AsyncProgressQueueWorker {\n public:\n FeedWorker(Nan::Callback *callback,\n Nan::Callback *progress,\n const Nan::FunctionCallbackInfo& info)\n : Nan::AsyncProgressQueueWorker(callback)\n , m_cb_progress(progress)\n , m_buf(NULL)\n , m_buf_len(0)\n , m_ret(-1) {\n m_obj = Nan::ObjectWrap::Unwrap(info.Holder());\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n const char *key = \"buf\";\n SaveToPersistent(key, info[0]);\n Nan::MaybeLocal mbBuf =\n Nan::To(GetFromPersistent(key));\n\n if (!mbBuf.IsEmpty()) {\n m_buf = node::Buffer::Data(mbBuf.ToLocalChecked());\n m_buf_len = info[1]->Uint32Value();\n }\n }\n }\n ~FeedWorker() {\n }\n\n void Execute(const AsyncProgressQueueWorker::ExecutionProgress& progress) {\n if ((m_buf) && (m_buf_len)) {\n\n Watcher watch(m_obj->m_parser, progress);\n\n m_ret = m_obj->m_parser.feed(\n m_buf_len, reinterpret_cast(m_buf)\n );\n }\n if (m_ret < 0) {\n SetErrorMessage(\"invalid buffer \/ length\");\n }\n }\n\n void HandleProgressCallback(const TableData *async_data, size_t count) {\n Nan::HandleScope scope;\n\n if (!m_cb_progress->IsEmpty()) {\n for (unsigned int i = 0; i < count; i++) {\n const TableData *data = &async_data[i];\n\n Nan::MaybeLocal jsonStr = Nan::New(data->json);\n if (!jsonStr.IsEmpty()) {\n Nan::MaybeLocal jsonVal =\n NanJSON.Parse(jsonStr.ToLocalChecked());\n\n if (!jsonVal.IsEmpty()) {\n Nan::MaybeLocal decoderName =\n Nan::New(data->decoderName);\n\n v8::Local decoderNameArg;\n if (decoderName.IsEmpty())\n decoderNameArg = Nan::Null();\n else\n decoderNameArg = decoderName.ToLocalChecked();\n\n v8::Local argv[] = {\n Nan::New(data->tableId),\n decoderNameArg,\n jsonVal.ToLocalChecked()\n };\n\n m_cb_progress->Call(3, argv);\n }\n }\n }\n }\n }\n\n void HandleOKCallback() {\n Nan::HandleScope scope;\n\n v8::Local argv[] = {\n Nan::Null()\n , Nan::New(m_ret)\n };\n\n callback->Call(2, argv);\n }\n\n private:\n Nan::Callback *m_cb_progress;\n Nan::JSON NanJSON;\n const AsyncProgressQueueWorker::ExecutionProgress *m_progress;\n dvbteeParser* m_obj;\n char* m_buf;\n unsigned int m_buf_len;\n int m_ret;\n\n class Watcher: public dvbtee::decode::TableWatcher {\n public:\n explicit Watcher(parse& p, const AsyncProgressQueueWorker::ExecutionProgress& progress)\n : m_parser(p)\n , m_progress(progress) {\n m_parser.subscribeTables(this);\n }\n ~Watcher() {\n m_parser.subscribeTables(NULL);\n }\n\n void updateTable(uint8_t tId, dvbtee::decode::Table *table) {\n m_progress.Send(\n new TableData(table->getTableid(),\n table->getDecoderName(),\n table->toJson()), 1\n );\n }\n\n private:\n parse& m_parser;\n const AsyncProgressQueueWorker::ExecutionProgress& m_progress;\n };\n};\n\nvoid dvbteeParser::feed(const Nan::FunctionCallbackInfo& info) {\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 1) && (info[lastArg]->IsFunction()) &&\n (info[lastArg - 1]->IsFunction())) {\n Nan::Callback *progress = new Nan::Callback(\n info[lastArg - 1].As()\n );\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As()\n );\n Nan::AsyncQueueWorker(new FeedWorker(callback, progress, info));\n\n } else {\n info.GetReturnValue().Set(Nan::New(-1));\n }\n}\nFeedWorker: Watcher takes `this` FeedWorker\/*********************************************************************\n * node-dvbtee for Node.js\n *\n * Copyright (c) 2017 Michael Ira Krufky \n *\n * MIT License \n *\n * See https:\/\/github.com\/mkrufky\/node-dvbtee for more information\n ********************************************************************\/\n\n#include \n#include \"dvbtee-parser.h\" \/\/ NOLINT(build\/include)\n\nTableData::TableData(const uint8_t &tableId,\n const std::string &decoderName,\n const std::string &json)\n: tableId(tableId)\n, decoderName(decoderName)\n, json(json)\n{}\n\nTableData::TableData()\n : tableId(0)\n{}\n\nTableData::TableData(const TableData &t)\n : tableId(t.tableId)\n , decoderName(t.decoderName)\n , json(t.json)\n{}\n\nTableData &TableData::operator=(const TableData &cSource) {\n if (this == &cSource)\n return *this;\n\n tableId = cSource.tableId;\n decoderName = cSource.decoderName;\n json = cSource.json;\n\n return *this;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nNan::Persistent dvbteeParser::constructor;\n\ndvbteeParser::dvbteeParser() {\n}\n\ndvbteeParser::~dvbteeParser() {\n}\n\nvoid dvbteeParser::Init(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE exports) {\n Nan::HandleScope scope;\n\n v8::Local tpl = Nan::New(New);\n tpl->SetClassName(Nan::New(\"Parser\").ToLocalChecked());\n tpl->InstanceTemplate()->SetInternalFieldCount(1);\n\n Nan::SetPrototypeMethod(tpl, \"reset\", reset);\n Nan::SetPrototypeMethod(tpl, \"feed\", feed);\n Nan::SetPrototypeMethod(tpl, \"enableEttCollection\", enableEttCollection);\n\n constructor.Reset(tpl->GetFunction());\n exports->Set(Nan::New(\"Parser\").ToLocalChecked(), tpl->GetFunction());\n}\n\nvoid dvbteeParser::New(const Nan::FunctionCallbackInfo& info) {\n if (info.IsConstructCall()) {\n \/\/ Invoked as constructor: `new dvbteeParser(...)`\n dvbteeParser* obj = new dvbteeParser();\n obj->Wrap(info.This());\n info.GetReturnValue().Set(info.This());\n } else {\n \/\/ Invoked as plain function `dvbteeParser(...)`, turn into construct call.\n const int argc = 0;\n v8::Local argv[argc] = { };\n v8::Local cons = Nan::New(constructor);\n info.GetReturnValue().Set(cons->NewInstance(argc, argv));\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid dvbteeParser::enableEttCollection(\n const Nan::FunctionCallbackInfo& info) {\n dvbteeParser* obj = ObjectWrap::Unwrap(info.Holder());\n\n obj->m_parser.enable_ett_collection();\n\n info.GetReturnValue().Set(info.Holder());\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass ResetWorker : public Nan::AsyncWorker {\n public:\n ResetWorker(Nan::Callback *callback,\n const Nan::FunctionCallbackInfo& info)\n : Nan::AsyncWorker(callback) {\n m_obj = Nan::ObjectWrap::Unwrap(info.Holder());\n }\n ~ResetWorker() {\n }\n\n void Execute () {\n m_obj->m_parser.cleanup();\n m_obj->m_parser.reset();\n }\n\n void HandleOKCallback () {\n Nan::HandleScope scope;\n\n v8::Local argv[] = {\n Nan::Null()\n , Nan::New(0)\n };\n\n callback->Call(2, argv);\n }\n\n private:\n dvbteeParser* m_obj;\n};\n\nvoid dvbteeParser::reset(const Nan::FunctionCallbackInfo& info) {\n \/\/ If a callback function is supplied, this method will run async\n \/\/ otherwise, it will run synchronous\n\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 0) && (info[lastArg]->IsFunction())) {\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As()\n );\n Nan::AsyncQueueWorker(new ResetWorker(callback, info));\n\n } else {\n dvbteeParser* obj = ObjectWrap::Unwrap(info.Holder());\n\n obj->m_parser.cleanup();\n obj->m_parser.reset();\n\n info.GetReturnValue().Set(info.Holder());\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass FeedWorker: public Nan::AsyncProgressQueueWorker {\n public:\n FeedWorker(Nan::Callback *callback,\n Nan::Callback *progress,\n const Nan::FunctionCallbackInfo& info)\n : Nan::AsyncProgressQueueWorker(callback)\n , m_cb_progress(progress)\n , m_buf(NULL)\n , m_buf_len(0)\n , m_ret(-1) {\n m_obj = Nan::ObjectWrap::Unwrap(info.Holder());\n\n if ((info[0]->IsObject()) && (info[1]->IsNumber())) {\n const char *key = \"buf\";\n SaveToPersistent(key, info[0]);\n Nan::MaybeLocal mbBuf =\n Nan::To(GetFromPersistent(key));\n\n if (!mbBuf.IsEmpty()) {\n m_buf = node::Buffer::Data(mbBuf.ToLocalChecked());\n m_buf_len = info[1]->Uint32Value();\n }\n }\n }\n ~FeedWorker() {\n }\n\n void Execute(const AsyncProgressQueueWorker::ExecutionProgress& progress) {\n if ((m_buf) && (m_buf_len)) {\n Watcher watch(this, progress);\n\n m_ret = m_obj->m_parser.feed(\n m_buf_len, reinterpret_cast(m_buf)\n );\n }\n if (m_ret < 0) {\n SetErrorMessage(\"invalid buffer \/ length\");\n }\n }\n\n void HandleProgressCallback(const TableData *async_data, size_t count) {\n Nan::HandleScope scope;\n\n if (!m_cb_progress->IsEmpty()) {\n for (unsigned int i = 0; i < count; i++) {\n const TableData *data = &async_data[i];\n\n Nan::MaybeLocal jsonStr = Nan::New(data->json);\n if (!jsonStr.IsEmpty()) {\n Nan::MaybeLocal jsonVal =\n NanJSON.Parse(jsonStr.ToLocalChecked());\n\n if (!jsonVal.IsEmpty()) {\n Nan::MaybeLocal decoderName =\n Nan::New(data->decoderName);\n\n v8::Local decoderNameArg;\n if (decoderName.IsEmpty())\n decoderNameArg = Nan::Null();\n else\n decoderNameArg = decoderName.ToLocalChecked();\n\n v8::Local argv[] = {\n Nan::New(data->tableId),\n decoderNameArg,\n jsonVal.ToLocalChecked()\n };\n\n m_cb_progress->Call(3, argv);\n }\n }\n }\n }\n }\n\n void HandleOKCallback() {\n Nan::HandleScope scope;\n\n v8::Local argv[] = {\n Nan::Null()\n , Nan::New(m_ret)\n };\n\n callback->Call(2, argv);\n }\n\n private:\n Nan::Callback *m_cb_progress;\n Nan::JSON NanJSON;\n const AsyncProgressQueueWorker::ExecutionProgress *m_progress;\n dvbteeParser* m_obj;\n char* m_buf;\n unsigned int m_buf_len;\n int m_ret;\n\n class Watcher: public dvbtee::decode::TableWatcher {\n public:\n explicit Watcher(FeedWorker* w,\n const AsyncProgressQueueWorker::ExecutionProgress& progress)\n : m_worker(w)\n , m_progress(progress) {\n m_worker->m_obj->m_parser.subscribeTables(this);\n }\n ~Watcher() {\n m_worker->m_obj->m_parser.subscribeTables(NULL);\n }\n\n void updateTable(uint8_t tId, dvbtee::decode::Table *table) {\n m_progress.Send(\n new TableData(table->getTableid(),\n table->getDecoderName(),\n table->toJson()), 1\n );\n }\n\n private:\n FeedWorker* m_worker;\n const AsyncProgressQueueWorker::ExecutionProgress& m_progress;\n };\n};\n\nvoid dvbteeParser::feed(const Nan::FunctionCallbackInfo& info) {\n int lastArg = info.Length() - 1;\n\n if ((lastArg >= 1) && (info[lastArg]->IsFunction()) &&\n (info[lastArg - 1]->IsFunction())) {\n Nan::Callback *progress = new Nan::Callback(\n info[lastArg - 1].As()\n );\n Nan::Callback *callback = new Nan::Callback(\n info[lastArg].As()\n );\n Nan::AsyncQueueWorker(new FeedWorker(callback, progress, info));\n\n } else {\n info.GetReturnValue().Set(Nan::New(-1));\n }\n}\n<|endoftext|>"} {"text":"#include \"terminal.h\"\n\n\n\n\/\/\/ Sets a newline operator to Terminal output.\nTerminal& Terminal::newline(Terminal& term)\n{\n term.set_ops(Ops::newline);\n return *this;\n}\n\n\n\n\/\/\/ Sets a newline operator then a flush operator to Terminal output.\nTerminal& Terminal::endl(Terminal& term)\n{\n term.set_ops(Ops::newline);\n term.set_ops(Ops::flush);\n return *this;\n}\n\n\n\n\/\/\/ Sets a flush operator to Terminal output.\nTerminal& Terminal::flush(Terminal& term)\n{\n term.set_ops(Ops::flush);\n return *this;\n}\n\n\n\n\/\/\/ Sets a general message state operator to Terminal output.\nTerminal& Terminal::general(Terminal& term)\n{\n term.set_ops(Ops::general);\n return *this;\n}\n\n\n\n\/\/\/ Sets a warning message state operator to Terminal output.\nTerminal& Terminal::warning(Terminal& term)\n{\n term.set_ops(Ops::warning);\n return *this;\n}\n\n\n\n\/\/\/ Sets a error message state operator to Terminal output.\nTerminal& Terminal::error(Terminal& term)\n{\n term.set_ops(Ops::error);\n return *this;\n}\n\n\n\n\/\/ Self-referencing print functions that redirect to output operators.\nTerminal& Terminal::print(short n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(unsigned short n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(int n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(unsigned int n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(long n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(unsigned long n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(float n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(double n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(const char* n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(const std::string& n)\n{\n return *this << n;\n}\n\n\n\nTerminal& Terminal::operator<<(Terminal& (*pf)(Terminal&))\n{\n return pf(*this);\n}\nFixed terminal class.#include \"terminal.h\"\n\n\n\n\/\/\/ Sets a newline operator to Terminal output.\nTerminal& Terminal::newline(Terminal& term)\n{\n term.set_ops(Ops::newline);\n}\n\n\n\n\/\/\/ Sets a newline operator then a flush operator to Terminal output.\nTerminal& Terminal::endl(Terminal& term)\n{\n term.set_ops(Ops::newline);\n term.set_ops(Ops::flush);\n}\n\n\n\n\/\/\/ Sets a flush operator to Terminal output.\nTerminal& Terminal::flush(Terminal& term)\n{\n term.set_ops(Ops::flush);\n}\n\n\n\n\/\/\/ Sets a general message state operator to Terminal output.\nTerminal& Terminal::general(Terminal& term)\n{\n term.set_ops(Ops::general);\n}\n\n\n\n\/\/\/ Sets a warning message state operator to Terminal output.\nTerminal& Terminal::warning(Terminal& term)\n{\n term.set_ops(Ops::warning);\n}\n\n\n\n\/\/\/ Sets a error message state operator to Terminal output.\nTerminal& Terminal::error(Terminal& term)\n{\n term.set_ops(Ops::error);\n}\n\n\n\n\/\/ Self-referencing print functions that redirect to output operators.\nTerminal& Terminal::print(short n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(unsigned short n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(int n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(unsigned int n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(long n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(unsigned long n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(float n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(double n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(const char* n)\n{\n return *this << n;\n}\nTerminal& Terminal::print(const std::string& n)\n{\n return *this << n;\n}\n\n\n\nTerminal& Terminal::operator<<(Terminal& (*pf)(Terminal&))\n{\n return pf(*this);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"after_initialization_fixture.h\"\n#include \"test\/testsupport\/fileutils.h\"\n\nnamespace {\r\n\r\nconst int kSampleRateHz = 16000;\r\nconst int kTestDurationMs = 1000;\r\nconst int16_t kInputValue = 15000;\r\nconst int16_t kSilenceValue = 0;\r\n\r\n} \/\/ namespace\n\nclass FileBeforeStreamingTest : public AfterInitializationFixture {\n protected:\n FileBeforeStreamingTest()\n : input_filename_(webrtc::test::OutputPath() + \"file_test_input.pcm\"),\r\n output_filename_(webrtc::test::OutputPath() + \"file_test_output.pcm\") {\n }\n\n void SetUp() {\n channel_ = voe_base_->CreateChannel();\n }\n\n void TearDown() {\n voe_base_->DeleteChannel(channel_);\n }\n\r\n \/\/ TODO(andrew): consolidate below methods in a shared place?\r\n\r\n \/\/ Generate input file with constant values as |kInputValue|. The file\r\n \/\/ will be one second longer than the duration of the test.\r\n void GenerateInputFile() {\r\n FILE* input_file = fopen(input_filename_.c_str(), \"wb\");\r\n ASSERT_TRUE(input_file != NULL);\r\n for (int i = 0; i < kSampleRateHz \/ 1000 * (kTestDurationMs + 1000); i++) {\r\n ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file));\r\n }\r\n ASSERT_EQ(0, fclose(input_file));\r\n }\n\n void RecordOutput() {\r\n \/\/ Start recording the mixed output for |kTestDurationMs| long.\r\n EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1,\r\n output_filename_.c_str()));\r\n Sleep(kTestDurationMs);\r\n EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));\n }\n\n void VerifyOutput(int16_t target_value) {\r\n FILE* output_file = fopen(output_filename_.c_str(), \"rb\");\r\n ASSERT_TRUE(output_file != NULL);\r\n int16_t output_value = 0;\r\n int samples_read = 0;\r\n\r\n while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {\r\n samples_read++;\r\n EXPECT_EQ(output_value, target_value);\r\n }\r\n\r\n \/\/ Ensure the recording length is close to the duration of the test.\r\n ASSERT_GE((samples_read * 1000.0) \/ kSampleRateHz, 0.9 * kTestDurationMs);\r\n\r\n \/\/ Ensure we read the entire file.\r\n ASSERT_NE(0, feof(output_file));\r\n ASSERT_EQ(0, fclose(output_file));\r\n }\n\nvoid VerifyEmptyOutput() {\r\n FILE* output_file = fopen(output_filename_.c_str(), \"rb\");\r\n ASSERT_TRUE(output_file != NULL);\r\n ASSERT_EQ(0, fseek(output_file, 0, SEEK_END));\r\n EXPECT_EQ(0, ftell(output_file));\r\n ASSERT_EQ(0, fclose(output_file));\r\n}\r\n\n int channel_;\n const std::string input_filename_;\r\n const std::string output_filename_;\n};\n\n\/\/ This test case is to ensure that StartPlayingFileLocally() and\n\/\/ StartPlayout() can be called in any order.\n\/\/ A DC signal is used as input. And the output of mixer is supposed to be:\n\/\/ 1. the same DC signal if file is played out,\n\/\/ 2. total silence if file is not played out,\n\/\/ 3. no output if playout is not started.\nTEST_F(FileBeforeStreamingTest,\n DISABLED_TestStartPlayingFileLocallyWithStartPlayout) {\n GenerateInputFile();\n\n TEST_LOG(\"Playout is not started. File will not be played out.\\n\");\n EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(\n channel_, input_filename_.c_str(), true));\n EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));\n RecordOutput();\n VerifyEmptyOutput();\n\n TEST_LOG(\"Playout is now started. File will be played out.\\n\");\n EXPECT_EQ(0, voe_base_->StartPlayout(channel_));\n RecordOutput();\n VerifyOutput(kInputValue);\n\n TEST_LOG(\"Stop playing file. Only silence will be played out.\\n\");\n EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));\n EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_));\n RecordOutput();\n VerifyOutput(kSilenceValue);\n\n TEST_LOG(\"Start playing file again. File will be played out.\\n\");\n EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(\n channel_, input_filename_.c_str(), true));\n EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));\n RecordOutput();\n VerifyOutput(kInputValue);\n\n EXPECT_EQ(0, voe_base_->StopPlayout(channel_));\n EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));\n}\nFix the flakiness in FileBeforeStreamingTest\/*\n * Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \"after_initialization_fixture.h\"\n#include \"test\/testsupport\/fileutils.h\"\n\nnamespace {\n\nconst int kSampleRateHz = 16000;\nconst int kTestDurationMs = 1000;\nconst int kSkipOutputMs = 50;\nconst int16_t kInputValue = 15000;\nconst int16_t kSilenceValue = 0;\n\n} \/\/ namespace\n\nclass FileBeforeStreamingTest : public AfterInitializationFixture {\n protected:\n FileBeforeStreamingTest()\n : input_filename_(webrtc::test::OutputPath() + \"file_test_input.pcm\"),\n output_filename_(webrtc::test::OutputPath() + \"file_test_output.pcm\") {\n }\n\n void SetUp() {\n channel_ = voe_base_->CreateChannel();\n }\n\n void TearDown() {\n voe_base_->DeleteChannel(channel_);\n }\n\n \/\/ TODO(andrew): consolidate below methods in a shared place?\n\n \/\/ Generate input file with constant values as |kInputValue|. The file\n \/\/ will be one second longer than the duration of the test.\n void GenerateInputFile() {\n FILE* input_file = fopen(input_filename_.c_str(), \"wb\");\n ASSERT_TRUE(input_file != NULL);\n for (int i = 0; i < kSampleRateHz \/ 1000 * (kTestDurationMs + 1000); i++) {\n ASSERT_EQ(1u, fwrite(&kInputValue, sizeof(kInputValue), 1, input_file));\n }\n ASSERT_EQ(0, fclose(input_file));\n }\n\n void RecordOutput() {\n \/\/ Start recording the mixed output for |kTestDurationMs| long.\n EXPECT_EQ(0, voe_file_->StartRecordingPlayout(-1,\n output_filename_.c_str()));\n Sleep(kTestDurationMs);\n EXPECT_EQ(0, voe_file_->StopRecordingPlayout(-1));\n }\n\n void VerifyOutput(int16_t target_value) {\n FILE* output_file = fopen(output_filename_.c_str(), \"rb\");\n ASSERT_TRUE(output_file != NULL);\n int16_t output_value = 0;\n int samples_read = 0;\n\n \/\/ Skip the first segment to avoid initialization and ramping-in effects.\n EXPECT_EQ(0, fseek(output_file, sizeof(output_value) *\n kSampleRateHz \/ 1000 * kSkipOutputMs, SEEK_SET));\n while (fread(&output_value, sizeof(output_value), 1, output_file) == 1) {\n samples_read++;\n EXPECT_EQ(output_value, target_value);\n }\n\n \/\/ Ensure the recording length is close to the duration of the test.\n ASSERT_GE((samples_read * 1000.0) \/ kSampleRateHz, 0.9 * kTestDurationMs);\n\n \/\/ Ensure we read the entire file.\n ASSERT_NE(0, feof(output_file));\n ASSERT_EQ(0, fclose(output_file));\n }\n\nvoid VerifyEmptyOutput() {\n FILE* output_file = fopen(output_filename_.c_str(), \"rb\");\n ASSERT_TRUE(output_file != NULL);\n ASSERT_EQ(0, fseek(output_file, 0, SEEK_END));\n EXPECT_EQ(0, ftell(output_file));\n ASSERT_EQ(0, fclose(output_file));\n}\n\n int channel_;\n const std::string input_filename_;\n const std::string output_filename_;\n};\n\n\/\/ This test case is to ensure that StartPlayingFileLocally() and\n\/\/ StartPlayout() can be called in any order.\n\/\/ A DC signal is used as input. And the output of mixer is supposed to be:\n\/\/ 1. the same DC signal if file is played out,\n\/\/ 2. total silence if file is not played out,\n\/\/ 3. no output if playout is not started.\nTEST_F(FileBeforeStreamingTest, TestStartPlayingFileLocallyWithStartPlayout) {\n GenerateInputFile();\n\n TEST_LOG(\"Playout is not started. File will not be played out.\\n\");\n EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(\n channel_, input_filename_.c_str(), true));\n EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));\n RecordOutput();\n VerifyEmptyOutput();\n\n TEST_LOG(\"Playout is now started. File will be played out.\\n\");\n EXPECT_EQ(0, voe_base_->StartPlayout(channel_));\n RecordOutput();\n VerifyOutput(kInputValue);\n\n TEST_LOG(\"Stop playing file. Only silence will be played out.\\n\");\n EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));\n EXPECT_EQ(0, voe_file_->IsPlayingFileLocally(channel_));\n RecordOutput();\n VerifyOutput(kSilenceValue);\n\n TEST_LOG(\"Start playing file again. File will be played out.\\n\");\n EXPECT_EQ(0, voe_file_->StartPlayingFileLocally(\n channel_, input_filename_.c_str(), true));\n EXPECT_EQ(1, voe_file_->IsPlayingFileLocally(channel_));\n RecordOutput();\n VerifyOutput(kInputValue);\n\n EXPECT_EQ(0, voe_base_->StopPlayout(channel_));\n EXPECT_EQ(0, voe_file_->StopPlayingFileLocally(channel_));\n}\n<|endoftext|>"} {"text":"\/**\n * Derived from this blog post:\n * http:\/\/simmesimme.github.io\/tutorials\/2015\/09\/20\/signal-slot\n *\/\n\n#ifndef SIGNAL_HPP\n#define SIGNAL_HPP\n\n#include \n#include \n\n\/\/ A signal object may call multiple slots with the\n\/\/ same signature. You can connect functions to the signal\n\/\/ which will be called when the emit() method on the\n\/\/ signal object is invoked. Any argument passed to emit()\n\/\/ will be passed to the given functions.\n\ntemplate class Signal {\n\npublic:\n Signal() : current_id_(0) {}\n\n \/\/ copy creates new signal\n Signal(Signal const &other) : current_id_(0) {}\n\n \/\/ connects a member function to this Signal\n template int ConnectMember(T *inst, void (T::*func)(Args...)) {\n return Connect([=](Args... args) { (inst->*func)(args...); });\n }\n\n \/\/ connects a member function to this Signal\n template \n int ConnectMember(std::shared_ptr inst, void (T::*func)(Args...)) {\n return Connect([=](Args... args) { ((*inst).*func)(args...); });\n }\n\n \/\/ connects a const member function to this Signal\n template \n int ConnectMember(T *inst, void (T::*func)(Args...) const) {\n return Connect([=](Args... args) { (inst->*func)(args...); });\n }\n\n \/\/ connects a std::function to the signal. The returned\n \/\/ value can be used to disconnect the function again\n int Connect(std::function const &slot) const {\n slots_.insert(std::make_pair(++current_id_, slot));\n return current_id_;\n }\n\n \/\/ disconnects a previously connected function\n void Disconnect(int id) const { slots_.erase(id); }\n\n \/\/ disconnects all previously connected functions\n void DisconnectAll() const { slots_.clear(); }\n\n \/\/ calls all connected functions\n void Emit(Args... p) {\n for (auto it : slots_) {\n it.second(p...);\n }\n }\n\n \/\/ assignment creates new Signal\n Signal &operator=(Signal const &other) { DisconnectAll(); }\n\nprivate:\n mutable std::map> slots_;\n mutable int current_id_;\n};\n\n#endif \/* SIGNAL_HPP *\/removed unneeded Signal::ConnectMember function\/**\n * Derived from this blog post:\n * http:\/\/simmesimme.github.io\/tutorials\/2015\/09\/20\/signal-slot\n *\/\n\n#ifndef SIGNAL_HPP\n#define SIGNAL_HPP\n\n#include \n#include \n\n\/\/ A signal object may call multiple slots with the\n\/\/ same signature. You can connect functions to the signal\n\/\/ which will be called when the emit() method on the\n\/\/ signal object is invoked. Any argument passed to emit()\n\/\/ will be passed to the given functions.\n\ntemplate class Signal {\n\npublic:\n Signal() : current_id_(0) {}\n\n \/\/ copy creates new signal\n Signal(Signal const &other) : current_id_(0) {}\n\n \/\/ connects a member function to this Signal\n template int ConnectMember(T *inst, void (T::*func)(Args...)) {\n return Connect([=](Args... args) { (inst->*func)(args...); });\n }\n\n \/\/ connects a const member function to this Signal\n template \n int ConnectMember(T *inst, void (T::*func)(Args...) const) {\n return Connect([=](Args... args) { (inst->*func)(args...); });\n }\n\n \/\/ connects a std::function to the signal. The returned\n \/\/ value can be used to disconnect the function again\n int Connect(std::function const &slot) const {\n slots_.insert(std::make_pair(++current_id_, slot));\n return current_id_;\n }\n\n \/\/ disconnects a previously connected function\n void Disconnect(int id) const { slots_.erase(id); }\n\n \/\/ disconnects all previously connected functions\n void DisconnectAll() const { slots_.clear(); }\n\n \/\/ calls all connected functions\n void Emit(Args... p) {\n for (auto it : slots_) {\n it.second(p...);\n }\n }\n\n \/\/ assignment creates new Signal\n Signal &operator=(Signal const &other) { DisconnectAll(); }\n\nprivate:\n mutable std::map> slots_;\n mutable int current_id_;\n};\n\n#endif \/* SIGNAL_HPP *\/<|endoftext|>"} {"text":"\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#ifndef EXTPROC_POOL_HPP_\n#define EXTPROC_POOL_HPP_\n\n#include \/\/ pid_t\n\n#include \"errors.hpp\"\n\n#include \"concurrency\/one_per_thread.hpp\"\n#include \"concurrency\/semaphore.hpp\"\n#include \"concurrency\/signal.hpp\"\n#include \"containers\/archive\/interruptible_stream.hpp\"\n#include \"containers\/archive\/socket_stream.hpp\"\n#include \"containers\/intrusive_list.hpp\"\n#include \"extproc\/job.hpp\"\n#include \"extproc\/spawner.hpp\"\n\nnamespace extproc {\n\nclass job_handle_t;\nclass pool_t;\n\n\/\/ Use this to create one process pool per thread, and access the appropriate\n\/\/ one (via `get()`).\nclass pool_group_t {\n friend class pool_t;\n\npublic:\n static const int DEFAULT_MIN_WORKERS = 2;\n static const int DEFAULT_MAX_WORKERS = 2;\n\n struct config_t {\n config_t()\n : min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}\n int min_workers; \/\/ >= 0\n int max_workers; \/\/ >= min_workers, > 0\n };\n\n static const config_t DEFAULTS;\n\n pool_group_t(spawner_info_t *info, const config_t &config);\n\n pool_t *get() { return pool_maker_.get(); }\n\nprivate:\n spawner_t spawner_;\n config_t config_;\n one_per_thread_t pool_maker_;\n};\n\n\/\/ A worker process.\nclass pool_worker_t : public intrusive_list_node_t {\n friend class job_handle_t;\n\npublic:\n pool_worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);\n ~pool_worker_t();\n\n \/\/ Called when we get an error on a worker process socket, which usually\n \/\/ indicates the worker process' death.\n void on_error();\n\n \/\/ Inherited from unix_socket_stream_t. Called when epoll finds an error\n \/\/ condition on our socket. Calls on_error().\n virtual void do_on_event(int events);\n\n unix_socket_stream_t unix_socket;\n\nprivate:\n friend class pool_t;\n\n pool_t *const pool_;\n const pid_t pid_;\n bool attached_;\n\n DISABLE_COPYING(pool_worker_t);\n};\n\n\n\/\/ A per-thread worker pool.\nclass pool_t : public home_thread_mixin_debug_only_t {\npublic:\n explicit pool_t(pool_group_t *group);\n ~pool_t();\n\nprivate:\n friend class job_handle_t;\n\n pool_group_t::config_t *config() { return &group_->config_; }\n spawner_t *spawner() { return &group_->spawner_; }\n\n private:\n \/\/ Checks & repairs invariants, namely:\n \/\/ - num_workers() >= config()->min_workers\n void repair_invariants();\n\n \/\/ Connects us to a worker. Private; used only by job_handle_t::spawn().\n pool_worker_t *acquire_worker();\n\n \/\/ Called by job_handle_t to indicate the job has finished or errored.\n void release_worker(pool_worker_t *worker) THROWS_NOTHING;\n\n \/\/ Called by job_handle_t to interrupt a running job.\n void interrupt_worker(pool_worker_t *worker) THROWS_NOTHING;\n\n \/\/ Detaches the worker from the pool, sends it SIGKILL, and ignores further\n \/\/ errors from it (ie. on_event will not call on_error, and hence will not\n \/\/ crash). Does not block.\n \/\/\n \/\/ This is used by the interruptor-signal logic in\n \/\/ job_handle_t::{read,write}_interruptible(), where interrupt_worker()\n \/\/ cannot be used because it destroys the worker.\n \/\/\n \/\/ It is the caller's responsibility to call cleanup_detached_worker() at\n \/\/ some point in the near future.\n void detach_worker(pool_worker_t *worker);\n\n \/\/ Cleans up after a detached worker. Destroys the worker. May block.\n void cleanup_detached_worker(pool_worker_t *worker);\n\n void spawn_workers(int n);\n void end_worker(intrusive_list_t *list, pool_worker_t *worker);\n\n int num_workers() {\n return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;\n }\n\nprivate:\n pool_group_t *group_;\n\n \/\/ Worker processes.\n intrusive_list_t idle_workers_;\n intrusive_list_t busy_workers_;\n\n \/\/ Count of the number of workers in the process of being spawned. Necessary\n \/\/ in order to maintain (min_workers, max_workers) bounds without race\n \/\/ conditions.\n int num_spawning_workers_;\n\n \/\/ Used to signify that you're using a worker. In particular, lets us block\n \/\/ for a worker to become available when we already have\n \/\/ config_->max_workers workers running.\n semaphore_t worker_semaphore_;\n};\n\n\/\/ A handle to a running job.\nclass job_handle_t : public interruptible_read_stream_t, public interruptible_write_stream_t {\npublic:\n \/\/ When constructed, job handles are \"disconnected\", not associated with a\n \/\/ job. They are connected by pool_t::spawn_job().\n job_handle_t();\n\n \/\/ You MUST call release() to finish a job normally, and you SHOULD call\n \/\/ interrupt() explicitly to interrupt a job (or signal the interruptor\n \/\/ during {read,write}_interruptible()).\n \/\/\n \/\/ However, as a convenience in the case of exception-raising code, if the\n \/\/ handle is connected, the destructor will log a warning and interrupt the\n \/\/ job.\n virtual ~job_handle_t();\n\n bool connected() { return NULL != worker_; }\n\n \/\/ Begins running `job` on `pool`. Must be disconnected beforehand. On\n \/\/ success, returns 0 and connects us to the spawned job. Returns -1 on\n \/\/ error.\n int begin(pool_t *pool, const job_t &job);\n\n \/\/ Indicates the job has either finished normally or experienced an I\/O\n \/\/ error; disconnects the job handle.\n void release() THROWS_NOTHING;\n\n \/\/ Forcibly interrupts a running job; disconnects the job handle.\n \/\/\n \/\/ MAY NOT be called concurrently with any I\/O methods. Instead, pass a\n \/\/ signal to {read,write}_interruptible().\n void interrupt() THROWS_NOTHING;\n\n \/\/ On either read or write error or interruption, the job handle becomes\n \/\/ disconnected and must not be used.\n virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);\n virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);\n\nprivate:\n friend class pool_t;\n friend class interruptor_wrapper_t;\n\n void check_attached();\n\n class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {\n public:\n interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);\n virtual void run() THROWS_NOTHING;\n job_handle_t *handle_;\n };\n\n pool_worker_t *worker_;\n\n DISABLE_COPYING(job_handle_t);\n};\n\n} \/\/ namespace extproc\n\n#endif \/\/ EXTPROC_POOL_HPP_\nAdded DISABLE_COPYINGs in pool.hpp.\/\/ Copyright 2010-2013 RethinkDB, all rights reserved.\n#ifndef EXTPROC_POOL_HPP_\n#define EXTPROC_POOL_HPP_\n\n#include \/\/ pid_t\n\n#include \"errors.hpp\"\n\n#include \"concurrency\/one_per_thread.hpp\"\n#include \"concurrency\/semaphore.hpp\"\n#include \"concurrency\/signal.hpp\"\n#include \"containers\/archive\/interruptible_stream.hpp\"\n#include \"containers\/archive\/socket_stream.hpp\"\n#include \"containers\/intrusive_list.hpp\"\n#include \"extproc\/job.hpp\"\n#include \"extproc\/spawner.hpp\"\n\nnamespace extproc {\n\nclass job_handle_t;\nclass pool_t;\n\n\/\/ Use this to create one process pool per thread, and access the appropriate\n\/\/ one (via `get()`).\nclass pool_group_t {\n friend class pool_t;\n\npublic:\n static const int DEFAULT_MIN_WORKERS = 2;\n static const int DEFAULT_MAX_WORKERS = 2;\n\n struct config_t {\n config_t()\n : min_workers(DEFAULT_MIN_WORKERS), max_workers(DEFAULT_MAX_WORKERS) {}\n int min_workers; \/\/ >= 0\n int max_workers; \/\/ >= min_workers, > 0\n };\n\n static const config_t DEFAULTS;\n\n pool_group_t(spawner_info_t *info, const config_t &config);\n\n pool_t *get() { return pool_maker_.get(); }\n\nprivate:\n spawner_t spawner_;\n config_t config_;\n one_per_thread_t pool_maker_;\n\n DISABLE_COPYING(pool_group_t);\n};\n\n\/\/ A worker process.\nclass pool_worker_t : public intrusive_list_node_t {\n friend class job_handle_t;\n\npublic:\n pool_worker_t(pool_t *pool, pid_t pid, scoped_fd_t *fd);\n ~pool_worker_t();\n\n \/\/ Called when we get an error on a worker process socket, which usually\n \/\/ indicates the worker process' death.\n void on_error();\n\n \/\/ Inherited from unix_socket_stream_t. Called when epoll finds an error\n \/\/ condition on our socket. Calls on_error().\n virtual void do_on_event(int events);\n\n unix_socket_stream_t unix_socket;\n\nprivate:\n friend class pool_t;\n\n pool_t *const pool_;\n const pid_t pid_;\n bool attached_;\n\n DISABLE_COPYING(pool_worker_t);\n};\n\n\n\/\/ A per-thread worker pool.\nclass pool_t : public home_thread_mixin_debug_only_t {\npublic:\n explicit pool_t(pool_group_t *group);\n ~pool_t();\n\nprivate:\n friend class job_handle_t;\n\n pool_group_t::config_t *config() { return &group_->config_; }\n spawner_t *spawner() { return &group_->spawner_; }\n\n private:\n \/\/ Checks & repairs invariants, namely:\n \/\/ - num_workers() >= config()->min_workers\n void repair_invariants();\n\n \/\/ Connects us to a worker. Private; used only by job_handle_t::spawn().\n pool_worker_t *acquire_worker();\n\n \/\/ Called by job_handle_t to indicate the job has finished or errored.\n void release_worker(pool_worker_t *worker) THROWS_NOTHING;\n\n \/\/ Called by job_handle_t to interrupt a running job.\n void interrupt_worker(pool_worker_t *worker) THROWS_NOTHING;\n\n \/\/ Detaches the worker from the pool, sends it SIGKILL, and ignores further\n \/\/ errors from it (ie. on_event will not call on_error, and hence will not\n \/\/ crash). Does not block.\n \/\/\n \/\/ This is used by the interruptor-signal logic in\n \/\/ job_handle_t::{read,write}_interruptible(), where interrupt_worker()\n \/\/ cannot be used because it destroys the worker.\n \/\/\n \/\/ It is the caller's responsibility to call cleanup_detached_worker() at\n \/\/ some point in the near future.\n void detach_worker(pool_worker_t *worker);\n\n \/\/ Cleans up after a detached worker. Destroys the worker. May block.\n void cleanup_detached_worker(pool_worker_t *worker);\n\n void spawn_workers(int n);\n void end_worker(intrusive_list_t *list, pool_worker_t *worker);\n\n int num_workers() const {\n return idle_workers_.size() + busy_workers_.size() + num_spawning_workers_;\n }\n\nprivate:\n pool_group_t *group_;\n\n \/\/ Worker processes.\n intrusive_list_t idle_workers_;\n intrusive_list_t busy_workers_;\n\n \/\/ Count of the number of workers in the process of being spawned. Necessary\n \/\/ in order to maintain (min_workers, max_workers) bounds without race\n \/\/ conditions.\n int num_spawning_workers_;\n\n \/\/ Used to signify that you're using a worker. In particular, lets us block\n \/\/ for a worker to become available when we already have\n \/\/ config_->max_workers workers running.\n semaphore_t worker_semaphore_;\n\n DISABLE_COPYING(pool_t);\n};\n\n\/\/ A handle to a running job.\nclass job_handle_t : public interruptible_read_stream_t, public interruptible_write_stream_t {\npublic:\n \/\/ When constructed, job handles are \"disconnected\", not associated with a\n \/\/ job. They are connected by pool_t::spawn_job().\n job_handle_t();\n\n \/\/ You MUST call release() to finish a job normally, and you SHOULD call\n \/\/ interrupt() explicitly to interrupt a job (or signal the interruptor\n \/\/ during {read,write}_interruptible()).\n \/\/\n \/\/ However, as a convenience in the case of exception-raising code, if the\n \/\/ handle is connected, the destructor will log a warning and interrupt the\n \/\/ job.\n virtual ~job_handle_t();\n\n bool connected() { return NULL != worker_; }\n\n \/\/ Begins running `job` on `pool`. Must be disconnected beforehand. On\n \/\/ success, returns 0 and connects us to the spawned job. Returns -1 on\n \/\/ error.\n int begin(pool_t *pool, const job_t &job);\n\n \/\/ Indicates the job has either finished normally or experienced an I\/O\n \/\/ error; disconnects the job handle.\n void release() THROWS_NOTHING;\n\n \/\/ Forcibly interrupts a running job; disconnects the job handle.\n \/\/\n \/\/ MAY NOT be called concurrently with any I\/O methods. Instead, pass a\n \/\/ signal to {read,write}_interruptible().\n void interrupt() THROWS_NOTHING;\n\n \/\/ On either read or write error or interruption, the job handle becomes\n \/\/ disconnected and must not be used.\n virtual MUST_USE int64_t read_interruptible(void *p, int64_t n, signal_t *interruptor);\n virtual int64_t write_interruptible(const void *p, int64_t n, signal_t *interruptor);\n\nprivate:\n friend class pool_t;\n friend class interruptor_wrapper_t;\n\n void check_attached();\n\n class interruptor_wrapper_t : public signal_t, public signal_t::subscription_t {\n public:\n interruptor_wrapper_t(job_handle_t *handle, signal_t *signal);\n virtual void run() THROWS_NOTHING;\n job_handle_t *handle_;\n };\n\n pool_worker_t *worker_;\n\n DISABLE_COPYING(job_handle_t);\n};\n\n} \/\/ namespace extproc\n\n#endif \/\/ EXTPROC_POOL_HPP_\n<|endoftext|>"} {"text":"\/\/ Copyright 2013 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Library for preprocessing fonts as part of the WOFF 2.0 conversion.\n\n#include \".\/transform.h\"\n\n#include \/\/ for std::abs\n\n#include \".\/buffer.h\"\n#include \".\/font.h\"\n#include \".\/glyph.h\"\n#include \".\/table_tags.h\"\n#include \".\/variable_length.h\"\n\nnamespace woff2 {\n\nnamespace {\n\nconst int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;\nconst int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;\n\nvoid WriteBytes(std::vector* out, const uint8_t* data, size_t len) {\n if (len == 0) return;\n size_t offset = out->size();\n out->resize(offset + len);\n memcpy(&(*out)[offset], data, len);\n}\n\nvoid WriteBytes(std::vector* out, const std::vector& in) {\n for (int i = 0; i < in.size(); ++i) {\n out->push_back(in[i]);\n }\n}\n\nvoid WriteUShort(std::vector* out, int value) {\n out->push_back(value >> 8);\n out->push_back(value & 255);\n}\n\nvoid WriteLong(std::vector* out, int value) {\n out->push_back((value >> 24) & 255);\n out->push_back((value >> 16) & 255);\n out->push_back((value >> 8) & 255);\n out->push_back(value & 255);\n}\n\n\/\/ Glyf table preprocessing, based on\n\/\/ GlyfEncoder.java\nclass GlyfEncoder {\n public:\n explicit GlyfEncoder(int num_glyphs)\n : n_glyphs_(num_glyphs) {\n bbox_bitmap_.resize(((num_glyphs + 31) >> 5) << 2);\n }\n\n bool Encode(int glyph_id, const Glyph& glyph) {\n if (glyph.composite_data_size > 0) {\n WriteCompositeGlyph(glyph_id, glyph);\n } else if (glyph.contours.size() > 0) {\n WriteSimpleGlyph(glyph_id, glyph);\n } else {\n WriteUShort(&n_contour_stream_, 0);\n }\n return true;\n }\n\n void GetTransformedGlyfBytes(std::vector* result) {\n WriteLong(result, 0); \/\/ version\n WriteUShort(result, n_glyphs_);\n WriteUShort(result, 0); \/\/ index_format, will be set later\n WriteLong(result, n_contour_stream_.size());\n WriteLong(result, n_points_stream_.size());\n WriteLong(result, flag_byte_stream_.size());\n WriteLong(result, glyph_stream_.size());\n WriteLong(result, composite_stream_.size());\n WriteLong(result, bbox_bitmap_.size() + bbox_stream_.size());\n WriteLong(result, instruction_stream_.size());\n WriteBytes(result, n_contour_stream_);\n WriteBytes(result, n_points_stream_);\n WriteBytes(result, flag_byte_stream_);\n WriteBytes(result, glyph_stream_);\n WriteBytes(result, composite_stream_);\n WriteBytes(result, bbox_bitmap_);\n WriteBytes(result, bbox_stream_);\n WriteBytes(result, instruction_stream_);\n }\n\n private:\n void WriteInstructions(const Glyph& glyph) {\n Write255UShort(&glyph_stream_, glyph.instructions_size);\n WriteBytes(&instruction_stream_,\n glyph.instructions_data, glyph.instructions_size);\n }\n\n bool ShouldWriteSimpleGlyphBbox(const Glyph& glyph) {\n if (glyph.contours.empty() || glyph.contours[0].empty()) {\n return glyph.x_min || glyph.y_min || glyph.x_max || glyph.y_max;\n }\n\n int16_t x_min = glyph.contours[0][0].x;\n int16_t y_min = glyph.contours[0][0].y;\n int16_t x_max = x_min;\n int16_t y_max = y_min;\n for (const auto& contour : glyph.contours) {\n for (const auto& point : contour) {\n if (point.x < x_min) x_min = point.x;\n if (point.x > x_max) x_max = point.x;\n if (point.y < y_min) y_min = point.y;\n if (point.y > y_max) y_max = point.y;\n }\n }\n\n if (glyph.x_min != x_min)\n return true;\n if (glyph.y_min != y_min)\n return true;\n if (glyph.x_max != x_max)\n return true;\n if (glyph.y_max != y_max)\n return true;\n\n return false;\n }\n\n void WriteSimpleGlyph(int glyph_id, const Glyph& glyph) {\n int num_contours = glyph.contours.size();\n WriteUShort(&n_contour_stream_, num_contours);\n if (ShouldWriteSimpleGlyphBbox(glyph)) {\n WriteBbox(glyph_id, glyph);\n }\n \/\/ TODO: check that bbox matches, write bbox if not\n for (int i = 0; i < num_contours; i++) {\n Write255UShort(&n_points_stream_, glyph.contours[i].size());\n }\n int lastX = 0;\n int lastY = 0;\n for (int i = 0; i < num_contours; i++) {\n int num_points = glyph.contours[i].size();\n for (int j = 0; j < num_points; j++) {\n int x = glyph.contours[i][j].x;\n int y = glyph.contours[i][j].y;\n int dx = x - lastX;\n int dy = y - lastY;\n WriteTriplet(glyph.contours[i][j].on_curve, dx, dy);\n lastX = x;\n lastY = y;\n }\n }\n if (num_contours > 0) {\n WriteInstructions(glyph);\n }\n }\n\n void WriteCompositeGlyph(int glyph_id, const Glyph& glyph) {\n WriteUShort(&n_contour_stream_, -1);\n WriteBbox(glyph_id, glyph);\n WriteBytes(&composite_stream_,\n glyph.composite_data,\n glyph.composite_data_size);\n if (glyph.have_instructions) {\n WriteInstructions(glyph);\n }\n }\n\n void WriteBbox(int glyph_id, const Glyph& glyph) {\n bbox_bitmap_[glyph_id >> 3] |= 0x80 >> (glyph_id & 7);\n WriteUShort(&bbox_stream_, glyph.x_min);\n WriteUShort(&bbox_stream_, glyph.y_min);\n WriteUShort(&bbox_stream_, glyph.x_max);\n WriteUShort(&bbox_stream_, glyph.y_max);\n }\n\n void WriteTriplet(bool on_curve, int x, int y) {\n int abs_x = std::abs(x);\n int abs_y = std::abs(y);\n int on_curve_bit = on_curve ? 0 : 128;\n int x_sign_bit = (x < 0) ? 0 : 1;\n int y_sign_bit = (y < 0) ? 0 : 1;\n int xy_sign_bits = x_sign_bit + 2 * y_sign_bit;\n if (x == 0 && abs_y < 1280) {\n flag_byte_stream_.push_back(on_curve_bit +\n ((abs_y & 0xf00) >> 7) + y_sign_bit);\n glyph_stream_.push_back(abs_y & 0xff);\n } else if (y == 0 && abs_x < 1280) {\n flag_byte_stream_.push_back(on_curve_bit + 10 +\n ((abs_x & 0xf00) >> 7) + x_sign_bit);\n glyph_stream_.push_back(abs_x & 0xff);\n } else if (abs_x < 65 && abs_y < 65) {\n flag_byte_stream_.push_back(on_curve_bit + 20 +\n ((abs_x - 1) & 0x30) +\n (((abs_y - 1) & 0x30) >> 2) +\n xy_sign_bits);\n glyph_stream_.push_back((((abs_x - 1) & 0xf) << 4) | ((abs_y - 1) & 0xf));\n } else if (abs_x < 769 && abs_y < 769) {\n flag_byte_stream_.push_back(on_curve_bit + 84 +\n 12 * (((abs_x - 1) & 0x300) >> 8) +\n (((abs_y - 1) & 0x300) >> 6) + xy_sign_bits);\n glyph_stream_.push_back((abs_x - 1) & 0xff);\n glyph_stream_.push_back((abs_y - 1) & 0xff);\n } else if (abs_x < 4096 && abs_y < 4096) {\n flag_byte_stream_.push_back(on_curve_bit + 120 + xy_sign_bits);\n glyph_stream_.push_back(abs_x >> 4);\n glyph_stream_.push_back(((abs_x & 0xf) << 4) | (abs_y >> 8));\n glyph_stream_.push_back(abs_y & 0xff);\n } else {\n flag_byte_stream_.push_back(on_curve_bit + 124 + xy_sign_bits);\n glyph_stream_.push_back(abs_x >> 8);\n glyph_stream_.push_back(abs_x & 0xff);\n glyph_stream_.push_back(abs_y >> 8);\n glyph_stream_.push_back(abs_y & 0xff);\n }\n }\n\n std::vector n_contour_stream_;\n std::vector n_points_stream_;\n std::vector flag_byte_stream_;\n std::vector composite_stream_;\n std::vector bbox_bitmap_;\n std::vector bbox_stream_;\n std::vector glyph_stream_;\n std::vector instruction_stream_;\n int n_glyphs_;\n};\n\n} \/\/ namespace\n\nbool TransformGlyfAndLocaTables(Font* font) {\n \/\/ no transform for CFF\n const Font::Table* glyf_table = font->FindTable(kGlyfTableTag);\n const Font::Table* loca_table = font->FindTable(kLocaTableTag);\n if (font->FindTable(kCffTableTag) != NULL\n && glyf_table == NULL\n && loca_table == NULL) {\n return true;\n }\n \/\/ Must share neither or both loca\/glyf\n if (glyf_table->IsReused() != loca_table->IsReused()) {\n return FONT_COMPRESSION_FAILURE();\n }\n if (glyf_table->IsReused()) {\n return true;\n }\n Font::Table* transformed_glyf = &font->tables[kGlyfTableTag ^ 0x80808080];\n Font::Table* transformed_loca = &font->tables[kLocaTableTag ^ 0x80808080];\n\n int num_glyphs = NumGlyphs(*font);\n GlyfEncoder encoder(num_glyphs);\n for (int i = 0; i < num_glyphs; ++i) {\n Glyph glyph;\n const uint8_t* glyph_data;\n size_t glyph_size;\n if (!GetGlyphData(*font, i, &glyph_data, &glyph_size) ||\n (glyph_size > 0 && !ReadGlyph(glyph_data, glyph_size, &glyph))) {\n return FONT_COMPRESSION_FAILURE();\n }\n encoder.Encode(i, glyph);\n }\n encoder.GetTransformedGlyfBytes(&transformed_glyf->buffer);\n\n const Font::Table* head_table = font->FindTable(kHeadTableTag);\n if (head_table == NULL || head_table->length < 52) {\n return FONT_COMPRESSION_FAILURE();\n }\n transformed_glyf->buffer[7] = head_table->data[51]; \/\/ index_format\n\n transformed_glyf->tag = kGlyfTableTag ^ 0x80808080;\n transformed_glyf->length = transformed_glyf->buffer.size();\n transformed_glyf->data = transformed_glyf->buffer.data();\n\n transformed_loca->tag = kLocaTableTag ^ 0x80808080;\n transformed_loca->length = 0;\n transformed_loca->data = NULL;\n\n return true;\n}\n\n} \/\/ namespace woff2\nremove comment that has been addressed\/\/ Copyright 2013 Google Inc. All Rights Reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/ Library for preprocessing fonts as part of the WOFF 2.0 conversion.\n\n#include \".\/transform.h\"\n\n#include \/\/ for std::abs\n\n#include \".\/buffer.h\"\n#include \".\/font.h\"\n#include \".\/glyph.h\"\n#include \".\/table_tags.h\"\n#include \".\/variable_length.h\"\n\nnamespace woff2 {\n\nnamespace {\n\nconst int FLAG_ARG_1_AND_2_ARE_WORDS = 1 << 0;\nconst int FLAG_WE_HAVE_INSTRUCTIONS = 1 << 8;\n\nvoid WriteBytes(std::vector* out, const uint8_t* data, size_t len) {\n if (len == 0) return;\n size_t offset = out->size();\n out->resize(offset + len);\n memcpy(&(*out)[offset], data, len);\n}\n\nvoid WriteBytes(std::vector* out, const std::vector& in) {\n for (int i = 0; i < in.size(); ++i) {\n out->push_back(in[i]);\n }\n}\n\nvoid WriteUShort(std::vector* out, int value) {\n out->push_back(value >> 8);\n out->push_back(value & 255);\n}\n\nvoid WriteLong(std::vector* out, int value) {\n out->push_back((value >> 24) & 255);\n out->push_back((value >> 16) & 255);\n out->push_back((value >> 8) & 255);\n out->push_back(value & 255);\n}\n\n\/\/ Glyf table preprocessing, based on\n\/\/ GlyfEncoder.java\nclass GlyfEncoder {\n public:\n explicit GlyfEncoder(int num_glyphs)\n : n_glyphs_(num_glyphs) {\n bbox_bitmap_.resize(((num_glyphs + 31) >> 5) << 2);\n }\n\n bool Encode(int glyph_id, const Glyph& glyph) {\n if (glyph.composite_data_size > 0) {\n WriteCompositeGlyph(glyph_id, glyph);\n } else if (glyph.contours.size() > 0) {\n WriteSimpleGlyph(glyph_id, glyph);\n } else {\n WriteUShort(&n_contour_stream_, 0);\n }\n return true;\n }\n\n void GetTransformedGlyfBytes(std::vector* result) {\n WriteLong(result, 0); \/\/ version\n WriteUShort(result, n_glyphs_);\n WriteUShort(result, 0); \/\/ index_format, will be set later\n WriteLong(result, n_contour_stream_.size());\n WriteLong(result, n_points_stream_.size());\n WriteLong(result, flag_byte_stream_.size());\n WriteLong(result, glyph_stream_.size());\n WriteLong(result, composite_stream_.size());\n WriteLong(result, bbox_bitmap_.size() + bbox_stream_.size());\n WriteLong(result, instruction_stream_.size());\n WriteBytes(result, n_contour_stream_);\n WriteBytes(result, n_points_stream_);\n WriteBytes(result, flag_byte_stream_);\n WriteBytes(result, glyph_stream_);\n WriteBytes(result, composite_stream_);\n WriteBytes(result, bbox_bitmap_);\n WriteBytes(result, bbox_stream_);\n WriteBytes(result, instruction_stream_);\n }\n\n private:\n void WriteInstructions(const Glyph& glyph) {\n Write255UShort(&glyph_stream_, glyph.instructions_size);\n WriteBytes(&instruction_stream_,\n glyph.instructions_data, glyph.instructions_size);\n }\n\n bool ShouldWriteSimpleGlyphBbox(const Glyph& glyph) {\n if (glyph.contours.empty() || glyph.contours[0].empty()) {\n return glyph.x_min || glyph.y_min || glyph.x_max || glyph.y_max;\n }\n\n int16_t x_min = glyph.contours[0][0].x;\n int16_t y_min = glyph.contours[0][0].y;\n int16_t x_max = x_min;\n int16_t y_max = y_min;\n for (const auto& contour : glyph.contours) {\n for (const auto& point : contour) {\n if (point.x < x_min) x_min = point.x;\n if (point.x > x_max) x_max = point.x;\n if (point.y < y_min) y_min = point.y;\n if (point.y > y_max) y_max = point.y;\n }\n }\n\n if (glyph.x_min != x_min)\n return true;\n if (glyph.y_min != y_min)\n return true;\n if (glyph.x_max != x_max)\n return true;\n if (glyph.y_max != y_max)\n return true;\n\n return false;\n }\n\n void WriteSimpleGlyph(int glyph_id, const Glyph& glyph) {\n int num_contours = glyph.contours.size();\n WriteUShort(&n_contour_stream_, num_contours);\n if (ShouldWriteSimpleGlyphBbox(glyph)) {\n WriteBbox(glyph_id, glyph);\n }\n for (int i = 0; i < num_contours; i++) {\n Write255UShort(&n_points_stream_, glyph.contours[i].size());\n }\n int lastX = 0;\n int lastY = 0;\n for (int i = 0; i < num_contours; i++) {\n int num_points = glyph.contours[i].size();\n for (int j = 0; j < num_points; j++) {\n int x = glyph.contours[i][j].x;\n int y = glyph.contours[i][j].y;\n int dx = x - lastX;\n int dy = y - lastY;\n WriteTriplet(glyph.contours[i][j].on_curve, dx, dy);\n lastX = x;\n lastY = y;\n }\n }\n if (num_contours > 0) {\n WriteInstructions(glyph);\n }\n }\n\n void WriteCompositeGlyph(int glyph_id, const Glyph& glyph) {\n WriteUShort(&n_contour_stream_, -1);\n WriteBbox(glyph_id, glyph);\n WriteBytes(&composite_stream_,\n glyph.composite_data,\n glyph.composite_data_size);\n if (glyph.have_instructions) {\n WriteInstructions(glyph);\n }\n }\n\n void WriteBbox(int glyph_id, const Glyph& glyph) {\n bbox_bitmap_[glyph_id >> 3] |= 0x80 >> (glyph_id & 7);\n WriteUShort(&bbox_stream_, glyph.x_min);\n WriteUShort(&bbox_stream_, glyph.y_min);\n WriteUShort(&bbox_stream_, glyph.x_max);\n WriteUShort(&bbox_stream_, glyph.y_max);\n }\n\n void WriteTriplet(bool on_curve, int x, int y) {\n int abs_x = std::abs(x);\n int abs_y = std::abs(y);\n int on_curve_bit = on_curve ? 0 : 128;\n int x_sign_bit = (x < 0) ? 0 : 1;\n int y_sign_bit = (y < 0) ? 0 : 1;\n int xy_sign_bits = x_sign_bit + 2 * y_sign_bit;\n if (x == 0 && abs_y < 1280) {\n flag_byte_stream_.push_back(on_curve_bit +\n ((abs_y & 0xf00) >> 7) + y_sign_bit);\n glyph_stream_.push_back(abs_y & 0xff);\n } else if (y == 0 && abs_x < 1280) {\n flag_byte_stream_.push_back(on_curve_bit + 10 +\n ((abs_x & 0xf00) >> 7) + x_sign_bit);\n glyph_stream_.push_back(abs_x & 0xff);\n } else if (abs_x < 65 && abs_y < 65) {\n flag_byte_stream_.push_back(on_curve_bit + 20 +\n ((abs_x - 1) & 0x30) +\n (((abs_y - 1) & 0x30) >> 2) +\n xy_sign_bits);\n glyph_stream_.push_back((((abs_x - 1) & 0xf) << 4) | ((abs_y - 1) & 0xf));\n } else if (abs_x < 769 && abs_y < 769) {\n flag_byte_stream_.push_back(on_curve_bit + 84 +\n 12 * (((abs_x - 1) & 0x300) >> 8) +\n (((abs_y - 1) & 0x300) >> 6) + xy_sign_bits);\n glyph_stream_.push_back((abs_x - 1) & 0xff);\n glyph_stream_.push_back((abs_y - 1) & 0xff);\n } else if (abs_x < 4096 && abs_y < 4096) {\n flag_byte_stream_.push_back(on_curve_bit + 120 + xy_sign_bits);\n glyph_stream_.push_back(abs_x >> 4);\n glyph_stream_.push_back(((abs_x & 0xf) << 4) | (abs_y >> 8));\n glyph_stream_.push_back(abs_y & 0xff);\n } else {\n flag_byte_stream_.push_back(on_curve_bit + 124 + xy_sign_bits);\n glyph_stream_.push_back(abs_x >> 8);\n glyph_stream_.push_back(abs_x & 0xff);\n glyph_stream_.push_back(abs_y >> 8);\n glyph_stream_.push_back(abs_y & 0xff);\n }\n }\n\n std::vector n_contour_stream_;\n std::vector n_points_stream_;\n std::vector flag_byte_stream_;\n std::vector composite_stream_;\n std::vector bbox_bitmap_;\n std::vector bbox_stream_;\n std::vector glyph_stream_;\n std::vector instruction_stream_;\n int n_glyphs_;\n};\n\n} \/\/ namespace\n\nbool TransformGlyfAndLocaTables(Font* font) {\n \/\/ no transform for CFF\n const Font::Table* glyf_table = font->FindTable(kGlyfTableTag);\n const Font::Table* loca_table = font->FindTable(kLocaTableTag);\n if (font->FindTable(kCffTableTag) != NULL\n && glyf_table == NULL\n && loca_table == NULL) {\n return true;\n }\n \/\/ Must share neither or both loca\/glyf\n if (glyf_table->IsReused() != loca_table->IsReused()) {\n return FONT_COMPRESSION_FAILURE();\n }\n if (glyf_table->IsReused()) {\n return true;\n }\n Font::Table* transformed_glyf = &font->tables[kGlyfTableTag ^ 0x80808080];\n Font::Table* transformed_loca = &font->tables[kLocaTableTag ^ 0x80808080];\n\n int num_glyphs = NumGlyphs(*font);\n GlyfEncoder encoder(num_glyphs);\n for (int i = 0; i < num_glyphs; ++i) {\n Glyph glyph;\n const uint8_t* glyph_data;\n size_t glyph_size;\n if (!GetGlyphData(*font, i, &glyph_data, &glyph_size) ||\n (glyph_size > 0 && !ReadGlyph(glyph_data, glyph_size, &glyph))) {\n return FONT_COMPRESSION_FAILURE();\n }\n encoder.Encode(i, glyph);\n }\n encoder.GetTransformedGlyfBytes(&transformed_glyf->buffer);\n\n const Font::Table* head_table = font->FindTable(kHeadTableTag);\n if (head_table == NULL || head_table->length < 52) {\n return FONT_COMPRESSION_FAILURE();\n }\n transformed_glyf->buffer[7] = head_table->data[51]; \/\/ index_format\n\n transformed_glyf->tag = kGlyfTableTag ^ 0x80808080;\n transformed_glyf->length = transformed_glyf->buffer.size();\n transformed_glyf->data = transformed_glyf->buffer.data();\n\n transformed_loca->tag = kLocaTableTag ^ 0x80808080;\n transformed_loca->length = 0;\n transformed_loca->data = NULL;\n\n return true;\n}\n\n} \/\/ namespace woff2\n<|endoftext|>"} {"text":"\/\/\n\/\/ fdf2nii_main.cpp\n\/\/\n\/\/ Created by Tobias Wood on 29\/08\/2013.\n\/\/\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \"fdf.h\"\n#include \"Nifti.h\"\n\nusing namespace std;\n\nstatic bool zip = false, procpar = false;\nstatic double scale = 1.;\nstatic string outPrefix;\nstatic struct option long_options[] =\n{\n\t{\"scale\", required_argument, 0, 's'},\n\t{\"out\", required_argument, 0, 'o'},\n\t{\"zip\", no_argument, 0, 'z'},\n\t{\"procpar\", no_argument, 0, 'p'},\n\t{0, 0, 0, 0}\n};\n\nconst string usage {\n\"fdf2nii - A utility to convert Agilent fdf files to nifti.\\n\\\n\\n\\\nUsage: fdf2nii [opts] image1 image2 ... imageN\\n\\\nimage1 to imageN are paths to the Agilent .img folders, not individual .fdf\\n\\\nfiles\\n\\\nOptions:\\n\\\n -s, --scale: Scale factor for image dimensions (set to 10 for use with SPM).\\n\\\n -o, --out: Specify an output prefix.\\n\\\n -z, --zip: Create .nii.gz files\\n\\\n -p, --procpar: Embed procpar in the nifti header.\\n\"\n};\n\nint main(int argc, char **argv) {\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"s:o:zp\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 0: break; \/\/ It was an option that just sets a flag.\n\t\t\tcase 's': scale = atof(optarg); break;\n\t\t\tcase 'o': outPrefix = string(optarg); break;\n\t\t\tcase 'z': zip = true; break;\n\t\t\tcase 'p': procpar = true; break;\n\t\t\tdefault: cout << \"Unknown option \" << optarg << endl;\n\t\t}\n\t}\n\t\n\tif ((argc - optind) <= 0) {\n\t\tcout << \"No input images specified.\" << endl << usage << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\twhile (optind < argc) {\n\t\tstring inPath(argv[optind]);\n\t\toptind++;\n\t\tstring outPath = outPrefix + inPath.substr(inPath.find_last_of(\"\/\") + 1, inPath.find_last_of(\".\")) + \".nii\";\n\t\tif (zip)\n\t\t\toutPath += \".gz\";\n\t\tcout << \"Converting \" << inPath << \" to \" << outPath << endl;\n\t\ttry {\n\t\t\tAgilent::fdfImage input(inPath);\n\t\t\ttry {\n\t\t\t\tNifti::File output(input.dim(0), input.dim(1), input.dim(2), input.dim(3),\n\t\t\t\t\t\t\t\t input.voxdim(0) * scale, input.voxdim(1) * scale, input.voxdim(2) * scale, 1.,\n\t\t\t\t\t\t\t\t DT_FLOAT32, input.ijk_to_xyz().cast());\n\t\t\t\tif (procpar) {\n\t\t\t\t\tifstream pp_file(inPath + \"\/procpar\", ios::binary);\n\t\t\t\t\tpp_file.seekg(ios::end);\n\t\t\t\t\tsize_t fileSize = pp_file.tellg();\n\t\t\t\t\tpp_file.seekg(ios::beg);\n\t\t\t\t\tvector data; data.reserve(fileSize);\n\t\t\t\t\tdata.assign(istreambuf_iterator(pp_file), istreambuf_iterator());\n\t\t\t\t\toutput.addExtension(NIFTI_ECODE_COMMENT, data);\n\t\t\t\t}\n\t\t\t\toutput.open(outPath, Nifti::Modes::Write);\n\t\t\t\tfor (size_t v = 0; v < input.dim(3); v++) {\n\t\t\t\t\toutput.writeVolume(v, input.readVolume(v));\n\t\t\t\t}\n\t\t\t\toutput.close();\n\t\t\t} catch (exception &e) {\n\t\t\t\tcerr << \"Error, skipping to next input. \" << e.what() << outPath << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} catch (exception &e) {\n\t\t\tcerr << \"Error, skipping to next input. \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n return EXIT_SUCCESS;\n}\nFixed a bug with working out the output path.\/\/\n\/\/ fdf2nii_main.cpp\n\/\/\n\/\/ Created by Tobias Wood on 29\/08\/2013.\n\/\/\n\/\/\n\n#include \n#include \n#include \n#include \n\n#include \"fdf.h\"\n#include \"Nifti.h\"\n\nusing namespace std;\n\nstatic bool zip = false, procpar = false;\nstatic double scale = 1.;\nstatic string outPrefix;\nstatic struct option long_options[] =\n{\n\t{\"scale\", required_argument, 0, 's'},\n\t{\"out\", required_argument, 0, 'o'},\n\t{\"zip\", no_argument, 0, 'z'},\n\t{\"procpar\", no_argument, 0, 'p'},\n\t{0, 0, 0, 0}\n};\n\nconst string usage {\n\"fdf2nii - A utility to convert Agilent fdf files to nifti.\\n\\\n\\n\\\nUsage: fdf2nii [opts] image1 image2 ... imageN\\n\\\nimage1 to imageN are paths to the Agilent .img folders, not individual .fdf\\n\\\nfiles\\n\\\nOptions:\\n\\\n -s, --scale: Scale factor for image dimensions (set to 10 for use with SPM).\\n\\\n -o, --out: Specify an output prefix.\\n\\\n -z, --zip: Create .nii.gz files\\n\\\n -p, --procpar: Embed procpar in the nifti header.\\n\"\n};\n\nint main(int argc, char **argv) {\n\tint indexptr = 0, c;\n\twhile ((c = getopt_long(argc, argv, \"s:o:zp\", long_options, &indexptr)) != -1) {\n\t\tswitch (c) {\n\t\t\tcase 0: break; \/\/ It was an option that just sets a flag.\n\t\t\tcase 's': scale = atof(optarg); break;\n\t\t\tcase 'o': outPrefix = string(optarg); break;\n\t\t\tcase 'z': zip = true; break;\n\t\t\tcase 'p': procpar = true; break;\n\t\t\tdefault: cout << \"Unknown option \" << optarg << endl;\n\t\t}\n\t}\n\t\n\tif ((argc - optind) <= 0) {\n\t\tcout << \"No input images specified.\" << endl << usage << endl;\n\t\texit(EXIT_FAILURE);\n\t}\n\twhile (optind < argc) {\n\t\tstring inPath(argv[optind]);\n\t\toptind++;\n\t\tsize_t fileSep = inPath.find_last_of(\"\/\") + 1;\n\t\tsize_t fileExt = inPath.find_last_of(\".\");\n\t\tif (inPath.substr(fileExt) != \".img\") {\n\t\t\tcerr << inPath << \" is not a valid .img folder. Skipping.\" << endl;\n\t\t\tcontinue;\n\t\t}\n\t\tstring outPath = outPrefix + inPath.substr(fileSep, fileExt - fileSep) + \".nii\";\n\n\t\tif (zip)\n\t\t\toutPath += \".gz\";\n\t\tcout << \"Converting \" << inPath << \" to \" << outPath << endl;\n\t\ttry {\n\t\t\tAgilent::fdfImage input(inPath);\n\t\t\ttry {\n\t\t\t\tNifti::File output(input.dim(0), input.dim(1), input.dim(2), input.dim(3),\n\t\t\t\t\t\t\t\t input.voxdim(0) * scale, input.voxdim(1) * scale, input.voxdim(2) * scale, 1.,\n\t\t\t\t\t\t\t\t DT_FLOAT32, input.ijk_to_xyz().cast());\n\t\t\t\tif (procpar) {\n\t\t\t\t\tifstream pp_file(inPath + \"\/procpar\", ios::binary);\n\t\t\t\t\tpp_file.seekg(ios::end);\n\t\t\t\t\tsize_t fileSize = pp_file.tellg();\n\t\t\t\t\tpp_file.seekg(ios::beg);\n\t\t\t\t\tvector data; data.reserve(fileSize);\n\t\t\t\t\tdata.assign(istreambuf_iterator(pp_file), istreambuf_iterator());\n\t\t\t\t\toutput.addExtension(NIFTI_ECODE_COMMENT, data);\n\t\t\t\t}\n\t\t\t\toutput.open(outPath, Nifti::Modes::Write);\n\t\t\t\tfor (size_t v = 0; v < input.dim(3); v++) {\n\t\t\t\t\toutput.writeVolume(v, input.readVolume(v));\n\t\t\t\t}\n\t\t\t\toutput.close();\n\t\t\t} catch (exception &e) {\n\t\t\t\tcerr << \"Error, skipping to next input. \" << e.what() << outPath << endl;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t} catch (exception &e) {\n\t\t\tcerr << \"Error, skipping to next input. \" << e.what() << endl;\n\t\t\tcontinue;\n\t\t}\n\t}\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef BENG_PROXY_FILE_ADDRESS_HXX\n#define BENG_PROXY_FILE_ADDRESS_HXX\n\n#include \"spawn\/ChildOptions.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include \"util\/Compiler.h\"\n\nclass AllocatorPtr;\nclass MatchInfo;\nstruct DelegateAddress;\n\n\/**\n * The address of a local static file.\n *\/\nstruct FileAddress {\n const char *path;\n const char *deflated = nullptr;\n const char *gzipped = nullptr;\n\n const char *content_type = nullptr;\n\n ConstBuffer content_type_lookup = nullptr;\n\n const char *document_root = nullptr;\n\n \/**\n * The value of #TRANSLATE_EXPAND_PATH. Only used by the\n * translation cache.\n *\/\n const char *expand_path = nullptr;\n\n \/**\n * The value of #TRANSLATE_EXPAND_DOCUMENT_ROOT. Only used by the\n * translation cache.\n *\/\n const char *expand_document_root = nullptr;\n\n DelegateAddress *delegate = nullptr;\n\n bool auto_gzipped = false;\n\n \/**\n * @param _path the new path pointer (taken as-is, no deep copy)\n *\/\n constexpr FileAddress(const char *_path) noexcept\n :path(_path)\n {\n }\n\n FileAddress(AllocatorPtr alloc, const FileAddress &src) noexcept;\n\n FileAddress(const FileAddress &) = delete;\n FileAddress &operator=(const FileAddress &) = delete;\n\n gcc_pure\n bool HasQueryString() const noexcept {\n return false;\n }\n\n \/**\n * Throws std::runtime_error on error.\n *\/\n void Check() const;\n\n gcc_pure\n bool IsValidBase() const noexcept;\n\n FileAddress *SaveBase(AllocatorPtr alloc,\n const char *suffix) const noexcept;\n FileAddress *LoadBase(AllocatorPtr alloc,\n const char *suffix) const noexcept;\n\n \/**\n * Does this address need to be expanded with Expand()?\n *\/\n gcc_pure\n bool IsExpandable() const noexcept;\n\n \/**\n * Throws std::runtime_error on error.\n *\/\n void Expand(AllocatorPtr alloc, const MatchInfo &match_info);\n};\n\n#endif\nfile_address: make constructor explicit\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef BENG_PROXY_FILE_ADDRESS_HXX\n#define BENG_PROXY_FILE_ADDRESS_HXX\n\n#include \"spawn\/ChildOptions.hxx\"\n#include \"util\/ConstBuffer.hxx\"\n\n#include \"util\/Compiler.h\"\n\nclass AllocatorPtr;\nclass MatchInfo;\nstruct DelegateAddress;\n\n\/**\n * The address of a local static file.\n *\/\nstruct FileAddress {\n const char *path;\n const char *deflated = nullptr;\n const char *gzipped = nullptr;\n\n const char *content_type = nullptr;\n\n ConstBuffer content_type_lookup = nullptr;\n\n const char *document_root = nullptr;\n\n \/**\n * The value of #TRANSLATE_EXPAND_PATH. Only used by the\n * translation cache.\n *\/\n const char *expand_path = nullptr;\n\n \/**\n * The value of #TRANSLATE_EXPAND_DOCUMENT_ROOT. Only used by the\n * translation cache.\n *\/\n const char *expand_document_root = nullptr;\n\n DelegateAddress *delegate = nullptr;\n\n bool auto_gzipped = false;\n\n \/**\n * @param _path the new path pointer (taken as-is, no deep copy)\n *\/\n explicit constexpr FileAddress(const char *_path) noexcept\n :path(_path)\n {\n }\n\n FileAddress(AllocatorPtr alloc, const FileAddress &src) noexcept;\n\n FileAddress(const FileAddress &) = delete;\n FileAddress &operator=(const FileAddress &) = delete;\n\n gcc_pure\n bool HasQueryString() const noexcept {\n return false;\n }\n\n \/**\n * Throws std::runtime_error on error.\n *\/\n void Check() const;\n\n gcc_pure\n bool IsValidBase() const noexcept;\n\n FileAddress *SaveBase(AllocatorPtr alloc,\n const char *suffix) const noexcept;\n FileAddress *LoadBase(AllocatorPtr alloc,\n const char *suffix) const noexcept;\n\n \/**\n * Does this address need to be expanded with Expand()?\n *\/\n gcc_pure\n bool IsExpandable() const noexcept;\n\n \/**\n * Throws std::runtime_error on error.\n *\/\n void Expand(AllocatorPtr alloc, const MatchInfo &match_info);\n};\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"file_headers.hxx\"\n#include \"static_headers.hxx\"\n#include \"GrowingBuffer.hxx\"\n#include \"header_writer.hxx\"\n#include \"request.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_headers.hxx\"\n#include \"translation\/Vary.hxx\"\n#include \"http\/List.hxx\"\n#include \"http\/Date.hxx\"\n#include \"util\/DecimalFormat.h\"\n\n#include \n\n#include \n#include \n#include \n\ngcc_pure\nstatic std::chrono::seconds\nread_xattr_max_age(int fd)\n{\n assert(fd >= 0);\n\n char buffer[32];\n ssize_t nbytes = fgetxattr(fd, \"user.MaxAge\",\n buffer, sizeof(buffer) - 1);\n if (nbytes <= 0)\n return std::chrono::seconds::zero();\n\n buffer[nbytes] = 0;\n\n char *endptr;\n unsigned long max_age = strtoul(buffer, &endptr, 10);\n if (*endptr != 0)\n return std::chrono::seconds::zero();\n\n return std::chrono::seconds(max_age);\n}\n\nstatic void\ngenerate_expires(GrowingBuffer &headers,\n std::chrono::system_clock::duration max_age)\n{\n constexpr std::chrono::system_clock::duration max_max_age =\n std::chrono::hours(365 * 24);\n if (max_age > max_max_age)\n \/* limit max_age to approximately one year *\/\n max_age = max_max_age;\n\n \/* generate an \"Expires\" response header *\/\n header_write(headers, \"expires\",\n http_date_format(std::chrono::system_clock::now() + max_age));\n}\n\nstatic bool\nReadETag(int fd, char *buffer, size_t size) noexcept\n{\n assert(fd >= 0);\n assert(size > 4);\n\n const auto nbytes = fgetxattr(fd, \"user.ETag\", buffer + 1, size - 3);\n if (nbytes <= 0)\n return false;\n\n assert((size_t)nbytes < size);\n\n buffer[0] = '\"';\n buffer[nbytes + 1] = '\"';\n buffer[nbytes + 2] = 0;\n return true;\n}\n\nstatic void\nMakeETag(GrowingBuffer &headers, int fd, const struct stat &st)\n{\n char buffer[512];\n\n if (fd < 0 || !ReadETag(fd, buffer, sizeof(buffer)))\n static_etag(buffer, st);\n\n header_write(headers, \"etag\", buffer);\n}\n\nstatic void\nfile_cache_headers(GrowingBuffer &headers,\n int fd, const struct stat &st,\n std::chrono::seconds max_age)\n{\n MakeETag(headers, fd, st);\n\n if (max_age == std::chrono::seconds::zero() && fd >= 0)\n max_age = read_xattr_max_age(fd);\n\n if (max_age > std::chrono::seconds::zero())\n generate_expires(headers, max_age);\n}\n\n\/**\n * Verifies the If-Range request header (RFC 2616 14.27).\n *\/\nstatic bool\ncheck_if_range(const char *if_range, const struct stat &st)\n{\n if (if_range == nullptr)\n return true;\n\n const auto t = http_date_parse(if_range);\n if (t != std::chrono::system_clock::from_time_t(-1))\n return std::chrono::system_clock::from_time_t(st.st_mtime) == t;\n\n char etag[64];\n static_etag(etag, st);\n return strcmp(if_range, etag) == 0;\n}\n\nbool\nfile_evaluate_request(Request &request2,\n int fd, const struct stat &st,\n struct file_request &file_request)\n{\n const auto &request = request2.request;\n const auto &request_headers = request.headers;\n const auto &tr = *request2.translate.response;\n bool ignore_if_modified_since = false;\n\n if (tr.status == 0 && request.method == HTTP_METHOD_GET &&\n !request2.IsTransformationEnabled()) {\n const char *p = request_headers.Get(\"range\");\n\n if (p != nullptr &&\n check_if_range(request_headers.Get(\"if-range\"), st))\n file_request.range.ParseRangeHeader(p);\n }\n\n if (!request2.IsTransformationEnabled()) {\n const char *p = request_headers.Get(\"if-match\");\n if (p != nullptr && strcmp(p, \"*\") != 0) {\n char buffer[64];\n static_etag(buffer, st);\n\n if (!http_list_contains(p, buffer)) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n }\n\n p = request_headers.Get(\"if-none-match\");\n if (p != nullptr && strcmp(p, \"*\") == 0) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n\n if (p != nullptr) {\n char buffer[64];\n static_etag(buffer, st);\n\n if (http_list_contains(p, buffer)) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n\n \/* RFC 2616 14.26: \"If none of the entity tags match, then\n the server MAY perform the requested method as if the\n If-None-Match header field did not exist, but MUST also\n ignore any If-Modified-Since header field(s) in the\n request.\" *\/\n ignore_if_modified_since = true;\n }\n }\n\n if (!request2.IsProcessorEnabled()) {\n const char *p = ignore_if_modified_since\n ? nullptr\n : request_headers.Get(\"if-modified-since\");\n if (p != nullptr) {\n const auto t = http_date_parse(p);\n if (t != std::chrono::system_clock::from_time_t(-1) &&\n std::chrono::system_clock::from_time_t(st.st_mtime) <= t) {\n HttpHeaders headers(request2.pool);\n auto &headers2 = headers.GetBuffer();\n\n file_cache_headers(headers2, fd, st, tr.expires_relative);\n\n write_translation_vary_header(headers2, tr);\n\n response_dispatch(request2, HTTP_STATUS_NOT_MODIFIED,\n std::move(headers), nullptr);\n return false;\n }\n }\n\n p = request_headers.Get(\"if-unmodified-since\");\n if (p != nullptr) {\n const auto t = http_date_parse(p);\n if (t != std::chrono::system_clock::from_time_t(-1) &&\n std::chrono::system_clock::from_time_t(st.st_mtime) > t) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid\nfile_response_headers(GrowingBuffer &headers,\n const char *override_content_type,\n int fd, const struct stat &st,\n std::chrono::seconds expires_relative,\n bool processor_enabled, bool processor_first)\n{\n if (!processor_first && fd >= 0)\n file_cache_headers(headers, fd, st, expires_relative);\n else {\n char etag[64];\n static_etag(etag, st);\n header_write(headers, \"etag\", etag);\n\n if (expires_relative > std::chrono::seconds::zero())\n generate_expires(headers, expires_relative);\n }\n\n if (override_content_type != nullptr) {\n \/* content type override from the translation server *\/\n header_write(headers, \"content-type\", override_content_type);\n } else {\n char content_type[256];\n if (load_xattr_content_type(content_type, sizeof(content_type), fd)) {\n header_write(headers, \"content-type\", content_type);\n } else {\n header_write(headers, \"content-type\", \"application\/octet-stream\");\n }\n }\n\n#ifndef NO_LAST_MODIFIED_HEADER\n if (!processor_enabled)\n header_write(headers, \"last-modified\",\n http_date_format(std::chrono::system_clock::from_time_t(st.st_mtime)));\n#endif\n}\nfile_headers: move code to DispatchNotModified()\/*\n * Copyright 2007-2017 Content Management AG\n * All rights reserved.\n *\n * author: Max Kellermann \n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions\n * are met:\n *\n * - Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n *\n * - Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in the\n * documentation and\/or other materials provided with the\n * distribution.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n * FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,\n * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED\n * OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#include \"file_headers.hxx\"\n#include \"static_headers.hxx\"\n#include \"GrowingBuffer.hxx\"\n#include \"header_writer.hxx\"\n#include \"request.hxx\"\n#include \"http_server\/Request.hxx\"\n#include \"http_headers.hxx\"\n#include \"translation\/Vary.hxx\"\n#include \"http\/List.hxx\"\n#include \"http\/Date.hxx\"\n#include \"util\/DecimalFormat.h\"\n\n#include \n\n#include \n#include \n#include \n\ngcc_pure\nstatic std::chrono::seconds\nread_xattr_max_age(int fd)\n{\n assert(fd >= 0);\n\n char buffer[32];\n ssize_t nbytes = fgetxattr(fd, \"user.MaxAge\",\n buffer, sizeof(buffer) - 1);\n if (nbytes <= 0)\n return std::chrono::seconds::zero();\n\n buffer[nbytes] = 0;\n\n char *endptr;\n unsigned long max_age = strtoul(buffer, &endptr, 10);\n if (*endptr != 0)\n return std::chrono::seconds::zero();\n\n return std::chrono::seconds(max_age);\n}\n\nstatic void\ngenerate_expires(GrowingBuffer &headers,\n std::chrono::system_clock::duration max_age)\n{\n constexpr std::chrono::system_clock::duration max_max_age =\n std::chrono::hours(365 * 24);\n if (max_age > max_max_age)\n \/* limit max_age to approximately one year *\/\n max_age = max_max_age;\n\n \/* generate an \"Expires\" response header *\/\n header_write(headers, \"expires\",\n http_date_format(std::chrono::system_clock::now() + max_age));\n}\n\nstatic bool\nReadETag(int fd, char *buffer, size_t size) noexcept\n{\n assert(fd >= 0);\n assert(size > 4);\n\n const auto nbytes = fgetxattr(fd, \"user.ETag\", buffer + 1, size - 3);\n if (nbytes <= 0)\n return false;\n\n assert((size_t)nbytes < size);\n\n buffer[0] = '\"';\n buffer[nbytes + 1] = '\"';\n buffer[nbytes + 2] = 0;\n return true;\n}\n\nstatic void\nMakeETag(GrowingBuffer &headers, int fd, const struct stat &st)\n{\n char buffer[512];\n\n if (fd < 0 || !ReadETag(fd, buffer, sizeof(buffer)))\n static_etag(buffer, st);\n\n header_write(headers, \"etag\", buffer);\n}\n\nstatic void\nfile_cache_headers(GrowingBuffer &headers,\n int fd, const struct stat &st,\n std::chrono::seconds max_age)\n{\n MakeETag(headers, fd, st);\n\n if (max_age == std::chrono::seconds::zero() && fd >= 0)\n max_age = read_xattr_max_age(fd);\n\n if (max_age > std::chrono::seconds::zero())\n generate_expires(headers, max_age);\n}\n\n\/**\n * Verifies the If-Range request header (RFC 2616 14.27).\n *\/\nstatic bool\ncheck_if_range(const char *if_range, const struct stat &st)\n{\n if (if_range == nullptr)\n return true;\n\n const auto t = http_date_parse(if_range);\n if (t != std::chrono::system_clock::from_time_t(-1))\n return std::chrono::system_clock::from_time_t(st.st_mtime) == t;\n\n char etag[64];\n static_etag(etag, st);\n return strcmp(if_range, etag) == 0;\n}\n\n\/**\n * Generate a \"304 Not Modified\" response.\n *\/\nstatic void\nDispatchNotModified(Request &request2, const TranslateResponse &tr,\n int fd, const struct stat &st)\n{\n HttpHeaders headers(request2.pool);\n auto &headers2 = headers.GetBuffer();\n\n file_cache_headers(headers2, fd, st, tr.expires_relative);\n\n write_translation_vary_header(headers2, tr);\n\n response_dispatch(request2, HTTP_STATUS_NOT_MODIFIED,\n std::move(headers), nullptr);\n}\n\nbool\nfile_evaluate_request(Request &request2,\n int fd, const struct stat &st,\n struct file_request &file_request)\n{\n const auto &request = request2.request;\n const auto &request_headers = request.headers;\n const auto &tr = *request2.translate.response;\n bool ignore_if_modified_since = false;\n\n if (tr.status == 0 && request.method == HTTP_METHOD_GET &&\n !request2.IsTransformationEnabled()) {\n const char *p = request_headers.Get(\"range\");\n\n if (p != nullptr &&\n check_if_range(request_headers.Get(\"if-range\"), st))\n file_request.range.ParseRangeHeader(p);\n }\n\n if (!request2.IsTransformationEnabled()) {\n const char *p = request_headers.Get(\"if-match\");\n if (p != nullptr && strcmp(p, \"*\") != 0) {\n char buffer[64];\n static_etag(buffer, st);\n\n if (!http_list_contains(p, buffer)) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n }\n\n p = request_headers.Get(\"if-none-match\");\n if (p != nullptr && strcmp(p, \"*\") == 0) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n\n if (p != nullptr) {\n char buffer[64];\n static_etag(buffer, st);\n\n if (http_list_contains(p, buffer)) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n\n \/* RFC 2616 14.26: \"If none of the entity tags match, then\n the server MAY perform the requested method as if the\n If-None-Match header field did not exist, but MUST also\n ignore any If-Modified-Since header field(s) in the\n request.\" *\/\n ignore_if_modified_since = true;\n }\n }\n\n if (!request2.IsProcessorEnabled()) {\n const char *p = ignore_if_modified_since\n ? nullptr\n : request_headers.Get(\"if-modified-since\");\n if (p != nullptr) {\n const auto t = http_date_parse(p);\n if (t != std::chrono::system_clock::from_time_t(-1) &&\n std::chrono::system_clock::from_time_t(st.st_mtime) <= t) {\n DispatchNotModified(request2, tr, fd, st);\n return false;\n }\n }\n\n p = request_headers.Get(\"if-unmodified-since\");\n if (p != nullptr) {\n const auto t = http_date_parse(p);\n if (t != std::chrono::system_clock::from_time_t(-1) &&\n std::chrono::system_clock::from_time_t(st.st_mtime) > t) {\n response_dispatch(request2, HTTP_STATUS_PRECONDITION_FAILED,\n HttpHeaders(request2.pool), nullptr);\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid\nfile_response_headers(GrowingBuffer &headers,\n const char *override_content_type,\n int fd, const struct stat &st,\n std::chrono::seconds expires_relative,\n bool processor_enabled, bool processor_first)\n{\n if (!processor_first && fd >= 0)\n file_cache_headers(headers, fd, st, expires_relative);\n else {\n char etag[64];\n static_etag(etag, st);\n header_write(headers, \"etag\", etag);\n\n if (expires_relative > std::chrono::seconds::zero())\n generate_expires(headers, expires_relative);\n }\n\n if (override_content_type != nullptr) {\n \/* content type override from the translation server *\/\n header_write(headers, \"content-type\", override_content_type);\n } else {\n char content_type[256];\n if (load_xattr_content_type(content_type, sizeof(content_type), fd)) {\n header_write(headers, \"content-type\", content_type);\n } else {\n header_write(headers, \"content-type\", \"application\/octet-stream\");\n }\n }\n\n#ifndef NO_LAST_MODIFIED_HEADER\n if (!processor_enabled)\n header_write(headers, \"last-modified\",\n http_date_format(std::chrono::system_clock::from_time_t(st.st_mtime)));\n#endif\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageAccumulate.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to C. Charles Law who developed this class.\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include \"vtkImageAccumulate.h\"\n#include \n#include \n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageAccumulate* vtkImageAccumulate::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkImageAccumulate\");\n if(ret)\n {\n return (vtkImageAccumulate*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkImageAccumulate;\n}\n\n\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Constructor sets default values\nvtkImageAccumulate::vtkImageAccumulate()\n{\n int idx;\n \n for (idx = 0; idx < 3; ++idx)\n {\n this->ComponentSpacing[idx] = 1.0;\n this->ComponentOrigin[idx] = 0.0;\n this->ComponentExtent[idx*2] = 0;\n this->ComponentExtent[idx*2+1] = 0;\n }\n this->ComponentExtent[1] = 255;\n \n this->ReverseStencil = 0;\n\n this->Min[0] = this->Min[1] = this->Min[2] = 0.0;\n this->Max[0] = this->Max[1] = this->Max[2] = 0.0;\n this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;\n this->VoxelCount = 0;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageAccumulate::~vtkImageAccumulate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::SetComponentExtent(int extent[6])\n{\n int idx, modified = 0;\n \n for (idx = 0; idx < 6; ++idx)\n {\n if (this->ComponentExtent[idx] != extent[idx])\n {\n this->ComponentExtent[idx] = extent[idx];\n this->Modified();\n }\n }\n if (modified)\n {\n this->Modified();\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::SetComponentExtent(int minX, int maxX, \n int minY, int maxY,\n int minZ, int maxZ)\n{\n int extent[6];\n \n extent[0] = minX; extent[1] = maxX;\n extent[2] = minY; extent[3] = maxY;\n extent[4] = minZ; extent[5] = maxZ;\n this->SetComponentExtent(extent);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::GetComponentExtent(int extent[6])\n{\n int idx;\n \n for (idx = 0; idx < 6; ++idx)\n {\n extent[idx] = this->ComponentExtent[idx];\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)\n{\n this->vtkProcessObject::SetNthInput(1, stencil); \n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageStencilData *vtkImageAccumulate::GetStencil()\n{\n if (this->NumberOfInputs < 2) \n { \n return NULL;\n }\n else\n {\n return (vtkImageStencilData *)(this->Inputs[1]); \n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This templated function executes the filter for any type of data.\ntemplate \nstatic void vtkImageAccumulateExecute(vtkImageAccumulate *self,\n\t\t\t\t vtkImageData *inData, T *inPtr,\n\t\t\t\t vtkImageData *outData, int *outPtr,\n\t\t\t\t double Min[3],\n\t\t\t\t double Max[3],\n\t\t\t\t double Mean[3],\n\t\t\t\t long int *VoxelCount)\n{\n int idX, idY, idZ, idxC;\n int r1, r2, cr1, cr2, iter, rval;\n int pmin0, pmax0, min0, max0, min1, max1, min2, max2;\n int inInc0, inInc1, inInc2;\n T *tempPtr;\n int *outPtrC;\n int numC, outIdx, *outExtent, *outIncs;\n float *origin, *spacing;\n unsigned long count = 0;\n unsigned long target;\n\n \/\/ variables used to compute statistics (filter handles max 3 components)\n double sum[3];\n sum[0] = sum[1] = sum[2] = 0.0;\n Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;\n Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;\n *VoxelCount = 0;\n \n vtkImageStencilData *stencil = self->GetStencil();\n\n \/\/ Zero count in every bin\n outData->GetExtent(min0, max0, min1, max1, min2, max2);\n memset((void *)outPtr, 0, \n (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));\n \n \/\/ Get information to march through data \n numC = inData->GetNumberOfScalarComponents();\n inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);\n inData->GetIncrements(inInc0, inInc1, inInc2);\n outExtent = outData->GetExtent();\n outIncs = outData->GetIncrements();\n origin = outData->GetOrigin();\n spacing = outData->GetSpacing();\n\n target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)\/50.0);\n target++;\n\n\n \/\/ Loop through input pixels\n for (idZ = min2; idZ <= max2; idZ++)\n {\n for (idY = min1; idY <= max1; idY++)\n {\n if (!(count%target)) \n\t{\n self->UpdateProgress(count\/(50.0*target));\n\t}\n count++;\n\n \/\/ loop over stencil sub-extents\n iter = 0;\n cr1 = min0;\n rval = 1;\n while (rval)\n\t{\n\trval = 0;\n\tr1 = max0 + 1;\n\tr2 = max0;\n\tif (stencil)\n\t { \/\/ get sub extent [r1,r2]\n\t rval = stencil->GetNextExtent(r1, r2, min0, max0, idY, idZ, iter);\n\t }\n\t\/\/ sub extents [cr1,cr2] are the complement of sub extents [r1,r2]\n\tcr2 = r1 - 1;\n\n\tpmin0 = cr1;\n\tpmax0 = cr2;\n\t\/\/ check whether to use [r1,r2] or its complement [cr1,cr2]\n\tif (stencil && !self->GetReverseStencil())\n\t {\n\t if (rval == 0)\n\t {\n\t break;\n\t }\n\t pmin0 = r1;\n\t pmax0 = r2;\n\t }\n\t\/\/ set up cr1 for next iteration\n\tcr1 = r2 + 1;\n\t\n\t\/\/ set up pointer for sub extent\n\ttempPtr = inPtr + (inInc2*(idZ - min2) +\n\t\t\t inInc1*(idY - min1) +\n\t\t\t numC*(pmin0 - min0));\n\n\t\/\/ accumulate over the sub extent\n\tfor (idX = pmin0; idX <= pmax0; idX++)\n\t {\n\t \/\/ find the bin for this pixel.\n\t outPtrC = outPtr;\n\t for (idxC = 0; idxC < numC; ++idxC)\n\t {\n\t \/\/ Gather statistics\n\t sum[idxC]+= *tempPtr;\n\t if (*tempPtr > Max[idxC])\n\t {\n\t Max[idxC] = *tempPtr;\n\t }\n\t else if (*tempPtr < Min[idxC])\n\t {\n\t Min[idxC] = *tempPtr;\n\t }\n\t (*VoxelCount)++;\n\t \/\/ compute the index\n\t outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) \n\t\t\t\t \/ spacing[idxC]));\n\t if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])\n\t {\n\t \/\/ Out of bin range\n\t outPtrC = NULL;\n\t break;\n\t }\n\t outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];\n\t }\n\t if (outPtrC)\n\t {\n\t ++(*outPtrC);\n\t }\n\t }\n }\n }\n }\n \n if (*VoxelCount) \/\/ avoid the div0\n {\n Mean[0] = sum[0] \/ (double)*VoxelCount; \n Mean[1] = sum[1] \/ (double)*VoxelCount; \n Mean[2] = sum[2] \/ (double)*VoxelCount; \n }\n else\n {\n Mean[0] = Mean[1] = Mean[2] = 0.0;\n }\n \n}\n\n \n\n\/\/----------------------------------------------------------------------------\n\/\/ This method is passed a input and output Data, and executes the filter\n\/\/ algorithm to fill the output from the input.\n\/\/ It just executes a switch statement to call the correct function for\n\/\/ the Datas data types.\nvoid vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))\n{\n void *inPtr;\n void *outPtr;\n vtkImageData *inData = this->GetInput();\n vtkImageData *outData = this->GetOutput();\n \n vtkDebugMacro(<<\"Executing image accumulate\");\n \n \/\/ We need to allocate our own scalars since we are overriding\n \/\/ the superclasses \"Execute()\" method.\n outData->SetExtent(outData->GetWholeExtent());\n outData->AllocateScalars();\n \n inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());\n outPtr = outData->GetScalarPointer();\n \n \/\/ Components turned into x, y and z\n if (this->GetInput()->GetNumberOfScalarComponents() > 3)\n {\n vtkErrorMacro(\"This filter can handle upto 3 components\");\n return;\n }\n \n \/\/ this filter expects that output is type int.\n if (outData->GetScalarType() != VTK_INT)\n {\n vtkErrorMacro(<< \"Execute: out ScalarType \" << outData->GetScalarType()\n << \" must be int\\n\");\n return;\n }\n \n switch (inData->GetScalarType())\n {\n vtkTemplateMacro9(vtkImageAccumulateExecute, this, \n inData, (VTK_TT *)(inPtr), \n outData, (int *)(outPtr),\n\t\t this->Min, this->Max,\n\t\t this->Mean, &this->VoxelCount);\n default:\n vtkErrorMacro(<< \"Execute: Unknown ScalarType\");\n return;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::ExecuteInformation(vtkImageData *input, \n vtkImageData *output)\n{\n output->SetWholeExtent(this->ComponentExtent);\n output->SetOrigin(this->ComponentOrigin);\n output->SetSpacing(this->ComponentSpacing);\n output->SetNumberOfScalarComponents(1);\n output->SetScalarType(VTK_INT);\n\n \/\/ need to set the spacing and origin of the stencil to match the output\n vtkImageStencilData *stencil = this->GetStencil();\n if (stencil)\n {\n stencil->SetSpacing(input->GetSpacing());\n stencil->SetOrigin(input->GetOrigin());\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Get ALL of the input.\nvoid vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6], \n int outExt[6])\n{\n int *wholeExtent;\n\n outExt = outExt;\n wholeExtent = this->GetInput()->GetWholeExtent();\n memcpy(inExt, wholeExtent, 6*sizeof(int));\n}\n\n\nvoid vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkImageToImageFilter::PrintSelf(os,indent);\n\n os << indent << \"Mean: \" << this->Mean << \"\\n\";\n os << indent << \"Min: \" << this->Min << \"\\n\";\n os << indent << \"Max: \" << this->Max << \"\\n\";\n os << indent << \"VoxelCount: \" << this->VoxelCount << \"\\n\";\n os << indent << \"Stencil: \" << this->GetStencil() << \"\\n\";\n os << indent << \"ReverseStencil: \" << (this->ReverseStencil ?\n\t\t \"On\\n\" : \"Off\\n\");\n\n os << indent << \"ComponentOrigin: ( \"\n << this->ComponentOrigin[0] << \", \"\n << this->ComponentOrigin[1] << \", \"\n << this->ComponentOrigin[2] << \" )\\n\";\n\n os << indent << \"ComponentSpacing: ( \"\n << this->ComponentSpacing[0] << \", \"\n << this->ComponentSpacing[1] << \", \"\n << this->ComponentSpacing[2] << \" )\\n\";\n\n os << indent << \"ComponentExtent: ( \"\n << this->ComponentExtent[0] << \",\" << this->ComponentExtent[1] << \" \"\n << this->ComponentExtent[2] << \",\" << this->ComponentExtent[3] << \" \"\n << this->ComponentExtent[4] << \",\" << this->ComponentExtent[5] << \" }\\n\";\n}\n\nENH: simplify reversal of stencil, also some 'progress' stuff was missing\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkImageAccumulate.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n Thanks: Thanks to C. Charles Law who developed this class.\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n\n#include \"vtkImageAccumulate.h\"\n#include \n#include \n#include \"vtkObjectFactory.h\"\n\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageAccumulate* vtkImageAccumulate::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkImageAccumulate\");\n if(ret)\n {\n return (vtkImageAccumulate*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkImageAccumulate;\n}\n\n\n\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ Constructor sets default values\nvtkImageAccumulate::vtkImageAccumulate()\n{\n int idx;\n \n for (idx = 0; idx < 3; ++idx)\n {\n this->ComponentSpacing[idx] = 1.0;\n this->ComponentOrigin[idx] = 0.0;\n this->ComponentExtent[idx*2] = 0;\n this->ComponentExtent[idx*2+1] = 0;\n }\n this->ComponentExtent[1] = 255;\n \n this->ReverseStencil = 0;\n\n this->Min[0] = this->Min[1] = this->Min[2] = 0.0;\n this->Max[0] = this->Max[1] = this->Max[2] = 0.0;\n this->Mean[0] = this->Mean[1] = this->Mean[2] = 0.0;\n this->VoxelCount = 0;\n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageAccumulate::~vtkImageAccumulate()\n{\n}\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::SetComponentExtent(int extent[6])\n{\n int idx, modified = 0;\n \n for (idx = 0; idx < 6; ++idx)\n {\n if (this->ComponentExtent[idx] != extent[idx])\n {\n this->ComponentExtent[idx] = extent[idx];\n this->Modified();\n }\n }\n if (modified)\n {\n this->Modified();\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::SetComponentExtent(int minX, int maxX, \n int minY, int maxY,\n int minZ, int maxZ)\n{\n int extent[6];\n \n extent[0] = minX; extent[1] = maxX;\n extent[2] = minY; extent[3] = maxY;\n extent[4] = minZ; extent[5] = maxZ;\n this->SetComponentExtent(extent);\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::GetComponentExtent(int extent[6])\n{\n int idx;\n \n for (idx = 0; idx < 6; ++idx)\n {\n extent[idx] = this->ComponentExtent[idx];\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::SetStencil(vtkImageStencilData *stencil)\n{\n this->vtkProcessObject::SetNthInput(1, stencil); \n}\n\n\n\/\/----------------------------------------------------------------------------\nvtkImageStencilData *vtkImageAccumulate::GetStencil()\n{\n if (this->NumberOfInputs < 2) \n { \n return NULL;\n }\n else\n {\n return (vtkImageStencilData *)(this->Inputs[1]); \n }\n}\n\n\n\/\/----------------------------------------------------------------------------\n\/\/ This templated function executes the filter for any type of data.\ntemplate \nstatic void vtkImageAccumulateExecute(vtkImageAccumulate *self,\n\t\t\t\t vtkImageData *inData, T *inPtr,\n\t\t\t\t vtkImageData *outData, int *outPtr,\n\t\t\t\t double Min[3],\n\t\t\t\t double Max[3],\n\t\t\t\t double Mean[3],\n\t\t\t\t long int *VoxelCount)\n{\n int idX, idY, idZ, idxC;\n int iter, pmin0, pmax0, min0, max0, min1, max1, min2, max2;\n int inInc0, inInc1, inInc2;\n T *tempPtr;\n int *outPtrC;\n int numC, outIdx, *outExtent, *outIncs;\n float *origin, *spacing;\n unsigned long count = 0;\n unsigned long target;\n\n \/\/ variables used to compute statistics (filter handles max 3 components)\n double sum[3];\n sum[0] = sum[1] = sum[2] = 0.0;\n Min[0] = Min[1] = Min[2] = VTK_DOUBLE_MAX;\n Max[0] = Max[1] = Max[2] = VTK_DOUBLE_MIN;\n *VoxelCount = 0;\n \n vtkImageStencilData *stencil = self->GetStencil();\n\n \/\/ Zero count in every bin\n outData->GetExtent(min0, max0, min1, max1, min2, max2);\n memset((void *)outPtr, 0, \n (max0-min0+1)*(max1-min1+1)*(max2-min2+1)*sizeof(int));\n \n \/\/ Get information to march through data \n numC = inData->GetNumberOfScalarComponents();\n inData->GetUpdateExtent(min0, max0, min1, max1, min2, max2);\n inData->GetIncrements(inInc0, inInc1, inInc2);\n outExtent = outData->GetExtent();\n outIncs = outData->GetIncrements();\n origin = outData->GetOrigin();\n spacing = outData->GetSpacing();\n\n target = (unsigned long)((max2 - min2 + 1)*(max1 - min1 +1)\/50.0);\n target++;\n\n\n \/\/ Loop through input pixels\n for (idZ = min2; idZ <= max2; idZ++)\n {\n for (idY = min1; idY <= max1; idY++)\n {\n if (!(count%target)) \n\t{\n self->UpdateProgress(count\/(50.0*target));\n\t}\n count++;\n\n \/\/ loop over stencil sub-extents\n iter = 0;\n if (self->GetReverseStencil())\n\t{ \/\/ flag that we want the complementary extents\n \titer = -1;\n\t}\n\n pmin0 = min0;\n pmax0 = max0;\n while ((stencil != 0 && \n\t stencil->GetNextExtent(pmin0,pmax0,min0,max0,idY,idZ,iter)) ||\n\t (stencil == 0 && iter++ == 0))\n\t{\n\t\/\/ set up pointer for sub extent\n\ttempPtr = inPtr + (inInc2*(idZ - min2) +\n\t\t\t inInc1*(idY - min1) +\n\t\t\t numC*(pmin0 - min0));\n\n\t\/\/ accumulate over the sub extent\n\tfor (idX = pmin0; idX <= pmax0; idX++)\n\t {\n\t \/\/ find the bin for this pixel.\n\t outPtrC = outPtr;\n\t for (idxC = 0; idxC < numC; ++idxC)\n\t {\n\t \/\/ Gather statistics\n\t sum[idxC]+= *tempPtr;\n\t if (*tempPtr > Max[idxC])\n\t {\n\t Max[idxC] = *tempPtr;\n\t }\n\t else if (*tempPtr < Min[idxC])\n\t {\n\t Min[idxC] = *tempPtr;\n\t }\n\t (*VoxelCount)++;\n\t \/\/ compute the index\n\t outIdx = (int) floor((((double)*tempPtr++ - origin[idxC]) \n\t\t\t\t \/ spacing[idxC]));\n\t if (outIdx < outExtent[idxC*2] || outIdx > outExtent[idxC*2+1])\n\t {\n\t \/\/ Out of bin range\n\t outPtrC = NULL;\n\t break;\n\t }\n\t outPtrC += (outIdx - outExtent[idxC*2]) * outIncs[idxC];\n\t }\n\t if (outPtrC)\n\t {\n\t ++(*outPtrC);\n\t }\n\t }\n }\n }\n }\n \n if (*VoxelCount) \/\/ avoid the div0\n {\n Mean[0] = sum[0] \/ (double)*VoxelCount; \n Mean[1] = sum[1] \/ (double)*VoxelCount; \n Mean[2] = sum[2] \/ (double)*VoxelCount; \n }\n else\n {\n Mean[0] = Mean[1] = Mean[2] = 0.0;\n }\n \n}\n\n \n\n\/\/----------------------------------------------------------------------------\n\/\/ This method is passed a input and output Data, and executes the filter\n\/\/ algorithm to fill the output from the input.\n\/\/ It just executes a switch statement to call the correct function for\n\/\/ the Datas data types.\nvoid vtkImageAccumulate::ExecuteData(vtkDataObject *vtkNotUsed(out))\n{\n void *inPtr;\n void *outPtr;\n vtkImageData *inData = this->GetInput();\n vtkImageData *outData = this->GetOutput();\n \n vtkDebugMacro(<<\"Executing image accumulate\");\n \n \/\/ We need to allocate our own scalars since we are overriding\n \/\/ the superclasses \"Execute()\" method.\n outData->SetExtent(outData->GetWholeExtent());\n outData->AllocateScalars();\n \n inPtr = inData->GetScalarPointerForExtent(inData->GetUpdateExtent());\n outPtr = outData->GetScalarPointer();\n \n \/\/ Components turned into x, y and z\n if (this->GetInput()->GetNumberOfScalarComponents() > 3)\n {\n vtkErrorMacro(\"This filter can handle upto 3 components\");\n return;\n }\n \n \/\/ this filter expects that output is type int.\n if (outData->GetScalarType() != VTK_INT)\n {\n vtkErrorMacro(<< \"Execute: out ScalarType \" << outData->GetScalarType()\n << \" must be int\\n\");\n return;\n }\n \n switch (inData->GetScalarType())\n {\n vtkTemplateMacro9(vtkImageAccumulateExecute, this, \n inData, (VTK_TT *)(inPtr), \n outData, (int *)(outPtr),\n\t\t this->Min, this->Max,\n\t\t this->Mean, &this->VoxelCount);\n default:\n vtkErrorMacro(<< \"Execute: Unknown ScalarType\");\n return;\n }\n}\n\n\n\/\/----------------------------------------------------------------------------\nvoid vtkImageAccumulate::ExecuteInformation(vtkImageData *input, \n vtkImageData *output)\n{\n output->SetWholeExtent(this->ComponentExtent);\n output->SetOrigin(this->ComponentOrigin);\n output->SetSpacing(this->ComponentSpacing);\n output->SetNumberOfScalarComponents(1);\n output->SetScalarType(VTK_INT);\n\n \/\/ need to set the spacing and origin of the stencil to match the output\n vtkImageStencilData *stencil = this->GetStencil();\n if (stencil)\n {\n stencil->SetSpacing(input->GetSpacing());\n stencil->SetOrigin(input->GetOrigin());\n }\n}\n\n\/\/----------------------------------------------------------------------------\n\/\/ Get ALL of the input.\nvoid vtkImageAccumulate::ComputeInputUpdateExtent(int inExt[6], \n int outExt[6])\n{\n int *wholeExtent;\n\n outExt = outExt;\n wholeExtent = this->GetInput()->GetWholeExtent();\n memcpy(inExt, wholeExtent, 6*sizeof(int));\n}\n\n\nvoid vtkImageAccumulate::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkImageToImageFilter::PrintSelf(os,indent);\n\n os << indent << \"Mean: \" << this->Mean << \"\\n\";\n os << indent << \"Min: \" << this->Min << \"\\n\";\n os << indent << \"Max: \" << this->Max << \"\\n\";\n os << indent << \"VoxelCount: \" << this->VoxelCount << \"\\n\";\n os << indent << \"Stencil: \" << this->GetStencil() << \"\\n\";\n os << indent << \"ReverseStencil: \" << (this->ReverseStencil ?\n\t\t \"On\\n\" : \"Off\\n\");\n\n os << indent << \"ComponentOrigin: ( \"\n << this->ComponentOrigin[0] << \", \"\n << this->ComponentOrigin[1] << \", \"\n << this->ComponentOrigin[2] << \" )\\n\";\n\n os << indent << \"ComponentSpacing: ( \"\n << this->ComponentSpacing[0] << \", \"\n << this->ComponentSpacing[1] << \", \"\n << this->ComponentSpacing[2] << \" )\\n\";\n\n os << indent << \"ComponentExtent: ( \"\n << this->ComponentExtent[0] << \",\" << this->ComponentExtent[1] << \" \"\n << this->ComponentExtent[2] << \",\" << this->ComponentExtent[3] << \" \"\n << this->ComponentExtent[4] << \",\" << this->ComponentExtent[5] << \" }\\n\";\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#ifndef D2D_LAMBERT_SCANNER_HPP\n#define D2D_LAMBERT_SCANNER_HPP\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace d2d\n{\n\n\/\/! Execute lambert_scanner.\n\/*!\n * Executes lambert_scanner application mode that performs a grid search to compute \\f$\\Delta V\\f$\n * for debris-to-debris transfers. The transfers are modelled as conic sections. The Lambert\n * targeter employed is based on Izzo (2014), implemented in PyKEP (Izzo, 2012).\n *\n * The results obtained from the grid search are stored in a SQLite database, containing the\n * following table:\n *\n *\t- \"lambert_scanner_results\": contains all Lambert transfers computed during grid search\n *\n * @param[in] config User-defined configuration options (extracted from JSON input file)\n *\/\nvoid executeLambertScanner( const rapidjson::Document& config );\n\n\/\/! lambert_scanner input.\n\/*!\n * Data struct containing all valid lambert_scanner input parameters. This struct is populated by\n * the checkLambertScannerInput() function and can be used to execute the lambert_scanner\n * application mode.\n *\n * @sa checkLambertScannerInput, executeLambertScanner\n *\/\nstruct LambertScannerInput\n{\npublic:\n\n \/\/! Construct data struct.\n \/*!\n * Constructs data struct based on verified input parameters.\n *\n * @sa checkLambertScannerInput, executeLambertScanner\n * @param[in] aCatalogPath Path to TLE catalog\n * @param[in] aDatabasePath Path to SQLite database\n * @param[in] aDepartureEpoch Departure epoch for all transfers\n * @param[in] aTimeOfFlightMinimum Minimum time-of-flight [s]\n * @param[in] aTimeOfFlightMaximum Maximum time-of-flight [s]\n * @param[in] someTimeOfFlightSteps Number of steps to take in time-of-flight grid\n * @param[in] aTimeOfFlightStepSize Time-of-flight step size (derived parameter) [s]\n * @param[in] progradeFlag Flag indicating if prograde transfer should be computed\n * (false = retrograde)\n * @param[in] aRevolutionsMaximum Maximum number of revolutions\n * @param[in] aShortlistLength Number of transfers to include in shortlist\n * @param[in] aShortlistPath Path to shortlist file\n *\/\n LambertScannerInput( const std::string& aCatalogPath,\n const std::string& aDatabasePath,\n const DateTime& aDepartureEpoch,\n const double aTimeOfFlightMinimum,\n const double aTimeOfFlightMaximum,\n const double someTimeOfFlightSteps,\n const double aTimeOfFlightStepSize,\n const bool progradeFlag,\n const int aRevolutionsMaximum,\n const int aShortlistLength,\n const std::string& aShortlistPath )\n : catalogPath( aCatalogPath ),\n databasePath( aDatabasePath ),\n departureEpoch( aDepartureEpoch ),\n timeOfFlightMinimum( aTimeOfFlightMinimum ),\n timeOfFlightMaximum( aTimeOfFlightMaximum ),\n timeOfFlightSteps( someTimeOfFlightSteps ),\n timeOfFlightStepSize( aTimeOfFlightStepSize ),\n isPrograde( progradeFlag ),\n revolutionsMaximum( aRevolutionsMaximum ),\n shortlistLength( aShortlistLength ),\n shortlistPath( aShortlistPath )\n { }\n\n \/\/! Path to TLE catalog.\n const std::string catalogPath;\n\n \/\/! Path to SQLite database to store output.\n const std::string databasePath;\n\n \/\/! Departure epoch.\n const DateTime departureEpoch;\n\n \/\/! Minimum time-of-flight [s].\n const double timeOfFlightMinimum;\n\n \/\/! Maximum time-of-flight [s].\n const double timeOfFlightMaximum;\n\n \/\/! Number of time-of-flight steps.\n const double timeOfFlightSteps;\n\n \/\/! Time-of-flight step size [s].\n const double timeOfFlightStepSize;\n\n \/\/! Flag indicating if transfers are prograde. False indicates retrograde.\n const bool isPrograde;\n\n \/\/! Maximum number of revolutions (N) for transfer. Number of revolutions is 2*N+1.\n const int revolutionsMaximum;\n\n \/\/! Number of entries (lowest transfer \\f$\\Delta V\\f$) to include in shortlist.\n const int shortlistLength;\n\n \/\/! Path to shortlist file.\n const std::string shortlistPath;\n\nprotected:\n\nprivate:\n};\n\n\/\/! Check lambert_scanner input parameters.\n\/*!\n * Checks that all inputs for the lambert_scanner application mode are valid. If not, an error is\n * thrown with a short description of the problem. If all inputs are valid, a data struct\n * containing all the inputs is returned, which is subsequently used to execute lambert_scanner\n * and related functions.\n *\n * @sa executeLambertScanner, LambertScannerInput\n * @param[in] config User-defined configuration options (extracted from JSON input file)\n * @return Struct containing all valid input to execute lambert_scanner\n *\/\nLambertScannerInput checkLambertScannerInput( const rapidjson::Document& config );\n\n\/\/! Create lambert_scanner table.\n\/*!\n * Creates lambert_scanner table in SQLite database used to store results obtaned from running\n * the lambert_scanner application mode.\n *\n * @sa executeLambertScanner\n * @param[in] database SQLite database handle\n *\/\nvoid createLambertScannerTable( SQLite::Database& database );\n\n\/\/! Write transfer shortlist to file.\n\/*!\n * Writes shortlist of debris-to-debris Lambert transfers to file. The shortlist is based on the\n * requested number of transfers with the lowest transfer \\f$\\Delta V\\f$, retrieved by sorting the\n * transfers in the SQLite database.\n *\n * @sa executeLambertScanner, createLambertScannerTable\n * @param[in] database SQLite database handle\n * @param[in] shortlistNumber Number of entries to include in shortlist (if it exceeds number of\n * entries in database table, the whole table is written to file)\n * @param[in] shortlistPath Path to shortlist file\n *\/\nvoid writeTransferShortlist( SQLite::Database& database,\n const int shortlistNumber,\n const std::string& shortlistPath );\n\n} \/\/ namespace d2d\n\n\/*!\n * Izzo, D. (2014) Revisiting Lambert's problem, http:\/\/arxiv.org\/abs\/1403.2705.\n * Izzo, D. (2012) PyGMO and PyKEP: open source tools for massively parallel optimization in\n * \tastrodynamics (the case of interplanetary trajectory optimization). Proceed. Fifth\n * International Conf. Astrodynam. Tools and Techniques, ESA\/ESTEC, The Netherlands.\n *\/\n\n#endif \/\/ D2D_LAMBERT_SCANNER_HPP\nUpdate Doxygen short description for Lambert scanner input struct.\/*\n * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#ifndef D2D_LAMBERT_SCANNER_HPP\n#define D2D_LAMBERT_SCANNER_HPP\n\n#include \n\n#include \n\n#include \n\n#include \n\n#include \n\nnamespace d2d\n{\n\n\/\/! Execute lambert_scanner.\n\/*!\n * Executes lambert_scanner application mode that performs a grid search to compute \\f$\\Delta V\\f$\n * for debris-to-debris transfers. The transfers are modelled as conic sections. The Lambert\n * targeter employed is based on Izzo (2014), implemented in PyKEP (Izzo, 2012).\n *\n * The results obtained from the grid search are stored in a SQLite database, containing the\n * following table:\n *\n *\t- \"lambert_scanner_results\": contains all Lambert transfers computed during grid search\n *\n * @param[in] config User-defined configuration options (extracted from JSON input file)\n *\/\nvoid executeLambertScanner( const rapidjson::Document& config );\n\n\/\/! Input for lambert_scanner application mode.\n\/*!\n * Data struct containing all valid lambert_scanner input parameters. This struct is populated by\n * the checkLambertScannerInput() function and can be used to execute the lambert_scanner\n * application mode.\n *\n * @sa checkLambertScannerInput, executeLambertScanner\n *\/\nstruct LambertScannerInput\n{\npublic:\n\n \/\/! Construct data struct.\n \/*!\n * Constructs data struct based on verified input parameters.\n *\n * @sa checkLambertScannerInput, executeLambertScanner\n * @param[in] aCatalogPath Path to TLE catalog\n * @param[in] aDatabasePath Path to SQLite database\n * @param[in] aDepartureEpoch Departure epoch for all transfers\n * @param[in] aTimeOfFlightMinimum Minimum time-of-flight [s]\n * @param[in] aTimeOfFlightMaximum Maximum time-of-flight [s]\n * @param[in] someTimeOfFlightSteps Number of steps to take in time-of-flight grid\n * @param[in] aTimeOfFlightStepSize Time-of-flight step size (derived parameter) [s]\n * @param[in] progradeFlag Flag indicating if prograde transfer should be computed\n * (false = retrograde)\n * @param[in] aRevolutionsMaximum Maximum number of revolutions\n * @param[in] aShortlistLength Number of transfers to include in shortlist\n * @param[in] aShortlistPath Path to shortlist file\n *\/\n LambertScannerInput( const std::string& aCatalogPath,\n const std::string& aDatabasePath,\n const DateTime& aDepartureEpoch,\n const double aTimeOfFlightMinimum,\n const double aTimeOfFlightMaximum,\n const double someTimeOfFlightSteps,\n const double aTimeOfFlightStepSize,\n const bool progradeFlag,\n const int aRevolutionsMaximum,\n const int aShortlistLength,\n const std::string& aShortlistPath )\n : catalogPath( aCatalogPath ),\n databasePath( aDatabasePath ),\n departureEpoch( aDepartureEpoch ),\n timeOfFlightMinimum( aTimeOfFlightMinimum ),\n timeOfFlightMaximum( aTimeOfFlightMaximum ),\n timeOfFlightSteps( someTimeOfFlightSteps ),\n timeOfFlightStepSize( aTimeOfFlightStepSize ),\n isPrograde( progradeFlag ),\n revolutionsMaximum( aRevolutionsMaximum ),\n shortlistLength( aShortlistLength ),\n shortlistPath( aShortlistPath )\n { }\n\n \/\/! Path to TLE catalog.\n const std::string catalogPath;\n\n \/\/! Path to SQLite database to store output.\n const std::string databasePath;\n\n \/\/! Departure epoch.\n const DateTime departureEpoch;\n\n \/\/! Minimum time-of-flight [s].\n const double timeOfFlightMinimum;\n\n \/\/! Maximum time-of-flight [s].\n const double timeOfFlightMaximum;\n\n \/\/! Number of time-of-flight steps.\n const double timeOfFlightSteps;\n\n \/\/! Time-of-flight step size [s].\n const double timeOfFlightStepSize;\n\n \/\/! Flag indicating if transfers are prograde. False indicates retrograde.\n const bool isPrograde;\n\n \/\/! Maximum number of revolutions (N) for transfer. Number of revolutions is 2*N+1.\n const int revolutionsMaximum;\n\n \/\/! Number of entries (lowest transfer \\f$\\Delta V\\f$) to include in shortlist.\n const int shortlistLength;\n\n \/\/! Path to shortlist file.\n const std::string shortlistPath;\n\nprotected:\n\nprivate:\n};\n\n\/\/! Check lambert_scanner input parameters.\n\/*!\n * Checks that all inputs for the lambert_scanner application mode are valid. If not, an error is\n * thrown with a short description of the problem. If all inputs are valid, a data struct\n * containing all the inputs is returned, which is subsequently used to execute lambert_scanner\n * and related functions.\n *\n * @sa executeLambertScanner, LambertScannerInput\n * @param[in] config User-defined configuration options (extracted from JSON input file)\n * @return Struct containing all valid input to execute lambert_scanner\n *\/\nLambertScannerInput checkLambertScannerInput( const rapidjson::Document& config );\n\n\/\/! Create lambert_scanner table.\n\/*!\n * Creates lambert_scanner table in SQLite database used to store results obtaned from running\n * the lambert_scanner application mode.\n *\n * @sa executeLambertScanner\n * @param[in] database SQLite database handle\n *\/\nvoid createLambertScannerTable( SQLite::Database& database );\n\n\/\/! Write transfer shortlist to file.\n\/*!\n * Writes shortlist of debris-to-debris Lambert transfers to file. The shortlist is based on the\n * requested number of transfers with the lowest transfer \\f$\\Delta V\\f$, retrieved by sorting the\n * transfers in the SQLite database.\n *\n * @sa executeLambertScanner, createLambertScannerTable\n * @param[in] database SQLite database handle\n * @param[in] shortlistNumber Number of entries to include in shortlist (if it exceeds number of\n * entries in database table, the whole table is written to file)\n * @param[in] shortlistPath Path to shortlist file\n *\/\nvoid writeTransferShortlist( SQLite::Database& database,\n const int shortlistNumber,\n const std::string& shortlistPath );\n\n} \/\/ namespace d2d\n\n\/*!\n * Izzo, D. (2014) Revisiting Lambert's problem, http:\/\/arxiv.org\/abs\/1403.2705.\n * Izzo, D. (2012) PyGMO and PyKEP: open source tools for massively parallel optimization in\n * \tastrodynamics (the case of interplanetary trajectory optimization). Proceed. Fifth\n * International Conf. Astrodynam. Tools and Techniques, ESA\/ESTEC, The Netherlands.\n *\/\n\n#endif \/\/ D2D_LAMBERT_SCANNER_HPP\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<>n>>f>>p1>>p2;\n\tREP(i,1,n){\n\t\tcin>>c[i];\n\t}\n\n\tREP(i,1,n){\n\t\tcin>>fa[i];\n\t\tmina=min(mina,fa[i]);\n\t}\n\n\tREP(i,1,n){\n\t\tcin>>fb[i];\n\t\tminb=min(minb,fb[i]);\n\t}\n\n\tmemset(dpa , 0 ,sizeof dpa);\n\tmemset(dpb , 0, sizeof dpb);\n\treturn ;\n}\n\nvoid Solve(){\n\tint ansa,ansb;\n\tREP(i,mina,f)\n\t{\n\t\tREP(j,1,n){\n\t\t\tif(i>=fa[j]){\n\t\t\t\tdpa[i]=max(dpa[i],dpa[i-fa[j]]+c[j]);\n\t\t\t}\n\t\t}\n\n\t\tif(dpa[i]>=p1){\n\t\t\tansa=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tREP(i,minb,f){\n\t\tREP(j,1,n){\n\t\t\tif(i>=fb[j]){\n\t\t\t\tdpb[i]=max(dpb[i],dpb[i-fb[j]]+c[j]);\n\t\t\t}\n\t\t}\n\t\tif(dpb[i]>=p2){\n\t\t\tansb=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(ansa+ansb<=f){\n\t\tprint(1);\n\t}else{\n\t\tprint(0);\n\t}\n\n\treturn ;\n}\n\nint main(){\n\n\tfreopen(\"uoj10680.in\",\"r\",stdin);\n\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t--)\n\tInit(),Solve();\n\treturn 0;\n}update uoj10680#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\n#define ll long long \n#define lson l,mid,id<<1\n#define rson mid+1,r,id<<1|1\n\ntypedef pairpii;\ntypedef pairpll;\ntypedef pairpdd;\n\nconst double eps = 1e-6;\nconst ll LINF = 0x3f3f3f3f3f3f3f3fLL;\nconst int INF = 0x3f3f3f3f;\nconst double FINF = 1e18;\n\n#define x first\n#define y second\n\n#define REP(i,j,k) for(int i =(j);i<=(k);i++)\n#define REPD(i,j,k) for(int i =(j);i>=(k);i--)\n#define print(x) cout<<(x)<>n>>f>>p1>>p2;\n\tREP(i,1,n){\n\t\tcin>>c[i];\n\t}\n\n\tREP(i,1,n){\n\t\tcin>>fa[i];\n\t\tmina=min(mina,fa[i]);\n\t}\n\n\tREP(i,1,n){\n\t\tcin>>fb[i];\n\t\tminb=min(minb,fb[i]);\n\t}\n\n\tmemset(dpa , 0 ,sizeof dpa);\n\tmemset(dpb , 0, sizeof dpb);\n\treturn ;\n}\n\nvoid Solve(){\n\tint ansa,ansb;\n\tREP(i,mina,f)\n\t{\n\t\tREP(j,1,n){\n\t\t\tif(i>=fa[j]){\n\t\t\t\tdpa[i]=max(dpa[i],dpa[i-fa[j]]+c[j]);\n\t\t\t}\n\t\t}\n\n\t\tif(dpa[i]>=p1){\n\t\t\tansa=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tREP(i,minb,f){\n\t\tREP(j,1,n){\n\t\t\tif(i>=fb[j]){\n\t\t\t\tdpb[i]=max(dpb[i],dpb[i-fb[j]]+c[j]);\n\t\t\t}\n\t\t}\n\t\tif(dpb[i]>=p2){\n\t\t\tansb=i;\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif(ansa+ansb<=f){\n\t\tprint(1);\n\t}else{\n\t\tprint(0);\n\t}\n\n\treturn ;\n}\n\nint main(){\n#ifdef LOCAL\n\tfreopen(\"uoj10680.in\",\"r\",stdin);\n#endif\n\tint t;\n\tscanf(\"%d\",&t);\n\twhile(t--)\n\tInit(),Solve();\n\treturn 0;\n}<|endoftext|>"} {"text":"\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_VALUE_TYPES_HPP\n#define MAPNIK_VALUE_TYPES_HPP\n\n\/\/ mapnik\n#include \n\n\/\/ icu\n#include \/\/ for U_NAMESPACE_QUALIFIER\n\n\/\/ stl\n#include \n#include \n#include \n\nnamespace U_ICU_NAMESPACE {\n class UnicodeString;\n}\n\nnamespace mapnik {\n\n#ifdef BIGINT\n\/\/using value_integer = boost::long_long_type;\nusing value_integer = long long;\n#else\nusing value_integer = int;\n#endif\n\nusing value_double = double;\nusing value_unicode_string = U_NAMESPACE_QUALIFIER UnicodeString;\nusing value_bool = bool;\n\nstruct MAPNIK_DECL value_null\n{\n bool operator==(value_null const&) const\n {\n return true;\n }\n\n template \n bool operator==(T const&) const\n {\n return false;\n }\n\n bool operator!=(value_null const&) const\n {\n return false;\n }\n\n template \n bool operator!=(T const&) const\n {\n return true;\n }\n\n template \n value_null operator+ (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator- (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator* (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator\/ (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator% (T const&) const\n {\n return *this;\n }\n};\n\ninline std::size_t hash_value(value_null const&)\n{\n return 0;\n}\n\ntemplate \ninline std::basic_ostream& operator<<(std::basic_ostream& out, value_null const& v)\n{\n return out;\n}\n\ninline std::istream& operator>> ( std::istream & s, value_null & )\n{\n return s;\n}\n\n\nnamespace detail {\n\/\/ to mapnik::value_type conversions traits\ntemplate \nstruct is_value_bool\n{\n bool value = std::is_same::value;\n};\n\ntemplate \nstruct is_value_integer\n{\n bool value = std::is_integral::value && !std::is_same::value;\n};\n\ntemplate \nstruct is_value_double\n{\n bool value = std::is_floating_point::value;\n};\n\ntemplate \nstruct is_value_unicode_string\n{\n bool value = std::is_same::value;\n};\n\ntemplate \nstruct is_value_string\n{\n bool value = std::is_same::value;\n};\n\ntemplate \nstruct is_value_null\n{\n bool value = std::is_same::value;\n};\n\ntemplate \nstruct mapnik_value_type\n{\n using type = T;\n};\n\n\/\/ value_null\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_null;\n};\n\n\/\/ value_bool\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_bool;\n};\n\n\/\/ value_integer\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_integer;\n};\n\n\/\/ value_double\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_double;\n};\n\n\/\/ value_unicode_string\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_unicode_string;\n};\n\n} \/\/ namespace detail\n\n} \/\/ namespace mapnik\n\n#endif \/\/ MAPNIK_VALUE_TYPES_HPP\nfix compile with gcc\/*****************************************************************************\n *\n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2012 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\n#ifndef MAPNIK_VALUE_TYPES_HPP\n#define MAPNIK_VALUE_TYPES_HPP\n\n\/\/ mapnik\n#include \n\n\/\/ icu\n#include \/\/ for U_NAMESPACE_QUALIFIER\n\n\/\/ stl\n#include \n#include \n#include \n\nnamespace U_ICU_NAMESPACE {\n class UnicodeString;\n}\n\nnamespace mapnik {\n\n#ifdef BIGINT\n\/\/using value_integer = boost::long_long_type;\nusing value_integer = long long;\n#else\nusing value_integer = int;\n#endif\n\nusing value_double = double;\nusing value_unicode_string = U_NAMESPACE_QUALIFIER UnicodeString;\nusing value_bool = bool;\n\nstruct MAPNIK_DECL value_null\n{\n bool operator==(value_null const&) const\n {\n return true;\n }\n\n template \n bool operator==(T const&) const\n {\n return false;\n }\n\n bool operator!=(value_null const&) const\n {\n return false;\n }\n\n template \n bool operator!=(T const&) const\n {\n return true;\n }\n\n template \n value_null operator+ (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator- (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator* (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator\/ (T const&) const\n {\n return *this;\n }\n\n template \n value_null operator% (T const&) const\n {\n return *this;\n }\n};\n\ninline std::size_t hash_value(value_null const&)\n{\n return 0;\n}\n\ntemplate \ninline std::basic_ostream& operator<<(std::basic_ostream& out, value_null const& v)\n{\n return out;\n}\n\ninline std::istream& operator>> ( std::istream & s, value_null & )\n{\n return s;\n}\n\n\nnamespace detail {\n\/\/ to mapnik::value_type conversions traits\ntemplate \nstruct is_value_bool\n{\n constexpr static bool value = std::is_same::value;\n};\n\ntemplate \nstruct is_value_integer\n{\n constexpr static bool value = std::is_integral::value && !std::is_same::value;\n};\n\ntemplate \nstruct is_value_double\n{\n constexpr static bool value = std::is_floating_point::value;\n};\n\ntemplate \nstruct is_value_unicode_string\n{\n constexpr static bool value = std::is_same::value;\n};\n\ntemplate \nstruct is_value_string\n{\n constexpr static bool value = std::is_same::value;\n};\n\ntemplate \nstruct is_value_null\n{\n constexpr static bool value = std::is_same::value;\n};\n\ntemplate \nstruct mapnik_value_type\n{\n using type = T;\n};\n\n\/\/ value_null\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_null;\n};\n\n\/\/ value_bool\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_bool;\n};\n\n\/\/ value_integer\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_integer;\n};\n\n\/\/ value_double\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_double;\n};\n\n\/\/ value_unicode_string\ntemplate \nstruct mapnik_value_type::value>::type>\n{\n using type = mapnik::value_unicode_string;\n};\n\n} \/\/ namespace detail\n\n} \/\/ namespace mapnik\n\n#endif \/\/ MAPNIK_VALUE_TYPES_HPP\n<|endoftext|>"} {"text":"\/**\n *\t\\file\n *\/\n\n#pragma once\n\n#include \"bases.hpp\"\n#include \"type_name.hpp\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace module_loader {\n\n\/**\n *\tA convenience base class for implementing\n *\t\\ref object or \\ref offer.\n *\n *\t\\tparam T\n *\t\tThe type being represented or offered.\n *\t\\tparam Base\n *\t\t\\ref object or \\ref offer.\n *\/\ntemplate \nclass base : public Base {\ntemplate \nfriend class base;\npublic:\n\tusing provides_type = typename Base::provides_type;\nprivate:\n\tstd::string name_;\n\tprovides_type provides_;\n\tstatic constexpr bool is_nothrow = std::is_same::value &&\n\t\tstd::is_nothrow_default_constructible::value &&\n\t\tstd::is_nothrow_move_constructible::value;\n\tstatic provides_type get_provides (std::true_type) noexcept(is_nothrow) {\n\t\treturn provides_type{};\n\t}\n\tstatic provides_type get_provides (std::false_type) {\n\t\treturn public_unambiguous_bases();\n\t}\n\tstatic provides_type get_provides () noexcept(is_nothrow) {\n\t\treturn get_provides(typename std::is_same::type{});\n\t}\npublic:\n\tbase ()\n\t\t:\tname_(type_name()),\n\t\t\tprovides_(get_provides())\n\t{\t}\n\ttemplate \n\texplicit base (base & other) noexcept(\n\t\tstd::is_nothrow_default_constructible::value &&\n\t\tstd::is_nothrow_default_constructible::value &&\n\t\tstd::is_nothrow_default_constructible::value\n\t) {\n\t\tusing std::swap;\n\t\tswap(name_,other.name_);\n\t\tswap(provides_,other.provides_);\n\t}\n\texplicit base (std::string name) noexcept(is_nothrow && std::is_nothrow_move_constructible::value)\n\t\t:\tname_(std::move(name)),\n\t\t\tprovides_(get_provides())\n\t{\t}\n\tvirtual const std::string & name () const noexcept override {\n\t\treturn name_;\n\t}\n\tvirtual const provides_type & provides () const noexcept override {\n\t\treturn provides_;\n\t}\n};\n\n}\nmodule_loader::base - Copy\/**\n *\t\\file\n *\/\n\n#pragma once\n\n#include \"bases.hpp\"\n#include \"type_name.hpp\"\n#include \n#include \n#include \n#include \n#include \n\nnamespace module_loader {\n\n\/**\n *\tA convenience base class for implementing\n *\t\\ref object or \\ref offer.\n *\n *\t\\tparam T\n *\t\tThe type being represented or offered.\n *\t\\tparam Base\n *\t\t\\ref object or \\ref offer.\n *\/\ntemplate \nclass base : public Base {\npublic:\n\tusing provides_type = typename Base::provides_type;\nprivate:\n\tstd::string name_;\n\tprovides_type provides_;\n\tstatic constexpr bool is_nothrow = std::is_same::value &&\n\t\tstd::is_nothrow_default_constructible::value &&\n\t\tstd::is_nothrow_move_constructible::value;\n\tstatic provides_type get_provides (std::true_type) noexcept(is_nothrow) {\n\t\treturn provides_type{};\n\t}\n\tstatic provides_type get_provides (std::false_type) {\n\t\treturn public_unambiguous_bases();\n\t}\n\tstatic provides_type get_provides () noexcept(is_nothrow) {\n\t\treturn get_provides(typename std::is_same::type{});\n\t}\npublic:\n\tbase ()\n\t\t:\tname_(type_name()),\n\t\t\tprovides_(get_provides())\n\t{\t}\n\ttemplate \n\texplicit base (base & other)\n\t\t:\tname_(other.name()),\n\t\t\tprovides_(get_provides())\n\t{\t}\n\texplicit base (std::string name) noexcept(is_nothrow && std::is_nothrow_move_constructible::value)\n\t\t:\tname_(std::move(name)),\n\t\t\tprovides_(get_provides())\n\t{\t}\n\tvirtual const std::string & name () const noexcept override {\n\t\treturn name_;\n\t}\n\tvirtual const provides_type & provides () const noexcept override {\n\t\treturn provides_;\n\t}\n};\n\n}\n<|endoftext|>"} {"text":"#ifndef _NEVIL_ARENA_SWITCH_HPP_\n#define _NEVIL_ARENA_SWITCH_HPP_\n\n#include \"nevil\/arena\/object.hpp\"\n\nnamespace nevil\n{\n class switch_object : public object\n {\n public:\n switch_object();\n switch_object(int x, int y, double size_x, double size_y, double height,\n const Enki::Color &off_color=Enki::Color(0.4, 0.0, 1.0),\n const Enki::Color &on_color=Enki::Color(0.7, 1.0, 1.0));\n virtual ~switch_object();\n void turn_on();\n void turn_off();\n };\n}\n\n#endif \/\/ _NEVIL_ARENA_SWITCH_HPP_changed red value of the on switch#ifndef _NEVIL_ARENA_SWITCH_HPP_\n#define _NEVIL_ARENA_SWITCH_HPP_\n\n#include \"nevil\/arena\/object.hpp\"\n\nnamespace nevil\n{\n class switch_object : public object\n {\n public:\n switch_object();\n switch_object(int x, int y, double size_x, double size_y, double height,\n const Enki::Color &off_color=Enki::Color(0.4, 0.0, 1.0),\n const Enki::Color &on_color=Enki::Color(0.9, 1.0, 1.0));\n virtual ~switch_object();\n void turn_on();\n void turn_off();\n };\n}\n\n#endif \/\/ _NEVIL_ARENA_SWITCH_HPP_<|endoftext|>"} {"text":"#ifndef __SGE_ASSET_MANAGER_HPP\n#define __SGE_ASSET_MANAGER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace sge\n{\n class AssetManager\n {\n private:\n std::vector> locators;\n std::unordered_map> loaders;\n\n AssetCache cache;\n\n public:\n void register_locator(std::shared_ptr locator);\n void register_loader(std::shared_ptr loader, const std::vector &extensions);\n\n void unload(BaseAsset *asset);\n\n template \n std::shared_ptr load(const D &assetdesc)\n {\n static_assert(std::is_base_of::value, \"Supplied asset type does not inherit from Asset\");\n static_assert(std::is_base_of::value, \"Supplied descriptor type does not inherit from AssetDescriptor\");\n\n auto passetdesc = std::make_shared(assetdesc);\n std::shared_ptr asset = nullptr;\n\n if (cache.find(passetdesc) == cache.end())\n {\n SDL_RWops *input = nullptr;\n\n for (auto &locator : locators)\n {\n try\n {\n input = locator->locate(passetdesc->name());\n }\n catch (const AssetLocatorError &e)\n {\n std::cerr << \"[AssetLocatorError] \" << e.what() << std::endl;\n input = nullptr;\n }\n\n if (input != nullptr)\n {\n break;\n }\n }\n\n if (input != nullptr)\n {\n if (loaders.find(passetdesc->extension()) != loaders.end())\n {\n auto loader = loaders[passetdesc->extension()];\n\n asset = std::shared_ptr(\n new A(loader, passetdesc),\n [&](A *ptr_asset)\n {\n BaseAsset *ptr_basset = static_cast(ptr_asset);\n unload(ptr_basset);\n }\n );\n\n try\n {\n loader->load(asset, input);\n }\n catch (const AssetLoaderError &e)\n {\n std::cerr << \"[AssetLoaderError] \" << e.what() << std::endl;\n asset.reset();\n }\n\n if (asset != nullptr)\n {\n cache[passetdesc] = std::static_pointer_cast(asset);\n }\n }\n else\n {\n std::cerr << \"[AssetLoaderError] No loader found for extension: \" << passetdesc->extension() << std::endl;\n }\n }\n else\n {\n std::cerr << \"[AssetLocatorError] Request asset not found by any locator: \" << passetdesc->name() << std::endl;\n }\n }\n else\n {\n asset = std::static_pointer_cast(cache[passetdesc].lock());\n }\n\n return asset;\n }\n };\n}\n\n#endif \/* __SGE_ASSET_MANAGER_HPP *\/\nmake AssetManager::unload() private#ifndef __SGE_ASSET_MANAGER_HPP\n#define __SGE_ASSET_MANAGER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace sge\n{\n class AssetManager\n {\n private:\n std::vector> locators;\n std::unordered_map> loaders;\n\n AssetCache cache;\n\n public:\n void register_locator(std::shared_ptr locator);\n void register_loader(std::shared_ptr loader, const std::vector &extensions);\n\n template \n std::shared_ptr load(const D &assetdesc)\n {\n static_assert(std::is_base_of::value, \"Supplied asset type does not inherit from Asset\");\n static_assert(std::is_base_of::value, \"Supplied descriptor type does not inherit from AssetDescriptor\");\n\n auto passetdesc = std::make_shared(assetdesc);\n std::shared_ptr asset = nullptr;\n\n if (cache.find(passetdesc) == cache.end())\n {\n SDL_RWops *input = nullptr;\n\n for (auto &locator : locators)\n {\n try\n {\n input = locator->locate(passetdesc->name());\n }\n catch (const AssetLocatorError &e)\n {\n std::cerr << \"[AssetLocatorError] \" << e.what() << std::endl;\n input = nullptr;\n }\n\n if (input != nullptr)\n {\n break;\n }\n }\n\n if (input != nullptr)\n {\n if (loaders.find(passetdesc->extension()) != loaders.end())\n {\n auto loader = loaders[passetdesc->extension()];\n\n asset = std::shared_ptr(\n new A(loader, passetdesc),\n [&](A *ptr_asset)\n {\n BaseAsset *ptr_basset = static_cast(ptr_asset);\n unload(ptr_basset);\n }\n );\n\n try\n {\n loader->load(asset, input);\n }\n catch (const AssetLoaderError &e)\n {\n std::cerr << \"[AssetLoaderError] \" << e.what() << std::endl;\n asset.reset();\n }\n\n if (asset != nullptr)\n {\n cache[passetdesc] = std::static_pointer_cast(asset);\n }\n }\n else\n {\n std::cerr << \"[AssetLoaderError] No loader found for extension: \" << passetdesc->extension() << std::endl;\n }\n }\n else\n {\n std::cerr << \"[AssetLocatorError] Request asset not found by any locator: \" << passetdesc->name() << std::endl;\n }\n }\n else\n {\n asset = std::static_pointer_cast(cache[passetdesc].lock());\n }\n\n return asset;\n }\n\n private:\n void unload(BaseAsset *asset);\n };\n}\n\n#endif \/* __SGE_ASSET_MANAGER_HPP *\/\n<|endoftext|>"} {"text":"\/\/============================================================================\n\/\/ include\/vsmc\/utility\/rdtsc.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ vSMC: Scalable Monte Carlo\n\/\/\n\/\/ This file is distributed under the 2-clauses BSD License.\n\/\/ See LICENSE for details.\n\/\/============================================================================\n\n#ifndef VSMC_UTILITY_RDTSC_HPP\n#define VSMC_UTILITY_RDTSC_HPP\n\n#include \n\n#ifdef _MSC_VER\n#include \n#endif\n\nnamespace vsmc {\n\n\/\/\/ \\brief Return the TSC value using RDTSC instruction after synchronization\n\/\/\/ with CPUID instruction\n\/\/\/ \\ingroup RDTSC\ninline uint64_t rdtsc ()\n{\n#ifdef _MSC_VER\n int aux[4];\n __cpuidex(aux, 0, 0);\n\n return static_cast(__rdtsc());\n#else \/\/ _MSC_VER\n unsigned eax = 0;\n unsigned ecx = 0;\n unsigned edx = 0;\n __asm__ volatile\n (\n \"cpuid\\n\\t\"\n \"rdtsc\\n\"\n : \"=a\" (eax), \"=d\" (edx)\n : \"a\" (eax), \"c\" (ecx)\n );\n\n return (static_cast(edx) << 32) + static_cast(eax);\n#endif \/\/ _MSC_VER\n}\n\n\/\/\/ \\brief Return the TSC and TSC_AUX values using RDTSCP instruction\n\/\/\/ \\ingroup RDTSC\ninline uint64_t rdtscp (unsigned *aux)\n{\n#ifdef _MSC_VER\n return static_cast(__rdtscp(aux));\n#else \/\/ _MSC_VER\n unsigned eax = 0;\n unsigned edx = 0;\n unsigned ecx = 0;\n __asm__ volatile\n (\n \"rdtscp\\n\"\n : \"=a\" (eax), \"=c\" (ecx), \"=d\" (edx)\n );\n *aux = ecx;\n\n return static_cast(eax) + (static_cast(edx) << 32);\n#endif \/\/ _MSC_VER\n}\n\n\/\/\/ \\brief CPU clock cycle counter using RDTSC\n\/\/\/ \\ingroup RDTSC\nclass RDTSCCounter\n{\n public :\n\n RDTSCCounter () : elapsed_(0), start_(0), running_(false) {}\n\n \/\/\/ \\brief If the counter is running\n \/\/\/\n \/\/\/ \\details\n \/\/\/ If `start()` has been called and no `stop()` call since, then it is\n \/\/\/ running, otherwise it is stoped.\n bool running () const {return running_;}\n\n \/\/\/ \\brief Start the counter, no effect if already started\n \/\/\/\n \/\/\/ \\return `true` if it is started by this call, and the elapsed cycle\n \/\/\/ count will be incremented next time `stop()` is called. The increment\n \/\/\/ will be relative to the time point of this call. `false` if it is\n \/\/\/ already started earlier.\n bool start ()\n {\n if (running_)\n return false;\n\n running_ = true;\n start_ = rdtsc();\n\n return true;\n }\n\n \/\/\/ \\brief Stop the counter, no effect if already stopped\n \/\/\/\n \/\/\/ \\return `true` if it is stoped by this call, and the elapsed cycle\n \/\/\/ count has been incremented. `false` in one of the following situations.\n \/\/\/ In all these situations, the elapsed cycle count will not be\n \/\/\/ incremented.\n \/\/\/ - It already stopped or wasn't started before.\n \/\/\/ - The cycle count appears to decrease. This is most likely in the case\n \/\/\/ that the TSC MSR has been reset.\n bool stop ()\n {\n if (!running_)\n return false;\n\n uint64_t stop = rdtsc();\n if (stop < start_)\n return false;\n\n elapsed_ += stop - start_;\n running_ = false;\n\n return true;\n }\n\n \/\/\/ \\brief Stop and reset the elapsed cycle count to zero\n void reset ()\n {\n elapsed_ = 0;\n running_ = false;\n }\n\n \/\/\/ \\brief Return the accumulated elapsed cycle count\n uint64_t cycles () const {return elapsed_;}\n\n private :\n\n uint64_t elapsed_;\n uint64_t start_;\n bool running_;\n}; \/\/ class RDTSCCounter\n\n\/\/\/ \\brief CPU clock cycle counter using RDTSCP\n\/\/\/ \\ingroup RDTSC\n\/\/\/\n\/\/\/ \\details\n\/\/\/ This class shall only be used if RDTSCP is supported. For example,\n\/\/\/ ~~~{.cpp}\n\/\/\/ RDTSCCouner c1;\n\/\/\/ RDTSCPCouner c2;\n\/\/\/ CPUID::has_feature() ? c2.start() : c1.start();\n\/\/\/ ~~~\nclass RDTSCPCounter\n{\n public :\n\n RDTSCPCounter () : elapsed_(0), start_(0), start_id_(0), running_(false) {}\n\n \/\/\/ \\brief If the counter is running\n \/\/\/\n \/\/\/ \\details\n \/\/\/ If `start()` has been called and no `stop()` call since, then it is\n \/\/\/ running, otherwise it is stoped.\n bool running () const {return running_;}\n\n \/\/\/ \\brief Start the counter, no effect if already started\n \/\/\/\n \/\/\/ \\return `true` if it is started by this call, and the elapsed cycle\n \/\/\/ count will be incremented next time `stop()` is called. The increment\n \/\/\/ will be relative to the time point of this call. `false` if it is\n \/\/\/ already started earlier.\n bool start ()\n {\n if (running_)\n return false;\n\n running_ = true;\n start_ = rdtscp(&start_id_);\n\n return true;\n }\n\n \/\/\/ \\brief Stop the counter, no effect if already stopped\n \/\/\/\n \/\/\/ \\return `true` if it is stoped by this call, and the elapsed cycle\n \/\/\/ count has been incremented. `false` in one of the following situations.\n \/\/\/ In all these situations, the elapsed cycle count will not be\n \/\/\/ incremented.\n \/\/\/ - It already stopped or wasn't started before.\n \/\/\/ - The logical processor has changed since the last successful `start()`\n \/\/\/ call. The user is repsonsible for assure threads affinity.\n \/\/\/ - The cycle count appears to decrease. This is most likely in the case\n \/\/\/ that the TSC MSR has been reset.\n bool stop ()\n {\n if (!running_)\n return false;\n\n unsigned stop_id = 0;\n uint64_t stop = rdtscp(&stop_id);\n if (stop_id != start_id_ || stop < start_)\n return false;\n\n elapsed_ += stop - start_;\n running_ = false;\n\n return true;\n }\n\n \/\/\/ \\brief Stop and reset the elapsed cycle count to zero\n void reset ()\n {\n elapsed_ = 0;\n running_ = false;\n }\n\n \/\/\/ \\brief Return the accumulated elapsed cycle count\n uint64_t cycles () const {return elapsed_;}\n\n private :\n\n uint64_t elapsed_;\n uint64_t start_;\n unsigned start_id_;\n bool running_;\n}; \/\/ class RDTSCPCounter\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_UTILITY_RDTSC_HPP\nFix RDTSC counter and remove sync by CPUID\/\/============================================================================\n\/\/ include\/vsmc\/utility\/rdtsc.hpp\n\/\/----------------------------------------------------------------------------\n\/\/\n\/\/ vSMC: Scalable Monte Carlo\n\/\/\n\/\/ This file is distributed under the 2-clauses BSD License.\n\/\/ See LICENSE for details.\n\/\/============================================================================\n\n#ifndef VSMC_UTILITY_RDTSC_HPP\n#define VSMC_UTILITY_RDTSC_HPP\n\n#include \n\n#ifdef _MSC_VER\n#include \n#endif\n\nnamespace vsmc {\n\n\/\/\/ \\brief Return the TSC value using RDTSC instruction\n\/\/\/ \\ingroup RDTSC\ninline uint64_t rdtsc ()\n{\n#ifdef _MSC_VER\n return static_cast(__rdtsc());\n#else \/\/ _MSC_VER\n unsigned eax = 0;\n unsigned edx = 0;\n __asm__ volatile\n (\n \"rdtsc\\n\"\n : \"=a\" (eax), \"=d\" (edx)\n );\n\n return (static_cast(edx) << 32) + static_cast(eax);\n#endif \/\/ _MSC_VER\n}\n\n\/\/\/ \\brief Return the TSC and TSC_AUX values using RDTSCP instruction\n\/\/\/ \\ingroup RDTSC\ninline uint64_t rdtscp (unsigned *aux)\n{\n#ifdef _MSC_VER\n return static_cast(__rdtscp(aux));\n#else \/\/ _MSC_VER\n unsigned eax = 0;\n unsigned ecx = 0;\n unsigned edx = 0;\n __asm__ volatile\n (\n \"rdtscp\\n\"\n : \"=a\" (eax), \"=c\" (ecx), \"=d\" (edx)\n );\n *aux = ecx;\n\n return static_cast(eax) + (static_cast(edx) << 32);\n#endif \/\/ _MSC_VER\n}\n\n\/\/\/ \\brief CPU clock cycle counter using RDTSC\n\/\/\/ \\ingroup RDTSC\nclass RDTSCCounter\n{\n public :\n\n RDTSCCounter () : elapsed_(0), start_(0), running_(false) {}\n\n \/\/\/ \\brief If the counter is running\n \/\/\/\n \/\/\/ \\details\n \/\/\/ If `start()` has been called and no `stop()` call since, then it is\n \/\/\/ running, otherwise it is stoped.\n bool running () const {return running_;}\n\n \/\/\/ \\brief Start the counter, no effect if already started\n \/\/\/\n \/\/\/ \\return `true` if it is started by this call, and the elapsed cycle\n \/\/\/ count will be incremented next time `stop()` is called. The increment\n \/\/\/ will be relative to the time point of this call. `false` if it is\n \/\/\/ already started earlier.\n bool start ()\n {\n if (running_)\n return false;\n\n running_ = true;\n start_ = rdtsc();\n\n return true;\n }\n\n \/\/\/ \\brief Stop the counter, no effect if already stopped\n \/\/\/\n \/\/\/ \\return `true` if it is stoped by this call, and the elapsed cycle\n \/\/\/ count has been incremented. `false` in one of the following situations.\n \/\/\/ In all these situations, the elapsed cycle count will not be\n \/\/\/ incremented.\n \/\/\/ - It already stopped or wasn't started before.\n \/\/\/ - The cycle count appears to decrease. This is most likely in the case\n \/\/\/ that the TSC MSR has been reset.\n bool stop ()\n {\n if (!running_)\n return false;\n\n uint64_t stop = rdtsc();\n if (stop < start_)\n return false;\n\n elapsed_ += stop - start_;\n running_ = false;\n\n return true;\n }\n\n \/\/\/ \\brief Stop and reset the elapsed cycle count to zero\n void reset ()\n {\n elapsed_ = 0;\n running_ = false;\n }\n\n \/\/\/ \\brief Return the accumulated elapsed cycle count\n uint64_t cycles () const {return elapsed_;}\n\n private :\n\n uint64_t elapsed_;\n uint64_t start_;\n bool running_;\n}; \/\/ class RDTSCCounter\n\n\/\/\/ \\brief CPU clock cycle counter using RDTSCP\n\/\/\/ \\ingroup RDTSC\n\/\/\/\n\/\/\/ \\details\n\/\/\/ This class shall only be used if RDTSCP is supported. For example,\n\/\/\/ ~~~{.cpp}\n\/\/\/ RDTSCCouner c1;\n\/\/\/ RDTSCPCouner c2;\n\/\/\/ CPUID::has_feature() ? c2.start() : c1.start();\n\/\/\/ ~~~\nclass RDTSCPCounter\n{\n public :\n\n RDTSCPCounter () : elapsed_(0), start_(0), start_id_(0), running_(false) {}\n\n \/\/\/ \\brief If the counter is running\n \/\/\/\n \/\/\/ \\details\n \/\/\/ If `start()` has been called and no `stop()` call since, then it is\n \/\/\/ running, otherwise it is stoped.\n bool running () const {return running_;}\n\n \/\/\/ \\brief Start the counter, no effect if already started\n \/\/\/\n \/\/\/ \\return `true` if it is started by this call, and the elapsed cycle\n \/\/\/ count will be incremented next time `stop()` is called. The increment\n \/\/\/ will be relative to the time point of this call. `false` if it is\n \/\/\/ already started earlier.\n bool start ()\n {\n if (running_)\n return false;\n\n running_ = true;\n start_ = rdtscp(&start_id_);\n\n return true;\n }\n\n \/\/\/ \\brief Stop the counter, no effect if already stopped\n \/\/\/\n \/\/\/ \\return `true` if it is stoped by this call, and the elapsed cycle\n \/\/\/ count has been incremented. `false` in one of the following situations.\n \/\/\/ In all these situations, the elapsed cycle count will not be\n \/\/\/ incremented.\n \/\/\/ - It already stopped or wasn't started before.\n \/\/\/ - The logical processor has changed since the last successful `start()`\n \/\/\/ call. The user is repsonsible for assure threads affinity.\n \/\/\/ - The cycle count appears to decrease. This is most likely in the case\n \/\/\/ that the TSC MSR has been reset.\n bool stop ()\n {\n if (!running_)\n return false;\n\n unsigned stop_id = 0;\n uint64_t stop = rdtscp(&stop_id);\n if (stop_id != start_id_ || stop < start_)\n return false;\n\n elapsed_ += stop - start_;\n running_ = false;\n\n return true;\n }\n\n \/\/\/ \\brief Stop and reset the elapsed cycle count to zero\n void reset ()\n {\n elapsed_ = 0;\n running_ = false;\n }\n\n \/\/\/ \\brief Return the accumulated elapsed cycle count\n uint64_t cycles () const {return elapsed_;}\n\n private :\n\n uint64_t elapsed_;\n uint64_t start_;\n unsigned start_id_;\n bool running_;\n}; \/\/ class RDTSCPCounter\n\n} \/\/ namespace vsmc\n\n#endif \/\/ VSMC_UTILITY_RDTSC_HPP\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\nnamespace gcl::mp\n{\n template \n struct type_index {};\n\n template \n struct tuple {\n\n constexpr static auto size = sizeof...(types);\n constexpr static auto empty = size == 0;\n\n constexpr tuple() requires(not empty)\n : storage{generate_storage(types{}...)}\n {}\n constexpr tuple(types&&... values)\n : storage{generate_storage(std::forward(values)...)}\n {}\n constexpr tuple(tuple&&) = default;\n \n private:\n \/\/ storage : by-pass missing features : auto non-static members, lambdas in unevaluated context\n \/*static constexpr auto generate_storage(types&&... values)\n {\n return [&values...](std::index_sequence)\n {\n static_assert(sizeof...(indexes) == sizeof...(types));\n static_assert(sizeof...(indexes) == sizeof...(values));\n\n const auto generate_storage_entry = [](T && init_value) constexpr\n {\n return [value = init_value](type_index) mutable -> auto& { return value; };\n };\n return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()(\n std::forward(values))...};\n }\n (std::make_index_sequence{});\n };*\/\n static constexpr auto generate_storage(types&&... values)\n {\n const auto generate_storage_entry = [](T && init_value) constexpr\n {\n return [value = init_value](type_index) mutable -> auto& { return value; };\n };\n\n #if defined(_MSC_VER) and not defined(__clang__)\n return [&](std::index_sequence)\n #else\n return [&generate_storage_entry, &values... ](std::index_sequence)\n #endif\n {\n static_assert(sizeof...(indexes) == sizeof...(types));\n static_assert(sizeof...(indexes) == sizeof...(values));\n\n return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()(\n std::forward(values))...};\n }\n (std::make_index_sequence{});\n };\n decltype(generate_storage(types{}...)) storage;\n\n template \n struct type_at_impl { \/\/ defer symbol (Clang)\n using type = std::remove_reference_t().template get())>;\n };\n\n public:\n template \n using type_at = typename type_at_impl::type;\n\n template \n requires(not empty and index <= (size - 1)) constexpr auto& get()\n {\n return storage(type_index{});\n }\n template \n requires(not empty and index <= (size - 1)) constexpr const auto& get() const\n {\n return const_cast(this)->get(); \/\/ violate constness invariants\n }\n\n template \n requires(sizeof...(arg_types) == size) constexpr bool operator==(const tuple& other) const\n {\n return [ this, &other ](std::index_sequence)\n {\n return (((get() == other.template get()) && ...));\n }\n (std::make_index_sequence{});\n }\n };\n}\n\nnamespace gcl::mp::tests\n{\n using namespace gcl::mp;\n\n using empty_tuple = tuple<>;\n using one_element_tuple = tuple;\n using two_element_tuple = tuple;\n \n static constexpr auto empty_tuple_default_init = empty_tuple{};\n \n \/\/static constexpr auto one_element_tuple_default_init = one_element_tuple{};\n\n\n \/*static constexpr auto one_element_tuple_values_init = one_element_tuple{42};\n static constexpr auto two_element_tuple_default_init = two_element_tuple{};\n static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};\n\n static_assert(std::is_same_v, decltype(tuple{42, 'a'})>);\n\n static_assert(std::is_same_v, int>);\n static_assert(std::is_same_v, char>);\n static_assert(std::is_same_v().get<0>()), int&>);\n static_assert(std::is_same_v().get<1>()), const char&>);*\/\n}[mp\/meta\/tuple] : fix Clang, msvc-cl ICEs#pragma once\n\n#include \n\nnamespace gcl::mp\n{\n template \n struct type_index {};\n\n template \n struct tuple {\n\n constexpr static auto size = sizeof...(types);\n constexpr static auto empty = size == 0;\n\n constexpr tuple() requires(not empty)\n : storage{generate_storage(types{}...)}\n {}\n constexpr tuple(types&&... values)\n : storage{generate_storage(std::forward(values)...)}\n {}\n constexpr tuple(tuple&&) = default;\n\n private:\n \/\/ storage : by-pass missing features : auto non-static members, lambdas in unevaluated context\n using index_sequence = std::make_index_sequence;\n static constexpr auto generate_storage(types&&... values)\n { \/\/ defer parameter pack expansion (msvc-cl, Clang)\n return generate_storage_impl(index_sequence{}, std::forward(values)...);\n }\n template \n static constexpr auto generate_storage_impl(std::index_sequence, types&&... values)\n {\n static_assert(sizeof...(indexes) == sizeof...(types));\n static_assert(sizeof...(indexes) == sizeof...(values));\n\n const auto generate_storage_entry = [](T && init_value) constexpr\n {\n return [value = init_value](type_index) mutable -> auto& { return value; };\n };\n return gcl::mp::meta::functional::overload{\n generate_storage_entry.template operator()(std::forward(values))...};\n };\n using storage_type = decltype(generate_storage(types{}...));\n storage_type storage;\n\n template \n struct type_at_impl { \/\/ defer symbol (Clang)\n using type = std::remove_reference_t().template get())>;\n };\n\n public:\n template \n using type_at = typename type_at_impl::type;\n\n template \n requires(not empty and index <= (size - 1)) constexpr auto& get()\n {\n return storage(type_index{});\n }\n template \n requires(not empty and index <= (size - 1)) constexpr const auto& get() const\n {\n return const_cast(this)->get(); \/\/ violate constness invariants\n }\n\n template \n requires(sizeof...(arg_types) == size) constexpr bool operator==(const tuple& other) const\n {\n return [ this, &other ](std::index_sequence)\n {\n return (((get() == other.template get()) && ...));\n }\n (std::make_index_sequence{});\n }\n };\n}\n\n\/\/ When Clang, Msvc-cl gets better, replace `tuple::generate_storage` implementation by :\n\/*static constexpr auto generate_storage(types&&... values)\n{\n return [&values...](std::index_sequence)\n {\n static_assert(sizeof...(indexes) == sizeof...(types));\n static_assert(sizeof...(indexes) == sizeof...(values));\n\n const auto generate_storage_entry = [](T && init_value) constexpr\n {\n return [value = init_value](type_index) mutable -> auto& { return value; };\n };\n return gcl::mp::meta::functional::overload{generate_storage_entry.template operator()(\n std::forward(values))...};\n }\n (std::make_index_sequence{});\n};*\/\n\nnamespace gcl::mp::tests\n{\n using namespace gcl::mp;\n\n using empty_tuple = tuple<>;\n using one_element_tuple = tuple;\n using two_element_tuple = tuple;\n \n static constexpr auto empty_tuple_default_init = empty_tuple{};\n \n static constexpr auto one_element_tuple_default_init = one_element_tuple{};\n\n\n static constexpr auto one_element_tuple_values_init = one_element_tuple{42};\n static constexpr auto two_element_tuple_default_init = two_element_tuple{};\n static constexpr auto two_element_tuple_values_init = two_element_tuple{42, 'a'};\n\n static_assert(std::is_same_v, decltype(tuple{42, 'a'})>);\n\n static_assert(std::is_same_v, int>);\n static_assert(std::is_same_v, char>);\n static_assert(std::is_same_v().get<0>()), int&>);\n static_assert(std::is_same_v().get<1>()), const char&>);\n}<|endoftext|>"} {"text":"#pragma once\n\n\n#include \n#include \n#include \n#include \n#include \n#include \"error.hpp\"\n\n\nnamespace uvw {\n\n\nclass Loop;\n\n\ntemplate\nclass Handle {\n friend class Loop;\n\n template\n explicit constexpr Handle(uv_loop_t *loop, Args&&... args)\n : res{std::make_shared(loop, std::forward(args)...)}\n { }\n\npublic:\n constexpr Handle(const Handle &other): res{other.res} { }\n constexpr Handle(Handle &&other): res{std::move(other.res)} { }\n\n constexpr void operator=(const Handle &other) { res = other.res; }\n constexpr void operator=(Handle &&other) { res = std::move(other.res); }\n\n constexpr operator R&() noexcept { return *res; }\n operator const R&() const noexcept { return *res; }\n\nprivate:\n std::shared_ptr res;\n};\n\n\nclass Loop final {\npublic:\n Loop(bool def = true)\n : loop{def ? uv_default_loop() : new uv_loop_t, [def](uv_loop_t *l){ if(!def) delete l; }}\n {\n if(!def) {\n auto err = uv_loop_init(loop.get());\n\n if(err) {\n throw UVWException{err};\n }\n } else if(!loop) {\n throw std::bad_alloc{};\n }\n }\n\n Loop(const Loop &) = delete;\n Loop(Loop &&other) = delete;\n Loop& operator=(const Loop &) = delete;\n Loop& operator=(Loop &&other) = delete;\n\n ~Loop() {\n if(loop) {\n close();\n }\n }\n\n template\n Handle handle(Args&&... args) {\n return Handle{loop.get(), std::forward(args)...};\n }\n\n bool close() noexcept {\n return (uv_loop_close(loop.get()) == 0);\n }\n\n bool run() noexcept {\n return (uv_run(loop.get(), UV_RUN_DEFAULT) == 0);\n }\n\n bool runOnce() noexcept {\n return (uv_run(loop.get(), UV_RUN_ONCE) == 0);\n }\n\n bool runWait() noexcept {\n return (uv_run(loop.get(), UV_RUN_NOWAIT) == 0);\n }\n\n bool alive() const noexcept {\n return !(uv_loop_alive(loop.get()) == 0);\n }\n\n void stop() noexcept {\n uv_stop(loop.get());\n }\n\nprivate:\n using Deleter = std::function;\n std::unique_ptr loop;\n};\n\n\n}\nclean up#pragma once\n\n\n#include \n#include \n#include \n#include \n#include \"error.hpp\"\n\n\nnamespace uvw {\n\n\nclass Loop;\n\n\ntemplate\nclass Handle {\n friend class Loop;\n\n template\n explicit constexpr Handle(uv_loop_t *loop, Args&&... args)\n : res{std::make_shared(loop, std::forward(args)...)}\n { }\n\npublic:\n constexpr Handle(const Handle &other): res{other.res} { }\n constexpr Handle(Handle &&other): res{std::move(other.res)} { }\n\n constexpr void operator=(const Handle &other) { res = other.res; }\n constexpr void operator=(Handle &&other) { res = std::move(other.res); }\n\n constexpr operator R&() noexcept { return *res; }\n operator const R&() const noexcept { return *res; }\n\nprivate:\n std::shared_ptr res;\n};\n\n\nclass Loop final {\npublic:\n Loop(bool def = true)\n : loop{def ? uv_default_loop() : new uv_loop_t, [def](uv_loop_t *l){ if(!def) delete l; }}\n {\n if(!def) {\n auto err = uv_loop_init(loop.get());\n\n if(err) {\n throw UVWException{err};\n }\n } else if(!loop) {\n throw std::bad_alloc{};\n }\n }\n\n Loop(const Loop &) = delete;\n Loop(Loop &&other) = delete;\n Loop& operator=(const Loop &) = delete;\n Loop& operator=(Loop &&other) = delete;\n\n ~Loop() {\n if(loop) {\n close();\n }\n }\n\n template\n Handle handle(Args&&... args) {\n return Handle{loop.get(), std::forward(args)...};\n }\n\n bool close() noexcept {\n return (uv_loop_close(loop.get()) == 0);\n }\n\n bool run() noexcept {\n return (uv_run(loop.get(), UV_RUN_DEFAULT) == 0);\n }\n\n bool runOnce() noexcept {\n return (uv_run(loop.get(), UV_RUN_ONCE) == 0);\n }\n\n bool runWait() noexcept {\n return (uv_run(loop.get(), UV_RUN_NOWAIT) == 0);\n }\n\n bool alive() const noexcept {\n return !(uv_loop_alive(loop.get()) == 0);\n }\n\n void stop() noexcept {\n uv_stop(loop.get());\n }\n\nprivate:\n using Deleter = std::function;\n std::unique_ptr loop;\n};\n\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"util.hpp\"\n\nusing namespace bc;\n\nbool validsig(transaction_type& tx, size_t input_index,\n elliptic_curve_key& key, const script_type& script_code,\n data_chunk signature)\n{\n uint32_t hash_type = 0;\n hash_type = signature.back();\n signature.pop_back();\n\n hash_digest tx_hash =\n script_type::generate_signature_hash(\n tx, input_index, script_code, hash_type);\n return key.verify(tx_hash, signature);\n}\n\nint main(int argc, char** argv)\n{\n if (argc != 5)\n {\n std::cerr << \"Usage: sign-input FILENAME N SCRIPT_CODE SIGNATURE\" << std::endl;\n return -1;\n }\n const std::string filename = argv[1];\n transaction_type tx;\n if (!load_tx(tx, filename))\n return -1;\n const std::string index_str = argv[2];\n size_t input_index;\n try\n {\n input_index = boost::lexical_cast(index_str);\n }\n catch (const boost::bad_lexical_cast&)\n {\n std::cerr << \"sign-input: Bad N provided.\" << std::endl;\n return -1;\n }\n const script_type script_code = parse_script(decode_hex(argv[3]));\n if (input_index >= tx.inputs.size())\n {\n std::cerr << \"sign-input: N out of range.\" << std::endl;\n return -1;\n }\n const data_chunk signature = decode_hex(argv[4]);\n elliptic_curve_key key;\n if (!read_public_or_private_key(key))\n return -1;\n if (!validsig(tx, input_index, key, script_code, signature))\n {\n std::cout << \"Status: Failed\" << std::endl;\n return 0;\n }\n std::cout << \"Status: OK\" << std::endl;\n return 0;\n}\n\nFix validsig usage and error messages.#include \n#include \n#include \n#include \"util.hpp\"\n\nusing namespace bc;\n\nbool validsig(transaction_type& tx, size_t input_index,\n elliptic_curve_key& key, const script_type& script_code,\n data_chunk signature)\n{\n uint32_t hash_type = 0;\n hash_type = signature.back();\n signature.pop_back();\n\n hash_digest tx_hash =\n script_type::generate_signature_hash(\n tx, input_index, script_code, hash_type);\n return key.verify(tx_hash, signature);\n}\n\nint main(int argc, char** argv)\n{\n if (argc != 5)\n {\n std::cerr << \"Usage: validsig FILENAME N SCRIPT_CODE SIGNATURE\" << std::endl;\n return -1;\n }\n const std::string filename = argv[1];\n transaction_type tx;\n if (!load_tx(tx, filename))\n return -1;\n const std::string index_str = argv[2];\n size_t input_index;\n try\n {\n input_index = boost::lexical_cast(index_str);\n }\n catch (const boost::bad_lexical_cast&)\n {\n std::cerr << \"validsig: Bad N provided.\" << std::endl;\n return -1;\n }\n const script_type script_code = parse_script(decode_hex(argv[3]));\n if (input_index >= tx.inputs.size())\n {\n std::cerr << \"validsig: N out of range.\" << std::endl;\n return -1;\n }\n const data_chunk signature = decode_hex(argv[4]);\n elliptic_curve_key key;\n if (!read_public_or_private_key(key))\n return -1;\n if (!validsig(tx, input_index, key, script_code, signature))\n {\n std::cout << \"Status: Failed\" << std::endl;\n return 0;\n }\n std::cout << \"Status: OK\" << std::endl;\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n\nCCriticalSection cs_warnings;\nstd::string strMiscWarning;\nbool fLargeWorkForkFound = false;\nbool fLargeWorkInvalidChainFound = false;\n\nvoid SetMiscWarning(const std::string& strWarning)\n{\n LOCK(cs_warnings);\n strMiscWarning = strWarning;\n}\n\nvoid SetfLargeWorkForkFound(bool flag)\n{\n LOCK(cs_warnings);\n fLargeWorkForkFound = flag;\n}\n\nbool GetfLargeWorkForkFound()\n{\n LOCK(cs_warnings);\n return fLargeWorkForkFound;\n}\n\nvoid SetfLargeWorkInvalidChainFound(bool flag)\n{\n LOCK(cs_warnings);\n fLargeWorkInvalidChainFound = flag;\n}\n\nstd::string GetWarnings(const std::string& strFor)\n{\n std::string strStatusBar;\n std::string strGUI;\n const std::string uiAlertSeperator = \"


\";\n\n LOCK(cs_warnings);\n\n if (!CLIENT_VERSION_IS_RELEASE) {\n strStatusBar = \"This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications\";\n strGUI = _(\"This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications\");\n }\n\n \/\/ Misc warnings like out of disk space and clock is wrong\n if (strMiscWarning != \"\")\n {\n strStatusBar = strMiscWarning;\n strGUI += (strGUI.empty() ? \"\" : uiAlertSeperator) + strMiscWarning;\n }\n\n if (fLargeWorkForkFound)\n {\n strStatusBar = \"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.\";\n strGUI += (strGUI.empty() ? \"\" : uiAlertSeperator) + _(\"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.\");\n }\n else if (fLargeWorkInvalidChainFound)\n {\n strStatusBar = \"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.\";\n strGUI += (strGUI.empty() ? \"\" : uiAlertSeperator) + _(\"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.\");\n }\n\n if (strFor == \"gui\")\n return strGUI;\n else if (strFor == \"statusbar\")\n return strStatusBar;\n assert(!\"GetWarnings(): invalid parameter\");\n return \"error\";\n}\nAdd Clang thread safety annotations for variables guarded by cs_warnings\/\/ Copyright (c) 2009-2010 Satoshi Nakamoto\n\/\/ Copyright (c) 2009-2017 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \n#include \n#include \n#include \n\nCCriticalSection cs_warnings;\nstd::string strMiscWarning GUARDED_BY(cs_warnings);\nbool fLargeWorkForkFound GUARDED_BY(cs_warnings) = false;\nbool fLargeWorkInvalidChainFound GUARDED_BY(cs_warnings) = false;\n\nvoid SetMiscWarning(const std::string& strWarning)\n{\n LOCK(cs_warnings);\n strMiscWarning = strWarning;\n}\n\nvoid SetfLargeWorkForkFound(bool flag)\n{\n LOCK(cs_warnings);\n fLargeWorkForkFound = flag;\n}\n\nbool GetfLargeWorkForkFound()\n{\n LOCK(cs_warnings);\n return fLargeWorkForkFound;\n}\n\nvoid SetfLargeWorkInvalidChainFound(bool flag)\n{\n LOCK(cs_warnings);\n fLargeWorkInvalidChainFound = flag;\n}\n\nstd::string GetWarnings(const std::string& strFor)\n{\n std::string strStatusBar;\n std::string strGUI;\n const std::string uiAlertSeperator = \"
\";\n\n LOCK(cs_warnings);\n\n if (!CLIENT_VERSION_IS_RELEASE) {\n strStatusBar = \"This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications\";\n strGUI = _(\"This is a pre-release test build - use at your own risk - do not use for privatesend, mining or merchant applications\");\n }\n\n \/\/ Misc warnings like out of disk space and clock is wrong\n if (strMiscWarning != \"\")\n {\n strStatusBar = strMiscWarning;\n strGUI += (strGUI.empty() ? \"\" : uiAlertSeperator) + strMiscWarning;\n }\n\n if (fLargeWorkForkFound)\n {\n strStatusBar = \"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.\";\n strGUI += (strGUI.empty() ? \"\" : uiAlertSeperator) + _(\"Warning: The network does not appear to fully agree! Some miners appear to be experiencing issues.\");\n }\n else if (fLargeWorkInvalidChainFound)\n {\n strStatusBar = \"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.\";\n strGUI += (strGUI.empty() ? \"\" : uiAlertSeperator) + _(\"Warning: We do not appear to fully agree with our peers! You may need to upgrade, or other nodes may need to upgrade.\");\n }\n\n if (strFor == \"gui\")\n return strGUI;\n else if (strFor == \"statusbar\")\n return strStatusBar;\n assert(!\"GetWarnings(): invalid parameter\");\n return \"error\";\n}\n<|endoftext|>"} {"text":"\/*************************************************\n* ANSI X9.31 RNG Source File *\n* (C) 1999-2007 Jack Lloyd *\n*************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*************************************************\n* Generate a buffer of random bytes *\n*************************************************\/\nvoid ANSI_X931_RNG::randomize(byte out[], u32bit length) throw(PRNG_Unseeded)\n {\n if(!is_seeded())\n throw PRNG_Unseeded(name());\n\n while(length)\n {\n const u32bit copied = std::min(length, R.size() - position);\n\n copy_mem(out, R + position, copied);\n out += copied;\n length -= copied;\n position += copied;\n\n if(position == R.size())\n update_buffer();\n }\n }\n\n\/*************************************************\n* Refill the internal state *\n*************************************************\/\nvoid ANSI_X931_RNG::update_buffer()\n {\n const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE;\n\n SecureVector DT(BLOCK_SIZE);\n\n prng->randomize(DT, DT.size());\n cipher->encrypt(DT);\n\n xor_buf(R, V, DT, BLOCK_SIZE);\n cipher->encrypt(R);\n\n xor_buf(V, R, DT, BLOCK_SIZE);\n cipher->encrypt(V);\n\n position = 0;\n }\n\n\/*************************************************\n* Add entropy to internal state *\n*************************************************\/\nvoid ANSI_X931_RNG::add_randomness(const byte data[], u32bit length)\n {\n prng->add_entropy(data, length);\n\n if(is_seeded())\n {\n SecureVector key(cipher->MAXIMUM_KEYLENGTH);\n prng->randomize(key, key.size());\n cipher->set_key(key, key.size());\n\n prng->randomize(V, V.size());\n\n update_buffer();\n }\n }\n\n\/*************************************************\n* Check if the the PRNG is seeded *\n*************************************************\/\nbool ANSI_X931_RNG::is_seeded() const\n {\n return prng->is_seeded();\n }\n\n\/*************************************************\n* Clear memory of sensitive data *\n*************************************************\/\nvoid ANSI_X931_RNG::clear() throw()\n {\n cipher->clear();\n prng->clear();\n R.clear();\n V.clear();\n\n position = 0;\n }\n\n\/*************************************************\n* Return the name of this type *\n*************************************************\/\nstd::string ANSI_X931_RNG::name() const\n {\n return \"X9.31(\" + cipher->name() + \")\";\n }\n\n\/*************************************************\n* ANSI X931 RNG Constructor *\n*************************************************\/\nANSI_X931_RNG::ANSI_X931_RNG(const std::string& cipher_name,\n RandomNumberGenerator* prng_ptr)\n {\n if(!prng_ptr)\n throw Invalid_Argument(\"ANSI_X931_RNG constructor: NULL prng\");\n\n prng = prng_ptr;\n cipher = get_block_cipher(cipher_name);\n\n const u32bit BLOCK_SIZE = cipher->BLOCK_SIZE;\n\n V.create(BLOCK_SIZE);\n R.create(BLOCK_SIZE);\n\n position = 0;\n }\n\n\/*************************************************\n* ANSI X931 RNG Destructor *\n*************************************************\/\nANSI_X931_RNG::~ANSI_X931_RNG()\n {\n delete cipher;\n delete prng;\n }\n\n}\nChange how the ANSI X9.31 generator tells that it is seeded. Previously, it was seeded if and only if the underlying PRNG was seeded. However if the PRNG always returned as being seeded, we would never generate a V value, etc (leaving them at the default zero). This would not occur with any of Botan's built in PRNGs since their implementations require that add_randomness be called at least once before is_seeded will return true. However this is not an invariant of the general RandomNumberGenerator interface.\/*************************************************\n* ANSI X9.31 RNG Source File *\n* (C) 1999-2007 Jack Lloyd *\n*************************************************\/\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Botan {\n\n\/*************************************************\n* Generate a buffer of random bytes *\n*************************************************\/\nvoid ANSI_X931_RNG::randomize(byte out[], u32bit length) throw(PRNG_Unseeded)\n {\n if(!is_seeded())\n throw PRNG_Unseeded(name());\n\n while(length)\n {\n if(position == R.size())\n update_buffer();\n\n const u32bit copied = std::min(length, R.size() - position);\n\n copy_mem(out, R + position, copied);\n out += copied;\n length -= copied;\n position += copied;\n }\n }\n\n\/*************************************************\n* Refill the internal state *\n*************************************************\/\nvoid ANSI_X931_RNG::update_buffer()\n {\n SecureVector DT(cipher->BLOCK_SIZE);\n\n prng->randomize(DT, DT.size());\n cipher->encrypt(DT);\n\n xor_buf(R, V, DT, cipher->BLOCK_SIZE);\n cipher->encrypt(R);\n\n xor_buf(V, R, DT, cipher->BLOCK_SIZE);\n cipher->encrypt(V);\n\n position = 0;\n }\n\n\/*************************************************\n* Add entropy to internal state *\n*************************************************\/\nvoid ANSI_X931_RNG::add_randomness(const byte data[], u32bit length)\n {\n prng->add_entropy(data, length);\n\n if(prng->is_seeded())\n {\n SecureVector key(cipher->MAXIMUM_KEYLENGTH);\n prng->randomize(key, key.size());\n cipher->set_key(key, key.size());\n\n if(V.size() != cipher->BLOCK_SIZE)\n V.create(cipher->BLOCK_SIZE);\n prng->randomize(V, V.size());\n\n update_buffer();\n }\n }\n\n\/*************************************************\n* Check if the the PRNG is seeded *\n*************************************************\/\nbool ANSI_X931_RNG::is_seeded() const\n {\n return V.has_items();\n }\n\n\/*************************************************\n* Clear memory of sensitive data *\n*************************************************\/\nvoid ANSI_X931_RNG::clear() throw()\n {\n cipher->clear();\n prng->clear();\n R.clear();\n V.clear();\n\n position = 0;\n }\n\n\/*************************************************\n* Return the name of this type *\n*************************************************\/\nstd::string ANSI_X931_RNG::name() const\n {\n return \"X9.31(\" + cipher->name() + \")\";\n }\n\n\/*************************************************\n* ANSI X931 RNG Constructor *\n*************************************************\/\nANSI_X931_RNG::ANSI_X931_RNG(const std::string& cipher_name,\n RandomNumberGenerator* prng_ptr)\n {\n if(!prng_ptr)\n throw Invalid_Argument(\"ANSI_X931_RNG constructor: NULL prng\");\n\n prng = prng_ptr;\n cipher = get_block_cipher(cipher_name);\n\n R.create(cipher->BLOCK_SIZE);\n position = 0;\n }\n\n\/*************************************************\n* ANSI X931 RNG Destructor *\n*************************************************\/\nANSI_X931_RNG::~ANSI_X931_RNG()\n {\n delete cipher;\n delete prng;\n }\n\n}\n<|endoftext|>"} {"text":"#ifndef IMAGE_MANAGER_HPP_INCLUDED\n#define IMAGE_MANAGER_HPP_INCLUDED\n\n#include \n\nstruct ImageType\n{\n int shmid;\n unsigned char *shmaddr;\n double time;\n};\n\n\n\n\nstruct ConvertedImage;\n\n\nclass ImageManager\n{\npublic:\n static boost::shared_ptr create(int width, int height);\n virtual boost::shared_ptr getImage() = 0;\n\n virtual boost::shared_ptr getConvertedImage() =0;\n\nprotected:\n ~ImageManager()\n {}\n};\n\n\n#endif\nSpacing#ifndef IMAGE_MANAGER_HPP_INCLUDED\n#define IMAGE_MANAGER_HPP_INCLUDED\n\n#include \n\nstruct ImageType\n{\n int shmid;\n unsigned char *shmaddr;\n double time;\n};\n\n\n\n\nstruct ConvertedImage;\n\n\nclass ImageManager\n{\npublic:\n static boost::shared_ptr create(int width, int height);\n \n virtual boost::shared_ptr getImage() = 0;\n virtual boost::shared_ptr getConvertedImage() =0;\n\nprotected:\n ~ImageManager()\n {}\n};\n\n\n#endif\n<|endoftext|>"} {"text":"\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated nodeation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/xml\/node.hpp\"\n#include \"flusspferd\/xml\/document.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/exception.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n\nusing namespace flusspferd;\nusing namespace flusspferd::xml;\n\nobject node::create(xmlNodePtr ptr) {\n if (ptr->_private)\n return value::from_permanent_ptr(ptr->_private).to_object();\n\n switch (ptr->type) {\n case XML_DOCUMENT_NODE:\n return create_native_object(object(), xmlDocPtr(ptr));\n default:\n return create_native_object(object(), ptr);\n }\n}\n\nxmlNodePtr node::c_from_js(object const &obj) {\n if (!obj.is_valid())\n return 0;\n try {\n xml::node *p = dynamic_cast(native_object_base::get_native(obj));\n if (!p)\n return 0;\n return p->c_obj();\n } catch (std::exception&) {\n return 0;\n }\n}\n\nnode::node(xmlNodePtr ptr)\n : ptr(ptr)\n{\n ptr->_private = permanent_ptr();\n}\n\nnode::node(call_context &x) {\n local_root_scope scope;\n\n string name(x.arg[0]);\n\n ptr = xmlNewNode(0, (xmlChar const *) name.c_str());\n\n if (!ptr)\n throw exception(\"Could not create XML node\");\n\n ptr->_private = permanent_ptr();\n}\n\nnode::~node() {\n if (ptr && !ptr->parent && ptr->_private == permanent_ptr()) {\n xmlFreeNode(ptr);\n }\n}\n\nvoid node::post_initialize() {\n ptr->_private = permanent_ptr();\n\n register_native_method(\"copy\", &node::copy);\n\n define_native_property(\"name\", permanent_property, &node::prop_name);\n define_native_property(\"lang\", permanent_property, &node::prop_lang);\n define_native_property(\"parent\", permanent_property, &node::prop_parent);\n define_native_property(\"next\", permanent_property, &node::prop_next);\n define_native_property(\n \"document\", permanent_property | read_only_property, &node::prop_document);\n define_native_property(\n \"type\", permanent_property | read_only_property, &node::prop_type);\n}\n\nobject node::class_info::create_prototype() {\n object proto = create_object();\n\n create_native_method(proto, \"copy\", 1);\n\n return proto;\n}\n\nchar const *node::class_info::constructor_name() {\n return \"Node\";\n}\n\nstd::size_t node::class_info::constructor_arity() {\n return 1;\n}\n\nstatic void trace_children(tracer &trc, xmlNodePtr ptr) {\n while (ptr) {\n trc(\"node-children\", value::from_permanent_ptr(ptr->_private));\n trace_children(trc, ptr->children);\n ptr = ptr->next;\n }\n}\n\nstatic void trace_parents(tracer &trc, xmlNodePtr ptr) {\n while (ptr) {\n trc(\"node-parent\", value::from_permanent_ptr(ptr->_private));\n ptr = ptr->parent;\n }\n}\n\nvoid node::trace(tracer &trc) {\n trc(\"node-self\", value::from_permanent_ptr(ptr->_private));\n\n trace_children(trc, ptr->children);\n trace_parents(trc, ptr->parent);\n\n if (ptr->doc)\n trc(\"node-doc\", value::from_permanent_ptr(ptr->doc->_private));\n\n if (ptr->next)\n trc(\"node-next\", value::from_permanent_ptr(ptr->next->_private));\n\n if (ptr->prev)\n trc(\"node-prev\", value::from_permanent_ptr(ptr->prev->_private));\n}\n\nvoid node::prop_name(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n if (!ptr->name)\n data = value();\n else\n data = string((char const *) ptr->name);\n break;\n case property_set:\n xmlNodeSetName(ptr, (xmlChar const *) data.to_string().c_str());\n break;\n default: break;\n };\n}\n\nvoid node::prop_lang(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n {\n xmlChar const *lang = xmlNodeGetLang(ptr);\n if (!lang)\n data = value();\n else\n data = string((char const *) lang);\n }\n break;\n case property_set:\n xmlNodeSetLang(ptr, (xmlChar const *) data.to_string().c_str());\n break;\n default: break;\n };\n}\n\nvoid node::prop_parent(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n if (!ptr->parent)\n data = object();\n else\n data = create(ptr->parent);\n break;\n case property_set:\n if (data.is_void() || data.is_null()) {\n xmlUnlinkNode(ptr);\n data = object();\n } else if (!data.is_object()) {\n data = value();\n } else {\n xmlNodePtr parent = c_from_js(data.get_object());\n if (!parent) {\n data = value();\n break;\n }\n if (ptr->parent)\n xmlUnlinkNode(ptr);\n xmlAddChild(parent, ptr);\n }\n break;\n default: break;\n }\n}\n\nvoid node::prop_next(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n if (!ptr->parent)\n data = object();\n else\n data = create(ptr->next);\n break;\n case property_set:\n if (data.is_void() || data.is_null()) {\n ptr->next = 0;\n data = object();\n } else if (!data.is_object()) {\n data = value();\n } else {\n xmlNodePtr next = c_from_js(data.get_object());\n if (!next) {\n data = value();\n break;\n }\n ptr->next = next;\n while (next) {\n next->parent = ptr->parent;\n if (!next->next)\n next->parent->last = next;\n next = next->next;\n }\n xmlSetListDoc(ptr->next, ptr->doc);\n }\n break;\n default: break;\n }\n}\n\nvoid node::prop_document(property_mode mode, value &data) {\n if (mode != property_get)\n return;\n\n if (!ptr->doc)\n data = object();\n else\n data = create(xmlNodePtr(ptr->doc));\n}\n\nvoid node::prop_type(property_mode mode, value &data) {\n if (mode != property_get)\n return;\n\n switch (ptr->type) {\n case XML_ELEMENT_NODE:\n data = string(\"ELEMENT\");\n break;\n case XML_ATTRIBUTE_NODE:\n data = string(\"ATTRIBUTE\");\n break;\n case XML_TEXT_NODE:\n data = string(\"TEXT\");\n break;\n case XML_CDATA_SECTION_NODE:\n data = string(\"CDATA-SECTION\");\n break;\n case XML_ENTITY_REF_NODE:\n data = string(\"ENTITY-REFERENCE\");\n break;\n case XML_ENTITY_NODE:\n data = string(\"ENTITY\");\n break;\n case XML_PI_NODE:\n data = string(\"PI\");\n break;\n case XML_COMMENT_NODE:\n data = string(\"COMMENT\");\n break;\n case XML_DOCUMENT_NODE:\n data = string(\"DOCUMENT\");\n break;\n case XML_DOCUMENT_TYPE_NODE:\n data = string(\"DOCUMENT-TYPE\");\n break;\n case XML_DOCUMENT_FRAG_NODE:\n data = string(\"DOCUMENT-FRAGMENT\");\n break;\n case XML_NOTATION_NODE:\n data = string(\"NOTATION\");\n break;\n case XML_HTML_DOCUMENT_NODE:\n data = string(\"HTML-DOCUMENT\");\n break;\n case XML_DTD_NODE:\n data = string(\"DTD\");\n break;\n case XML_ELEMENT_DECL:\n data = string(\"ELEMENT-DECLARATION\");\n break;\n case XML_ATTRIBUTE_DECL:\n data = string(\"ATTRIBUTE-DECLARATION\");\n break;\n case XML_ENTITY_DECL:\n data = string(\"ENTITY-DECLARATION\");\n break;\n case XML_NAMESPACE_DECL:\n data = string(\"NAMESPACE-DECLARATION\");\n break;\n case XML_XINCLUDE_START:\n data = string(\"XINCLUDE-START\");\n break;\n case XML_XINCLUDE_END:\n data = string(\"XINCLUDE-END\");\n break;\n default:\n data = string(\"OTHER\");\n break;\n }\n}\n\nobject node::copy(bool recursive) {\n xmlNodePtr copy = xmlCopyNode(ptr, recursive);\n\n if (!copy)\n throw exception(\"Could not copy XML node\");\n\n return create(copy);\n}\n\nsimplify\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Aristid Breitkreuz, Ruediger Sonderfeld\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated nodeation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/xml\/node.hpp\"\n#include \"flusspferd\/xml\/document.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/create.hpp\"\n#include \"flusspferd\/tracer.hpp\"\n#include \"flusspferd\/exception.hpp\"\n#include \"flusspferd\/local_root_scope.hpp\"\n\nusing namespace flusspferd;\nusing namespace flusspferd::xml;\n\nobject node::create(xmlNodePtr ptr) {\n if (ptr->_private)\n return from_permanent_ptr(ptr->_private);\n\n switch (ptr->type) {\n case XML_DOCUMENT_NODE:\n return create_native_object(object(), xmlDocPtr(ptr));\n default:\n return create_native_object(object(), ptr);\n }\n}\n\nxmlNodePtr node::c_from_js(object const &obj) {\n if (!obj.is_valid())\n return 0;\n try {\n xml::node *p = dynamic_cast(native_object_base::get_native(obj));\n if (!p)\n return 0;\n return p->c_obj();\n } catch (std::exception&) {\n return 0;\n }\n}\n\nnode::node(xmlNodePtr ptr)\n : ptr(ptr)\n{\n ptr->_private = permanent_ptr();\n}\n\nnode::node(call_context &x) {\n local_root_scope scope;\n\n string name(x.arg[0]);\n\n ptr = xmlNewNode(0, (xmlChar const *) name.c_str());\n\n if (!ptr)\n throw exception(\"Could not create XML node\");\n\n ptr->_private = permanent_ptr();\n}\n\nnode::~node() {\n if (ptr && !ptr->parent && ptr->_private == permanent_ptr()) {\n xmlFreeNode(ptr);\n }\n}\n\nvoid node::post_initialize() {\n ptr->_private = permanent_ptr();\n\n register_native_method(\"copy\", &node::copy);\n\n define_native_property(\"name\", permanent_property, &node::prop_name);\n define_native_property(\"lang\", permanent_property, &node::prop_lang);\n define_native_property(\"parent\", permanent_property, &node::prop_parent);\n define_native_property(\"next\", permanent_property, &node::prop_next);\n define_native_property(\n \"document\", permanent_property | read_only_property, &node::prop_document);\n define_native_property(\n \"type\", permanent_property | read_only_property, &node::prop_type);\n}\n\nobject node::class_info::create_prototype() {\n object proto = create_object();\n\n create_native_method(proto, \"copy\", 1);\n\n return proto;\n}\n\nchar const *node::class_info::constructor_name() {\n return \"Node\";\n}\n\nstd::size_t node::class_info::constructor_arity() {\n return 1;\n}\n\nstatic void trace_children(tracer &trc, xmlNodePtr ptr) {\n while (ptr) {\n trc(\"node-children\", value::from_permanent_ptr(ptr->_private));\n trace_children(trc, ptr->children);\n ptr = ptr->next;\n }\n}\n\nstatic void trace_parents(tracer &trc, xmlNodePtr ptr) {\n while (ptr) {\n trc(\"node-parent\", value::from_permanent_ptr(ptr->_private));\n ptr = ptr->parent;\n }\n}\n\nvoid node::trace(tracer &trc) {\n trc(\"node-self\", value::from_permanent_ptr(ptr->_private));\n\n trace_children(trc, ptr->children);\n trace_parents(trc, ptr->parent);\n\n if (ptr->doc)\n trc(\"node-doc\", value::from_permanent_ptr(ptr->doc->_private));\n\n if (ptr->next)\n trc(\"node-next\", value::from_permanent_ptr(ptr->next->_private));\n\n if (ptr->prev)\n trc(\"node-prev\", value::from_permanent_ptr(ptr->prev->_private));\n}\n\nvoid node::prop_name(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n if (!ptr->name)\n data = value();\n else\n data = string((char const *) ptr->name);\n break;\n case property_set:\n xmlNodeSetName(ptr, (xmlChar const *) data.to_string().c_str());\n break;\n default: break;\n };\n}\n\nvoid node::prop_lang(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n {\n xmlChar const *lang = xmlNodeGetLang(ptr);\n if (!lang)\n data = value();\n else\n data = string((char const *) lang);\n }\n break;\n case property_set:\n xmlNodeSetLang(ptr, (xmlChar const *) data.to_string().c_str());\n break;\n default: break;\n };\n}\n\nvoid node::prop_parent(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n if (!ptr->parent)\n data = object();\n else\n data = create(ptr->parent);\n break;\n case property_set:\n if (data.is_void() || data.is_null()) {\n xmlUnlinkNode(ptr);\n data = object();\n } else if (!data.is_object()) {\n data = value();\n } else {\n xmlNodePtr parent = c_from_js(data.get_object());\n if (!parent) {\n data = value();\n break;\n }\n if (ptr->parent)\n xmlUnlinkNode(ptr);\n xmlAddChild(parent, ptr);\n }\n break;\n default: break;\n }\n}\n\nvoid node::prop_next(property_mode mode, value &data) {\n switch (mode) {\n case property_get:\n if (!ptr->parent)\n data = object();\n else\n data = create(ptr->next);\n break;\n case property_set:\n if (data.is_void() || data.is_null()) {\n ptr->next = 0;\n data = object();\n } else if (!data.is_object()) {\n data = value();\n } else {\n xmlNodePtr next = c_from_js(data.get_object());\n if (!next) {\n data = value();\n break;\n }\n ptr->next = next;\n while (next) {\n next->parent = ptr->parent;\n if (!next->next)\n next->parent->last = next;\n next = next->next;\n }\n xmlSetListDoc(ptr->next, ptr->doc);\n }\n break;\n default: break;\n }\n}\n\nvoid node::prop_document(property_mode mode, value &data) {\n if (mode != property_get)\n return;\n\n if (!ptr->doc)\n data = object();\n else\n data = create(xmlNodePtr(ptr->doc));\n}\n\nvoid node::prop_type(property_mode mode, value &data) {\n if (mode != property_get)\n return;\n\n switch (ptr->type) {\n case XML_ELEMENT_NODE:\n data = string(\"ELEMENT\");\n break;\n case XML_ATTRIBUTE_NODE:\n data = string(\"ATTRIBUTE\");\n break;\n case XML_TEXT_NODE:\n data = string(\"TEXT\");\n break;\n case XML_CDATA_SECTION_NODE:\n data = string(\"CDATA-SECTION\");\n break;\n case XML_ENTITY_REF_NODE:\n data = string(\"ENTITY-REFERENCE\");\n break;\n case XML_ENTITY_NODE:\n data = string(\"ENTITY\");\n break;\n case XML_PI_NODE:\n data = string(\"PI\");\n break;\n case XML_COMMENT_NODE:\n data = string(\"COMMENT\");\n break;\n case XML_DOCUMENT_NODE:\n data = string(\"DOCUMENT\");\n break;\n case XML_DOCUMENT_TYPE_NODE:\n data = string(\"DOCUMENT-TYPE\");\n break;\n case XML_DOCUMENT_FRAG_NODE:\n data = string(\"DOCUMENT-FRAGMENT\");\n break;\n case XML_NOTATION_NODE:\n data = string(\"NOTATION\");\n break;\n case XML_HTML_DOCUMENT_NODE:\n data = string(\"HTML-DOCUMENT\");\n break;\n case XML_DTD_NODE:\n data = string(\"DTD\");\n break;\n case XML_ELEMENT_DECL:\n data = string(\"ELEMENT-DECLARATION\");\n break;\n case XML_ATTRIBUTE_DECL:\n data = string(\"ATTRIBUTE-DECLARATION\");\n break;\n case XML_ENTITY_DECL:\n data = string(\"ENTITY-DECLARATION\");\n break;\n case XML_NAMESPACE_DECL:\n data = string(\"NAMESPACE-DECLARATION\");\n break;\n case XML_XINCLUDE_START:\n data = string(\"XINCLUDE-START\");\n break;\n case XML_XINCLUDE_END:\n data = string(\"XINCLUDE-END\");\n break;\n default:\n data = string(\"OTHER\");\n break;\n }\n}\n\nobject node::copy(bool recursive) {\n xmlNodePtr copy = xmlCopyNode(ptr, recursive);\n\n if (!copy)\n throw exception(\"Could not copy XML node\");\n\n return create(copy);\n}\n\n<|endoftext|>"} {"text":"#include \"arena.h\"\n#include \"image_util.h\"\n#include \"image_writer.h\"\n#include \"logger.h\"\n\n#include \n\nusing namespace wotreplay;\n\nconst int element_size = 48;\n\nimage_writer_t::image_writer_t()\n : filter([](const packet_t &){ return true; }),\n image_width(512), image_height(512)\n{}\n\nvoid image_writer_t::draw_element(const boost::multi_array &element, int x, int y, int mask) {\n const size_t *shape = element.shape();\n const size_t *image_size = base.shape();\n for (int i = 0; i < shape[0]; ++i) {\n for (int j = 0; j < shape[1]; ++j) {\n \/\/ don't touch alpha channel, use from original\n for (int k = 0; k < 3; ++k) {\n if (((i + y) >= image_size[0]) || ((j + x) >= image_size[1])) {\n continue;\n }\n base[i + y][j + x][k] = mix(base[i + y][j + x][k], base[i + y][j + x][k], (255 - element[i][j][3]) \/ 255.f,\n element[i][j][k] & ((mask >> ((4- (k + 1))*8)) & 0xFF), element[i][j][3] \/ 255.f);\n }\n }\n }\n}\n\nboost::multi_array image_writer_t::get_element(const std::string &name) {\n boost::multi_array element, resized_element;\n std::ifstream is(\"elements\/\" + name + \".png\", std::ios::binary);\n read_png(is, element);\n double f = image_width \/ 512.0; \/\/ we need to scale the elements to the right size\n resize(element, element_size*f, element_size*f, resized_element);\n return resized_element;\n}\n\nvoid image_writer_t::draw_element(const boost::multi_array &element, std::tuple position, int mask) {\n auto shape = base.shape();\n auto element_shape = element.shape();\n float x,y;\n auto position3d = std::make_tuple(std::get<0>(position), 0.f, std::get<1>(position));\n std::tie(x,y) = get_2d_coord(position3d, arena.bounding_box, (int) shape[1], (int) shape[0]);\n draw_element(element, x - element_shape[1]\/2, y - element_shape[0]\/2, mask);\n}\n\nvoid image_writer_t::draw_grid(boost::multi_array &image) {\n const int grid_line_width = 2;\n const int grid_cells = 10;\n auto shape = image.shape();\n int grid_width = ((int) shape[1] - (grid_cells + 1) * grid_line_width) \/ grid_cells;\n int grid_height = ((int) shape[0] - (grid_cells + 1) * grid_line_width) \/ grid_cells;\n for (int y = 0; y < shape[0]; y += (grid_height + grid_line_width)) {\n for (int i = 0; i < grid_line_width; ++i) {\n for (int x = 0; x < shape[1]; ++x) {\n for (int c = 0; c < 3; ++ c) {\n image[y + i][x][c] = std::min(image[y][x][c] + 20, 255);\n }\n }\n }\n }\n for (int x = 0; x < shape[1]; x += (grid_width + grid_line_width)) {\n for (int i = 0; i < grid_line_width; ++i) {\n for (int y = 0; y < shape[0]; ++y) {\n for (int c = 0; c < 3; ++ c) {\n image[y][x + i][c] = std::min(image[y][x][c] + 20, 255);\n }\n }\n }\n }\n}\n\nvoid image_writer_t::draw_elements() {\n auto it = arena.configurations.find(game_mode);\n if (it == arena.configurations.end()) {\n wotreplay::logger.writef(log_level_t::warning, \"Could not find configuration for game mode '%1%'\\n\", game_mode);\n return;\n }\n\n const arena_configuration_t &configuration = arena.configurations[game_mode];\n int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;\n \n if (game_mode == \"domination\") {\n auto neutral_base = get_element(\"neutral_base\");\n draw_element(neutral_base, configuration.control_point);\n }\n\n auto friendly_base = get_element(\"friendly_base\");\n auto enemy_base = get_element(\"enemy_base\");\n for(const auto &entry : configuration.team_base_positions) {\n for (const auto &position : entry.second) {\n draw_element((entry.first - 1) == reference_team_id ? friendly_base : enemy_base, position);\n }\n }\n\n std::vector> spawns{\n get_element(\"neutral_spawn1\"),\n get_element(\"neutral_spawn2\"),\n get_element(\"neutral_spawn3\"),\n get_element(\"neutral_spawn4\")\n };\n \n for(const auto &entry : configuration.team_spawn_points) {\n for (int i = 0; i < entry.second.size(); ++i) {\n int mask = (reference_team_id == (entry.first - 1)) ? 0x00FF00FF : 0xFF0000FF;\n draw_element(spawns[i], entry.second[i], mask);\n }\n }\n\n draw_grid(base);\n}\n\nvoid image_writer_t::draw_death(const packet_t &packet, const game_t &game) {\n uint32_t killer, killed;\n std::tie(killed, killer) = packet.tank_destroyed();\n packet_t position_packet;\n bool found = game.find_property(packet.clock(), killed, property_t::position, position_packet);\n if (found) {\n draw_position(position_packet, game, this->deaths);\n }\n}\n\nvoid image_writer_t::draw_position(const packet_t &packet, const game_t &game, boost::multi_array &image) {\n uint32_t player_id = packet.player_id();\n\n int team_id = game.get_team_id(player_id);\n if (team_id < 0) return;\n\n auto shape = image.shape();\n int height = static_cast(shape[1]);\n int width = static_cast(shape[2]);\n\n const bounding_box_t &bounding_box = game.get_arena().bounding_box;\n std::tuple position = get_2d_coord( packet.position(), bounding_box, width, height);\n long x = std::lround(std::get<0>(position));\n long y = std::lround(std::get<1>(position));\n if (x >= 0 && y >= 0 && x < width && y < height) {\n image[team_id][y][x]++;\n if (player_id == game.get_recorder_id()) {\n image[2][y][x]++;\n }\n }\n}\n\nvoid image_writer_t::update(const game_t &game) {\n recorder_team = game.get_team_id(game.get_recorder_id());\n \n std::set dead_players;\n for (const packet_t &packet : game.get_packets()) {\n if (!filter(packet)) continue;\n if (packet.has_property(property_t::position)\n && dead_players.find(packet.player_id()) == dead_players.end()) {\n draw_position(packet, game, this->positions);\n } else if (packet.has_property(property_t::tank_destroyed)) {\n uint32_t target, killer;\n std::tie(target, killer) = packet.tank_destroyed();\n dead_players.insert(target);\n draw_death(packet, game);\n }\n }\n}\n\nvoid image_writer_t::load_base_map(const std::string &path) {\n boost::multi_array map;\n std::ifstream is(path, std::ios::binary);\n read_png(is, map);\n resize(map, image_width, image_height, this->base);\n}\n\nvoid image_writer_t::write(std::ostream &os) {\n write_png(os, result);\n}\n\nvoid image_writer_t::init(const arena_t &arena, const std::string &mode) {\n this->arena = arena;\n this->game_mode = mode;\n\n positions.resize(boost::extents[3][image_height][image_width]);\n deaths.resize(boost::extents[3][image_height][image_width]);\n\n clear();\n\n initialized = true;\n}\n\nvoid image_writer_t::clear() {\n std::fill(result.origin(), result.origin() + result.num_elements(), 0.f);\n std::fill(deaths.origin(), deaths.origin() + deaths.num_elements(), 0.f);\n std::fill(positions.origin(), positions.origin() + positions.num_elements(), 0.f);\n}\n\nvoid image_writer_t::finish() {\n draw_basemap();\n\n const size_t *shape = base.shape();\n result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n result = base;\n\n int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;\n for (int i = 0; i < image_height; ++i) {\n for (int j = 0; j < image_width; ++j) {\n if (positions[0][i][j] > positions[1][i][j]) {\n \/\/ position claimed by first team\n if (reference_team_id == 0) {\n result[i][j][0] = result[i][j][2] = 0x00;\n result[i][j][1] = result[i][j][3] = 0xFF;\n } else {\n result[i][j][1] = result[i][j][2] = 0x00;\n result[i][j][0] = result[i][j][3] = 0xFF;\n }\n \n } else if (positions[0][i][j] < positions[1][i][j]) {\n \/\/ position claimed by second team\n if (reference_team_id == 0) {\n result[i][j][1] = result[i][j][2] = 0x00;\n result[i][j][0] = result[i][j][3] = 0xFF;\n } else {\n result[i][j][0] = result[i][j][2] = 0x00;\n result[i][j][1] = result[i][j][3] = 0xFF;\n }\n } else {\n \/\/ no change\n }\n\n if (this->show_self && positions[2][i][j] > 0.f) {\n \/\/ position claimed by second team\n result[i][j][0] = result[i][j][1] = 0x00;\n result[i][j][2] = result[i][j][3] = 0xFF;\n }\n\n if (deaths[0][i][j] + deaths[1][i][j] > 0.f) {\n\t\t\t\tfor (int k = 0; k < 3; k += 1) {\n\t\t\t\t\tfor (int l = 0; l < 3; l += 1) {\n\t\t\t\t\t\tint x = j + k - 1;\n\t\t\t\t\t\tint y = i + l - 1;\n\n\t\t\t\t\t\t\/\/ draw only if within bounds\n\t\t\t\t\t\tif (x >= 0 && x < image_width && y >= 0 && y < image_height) {\n\t\t\t\t\t\t\tresult[y][x][3] = result[y][x][0] = result[y][x][1] = 0xFF;\n\t\t\t\t\t\t\tresult[y][x][2] = 0x00;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t} \n }\n }\n }\n}\n\nvoid image_writer_t::reset() {\n \/\/ initialize with empty image arrays\n initialized = false;\n}\n\nbool image_writer_t::is_initialized() const {\n return initialized;\n}\n\nvoid image_writer_t::set_show_self(bool show_self) {\n this->show_self = show_self;\n}\n\nbool image_writer_t::get_show_self() const {\n return show_self;\n}\n\nvoid image_writer_t::set_use_fixed_teamcolors(bool use_fixed_teamcolors) {\n this->use_fixed_teamcolors = use_fixed_teamcolors;\n}\n\nbool image_writer_t::get_use_fixed_teamcolors() const {\n return use_fixed_teamcolors;\n}\n\nvoid image_writer_t::set_recorder_team(int recorder_team) {\n this->recorder_team = recorder_team;\n}\n\nint image_writer_t::get_recorder_team() const {\n return recorder_team;\n}\n\nvoid image_writer_t::set_filter(filter_t filter) {\n this->filter = filter;\n}\n\nconst arena_t &image_writer_t::get_arena() const {\n return arena;\n}\n\nconst std::string &image_writer_t::get_game_mode() const {\n return game_mode;\n}\n\nvoid image_writer_t::merge(const image_writer_t &writer) {\n \/\/ TODO: implement this\n std::transform(positions.origin(), positions.origin() + positions.num_elements(),\n writer.positions.origin(), positions.origin(), std::plus());\n}\n\nint image_writer_t::get_image_height() const {\n return image_height;\n}\n\nvoid image_writer_t::set_image_height(int image_height) {\n this->image_height = image_height;\n}\n\n\nint image_writer_t::get_image_width() const {\n return image_width;\n}\n\nvoid image_writer_t::set_image_width(int image_width) {\n this->image_width = image_width;\n}\n\nbool image_writer_t::get_no_basemap() const {\n return no_basemap;\n}\n\nvoid image_writer_t::set_no_basemap(bool no_basemap) {\n this->no_basemap = no_basemap;\n}\n\nvoid image_writer_t::draw_basemap() {\n if (!no_basemap) {\n load_base_map(arena.mini_map);\n const size_t *shape = base.shape();\n result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n draw_elements();\n } else {\n base.resize(boost::extents[image_width][image_height][4]);\n }\n}\n\n\nconst boost::multi_array &image_writer_t::get_result() const { \n\treturn result; \n}image_writer_t::load_base_map() handle failure to open file#include \"arena.h\"\n#include \"image_util.h\"\n#include \"image_writer.h\"\n#include \"logger.h\"\n\n#include \n\nusing namespace wotreplay;\n\nconst int element_size = 48;\n\nimage_writer_t::image_writer_t()\n : filter([](const packet_t &) { return true; }),\n image_width(512), image_height(512)\n{}\n\nvoid image_writer_t::draw_element(const boost::multi_array &element, int x, int y, int mask) {\n const size_t *shape = element.shape();\n const size_t *image_size = base.shape();\n for (int i = 0; i < shape[0]; ++i) {\n for (int j = 0; j < shape[1]; ++j) {\n \/\/ don't touch alpha channel, use from original\n for (int k = 0; k < 3; ++k) {\n if (((i + y) >= image_size[0]) || ((j + x) >= image_size[1])) {\n continue;\n }\n base[i + y][j + x][k] = mix(base[i + y][j + x][k], base[i + y][j + x][k], (255 - element[i][j][3]) \/ 255.f,\n element[i][j][k] & ((mask >> ((4 - (k + 1)) * 8)) & 0xFF), element[i][j][3] \/ 255.f);\n }\n }\n }\n}\n\nboost::multi_array image_writer_t::get_element(const std::string &name) {\n boost::multi_array element, resized_element;\n std::ifstream is(\"elements\/\" + name + \".png\", std::ios::binary);\n read_png(is, element);\n double f = image_width \/ 512.0; \/\/ we need to scale the elements to the right size\n resize(element, element_size*f, element_size*f, resized_element);\n return resized_element;\n}\n\nvoid image_writer_t::draw_element(const boost::multi_array &element, std::tuple position, int mask) {\n auto shape = base.shape();\n auto element_shape = element.shape();\n float x, y;\n auto position3d = std::make_tuple(std::get<0>(position), 0.f, std::get<1>(position));\n std::tie(x, y) = get_2d_coord(position3d, arena.bounding_box, (int) shape[1], (int) shape[0]);\n draw_element(element, x - element_shape[1] \/ 2, y - element_shape[0] \/ 2, mask);\n}\n\nvoid image_writer_t::draw_grid(boost::multi_array &image) {\n const int grid_line_width = 2;\n const int grid_cells = 10;\n auto shape = image.shape();\n int grid_width = ((int) shape[1] - (grid_cells + 1) * grid_line_width) \/ grid_cells;\n int grid_height = ((int) shape[0] - (grid_cells + 1) * grid_line_width) \/ grid_cells;\n for (int y = 0; y < shape[0]; y += (grid_height + grid_line_width)) {\n for (int i = 0; i < grid_line_width; ++i) {\n for (int x = 0; x < shape[1]; ++x) {\n for (int c = 0; c < 3; ++c) {\n image[y + i][x][c] = std::min(image[y][x][c] + 20, 255);\n }\n }\n }\n }\n for (int x = 0; x < shape[1]; x += (grid_width + grid_line_width)) {\n for (int i = 0; i < grid_line_width; ++i) {\n for (int y = 0; y < shape[0]; ++y) {\n for (int c = 0; c < 3; ++c) {\n image[y][x + i][c] = std::min(image[y][x][c] + 20, 255);\n }\n }\n }\n }\n}\n\nvoid image_writer_t::draw_elements() {\n auto it = arena.configurations.find(game_mode);\n if (it == arena.configurations.end()) {\n wotreplay::logger.writef(log_level_t::warning, \"Could not find configuration for game mode '%1%'\\n\", game_mode);\n return;\n }\n\n const arena_configuration_t &configuration = arena.configurations[game_mode];\n int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;\n\n if (game_mode == \"domination\") {\n auto neutral_base = get_element(\"neutral_base\");\n draw_element(neutral_base, configuration.control_point);\n }\n\n auto friendly_base = get_element(\"friendly_base\");\n auto enemy_base = get_element(\"enemy_base\");\n for (const auto &entry : configuration.team_base_positions) {\n for (const auto &position : entry.second) {\n draw_element((entry.first - 1) == reference_team_id ? friendly_base : enemy_base, position);\n }\n }\n\n std::vector> spawns{\n get_element(\"neutral_spawn1\"),\n get_element(\"neutral_spawn2\"),\n get_element(\"neutral_spawn3\"),\n get_element(\"neutral_spawn4\")\n };\n\n for (const auto &entry : configuration.team_spawn_points) {\n for (int i = 0; i < entry.second.size(); ++i) {\n int mask = (reference_team_id == (entry.first - 1)) ? 0x00FF00FF : 0xFF0000FF;\n draw_element(spawns[i], entry.second[i], mask);\n }\n }\n\n draw_grid(base);\n}\n\nvoid image_writer_t::draw_death(const packet_t &packet, const game_t &game) {\n uint32_t killer, killed;\n std::tie(killed, killer) = packet.tank_destroyed();\n packet_t position_packet;\n bool found = game.find_property(packet.clock(), killed, property_t::position, position_packet);\n if (found) {\n draw_position(position_packet, game, this->deaths);\n }\n}\n\nvoid image_writer_t::draw_position(const packet_t &packet, const game_t &game, boost::multi_array &image) {\n uint32_t player_id = packet.player_id();\n\n int team_id = game.get_team_id(player_id);\n if (team_id < 0) return;\n\n auto shape = image.shape();\n int height = static_cast(shape[1]);\n int width = static_cast(shape[2]);\n\n const bounding_box_t &bounding_box = game.get_arena().bounding_box;\n std::tuple position = get_2d_coord(packet.position(), bounding_box, width, height);\n long x = std::lround(std::get<0>(position));\n long y = std::lround(std::get<1>(position));\n if (x >= 0 && y >= 0 && x < width && y < height) {\n image[team_id][y][x]++;\n if (player_id == game.get_recorder_id()) {\n image[2][y][x]++;\n }\n }\n}\n\nvoid image_writer_t::update(const game_t &game) {\n recorder_team = game.get_team_id(game.get_recorder_id());\n\n std::set dead_players;\n for (const packet_t &packet : game.get_packets()) {\n if (!filter(packet)) continue;\n if (packet.has_property(property_t::position)\n && dead_players.find(packet.player_id()) == dead_players.end()) {\n draw_position(packet, game, this->positions);\n }\n else if (packet.has_property(property_t::tank_destroyed)) {\n uint32_t target, killer;\n std::tie(target, killer) = packet.tank_destroyed();\n dead_players.insert(target);\n draw_death(packet, game);\n }\n }\n}\n\nvoid image_writer_t::load_base_map(const std::string &path) {\n boost::multi_array map;\n std::ifstream is(path, std::ios::binary);\n if (is) {\n read_png(is, map);\n resize(map, image_width, image_height, this->base);\n }\n}\n\nvoid image_writer_t::write(std::ostream &os) {\n write_png(os, result);\n}\n\nvoid image_writer_t::init(const arena_t &arena, const std::string &mode) {\n this->arena = arena;\n this->game_mode = mode;\n\n positions.resize(boost::extents[3][image_height][image_width]);\n deaths.resize(boost::extents[3][image_height][image_width]);\n\n clear();\n\n initialized = true;\n}\n\nvoid image_writer_t::clear() {\n std::fill(result.origin(), result.origin() + result.num_elements(), 0.f);\n std::fill(deaths.origin(), deaths.origin() + deaths.num_elements(), 0.f);\n std::fill(positions.origin(), positions.origin() + positions.num_elements(), 0.f);\n}\n\nvoid image_writer_t::finish() {\n draw_basemap();\n\n const size_t *shape = base.shape();\n result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n result = base;\n\n int reference_team_id = use_fixed_teamcolors ? 0 : recorder_team;\n for (int i = 0; i < image_height; ++i) {\n for (int j = 0; j < image_width; ++j) {\n if (positions[0][i][j] > positions[1][i][j]) {\n \/\/ position claimed by first team\n if (reference_team_id == 0) {\n result[i][j][0] = result[i][j][2] = 0x00;\n result[i][j][1] = result[i][j][3] = 0xFF;\n }\n else {\n result[i][j][1] = result[i][j][2] = 0x00;\n result[i][j][0] = result[i][j][3] = 0xFF;\n }\n\n }\n else if (positions[0][i][j] < positions[1][i][j]) {\n \/\/ position claimed by second team\n if (reference_team_id == 0) {\n result[i][j][1] = result[i][j][2] = 0x00;\n result[i][j][0] = result[i][j][3] = 0xFF;\n }\n else {\n result[i][j][0] = result[i][j][2] = 0x00;\n result[i][j][1] = result[i][j][3] = 0xFF;\n }\n }\n else {\n \/\/ no change\n }\n\n if (this->show_self && positions[2][i][j] > 0.f) {\n \/\/ position claimed by second team\n result[i][j][0] = result[i][j][1] = 0x00;\n result[i][j][2] = result[i][j][3] = 0xFF;\n }\n\n if (deaths[0][i][j] + deaths[1][i][j] > 0.f) {\n for (int k = 0; k < 3; k += 1) {\n for (int l = 0; l < 3; l += 1) {\n int x = j + k - 1;\n int y = i + l - 1;\n\n \/\/ draw only if within bounds\n if (x >= 0 && x < image_width && y >= 0 && y < image_height) {\n result[y][x][3] = result[y][x][0] = result[y][x][1] = 0xFF;\n result[y][x][2] = 0x00;\n }\n }\n }\n }\n }\n }\n}\n\nvoid image_writer_t::reset() {\n \/\/ initialize with empty image arrays\n initialized = false;\n}\n\nbool image_writer_t::is_initialized() const {\n return initialized;\n}\n\nvoid image_writer_t::set_show_self(bool show_self) {\n this->show_self = show_self;\n}\n\nbool image_writer_t::get_show_self() const {\n return show_self;\n}\n\nvoid image_writer_t::set_use_fixed_teamcolors(bool use_fixed_teamcolors) {\n this->use_fixed_teamcolors = use_fixed_teamcolors;\n}\n\nbool image_writer_t::get_use_fixed_teamcolors() const {\n return use_fixed_teamcolors;\n}\n\nvoid image_writer_t::set_recorder_team(int recorder_team) {\n this->recorder_team = recorder_team;\n}\n\nint image_writer_t::get_recorder_team() const {\n return recorder_team;\n}\n\nvoid image_writer_t::set_filter(filter_t filter) {\n this->filter = filter;\n}\n\nconst arena_t &image_writer_t::get_arena() const {\n return arena;\n}\n\nconst std::string &image_writer_t::get_game_mode() const {\n return game_mode;\n}\n\nvoid image_writer_t::merge(const image_writer_t &writer) {\n \/\/ TODO: implement this\n std::transform(positions.origin(), positions.origin() + positions.num_elements(),\n writer.positions.origin(), positions.origin(), std::plus());\n}\n\nint image_writer_t::get_image_height() const {\n return image_height;\n}\n\nvoid image_writer_t::set_image_height(int image_height) {\n this->image_height = image_height;\n}\n\n\nint image_writer_t::get_image_width() const {\n return image_width;\n}\n\nvoid image_writer_t::set_image_width(int image_width) {\n this->image_width = image_width;\n}\n\nbool image_writer_t::get_no_basemap() const {\n return no_basemap;\n}\n\nvoid image_writer_t::set_no_basemap(bool no_basemap) {\n this->no_basemap = no_basemap;\n}\n\nvoid image_writer_t::draw_basemap() {\n if (!no_basemap) {\n load_base_map(arena.mini_map);\n const size_t *shape = base.shape();\n result.resize(boost::extents[shape[0]][shape[1]][shape[2]]);\n draw_elements();\n }\n else {\n base.resize(boost::extents[image_width][image_height][4]);\n }\n}\n\n\nconst boost::multi_array &image_writer_t::get_result() const {\n return result;\n}<|endoftext|>"} {"text":"Added a new optional command-line flag to allow filtering of open-access records.<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014 Wenbin He. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"io\/raw_reader.h\"\n\n#include \"core\/basic_types.h\"\n#include \"core\/cartesian_grid.h\"\n#include \"core\/field.h\"\n#include \"core\/float_array.h\"\n#include \"io\/console.h\"\n\nnamespace itl {\n\nstd::unique_ptr RawReader::LoadData(\n std::initializer_list> file_list,\n bool with_header) {\n if (with_header) {\n FILE* file;\n file = fopen(file_list.begin()->first, \"rb\");\n int dimensions[3];\n fread(dimensions, sizeof(int), 3, file);\n set_dimensions(dimensions[0], dimensions[1], dimensions[2]);\n fclose(file);\n }\n\n int data_size = x_dim_ * y_dim_ * z_dim_;\n std::unique_ptr grid(new CartesianGrid(x_dim_, y_dim_, z_dim_,\n x_bias_, y_bias_, z_bias_));\n\n std::unique_ptr field(new Field());\n field->set_grid(grid.release());\n\n for (auto it = file_list.begin(); it != file_list.end(); ++it) {\n FILE* file;\n file = fopen(it->first, \"rb\");\n\n if (with_header) {\n int dimensions[3];\n fread(dimensions, sizeof(int), 3, file);\n }\n\n std::unique_ptr array;\n\n switch (it->second) {\n case kFloat:\n array.reset(new FloatArray(data_size));\n fread(static_cast(array.get())->data(),\n sizeof(float), data_size, file);\n break;\n default:\n Console::Warn(\"RawReader::LoadData() given unsupported data type.\");\n }\n\n fclose(file);\n field->attach_variable(array.release());\n }\n\n return field;\n}\n\n} \/\/ namespace itl\nUpdate RawReader\/\/ Copyright (c) 2014 Wenbin He. All rights reserved.\n\/\/ Use of this source code is governed by a MIT-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"io\/raw_reader.h\"\n\n#include \"core\/basic_types.h\"\n#include \"core\/cartesian_grid.h\"\n#include \"core\/field.h\"\n#include \"core\/float_array.h\"\n#include \"core\/double_array.h\"\n#include \"core\/int32_array.h\"\n#include \"io\/console.h\"\n\nnamespace itl {\n\nstd::unique_ptr RawReader::LoadData(\n std::initializer_list> file_list,\n bool with_header) {\n if (with_header) {\n FILE* file;\n file = fopen(file_list.begin()->first, \"rb\");\n int dimensions[3];\n fread(dimensions, sizeof(int), 3, file);\n set_dimensions(dimensions[0], dimensions[1], dimensions[2]);\n fclose(file);\n }\n\n int data_size = x_dim_ * y_dim_ * z_dim_;\n std::unique_ptr grid(new CartesianGrid(x_dim_, y_dim_, z_dim_,\n x_bias_, y_bias_, z_bias_));\n\n std::unique_ptr field(new Field());\n field->set_grid(grid.release());\n\n for (auto it = file_list.begin(); it != file_list.end(); ++it) {\n FILE* file;\n file = fopen(it->first, \"rb\");\n\n if (with_header) {\n int dimensions[3];\n fread(dimensions, sizeof(int), 3, file);\n }\n\n std::unique_ptr array;\n\n switch (it->second) {\n case kFloat:\n array.reset(new FloatArray(data_size));\n fread(static_cast(array.get())->data(),\n sizeof(float), data_size, file);\n break;\n case kDouble:\n array.reset(new DoubleArray(data_size));\n fread(static_cast(array.get())->data(),\n sizeof(double), data_size, file);\n break;\n case kInt32:\n array.reset(new Int32Array(data_size));\n fread(static_cast(array.get())->data(),\n sizeof(int32_t), data_size, file);\n default:\n Console::Warn(\"RawReader::LoadData() given unsupported data type.\");\n }\n\n fclose(file);\n field->attach_variable(array.release());\n }\n\n return field;\n}\n\n} \/\/ namespace itl\n<|endoftext|>"} {"text":"#include \"itemrenderer.h\"\n\n#include \n\n#include \"configcontainer.h\"\n#include \"htmlrenderer.h\"\n#include \"rssfeed.h\"\n#include \"textformatter.h\"\n\nnamespace newsboat {\n\nstd::string item_renderer::get_feedtitle(std::shared_ptr item) {\n\tconst std::shared_ptr feedptr = item->get_feedptr();\n\n\tstd::string feedtitle;\n\tif (feedptr) {\n\t\tif (!feedptr->title().empty()) {\n\t\t\tfeedtitle = feedptr->title();\n\t\t\tutils::remove_soft_hyphens(feedtitle);\n\t\t} else if (!feedptr->link().empty()) {\n\t\t\tfeedtitle = feedptr->link();\n\t\t} else if (!feedptr->rssurl().empty()) {\n\t\t\tfeedtitle = feedptr->rssurl();\n\t\t}\n\t}\n\n\treturn feedtitle;\n}\n\nvoid prepare_header(\n\tstd::shared_ptr item,\n\tstd::vector>& lines,\n\tstd::vector& \/*links*\/)\n{\n\tconst auto add_line =\n\t\t[&lines]\n\t\t(const std::string& value,\n\t\t const std::string& name,\n\t\t LineType lineType = LineType::wrappable)\n\t\t{\n\t\t\tif (!value.empty()) {\n\t\t\t\tconst auto line = strprintf::fmt(\"%s%s\", name, value);\n\t\t\t\tlines.push_back(std::make_pair(lineType, line));\n\t\t\t}\n\t\t};\n\n\tconst std::string feedtitle = item_renderer::get_feedtitle(item);\n\tadd_line(feedtitle, _(\"Feed: \"));\n\tadd_line(item->title(), _(\"Title: \"));\n\tadd_line(item->author(), _(\"Author: \"));\n\tadd_line(item->pubDate(), _(\"Date: \"));\n\tadd_line(item->link(), _(\"Link: \"), LineType::softwrappable);\n\tadd_line(item->flags(), _(\"Flags: \"));\n\n\tif (!item->enclosure_url().empty()) {\n\t\tauto dlurl = strprintf::fmt(\n\t\t\t\"%s%s\",\n\t\t\t_(\"Podcast Download URL: \"),\n\t\t\tutils::censor_url(item->enclosure_url()));\n\t\tif (!item->enclosure_type().empty()) {\n\t\t\tdlurl.append(\n\t\t\t\t\tstrprintf::fmt(\" (%s%s)\",\n\t\t\t\t\t\t_(\"type: \"),\n\t\t\t\t\t\titem->enclosure_type()));\n\t\t}\n\t\tlines.push_back(std::make_pair(LineType::softwrappable, dlurl));\n\t}\n\n\tlines.push_back(std::make_pair(LineType::wrappable, std::string(\"\")));\n}\n\nstd::string get_item_base_link(const std::shared_ptr& item)\n{\n\tif (!item->get_base().empty()) {\n\t\treturn item->get_base();\n\t} else {\n\t\treturn item->feedurl();\n\t}\n}\n\nvoid render_html(\n\tConfigContainer& cfg,\n\tconst std::string& source,\n\tstd::vector>& lines,\n\tstd::vector& thelinks,\n\tconst std::string& url,\n\tbool raw)\n{\n\tconst std::string renderer = cfg.get_configvalue(\"html-renderer\");\n\tif (renderer == \"internal\") {\n\t\tHtmlRenderer rnd(raw);\n\t\trnd.render(source, lines, thelinks, url);\n\t} else {\n\t\tchar* argv[4];\n\t\targv[0] = const_cast(\"\/bin\/sh\");\n\t\targv[1] = const_cast(\"-c\");\n\t\targv[2] = const_cast(renderer.c_str());\n\t\targv[3] = nullptr;\n\t\tLOG(Level::DEBUG,\n\t\t\t\"item_renderer::render_html: source = %s\",\n\t\t\tsource);\n\t\tLOG(Level::DEBUG,\n\t\t\t\"item_renderer::render_html: html-renderer = %s\",\n\t\t\targv[2]);\n\n\t\tconst std::string output = utils::run_program(argv, source);\n\t\tstd::istringstream is(output);\n\t\tstd::string line;\n\t\twhile (!is.eof()) {\n\t\t\tgetline(is, line);\n\t\t\tif (!raw) {\n\t\t\t\tline = utils::quote_for_stfl(line);\n\t\t\t}\n\t\t\tlines.push_back(std::make_pair(LineType::softwrappable, line));\n\t\t}\n\t}\n}\n\nstd::string item_renderer::to_plain_text(\n\t\tConfigContainer& cfg,\n\t\tstd::shared_ptr item)\n{\n\tstd::vector> lines;\n\tstd::vector links;\n\n\tprepare_header(item, lines, links);\n\tconst auto base = get_item_base_link(item);\n\trender_html(cfg, item->description(), lines, links, base, true);\n\n\tTextFormatter txtfmt;\n\ttxtfmt.add_lines(lines);\n\n\tunsigned int width = cfg.get_configvalue_as_int(\"text-width\");\n\tif (width == 0) {\n\t\twidth = 80;\n\t}\n\n\treturn txtfmt.format_text_plain(width);\n}\n\nstd::pair item_renderer::to_stfl_list(\n\t\tConfigContainer& cfg,\n\t\tstd::shared_ptr item,\n\t\tunsigned int text_width,\n\t\tunsigned int window_width,\n\t\tRegexManager* rxman,\n\t\tconst std::string& location,\n\t\tstd::vector& links)\n{\n\tstd::vector> lines;\n\n\tprepare_header(item, lines, links);\n\tconst std::string baseurl = get_item_base_link(item);\n\tconst auto body = item->description();\n\trender_html(cfg, body, lines, links, baseurl, false);\n\n\tTextFormatter txtfmt;\n\ttxtfmt.add_lines(lines);\n\n\treturn txtfmt.format_text_to_list(rxman, location, text_width, window_width);\n}\n\nvoid render_source(\n\tstd::vector>& lines,\n\tstd::string source)\n{\n\t\/*\n\t * This function is called instead of HtmlRenderer::render() when the\n\t * user requests to have the source displayed instead of seeing the\n\t * rendered HTML.\n\t *\/\n\tstd::string line;\n\tdo {\n\t\tstd::string::size_type pos = source.find_first_of(\"\\r\\n\");\n\t\tline = source.substr(0, pos);\n\t\tif (pos == std::string::npos) {\n\t\t\tsource.erase();\n\t\t} else {\n\t\t\tsource.erase(0, pos + 1);\n\t\t}\n\t\tlines.push_back(std::make_pair(LineType::softwrappable, line));\n\t} while (source.length() > 0);\n}\n\nstd::pair item_renderer::source_to_stfl_list(\n\t\tstd::shared_ptr item,\n\t\tunsigned int text_width,\n\t\tunsigned int window_width,\n\t\tRegexManager* rxman,\n\t\tconst std::string& location)\n{\n\tstd::vector> lines;\n\tstd::vector links;\n\n\tprepare_header(item, lines, links);\n\trender_source(lines, utils::quote_for_stfl(item->description()));\n\n\tTextFormatter txtfmt;\n\ttxtfmt.add_lines(lines);\n\n\treturn txtfmt.format_text_to_list(rxman, location, text_width, window_width);\n}\n\n}\nMinimize nesting in item_renderer::get_feedtitle#include \"itemrenderer.h\"\n\n#include \n\n#include \"configcontainer.h\"\n#include \"htmlrenderer.h\"\n#include \"rssfeed.h\"\n#include \"textformatter.h\"\n\nnamespace newsboat {\n\nstd::string item_renderer::get_feedtitle(std::shared_ptr item) {\n\tconst std::shared_ptr feedptr = item->get_feedptr();\n\n\tif (!feedptr) {\n\t\treturn {};\n\t}\n\n\tstd::string feedtitle;\n\tif (!feedptr->title().empty()) {\n\t\tfeedtitle = feedptr->title();\n\t\tutils::remove_soft_hyphens(feedtitle);\n\t} else if (!feedptr->link().empty()) {\n\t\tfeedtitle = feedptr->link();\n\t} else if (!feedptr->rssurl().empty()) {\n\t\tfeedtitle = feedptr->rssurl();\n\t}\n\n\treturn feedtitle;\n}\n\nvoid prepare_header(\n\tstd::shared_ptr item,\n\tstd::vector>& lines,\n\tstd::vector& \/*links*\/)\n{\n\tconst auto add_line =\n\t\t[&lines]\n\t\t(const std::string& value,\n\t\t const std::string& name,\n\t\t LineType lineType = LineType::wrappable)\n\t\t{\n\t\t\tif (!value.empty()) {\n\t\t\t\tconst auto line = strprintf::fmt(\"%s%s\", name, value);\n\t\t\t\tlines.push_back(std::make_pair(lineType, line));\n\t\t\t}\n\t\t};\n\n\tconst std::string feedtitle = item_renderer::get_feedtitle(item);\n\tadd_line(feedtitle, _(\"Feed: \"));\n\tadd_line(item->title(), _(\"Title: \"));\n\tadd_line(item->author(), _(\"Author: \"));\n\tadd_line(item->pubDate(), _(\"Date: \"));\n\tadd_line(item->link(), _(\"Link: \"), LineType::softwrappable);\n\tadd_line(item->flags(), _(\"Flags: \"));\n\n\tif (!item->enclosure_url().empty()) {\n\t\tauto dlurl = strprintf::fmt(\n\t\t\t\"%s%s\",\n\t\t\t_(\"Podcast Download URL: \"),\n\t\t\tutils::censor_url(item->enclosure_url()));\n\t\tif (!item->enclosure_type().empty()) {\n\t\t\tdlurl.append(\n\t\t\t\t\tstrprintf::fmt(\" (%s%s)\",\n\t\t\t\t\t\t_(\"type: \"),\n\t\t\t\t\t\titem->enclosure_type()));\n\t\t}\n\t\tlines.push_back(std::make_pair(LineType::softwrappable, dlurl));\n\t}\n\n\tlines.push_back(std::make_pair(LineType::wrappable, std::string(\"\")));\n}\n\nstd::string get_item_base_link(const std::shared_ptr& item)\n{\n\tif (!item->get_base().empty()) {\n\t\treturn item->get_base();\n\t} else {\n\t\treturn item->feedurl();\n\t}\n}\n\nvoid render_html(\n\tConfigContainer& cfg,\n\tconst std::string& source,\n\tstd::vector>& lines,\n\tstd::vector& thelinks,\n\tconst std::string& url,\n\tbool raw)\n{\n\tconst std::string renderer = cfg.get_configvalue(\"html-renderer\");\n\tif (renderer == \"internal\") {\n\t\tHtmlRenderer rnd(raw);\n\t\trnd.render(source, lines, thelinks, url);\n\t} else {\n\t\tchar* argv[4];\n\t\targv[0] = const_cast(\"\/bin\/sh\");\n\t\targv[1] = const_cast(\"-c\");\n\t\targv[2] = const_cast(renderer.c_str());\n\t\targv[3] = nullptr;\n\t\tLOG(Level::DEBUG,\n\t\t\t\"item_renderer::render_html: source = %s\",\n\t\t\tsource);\n\t\tLOG(Level::DEBUG,\n\t\t\t\"item_renderer::render_html: html-renderer = %s\",\n\t\t\targv[2]);\n\n\t\tconst std::string output = utils::run_program(argv, source);\n\t\tstd::istringstream is(output);\n\t\tstd::string line;\n\t\twhile (!is.eof()) {\n\t\t\tgetline(is, line);\n\t\t\tif (!raw) {\n\t\t\t\tline = utils::quote_for_stfl(line);\n\t\t\t}\n\t\t\tlines.push_back(std::make_pair(LineType::softwrappable, line));\n\t\t}\n\t}\n}\n\nstd::string item_renderer::to_plain_text(\n\t\tConfigContainer& cfg,\n\t\tstd::shared_ptr item)\n{\n\tstd::vector> lines;\n\tstd::vector links;\n\n\tprepare_header(item, lines, links);\n\tconst auto base = get_item_base_link(item);\n\trender_html(cfg, item->description(), lines, links, base, true);\n\n\tTextFormatter txtfmt;\n\ttxtfmt.add_lines(lines);\n\n\tunsigned int width = cfg.get_configvalue_as_int(\"text-width\");\n\tif (width == 0) {\n\t\twidth = 80;\n\t}\n\n\treturn txtfmt.format_text_plain(width);\n}\n\nstd::pair item_renderer::to_stfl_list(\n\t\tConfigContainer& cfg,\n\t\tstd::shared_ptr item,\n\t\tunsigned int text_width,\n\t\tunsigned int window_width,\n\t\tRegexManager* rxman,\n\t\tconst std::string& location,\n\t\tstd::vector& links)\n{\n\tstd::vector> lines;\n\n\tprepare_header(item, lines, links);\n\tconst std::string baseurl = get_item_base_link(item);\n\tconst auto body = item->description();\n\trender_html(cfg, body, lines, links, baseurl, false);\n\n\tTextFormatter txtfmt;\n\ttxtfmt.add_lines(lines);\n\n\treturn txtfmt.format_text_to_list(rxman, location, text_width, window_width);\n}\n\nvoid render_source(\n\tstd::vector>& lines,\n\tstd::string source)\n{\n\t\/*\n\t * This function is called instead of HtmlRenderer::render() when the\n\t * user requests to have the source displayed instead of seeing the\n\t * rendered HTML.\n\t *\/\n\tstd::string line;\n\tdo {\n\t\tstd::string::size_type pos = source.find_first_of(\"\\r\\n\");\n\t\tline = source.substr(0, pos);\n\t\tif (pos == std::string::npos) {\n\t\t\tsource.erase();\n\t\t} else {\n\t\t\tsource.erase(0, pos + 1);\n\t\t}\n\t\tlines.push_back(std::make_pair(LineType::softwrappable, line));\n\t} while (source.length() > 0);\n}\n\nstd::pair item_renderer::source_to_stfl_list(\n\t\tstd::shared_ptr item,\n\t\tunsigned int text_width,\n\t\tunsigned int window_width,\n\t\tRegexManager* rxman,\n\t\tconst std::string& location)\n{\n\tstd::vector> lines;\n\tstd::vector links;\n\n\tprepare_header(item, lines, links);\n\trender_source(lines, utils::quote_for_stfl(item->description()));\n\n\tTextFormatter txtfmt;\n\ttxtfmt.add_lines(lines);\n\n\treturn txtfmt.format_text_to_list(rxman, location, text_width, window_width);\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/dcache:$Name: v3-03-05 $:$Id: TDCacheFile.cxx,v 1.2 2002\/03\/25 16:43:16 rdm Exp $\n\/\/ Author: Grzegorz Mazur 20\/01\/2002\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TDCacheFile \/\/\n\/\/ \/\/\n\/\/ A TDCacheFile is like a normal TFile except that it may read and \/\/\n\/\/ write its data via a dCache server (for more on the dCache daemon \/\/\n\/\/ see http:\/\/www-dcache.desy.de\/. Given a path which doesn't belong \/\/\n\/\/ to the dCache managed filesystem, it falls back to the ordinary \/\/\n\/\/ TFile behaviour. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TDCacheFile.h\"\n#include \"TError.h\"\n#include \"TSystem.h\"\n#include \"TROOT.h\"\n\n#include \n#include \n#include \n\n#include \n\n\/\/______________________________________________________________________________\nstatic const char* const DCACHE_PREFIX = \"dcache:\";\nstatic const size_t DCACHE_PREFIX_LEN = strlen(DCACHE_PREFIX);\nstatic const char* const DCAP_PREFIX = \"dcap:\";\nstatic const size_t DCAP_PREFIX_LEN = strlen(DCAP_PREFIX);\n\n\/\/______________________________________________________________________________\nClassImp(TDCacheFile)\n\n\/\/______________________________________________________________________________\nTDCacheFile::TDCacheFile(const char *path, Option_t *option,\n const char *ftitle, Int_t compress):\n TFile(path, \"NET\", ftitle, compress)\n{\n \/\/ get rid of the optional URI\n if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))\n path += 7;\n\n fOption = option;\n fOffset = 0;\n\n Bool_t create = kFALSE;\n if (!fOption.CompareTo(\"NEW\", TString::kIgnoreCase) ||\n !fOption.CompareTo(\"CREATE\", TString::kIgnoreCase))\n create = kTRUE;\n Bool_t recreate = fOption.CompareTo(\"RECREATE\", TString::kIgnoreCase)\n ? kFALSE : kTRUE;\n Bool_t update = fOption.CompareTo(\"UPDATE\", TString::kIgnoreCase)\n ? kFALSE : kTRUE;\n Bool_t read = fOption.CompareTo(\"READ\", TString::kIgnoreCase)\n ? kFALSE : kTRUE;\n if (!create && !recreate && !update && !read) {\n read = kTRUE;\n fOption = \"READ\";\n }\n\n const char *fname;\n\n if (!strncmp(path, DCAP_PREFIX, DCAP_PREFIX_LEN)) {\n \/\/ Ugh, no PNFS support\n if (create || recreate || update) {\n Error(\"TDCacheFile\", \"Without PNFS support only reading access is allowed.\");\n goto zombie;\n }\n SetName(path);\n fname = GetName();\n } else {\n \/\/ Metadata provided by PNFS\n if ((fname = gSystem->ExpandPathName(path))) {\n SetName(fname);\n delete [] (char*)fname;\n fname = GetName();\n } else {\n Error(\"TDCacheFile\", \"error expanding path %s\", path);\n goto zombie;\n }\n\n if (recreate) {\n if (!gSystem->AccessPathName(fname, kFileExists))\n gSystem->Unlink(fname);\n recreate = kFALSE;\n create = kTRUE;\n fOption = \"CREATE\";\n }\n if (create && !gSystem->AccessPathName(fname, kFileExists)) {\n Error(\"TDCacheFile\", \"file %s already exists\", fname);\n goto zombie;\n }\n if (update) {\n if (gSystem->AccessPathName(fname, kFileExists)) {\n update = kFALSE;\n create = kTRUE;\n }\n if (update && gSystem->AccessPathName(fname, kWritePermission)) {\n Error(\"TDCacheFile\", \"no write permission, could not open file %s\", fname);\n goto zombie;\n }\n }\n if (read) {\n if (gSystem->AccessPathName(fname, kFileExists)) {\n Error(\"TDCacheFile\", \"file %s does not exist\", fname);\n goto zombie;\n }\n if (gSystem->AccessPathName(fname, kReadPermission)) {\n Error(\"TDCacheFile\", \"no read permission, could not open file %s\", fname);\n goto zombie;\n }\n }\n }\n \/\/ Connect to file system stream\n if (create || update) {\n#ifndef WIN32\n fD = SysOpen(fname, O_RDWR | O_CREAT, 0644);\n#else\n fD = SysOpen(fname, O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);\n#endif\n if (fD == -1) {\n SysError(\"TDCacheFile\", \"file %s can not be opened\", fname);\n goto zombie;\n }\n fWritable = kTRUE;\n } else {\n#ifndef WIN32\n fD = SysOpen(fname, O_RDONLY, 0644);\n#else\n fD = SysOpen(fname, O_RDONLY | O_BINARY, S_IREAD | S_IWRITE);\n#endif\n if (fD == -1) {\n SysError(\"TFile\", \"file %s can not be opened for reading\", fname);\n goto zombie;\n }\n fWritable = kFALSE;\n }\n\n \/\/ Disable dCache read-ahead buffer, as it doesn't cooperate well\n \/\/ with usually non-sequential file access pattern typical for\n \/\/ TFile. TCache performs much better, so UseCache() should be used\n \/\/ instead.\n dc_noBuffering(fD);\n\n Init(create);\n\n return;\n\nzombie:\n \/\/ error in file opening occured, make this object a zombie\n MakeZombie();\n gDirectory = gROOT;\n}\n\n\/\/______________________________________________________________________________\nTDCacheFile::~TDCacheFile()\n{\n \/\/ Close and cleanup dCache file.\n\n Close();\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::ReadBuffer(char *buf, Int_t len)\n{\n \/\/ Read specified byte range from remote file via dCache daemon.\n \/\/ Returns kTRUE in case of error.\n\n if (fCache) {\n Int_t st;\n Seek_t off = fOffset;\n if ((st = fCache->ReadBuffer(fOffset, buf, len)) < 0) {\n Error(\"ReadBuffer\", \"error reading from cache\");\n return kTRUE;\n }\n if (st > 0) {\n \/\/ fOffset might have been changed via TCache::ReadBuffer(), reset it\n fOffset = off + len;\n return kFALSE;\n }\n }\n\n return TFile::ReadBuffer(buf, len);\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::WriteBuffer(const char *buf, Int_t len)\n{\n \/\/ Write specified byte range to remote file via dCache daemon.\n \/\/ Returns kTRUE in case of error.\n\n if (!IsOpen() || !fWritable) return kTRUE;\n\n if (fCache) {\n Int_t st;\n Seek_t off = fOffset;\n if ((st = fCache->WriteBuffer(fOffset, buf, len)) < 0) {\n Error(\"WriteBuffer\", \"error writing to cache\");\n return kTRUE;\n }\n if (st > 0) {\n \/\/ fOffset might have been changed via TCache::WriteBuffer(), reset it\n fOffset = off + len;\n return kFALSE;\n }\n }\n\n return TFile::WriteBuffer(buf, len);\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::Stage(const char *path, UInt_t after, const char *location)\n{\n \/\/ Stage() returns kTRUE on success and kFALSE on failure.\n\n if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))\n path += 7;\n\n dc_errno = 0;\n\n if (dc_stage(path, after, location) == 0)\n return kTRUE;\n\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::CheckFile(const char *path, const char *location)\n{\n \/\/ Note: Name of the method was changed to avoid collision with Check\n \/\/ macro #defined in ROOT.\n \/\/ CheckFile() returns kTRUE on success and kFALSE on failure. In\n \/\/ case the file exists but is not cached, CheckFile() returns\n \/\/ kFALSE and errno is set to EAGAIN.\n\n if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))\n path += 7;\n\n dc_errno = 0;\n\n if (dc_check(path, location) == 0)\n return kTRUE;\n\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::SetOpenTimeout(UInt_t n)\n{\n dc_setOpenTimeout(n);\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::SetOnError(OnErrorAction a)\n{\n dc_setOnError(a);\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::SetReplyHostName(const char *host_name)\n{\n dc_setReplyHostName((char*)host_name);\n}\n\n\/\/______________________________________________________________________________\nconst char *TDCacheFile::GetDcapVersion()\n{\n return getDcapVersion();\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::EnableSSL()\n{\n#ifdef DCAP_USE_SSL\n dc_enableSSL();\n return kTRUE;\n#else\n return kFALSE;\n#endif\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysOpen(const char *pathname, Int_t flags, UInt_t mode)\n{\n dc_errno = 0;\n\n Int_t rc = dc_open(pathname, flags, (Int_t) mode);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysClose(Int_t fd)\n{\n dc_errno = 0;\n\n Int_t rc = dc_close(fd);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysRead(Int_t fd, void *buf, Int_t len)\n{\n fOffset += len;\n\n dc_errno = 0;\n\n Int_t rc = dc_read(fd, buf, len);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysWrite(Int_t fd, const void *buf, Int_t len)\n{\n fOffset += len;\n\n dc_errno = 0;\n\n Int_t rc = dc_write(fd, (char *)buf, len);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nSeek_t TDCacheFile::SysSeek(Int_t fd, Seek_t offset, Int_t whence)\n{\n switch (whence) {\n case SEEK_SET:\n if (offset == fOffset)\n return offset;\n else\n fOffset = offset;\n break;\n case SEEK_CUR:\n fOffset += offset;\n break;\n case SEEK_END:\n fOffset = fEND + offset;\n break;\n }\n\n dc_errno = 0;\n\n Int_t rc = dc_lseek(fd, offset, whence);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysSync(Int_t fd)\n{\n \/\/ dCache always keep it's files sync'ed, so there's no need to\n \/\/ sync() them manually.\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysStat(Int_t fd, Long_t *id, Long_t *size,\n Long_t *flags, Long_t *modtime)\n{\n \/\/ FIXME: dcap library doesn't (yet) provide any stat()\n \/\/ capabilities, relying on PNFS to provide all meta-level data. In\n \/\/ spite of this, it is possible to open a file which is not\n \/\/ accessible via PNFS. In such case we do some dirty tricks to\n \/\/ provide as much information as possible, but not everything can\n \/\/ really be done correctly.\n\n if (!strncmp(GetName(), DCAP_PREFIX, DCAP_PREFIX_LEN)) {\n \/\/ Ugh, no PNFS support.\n\n \/\/ Try to provide a unique id\n *id = ::Hash(GetName());\n\n \/\/ Funny way of checking the file size, isn't it?\n Seek_t offset = fOffset;\n *size = SysSeek(fd, 0, SEEK_END);\n SysSeek(fd, offset, SEEK_SET);\n\n *flags = 0; \/\/ This one is easy, only ordinary files are allowed here\n *modtime = 0; \/\/ FIXME: no way to get it right without dc_stat()\n return 0;\n } else {\n return TFile::SysStat(fd, id, size, flags, modtime);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::ResetErrno() const\n{\n \/\/ Method resetting the dc_errno and errno.\n\n dc_errno = 0;\n TSystem::ResetErrno();\n}\nsmall mod in option handling.\/\/ @(#)root\/dcache:$Name: $:$Id: TDCacheFile.cxx,v 1.3 2002\/07\/19 11:41:41 rdm Exp $\n\/\/ Author: Grzegorz Mazur 20\/01\/2002\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TDCacheFile \/\/\n\/\/ \/\/\n\/\/ A TDCacheFile is like a normal TFile except that it may read and \/\/\n\/\/ write its data via a dCache server (for more on the dCache daemon \/\/\n\/\/ see http:\/\/www-dcache.desy.de\/. Given a path which doesn't belong \/\/\n\/\/ to the dCache managed filesystem, it falls back to the ordinary \/\/\n\/\/ TFile behaviour. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TDCacheFile.h\"\n#include \"TError.h\"\n#include \"TSystem.h\"\n#include \"TROOT.h\"\n\n#include \n#include \n#include \n\n#include \n\n\/\/______________________________________________________________________________\nstatic const char* const DCACHE_PREFIX = \"dcache:\";\nstatic const size_t DCACHE_PREFIX_LEN = strlen(DCACHE_PREFIX);\nstatic const char* const DCAP_PREFIX = \"dcap:\";\nstatic const size_t DCAP_PREFIX_LEN = strlen(DCAP_PREFIX);\n\n\/\/______________________________________________________________________________\nClassImp(TDCacheFile)\n\n\/\/______________________________________________________________________________\nTDCacheFile::TDCacheFile(const char *path, Option_t *option,\n const char *ftitle, Int_t compress):\n TFile(path, \"NET\", ftitle, compress)\n{\n \/\/ get rid of the optional URI\n if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))\n path += 7;\n\n fOffset = 0;\n fOption = option;\n fOption.ToUpper();\n\n if (fOption == \"NEW\")\n fOption = \"CREATE\";\n\n Bool_t create = (fOption == \"CREATE\") ? kTRUE : kFALSE;\n Bool_t recreate = (fOption == \"RECREATE\") ? kTRUE : kFALSE;\n Bool_t update = (fOption == \"UPDATE\") ? kTRUE : kFALSE;\n Bool_t read = (fOption == \"READ\") ? kTRUE : kFALSE;\n if (!create && !recreate && !update && !read) {\n read = kTRUE;\n fOption = \"READ\";\n }\n\n const char *fname;\n\n if (!strncmp(path, DCAP_PREFIX, DCAP_PREFIX_LEN)) {\n \/\/ Ugh, no PNFS support\n if (create || recreate || update) {\n Error(\"TDCacheFile\", \"Without PNFS support only reading access is allowed.\");\n goto zombie;\n }\n SetName(path);\n fname = GetName();\n } else {\n \/\/ Metadata provided by PNFS\n if ((fname = gSystem->ExpandPathName(path))) {\n SetName(fname);\n delete [] (char*)fname;\n fname = GetName();\n } else {\n Error(\"TDCacheFile\", \"error expanding path %s\", path);\n goto zombie;\n }\n\n if (recreate) {\n if (!gSystem->AccessPathName(fname, kFileExists))\n gSystem->Unlink(fname);\n recreate = kFALSE;\n create = kTRUE;\n fOption = \"CREATE\";\n }\n if (create && !gSystem->AccessPathName(fname, kFileExists)) {\n Error(\"TDCacheFile\", \"file %s already exists\", fname);\n goto zombie;\n }\n if (update) {\n if (gSystem->AccessPathName(fname, kFileExists)) {\n update = kFALSE;\n create = kTRUE;\n }\n if (update && gSystem->AccessPathName(fname, kWritePermission)) {\n Error(\"TDCacheFile\", \"no write permission, could not open file %s\", fname);\n goto zombie;\n }\n }\n if (read) {\n if (gSystem->AccessPathName(fname, kFileExists)) {\n Error(\"TDCacheFile\", \"file %s does not exist\", fname);\n goto zombie;\n }\n if (gSystem->AccessPathName(fname, kReadPermission)) {\n Error(\"TDCacheFile\", \"no read permission, could not open file %s\", fname);\n goto zombie;\n }\n }\n }\n \/\/ Connect to file system stream\n if (create || update) {\n#ifndef WIN32\n fD = SysOpen(fname, O_RDWR | O_CREAT, 0644);\n#else\n fD = SysOpen(fname, O_RDWR | O_CREAT | O_BINARY, S_IREAD | S_IWRITE);\n#endif\n if (fD == -1) {\n SysError(\"TDCacheFile\", \"file %s can not be opened\", fname);\n goto zombie;\n }\n fWritable = kTRUE;\n } else {\n#ifndef WIN32\n fD = SysOpen(fname, O_RDONLY, 0644);\n#else\n fD = SysOpen(fname, O_RDONLY | O_BINARY, S_IREAD | S_IWRITE);\n#endif\n if (fD == -1) {\n SysError(\"TFile\", \"file %s can not be opened for reading\", fname);\n goto zombie;\n }\n fWritable = kFALSE;\n }\n\n \/\/ Disable dCache read-ahead buffer, as it doesn't cooperate well\n \/\/ with usually non-sequential file access pattern typical for\n \/\/ TFile. TCache performs much better, so UseCache() should be used\n \/\/ instead.\n dc_noBuffering(fD);\n\n Init(create);\n\n return;\n\nzombie:\n \/\/ error in file opening occured, make this object a zombie\n MakeZombie();\n gDirectory = gROOT;\n}\n\n\/\/______________________________________________________________________________\nTDCacheFile::~TDCacheFile()\n{\n \/\/ Close and cleanup dCache file.\n\n Close();\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::ReadBuffer(char *buf, Int_t len)\n{\n \/\/ Read specified byte range from remote file via dCache daemon.\n \/\/ Returns kTRUE in case of error.\n\n if (fCache) {\n Int_t st;\n Seek_t off = fOffset;\n if ((st = fCache->ReadBuffer(fOffset, buf, len)) < 0) {\n Error(\"ReadBuffer\", \"error reading from cache\");\n return kTRUE;\n }\n if (st > 0) {\n \/\/ fOffset might have been changed via TCache::ReadBuffer(), reset it\n fOffset = off + len;\n return kFALSE;\n }\n }\n\n return TFile::ReadBuffer(buf, len);\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::WriteBuffer(const char *buf, Int_t len)\n{\n \/\/ Write specified byte range to remote file via dCache daemon.\n \/\/ Returns kTRUE in case of error.\n\n if (!IsOpen() || !fWritable) return kTRUE;\n\n if (fCache) {\n Int_t st;\n Seek_t off = fOffset;\n if ((st = fCache->WriteBuffer(fOffset, buf, len)) < 0) {\n Error(\"WriteBuffer\", \"error writing to cache\");\n return kTRUE;\n }\n if (st > 0) {\n \/\/ fOffset might have been changed via TCache::WriteBuffer(), reset it\n fOffset = off + len;\n return kFALSE;\n }\n }\n\n return TFile::WriteBuffer(buf, len);\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::Stage(const char *path, UInt_t after, const char *location)\n{\n \/\/ Stage() returns kTRUE on success and kFALSE on failure.\n\n if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))\n path += 7;\n\n dc_errno = 0;\n\n if (dc_stage(path, after, location) == 0)\n return kTRUE;\n\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::CheckFile(const char *path, const char *location)\n{\n \/\/ Note: Name of the method was changed to avoid collision with Check\n \/\/ macro #defined in ROOT.\n \/\/ CheckFile() returns kTRUE on success and kFALSE on failure. In\n \/\/ case the file exists but is not cached, CheckFile() returns\n \/\/ kFALSE and errno is set to EAGAIN.\n\n if (!strncmp(path, DCACHE_PREFIX, DCACHE_PREFIX_LEN))\n path += 7;\n\n dc_errno = 0;\n\n if (dc_check(path, location) == 0)\n return kTRUE;\n\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n\n return kFALSE;\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::SetOpenTimeout(UInt_t n)\n{\n dc_setOpenTimeout(n);\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::SetOnError(OnErrorAction a)\n{\n dc_setOnError(a);\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::SetReplyHostName(const char *host_name)\n{\n dc_setReplyHostName((char*)host_name);\n}\n\n\/\/______________________________________________________________________________\nconst char *TDCacheFile::GetDcapVersion()\n{\n return getDcapVersion();\n}\n\n\/\/______________________________________________________________________________\nBool_t TDCacheFile::EnableSSL()\n{\n#ifdef DCAP_USE_SSL\n dc_enableSSL();\n return kTRUE;\n#else\n return kFALSE;\n#endif\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysOpen(const char *pathname, Int_t flags, UInt_t mode)\n{\n dc_errno = 0;\n\n Int_t rc = dc_open(pathname, flags, (Int_t) mode);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysClose(Int_t fd)\n{\n dc_errno = 0;\n\n Int_t rc = dc_close(fd);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysRead(Int_t fd, void *buf, Int_t len)\n{\n fOffset += len;\n\n dc_errno = 0;\n\n Int_t rc = dc_read(fd, buf, len);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysWrite(Int_t fd, const void *buf, Int_t len)\n{\n fOffset += len;\n\n dc_errno = 0;\n\n Int_t rc = dc_write(fd, (char *)buf, len);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nSeek_t TDCacheFile::SysSeek(Int_t fd, Seek_t offset, Int_t whence)\n{\n switch (whence) {\n case SEEK_SET:\n if (offset == fOffset)\n return offset;\n else\n fOffset = offset;\n break;\n case SEEK_CUR:\n fOffset += offset;\n break;\n case SEEK_END:\n fOffset = fEND + offset;\n break;\n }\n\n dc_errno = 0;\n\n Int_t rc = dc_lseek(fd, offset, whence);\n\n if (rc < 0) {\n if (dc_errno != 0)\n gSystem->SetErrorStr(dc_strerror(dc_errno));\n else\n gSystem->SetErrorStr(strerror(errno));\n }\n\n return rc;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysSync(Int_t fd)\n{\n \/\/ dCache always keep it's files sync'ed, so there's no need to\n \/\/ sync() them manually.\n\n return 0;\n}\n\n\/\/______________________________________________________________________________\nInt_t TDCacheFile::SysStat(Int_t fd, Long_t *id, Long_t *size,\n Long_t *flags, Long_t *modtime)\n{\n \/\/ FIXME: dcap library doesn't (yet) provide any stat()\n \/\/ capabilities, relying on PNFS to provide all meta-level data. In\n \/\/ spite of this, it is possible to open a file which is not\n \/\/ accessible via PNFS. In such case we do some dirty tricks to\n \/\/ provide as much information as possible, but not everything can\n \/\/ really be done correctly.\n\n if (!strncmp(GetName(), DCAP_PREFIX, DCAP_PREFIX_LEN)) {\n \/\/ Ugh, no PNFS support.\n\n \/\/ Try to provide a unique id\n *id = ::Hash(GetName());\n\n \/\/ Funny way of checking the file size, isn't it?\n Seek_t offset = fOffset;\n *size = SysSeek(fd, 0, SEEK_END);\n SysSeek(fd, offset, SEEK_SET);\n\n *flags = 0; \/\/ This one is easy, only ordinary files are allowed here\n *modtime = 0; \/\/ FIXME: no way to get it right without dc_stat()\n return 0;\n } else {\n return TFile::SysStat(fd, id, size, flags, modtime);\n }\n}\n\n\/\/______________________________________________________________________________\nvoid TDCacheFile::ResetErrno() const\n{\n \/\/ Method resetting the dc_errno and errno.\n\n dc_errno = 0;\n TSystem::ResetErrno();\n}\n<|endoftext|>"} {"text":"\n#include \"microsoftpush.hh\"\n#include \"log\/logmanager.hh\"\n#include \"sofia-sip\/base64.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\nWindowsPhonePushNotificationRequest::WindowsPhonePushNotificationRequest(const PushInfo &pinfo)\n: PushNotificationRequest(pinfo.mAppId, pinfo.mType), mPushInfo(pinfo) {\n\n if(pinfo.mType == \"wp\"){\n createHTTPRequest(\"\");\n }\n}\n\nvoid WindowsPhonePushNotificationRequest::createHTTPRequest(const std::string &access_token) {\n const string &host = mPushInfo.mAppId;\n char decodeUri[512] = {0};\n\n bool is_message = mPushInfo.mEvent == PushInfo::Message;\n const std::string &message = mPushInfo.mText;\n const std::string &sender_name = mPushInfo.mFromName;\n const std::string &sender_uri = mPushInfo.mFromUri;\n ostringstream httpBody;\n ostringstream httpHeader;\n \n if(mPushInfo.mType == \"w10\") {\n char unescapedUrl[512];\n url_unescape(unescapedUrl, mPushInfo.mDeviceToken.c_str());\n base64_d(decodeUri, sizeof(decodeUri), unescapedUrl);\n string query(decodeUri);\n if (is_message) {\n \/\/ We have to send the content of the message and the name of the sender.\n \/\/ We also need the sender address to be able to display the full chat view in case the receiver click the\n \/\/ toast.\n \n httpBody << \"\"\n << \"\"\n << \"\"\n << \"\"\n << \"\"\t<< sender_uri << \"<\/text>\"\n << \"\" << message << \"<\/text>\"\n << \"<\/binding>\"\n << \"<\/visual>\"\n << \"<\/toast>\";\n } else {\n \/\/ No need to specify name or number, this PN will only wake up linphone.\n httpBody << \"\"\n \t\t<< \"\"\n << \"\"\n << \"\"\n << \"Incoming Call<\/text>\"\n << \"\" << sender_uri << \"<\/text>\"\n << \"<\/binding>\"\n \t\t<< \"<\/visual>\"\n << \"<\/toast>\";\n }\n \n httpHeader << \"POST \" << query << \" HTTP\/1.1\\r\\n\"\n << \"Authorization: Bearer \" << access_token << \"\\r\\n\"\n << \"X-WNS-RequestForStatus: true\\r\\n\"\n << \"X-WNS-Type: wns\/toast\\r\\n\"\n << \"Content-Type: text\/xml\\r\\n\"\n << \"Host: \" << host << \"\\r\\n\"\n << \"Content-Length: \" << httpBody.str().size() << \"\\r\\n\\r\\n\";\n \n } else if(mPushInfo.mType == \"wp\"){\n if(is_message){\n httpBody << \"\"\n << sender_name << \"<\/wp:Text1>\" << message << \"<\/wp:Text2>\"\n \t<< \"\/Views\/Chat.xaml?sip=\" << sender_uri << \"<\/wp:Param><\/wp:Toast><\/wp:Notification>\";\n \n \/\/ Notification class 2 is the type for toast notifitcation.\n httpHeader\n << \"POST \" << mPushInfo.mDeviceToken << \" HTTP\/1.1\\r\\nHost:\" << host\n << \"\\r\\nX-WindowsPhone-Target:toast\\r\\nX-NotificationClass:2\\r\\nContent-Type:text\/xml\\r\\nContent-Length:\"\n << httpBody.str().size() << \"\\r\\n\\r\\n\";\n } else {\n httpBody << \"\"\n << \"<\/Name><\/Number><\/IncomingCall>\";\n \n \/\/ Notification class 4 is the type for VoIP incoming call.\n httpHeader << \"POST \" << mPushInfo.mDeviceToken << \" HTTP\/1.1\\r\\nHost:\" << host\n \t<< \"\\r\\nX-NotificationClass:4\\r\\nContent-Type:text\/xml\\r\\nContent-Length:\" << httpBody.str().size()\n \t<< \"\\r\\n\\r\\n\";\n }\n }\n \n mHttpHeader = httpHeader.str();\n mHttpBody = httpBody.str();\n\n SLOGD << \"PNR \" << this << \" POST header is \" << mHttpHeader;\n SLOGD << \"PNR \" << this << \" POST body is \" << mHttpBody;\n}\n\nvoid WindowsPhonePushNotificationRequest::createPushNotification() {\n\tint headerLength = mHttpHeader.length();\n\tint bodyLength = mHttpBody.length();\n\n\tmBuffer.clear();\n\tmBuffer.resize(headerLength + bodyLength);\n\n\tchar *binaryMessageBuff = &mBuffer[0];\n\tchar *binaryMessagePt = binaryMessageBuff;\n\n\tmemcpy(binaryMessagePt, &mHttpHeader[0], headerLength);\n\tbinaryMessagePt += headerLength;\n\n\tmemcpy(binaryMessagePt, &mHttpBody[0], bodyLength);\n\tbinaryMessagePt += bodyLength;\n}\n\nconst vector &WindowsPhonePushNotificationRequest::getData() {\n\tcreatePushNotification();\n\treturn mBuffer;\n}\n\nstd::string WindowsPhonePushNotificationRequest::isValidResponse(const string &str) {\n\tstring line;\n\tistringstream iss(str);\n\tbool valid = false, connect = false, notif = false;\n\twhile (getline(iss, line)) {\n if(mPushInfo.mType == \"w10\"){\n valid |= (line.find(\"HTTP\/1.1 200 OK\") != string::npos);\n connect |= (line.find(\"X-WNS-DEVICECONNECTIONSTATUS: connected\") != string::npos);\n notif |= (line.find(\"X-WNS-STATUS: received\") != string::npos);\n } else {\n connect |= (line.find(\"X-DeviceConnectionStatus: connected\") != string::npos);\n notif |= (line.find(\"X-NotificationStatus: Received\") != string::npos);\n valid |= (line.find(\"X-SubscriptionStatus: Active\") != string::npos);\n\n }\n\t\t\n\n\t\tauto it = line.find(\"X-WNS-ERROR-DESCRIPTION\");\n\t\tif (it != string::npos) {\n\t\t\treturn line.substr(line.find(' '));\n\t\t}\n\t}\n\tif (!valid) return \"Unexpected HTTP response value (not 200 OK)\";\n\tif (!connect) return \"Device connection status not set to connected\";\n\tif (!notif) return \"Notification not received by server\";\n\treturn \"\";\n}\nfix potential buffer overflow and reformat source code\/*\n\tFlexisip, a flexible SIP proxy server with media capabilities.\n\tCopyright (C) 2010-2015 Belledonne Communications SARL, All rights reserved.\n\n\tThis program is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU Affero General Public License as\n\tpublished by the Free Software Foundation, either version 3 of the\n\tLicense, or (at your option) any later version.\n\n\tThis program is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU Affero General Public License for more details.\n\n\tYou should have received a copy of the GNU Affero General Public License\n\talong with this program. If not, see .\n*\/\n\n\n#include \"microsoftpush.hh\"\n#include \"log\/logmanager.hh\"\n#include \"sofia-sip\/base64.h\"\n#include \n#include \n#include \n\nusing namespace std;\n\nWindowsPhonePushNotificationRequest::WindowsPhonePushNotificationRequest ( const PushInfo &pinfo )\n\t: PushNotificationRequest ( pinfo.mAppId, pinfo.mType ), mPushInfo ( pinfo ) {\n\n\tif ( pinfo.mType == \"wp\" ) {\n\t\tcreateHTTPRequest ( \"\" );\n\t}\n}\n\nvoid WindowsPhonePushNotificationRequest::createHTTPRequest ( const std::string &access_token ) {\n\tconst string &host = mPushInfo.mAppId;\n\tchar decodeUri[512] = {0};\n\n\tbool is_message = mPushInfo.mEvent == PushInfo::Message;\n\tconst std::string &message = mPushInfo.mText;\n\tconst std::string &sender_name = mPushInfo.mFromName;\n\tconst std::string &sender_uri = mPushInfo.mFromUri;\n\tostringstream httpBody;\n\tostringstream httpHeader;\n\n\tif ( mPushInfo.mType == \"w10\" ) {\n\t\tstring unescapedUrl;\n\n\t\tunescapedUrl.resize ( mPushInfo.mDeviceToken.size() );\n\t\turl_unescape ( &unescapedUrl[0], mPushInfo.mDeviceToken.c_str() );\n\t\tbase64_d ( decodeUri, sizeof ( decodeUri ), unescapedUrl.c_str() );\n\t\tstring query ( decodeUri );\n\t\tif ( is_message ) {\n\t\t\t\/\/ We have to send the content of the message and the name of the sender.\n\t\t\t\/\/ We also need the sender address to be able to display the full chat view in case the receiver click the\n\t\t\t\/\/ toast.\n\n\t\t\thttpBody << \"\"\n\t\t\t\t\t << \"\"\n\t\t\t\t\t << \"\"\n\t\t\t\t\t << \"\"\n\t\t\t\t\t << \"\"\t<< sender_uri << \"<\/text>\"\n\t\t\t\t\t << \"\" << message << \"<\/text>\"\n\t\t\t\t\t << \"<\/binding>\"\n\t\t\t\t\t << \"<\/visual>\"\n\t\t\t\t\t << \"<\/toast>\";\n\t\t} else {\n\t\t\t\/\/ No need to specify name or number, this PN will only wake up linphone.\n\t\t\thttpBody << \"\"\n\t\t\t\t\t << \"\"\n\t\t\t\t\t << \"\"\n\t\t\t\t\t << \"\"\n\t\t\t\t\t << \"Incoming Call<\/text>\"\n\t\t\t\t\t << \"\" << sender_uri << \"<\/text>\"\n\t\t\t\t\t << \"<\/binding>\"\n\t\t\t\t\t << \"<\/visual>\"\n\t\t\t\t\t << \"<\/toast>\";\n\t\t}\n\n\t\thttpHeader << \"POST \" << query << \" HTTP\/1.1\\r\\n\"\n\t\t\t\t << \"Authorization: Bearer \" << access_token << \"\\r\\n\"\n\t\t\t\t << \"X-WNS-RequestForStatus: true\\r\\n\"\n\t\t\t\t << \"X-WNS-Type: wns\/toast\\r\\n\"\n\t\t\t\t << \"Content-Type: text\/xml\\r\\n\"\n\t\t\t\t << \"Host: \" << host << \"\\r\\n\"\n\t\t\t\t << \"Content-Length: \" << httpBody.str().size() << \"\\r\\n\\r\\n\";\n\n\t} else if ( mPushInfo.mType == \"wp\" ) {\n\t\tif ( is_message ) {\n\t\t\thttpBody << \"\"\n\t\t\t\t\t << sender_name << \"<\/wp:Text1>\" << message << \"<\/wp:Text2>\"\n\t\t\t\t\t << \"\/Views\/Chat.xaml?sip=\" << sender_uri << \"<\/wp:Param><\/wp:Toast><\/wp:Notification>\";\n\n\t\t\t\/\/ Notification class 2 is the type for toast notifitcation.\n\t\t\thttpHeader\n\t\t\t\t\t<< \"POST \" << mPushInfo.mDeviceToken << \" HTTP\/1.1\\r\\nHost:\" << host\n\t\t\t\t\t<< \"\\r\\nX-WindowsPhone-Target:toast\\r\\nX-NotificationClass:2\\r\\nContent-Type:text\/xml\\r\\nContent-Length:\"\n\t\t\t\t\t<< httpBody.str().size() << \"\\r\\n\\r\\n\";\n\t\t} else {\n\t\t\thttpBody << \"\"\n\t\t\t\t\t << \"<\/Name><\/Number><\/IncomingCall>\";\n\n\t\t\t\/\/ Notification class 4 is the type for VoIP incoming call.\n\t\t\thttpHeader << \"POST \" << mPushInfo.mDeviceToken << \" HTTP\/1.1\\r\\nHost:\" << host\n\t\t\t\t\t << \"\\r\\nX-NotificationClass:4\\r\\nContent-Type:text\/xml\\r\\nContent-Length:\" << httpBody.str().size()\n\t\t\t\t\t << \"\\r\\n\\r\\n\";\n\t\t}\n\t}\n\n\tmHttpHeader = httpHeader.str();\n\tmHttpBody = httpBody.str();\n\n\tSLOGD << \"PNR \" << this << \" POST header is \" << mHttpHeader;\n\tSLOGD << \"PNR \" << this << \" POST body is \" << mHttpBody;\n}\n\nvoid WindowsPhonePushNotificationRequest::createPushNotification() {\n\tint headerLength = mHttpHeader.length();\n\tint bodyLength = mHttpBody.length();\n\n\tmBuffer.clear();\n\tmBuffer.resize ( headerLength + bodyLength );\n\n\tchar *binaryMessageBuff = &mBuffer[0];\n\tchar *binaryMessagePt = binaryMessageBuff;\n\n\tmemcpy ( binaryMessagePt, &mHttpHeader[0], headerLength );\n\tbinaryMessagePt += headerLength;\n\n\tmemcpy ( binaryMessagePt, &mHttpBody[0], bodyLength );\n\tbinaryMessagePt += bodyLength;\n}\n\nconst vector &WindowsPhonePushNotificationRequest::getData() {\n\tcreatePushNotification();\n\treturn mBuffer;\n}\n\nstd::string WindowsPhonePushNotificationRequest::isValidResponse ( const string &str ) {\n\tstring line;\n\tistringstream iss ( str );\n\tbool valid = false, connect = false, notif = false;\n\twhile ( getline ( iss, line ) ) {\n\t\tif ( mPushInfo.mType == \"w10\" ) {\n\t\t\tvalid |= ( line.find ( \"HTTP\/1.1 200 OK\" ) != string::npos );\n\t\t\tconnect |= ( line.find ( \"X-WNS-DEVICECONNECTIONSTATUS: connected\" ) != string::npos );\n\t\t\tnotif |= ( line.find ( \"X-WNS-STATUS: received\" ) != string::npos );\n\t\t} else {\n\t\t\tconnect |= ( line.find ( \"X-DeviceConnectionStatus: connected\" ) != string::npos );\n\t\t\tnotif |= ( line.find ( \"X-NotificationStatus: Received\" ) != string::npos );\n\t\t\tvalid |= ( line.find ( \"X-SubscriptionStatus: Active\" ) != string::npos );\n\n\t\t}\n\n\n\t\tauto it = line.find ( \"X-WNS-ERROR-DESCRIPTION\" );\n\t\tif ( it != string::npos ) {\n\t\t\treturn line.substr ( line.find ( ' ' ) );\n\t\t}\n\t}\n\tif ( !valid ) return \"Unexpected HTTP response value (not 200 OK)\";\n\tif ( !connect ) return \"Device connection status not set to connected\";\n\tif ( !notif ) return \"Notification not received by server\";\n\treturn \"\";\n}\n<|endoftext|>"} {"text":"\/*\n * PrimeSieveGUI_menu.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2012 Kim Walisch, \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see \n *\/\n\n#include \"PrimeSieveGUI.h\"\n#include \"ui_PrimeSieveGUI.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\/**\n * Initialize the menu items.\n *\/\nvoid PrimeSieveGUI::createMenuActions(QVector& primeText) {\n \/\/ file actions\n saveAct_ = new QAction(\"&Save\", this);\n saveAct_->setShortcut(tr(\"Ctrl+S\"));\n quitAct_ = new QAction(\"&Quit\", this);\n quitAct_->setShortcut(tr(\"Ctrl+Q\"));\n\n \/\/ count actions\n countAct_.push_back(new QAction(primeText[0], this));\n countAct_.back()->setCheckable(true);\n countAct_.push_back(new QAction(\"Prime k-tuplets\", this));\n countAct_.back()->setCheckable(true);\n \/\/ default count prime numbers\n countAct_.front()->setChecked(true);\n\n \/\/ radio button like behaviour for print actions\n alignmentGroup_ = new QActionGroup(this);\n alignmentGroup_->setExclusive(false);\n\n \/\/ print actions\n for (int i = 0; i < primeText.size(); i++) {\n printAct_.push_back(new QAction(primeText[i], this));\n printAct_.back()->setCheckable(true);\n alignmentGroup_->addAction(printAct_.back());\n }\n \/\/ about action\n aboutAct_ = new QAction(\"About\", this);\n}\n\n\/**\n * Create the menu bar with 'File', 'Count', 'Print' and 'Help'\n * menu options.\n *\/\nvoid PrimeSieveGUI::createMenu(QVector& primeText) {\n this->createMenuActions(primeText);\n\n fileMenu_ = menuBar()->addMenu(\"&File\");\n fileMenu_->addAction(saveAct_);\n fileMenu_->addAction(quitAct_);\n countMenu_ = menuBar()->addMenu(\"&Count\");\n for (int i = 0; i < countAct_.size(); i++)\n countMenu_->addAction(countAct_[i]);\n printMenu_ = menuBar()->addMenu(\"&Print\");\n for (int i = 0; i < printAct_.size(); i++)\n printMenu_->addAction(printAct_[i]);\n helpMenu_ = menuBar()->addMenu(\"&Help\");\n helpMenu_->addAction(aboutAct_);\n}\n\n\/**\n * Return the count and print menu settings as bit flags.\n *\/\nint PrimeSieveGUI::getMenuSettings() {\n int flags = 0;\n \/\/ get count settings\n if (countAct_[0]->isChecked())\n flags |= COUNT_PRIMES;\n if (countAct_[1]->isChecked())\n flags |= COUNT_KTUPLETS;\n \/\/ get print settings\n for (int i = 0; i < printAct_.size(); i++)\n if (printAct_[i]->isChecked())\n flags |= PRINT_PRIMES << i;\n return flags;\n}\n\n\/**\n * Disable the \"Threads\" ComboBox and the \"Auto set\" CheckBox and\n * set to 1 Threads for printing (else invert).\n *\/\nvoid PrimeSieveGUI::printMenuClicked(QAction* qAct) {\n \/\/ disable other print options\n for (int i = 0; i < printAct_.size(); i++) {\n if (printAct_[i] != qAct)\n printAct_[i]->setChecked(false);\n }\n ui->autoSetCheckBox->setDisabled(qAct->isChecked());\n if (qAct->isChecked()) {\n ui->autoSetCheckBox->setChecked(true);\n ui->threadsComboBox->setCurrentIndex(0);\n }\n ui->threadsComboBox->setDisabled(qAct->isChecked());\n this->autoSetThreads();\n}\n\n\/**\n * Save the content of the textEdit to a file.\n *\/\nvoid PrimeSieveGUI::saveToFile() {\n \/\/ Qt uses '\/' internally, also for Windows\n QString currentPath = QDir::currentPath() + \"\/Unsaved Document 1\";\n QString fileName = QFileDialog::getSaveFileName(this, \"Save As...\", currentPath, \"All Files (*)\");\n QFile file(fileName);\n if (file.open(QFile::WriteOnly | QFile::Text)) {\n QTextStream textStream(&file);\n textStream << ui->textEdit->toPlainText();\n }\n}\n\nvoid PrimeSieveGUI::showAboutDialog() {\n QString title = \"About \" + APPLICATION_NAME;\n QString message = \"

\" + APPLICATION_NAME + \" \" + PRIMESIEVE_VERSION + \"<\/h2>\"\n + \"

Copyright © \" + PRIMESIEVE_YEAR + \" Kim Walisch<\/p>\"\n + \"

\" + APPLICATION_ABOUT + \"<\/p>\"\n + \"\" + APPLICATION_HOMEPAGE + \"<\/a>\";\n QMessageBox::about(this, title, message);\n}\nfixed typing error\/*\n * PrimeSieveGUI_menu.cpp -- This file is part of primesieve\n *\n * Copyright (C) 2012 Kim Walisch, \n *\n * This program is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program. If not, see \n *\/\n\n#include \"PrimeSieveGUI.h\"\n#include \"ui_PrimeSieveGUI.h\"\n#include \"..\/soe\/ParallelPrimeSieve.h\"\n\n#include \n#include \n#include \n#include \n#include \n\n\/**\n * Initialize the menu items.\n *\/\nvoid PrimeSieveGUI::createMenuActions(QVector& primeText) {\n \/\/ file actions\n saveAct_ = new QAction(\"&Save\", this);\n saveAct_->setShortcut(tr(\"Ctrl+S\"));\n quitAct_ = new QAction(\"&Quit\", this);\n quitAct_->setShortcut(tr(\"Ctrl+Q\"));\n\n \/\/ count actions\n countAct_.push_back(new QAction(primeText[0], this));\n countAct_.back()->setCheckable(true);\n countAct_.push_back(new QAction(\"Prime k-tuplets\", this));\n countAct_.back()->setCheckable(true);\n \/\/ default count prime numbers\n countAct_.front()->setChecked(true);\n\n \/\/ radio button like behaviour for print actions\n alignmentGroup_ = new QActionGroup(this);\n alignmentGroup_->setExclusive(false);\n\n \/\/ print actions\n for (int i = 0; i < primeText.size(); i++) {\n printAct_.push_back(new QAction(primeText[i], this));\n printAct_.back()->setCheckable(true);\n alignmentGroup_->addAction(printAct_.back());\n }\n \/\/ about action\n aboutAct_ = new QAction(\"About\", this);\n}\n\n\/**\n * Create the menu bar with 'File', 'Count', 'Print' and 'Help'\n * menu options.\n *\/\nvoid PrimeSieveGUI::createMenu(QVector& primeText) {\n this->createMenuActions(primeText);\n\n fileMenu_ = menuBar()->addMenu(\"&File\");\n fileMenu_->addAction(saveAct_);\n fileMenu_->addAction(quitAct_);\n countMenu_ = menuBar()->addMenu(\"&Count\");\n for (int i = 0; i < countAct_.size(); i++)\n countMenu_->addAction(countAct_[i]);\n printMenu_ = menuBar()->addMenu(\"&Print\");\n for (int i = 0; i < printAct_.size(); i++)\n printMenu_->addAction(printAct_[i]);\n helpMenu_ = menuBar()->addMenu(\"&Help\");\n helpMenu_->addAction(aboutAct_);\n}\n\n\/**\n * Return the count and print menu settings as bit flags.\n *\/\nint PrimeSieveGUI::getMenuSettings() {\n int flags = 0;\n \/\/ get count settings\n if (countAct_[0]->isChecked())\n flags |= COUNT_PRIMES;\n if (countAct_[1]->isChecked())\n flags |= COUNT_KTUPLETS;\n \/\/ get print settings\n for (int i = 0; i < printAct_.size(); i++)\n if (printAct_[i]->isChecked())\n flags |= PRINT_PRIMES << i;\n return flags;\n}\n\n\/**\n * Disable the \"Threads\" ComboBox and the \"Auto set\" CheckBox and\n * set to 1 Threads for printing (else invert).\n *\/\nvoid PrimeSieveGUI::printMenuClicked(QAction* qAct) {\n \/\/ disable other print options\n for (int i = 0; i < printAct_.size(); i++) {\n if (printAct_[i] != qAct)\n printAct_[i]->setChecked(false);\n }\n ui->autoSetCheckBox->setDisabled(qAct->isChecked());\n if (qAct->isChecked()) {\n ui->autoSetCheckBox->setChecked(true);\n ui->threadsComboBox->setCurrentIndex(0);\n }\n ui->threadsComboBox->setDisabled(qAct->isChecked());\n this->autoSetThreads();\n}\n\n\/**\n * Save the content of the textEdit to a file.\n *\/\nvoid PrimeSieveGUI::saveToFile() {\n \/\/ Qt uses '\/' internally, also for Windows\n QString currentPath = QDir::currentPath() + \"\/Unsaved Document 1\";\n QString fileName = QFileDialog::getSaveFileName(this, \"Save As...\", currentPath, \"All Files (*)\");\n QFile file(fileName);\n if (file.open(QFile::WriteOnly | QFile::Text)) {\n QTextStream textStream(&file);\n textStream << ui->textEdit->toPlainText();\n }\n}\n\nvoid PrimeSieveGUI::showAboutDialog() {\n QString year = QString::number(PRIMESIEVE_YEAR);\n QString title = \"About \" + APPLICATION_NAME;\n QString message = \"

\" + APPLICATION_NAME + \" \" + PRIMESIEVE_VERSION + \"<\/h2>\"\n + \"

Copyright © \" + year + \" Kim Walisch<\/p>\"\n + \"

\" + APPLICATION_ABOUT + \"<\/p>\"\n + \"\" + APPLICATION_HOMEPAGE + \"<\/a>\";\n QMessageBox::about(this, title, message);\n}\n<|endoftext|>"} {"text":"#include \"offerwhitelisttablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet\/wallet.h\"\n#include \"base58.h\"\n\n#include \nusing namespace std;\n\nstruct MyOfferWhitelistTableEntry\n{\n\tQString offer;\n QString alias;\n\tQString expires;\n\tQString discount;\t\n\n MyOfferWhitelistTableEntry() {}\n MyOfferWhitelistTableEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount):\n offer(offer), alias(alias), expires(expires),discount(discount) {}\n};\n\n\n\/\/ Private implementation\nclass MyOfferWhitelistTablePriv\n{\npublic:\n QList cachedEntryTable;\n MyOfferWhitelistTableModel *parent;\n\n OfferWhitelistTablePriv(MyOfferWhitelistTableModel *parent):\n parent(parent) {}\n\n\n void updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)\n {\n\t\tif(!parent)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n switch(status)\n {\n case CT_NEW:\n\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedEntryTable.insert(lowerIndex, MyOfferWhitelistTableEntry(offer, alias, expires, discount));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n lower->offer = offer;\n\t\t\tlower->alias = alias;\n\t\t\tlower->expires = expires;\n\t\t\tlower->discount = discount;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n \n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedEntryTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedEntryTable.size();\n }\n\n OfferWhitelistTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedEntryTable.size())\n {\n return &cachedEntryTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nMyOfferWhitelistTableModel::MyOfferWhitelistTableModel(WalletModel *parent) :\n QAbstractTableModel(parent)\n{\n columns << tr(\"Offer\") << tr(\"Alias\") << tr(\"Discount\") << tr(\"Expires In\");\n priv = new OfferWhitelistTablePriv(this);\n\n}\n\nMyOfferWhitelistTableModel::~MyOfferWhitelistTableModel()\n{\n delete priv;\n}\nint MyOfferWhitelistTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint MyOfferWhitelistTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant MyOfferWhitelistTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n OfferWhitelistTableEntry *rec = static_cast(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Offer:\n return rec->offer;\n case Alias:\n return rec->alias;\n case Discount:\n return rec->discount;\n case Expires:\n return rec->expires;\n }\n }\n else if (role == AliasRole)\n {\n return rec->alias;\n }\n return QVariant();\n}\n\nbool MyOfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n OfferWhitelistTableEntry *rec = static_cast(index.internalPointer());\n\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Offer:\n \/\/ Do nothing, if old value == new value\n if(rec->offer == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \n break;\n case Alias:\n \/\/ Do nothing, if old value == new value\n if(rec->alias == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \n break;\n case Discount:\n \/\/ Do nothing, if old value == new value\n if(rec->discount == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \n break;\n case Expires:\n \/\/ Do nothing, if old value == new value\n if(rec->expires == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n break;\n return true;\n\t\t}\n }\n return false;\n}\n\nQVariant MyOfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags MyOfferWhitelistTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n return retval;\n}\n\nQModelIndex MyOfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n OfferWhitelistTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid MyOfferWhitelistTableModel::updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)\n{\n priv->updateEntry(offer, alias, expires, discount, status);\n}\n\nQString MyOfferWhitelistTableModel::addRow(const QString &offer, const QString &alias, const QString &expires,const QString &discount)\n{\n std::string strAlias = alias.toStdString();\n editStatus = OK;\n return QString::fromStdString(strAlias);\n}\nvoid MyOfferWhitelistTableModel::clear()\n{\n\tbeginResetModel();\n priv->cachedEntryTable.clear();\n\tendResetModel();\n}\n\n\nvoid MyOfferWhitelistTableModel::emitDataChanged(int idx)\n{\n Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\ntypo#include \"myofferwhitelisttablemodel.h\"\n\n#include \"guiutil.h\"\n#include \"walletmodel.h\"\n\n#include \"wallet\/wallet.h\"\n#include \"base58.h\"\n\n#include \nusing namespace std;\n\nstruct MyOfferWhitelistTableEntry\n{\n\tQString offer;\n QString alias;\n\tQString expires;\n\tQString discount;\t\n\n MyOfferWhitelistTableEntry() {}\n MyOfferWhitelistTableEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount):\n offer(offer), alias(alias), expires(expires),discount(discount) {}\n};\n\n\n\/\/ Private implementation\nclass MyOfferWhitelistTablePriv\n{\npublic:\n QList cachedEntryTable;\n MyOfferWhitelistTableModel *parent;\n\n OfferWhitelistTablePriv(MyOfferWhitelistTableModel *parent):\n parent(parent) {}\n\n\n void updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)\n {\n\t\tif(!parent)\n\t\t{\n\t\t\treturn;\n\t\t}\n\n switch(status)\n {\n case CT_NEW:\n\n parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);\n cachedEntryTable.insert(lowerIndex, MyOfferWhitelistTableEntry(offer, alias, expires, discount));\n parent->endInsertRows();\n break;\n case CT_UPDATED:\n lower->offer = offer;\n\t\t\tlower->alias = alias;\n\t\t\tlower->expires = expires;\n\t\t\tlower->discount = discount;\n parent->emitDataChanged(lowerIndex);\n break;\n case CT_DELETED:\n \n parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex-1);\n cachedEntryTable.erase(lower, upper);\n parent->endRemoveRows();\n break;\n }\n }\n\n int size()\n {\n return cachedEntryTable.size();\n }\n\n OfferWhitelistTableEntry *index(int idx)\n {\n if(idx >= 0 && idx < cachedEntryTable.size())\n {\n return &cachedEntryTable[idx];\n }\n else\n {\n return 0;\n }\n }\n};\n\nMyOfferWhitelistTableModel::MyOfferWhitelistTableModel(WalletModel *parent) :\n QAbstractTableModel(parent)\n{\n columns << tr(\"Offer\") << tr(\"Alias\") << tr(\"Discount\") << tr(\"Expires In\");\n priv = new OfferWhitelistTablePriv(this);\n\n}\n\nMyOfferWhitelistTableModel::~MyOfferWhitelistTableModel()\n{\n delete priv;\n}\nint MyOfferWhitelistTableModel::rowCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return priv->size();\n}\n\nint MyOfferWhitelistTableModel::columnCount(const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n return columns.length();\n}\n\nQVariant MyOfferWhitelistTableModel::data(const QModelIndex &index, int role) const\n{\n if(!index.isValid())\n return QVariant();\n\n OfferWhitelistTableEntry *rec = static_cast(index.internalPointer());\n\n if(role == Qt::DisplayRole || role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Offer:\n return rec->offer;\n case Alias:\n return rec->alias;\n case Discount:\n return rec->discount;\n case Expires:\n return rec->expires;\n }\n }\n else if (role == AliasRole)\n {\n return rec->alias;\n }\n return QVariant();\n}\n\nbool MyOfferWhitelistTableModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if(!index.isValid())\n return false;\n OfferWhitelistTableEntry *rec = static_cast(index.internalPointer());\n\n editStatus = OK;\n\n if(role == Qt::EditRole)\n {\n switch(index.column())\n {\n case Offer:\n \/\/ Do nothing, if old value == new value\n if(rec->offer == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \n break;\n case Alias:\n \/\/ Do nothing, if old value == new value\n if(rec->alias == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \n break;\n case Discount:\n \/\/ Do nothing, if old value == new value\n if(rec->discount == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n \n break;\n case Expires:\n \/\/ Do nothing, if old value == new value\n if(rec->expires == value.toString())\n {\n editStatus = NO_CHANGES;\n return false;\n }\n break;\n return true;\n\t\t}\n }\n return false;\n}\n\nQVariant MyOfferWhitelistTableModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n if(orientation == Qt::Horizontal)\n {\n if(role == Qt::DisplayRole)\n {\n return columns[section];\n }\n }\n return QVariant();\n}\n\nQt::ItemFlags MyOfferWhitelistTableModel::flags(const QModelIndex &index) const\n{\n if(!index.isValid())\n return 0;\n Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;\n return retval;\n}\n\nQModelIndex MyOfferWhitelistTableModel::index(int row, int column, const QModelIndex &parent) const\n{\n Q_UNUSED(parent);\n OfferWhitelistTableEntry *data = priv->index(row);\n if(data)\n {\n return createIndex(row, column, priv->index(row));\n }\n else\n {\n return QModelIndex();\n }\n}\n\nvoid MyOfferWhitelistTableModel::updateEntry(const QString &offer, const QString &alias, const QString &expires,const QString &discount, int status)\n{\n priv->updateEntry(offer, alias, expires, discount, status);\n}\n\nQString MyOfferWhitelistTableModel::addRow(const QString &offer, const QString &alias, const QString &expires,const QString &discount)\n{\n std::string strAlias = alias.toStdString();\n editStatus = OK;\n return QString::fromStdString(strAlias);\n}\nvoid MyOfferWhitelistTableModel::clear()\n{\n\tbeginResetModel();\n priv->cachedEntryTable.clear();\n\tendResetModel();\n}\n\n\nvoid MyOfferWhitelistTableModel::emitDataChanged(int idx)\n{\n Q_EMIT dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length()-1, QModelIndex()));\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2014 Jolla Ltd.\n** Contact: Raine Makelainen \n**\n****************************************************************************\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this file,\n * You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"declarativewebpage.h\"\n#include \"declarativewebcontainer.h\"\n#include \"dbmanager.h\"\n\n#include \n#include \n\nstatic const QString gFullScreenMessage(\"embed:fullscreenchanged\");\nstatic const QString gDomContentLoadedMessage(\"embed:domcontentloaded\");\n\nstatic const QString gLinkAddedMessage(\"chrome:linkadded\");\nstatic const QString gAlertMessage(\"embed:alert\");\nstatic const QString gConfirmMessage(\"embed:confirm\");\nstatic const QString gPromptMessage(\"embed:prompt\");\nstatic const QString gAuthMessage(\"embed:auth\");\nstatic const QString gLoginMessage(\"embed:login\");\nstatic const QString gFindMessage(\"embed:find\");\nstatic const QString gPermissionsMessage(\"embed:permissions\");\nstatic const QString gContextMenuMessage(\"Content:ContextMenu\");\nstatic const QString gSelectionRangeMessage(\"Content:SelectionRange\");\nstatic const QString gSelectionCopiedMessage(\"Content:SelectionCopied\");\nstatic const QString gSelectAsyncMessage(\"embed:selectasync\");\nstatic const QString gFilePickerMessage(\"embed:filepicker\");\n\nbool isBlack(QRgb rgb)\n{\n return qRed(rgb) == 0 && qGreen(rgb) == 0 && qBlue(rgb) == 0;\n}\n\nbool allBlack(const QImage &image)\n{\n int h = image.height();\n int w = image.width();\n\n for (int j = 0; j < h; ++j) {\n const QRgb *b = (const QRgb *)image.constScanLine(j);\n for (int i = 0; i < w; ++i) {\n if (!isBlack(b[i]))\n return false;\n }\n }\n return true;\n}\n\nDeclarativeWebPage::DeclarativeWebPage(QObject *parent)\n : QOpenGLWebPage(parent)\n , m_container(0)\n , m_userHasDraggedWhileLoading(false)\n , m_fullscreen(false)\n , m_forcedChrome(false)\n , m_domContentLoaded(false)\n , m_initialLoadHasHappened(false)\n , m_tabHistoryReady(false)\n , m_urlReady(false)\n{\n addMessageListener(gFullScreenMessage);\n addMessageListener(gDomContentLoadedMessage);\n\n addMessageListener(gLinkAddedMessage);\n addMessageListener(gAlertMessage);\n addMessageListener(gConfirmMessage);\n addMessageListener(gPromptMessage);\n addMessageListener(gAuthMessage);\n addMessageListener(gLoginMessage);\n addMessageListener(gFindMessage);\n addMessageListener(gPermissionsMessage);\n addMessageListener(gContextMenuMessage);\n addMessageListener(gSelectionRangeMessage);\n addMessageListener(gSelectionCopiedMessage);\n addMessageListener(gSelectAsyncMessage);\n addMessageListener(gFilePickerMessage);\n\n loadFrameScript(\"chrome:\/\/embedlite\/content\/SelectAsyncHelper.js\");\n loadFrameScript(\"chrome:\/\/embedlite\/content\/embedhelper.js\");\n\n connect(this, SIGNAL(recvAsyncMessage(const QString, const QVariant)),\n this, SLOT(onRecvAsyncMessage(const QString&, const QVariant&)));\n connect(&m_grabWritter, SIGNAL(finished()), this, SLOT(grabWritten()));\n connect(this, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight()));\n connect(this, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight()));\n connect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));\n}\n\nDeclarativeWebPage::~DeclarativeWebPage()\n{\n m_grabWritter.cancel();\n m_grabWritter.waitForFinished();\n m_grabResult.clear();\n m_thumbnailResult.clear();\n}\n\nDeclarativeWebContainer *DeclarativeWebPage::container() const\n{\n return m_container;\n}\n\nvoid DeclarativeWebPage::setContainer(DeclarativeWebContainer *container)\n{\n if (m_container != container) {\n m_container = container;\n emit containerChanged();\n }\n}\n\nint DeclarativeWebPage::tabId() const\n{\n return m_initialTab.tabId();\n}\n\nvoid DeclarativeWebPage::setInitialTab(const Tab& tab)\n{\n Q_ASSERT(m_initialTab.tabId() == 0);\n\n m_initialTab = tab;\n emit tabIdChanged();\n connect(DBManager::instance(), SIGNAL(tabHistoryAvailable(int, QList)),\n this, SLOT(onTabHistoryAvailable(int, QList)));\n DBManager::instance()->getTabHistory(tabId());\n}\n\nvoid DeclarativeWebPage::onUrlChanged()\n{\n disconnect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));\n m_urlReady = true;\n restoreHistory();\n}\n\nvoid DeclarativeWebPage::onTabHistoryAvailable(const int& historyTabId, const QList& links)\n{\n if (historyTabId == tabId()) {\n m_restoredTabHistory = links;\n\n std::reverse(m_restoredTabHistory.begin(), m_restoredTabHistory.end());\n DBManager::instance()->disconnect(this);\n m_tabHistoryReady = true;\n restoreHistory();\n }\n}\n\nvoid DeclarativeWebPage::restoreHistory() {\n if (!m_urlReady || !m_tabHistoryReady || m_restoredTabHistory.count() == 0) {\n return;\n }\n\n QList urls;\n int index(-1);\n int i(0);\n foreach (Link link, m_restoredTabHistory) {\n urls << link.url();\n if (link.linkId() == m_initialTab.currentLink()) {\n index = i;\n if (link.url() != m_initialTab.url()) {\n \/\/ The browser was started with an initial URL as a cmdline parameter -> reset tab history\n urls << m_initialTab.url();\n index++;\n DBManager::instance()->navigateTo(tabId(), m_initialTab.url(), \"\", \"\");\n break;\n }\n }\n i++;\n }\n\n if (index < 0) {\n urls << url().toString();\n index = urls.count() - 1;\n }\n\n QVariantMap data;\n data.insert(QString(\"links\"), QVariant(urls));\n data.insert(QString(\"index\"), QVariant(index));\n sendAsyncMessage(\"embedui:addhistory\", QVariant(data));\n}\n\nbool DeclarativeWebPage::domContentLoaded() const\n{\n return m_domContentLoaded;\n}\n\nbool DeclarativeWebPage::initialLoadHasHappened() const\n{\n return m_initialLoadHasHappened;\n}\n\nvoid DeclarativeWebPage::setInitialLoadHasHappened()\n{\n m_initialLoadHasHappened = true;\n}\n\nQVariant DeclarativeWebPage::resurrectedContentRect() const\n{\n return m_resurrectedContentRect;\n}\n\nvoid DeclarativeWebPage::setResurrectedContentRect(QVariant resurrectedContentRect)\n{\n if (m_resurrectedContentRect != resurrectedContentRect) {\n m_resurrectedContentRect = resurrectedContentRect;\n emit resurrectedContentRectChanged();\n }\n}\n\nvoid DeclarativeWebPage::loadTab(QString newUrl, bool force)\n{\n \/\/ Always enable chrome when load is called.\n setChrome(true);\n QString oldUrl = url().toString();\n if ((!newUrl.isEmpty() && oldUrl != newUrl) || force) {\n m_domContentLoaded = false;\n emit domContentLoadedChanged();\n load(newUrl);\n }\n}\n\nvoid DeclarativeWebPage::grabToFile(const QSize &size)\n{\n emit clearGrabResult();\n \/\/ grabToImage handles invalid geometry.\n m_grabResult = grabToImage(size);\n if (m_grabResult) {\n if (!m_grabResult->isReady()) {\n connect(m_grabResult.data(), SIGNAL(ready()), this, SLOT(grabResultReady()));\n } else {\n grabResultReady();\n }\n }\n}\n\n\nvoid DeclarativeWebPage::grabThumbnail(const QSize &size)\n{\n m_thumbnailResult = grabToImage(size);\n if (m_thumbnailResult) {\n connect(m_thumbnailResult.data(), SIGNAL(ready()), this, SLOT(thumbnailReady()));\n }\n}\n\n\/**\n * Use this to lock to chrome mode. This disables the gesture\n * that normally enables fullscreen mode. The chromeGestureEnabled property\n * is bound to this so that contentHeight changes do not re-enable the\n * gesture.\n *\n * When gesture is allowed to be used again, unlock call by forceChrome(false).\n *\n * Used for instance when find-in-page view is active that is part of\n * the new browser user interface.\n *\/\nvoid DeclarativeWebPage::forceChrome(bool forcedChrome)\n{\n \/\/ This way we don't break chromeGestureEnabled and chrome bindings.\n setChromeGestureEnabled(!forcedChrome);\n if (forcedChrome) {\n setChrome(forcedChrome);\n }\n \/\/ Without chrome respect content height.\n resetHeight(!forcedChrome);\n if (m_forcedChrome != forcedChrome) {\n m_forcedChrome = forcedChrome;\n emit forcedChromeChanged();\n }\n}\n\nvoid DeclarativeWebPage::resetHeight(bool respectContentHeight)\n{\n \/\/ Input panel is fully open.\n if (m_container->imOpened()) {\n return;\n }\n\n \/\/ fullscreen() below in the fullscreen request coming from the web content.\n if (respectContentHeight && (!m_forcedChrome || fullscreen())) {\n \/\/ Handle webPage height over here, BrowserPage.qml loading\n \/\/ reset might be redundant as we have also loaded trigger\n \/\/ reset. However, I'd leave it there for safety reasons.\n \/\/ We need to reset height always back to short height when loading starts\n \/\/ so that after tab change there is always initial short composited height.\n \/\/ Height may expand when content is moved.\n if (contentHeight() > (m_fullScreenHeight + m_toolbarHeight) || fullscreen()) {\n setHeight(m_fullScreenHeight);\n } else {\n setHeight(m_fullScreenHeight - m_toolbarHeight);\n }\n } else {\n setHeight(m_fullScreenHeight - m_toolbarHeight);\n }\n}\n\nvoid DeclarativeWebPage::grabResultReady()\n{\n QImage image = m_grabResult->image();\n m_grabResult.clear();\n m_grabWritter.setFuture(QtConcurrent::run(this, &DeclarativeWebPage::saveToFile, image));\n}\n\nvoid DeclarativeWebPage::grabWritten()\n{\n QString path = m_grabWritter.result();\n emit grabResult(path);\n}\n\nvoid DeclarativeWebPage::thumbnailReady()\n{\n QImage image = m_thumbnailResult->image();\n m_thumbnailResult.clear();\n QByteArray iconData;\n QBuffer buffer(&iconData);\n buffer.open(QIODevice::WriteOnly);\n if (image.save(&buffer, \"jpg\", 75)) {\n buffer.close();\n emit thumbnailResult(QString(BASE64_IMAGE).arg(QString(iconData.toBase64())));\n } else {\n emit thumbnailResult(DEFAULT_DESKTOP_BOOKMARK_ICON);\n }\n}\n\nQString DeclarativeWebPage::saveToFile(QImage image)\n{\n if (image.isNull()) {\n return \"\";\n }\n\n \/\/ 75% quality jpg produces small and good enough capture.\n QString path = QString(\"%1\/tab-%2-thumb.jpg\").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).arg(tabId());\n return !allBlack(image) && image.save(path, \"jpg\", 75) ? path : \"\";\n}\n\nvoid DeclarativeWebPage::onRecvAsyncMessage(const QString& message, const QVariant& data)\n{\n if (message == gFullScreenMessage) {\n setFullscreen(data.toMap().value(QString(\"fullscreen\")).toBool());\n } else if (message == gDomContentLoadedMessage && data.toMap().value(\"rootFrame\").toBool()) {\n m_domContentLoaded = true;\n emit domContentLoadedChanged();\n }\n}\n\nbool DeclarativeWebPage::fullscreen() const\n{\n return m_fullscreen;\n}\n\nbool DeclarativeWebPage::forcedChrome() const\n{\n return m_forcedChrome;\n}\n\nvoid DeclarativeWebPage::setFullscreen(const bool fullscreen)\n{\n if (m_fullscreen != fullscreen) {\n m_fullscreen = fullscreen;\n resetHeight();\n emit fullscreenChanged();\n }\n}\n\nQDebug operator<<(QDebug dbg, const DeclarativeWebPage *page)\n{\n if (!page) {\n return dbg << \"DeclarativeWebPage (this = 0x0)\";\n }\n\n dbg.nospace() << \"DeclarativeWebPage(url = \" << page->url() << \", title = \" << page->title() << \", width = \" << page->width()\n << \", height = \" << page->height() << \", completed = \" << page->completed()\n << \", active = \" << page->active() << \", enabled = \" << page->enabled() << \")\";\n return dbg.space();\n}\n[history] Use actual current URL when modifying session history.\/****************************************************************************\n**\n** Copyright (C) 2014 Jolla Ltd.\n** Contact: Raine Makelainen \n**\n****************************************************************************\/\n\n\/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this file,\n * You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n\n#include \"declarativewebpage.h\"\n#include \"declarativewebcontainer.h\"\n#include \"dbmanager.h\"\n\n#include \n#include \n\nstatic const QString gFullScreenMessage(\"embed:fullscreenchanged\");\nstatic const QString gDomContentLoadedMessage(\"embed:domcontentloaded\");\n\nstatic const QString gLinkAddedMessage(\"chrome:linkadded\");\nstatic const QString gAlertMessage(\"embed:alert\");\nstatic const QString gConfirmMessage(\"embed:confirm\");\nstatic const QString gPromptMessage(\"embed:prompt\");\nstatic const QString gAuthMessage(\"embed:auth\");\nstatic const QString gLoginMessage(\"embed:login\");\nstatic const QString gFindMessage(\"embed:find\");\nstatic const QString gPermissionsMessage(\"embed:permissions\");\nstatic const QString gContextMenuMessage(\"Content:ContextMenu\");\nstatic const QString gSelectionRangeMessage(\"Content:SelectionRange\");\nstatic const QString gSelectionCopiedMessage(\"Content:SelectionCopied\");\nstatic const QString gSelectAsyncMessage(\"embed:selectasync\");\nstatic const QString gFilePickerMessage(\"embed:filepicker\");\n\nbool isBlack(QRgb rgb)\n{\n return qRed(rgb) == 0 && qGreen(rgb) == 0 && qBlue(rgb) == 0;\n}\n\nbool allBlack(const QImage &image)\n{\n int h = image.height();\n int w = image.width();\n\n for (int j = 0; j < h; ++j) {\n const QRgb *b = (const QRgb *)image.constScanLine(j);\n for (int i = 0; i < w; ++i) {\n if (!isBlack(b[i]))\n return false;\n }\n }\n return true;\n}\n\nDeclarativeWebPage::DeclarativeWebPage(QObject *parent)\n : QOpenGLWebPage(parent)\n , m_container(0)\n , m_userHasDraggedWhileLoading(false)\n , m_fullscreen(false)\n , m_forcedChrome(false)\n , m_domContentLoaded(false)\n , m_initialLoadHasHappened(false)\n , m_tabHistoryReady(false)\n , m_urlReady(false)\n{\n addMessageListener(gFullScreenMessage);\n addMessageListener(gDomContentLoadedMessage);\n\n addMessageListener(gLinkAddedMessage);\n addMessageListener(gAlertMessage);\n addMessageListener(gConfirmMessage);\n addMessageListener(gPromptMessage);\n addMessageListener(gAuthMessage);\n addMessageListener(gLoginMessage);\n addMessageListener(gFindMessage);\n addMessageListener(gPermissionsMessage);\n addMessageListener(gContextMenuMessage);\n addMessageListener(gSelectionRangeMessage);\n addMessageListener(gSelectionCopiedMessage);\n addMessageListener(gSelectAsyncMessage);\n addMessageListener(gFilePickerMessage);\n\n loadFrameScript(\"chrome:\/\/embedlite\/content\/SelectAsyncHelper.js\");\n loadFrameScript(\"chrome:\/\/embedlite\/content\/embedhelper.js\");\n\n connect(this, SIGNAL(recvAsyncMessage(const QString, const QVariant)),\n this, SLOT(onRecvAsyncMessage(const QString&, const QVariant&)));\n connect(&m_grabWritter, SIGNAL(finished()), this, SLOT(grabWritten()));\n connect(this, SIGNAL(contentHeightChanged()), this, SLOT(resetHeight()));\n connect(this, SIGNAL(scrollableOffsetChanged()), this, SLOT(resetHeight()));\n connect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));\n}\n\nDeclarativeWebPage::~DeclarativeWebPage()\n{\n m_grabWritter.cancel();\n m_grabWritter.waitForFinished();\n m_grabResult.clear();\n m_thumbnailResult.clear();\n}\n\nDeclarativeWebContainer *DeclarativeWebPage::container() const\n{\n return m_container;\n}\n\nvoid DeclarativeWebPage::setContainer(DeclarativeWebContainer *container)\n{\n if (m_container != container) {\n m_container = container;\n emit containerChanged();\n }\n}\n\nint DeclarativeWebPage::tabId() const\n{\n return m_initialTab.tabId();\n}\n\nvoid DeclarativeWebPage::setInitialTab(const Tab& tab)\n{\n Q_ASSERT(m_initialTab.tabId() == 0);\n\n m_initialTab = tab;\n emit tabIdChanged();\n connect(DBManager::instance(), SIGNAL(tabHistoryAvailable(int, QList)),\n this, SLOT(onTabHistoryAvailable(int, QList)));\n DBManager::instance()->getTabHistory(tabId());\n}\n\nvoid DeclarativeWebPage::onUrlChanged()\n{\n disconnect(this, SIGNAL(urlChanged()), this, SLOT(onUrlChanged()));\n m_urlReady = true;\n restoreHistory();\n}\n\nvoid DeclarativeWebPage::onTabHistoryAvailable(const int& historyTabId, const QList& links)\n{\n if (historyTabId == tabId()) {\n m_restoredTabHistory = links;\n\n std::reverse(m_restoredTabHistory.begin(), m_restoredTabHistory.end());\n DBManager::instance()->disconnect(this);\n m_tabHistoryReady = true;\n restoreHistory();\n }\n}\n\nvoid DeclarativeWebPage::restoreHistory() {\n if (!m_urlReady || !m_tabHistoryReady || m_restoredTabHistory.count() == 0) {\n return;\n }\n\n QList urls;\n int index(-1);\n int i(0);\n foreach (Link link, m_restoredTabHistory) {\n urls << link.url();\n if (link.linkId() == m_initialTab.currentLink()) {\n index = i;\n QString currentUrl(url().toString());\n if (link.url() != currentUrl) {\n \/\/ The browser was started with an initial URL as a cmdline parameter -> reset tab history\n urls << currentUrl;\n index++;\n DBManager::instance()->navigateTo(tabId(), currentUrl, \"\", \"\");\n break;\n }\n }\n i++;\n }\n\n if (index < 0) {\n urls << url().toString();\n index = urls.count() - 1;\n }\n\n QVariantMap data;\n data.insert(QString(\"links\"), QVariant(urls));\n data.insert(QString(\"index\"), QVariant(index));\n sendAsyncMessage(\"embedui:addhistory\", QVariant(data));\n}\n\nbool DeclarativeWebPage::domContentLoaded() const\n{\n return m_domContentLoaded;\n}\n\nbool DeclarativeWebPage::initialLoadHasHappened() const\n{\n return m_initialLoadHasHappened;\n}\n\nvoid DeclarativeWebPage::setInitialLoadHasHappened()\n{\n m_initialLoadHasHappened = true;\n}\n\nQVariant DeclarativeWebPage::resurrectedContentRect() const\n{\n return m_resurrectedContentRect;\n}\n\nvoid DeclarativeWebPage::setResurrectedContentRect(QVariant resurrectedContentRect)\n{\n if (m_resurrectedContentRect != resurrectedContentRect) {\n m_resurrectedContentRect = resurrectedContentRect;\n emit resurrectedContentRectChanged();\n }\n}\n\nvoid DeclarativeWebPage::loadTab(QString newUrl, bool force)\n{\n \/\/ Always enable chrome when load is called.\n setChrome(true);\n QString oldUrl = url().toString();\n if ((!newUrl.isEmpty() && oldUrl != newUrl) || force) {\n m_domContentLoaded = false;\n emit domContentLoadedChanged();\n load(newUrl);\n }\n}\n\nvoid DeclarativeWebPage::grabToFile(const QSize &size)\n{\n emit clearGrabResult();\n \/\/ grabToImage handles invalid geometry.\n m_grabResult = grabToImage(size);\n if (m_grabResult) {\n if (!m_grabResult->isReady()) {\n connect(m_grabResult.data(), SIGNAL(ready()), this, SLOT(grabResultReady()));\n } else {\n grabResultReady();\n }\n }\n}\n\n\nvoid DeclarativeWebPage::grabThumbnail(const QSize &size)\n{\n m_thumbnailResult = grabToImage(size);\n if (m_thumbnailResult) {\n connect(m_thumbnailResult.data(), SIGNAL(ready()), this, SLOT(thumbnailReady()));\n }\n}\n\n\/**\n * Use this to lock to chrome mode. This disables the gesture\n * that normally enables fullscreen mode. The chromeGestureEnabled property\n * is bound to this so that contentHeight changes do not re-enable the\n * gesture.\n *\n * When gesture is allowed to be used again, unlock call by forceChrome(false).\n *\n * Used for instance when find-in-page view is active that is part of\n * the new browser user interface.\n *\/\nvoid DeclarativeWebPage::forceChrome(bool forcedChrome)\n{\n \/\/ This way we don't break chromeGestureEnabled and chrome bindings.\n setChromeGestureEnabled(!forcedChrome);\n if (forcedChrome) {\n setChrome(forcedChrome);\n }\n \/\/ Without chrome respect content height.\n resetHeight(!forcedChrome);\n if (m_forcedChrome != forcedChrome) {\n m_forcedChrome = forcedChrome;\n emit forcedChromeChanged();\n }\n}\n\nvoid DeclarativeWebPage::resetHeight(bool respectContentHeight)\n{\n \/\/ Input panel is fully open.\n if (m_container->imOpened()) {\n return;\n }\n\n \/\/ fullscreen() below in the fullscreen request coming from the web content.\n if (respectContentHeight && (!m_forcedChrome || fullscreen())) {\n \/\/ Handle webPage height over here, BrowserPage.qml loading\n \/\/ reset might be redundant as we have also loaded trigger\n \/\/ reset. However, I'd leave it there for safety reasons.\n \/\/ We need to reset height always back to short height when loading starts\n \/\/ so that after tab change there is always initial short composited height.\n \/\/ Height may expand when content is moved.\n if (contentHeight() > (m_fullScreenHeight + m_toolbarHeight) || fullscreen()) {\n setHeight(m_fullScreenHeight);\n } else {\n setHeight(m_fullScreenHeight - m_toolbarHeight);\n }\n } else {\n setHeight(m_fullScreenHeight - m_toolbarHeight);\n }\n}\n\nvoid DeclarativeWebPage::grabResultReady()\n{\n QImage image = m_grabResult->image();\n m_grabResult.clear();\n m_grabWritter.setFuture(QtConcurrent::run(this, &DeclarativeWebPage::saveToFile, image));\n}\n\nvoid DeclarativeWebPage::grabWritten()\n{\n QString path = m_grabWritter.result();\n emit grabResult(path);\n}\n\nvoid DeclarativeWebPage::thumbnailReady()\n{\n QImage image = m_thumbnailResult->image();\n m_thumbnailResult.clear();\n QByteArray iconData;\n QBuffer buffer(&iconData);\n buffer.open(QIODevice::WriteOnly);\n if (image.save(&buffer, \"jpg\", 75)) {\n buffer.close();\n emit thumbnailResult(QString(BASE64_IMAGE).arg(QString(iconData.toBase64())));\n } else {\n emit thumbnailResult(DEFAULT_DESKTOP_BOOKMARK_ICON);\n }\n}\n\nQString DeclarativeWebPage::saveToFile(QImage image)\n{\n if (image.isNull()) {\n return \"\";\n }\n\n \/\/ 75% quality jpg produces small and good enough capture.\n QString path = QString(\"%1\/tab-%2-thumb.jpg\").arg(QStandardPaths::writableLocation(QStandardPaths::CacheLocation)).arg(tabId());\n return !allBlack(image) && image.save(path, \"jpg\", 75) ? path : \"\";\n}\n\nvoid DeclarativeWebPage::onRecvAsyncMessage(const QString& message, const QVariant& data)\n{\n if (message == gFullScreenMessage) {\n setFullscreen(data.toMap().value(QString(\"fullscreen\")).toBool());\n } else if (message == gDomContentLoadedMessage && data.toMap().value(\"rootFrame\").toBool()) {\n m_domContentLoaded = true;\n emit domContentLoadedChanged();\n }\n}\n\nbool DeclarativeWebPage::fullscreen() const\n{\n return m_fullscreen;\n}\n\nbool DeclarativeWebPage::forcedChrome() const\n{\n return m_forcedChrome;\n}\n\nvoid DeclarativeWebPage::setFullscreen(const bool fullscreen)\n{\n if (m_fullscreen != fullscreen) {\n m_fullscreen = fullscreen;\n resetHeight();\n emit fullscreenChanged();\n }\n}\n\nQDebug operator<<(QDebug dbg, const DeclarativeWebPage *page)\n{\n if (!page) {\n return dbg << \"DeclarativeWebPage (this = 0x0)\";\n }\n\n dbg.nospace() << \"DeclarativeWebPage(url = \" << page->url() << \", title = \" << page->title() << \", width = \" << page->width()\n << \", height = \" << page->height() << \", completed = \" << page->completed()\n << \", active = \" << page->active() << \", enabled = \" << page->enabled() << \")\";\n return dbg.space();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * Copyright 2016 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_UTIL_INTERPROCESS_MUTEX\n#define REALM_UTIL_INTERPROCESS_MUTEX\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Enable this only on platforms where it might be needed\n#if REALM_PLATFORM_APPLE || REALM_ANDROID\n#define REALM_ROBUST_MUTEX_EMULATION\n#endif\n\nnamespace realm {\nnamespace util {\n\n\/\/ fwd decl to support friend decl below\nclass InterprocessCondVar;\n\n\n\/\/\/ Emulation of a Robust Mutex.\n\/\/\/ A Robust Mutex is an interprocess mutex which will automatically\n\/\/\/ release any locks held by a process when it crashes. Contrary to\n\/\/\/ Posix robust mutexes, this robust mutex is not capable of informing\n\/\/\/ participants that they have been granted a lock after a crash of\n\/\/\/ the process holding it (though it could be added if needed).\n\nclass InterprocessMutex {\npublic:\n InterprocessMutex();\n ~InterprocessMutex() noexcept;\n\n \/\/ Disable copying. Copying a locked Mutex will create a scenario\n \/\/ where the same file descriptor will be locked once but unlocked twice.\n InterprocessMutex(const InterprocessMutex&) = delete;\n InterprocessMutex& operator=(const InterprocessMutex&) = delete;\n\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n struct SharedPart {\n };\n#else\n using SharedPart = RobustMutex;\n#endif\n\n \/\/\/ You need to bind the emulation to a SharedPart in shared\/mmapped memory.\n \/\/\/ The SharedPart is assumed to have been initialized (possibly by another process)\n \/\/\/ elsewhere.\n void set_shared_part(SharedPart& shared_part, const std::string& path, const std::string& mutex_name);\n void set_shared_part(SharedPart& shared_part, File&& lock_file);\n\n \/\/\/ Destroy shared object. Potentially release system resources. Caller must\n \/\/\/ ensure that the shared_part is not in use at the point of call.\n void release_shared_part();\n\n \/\/\/ Lock the mutex. If the mutex is already locked, wait for it to be unlocked.\n void lock();\n\n \/\/\/ Unlock the mutex\n void unlock();\n\n \/\/\/ Attempt to check if the mutex is valid (only relevant if not emulating)\n bool is_valid() noexcept;\n\n static bool is_robust_on_this_platform()\n {\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n return true; \/\/ we're faking it!\n#else\n return RobustMutex::is_robust_on_this_platform();\n#endif\n }\n\nprivate:\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n struct LockInfo {\n File m_file;\n Mutex m_local_mutex;\n LockInfo() {}\n ~LockInfo() noexcept;\n \/\/ Disable copying.\n LockInfo(const LockInfo&) = delete;\n LockInfo& operator=(const LockInfo&) = delete;\n };\n \/\/\/ InterprocessMutex created on the same file (same inode on POSIX) share the same LockInfo.\n \/\/\/ LockInfo will be saved in a static map as a weak ptr and use the UniqueID as the key.\n \/\/\/ Operations on the map need to be protected by s_mutex\n static std::map>* s_info_map;\n static Mutex* s_mutex;\n \/\/\/ We manually initialize these static variables when first needed,\n \/\/\/ creating them on the heap so that they last for the entire lifetime\n \/\/\/ of the process. The destructor of these is never called; the\n \/\/\/ process will clean up their memory when exiting. It is not enough\n \/\/\/ to count instances of InterprocessMutex and clean up these statics when\n \/\/\/ the count reaches zero because the program can create more\n \/\/\/ InterprocessMutex instances before the process ends, so we really need\n \/\/\/ these variables for the entire lifetime of the process.\n static std::once_flag s_init_flag;\n static void initialize_statics();\n\n \/\/\/ Only used for release_shared_part\n std::string m_filename;\n File::UniqueID m_fileuid;\n std::shared_ptr m_lock_info;\n\n \/\/\/ Free the lock info hold by this instance.\n \/\/\/ If it is the last reference, underly resources will be freed as well.\n void free_lock_info();\n#else\n SharedPart* m_shared_part = nullptr;\n#endif\n friend class InterprocessCondVar;\n};\n\ninline InterprocessMutex::InterprocessMutex()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n std::call_once(s_init_flag, initialize_statics);\n#endif\n}\n\ninline InterprocessMutex::~InterprocessMutex() noexcept\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n free_lock_info();\n#endif\n}\n\n#ifdef REALM_ROBUST_MUTEX_EMULATION\ninline InterprocessMutex::LockInfo::~LockInfo() noexcept\n{\n if (m_file.is_attached()) {\n m_file.close();\n }\n}\n\ninline void InterprocessMutex::free_lock_info()\n{\n \/\/ It has not been initiated yet.\n if (!m_lock_info)\n return;\n\n std::lock_guard guard(*s_mutex);\n\n m_lock_info.reset();\n if ((*s_info_map)[m_fileuid].expired()) {\n s_info_map->erase(m_fileuid);\n }\n m_filename.clear();\n}\n\ninline void InterprocessMutex::initialize_statics()\n{\n s_mutex = new Mutex();\n s_info_map = new std::map>();\n}\n#endif\n\ninline void InterprocessMutex::set_shared_part(SharedPart& shared_part, const std::string& path,\n const std::string& mutex_name)\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n static_cast(shared_part);\n\n free_lock_info();\n\n m_filename = path + \".\" + mutex_name + \".mx\";\n\n std::lock_guard guard(*s_mutex);\n\n \/\/ Try to get the file uid if the file exists\n if (File::get_unique_id(m_filename, m_fileuid)) {\n auto result = s_info_map->find(m_fileuid);\n if (result != s_info_map->end()) {\n \/\/ File exists and the lock info has been created in the map.\n m_lock_info = result->second.lock();\n return;\n }\n }\n\n \/\/ LockInfo has not been created yet.\n m_lock_info = std::make_shared();\n \/\/ Always use mod_Write to open file and retreive the uid in case other process\n \/\/ deletes the file.\n m_lock_info->m_file.open(m_filename, File::mode_Write);\n m_fileuid = m_lock_info->m_file.get_unique_id();\n\n (*s_info_map)[m_fileuid] = m_lock_info;\n#else\n m_shared_part = &shared_part;\n static_cast(path);\n static_cast(mutex_name);\n#endif\n}\n\ninline void InterprocessMutex::set_shared_part(SharedPart& shared_part, File&& lock_file)\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n static_cast(shared_part);\n\n free_lock_info();\n\n std::lock_guard guard(*s_mutex);\n\n m_fileuid = lock_file.get_unique_id();\n auto result = s_info_map->find(m_fileuid);\n if (result == s_info_map->end()) {\n m_lock_info = std::make_shared();\n m_lock_info->m_file = std::move(lock_file);\n (*s_info_map)[m_fileuid] = m_lock_info;\n }\n else {\n \/\/ File exists and the lock info has been created in the map.\n m_lock_info = result->second.lock();\n lock_file.close();\n }\n#else\n m_shared_part = &shared_part;\n static_cast(lock_file);\n#endif\n}\n\ninline void InterprocessMutex::release_shared_part()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n if (!m_filename.empty())\n File::try_remove(m_filename);\n\n free_lock_info();\n#else\n m_shared_part = nullptr;\n#endif\n}\n\ninline void InterprocessMutex::lock()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n std::unique_lock mutex_lock(m_lock_info->m_local_mutex);\n m_lock_info->m_file.lock_exclusive();\n mutex_lock.release();\n#else\n REALM_ASSERT(m_shared_part);\n m_shared_part->lock([]() {});\n#endif\n}\n\n\ninline void InterprocessMutex::unlock()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n m_lock_info->m_file.unlock();\n m_lock_info->m_local_mutex.unlock();\n#else\n REALM_ASSERT(m_shared_part);\n m_shared_part->unlock();\n#endif\n}\n\n\ninline bool InterprocessMutex::is_valid() noexcept\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n return true;\n#else\n REALM_ASSERT(m_shared_part);\n return m_shared_part->is_valid();\n#endif\n}\n\n\n} \/\/ namespace util\n} \/\/ namespace realm\n\n#endif \/\/ #ifndef REALM_UTIL_INTERPROCESS_MUTEX\nSpelling error in comment.\/*************************************************************************\n *\n * Copyright 2016 Realm Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n **************************************************************************\/\n\n#ifndef REALM_UTIL_INTERPROCESS_MUTEX\n#define REALM_UTIL_INTERPROCESS_MUTEX\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Enable this only on platforms where it might be needed\n#if REALM_PLATFORM_APPLE || REALM_ANDROID\n#define REALM_ROBUST_MUTEX_EMULATION\n#endif\n\nnamespace realm {\nnamespace util {\n\n\/\/ fwd decl to support friend decl below\nclass InterprocessCondVar;\n\n\n\/\/\/ Emulation of a Robust Mutex.\n\/\/\/ A Robust Mutex is an interprocess mutex which will automatically\n\/\/\/ release any locks held by a process when it crashes. Contrary to\n\/\/\/ Posix robust mutexes, this robust mutex is not capable of informing\n\/\/\/ participants that they have been granted a lock after a crash of\n\/\/\/ the process holding it (though it could be added if needed).\n\nclass InterprocessMutex {\npublic:\n InterprocessMutex();\n ~InterprocessMutex() noexcept;\n\n \/\/ Disable copying. Copying a locked Mutex will create a scenario\n \/\/ where the same file descriptor will be locked once but unlocked twice.\n InterprocessMutex(const InterprocessMutex&) = delete;\n InterprocessMutex& operator=(const InterprocessMutex&) = delete;\n\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n struct SharedPart {\n };\n#else\n using SharedPart = RobustMutex;\n#endif\n\n \/\/\/ You need to bind the emulation to a SharedPart in shared\/mmapped memory.\n \/\/\/ The SharedPart is assumed to have been initialized (possibly by another process)\n \/\/\/ elsewhere.\n void set_shared_part(SharedPart& shared_part, const std::string& path, const std::string& mutex_name);\n void set_shared_part(SharedPart& shared_part, File&& lock_file);\n\n \/\/\/ Destroy shared object. Potentially release system resources. Caller must\n \/\/\/ ensure that the shared_part is not in use at the point of call.\n void release_shared_part();\n\n \/\/\/ Lock the mutex. If the mutex is already locked, wait for it to be unlocked.\n void lock();\n\n \/\/\/ Unlock the mutex\n void unlock();\n\n \/\/\/ Attempt to check if the mutex is valid (only relevant if not emulating)\n bool is_valid() noexcept;\n\n static bool is_robust_on_this_platform()\n {\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n return true; \/\/ we're faking it!\n#else\n return RobustMutex::is_robust_on_this_platform();\n#endif\n }\n\nprivate:\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n struct LockInfo {\n File m_file;\n Mutex m_local_mutex;\n LockInfo() {}\n ~LockInfo() noexcept;\n \/\/ Disable copying.\n LockInfo(const LockInfo&) = delete;\n LockInfo& operator=(const LockInfo&) = delete;\n };\n \/\/\/ InterprocessMutex created on the same file (same inode on POSIX) share the same LockInfo.\n \/\/\/ LockInfo will be saved in a static map as a weak ptr and use the UniqueID as the key.\n \/\/\/ Operations on the map need to be protected by s_mutex\n static std::map>* s_info_map;\n static Mutex* s_mutex;\n \/\/\/ We manually initialize these static variables when first needed,\n \/\/\/ creating them on the heap so that they last for the entire lifetime\n \/\/\/ of the process. The destructor of these is never called; the\n \/\/\/ process will clean up their memory when exiting. It is not enough\n \/\/\/ to count instances of InterprocessMutex and clean up these statics when\n \/\/\/ the count reaches zero because the program can create more\n \/\/\/ InterprocessMutex instances before the process ends, so we really need\n \/\/\/ these variables for the entire lifetime of the process.\n static std::once_flag s_init_flag;\n static void initialize_statics();\n\n \/\/\/ Only used for release_shared_part\n std::string m_filename;\n File::UniqueID m_fileuid;\n std::shared_ptr m_lock_info;\n\n \/\/\/ Free the lock info hold by this instance.\n \/\/\/ If it is the last reference, underly resources will be freed as well.\n void free_lock_info();\n#else\n SharedPart* m_shared_part = nullptr;\n#endif\n friend class InterprocessCondVar;\n};\n\ninline InterprocessMutex::InterprocessMutex()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n std::call_once(s_init_flag, initialize_statics);\n#endif\n}\n\ninline InterprocessMutex::~InterprocessMutex() noexcept\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n free_lock_info();\n#endif\n}\n\n#ifdef REALM_ROBUST_MUTEX_EMULATION\ninline InterprocessMutex::LockInfo::~LockInfo() noexcept\n{\n if (m_file.is_attached()) {\n m_file.close();\n }\n}\n\ninline void InterprocessMutex::free_lock_info()\n{\n \/\/ It has not been initialized yet.\n if (!m_lock_info)\n return;\n\n std::lock_guard guard(*s_mutex);\n\n m_lock_info.reset();\n if ((*s_info_map)[m_fileuid].expired()) {\n s_info_map->erase(m_fileuid);\n }\n m_filename.clear();\n}\n\ninline void InterprocessMutex::initialize_statics()\n{\n s_mutex = new Mutex();\n s_info_map = new std::map>();\n}\n#endif\n\ninline void InterprocessMutex::set_shared_part(SharedPart& shared_part, const std::string& path,\n const std::string& mutex_name)\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n static_cast(shared_part);\n\n free_lock_info();\n\n m_filename = path + \".\" + mutex_name + \".mx\";\n\n std::lock_guard guard(*s_mutex);\n\n \/\/ Try to get the file uid if the file exists\n if (File::get_unique_id(m_filename, m_fileuid)) {\n auto result = s_info_map->find(m_fileuid);\n if (result != s_info_map->end()) {\n \/\/ File exists and the lock info has been created in the map.\n m_lock_info = result->second.lock();\n return;\n }\n }\n\n \/\/ LockInfo has not been created yet.\n m_lock_info = std::make_shared();\n \/\/ Always use mod_Write to open file and retreive the uid in case other process\n \/\/ deletes the file.\n m_lock_info->m_file.open(m_filename, File::mode_Write);\n m_fileuid = m_lock_info->m_file.get_unique_id();\n\n (*s_info_map)[m_fileuid] = m_lock_info;\n#else\n m_shared_part = &shared_part;\n static_cast(path);\n static_cast(mutex_name);\n#endif\n}\n\ninline void InterprocessMutex::set_shared_part(SharedPart& shared_part, File&& lock_file)\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n static_cast(shared_part);\n\n free_lock_info();\n\n std::lock_guard guard(*s_mutex);\n\n m_fileuid = lock_file.get_unique_id();\n auto result = s_info_map->find(m_fileuid);\n if (result == s_info_map->end()) {\n m_lock_info = std::make_shared();\n m_lock_info->m_file = std::move(lock_file);\n (*s_info_map)[m_fileuid] = m_lock_info;\n }\n else {\n \/\/ File exists and the lock info has been created in the map.\n m_lock_info = result->second.lock();\n lock_file.close();\n }\n#else\n m_shared_part = &shared_part;\n static_cast(lock_file);\n#endif\n}\n\ninline void InterprocessMutex::release_shared_part()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n if (!m_filename.empty())\n File::try_remove(m_filename);\n\n free_lock_info();\n#else\n m_shared_part = nullptr;\n#endif\n}\n\ninline void InterprocessMutex::lock()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n std::unique_lock mutex_lock(m_lock_info->m_local_mutex);\n m_lock_info->m_file.lock_exclusive();\n mutex_lock.release();\n#else\n REALM_ASSERT(m_shared_part);\n m_shared_part->lock([]() {});\n#endif\n}\n\n\ninline void InterprocessMutex::unlock()\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n m_lock_info->m_file.unlock();\n m_lock_info->m_local_mutex.unlock();\n#else\n REALM_ASSERT(m_shared_part);\n m_shared_part->unlock();\n#endif\n}\n\n\ninline bool InterprocessMutex::is_valid() noexcept\n{\n#ifdef REALM_ROBUST_MUTEX_EMULATION\n return true;\n#else\n REALM_ASSERT(m_shared_part);\n return m_shared_part->is_valid();\n#endif\n}\n\n\n} \/\/ namespace util\n} \/\/ namespace realm\n\n#endif \/\/ #ifndef REALM_UTIL_INTERPROCESS_MUTEX\n<|endoftext|>"} {"text":"#include \n#include \"utList.h\"\n\nint main( int argc , char **argv )\n{\n testing :: InitGoogleTest( &argc , argv ) ;\n return RUN_ALL_TESTS( ) ;\n}\nDelete mainStructure.cpp<|endoftext|>"} {"text":"\/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"AdaptiveLayerHeights.h\"\r\n\r\nnamespace cura\r\n{\r\n\r\nAdaptiveLayer::AdaptiveLayer(int layer_height)\r\n{\r\n this->layer_height = layer_height;\r\n}\r\n\r\nAdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)\r\n{\r\n \/\/ store the required parameters\r\n this->mesh = mesh;\r\n this->layer_height = layer_thickness;\r\n this->initial_layer_height = initial_layer_thickness;\r\n this->max_variation = static_cast(variation);\r\n this->step_size = static_cast(step_size);\r\n this->threshold = threshold;\r\n\r\n \/\/ calculate the allowed layer heights from variation and step size\r\n \/\/ note: the order is from thickest to thinnest height!\r\n for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)\r\n {\r\n this->allowed_layer_heights.push_back(allowed_layer_height);\r\n }\r\n\r\n this->calculateMeshTriangleSlopes();\r\n this->calculateLayers();\r\n}\r\n\r\nint AdaptiveLayerHeights::getLayerCount()\r\n{\r\n return this->layers.size();\r\n}\r\n\r\nstd::vector* AdaptiveLayerHeights::getLayers()\r\n{\r\n return &this->layers;\r\n}\r\n\r\nvoid AdaptiveLayerHeights::calculateLayers()\r\n{\r\n const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());\r\n SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance(\"slicing_tolerance\");\r\n std::vector triangles_of_interest;\r\n int z_level = 0;\r\n int previous_layer_height = 0;\r\n\r\n \/\/ the first layer has it's own independent height set, so we always add that\r\n z_level += this->initial_layer_height;\r\n\r\n \/\/ compensate first layer thickness depending on slicing mode\r\n if (slicing_tolerance == SlicingTolerance::MIDDLE)\r\n {\r\n z_level += this->initial_layer_height \/ 2;\r\n this->initial_layer_height += this->initial_layer_height \/ 2;\r\n }\r\n\r\n auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);\r\n adaptive_layer->z_position = z_level;\r\n previous_layer_height = adaptive_layer->layer_height;\r\n this->layers.push_back(*adaptive_layer);\r\n\r\n \/\/ loop while triangles are found\r\n while (!triangles_of_interest.empty() || this->layers.size() < 2)\r\n {\r\n \/\/ loop over all allowed layer heights starting with the largest\r\n for (auto & layer_height : this->allowed_layer_heights)\r\n {\r\n int lower_bound = z_level;\r\n int upper_bound = z_level + layer_height;\r\n\r\n std::vector min_bounds;\r\n std::vector max_bounds;\r\n\r\n \/\/ calculate all intersecting lower bounds\r\n for (auto it_lower = this->face_min_z_values.begin(); it_lower != this->face_min_z_values.end(); ++it_lower)\r\n {\r\n if (*it_lower <= upper_bound)\r\n {\r\n min_bounds.emplace_back(std::distance(this->face_min_z_values.begin(), it_lower));\r\n }\r\n }\r\n\r\n \/\/ calculate all intersecting upper bounds\r\n for (auto it_upper = this->face_max_z_values.begin(); it_upper != this->face_max_z_values.end(); ++it_upper)\r\n {\r\n if (*it_upper >= lower_bound)\r\n {\r\n max_bounds.emplace_back(std::distance(this->face_max_z_values.begin(), it_upper));\r\n }\r\n }\r\n\r\n \/\/ use lower and upper bounds to filter on triangles that are interesting for this potential layer\r\n triangles_of_interest.clear();\r\n std::set_intersection(min_bounds.begin(), min_bounds.end(), max_bounds.begin(), max_bounds.end(), std::back_inserter(triangles_of_interest));\r\n\r\n \/\/ when there not interesting triangles in this potential layer go to the next one\r\n if (triangles_of_interest.empty())\r\n {\r\n break;\r\n }\r\n\r\n std::vector slopes;\r\n\r\n \/\/ find all slopes for interesting triangles\r\n for (auto & triangle_index : triangles_of_interest)\r\n {\r\n double slope = this->face_slopes.at(triangle_index);\r\n slopes.push_back(slope);\r\n }\r\n\r\n double minimum_slope = *std::min_element(slopes.begin(), slopes.end());\r\n double minimum_slope_tan = std::tan(minimum_slope);\r\n\r\n \/\/ check if the maximum step size has been exceeded depending on layer height direction\r\n bool has_exceeded_step_size = false;\r\n if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)\r\n {\r\n has_exceeded_step_size = true;\r\n }\r\n else if (layer_height - previous_layer_height > this->step_size && layer_height > minimum_layer_height)\r\n {\r\n continue;\r\n }\r\n\r\n \/\/ we add the layer in the following cases:\r\n \/\/ 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size\r\n \/\/ 2) the layer height is the smallest it is allowed\r\n \/\/ 3) the layer is a flat surface (we can't divide by 0)\r\n if (minimum_slope_tan == 0.0\r\n || (layer_height \/ minimum_slope_tan) <= this->threshold\r\n || layer_height == minimum_layer_height\r\n || has_exceeded_step_size)\r\n {\r\n z_level += layer_height;\r\n auto * adaptive_layer = new AdaptiveLayer(layer_height);\r\n adaptive_layer->z_position = z_level;\r\n previous_layer_height = adaptive_layer->layer_height;\r\n this->layers.push_back(*adaptive_layer);\r\n break;\r\n }\r\n }\r\n\r\n \/\/ stop calculating when we're out of triangles (e.g. above the mesh)\r\n if (triangles_of_interest.empty())\r\n {\r\n break;\r\n }\r\n }\r\n}\r\n\r\nvoid AdaptiveLayerHeights::calculateMeshTriangleSlopes()\r\n{\r\n \/\/ loop over all mesh faces (triangles) and find their slopes\r\n for (const auto &face : this->mesh->faces)\r\n {\r\n const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];\r\n const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];\r\n const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];\r\n\r\n FPoint3 p0 = v0.p;\r\n FPoint3 p1 = v1.p;\r\n FPoint3 p2 = v2.p;\r\n\r\n float minZ = p0.z;\r\n float maxZ = p0.z;\r\n\r\n if (p1.z < minZ) minZ = p1.z;\r\n if (p2.z < minZ) minZ = p2.z;\r\n if (p1.z > maxZ) maxZ = p1.z;\r\n if (p2.z > maxZ) maxZ = p2.z;\r\n\r\n \/\/ calculate the angle of this triangle in the z direction\r\n FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);\r\n FPoint3 normal = n.normalized();\r\n double z_angle = std::acos(std::abs(normal.z));\r\n\r\n \/\/ prevent flat surfaces from influencing the algorithm\r\n if (z_angle == 0)\r\n {\r\n z_angle = M_PI;\r\n }\r\n\r\n this->face_min_z_values.push_back(minZ * 1000);\r\n this->face_max_z_values.push_back(maxZ * 1000);\r\n this->face_slopes.push_back(z_angle);\r\n }\r\n}\r\n\r\n}Make search for interesting triangles more efficient.\/** Copyright (C) 2017 Ultimaker - Released under terms of the AGPLv3 License *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \"AdaptiveLayerHeights.h\"\r\n\r\nnamespace cura\r\n{\r\n\r\nAdaptiveLayer::AdaptiveLayer(int layer_height)\r\n{\r\n this->layer_height = layer_height;\r\n}\r\n\r\nAdaptiveLayerHeights::AdaptiveLayerHeights(Mesh* mesh, int layer_thickness, int initial_layer_thickness, coord_t variation, coord_t step_size, double threshold)\r\n{\r\n \/\/ store the required parameters\r\n this->mesh = mesh;\r\n this->layer_height = layer_thickness;\r\n this->initial_layer_height = initial_layer_thickness;\r\n this->max_variation = static_cast(variation);\r\n this->step_size = static_cast(step_size);\r\n this->threshold = threshold;\r\n\r\n \/\/ calculate the allowed layer heights from variation and step size\r\n \/\/ note: the order is from thickest to thinnest height!\r\n for (int allowed_layer_height = this->layer_height + this->max_variation; allowed_layer_height >= this->layer_height - this->max_variation; allowed_layer_height -= this->step_size)\r\n {\r\n this->allowed_layer_heights.push_back(allowed_layer_height);\r\n }\r\n\r\n this->calculateMeshTriangleSlopes();\r\n this->calculateLayers();\r\n}\r\n\r\nint AdaptiveLayerHeights::getLayerCount()\r\n{\r\n return this->layers.size();\r\n}\r\n\r\nstd::vector* AdaptiveLayerHeights::getLayers()\r\n{\r\n return &this->layers;\r\n}\r\n\r\nvoid AdaptiveLayerHeights::calculateLayers()\r\n{\r\n const int minimum_layer_height = *std::min_element(this->allowed_layer_heights.begin(), this->allowed_layer_heights.end());\r\n SlicingTolerance slicing_tolerance = this->mesh->getSettingAsSlicingTolerance(\"slicing_tolerance\");\r\n std::vector triangles_of_interest;\r\n int z_level = 0;\r\n int previous_layer_height = 0;\r\n\r\n \/\/ the first layer has it's own independent height set, so we always add that\r\n z_level += this->initial_layer_height;\r\n\r\n \/\/ compensate first layer thickness depending on slicing mode\r\n if (slicing_tolerance == SlicingTolerance::MIDDLE)\r\n {\r\n z_level += this->initial_layer_height \/ 2;\r\n this->initial_layer_height += this->initial_layer_height \/ 2;\r\n }\r\n\r\n auto * adaptive_layer = new AdaptiveLayer(this->initial_layer_height);\r\n adaptive_layer->z_position = z_level;\r\n previous_layer_height = adaptive_layer->layer_height;\r\n this->layers.push_back(*adaptive_layer);\r\n\r\n \/\/ loop while triangles are found\r\n while (!triangles_of_interest.empty() || this->layers.size() < 2)\r\n {\r\n \/\/ loop over all allowed layer heights starting with the largest\r\n for (auto & layer_height : this->allowed_layer_heights)\r\n {\r\n \/\/ use lower and upper bounds to filter on triangles that are interesting for this potential layer\r\n const int lower_bound = z_level;\r\n const int upper_bound = z_level + layer_height;\r\n\r\n triangles_of_interest.clear();\r\n\r\n for (unsigned int i = 0; i < this->face_min_z_values.size(); ++i)\r\n {\r\n if (this->face_min_z_values[i] <= upper_bound && this->face_max_z_values[i] >= lower_bound)\r\n {\r\n triangles_of_interest.push_back(i);\r\n }\r\n }\r\n\r\n \/\/ when there not interesting triangles in this potential layer go to the next one\r\n if (triangles_of_interest.empty())\r\n {\r\n break;\r\n }\r\n\r\n std::vector slopes;\r\n\r\n \/\/ find all slopes for interesting triangles\r\n for (auto & triangle_index : triangles_of_interest)\r\n {\r\n double slope = this->face_slopes.at(triangle_index);\r\n slopes.push_back(slope);\r\n }\r\n\r\n double minimum_slope = *std::min_element(slopes.begin(), slopes.end());\r\n double minimum_slope_tan = std::tan(minimum_slope);\r\n\r\n \/\/ check if the maximum step size has been exceeded depending on layer height direction\r\n bool has_exceeded_step_size = false;\r\n if (previous_layer_height > layer_height && previous_layer_height - layer_height > this->step_size)\r\n {\r\n has_exceeded_step_size = true;\r\n }\r\n else if (layer_height - previous_layer_height > this->step_size && layer_height > minimum_layer_height)\r\n {\r\n continue;\r\n }\r\n\r\n \/\/ we add the layer in the following cases:\r\n \/\/ 1) the layer angle is below the threshold and the layer height difference with the previous layer is the maximum allowed step size\r\n \/\/ 2) the layer height is the smallest it is allowed\r\n \/\/ 3) the layer is a flat surface (we can't divide by 0)\r\n if (minimum_slope_tan == 0.0\r\n || (layer_height \/ minimum_slope_tan) <= this->threshold\r\n || layer_height == minimum_layer_height\r\n || has_exceeded_step_size)\r\n {\r\n z_level += layer_height;\r\n auto * adaptive_layer = new AdaptiveLayer(layer_height);\r\n adaptive_layer->z_position = z_level;\r\n previous_layer_height = adaptive_layer->layer_height;\r\n this->layers.push_back(*adaptive_layer);\r\n break;\r\n }\r\n }\r\n\r\n \/\/ stop calculating when we're out of triangles (e.g. above the mesh)\r\n if (triangles_of_interest.empty())\r\n {\r\n break;\r\n }\r\n }\r\n}\r\n\r\nvoid AdaptiveLayerHeights::calculateMeshTriangleSlopes()\r\n{\r\n \/\/ loop over all mesh faces (triangles) and find their slopes\r\n for (const auto &face : this->mesh->faces)\r\n {\r\n const MeshVertex& v0 = this->mesh->vertices[face.vertex_index[0]];\r\n const MeshVertex& v1 = this->mesh->vertices[face.vertex_index[1]];\r\n const MeshVertex& v2 = this->mesh->vertices[face.vertex_index[2]];\r\n\r\n FPoint3 p0 = v0.p;\r\n FPoint3 p1 = v1.p;\r\n FPoint3 p2 = v2.p;\r\n\r\n float minZ = p0.z;\r\n float maxZ = p0.z;\r\n\r\n if (p1.z < minZ) minZ = p1.z;\r\n if (p2.z < minZ) minZ = p2.z;\r\n if (p1.z > maxZ) maxZ = p1.z;\r\n if (p2.z > maxZ) maxZ = p2.z;\r\n\r\n \/\/ calculate the angle of this triangle in the z direction\r\n FPoint3 n = FPoint3(p1 - p0).cross(p2 - p0);\r\n FPoint3 normal = n.normalized();\r\n double z_angle = std::acos(std::abs(normal.z));\r\n\r\n \/\/ prevent flat surfaces from influencing the algorithm\r\n if (z_angle == 0)\r\n {\r\n z_angle = M_PI;\r\n }\r\n\r\n this->face_min_z_values.push_back(minZ * 1000);\r\n this->face_max_z_values.push_back(maxZ * 1000);\r\n this->face_slopes.push_back(z_angle);\r\n }\r\n}\r\n\r\n}<|endoftext|>"} {"text":"#include \n\nOpenGLTextureRenderer::OpenGLTextureRenderer() : Base(anax::ComponentFilter().requires()) {\n\n}\n\nOpenGLTextureRenderer::~OpenGLTextureRenderer() {\n}\n\nvoid OpenGLTextureRenderer::render() {\n\tauto entities = getEntities();\n\tconst float M2P = 30;\n\tint s = entities.size();\n\tfor (auto entity : entities) {\n\t\tauto& texCoordsComp = entity.getComponent();\n\t\tauto& physicsComp = entity.getComponent();\n\t\tauto& image = texCoordsComp.image;\n\n\t\tauto& texCoordsVec = texCoordsComp.textCoords;\n\t\tb2Body* body = physicsComp.physicsBody;\n\n\t\tGLuint texture = 0;\n\t\t{\n\/\/\t\t\tif (!image.loadFromFile(\"1.png\"))\n\/\/\t\t\t\treturn;\n\/\/\t\t\timage.flipVertically();\n\t\t\tglGenTextures(1, &texture);\n\t\t\tglBindTexture(GL_TEXTURE_2D, texture);\n\t\t\tgluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x,\n\t\t\t\t\timage.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE,\n\t\t\t\t\timage.getPixelsPtr());\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,\n\t\t\t\t\tGL_LINEAR_MIPMAP_LINEAR);\n\t\t}\n\n\t\tglBindTexture(GL_TEXTURE_2D, texture);\n\t\tglDisableClientState(GL_NORMAL_ARRAY);\n\t\tglDisableClientState(GL_COLOR_ARRAY);\n\n\t\tb2PolygonShape* shape =\n\t\t\t\t((b2PolygonShape*) body->GetFixtureList()->GetShape());\n\t\tstd::vector points(shape->GetVertexCount());\n\t\tfor (int i = 0; i < shape->GetVertexCount(); i++) {\n\t\t\tpoints[i] = (shape)->GetVertex(i);\n\t\t}\n\n\t\tglPushMatrix();\n\t\tb2Vec2 center = physicsComp.smoothedPosition;\n\t\tfloat angle = body->GetAngle();\n\t\tglTranslatef(static_cast(floor(center.x * M2P)), static_cast(floor(center.y * M2P)), 0.0f);\n\t\tglRotatef(angle * 180.0 \/ M_PI, 0, 0, 1);\n\n\t\tglBegin(GL_POLYGON); \/\/begin drawing of polygon\n\t\tfor (int i = 0; i < shape->GetVertexCount(); i++) {\n\t\t\t\tglTexCoord2d(texCoordsVec[i].x, texCoordsVec[i].y);\n\t\t\tglVertex2f(floor(points[i].x * M2P), floor(points[i].y * M2P));\n\t\t}\n\t\tglEnd(); \/\/end drawing of polygon\n\t\tglPopMatrix();\n\t}\n\n}\nUpdated code to use simple opengl calls for textures#include \n\nOpenGLTextureRenderer::OpenGLTextureRenderer() : Base(anax::ComponentFilter().requires()) {\n\n}\n\nOpenGLTextureRenderer::~OpenGLTextureRenderer() {\n}\n\nvoid OpenGLTextureRenderer::render() {\n\tauto entities = getEntities();\n\tconst float M2P = 30.0f;\n\tfor (auto entity : entities) {\n\t\tauto& texCoordsComp = entity.getComponent();\n\t\tauto& physicsComp = entity.getComponent();\n\t\tauto& image = texCoordsComp.image;\n\n\t\tauto& texCoordsVec = texCoordsComp.textCoords;\n\t\tb2Body* body = physicsComp.physicsBody;\n\n\t\tGLuint texture = 0;\n\t\t{\n\/\/\t\t\tif (!image.loadFromFile(\"1.png\"))\n\/\/\t\t\t\treturn;\n\/\/\t\t\timage.flipVertically();\n\t\t\tglGenTextures(1, &texture);\n\t\t\tglBindTexture(GL_TEXTURE_2D, texture);\n\t\t\tgluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, image.getSize().x,\n\t\t\t\t\timage.getSize().y, GL_RGBA, GL_UNSIGNED_BYTE,\n\t\t\t\t\timage.getPixelsPtr());\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\t\t\tglTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER,\n\t\t\t\t\tGL_LINEAR_MIPMAP_LINEAR);\n\t\t}\n\n\t\tglBindTexture(GL_TEXTURE_2D, texture);\n\t\tglDisableClientState(GL_NORMAL_ARRAY);\n\t\tglDisableClientState(GL_COLOR_ARRAY);\n\n\t\tb2PolygonShape* shape =\n\t\t\t\t((b2PolygonShape*) body->GetFixtureList()->GetShape());\n\t\tstd::vector points(shape->GetVertexCount());\n\t\tfor (int i = 0; i < shape->GetVertexCount(); i++) {\n\t\t\tpoints[i] = (shape)->GetVertex(i);\n\t\t}\n\n\t\tglPushMatrix();\n\/\/\t\tb2Vec2 center = physicsComp.smoothedPosition;\n\t\tb2Vec2 center = physicsComp.physicsBody->GetPosition();\n\n\t\tfloat angle = body->GetAngle();\n\t\tglTranslatef(static_cast(floor(center.x * M2P)), static_cast(floor(center.y * M2P)), 0.0f);\n\t\tglRotatef(angle * 180.0 \/ M_PI, 0, 0, 1);\n\n\t\tglBegin(GL_POLYGON); \/\/begin drawing of polygon\n\t\tfor (int i = 0; i < shape->GetVertexCount(); i++) {\n\t\t\t\tglTexCoord2d(texCoordsVec[i].x, texCoordsVec[i].y);\n\t\t\tglVertex2f(floor(points[i].x * M2P), floor(points[i].y * M2P));\n\t\t}\n\t\tglEnd(); \/\/end drawing of polygon\n\t\tglPopMatrix();\n\t}\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"..\/global.hpp\"\n\nusing namespace blackhole;\n\nTEST(elasticsearch_t, Class) {\n using blackhole::sink::elasticsearch_t;\n elasticsearch_t sink;\n UNUSED(sink);\n}\n\nTEST(elasticsearch_t, Manual) {\n using blackhole::sink::elasticsearch_t;\n elasticsearch_t sink;\n std::string msg = \"{}\";\n boost::algorithm::replace_all(msg, \"'\", \"\\\"\");\n for (int i = 0; i < 200; ++i) {\n sink.consume(msg);\n }\n}\n\nusing namespace elasticsearch;\n\nnamespace mock {\n\nclass logger_t {\npublic:\n template\n log::record_t open_record(Args&&...) const {\n return log::record_t();\n }\n\n void push(log::record_t&&) const {}\n};\n\nclass response_t {\n};\n\nclass action_t {\npublic:\n typedef response_t response_type;\n typedef result_t::type result_type;\n\n static const request::method_t method_value = request::method_t::get;\n\n static const char* name() {\n return \"mock.action\";\n }\n\n std::string path() const {\n return \"\/\";\n }\n};\n\nclass connection_t {\npublic:\n typedef boost::asio::ip::tcp protocol_type;\n typedef protocol_type::endpoint endpoint_type;\n\n template\n connection_t(Args&&...) {}\n\n MOCK_CONST_METHOD0(endpoint, endpoint_type());\n\n MOCK_METHOD3(perform, void(\n actions::nodes_info_t,\n callback::type,\n long\n ));\n\n MOCK_METHOD3(perform, void(\n action_t,\n callback::type,\n long\n ));\n};\n\nclass pool_t {\npublic:\n typedef connection_t connection_type;\n typedef connection_type::endpoint_type endpoint_type;\n typedef std::unordered_map<\n endpoint_type,\n std::shared_ptr\n > pool_type;\n typedef pool_type::size_type size_type;\n typedef pool_type::iterator iterator;\n\n typedef std::mutex mutex_type;\n typedef pool_lock_t pool_lock_type;\n\n mutable std::mutex mutex;\n\n typedef std::pair pair_type;\n MOCK_METHOD2(insert, pair_type(\n const endpoint_type&,\n const std::shared_ptr&\n ));\n MOCK_METHOD1(remove, void(const endpoint_type&));\n\n \/\/!@note: These methods are pure stubs, they shouldn't be called ever.\n MOCK_CONST_METHOD1(size, size_type(pool_lock_type&));\n MOCK_CONST_METHOD1(empty, bool(pool_lock_type&));\n MOCK_METHOD1(begin, iterator(pool_lock_type&));\n MOCK_METHOD1(end, iterator(pool_lock_type&));\n};\n\nclass balancer : public balancing::strategy {\npublic:\n typedef pool_t pool_type;\n typedef pool_type::connection_type connection_type;\n\n MOCK_METHOD1(next, std::shared_ptr(pool_type& pool));\n};\n\n} \/\/ namespace mock\n\nnamespace elasticsearch {\n\ntemplate<>\nstruct extractor_t {\n static mock::response_t extract(const rapidjson::Value&) {\n return mock::response_t();\n }\n};\n\n} \/\/ namespace elasticsearch\n\nclass transport_t_SuccessfullyHandleMessage_Test;\n\nnamespace inspector {\n\n\/\/!@note: Helper class to easy ancestor's mock fields inspection.\ntemplate\nclass http_transport_t : public elasticsearch::http_transport_t {\n friend class ::transport_t_SuccessfullyHandleMessage_Test;\n\npublic:\n template\n http_transport_t(Args&&... args) :\n elasticsearch::http_transport_t(std::forward(args)...)\n {}\n};\n\n} \/\/ namespace inspector\n\ntemplate\nstruct event_t {\n std::atomic& counter;\n\n void operator()(typename Action::result_type) {\n counter++;\n }\n};\n\nvoid post(boost::asio::io_service& loop,\n callback::type callback,\n result_t::type result) {\n loop.post(std::bind(callback, result));\n}\n\nnamespace stub {\n\nsynchronized log(logger_factory_t::create());\n\n} \/\/ namespace stub\n\nTEST(transport_t, SuccessfullyHandleMessage) {\n boost::asio::io_service loop;\n\n std::unique_ptr balancer(new mock::balancer);\n std::shared_ptr connection(new mock::connection_t);\n\n settings_t settings;\n inspector::http_transport_t<\n mock::connection_t,\n mock::pool_t\n > transport(settings, loop, stub::log);\n\n EXPECT_CALL(*balancer, next(_))\n .Times(1)\n .WillOnce(Return(connection));\n EXPECT_CALL(*connection, endpoint())\n .WillOnce(Return(mock::connection_t::endpoint_type()));\n EXPECT_CALL(*connection, perform(An(), _, _))\n .Times(1)\n .WillOnce(\n WithArg<1>(\n Invoke(\n std::bind(\n &post,\n std::ref(loop),\n std::placeholders::_1,\n mock::response_t()\n )\n )\n )\n );\n\n transport.balancer = std::move(balancer);\n\n std::atomic counter(0);\n transport.perform(mock::action_t(), event_t { counter });\n loop.run_one();\n\n EXPECT_EQ(1, counter);\n}\n[Unit Testing] Added test that checks code sequence after some generic elasticsearch error occurs.#include \n#include \n\n#include \"..\/global.hpp\"\n\nusing namespace blackhole;\n\nTEST(elasticsearch_t, Class) {\n using blackhole::sink::elasticsearch_t;\n elasticsearch_t sink;\n UNUSED(sink);\n}\n\nTEST(elasticsearch_t, Manual) {\n using blackhole::sink::elasticsearch_t;\n elasticsearch_t sink;\n std::string msg = \"{}\";\n boost::algorithm::replace_all(msg, \"'\", \"\\\"\");\n for (int i = 0; i < 200; ++i) {\n sink.consume(msg);\n }\n}\n\nusing namespace elasticsearch;\n\nnamespace mock {\n\nclass logger_t {\npublic:\n template\n log::record_t open_record(Args&&...) const {\n return log::record_t();\n }\n\n void push(log::record_t&&) const {}\n};\n\nclass response_t {\n};\n\nclass action_t {\npublic:\n typedef response_t response_type;\n typedef result_t::type result_type;\n\n static const request::method_t method_value = request::method_t::get;\n\n static const char* name() {\n return \"mock.action\";\n }\n\n std::string path() const {\n return \"\/\";\n }\n};\n\nclass connection_t {\npublic:\n typedef boost::asio::ip::tcp protocol_type;\n typedef protocol_type::endpoint endpoint_type;\n\n template\n connection_t(Args&&...) {}\n\n MOCK_CONST_METHOD0(endpoint, endpoint_type());\n\n MOCK_METHOD3(perform, void(\n actions::nodes_info_t,\n callback::type,\n long\n ));\n\n MOCK_METHOD3(perform, void(\n action_t,\n callback::type,\n long\n ));\n};\n\nclass pool_t {\npublic:\n typedef connection_t connection_type;\n typedef connection_type::endpoint_type endpoint_type;\n typedef std::unordered_map<\n endpoint_type,\n std::shared_ptr\n > pool_type;\n typedef pool_type::size_type size_type;\n typedef pool_type::iterator iterator;\n\n typedef std::mutex mutex_type;\n typedef pool_lock_t pool_lock_type;\n\n mutable std::mutex mutex;\n\n typedef std::pair pair_type;\n MOCK_METHOD2(insert, pair_type(\n const endpoint_type&,\n const std::shared_ptr&\n ));\n MOCK_METHOD1(remove, void(const endpoint_type&));\n\n \/\/!@note: These methods are pure stubs, they shouldn't be called ever.\n MOCK_CONST_METHOD1(size, size_type(pool_lock_type&));\n MOCK_CONST_METHOD1(empty, bool(pool_lock_type&));\n MOCK_METHOD1(begin, iterator(pool_lock_type&));\n MOCK_METHOD1(end, iterator(pool_lock_type&));\n};\n\nclass balancer : public balancing::strategy {\npublic:\n typedef pool_t pool_type;\n typedef pool_type::connection_type connection_type;\n\n MOCK_METHOD1(next, std::shared_ptr(pool_type& pool));\n};\n\n} \/\/ namespace mock\n\nnamespace elasticsearch {\n\ntemplate<>\nstruct extractor_t {\n static mock::response_t extract(const rapidjson::Value&) {\n return mock::response_t();\n }\n};\n\n} \/\/ namespace elasticsearch\n\nclass transport_t_SuccessfullyHandleMessage_Test;\nclass transport_t_HandleGenericError_Test;\n\nnamespace inspector {\n\n\/\/!@note: Helper class to easy ancestor's mock fields inspection.\ntemplate\nclass http_transport_t : public elasticsearch::http_transport_t {\n friend class ::transport_t_SuccessfullyHandleMessage_Test;\n friend class ::transport_t_HandleGenericError_Test;\n\npublic:\n template\n http_transport_t(Args&&... args) :\n elasticsearch::http_transport_t(std::forward(args)...)\n {}\n};\n\n} \/\/ namespace inspector\n\ntemplate\nstruct event_t {\n std::atomic& counter;\n\n void operator()(typename Action::result_type) {\n counter++;\n }\n};\n\nvoid post(boost::asio::io_service& loop,\n callback::type callback,\n result_t::type result) {\n loop.post(std::bind(callback, result));\n}\n\nnamespace stub {\n\nsynchronized log(logger_factory_t::create());\n\n} \/\/ namespace stub\n\nTEST(transport_t, SuccessfullyHandleMessage) {\n boost::asio::io_service loop;\n\n std::unique_ptr balancer(new mock::balancer);\n std::shared_ptr connection(new mock::connection_t);\n\n settings_t settings;\n inspector::http_transport_t<\n mock::connection_t,\n mock::pool_t\n > transport(settings, loop, stub::log);\n\n EXPECT_CALL(*balancer, next(_))\n .Times(1)\n .WillOnce(Return(connection));\n EXPECT_CALL(*connection, endpoint())\n .WillOnce(Return(mock::connection_t::endpoint_type()));\n EXPECT_CALL(*connection, perform(An(), _, _))\n .Times(1)\n .WillOnce(\n WithArg<1>(\n Invoke(\n std::bind(\n &post,\n std::ref(loop),\n std::placeholders::_1,\n mock::response_t()\n )\n )\n )\n );\n\n transport.balancer = std::move(balancer);\n\n std::atomic counter(0);\n transport.perform(mock::action_t(), event_t { counter });\n loop.run_one();\n\n EXPECT_EQ(1, counter);\n}\n\nTEST(transport_t, HandleGenericError) {\n \/\/! After receiving the response with some elasticsearch error,\n \/\/! a caller's callback must be called during next event loop tick.\n\n boost::asio::io_service loop;\n\n std::unique_ptr balancer(new mock::balancer);\n std::shared_ptr connection(new mock::connection_t);\n\n settings_t settings;\n inspector::http_transport_t<\n mock::connection_t,\n mock::pool_t\n > transport(settings, loop, stub::log);\n\n EXPECT_CALL(*balancer, next(_))\n .Times(1)\n .WillOnce(Return(connection));\n EXPECT_CALL(*connection, endpoint())\n .WillOnce(Return(mock::connection_t::endpoint_type()));\n EXPECT_CALL(*connection, perform(An(), _, _))\n .Times(1)\n .WillOnce(\n WithArg<1>(\n Invoke(\n std::bind(\n &post,\n std::ref(loop),\n std::placeholders::_1,\n elasticsearch::error_t(generic_error_t(\"mock\"))\n )\n )\n )\n );\n\n transport.balancer = std::move(balancer);\n\n std::atomic counter(0);\n transport.perform(mock::action_t(), event_t { counter });\n loop.run_one();\n\n EXPECT_EQ(1, counter);\n}\n<|endoftext|>"} {"text":"\/*\nQWebSockets implements the WebSocket protocol as defined in RFC 6455.\nCopyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"handshakerequest_p.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"qwebsocketprotocol.h\"\n\nQT_BEGIN_NAMESPACE\n\n\/*!\n \\internal\n *\/\nHandshakeRequest::HandshakeRequest(int port, bool isSecure) :\n m_port(port),\n m_isSecure(isSecure),\n m_isValid(false),\n m_headers(),\n m_versions(),\n m_key(),\n m_origin(),\n m_protocols(),\n m_extensions(),\n m_requestUrl()\n{\n}\n\n\/*!\n \\internal\n *\/\nHandshakeRequest::~HandshakeRequest()\n{\n}\n\n\/*!\n \\internal\n *\/\nvoid HandshakeRequest::clear()\n{\n m_port = -1;\n m_isSecure = false;\n m_isValid = false;\n m_headers.clear();\n m_versions.clear();\n m_key.clear();\n m_origin.clear();\n m_protocols.clear();\n m_extensions.clear();\n m_requestUrl.clear();\n}\n\n\/*!\n \\internal\n *\/\nint HandshakeRequest::getPort() const\n{\n return m_requestUrl.port(m_port);\n}\n\n\/*!\n \\internal\n *\/\nbool HandshakeRequest::isSecure() const\n{\n return m_isSecure;\n}\n\n\/*!\n \\internal\n *\/\nbool HandshakeRequest::isValid() const\n{\n return m_isValid;\n}\n\n\/*!\n \\internal\n *\/\nQMap HandshakeRequest::getHeaders() const\n{\n return m_headers;\n}\n\n\/*!\n \\internal\n *\/\nQList HandshakeRequest::getVersions() const\n{\n return m_versions;\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getResourceName() const\n{\n return m_requestUrl.path();\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getKey() const\n{\n return m_key;\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getHost() const\n{\n return m_requestUrl.host();\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getOrigin() const\n{\n return m_origin;\n}\n\n\/*!\n \\internal\n *\/\nQList HandshakeRequest::getProtocols() const\n{\n return m_protocols;\n}\n\n\/*!\n \\internal\n *\/\nQList HandshakeRequest::getExtensions() const\n{\n return m_extensions;\n}\n\n\/*!\n \\internal\n *\/\nQUrl HandshakeRequest::getRequestUrl() const\n{\n return m_requestUrl;\n}\n\n\/*!\n \\internal\n *\/\nQTextStream &HandshakeRequest::readFromStream(QTextStream &textStream)\n{\n m_isValid = false;\n clear();\n if (textStream.status() == QTextStream::Ok)\n {\n QString requestLine = textStream.readLine();\n QStringList tokens = requestLine.split(' ', QString::SkipEmptyParts);\n QString verb = tokens[0];\n QString resourceName = tokens[1];\n QString httpProtocol = tokens[2];\n bool conversionOk = false;\n float httpVersion = httpProtocol.midRef(5).toFloat(&conversionOk);\n\n QString headerLine = textStream.readLine();\n m_headers.clear();\n while (!headerLine.isEmpty())\n {\n QStringList headerField = headerLine.split(QString(\": \"), QString::SkipEmptyParts);\n m_headers.insertMulti(headerField[0], headerField[1]);\n headerLine = textStream.readLine();\n }\n\n QString host = m_headers.value(\"Host\", \"\");\n m_requestUrl = QUrl::fromEncoded(resourceName.toLatin1());\n if (m_requestUrl.isRelative())\n {\n m_requestUrl.setHost(host);\n }\n if (m_requestUrl.scheme().isEmpty())\n {\n QString scheme = isSecure() ? \"wss:\/\/\" : \"ws:\/\/\";\n m_requestUrl.setScheme(scheme);\n }\n\n QStringList versionLines = m_headers.values(\"Sec-WebSocket-Version\");\n Q_FOREACH(QString versionLine, versionLines)\n {\n QStringList versions = versionLine.split(\",\", QString::SkipEmptyParts);\n Q_FOREACH(QString version, versions)\n {\n QWebSocketProtocol::Version ver = QWebSocketProtocol::versionFromString(version.trimmed());\n m_versions << ver;\n }\n }\n qStableSort(m_versions.begin(), m_versions.end(), qGreater());\t\/\/sort in descending order\n m_key = m_headers.value(\"Sec-WebSocket-Key\", \"\");\n QString upgrade = m_headers.value(\"Upgrade\", \"\"); \/\/must be equal to \"websocket\", case-insensitive\n QString connection = m_headers.value(\"Connection\", \"\");\t\/\/must contain \"Upgrade\", case-insensitive\n QStringList connectionLine = connection.split(\",\", QString::SkipEmptyParts);\n QStringList connectionValues;\n Q_FOREACH(QString connection, connectionLine)\n {\n connectionValues << connection.trimmed();\n }\n\n \/\/optional headers\n m_origin = m_headers.value(\"Sec-WebSocket-Origin\", \"\");\n QStringList protocolLines = m_headers.values(\"Sec-WebSocket-Protocol\");\n Q_FOREACH(QString protocolLine, protocolLines)\n {\n QStringList protocols = protocolLine.split(\",\", QString::SkipEmptyParts);\n Q_FOREACH(QString protocol, protocols)\n {\n m_protocols << protocol.trimmed();\n }\n }\n QStringList extensionLines = m_headers.values(\"Sec-WebSocket-Extensions\");\n Q_FOREACH(QString extensionLine, extensionLines)\n {\n QStringList extensions = extensionLine.split(\",\", QString::SkipEmptyParts);\n Q_FOREACH(QString extension, extensions)\n {\n m_extensions << extension.trimmed();\n }\n }\n \/\/TODO: authentication field\n\n m_isValid = !(host.isEmpty() ||\n resourceName.isEmpty() ||\n m_versions.isEmpty() ||\n m_key.isEmpty() ||\n (verb != \"GET\") ||\n (!conversionOk || (httpVersion < 1.1f)) ||\n (upgrade.toLower() != \"websocket\") ||\n (!connectionValues.contains(\"upgrade\", Qt::CaseInsensitive)));\n }\n return textStream;\n}\n\n\/*!\n \\internal\n *\/\nQTextStream &operator >>(QTextStream &stream, HandshakeRequest &request)\n{\n return request.readFromStream(stream);\n}\n\nQT_END_NAMESPACE\nReplace string literals with QString::fromLatin1() expression, to avoid deprecated warning (since Qt 5.1.1)\/*\nQWebSockets implements the WebSocket protocol as defined in RFC 6455.\nCopyright (C) 2013 Kurt Pattyn (pattyn.kurt@gmail.com)\n\nThis library is free software; you can redistribute it and\/or\nmodify it under the terms of the GNU Lesser General Public\nLicense as published by the Free Software Foundation; either\nversion 2.1 of the License, or (at your option) any later version.\n\nThis library is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\nLesser General Public License for more details.\n\nYou should have received a copy of the GNU Lesser General Public\nLicense along with this library; if not, write to the Free Software\nFoundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \"handshakerequest_p.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"qwebsocketprotocol.h\"\n\nQT_BEGIN_NAMESPACE\n\n\/*!\n \\internal\n *\/\nHandshakeRequest::HandshakeRequest(int port, bool isSecure) :\n m_port(port),\n m_isSecure(isSecure),\n m_isValid(false),\n m_headers(),\n m_versions(),\n m_key(),\n m_origin(),\n m_protocols(),\n m_extensions(),\n m_requestUrl()\n{\n}\n\n\/*!\n \\internal\n *\/\nHandshakeRequest::~HandshakeRequest()\n{\n}\n\n\/*!\n \\internal\n *\/\nvoid HandshakeRequest::clear()\n{\n m_port = -1;\n m_isSecure = false;\n m_isValid = false;\n m_headers.clear();\n m_versions.clear();\n m_key.clear();\n m_origin.clear();\n m_protocols.clear();\n m_extensions.clear();\n m_requestUrl.clear();\n}\n\n\/*!\n \\internal\n *\/\nint HandshakeRequest::getPort() const\n{\n return m_requestUrl.port(m_port);\n}\n\n\/*!\n \\internal\n *\/\nbool HandshakeRequest::isSecure() const\n{\n return m_isSecure;\n}\n\n\/*!\n \\internal\n *\/\nbool HandshakeRequest::isValid() const\n{\n return m_isValid;\n}\n\n\/*!\n \\internal\n *\/\nQMap HandshakeRequest::getHeaders() const\n{\n return m_headers;\n}\n\n\/*!\n \\internal\n *\/\nQList HandshakeRequest::getVersions() const\n{\n return m_versions;\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getResourceName() const\n{\n return m_requestUrl.path();\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getKey() const\n{\n return m_key;\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getHost() const\n{\n return m_requestUrl.host();\n}\n\n\/*!\n \\internal\n *\/\nQString HandshakeRequest::getOrigin() const\n{\n return m_origin;\n}\n\n\/*!\n \\internal\n *\/\nQList HandshakeRequest::getProtocols() const\n{\n return m_protocols;\n}\n\n\/*!\n \\internal\n *\/\nQList HandshakeRequest::getExtensions() const\n{\n return m_extensions;\n}\n\n\/*!\n \\internal\n *\/\nQUrl HandshakeRequest::getRequestUrl() const\n{\n return m_requestUrl;\n}\n\n\/*!\n \\internal\n *\/\nQTextStream &HandshakeRequest::readFromStream(QTextStream &textStream)\n{\n m_isValid = false;\n clear();\n if (textStream.status() == QTextStream::Ok)\n {\n QString requestLine = textStream.readLine();\n QStringList tokens = requestLine.split(' ', QString::SkipEmptyParts);\n QString verb = tokens[0];\n QString resourceName = tokens[1];\n QString httpProtocol = tokens[2];\n bool conversionOk = false;\n float httpVersion = httpProtocol.midRef(5).toFloat(&conversionOk);\n\n QString headerLine = textStream.readLine();\n m_headers.clear();\n while (!headerLine.isEmpty())\n {\n QStringList headerField = headerLine.split(QString::fromLatin1(\": \"), QString::SkipEmptyParts);\n m_headers.insertMulti(headerField[0], headerField[1]);\n headerLine = textStream.readLine();\n }\n\n QString host = m_headers.value(\"Host\", \"\");\n m_requestUrl = QUrl::fromEncoded(resourceName.toLatin1());\n if (m_requestUrl.isRelative())\n {\n m_requestUrl.setHost(host);\n }\n if (m_requestUrl.scheme().isEmpty())\n {\n QString scheme = QString::fromLatin1(isSecure() ? \"wss:\/\/\" : \"ws:\/\/\");\n m_requestUrl.setScheme(scheme);\n }\n\n QStringList versionLines = m_headers.values(\"Sec-WebSocket-Version\");\n Q_FOREACH(QString versionLine, versionLines)\n {\n QStringList versions = versionLine.split(\",\", QString::SkipEmptyParts);\n Q_FOREACH(QString version, versions)\n {\n QWebSocketProtocol::Version ver = QWebSocketProtocol::versionFromString(version.trimmed());\n m_versions << ver;\n }\n }\n qStableSort(m_versions.begin(), m_versions.end(), qGreater());\t\/\/sort in descending order\n m_key = m_headers.value(\"Sec-WebSocket-Key\", \"\");\n QString upgrade = m_headers.value(\"Upgrade\", \"\"); \/\/must be equal to \"websocket\", case-insensitive\n QString connection = m_headers.value(\"Connection\", \"\");\t\/\/must contain \"Upgrade\", case-insensitive\n QStringList connectionLine = connection.split(\",\", QString::SkipEmptyParts);\n QStringList connectionValues;\n Q_FOREACH(QString connection, connectionLine)\n {\n connectionValues << connection.trimmed();\n }\n\n \/\/optional headers\n m_origin = m_headers.value(\"Sec-WebSocket-Origin\", \"\");\n QStringList protocolLines = m_headers.values(\"Sec-WebSocket-Protocol\");\n Q_FOREACH(QString protocolLine, protocolLines)\n {\n QStringList protocols = protocolLine.split(\",\", QString::SkipEmptyParts);\n Q_FOREACH(QString protocol, protocols)\n {\n m_protocols << protocol.trimmed();\n }\n }\n QStringList extensionLines = m_headers.values(\"Sec-WebSocket-Extensions\");\n Q_FOREACH(QString extensionLine, extensionLines)\n {\n QStringList extensions = extensionLine.split(\",\", QString::SkipEmptyParts);\n Q_FOREACH(QString extension, extensions)\n {\n m_extensions << extension.trimmed();\n }\n }\n \/\/TODO: authentication field\n\n m_isValid = !(host.isEmpty() ||\n resourceName.isEmpty() ||\n m_versions.isEmpty() ||\n m_key.isEmpty() ||\n (verb != QString::fromLatin1(\"GET\")) ||\n (!conversionOk || (httpVersion < 1.1f)) ||\n (upgrade.toLower() != QString::fromLatin1(\"websocket\")) ||\n (!connectionValues.contains(\"upgrade\", Qt::CaseInsensitive)));\n }\n return textStream;\n}\n\n\/*!\n \\internal\n *\/\nQTextStream &operator >>(QTextStream &stream, HandshakeRequest &request)\n{\n return request.readFromStream(stream);\n}\n\nQT_END_NAMESPACE\n<|endoftext|>"} {"text":"\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2015 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/main.h\"\n#include \"xenia\/base\/platform.h\"\n#include \"xenia\/base\/string.h\"\n#include \"xenia\/gpu\/dxbc_shader_translator.h\"\n#include \"xenia\/gpu\/glsl_shader_translator.h\"\n#include \"xenia\/gpu\/shader_translator.h\"\n#include \"xenia\/gpu\/spirv_shader_translator.h\"\n#include \"xenia\/ui\/spirv\/spirv_disassembler.h\"\n\n\/\/ For D3DDisassemble:\n#if XE_PLATFORM_WIN32\n#include \"xenia\/ui\/d3d12\/d3d12_api.h\"\n#endif \/\/ XE_PLATFORM_WIN32\n\nDEFINE_string(shader_input, \"\", \"Input shader binary file path.\");\nDEFINE_string(shader_input_type, \"\",\n \"'vs', 'ps', or unspecified to infer from the given filename.\");\nDEFINE_string(shader_output, \"\", \"Output shader file path.\");\nDEFINE_string(shader_output_type, \"ucode\",\n \"Translator to use: [ucode, glsl45, spirv, spirvtext, dxbc].\");\nDEFINE_string(shader_output_patch, \"\",\n \"Tessellation patch type in the generated tessellation \"\n \"evaluation (domain) shader, or unspecified to produce a vertex \"\n \"shader: [line, triangle, quad].\");\nDEFINE_bool(shader_output_dxbc_rov, false,\n \"Output ROV-based output-merger code in DXBC pixel shaders.\");\n\nnamespace xe {\nnamespace gpu {\n\nint shader_compiler_main(const std::vector& args) {\n ShaderType shader_type;\n if (!FLAGS_shader_input_type.empty()) {\n if (FLAGS_shader_input_type == \"vs\") {\n shader_type = ShaderType::kVertex;\n } else if (FLAGS_shader_input_type == \"ps\") {\n shader_type = ShaderType::kPixel;\n } else {\n XELOGE(\"Invalid --shader_input_type; must be 'vs' or 'ps'.\");\n return 1;\n }\n } else {\n auto last_dot = FLAGS_shader_input.find_last_of('.');\n bool valid_type = false;\n if (last_dot != std::string::npos) {\n if (FLAGS_shader_input.substr(last_dot) == \".vs\") {\n shader_type = ShaderType::kVertex;\n valid_type = true;\n } else if (FLAGS_shader_input.substr(last_dot) == \".ps\") {\n shader_type = ShaderType::kPixel;\n valid_type = true;\n }\n }\n if (!valid_type) {\n XELOGE(\n \"File type not recognized (use .vs, .ps or \"\n \"--shader_input_type=vs|ps).\");\n return 1;\n }\n }\n\n auto input_file = fopen(FLAGS_shader_input.c_str(), \"rb\");\n if (!input_file) {\n XELOGE(\"Unable to open input file: %s\", FLAGS_shader_input.c_str());\n return 1;\n }\n fseek(input_file, 0, SEEK_END);\n size_t input_file_size = ftell(input_file);\n fseek(input_file, 0, SEEK_SET);\n std::vector ucode_dwords(input_file_size \/ 4);\n fread(ucode_dwords.data(), 4, ucode_dwords.size(), input_file);\n fclose(input_file);\n\n XELOGI(\"Opened %s as a %s shader, %\" PRId64 \" words (%\" PRId64 \" bytes).\",\n FLAGS_shader_input.c_str(),\n shader_type == ShaderType::kVertex ? \"vertex\" : \"pixel\",\n ucode_dwords.size(), ucode_dwords.size() * 4);\n\n \/\/ TODO(benvanik): hash? need to return the data to big-endian format first.\n uint64_t ucode_data_hash = 0;\n auto shader = std::make_unique(\n shader_type, ucode_data_hash, ucode_dwords.data(), ucode_dwords.size());\n\n std::unique_ptr translator;\n if (FLAGS_shader_output_type == \"spirv\" ||\n FLAGS_shader_output_type == \"spirvtext\") {\n translator = std::make_unique();\n } else if (FLAGS_shader_output_type == \"glsl45\") {\n translator = std::make_unique(\n GlslShaderTranslator::Dialect::kGL45);\n } else if (FLAGS_shader_output_type == \"dxbc\") {\n translator =\n std::make_unique(0, FLAGS_shader_output_dxbc_rov);\n } else {\n translator = std::make_unique();\n }\n\n PrimitiveType patch_primitive_type = PrimitiveType::kNone;\n if (shader_type == ShaderType::kVertex) {\n if (FLAGS_shader_output_patch == \"line\") {\n patch_primitive_type == PrimitiveType::kLinePatch;\n } else if (FLAGS_shader_output_patch == \"triangle\") {\n patch_primitive_type == PrimitiveType::kTrianglePatch;\n } else if (FLAGS_shader_output_patch == \"quad\") {\n patch_primitive_type == PrimitiveType::kQuadPatch;\n }\n }\n\n translator->Translate(shader.get(), patch_primitive_type);\n\n const void* source_data = shader->translated_binary().data();\n size_t source_data_size = shader->translated_binary().size();\n\n std::unique_ptr spirv_disasm_result;\n if (FLAGS_shader_output_type == \"spirvtext\") {\n \/\/ Disassemble SPIRV.\n spirv_disasm_result = xe::ui::spirv::SpirvDisassembler().Disassemble(\n reinterpret_cast(source_data), source_data_size \/ 4);\n source_data = spirv_disasm_result->text();\n source_data_size = std::strlen(spirv_disasm_result->text()) + 1;\n }\n#if XE_PLATFORM_WIN32\n ID3DBlob* dxbc_disasm_blob = nullptr;\n if (FLAGS_shader_output_type == \"dxbc\") {\n HMODULE d3d_compiler = LoadLibrary(L\"D3DCompiler_47.dll\");\n if (d3d_compiler != nullptr) {\n pD3DDisassemble d3d_disassemble =\n pD3DDisassemble(GetProcAddress(d3d_compiler, \"D3DDisassemble\"));\n if (d3d_disassemble != nullptr) {\n \/\/ Disassemble DXBC.\n if (SUCCEEDED(d3d_disassemble(source_data, source_data_size,\n D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING |\n D3D_DISASM_ENABLE_INSTRUCTION_OFFSET,\n nullptr, &dxbc_disasm_blob))) {\n source_data = dxbc_disasm_blob->GetBufferPointer();\n source_data_size = dxbc_disasm_blob->GetBufferSize();\n }\n }\n FreeLibrary(d3d_compiler);\n }\n }\n#endif \/\/ XE_PLATFORM_WIN32\n\n if (!FLAGS_shader_output.empty()) {\n auto output_file = fopen(FLAGS_shader_output.c_str(), \"wb\");\n fwrite(source_data, 1, source_data_size, output_file);\n fclose(output_file);\n }\n\n#if XE_PLATFORM_WIN32\n if (dxbc_disasm_blob != nullptr) {\n dxbc_disasm_blob->Release();\n }\n#endif \/\/ XE_PLATFORM_WIN32\n\n return 0;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xe\n\nDEFINE_ENTRY_POINT(L\"xenia-gpu-shader-compiler\",\n L\"xenia-gpu-shader-compiler shader.bin\",\n xe::gpu::shader_compiler_main);\n[D3D12] Fix typos in shader_compiler_main\/**\n ******************************************************************************\n * Xenia : Xbox 360 Emulator Research Project *\n ******************************************************************************\n * Copyright 2015 Ben Vanik. All rights reserved. *\n * Released under the BSD license - see LICENSE in the root for more details. *\n ******************************************************************************\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \"xenia\/base\/logging.h\"\n#include \"xenia\/base\/main.h\"\n#include \"xenia\/base\/platform.h\"\n#include \"xenia\/base\/string.h\"\n#include \"xenia\/gpu\/dxbc_shader_translator.h\"\n#include \"xenia\/gpu\/glsl_shader_translator.h\"\n#include \"xenia\/gpu\/shader_translator.h\"\n#include \"xenia\/gpu\/spirv_shader_translator.h\"\n#include \"xenia\/ui\/spirv\/spirv_disassembler.h\"\n\n\/\/ For D3DDisassemble:\n#if XE_PLATFORM_WIN32\n#include \"xenia\/ui\/d3d12\/d3d12_api.h\"\n#endif \/\/ XE_PLATFORM_WIN32\n\nDEFINE_string(shader_input, \"\", \"Input shader binary file path.\");\nDEFINE_string(shader_input_type, \"\",\n \"'vs', 'ps', or unspecified to infer from the given filename.\");\nDEFINE_string(shader_output, \"\", \"Output shader file path.\");\nDEFINE_string(shader_output_type, \"ucode\",\n \"Translator to use: [ucode, glsl45, spirv, spirvtext, dxbc].\");\nDEFINE_string(shader_output_patch, \"\",\n \"Tessellation patch type in the generated tessellation \"\n \"evaluation (domain) shader, or unspecified to produce a vertex \"\n \"shader: [line, triangle, quad].\");\nDEFINE_bool(shader_output_dxbc_rov, false,\n \"Output ROV-based output-merger code in DXBC pixel shaders.\");\n\nnamespace xe {\nnamespace gpu {\n\nint shader_compiler_main(const std::vector& args) {\n ShaderType shader_type;\n if (!FLAGS_shader_input_type.empty()) {\n if (FLAGS_shader_input_type == \"vs\") {\n shader_type = ShaderType::kVertex;\n } else if (FLAGS_shader_input_type == \"ps\") {\n shader_type = ShaderType::kPixel;\n } else {\n XELOGE(\"Invalid --shader_input_type; must be 'vs' or 'ps'.\");\n return 1;\n }\n } else {\n auto last_dot = FLAGS_shader_input.find_last_of('.');\n bool valid_type = false;\n if (last_dot != std::string::npos) {\n if (FLAGS_shader_input.substr(last_dot) == \".vs\") {\n shader_type = ShaderType::kVertex;\n valid_type = true;\n } else if (FLAGS_shader_input.substr(last_dot) == \".ps\") {\n shader_type = ShaderType::kPixel;\n valid_type = true;\n }\n }\n if (!valid_type) {\n XELOGE(\n \"File type not recognized (use .vs, .ps or \"\n \"--shader_input_type=vs|ps).\");\n return 1;\n }\n }\n\n auto input_file = fopen(FLAGS_shader_input.c_str(), \"rb\");\n if (!input_file) {\n XELOGE(\"Unable to open input file: %s\", FLAGS_shader_input.c_str());\n return 1;\n }\n fseek(input_file, 0, SEEK_END);\n size_t input_file_size = ftell(input_file);\n fseek(input_file, 0, SEEK_SET);\n std::vector ucode_dwords(input_file_size \/ 4);\n fread(ucode_dwords.data(), 4, ucode_dwords.size(), input_file);\n fclose(input_file);\n\n XELOGI(\"Opened %s as a %s shader, %\" PRId64 \" words (%\" PRId64 \" bytes).\",\n FLAGS_shader_input.c_str(),\n shader_type == ShaderType::kVertex ? \"vertex\" : \"pixel\",\n ucode_dwords.size(), ucode_dwords.size() * 4);\n\n \/\/ TODO(benvanik): hash? need to return the data to big-endian format first.\n uint64_t ucode_data_hash = 0;\n auto shader = std::make_unique(\n shader_type, ucode_data_hash, ucode_dwords.data(), ucode_dwords.size());\n\n std::unique_ptr translator;\n if (FLAGS_shader_output_type == \"spirv\" ||\n FLAGS_shader_output_type == \"spirvtext\") {\n translator = std::make_unique();\n } else if (FLAGS_shader_output_type == \"glsl45\") {\n translator = std::make_unique(\n GlslShaderTranslator::Dialect::kGL45);\n } else if (FLAGS_shader_output_type == \"dxbc\") {\n translator =\n std::make_unique(0, FLAGS_shader_output_dxbc_rov);\n } else {\n translator = std::make_unique();\n }\n\n PrimitiveType patch_primitive_type = PrimitiveType::kNone;\n if (shader_type == ShaderType::kVertex) {\n if (FLAGS_shader_output_patch == \"line\") {\n patch_primitive_type = PrimitiveType::kLinePatch;\n } else if (FLAGS_shader_output_patch == \"triangle\") {\n patch_primitive_type = PrimitiveType::kTrianglePatch;\n } else if (FLAGS_shader_output_patch == \"quad\") {\n patch_primitive_type = PrimitiveType::kQuadPatch;\n }\n }\n\n translator->Translate(shader.get(), patch_primitive_type);\n\n const void* source_data = shader->translated_binary().data();\n size_t source_data_size = shader->translated_binary().size();\n\n std::unique_ptr spirv_disasm_result;\n if (FLAGS_shader_output_type == \"spirvtext\") {\n \/\/ Disassemble SPIRV.\n spirv_disasm_result = xe::ui::spirv::SpirvDisassembler().Disassemble(\n reinterpret_cast(source_data), source_data_size \/ 4);\n source_data = spirv_disasm_result->text();\n source_data_size = std::strlen(spirv_disasm_result->text()) + 1;\n }\n#if XE_PLATFORM_WIN32\n ID3DBlob* dxbc_disasm_blob = nullptr;\n if (FLAGS_shader_output_type == \"dxbc\") {\n HMODULE d3d_compiler = LoadLibrary(L\"D3DCompiler_47.dll\");\n if (d3d_compiler != nullptr) {\n pD3DDisassemble d3d_disassemble =\n pD3DDisassemble(GetProcAddress(d3d_compiler, \"D3DDisassemble\"));\n if (d3d_disassemble != nullptr) {\n \/\/ Disassemble DXBC.\n if (SUCCEEDED(d3d_disassemble(source_data, source_data_size,\n D3D_DISASM_ENABLE_INSTRUCTION_NUMBERING |\n D3D_DISASM_ENABLE_INSTRUCTION_OFFSET,\n nullptr, &dxbc_disasm_blob))) {\n source_data = dxbc_disasm_blob->GetBufferPointer();\n source_data_size = dxbc_disasm_blob->GetBufferSize();\n }\n }\n FreeLibrary(d3d_compiler);\n }\n }\n#endif \/\/ XE_PLATFORM_WIN32\n\n if (!FLAGS_shader_output.empty()) {\n auto output_file = fopen(FLAGS_shader_output.c_str(), \"wb\");\n fwrite(source_data, 1, source_data_size, output_file);\n fclose(output_file);\n }\n\n#if XE_PLATFORM_WIN32\n if (dxbc_disasm_blob != nullptr) {\n dxbc_disasm_blob->Release();\n }\n#endif \/\/ XE_PLATFORM_WIN32\n\n return 0;\n}\n\n} \/\/ namespace gpu\n} \/\/ namespace xe\n\nDEFINE_ENTRY_POINT(L\"xenia-gpu-shader-compiler\",\n L\"xenia-gpu-shader-compiler shader.bin\",\n xe::gpu::shader_compiler_main);\n<|endoftext|>"} {"text":"coverity#1255389 Dereference null return value<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swstylemanager.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: rt $ $Date: 2006-12-05 16:38:21 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#pragma hdrstop\n\n#include \"swstylemanager.hxx\"\n#include \n#include \n\n#ifndef _DOC_HXX\n#include \n#endif\n\n#ifndef _CHARFMT_HXX\n#include \n#endif\n\n#ifndef _DOCARY_HXX\n#include \n#endif\n\n#ifndef _SWTYPES_HXX\n#include \n#endif\n\n#ifndef _ISTYLEACCESS_HXX\n#include \n#endif\n\ntypedef ::std::hash_map< const ::rtl::OUString,\n StylePool::SfxItemSet_Pointer_t,\n ::rtl::OUStringHash,\n ::std::equal_to< ::rtl::OUString > > SwStyleNameCache;\n\nclass SwStyleCache\n{\n SwStyleNameCache mMap;\npublic:\n SwStyleCache() {}\n void addStyleName( StylePool::SfxItemSet_Pointer_t pStyle )\n { mMap[ StylePool::nameOf(pStyle) ] = pStyle; }\n void addCompletePool( StylePool& rPool );\n StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName ) { return mMap[rName]; }\n};\n\nvoid SwStyleCache::addCompletePool( StylePool& rPool )\n{\n IStylePoolIteratorAccess *pIter = rPool.createIterator();\n StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();\n while( pStyle.get() )\n {\n rtl::OUString aName( StylePool::nameOf(pStyle) );\n mMap[ aName ] = pStyle;\n pStyle = pIter->getNext();\n }\n delete pIter;\n}\n\nclass SwStyleManager : public IStyleAccess\n{\n StylePool aAutoCharPool;\n StylePool aAutoParaPool;\n SwStyleCache *mpCharCache;\n SwStyleCache *mpParaCache;\n\npublic:\n SwStyleManager() : mpCharCache(0), mpParaCache(0) {}\n virtual ~SwStyleManager();\n virtual StylePool::SfxItemSet_Pointer_t getAutomaticStyle( const SfxItemSet& rSet,\n IStyleAccess::SwAutoStyleFamily eFamily );\n virtual StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName,\n IStyleAccess::SwAutoStyleFamily eFamily );\n virtual void getAllStyles( std::vector &rStyles,\n IStyleAccess::SwAutoStyleFamily eFamily );\n virtual StylePool::SfxItemSet_Pointer_t cacheAutomaticStyle( const SfxItemSet& rSet,\n SwAutoStyleFamily eFamily );\n virtual void clearCaches();\n};\n\nIStyleAccess *createStyleManager()\n{\n return new SwStyleManager();\n}\n\nSwStyleManager::~SwStyleManager()\n{\n delete mpCharCache;\n delete mpParaCache;\n}\n\nvoid SwStyleManager::clearCaches()\n{\n delete mpCharCache;\n mpCharCache = 0;\n delete mpParaCache;\n mpParaCache = 0;\n}\n\nStylePool::SfxItemSet_Pointer_t SwStyleManager::getAutomaticStyle( const SfxItemSet& rSet,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n return rAutoPool.insertItemSet( rSet );\n}\n\nStylePool::SfxItemSet_Pointer_t SwStyleManager::cacheAutomaticStyle( const SfxItemSet& rSet,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n StylePool::SfxItemSet_Pointer_t pStyle = rAutoPool.insertItemSet( rSet );\n SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ?\n mpCharCache : mpParaCache;\n if( !rpCache )\n rpCache = new SwStyleCache();\n rpCache->addStyleName( pStyle );\n return pStyle;\n}\n\nStylePool::SfxItemSet_Pointer_t SwStyleManager::getByName( const rtl::OUString& rName,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? mpCharCache : mpParaCache;\n if( !rpCache )\n rpCache = new SwStyleCache();\n StylePool::SfxItemSet_Pointer_t pStyle = rpCache->getByName( rName );\n if( !pStyle.get() )\n {\n \/\/ Ok, ok, it's allowed to ask for uncached styles (from UNO) but it should not be done\n \/\/ during loading a document\n ASSERT( false, \"Don't ask for uncached styles\" );\n rpCache->addCompletePool( rAutoPool );\n pStyle = rpCache->getByName( rName );\n }\n return pStyle;\n}\n\nvoid SwStyleManager::getAllStyles( std::vector &rStyles,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n IStylePoolIteratorAccess *pIter = rAutoPool.createIterator();\n StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();\n while( pStyle.get() )\n {\n \/\/ Do not consider styles which aren't used.\n if ( pStyle.use_count() > 2 )\n rStyles.push_back( pStyle );\n pStyle = pIter->getNext();\n }\n delete pIter;\n}\nINTEGRATION: CWS mingwport06 (1.3.358); FILE MERGED 2007\/08\/24 13:25:59 vg 1.3.358.1: #i75499# pragma is for MSVC\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: swstylemanager.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: kz $ $Date: 2007-09-06 14:00:34 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#ifdef _MSC_VER\n#pragma hdrstop\n#endif\n\n#include \"swstylemanager.hxx\"\n#include \n#include \n\n#ifndef _DOC_HXX\n#include \n#endif\n\n#ifndef _CHARFMT_HXX\n#include \n#endif\n\n#ifndef _DOCARY_HXX\n#include \n#endif\n\n#ifndef _SWTYPES_HXX\n#include \n#endif\n\n#ifndef _ISTYLEACCESS_HXX\n#include \n#endif\n\ntypedef ::std::hash_map< const ::rtl::OUString,\n StylePool::SfxItemSet_Pointer_t,\n ::rtl::OUStringHash,\n ::std::equal_to< ::rtl::OUString > > SwStyleNameCache;\n\nclass SwStyleCache\n{\n SwStyleNameCache mMap;\npublic:\n SwStyleCache() {}\n void addStyleName( StylePool::SfxItemSet_Pointer_t pStyle )\n { mMap[ StylePool::nameOf(pStyle) ] = pStyle; }\n void addCompletePool( StylePool& rPool );\n StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName ) { return mMap[rName]; }\n};\n\nvoid SwStyleCache::addCompletePool( StylePool& rPool )\n{\n IStylePoolIteratorAccess *pIter = rPool.createIterator();\n StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();\n while( pStyle.get() )\n {\n rtl::OUString aName( StylePool::nameOf(pStyle) );\n mMap[ aName ] = pStyle;\n pStyle = pIter->getNext();\n }\n delete pIter;\n}\n\nclass SwStyleManager : public IStyleAccess\n{\n StylePool aAutoCharPool;\n StylePool aAutoParaPool;\n SwStyleCache *mpCharCache;\n SwStyleCache *mpParaCache;\n\npublic:\n SwStyleManager() : mpCharCache(0), mpParaCache(0) {}\n virtual ~SwStyleManager();\n virtual StylePool::SfxItemSet_Pointer_t getAutomaticStyle( const SfxItemSet& rSet,\n IStyleAccess::SwAutoStyleFamily eFamily );\n virtual StylePool::SfxItemSet_Pointer_t getByName( const rtl::OUString& rName,\n IStyleAccess::SwAutoStyleFamily eFamily );\n virtual void getAllStyles( std::vector &rStyles,\n IStyleAccess::SwAutoStyleFamily eFamily );\n virtual StylePool::SfxItemSet_Pointer_t cacheAutomaticStyle( const SfxItemSet& rSet,\n SwAutoStyleFamily eFamily );\n virtual void clearCaches();\n};\n\nIStyleAccess *createStyleManager()\n{\n return new SwStyleManager();\n}\n\nSwStyleManager::~SwStyleManager()\n{\n delete mpCharCache;\n delete mpParaCache;\n}\n\nvoid SwStyleManager::clearCaches()\n{\n delete mpCharCache;\n mpCharCache = 0;\n delete mpParaCache;\n mpParaCache = 0;\n}\n\nStylePool::SfxItemSet_Pointer_t SwStyleManager::getAutomaticStyle( const SfxItemSet& rSet,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n return rAutoPool.insertItemSet( rSet );\n}\n\nStylePool::SfxItemSet_Pointer_t SwStyleManager::cacheAutomaticStyle( const SfxItemSet& rSet,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n StylePool::SfxItemSet_Pointer_t pStyle = rAutoPool.insertItemSet( rSet );\n SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ?\n mpCharCache : mpParaCache;\n if( !rpCache )\n rpCache = new SwStyleCache();\n rpCache->addStyleName( pStyle );\n return pStyle;\n}\n\nStylePool::SfxItemSet_Pointer_t SwStyleManager::getByName( const rtl::OUString& rName,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n SwStyleCache* &rpCache = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? mpCharCache : mpParaCache;\n if( !rpCache )\n rpCache = new SwStyleCache();\n StylePool::SfxItemSet_Pointer_t pStyle = rpCache->getByName( rName );\n if( !pStyle.get() )\n {\n \/\/ Ok, ok, it's allowed to ask for uncached styles (from UNO) but it should not be done\n \/\/ during loading a document\n ASSERT( false, \"Don't ask for uncached styles\" );\n rpCache->addCompletePool( rAutoPool );\n pStyle = rpCache->getByName( rName );\n }\n return pStyle;\n}\n\nvoid SwStyleManager::getAllStyles( std::vector &rStyles,\n IStyleAccess::SwAutoStyleFamily eFamily )\n{\n StylePool& rAutoPool = eFamily == IStyleAccess::AUTO_STYLE_CHAR ? aAutoCharPool : aAutoParaPool;\n IStylePoolIteratorAccess *pIter = rAutoPool.createIterator();\n StylePool::SfxItemSet_Pointer_t pStyle = pIter->getNext();\n while( pStyle.get() )\n {\n \/\/ Do not consider styles which aren't used.\n if ( pStyle.use_count() > 2 )\n rStyles.push_back( pStyle );\n pStyle = pIter->getNext();\n }\n delete pIter;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: staticassert.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 06:05:02 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- *\/\n#ifndef WW_STATICASSERT_HXX\n#define WW_STATICASSERT_HXX\n\n\/*\n Lifted direct from:\n Modern C++ Design: Generic Programming and Design Patterns Applied\n Section 2.1\n by Andrei Alexandrescu\n*\/\nnamespace ww\n{\n template class compile_time_check\n {\n public:\n compile_time_check(...) {}\n };\n\n template<> class compile_time_check\n {\n };\n}\n\n \/*\n Similiar to assert, StaticAssert is only in operation when NDEBUG is not\n defined. It will test its first argument at compile time and on failure\n report the error message of the second argument, which must be a valid c++\n classname. i.e. no spaces, punctuation or reserved keywords.\n *\/\n#ifndef NDEBUG\n# define StaticAssert(test, errormsg) \\\n do { \\\n struct ERROR_##errormsg {}; \\\n typedef ww::compile_time_check< (test) != 0 > tmplimpl; \\\n tmplimpl aTemp = tmplimpl(ERROR_##errormsg()); \\\n sizeof(aTemp); \\\n } while (0)\n#else\n# define StaticAssert(test, errormsg) \\\n do {} while (0)\n#endif\n\n#endif\n\/* vi:set tabstop=4 shiftwidth=4 expandtab: *\/\nINTEGRATION: CWS thaiissues (1.4.888); FILE MERGED\/*************************************************************************\n *\n * $RCSfile: staticassert.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: obo $ $Date: 2005-11-16 09:33:33 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil -*- *\/\n#ifndef WW_STATICASSERT_HXX\n#define WW_STATICASSERT_HXX\n\n\/*\n Lifted direct from:\n Modern C++ Design: Generic Programming and Design Patterns Applied\n Section 2.1\n by Andrei Alexandrescu\n*\/\nnamespace ww\n{\n template class compile_time_check\n {\n public:\n compile_time_check(...) {}\n };\n\n template<> class compile_time_check\n {\n };\n}\n\n \/*\n Similiar to assert, StaticAssert is only in operation when NDEBUG is not\n defined. It will test its first argument at compile time and on failure\n report the error message of the second argument, which must be a valid c++\n classname. i.e. no spaces, punctuation or reserved keywords.\n *\/\n#ifndef NDEBUG\n# define StaticAssert(test, errormsg) \\\n do { \\\n struct ERROR_##errormsg {}; \\\n typedef ww::compile_time_check< (test) != 0 > tmplimpl; \\\n tmplimpl aTemp = tmplimpl(ERROR_##errormsg()); \\\n sizeof(aTemp); \\\n } while (0)\n#else\n# define StaticAssert(test, errormsg) \\\n do {} while (0)\n#endif\n\n#endif\n\/* vi:set tabstop=4 shiftwidth=4 expandtab: *\/\n<|endoftext|>"} {"text":"\/\/ RUN: %clang_cc1 -triple %itanium_abi_triple -verify -fsyntax-only -Wsign-conversion %s\n\n\/\/ NOTE: When a 'enumeral mismatch' warning is implemented then expect several\n\/\/ of the following cases to be impacted.\n\n\/\/ namespace for anonymous enums tests\nnamespace test1 {\n enum { A };\n enum { B = -1 };\n\n template struct Foo {\n enum { C };\n enum { D = ~0U };\n };\n\n enum { E = ~0U };\n\n void doit_anonymous( int i ) {\n int a1 = 1 ? i : A;\n int a2 = 1 ? A : i;\n\n int b1 = 1 ? i : B;\n int b2 = 1 ? B : i;\n\n int c1 = 1 ? i : Foo::C;\n int c2 = 1 ? Foo::C : i;\n\n int d1a = 1 ? i : Foo::D; \/\/ expected-warning {{test1::Foo::(anonymous enum at }}\n int d1b = 1 ? i : Foo::D; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n int d2a = 1 ? Foo::D : i; \/\/ expected-warning {{operand of ? changes signedness: 'test1::Foo::(anonymous enum at }}\n int d2b = 1 ? Foo::D : i; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n int d3a = 1 ? B : Foo::D; \/\/ expected-warning {{operand of ? changes signedness: 'test1::Foo::(anonymous enum at }}\n int d3b = 1 ? B : Foo::D; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n int d4a = 1 ? Foo::D : B; \/\/ expected-warning {{operand of ? changes signedness: 'test1::Foo::(anonymous enum at }}\n int d4b = 1 ? Foo::D : B; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n\n int e1a = 1 ? i : E; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e1b = 1 ? i : E; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n int e2a = 1 ? E : i; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e2b = 1 ? E : i; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n int e3a = 1 ? E : B; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e3b = 1 ? E : B; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n int e4a = 1 ? B : E; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e4b = 1 ? B : E; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n }\n}\n\n\/\/ namespace for named enums tests\nnamespace test2 {\n enum Named1 { A };\n enum Named2 { B = -1 };\n\n template struct Foo {\n enum Named3 { C };\n enum Named4 { D = ~0U };\n };\n\n enum Named5 { E = ~0U };\n\n void doit_anonymous( int i ) {\n int a1 = 1 ? i : A;\n int a2 = 1 ? A : i;\n\n int b1 = 1 ? i : B;\n int b2 = 1 ? B : i;\n\n int c1 = 1 ? i : Foo::C;\n int c2 = 1 ? Foo::C : i;\n\n int d1 = 1 ? i : Foo::D; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n int d2 = 1 ? Foo::D : i; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n int d3 = 1 ? B : Foo::D; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n int d4 = 1 ? Foo::D : B; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n\n int e1 = 1 ? i : E; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n int e2 = 1 ? E : i; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n int e3 = 1 ? E : B; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n int e4 = 1 ? B : E; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n }\n}\n[NFCI] Updated broken test\/\/ RUN: %clang_cc1 -triple %itanium_abi_triple -verify -fsyntax-only -Wsign-conversion %s\n\n\/\/ NOTE: When a 'enumeral mismatch' warning is implemented then expect several\n\/\/ of the following cases to be impacted.\n\n\/\/ namespace for anonymous enums tests\nnamespace test1 {\n enum { A };\n enum { B = -1 };\n\n template struct Foo {\n enum { C };\n enum { D = ~0U };\n };\n\n enum { E = ~0U };\n\n void doit_anonymous( int i ) {\n int a1 = 1 ? i : A;\n int a2 = 1 ? A : i;\n\n int b1 = 1 ? i : B;\n int b2 = 1 ? B : i;\n\n int c1 = 1 ? i : Foo::C;\n int c2 = 1 ? Foo::C : i;\n\n int d1a = 1 ? i : Foo::D; \/\/ expected-warning {{test1::Foo::(anonymous enum at }}\n int d1b = 1 ? i : Foo::D; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n int d2a = 1 ? Foo::D : i; \/\/ expected-warning {{operand of ? changes signedness: 'test1::Foo::(anonymous enum at }}\n int d2b = 1 ? Foo::D : i; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n int d3a = 1 ? B : Foo::D; \/\/ expected-warning {{operand of ? changes signedness: 'test1::Foo::(anonymous enum at }}\n int d3b = 1 ? B : Foo::D; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n int d4a = 1 ? Foo::D : B; \/\/ expected-warning {{operand of ? changes signedness: 'test1::Foo::(anonymous enum at }}\n int d4b = 1 ? Foo::D : B; \/\/ expected-warning {{warn-sign-conversion.cpp:13:5)' to 'int'}}\n\n int e1a = 1 ? i : E; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e1b = 1 ? i : E; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n int e2a = 1 ? E : i; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e2b = 1 ? E : i; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n int e3a = 1 ? E : B; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e3b = 1 ? E : B; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n int e4a = 1 ? B : E; \/\/ expected-warning {{operand of ? changes signedness: 'test1::(anonymous enum at }}\n int e4b = 1 ? B : E; \/\/ expected-warning {{warn-sign-conversion.cpp:16:3)' to 'int'}}\n }\n}\n\n\/\/ namespace for named enums tests\nnamespace test2 {\n enum Named1 { A };\n enum Named2 { B = -1 };\n\n template struct Foo {\n enum Named3 { C };\n enum Named4 { D = ~0U };\n };\n\n enum Named5 { E = ~0U };\n\n void doit_anonymous( int i ) {\n int a1 = 1 ? i : A;\n int a2 = 1 ? A : i;\n\n int b1 = 1 ? i : B;\n int b2 = 1 ? B : i;\n\n int c1 = 1 ? i : Foo::C;\n int c2 = 1 ? Foo::C : i;\n\n int d1 = 1 ? i : Foo::D; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n int d2 = 1 ? Foo::D : i; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n int d3 = 1 ? B : Foo::D; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n \/\/ expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named2' and 'test2::Foo::Named4')}}\n int d4 = 1 ? Foo::D : B; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Foo::Named4' to 'int'}}\n \/\/ expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Foo::Named4' and 'test2::Named2')}}\n\n int e1 = 1 ? i : E; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n int e2 = 1 ? E : i; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n int e3 = 1 ? E : B; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n \/\/ expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named5' and 'test2::Named2')}}\n int e4 = 1 ? B : E; \/\/ expected-warning {{operand of ? changes signedness: 'test2::Named5' to 'int'}}\n \/\/ expected-warning@+1 {{enumeration type mismatch in conditional expression ('test2::Named2' and 'test2::Named5')}}\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#if __cpp_deduction_guides\n#else\n#error \"Class Template Argument Deduction is not supported by the compiler\"\n#endif\n\n\n\ntemplate\nstruct MyPair\n{\n MyPair(const A &, const B &)\n {\n }\n};\n\n\ntemplate\nstruct StaticString\n{\n StaticString(const char (&str)[Size]): c_str(str)\n {\n }\n\n const char *c_str;\n};\n\n\ntemplate\nstruct Container\n{\n struct Iterator\n {\n using value_type = T;\n };\n\n template\n Container( It begin, It end )\n {\n \n }\n};\n\n\n\/\/ Class Template Argument Deduction guide (must be outside the class, in the same namespace).\ntemplate\nContainer(It begin, It end) ->Container;\n\n\n\ntemplate\nstruct MyPerfectPair\n{\n \/\/ perfect forwarding like\n template\n MyPerfectPair(U &&, V &&)\n {\n }\n};\n\n\/**\n * \/\/ CTAD guide, signature does not need to match. \n * \n * Use \"decay by value\" trick. \n * \n * Takes by value to partially simulate decay. See https:\/\/youtu.be\/-H-ut6j1BYU?list=PLHTh1InhhwT6V9RVdFRoCG_Pm5udDxG1c&t=1987\n * \n * CTAD signature does not impact with ctor parameter overload resolution. It will be done as usual, but in the context of type MyPerfectPair.\n *\/\ntemplate\nMyPerfectPair(A, B) -> MyPerfectPair;\n\n\n\nvoid typeTracer(int x)\n{\n}\n\nint main()\n{\n \/\/ CTAG automatically deduce template argument type based on constructor parameters\n MyPair p1{ 1729, 3.14 };\n StaticString s1{ \"hello\" };\n\/\/ typeTracer(s1);\n static_assert( std::is_same_v> );\n\n Container::Iterator it;\n Container cont{ it, it }; \/\/ using CTAD deduction guide\n\n int i1 = 12;\n double d2 = 3.4;\n MyPerfectPair p2{ std::move(i1), std::move(d2) };\n static_assert(std::is_same_v>);\n\n return 0;\n}More CTAD example.#include \n#include \n\n#if __cpp_deduction_guides\n#else\n#error \"Class Template Argument Deduction is not supported by the compiler\"\n#endif\n\n\n\ntemplate\nstruct MyPair\n{\n MyPair(const A &, const B &)\n {\n }\n};\n\n\ntemplate\nstruct StaticString\n{\n StaticString(const char (&str)[Size]): c_str(str)\n {\n }\n\n const char *c_str;\n};\n\n\ntemplate\nstruct Container\n{\n struct Iterator\n {\n using value_type = T;\n };\n\n template\n Container( It begin, It end )\n {\n \n }\n};\n\n\n\/\/ Class Template Argument Deduction guide (must be outside the class, in the same namespace).\ntemplate\nContainer(It begin, It end) ->Container;\n\n\n\ntemplate\nstruct MyPerfectPair\n{\n \/\/ perfect forwarding like\n template\n MyPerfectPair(U &&, V &&)\n {\n }\n};\n\n\/**\n * \/\/ CTAD guide, signature does not need to match. \n * \n * Use \"decay by value\" trick. \n * \n * Takes by value to partially simulate decay. See https:\/\/youtu.be\/-H-ut6j1BYU?list=PLHTh1InhhwT6V9RVdFRoCG_Pm5udDxG1c&t=1987\n * \n * CTAD signature does not impact with ctor parameter overload resolution. It will be done as usual, but in the context of type MyPerfectPair.\n *\/\ntemplate\nMyPerfectPair(A, B) -> MyPerfectPair;\n\n\n\nvoid typeTracer(int x)\n{\n}\n\nint main()\n{\n \/\/ CTAG automatically deduce template argument type based on constructor parameters\n MyPair p1{ 1729, 3.14 };\n StaticString s1{ \"hello\" };\n\/\/ typeTracer(s1);\n static_assert( std::is_same_v> );\n\n MyPair p1b{ 1729, \"hello\" };\n static_assert(std::is_same_v>);\/\/ watch out, not const char\n\n Container::Iterator it;\n Container cont{ it, it }; \/\/ using CTAD deduction guide\n\n int i1 = 12;\n double d2 = 3.4;\n MyPerfectPair p2{ std::move(i1), std::move(d2) };\n static_assert(std::is_same_v>);\n\n return 0;\n}<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n\n#include \"gmock\/gmock.h\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace testing_utilities {\n\ntemplate\nclass VanishesBeforeMatcher;\n\n\/\/ The matchers below are useful when a computation gives a result whose\n\/\/ expected value is zero. Because of cancellations it is unlikely that the\n\/\/ computed value is exactly zero. The matchers take a reference value, which\n\/\/ represents the order of magnitude of the intermediate results that triggered\n\/\/ the cancellation, and a tolerance expressed as a number of ulps in the\n\/\/ error. More precisely the matcher checks that the |reference| is equal to\n\/\/ to |actual + reference| to within the specified number of ulps.\n\n\/\/ The 2-argument version of |VanishesBefore()| should always be preferred as it\n\/\/ guarantees that the error bound is tight.\ntemplate\ntesting::PolymorphicMatcher> VanishesBefore(\n T const& reference,\n std::int64_t const max_ulps);\n\n\/\/ The 3-argument version of |VanishesBefore()| is exclusively for use when a\n\/\/ given assertion may have different errors, e.g., because it's in a loop. It\n\/\/ doesn't guarantee that the error bound is tight.\ntemplate\ntesting::PolymorphicMatcher> VanishesBefore(\n T const& reference,\n std::int64_t const min_ulps,\n std::int64_t const max_ulps);\n\ntemplate\nclass VanishesBeforeMatcher{\n public:\n explicit VanishesBeforeMatcher(T const& reference,\n std::int64_t const min_ulps,\n std::int64_t const max_ulps);\n ~VanishesBeforeMatcher() = default;\n\n template\n bool MatchAndExplain(quantities::Quantity const& actual,\n testing::MatchResultListener* listener) const;\n bool MatchAndExplain(double const actual,\n testing::MatchResultListener* listener) const;\n\n void DescribeTo(std::ostream* out) const;\n void DescribeNegationTo(std::ostream* out) const;\n\n private:\n T const reference_;\n std::int64_t const min_ulps_;\n std::int64_t const max_ulps_;\n};\n\n} \/\/ namespace testing_utilities\n} \/\/ namespace principia\n\n#include \"testing_utilities\/vanishes_before_body.hpp\"\nUn p'tit blanc sec.#pragma once\n\n#include \n#include \n\n#include \n\n#include \"gmock\/gmock.h\"\n#include \"quantities\/quantities.hpp\"\n\nnamespace principia {\nnamespace testing_utilities {\n\ntemplate\nclass VanishesBeforeMatcher;\n\n\/\/ The matchers below are useful when a computation gives a result whose\n\/\/ expected value is zero. Because of cancellations it is unlikely that the\n\/\/ computed value is exactly zero. The matchers take a reference value, which\n\/\/ represents the order of magnitude of the intermediate results that triggered\n\/\/ the cancellation, and a tolerance expressed as a number of ulps in the\n\/\/ error. More precisely the matcher checks that the |reference| is equal to\n\/\/ to |actual + reference| to within the specified number of ulps.\n\n\/\/ The 2-argument version of |VanishesBefore()| should always be preferred as it\n\/\/ guarantees that the error bound is tight.\ntemplate\ntesting::PolymorphicMatcher> VanishesBefore(\n T const& reference,\n std::int64_t const max_ulps);\n\n\/\/ The 3-argument version of |VanishesBefore()| is exclusively for use when a\n\/\/ given assertion may have different errors, e.g., because it's in a loop. It\n\/\/ doesn't guarantee that the error bound is tight.\ntemplate\ntesting::PolymorphicMatcher> VanishesBefore(\n T const& reference,\n std::int64_t const min_ulps,\n std::int64_t const max_ulps);\n\ntemplate\nclass VanishesBeforeMatcher {\n public:\n explicit VanishesBeforeMatcher(T const& reference,\n std::int64_t const min_ulps,\n std::int64_t const max_ulps);\n ~VanishesBeforeMatcher() = default;\n\n template\n bool MatchAndExplain(quantities::Quantity const& actual,\n testing::MatchResultListener* listener) const;\n bool MatchAndExplain(double const actual,\n testing::MatchResultListener* listener) const;\n\n void DescribeTo(std::ostream* out) const;\n void DescribeNegationTo(std::ostream* out) const;\n\n private:\n T const reference_;\n std::int64_t const min_ulps_;\n std::int64_t const max_ulps_;\n};\n\n} \/\/ namespace testing_utilities\n} \/\/ namespace principia\n\n#include \"testing_utilities\/vanishes_before_body.hpp\"\n<|endoftext|>"} {"text":"#include \"..\/..\/src\/common\/problem_definition.h\"\n#include \"..\/test_utilities.h\"\n\nvoid setup_parameters (dealii::ParameterHandler &prm)\n{\n \/\/ set entry values for those without default input\n prm.set (\"reflective boundary names\", \"xmin\");\n prm.set (\"x, y, z max values of boundary locations\", \"1.0, 2.0\");\n prm.set (\"number of cells for x, y, z directions\", \"1, 3\");\n}\n\nvoid find_errors (dealii::ParameterHandler &prm)\n{\n \/\/ dealii::ExcInternalError() is used to indicate expected\n \/\/ condition is not satisfied.\n AssertThrow (prm.get_integer(\"problem dimension\")==2,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"transport model\")==\"none\", dealii::ExcInternalError());\n AssertThrow (prm.get(\"HO linear solver name\")==\"cg\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"HO preconditioner name\")==\"amg\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_double(\"HO ssor factor\")==1.0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"NDA linear solver name\")==\"none\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"NDA preconditioner name\")==\"none\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_double(\"NDA ssor factor\")==1.0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"angular quadrature name\")==\"none\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"angular quadrature order\")==4,\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"number of groups\")==1,\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"thermal group boundary\")==0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"spatial discretization\")==\"cfem\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"do eigenvalue calculations\")==false,\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"do NDA\")==false, dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"have reflective BC\")==false,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"reflective boundary names\")==\"xmin\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"finite element polynomial degree\")==1,\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"uniform refinements\")==0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"x, y, z max values of boundary locations\")==\"1.0, 2.0\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"number of cells for x, y, z directions\")==\"1, 3\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"number of materials\")==1,\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"do print angular quadrature info\")==true,\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"is mesh generated by deal.II\")==true,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"output file name base\")==\"solu\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"mesh file name\")==\"mesh.msh\",\n dealii::ExcInternalError());\n}\n\nvoid test (dealii::ParameterHandler &prm)\n{\n \/\/ purpose of this test is to see whether parameters\n \/\/ are parsed correctly\n ProblemDefinition::declare_parameters (prm);\n setup_parameters (prm);\n find_errors (prm);\n dealii::deallog << \"OK\" << std::endl;\n}\n\nint main ()\n{\n dealii::ParameterHandler prm;\n \n testing::init_log ();\n \n test (prm);\n return 0;\n}\nModified ProblemDefinition test w\/ GGL style #61#include \"..\/..\/src\/common\/problem_definition.h\"\n#include \"..\/test_utilities.h\"\n\nvoid SetupParameters (dealii::ParameterHandler &prm)\n{\n \/\/ set entry values for those without default input\n prm.set (\"reflective boundary names\", \"xmin\");\n prm.set (\"x, y, z max values of boundary locations\", \"1.0, 2.0\");\n prm.set (\"number of cells for x, y, z directions\", \"1, 3\");\n}\n\nvoid FindErrors (dealii::ParameterHandler &prm)\n{\n \/\/ dealii::ExcInternalError() is used to indicate expected\n \/\/ condition is not satisfied.\n AssertThrow (prm.get_integer(\"problem dimension\")==2,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"transport model\")==\"none\", dealii::ExcInternalError());\n AssertThrow (prm.get(\"HO linear solver name\")==\"cg\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"HO preconditioner name\")==\"amg\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_double(\"HO ssor factor\")==1.0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"NDA linear solver name\")==\"none\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"NDA preconditioner name\")==\"none\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_double(\"NDA ssor factor\")==1.0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"angular quadrature name\")==\"none\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"angular quadrature order\")==4,\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"number of groups\")==1,\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"thermal group boundary\")==0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"spatial discretization\")==\"cfem\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"do eigenvalue calculations\")==false,\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"do NDA\")==false, dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"have reflective BC\")==false,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"reflective boundary names\")==\"xmin\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"finite element polynomial degree\")==1,\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"uniform refinements\")==0,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"x, y, z max values of boundary locations\")==\"1.0, 2.0\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"number of cells for x, y, z directions\")==\"1, 3\",\n dealii::ExcInternalError());\n AssertThrow (prm.get_integer(\"number of materials\")==1,\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"do print angular quadrature info\")==true,\n dealii::ExcInternalError());\n AssertThrow (prm.get_bool(\"is mesh generated by deal.II\")==true,\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"output file name base\")==\"solu\",\n dealii::ExcInternalError());\n AssertThrow (prm.get(\"mesh file name\")==\"mesh.msh\",\n dealii::ExcInternalError());\n}\n\nvoid Test (dealii::ParameterHandler &prm)\n{\n \/\/ purpose of this test is to see whether parameters\n \/\/ are parsed correctly\n ProblemDefinition::DeclareParameters (prm);\n SetupParameters (prm);\n FindErrors (prm);\n dealii::deallog << \"OK\" << std::endl;\n}\n\nint main ()\n{\n dealii::ParameterHandler prm;\n\n testing::init_log ();\n\n Test (prm);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n This file is part of the kolab resource - the implementation of the\n Kolab storage format. See www.kolab.org for documentation on this.\n\n Copyright (c) 2004 Bo Thorsen \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"task.h\"\n\n#include \n#include \n\nusing namespace Kolab;\n\n\nKCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )\n{\n Task task( tz );\n task.load( xml );\n KCal::Todo* todo = new KCal::Todo();\n task.saveTo( todo );\n return todo;\n}\n\nQString Task::taskToXML( KCal::Todo* todo, const QString& tz )\n{\n Task task( tz, todo );\n return task.saveXML();\n}\n\nTask::Task( const QString& tz, KCal::Todo* task )\n : Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),\n mStatus( KCal::Incidence::StatusNone ),\n mHasDueDate( false ), mHasCompletedDate( false )\n{\n if ( task )\n setFields( task );\n}\n\nTask::~Task()\n{\n}\n\nvoid Task::setPriority( int priority )\n{\n mPriority = priority;\n}\n\nint Task::priority() const\n{\n return mPriority;\n}\n\nvoid Task::setPercentCompleted( int percent )\n{\n mPercentCompleted = percent;\n}\n\nint Task::percentCompleted() const\n{\n return mPercentCompleted;\n}\n\nvoid Task::setStatus( KCal::Incidence::Status status )\n{\n mStatus = status;\n}\n\nKCal::Incidence::Status Task::status() const\n{\n return mStatus;\n}\n\nvoid Task::setParent( const QString& parentUid )\n{\n mParent = parentUid;\n}\n\nQString Task::parent() const\n{\n return mParent;\n}\n\nvoid Task::setDueDate( const QDateTime& date )\n{\n mDueDate = date;\n mHasDueDate = true;\n}\n\nQDateTime Task::dueDate() const\n{\n return mDueDate;\n}\n\nbool Task::hasDueDate() const\n{\n return mHasDueDate;\n}\n\nvoid Task::setCompletedDate( const QDateTime& date )\n{\n mCompletedDate = date;\n mHasCompletedDate = true;\n}\n\nQDateTime Task::completedDate() const\n{\n return mCompletedDate;\n}\n\nbool Task::hasCompletedDate() const\n{\n return mHasCompletedDate;\n}\n\nbool Task::loadAttribute( QDomElement& element )\n{\n QString tagName = element.tagName();\n\n if ( tagName == \"priority\" ) {\n bool ok;\n int priority = element.text().toInt( &ok );\n if ( !ok || priority < 0 || priority > 5 )\n priority = 3;\n setPriority( priority );\n } else if ( tagName == \"completed\" ) {\n bool ok;\n int percent = element.text().toInt( &ok );\n if ( !ok || percent < 0 || percent > 100 )\n percent = 0;\n setPercentCompleted( percent );\n } else if ( tagName == \"status\" ) {\n if ( element.text() == \"in-progress\" )\n setStatus( KCal::Incidence::StatusInProcess );\n else if ( element.text() == \"completed\" )\n setStatus( KCal::Incidence::StatusCompleted );\n else if ( element.text() == \"waiting-on-someone-else\" )\n setStatus( KCal::Incidence::StatusNeedsAction );\n else if ( element.text() == \"deferred\" )\n \/\/ Guessing a status here\n setStatus( KCal::Incidence::StatusCanceled );\n else\n \/\/ Default\n setStatus( KCal::Incidence::StatusNone );\n } else if ( tagName == \"due-date\" )\n setDueDate( stringToDateTime( element.text() ) );\n else if ( tagName == \"parent\" )\n setParent( element.text() );\n else if ( tagName == \"x-completed-date\" )\n setCompletedDate( stringToDateTime( element.text() ) );\n else\n return Incidence::loadAttribute( element );\n\n \/\/ We handled this\n return true;\n}\n\nbool Task::saveAttributes( QDomElement& element ) const\n{\n \/\/ Save the base class elements\n Incidence::saveAttributes( element );\n\n writeString( element, \"priority\", QString::number( priority() ) );\n writeString( element, \"completed\", QString::number( percentCompleted() ) );\n\n switch( status() ) {\n case KCal::Incidence::StatusInProcess:\n writeString( element, \"status\", \"in-progress\" );\n break;\n case KCal::Incidence::StatusCompleted:\n writeString( element, \"status\", \"completed\" );\n break;\n case KCal::Incidence::StatusNeedsAction:\n writeString( element, \"status\", \"waiting-on-someone-else\" );\n break;\n case KCal::Incidence::StatusCanceled:\n writeString( element, \"status\", \"deferred\" );\n break;\n case KCal::Incidence::StatusNone:\n writeString( element, \"status\", \"not-started\" );\n break;\n case KCal::Incidence::StatusTentative:\n case KCal::Incidence::StatusConfirmed:\n case KCal::Incidence::StatusDraft:\n case KCal::Incidence::StatusFinal:\n case KCal::Incidence::StatusX:\n \/\/ All of these are saved as StatusNone.\n writeString( element, \"status\", \"not-started\" );\n break;\n }\n\n if ( hasDueDate() )\n writeString( element, \"due-date\", dateTimeToString( dueDate() ) );\n\n if ( !parent().isNull() )\n writeString( element, \"parent\", parent() );\n\n if ( hasCompletedDate() )\n writeString( element, \"x-completed-date\", dateTimeToString( completedDate() ) );\n\n return true;\n}\n\n\nbool Task::loadXML( const QDomDocument& document )\n{\n QDomElement top = document.documentElement();\n\n if ( top.tagName() != \"task\" ) {\n qWarning( \"XML error: Top tag was %s instead of the expected task\",\n top.tagName().ascii() );\n return false;\n }\n\n for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {\n if ( n.isComment() )\n continue;\n if ( n.isElement() ) {\n QDomElement e = n.toElement();\n if ( !loadAttribute( e ) )\n \/\/ TODO: Unhandled tag - save for later storage\n kdDebug() << \"Warning: Unhandled tag \" << e.tagName() << endl;\n } else\n kdDebug() << \"Node is not a comment or an element???\" << endl;\n }\n\n return true;\n}\n\nQString Task::saveXML() const\n{\n QDomDocument document = domTree();\n QDomElement element = document.createElement( \"task\" );\n element.setAttribute( \"version\", \"1.0\" );\n saveAttributes( element );\n document.appendChild( element );\n return document.toString();\n}\n\nvoid Task::setFields( const KCal::Todo* task )\n{\n Incidence::setFields( task );\n\n setPriority( task->priority() );\n setPercentCompleted( task->percentComplete() );\n setStatus( task->status() );\n if ( task->hasDueDate() )\n setDueDate( localToUTC( task->dtDue() ) );\n else\n mHasDueDate = false;\n setParent( QString::null );\n\n if ( task->hasCompletedDate() )\n setCompletedDate( localToUTC( task->completed() ) );\n else\n mHasCompletedDate = false;\n}\n\nvoid Task::saveTo( KCal::Todo* task )\n{\n Incidence::saveTo( task );\n\n task->setPriority( priority() );\n task->setPercentComplete( percentCompleted() );\n task->setStatus( status() );\n task->setHasDueDate( hasDueDate() );\n if ( hasDueDate() )\n task->setDtDue( utcToLocal( dueDate() ) );\n\n if ( parent() != QString::null )\n task->setRelatedToUid( parent() );\n\n if ( hasCompletedDate() )\n task->setCompleted( utcToLocal( mCompletedDate ) );\n}\nSave the parent of todos if they have one.\/*\n This file is part of the kolab resource - the implementation of the\n Kolab storage format. See www.kolab.org for documentation on this.\n\n Copyright (c) 2004 Bo Thorsen \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public License\n along with this library; see the file COPYING.LIB. If not, write to\n the Free Software Foundation, Inc., 59 Temple Place - Suite 330,\n Boston, MA 02111-1307, USA.\n\n In addition, as a special exception, the copyright holders give\n permission to link the code of this program with any edition of\n the Qt library by Trolltech AS, Norway (or with modified versions\n of Qt that use the same license as Qt), and distribute linked\n combinations including the two. You must obey the GNU General\n Public License in all respects for all of the code used other than\n Qt. If you modify this file, you may extend this exception to\n your version of the file, but you are not obligated to do so. If\n you do not wish to do so, delete this exception statement from\n your version.\n*\/\n\n#include \"task.h\"\n\n#include \n#include \n\nusing namespace Kolab;\n\n\nKCal::Todo* Task::xmlToTask( const QString& xml, const QString& tz )\n{\n Task task( tz );\n task.load( xml );\n KCal::Todo* todo = new KCal::Todo();\n task.saveTo( todo );\n return todo;\n}\n\nQString Task::taskToXML( KCal::Todo* todo, const QString& tz )\n{\n Task task( tz, todo );\n return task.saveXML();\n}\n\nTask::Task( const QString& tz, KCal::Todo* task )\n : Incidence( tz ), mPriority( 3 ), mPercentCompleted( 100 ),\n mStatus( KCal::Incidence::StatusNone ),\n mHasDueDate( false ), mHasCompletedDate( false )\n{\n if ( task )\n setFields( task );\n}\n\nTask::~Task()\n{\n}\n\nvoid Task::setPriority( int priority )\n{\n mPriority = priority;\n}\n\nint Task::priority() const\n{\n return mPriority;\n}\n\nvoid Task::setPercentCompleted( int percent )\n{\n mPercentCompleted = percent;\n}\n\nint Task::percentCompleted() const\n{\n return mPercentCompleted;\n}\n\nvoid Task::setStatus( KCal::Incidence::Status status )\n{\n mStatus = status;\n}\n\nKCal::Incidence::Status Task::status() const\n{\n return mStatus;\n}\n\nvoid Task::setParent( const QString& parentUid )\n{\n mParent = parentUid;\n}\n\nQString Task::parent() const\n{\n return mParent;\n}\n\nvoid Task::setDueDate( const QDateTime& date )\n{\n mDueDate = date;\n mHasDueDate = true;\n}\n\nQDateTime Task::dueDate() const\n{\n return mDueDate;\n}\n\nbool Task::hasDueDate() const\n{\n return mHasDueDate;\n}\n\nvoid Task::setCompletedDate( const QDateTime& date )\n{\n mCompletedDate = date;\n mHasCompletedDate = true;\n}\n\nQDateTime Task::completedDate() const\n{\n return mCompletedDate;\n}\n\nbool Task::hasCompletedDate() const\n{\n return mHasCompletedDate;\n}\n\nbool Task::loadAttribute( QDomElement& element )\n{\n QString tagName = element.tagName();\n\n if ( tagName == \"priority\" ) {\n bool ok;\n int priority = element.text().toInt( &ok );\n if ( !ok || priority < 0 || priority > 5 )\n priority = 3;\n setPriority( priority );\n } else if ( tagName == \"completed\" ) {\n bool ok;\n int percent = element.text().toInt( &ok );\n if ( !ok || percent < 0 || percent > 100 )\n percent = 0;\n setPercentCompleted( percent );\n } else if ( tagName == \"status\" ) {\n if ( element.text() == \"in-progress\" )\n setStatus( KCal::Incidence::StatusInProcess );\n else if ( element.text() == \"completed\" )\n setStatus( KCal::Incidence::StatusCompleted );\n else if ( element.text() == \"waiting-on-someone-else\" )\n setStatus( KCal::Incidence::StatusNeedsAction );\n else if ( element.text() == \"deferred\" )\n \/\/ Guessing a status here\n setStatus( KCal::Incidence::StatusCanceled );\n else\n \/\/ Default\n setStatus( KCal::Incidence::StatusNone );\n } else if ( tagName == \"due-date\" )\n setDueDate( stringToDateTime( element.text() ) );\n else if ( tagName == \"parent\" )\n setParent( element.text() );\n else if ( tagName == \"x-completed-date\" )\n setCompletedDate( stringToDateTime( element.text() ) );\n else\n return Incidence::loadAttribute( element );\n\n \/\/ We handled this\n return true;\n}\n\nbool Task::saveAttributes( QDomElement& element ) const\n{\n \/\/ Save the base class elements\n Incidence::saveAttributes( element );\n\n writeString( element, \"priority\", QString::number( priority() ) );\n writeString( element, \"completed\", QString::number( percentCompleted() ) );\n\n switch( status() ) {\n case KCal::Incidence::StatusInProcess:\n writeString( element, \"status\", \"in-progress\" );\n break;\n case KCal::Incidence::StatusCompleted:\n writeString( element, \"status\", \"completed\" );\n break;\n case KCal::Incidence::StatusNeedsAction:\n writeString( element, \"status\", \"waiting-on-someone-else\" );\n break;\n case KCal::Incidence::StatusCanceled:\n writeString( element, \"status\", \"deferred\" );\n break;\n case KCal::Incidence::StatusNone:\n writeString( element, \"status\", \"not-started\" );\n break;\n case KCal::Incidence::StatusTentative:\n case KCal::Incidence::StatusConfirmed:\n case KCal::Incidence::StatusDraft:\n case KCal::Incidence::StatusFinal:\n case KCal::Incidence::StatusX:\n \/\/ All of these are saved as StatusNone.\n writeString( element, \"status\", \"not-started\" );\n break;\n }\n\n if ( hasDueDate() )\n writeString( element, \"due-date\", dateTimeToString( dueDate() ) );\n\n if ( !parent().isNull() )\n writeString( element, \"parent\", parent() );\n\n if ( hasCompletedDate() )\n writeString( element, \"x-completed-date\", dateTimeToString( completedDate() ) );\n\n return true;\n}\n\n\nbool Task::loadXML( const QDomDocument& document )\n{\n QDomElement top = document.documentElement();\n\n if ( top.tagName() != \"task\" ) {\n qWarning( \"XML error: Top tag was %s instead of the expected task\",\n top.tagName().ascii() );\n return false;\n }\n\n for ( QDomNode n = top.firstChild(); !n.isNull(); n = n.nextSibling() ) {\n if ( n.isComment() )\n continue;\n if ( n.isElement() ) {\n QDomElement e = n.toElement();\n if ( !loadAttribute( e ) )\n \/\/ TODO: Unhandled tag - save for later storage\n kdDebug() << \"Warning: Unhandled tag \" << e.tagName() << endl;\n } else\n kdDebug() << \"Node is not a comment or an element???\" << endl;\n }\n\n return true;\n}\n\nQString Task::saveXML() const\n{\n QDomDocument document = domTree();\n QDomElement element = document.createElement( \"task\" );\n element.setAttribute( \"version\", \"1.0\" );\n saveAttributes( element );\n document.appendChild( element );\n return document.toString();\n}\n\nvoid Task::setFields( const KCal::Todo* task )\n{\n Incidence::setFields( task );\n\n setPriority( task->priority() );\n setPercentCompleted( task->percentComplete() );\n setStatus( task->status() );\n if ( task->hasDueDate() )\n setDueDate( localToUTC( task->dtDue() ) );\n else\n mHasDueDate = false;\n if ( task->relatedTo() )\n setParent( task->relatedTo()->uid() );\n else \n setParent( QString::null );\n\n if ( task->hasCompletedDate() )\n setCompletedDate( localToUTC( task->completed() ) );\n else\n mHasCompletedDate = false;\n}\n\nvoid Task::saveTo( KCal::Todo* task )\n{\n Incidence::saveTo( task );\n\n task->setPriority( priority() );\n task->setPercentComplete( percentCompleted() );\n task->setStatus( status() );\n task->setHasDueDate( hasDueDate() );\n if ( hasDueDate() )\n task->setDtDue( utcToLocal( dueDate() ) );\n\n if ( parent() != QString::null )\n task->setRelatedToUid( parent() );\n\n if ( hasCompletedDate() )\n task->setCompleted( utcToLocal( mCompletedDate ) );\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#include \"mfem.hpp\"\n#include \"catch.hpp\"\n\n#include \n#include \n\nusing namespace mfem;\n\n\/**\n * Utility function to generate IntegerationPoints, based on param ip\n * that are outside the unit interval. Results are placed in output\n * parameter arr.\n *\n * Note: this is defined in test_calcshape.cpp\n *\/\nvoid GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,\n Array& arr);\n\n\/**\n * Utility function to setup IsoparametricTransformations for reference\n * elements of various types.\n *\n * Note: this is defined in test_calcvshape.cpp\n *\/\nvoid GetReferenceTransformation(const Element::Type ElemType,\n IsoparametricTransformation & T);\n\n\/**\n * Linear test function whose curl is equal to 1 in 2D and (1,1,1) in 3D.\n*\/\nvoid test_curl_func(const Vector &x, Vector &v)\n{\n int dim = x.Size();\n v.SetSize(dim);\n v[0] = 4.0 * x[1];\n v[1] = 5.0 * x[0];\n if (dim == 3)\n {\n v[0] += 3.0 * x[2];\n v[1] += x[2];\n v[2] = 2.0 * (x[0] + x[1]);\n }\n}\n\n\/**\n * Tests fe->CalcCurlShape() over a grid of IntegrationPoints\n * of resolution res. Also tests at integration points\n * that are outside the element.\n *\/\nvoid TestCalcCurlShape(FiniteElement* fe, ElementTransformation * T, int res)\n{\n int dof = fe->GetDof();\n int dim = fe->GetDim();\n int cdim = 2 * dim - 3;\n\n Vector dofs(dof);\n Vector v(cdim);\n DenseMatrix weights( dof, cdim );\n\n VectorFunctionCoefficient vCoef(dim, test_curl_func);\n\n fe->Project(vCoef, *T, dofs);\n\n \/\/ Get a uniform grid or integration points\n RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);\n const IntegrationRule& intRule = ref->RefPts;\n\n int npoints = intRule.GetNPoints();\n for (int i=0; i < npoints; ++i)\n {\n \/\/ Get the current integration point from intRule\n IntegrationPoint pt = intRule.IntPoint(i);\n\n \/\/ Get several variants of this integration point\n \/\/ some of which are inside the element and some are outside\n Array ipArr;\n GetRelatedIntegrationPoints( pt, dim, ipArr );\n\n \/\/ For each such integration point check that the weights\n \/\/ from CalcCurlShape() sum to one\n for (int j=0; j < ipArr.Size(); ++j)\n {\n IntegrationPoint& ip = ipArr[j];\n fe->CalcCurlShape(ip, weights);\n\n weights.MultTranspose(dofs, v);\n REQUIRE( v[0] == Approx(1.) );\n if (dim == 3)\n {\n REQUIRE( v[1] == Approx(1.) );\n REQUIRE( v[2] == Approx(1.) );\n }\n }\n }\n}\n\nTEST_CASE(\"CalcCurlShape for several ND FiniteElement instances\",\n \"[ND_TriangleElement]\"\n \"[ND_QuadrilateralElement]\"\n \"[ND_TetrahedronElement]\"\n \"[ND_WedgeElement]\"\n \"[ND_HexahedronElement]\")\n{\n int maxOrder = 5;\n int resolution = 10;\n\n SECTION(\"ND_TriangleElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::TRIANGLE, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_TriangleElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_TriangleElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_QuadrilateralElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::QUADRILATERAL, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_QuadrilateralElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_QuadrilateralElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_TetrahedronElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::TETRAHEDRON, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_TetrahedronElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_TetrahedronElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_WedgeElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::WEDGE, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_WedgeElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_WedgeElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_HexahedronElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::HEXAHEDRON, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_HexahedronElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_HexahedronElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n}\nPartial copyright statement fix for testing\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced at\n\/\/ the Lawrence Livermore National Laboratory. LLNL-CODE-443211. All Rights\n\/\/ reserved. See file COPYRIGHT for details.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability see http:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the GNU Lesser General Public License (as published by the Free\n\/\/ Software Foundation) version 2.1 dated February 1999.\n\n#include \"mfem.hpp\"\n#include \"catch.hpp\"\n\n#include \n#include \n\nusing namespace mfem;\n\n\/**\n * Utility function to generate IntegerationPoints, based on param ip\n * that are outside the unit interval. Results are placed in output\n * parameter arr.\n *\n * Note: this is defined in test_calcshape.cpp\n *\/\nvoid GetRelatedIntegrationPoints(const IntegrationPoint& ip, int dim,\n Array& arr);\n\n\/**\n * Utility function to setup IsoparametricTransformations for reference\n * elements of various types.\n *\n * Note: this is defined in test_calcvshape.cpp\n *\/\nvoid GetReferenceTransformation(const Element::Type ElemType,\n IsoparametricTransformation & T);\n\n\/**\n * Linear test function whose curl is equal to 1 in 2D and (1,1,1) in 3D.\n*\/\nvoid test_curl_func(const Vector &x, Vector &v)\n{\n int dim = x.Size();\n v.SetSize(dim);\n v[0] = 4.0 * x[1];\n v[1] = 5.0 * x[0];\n if (dim == 3)\n {\n v[0] += 3.0 * x[2];\n v[1] += x[2];\n v[2] = 2.0 * (x[0] + x[1]);\n }\n}\n\n\/**\n * Tests fe->CalcCurlShape() over a grid of IntegrationPoints\n * of resolution res. Also tests at integration points\n * that are outside the element.\n *\/\nvoid TestCalcCurlShape(FiniteElement* fe, ElementTransformation * T, int res)\n{\n int dof = fe->GetDof();\n int dim = fe->GetDim();\n int cdim = 2 * dim - 3;\n\n Vector dofs(dof);\n Vector v(cdim);\n DenseMatrix weights( dof, cdim );\n\n VectorFunctionCoefficient vCoef(dim, test_curl_func);\n\n fe->Project(vCoef, *T, dofs);\n\n \/\/ Get a uniform grid or integration points\n RefinedGeometry* ref = GlobGeometryRefiner.Refine( fe->GetGeomType(), res);\n const IntegrationRule& intRule = ref->RefPts;\n\n int npoints = intRule.GetNPoints();\n for (int i=0; i < npoints; ++i)\n {\n \/\/ Get the current integration point from intRule\n IntegrationPoint pt = intRule.IntPoint(i);\n\n \/\/ Get several variants of this integration point\n \/\/ some of which are inside the element and some are outside\n Array ipArr;\n GetRelatedIntegrationPoints( pt, dim, ipArr );\n\n \/\/ For each such integration point check that the weights\n \/\/ from CalcCurlShape() sum to one\n for (int j=0; j < ipArr.Size(); ++j)\n {\n IntegrationPoint& ip = ipArr[j];\n fe->CalcCurlShape(ip, weights);\n\n weights.MultTranspose(dofs, v);\n REQUIRE( v[0] == Approx(1.) );\n if (dim == 3)\n {\n REQUIRE( v[1] == Approx(1.) );\n REQUIRE( v[2] == Approx(1.) );\n }\n }\n }\n}\n\nTEST_CASE(\"CalcCurlShape for several ND FiniteElement instances\",\n \"[ND_TriangleElement]\"\n \"[ND_QuadrilateralElement]\"\n \"[ND_TetrahedronElement]\"\n \"[ND_WedgeElement]\"\n \"[ND_HexahedronElement]\")\n{\n int maxOrder = 5;\n int resolution = 10;\n\n SECTION(\"ND_TriangleElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::TRIANGLE, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_TriangleElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_TriangleElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_QuadrilateralElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::QUADRILATERAL, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_QuadrilateralElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_QuadrilateralElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_TetrahedronElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::TETRAHEDRON, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_TetrahedronElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_TetrahedronElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_WedgeElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::WEDGE, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_WedgeElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_WedgeElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n\n SECTION(\"ND_HexahedronElement\")\n {\n IsoparametricTransformation T;\n GetReferenceTransformation(Element::HEXAHEDRON, T);\n\n for (int order =1; order <= maxOrder; ++order)\n {\n std::cout << \"Testing ND_HexahedronElement::CalcCurlShape() \"\n << \"for order \" << order << std::endl;\n ND_HexahedronElement fe(order);\n TestCalcCurlShape(&fe, &T, resolution);\n }\n }\n}\n<|endoftext|>"} {"text":"\/**\n * Touhou Community Reliant Automatic Patcher\n * Tasogare Frontier support plugin\n *\n * ----\n *\n * Plugin entry point.\n *\/\n\n#include \n#include \"thcrap_tasofro.h\"\n#include \"th135.h\"\n\ntasofro_game_t game_id;\n\n\/\/ Translate strings to IDs.\nstatic tasofro_game_t game_id_from_string(const char *game)\n{\n\tif (game == NULL) {\n\t\treturn TH_NONE;\n\t}\n\telse if (!strcmp(game, \"megamari\")) {\n\t\treturn TH_MEGAMARI;\n\t}\n\telse if (!strcmp(game, \"nsml\")) {\n\t\treturn TH_NSML;\n\t}\n\telse if (!strcmp(game, \"th105\")) {\n\t\treturn TH105;\n\t}\n\telse if (!strcmp(game, \"th123\")) {\n\t\treturn TH123;\n\t}\n\telse if (!strcmp(game, \"th135\")) {\n\t\treturn TH135;\n\t}\n\telse if (!strcmp(game, \"th145\")) {\n\t\treturn TH145;\n\t}\n\telse if (!strcmp(game, \"th155\")) {\n\t\treturn TH155;\n\t}\n\treturn TH_FUTURE;\n}\n\nint __stdcall thcrap_plugin_init()\n{\n\tint base_tasofro_removed = stack_remove_if_unneeded(\"base_tasofro\");\n\tif (base_tasofro_removed == 1) {\n\t\treturn 1;\n\t}\n\n\tconst char *game = json_object_get_string(runconfig_get(), \"game\");\n\tgame_id = game_id_from_string(game);\n\n\tif(base_tasofro_removed == -1) {\n\t\tif(game_id == TH145) {\n\t\t\tlog_mboxf(NULL, MB_OK | MB_ICONINFORMATION,\n\t\t\t\t\"Support for TH14.5 has been moved out of the sandbox.\\n\"\n\t\t\t\t\"\\n\"\n\t\t\t\t\"Please reconfigure your patch stack; otherwise, you might \"\n\t\t\t\t\"encounter errors or missing functionality after further \"\n\t\t\t\t\"updates.\\n\"\n\t\t\t);\n\t\t} else {\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tif (game_id >= TH135) {\n\t\treturn th135_init();\n\t}\n\telse {\n\t\treturn nsml_init();\n\t}\n\n\treturn 0;\n}\nthcrap_tasofro: Add the Steam AppID for th155. [V]\/**\n * Touhou Community Reliant Automatic Patcher\n * Tasogare Frontier support plugin\n *\n * ----\n *\n * Plugin entry point.\n *\/\n\n#include \n#include \"thcrap_tasofro.h\"\n#include \"th135.h\"\n\ntasofro_game_t game_id;\n\n\/\/ Translate strings to IDs.\nstatic tasofro_game_t game_id_from_string(const char *game)\n{\n\tif (game == NULL) {\n\t\treturn TH_NONE;\n\t}\n\telse if (!strcmp(game, \"megamari\")) {\n\t\treturn TH_MEGAMARI;\n\t}\n\telse if (!strcmp(game, \"nsml\")) {\n\t\treturn TH_NSML;\n\t}\n\telse if (!strcmp(game, \"th105\")) {\n\t\treturn TH105;\n\t}\n\telse if (!strcmp(game, \"th123\")) {\n\t\treturn TH123;\n\t}\n\telse if (!strcmp(game, \"th135\")) {\n\t\treturn TH135;\n\t}\n\telse if (!strcmp(game, \"th145\")) {\n\t\treturn TH145;\n\t}\n\telse if (!strcmp(game, \"th155\")) {\n\t\treturn TH155;\n\t}\n\treturn TH_FUTURE;\n}\n\nextern \"C\" __declspec(dllexport) const char* steam_appid(void)\n{\n\tswitch(game_id) {\n\tcase TH155:\n\t\treturn \"716710\";\n\tdefault: \/\/ -Wswitch...\n\t\treturn nullptr;\n\t}\n}\n\nint __stdcall thcrap_plugin_init()\n{\n\tint base_tasofro_removed = stack_remove_if_unneeded(\"base_tasofro\");\n\tif (base_tasofro_removed == 1) {\n\t\treturn 1;\n\t}\n\n\tconst char *game = json_object_get_string(runconfig_get(), \"game\");\n\tgame_id = game_id_from_string(game);\n\n\tif(base_tasofro_removed == -1) {\n\t\tif(game_id == TH145) {\n\t\t\tlog_mboxf(NULL, MB_OK | MB_ICONINFORMATION,\n\t\t\t\t\"Support for TH14.5 has been moved out of the sandbox.\\n\"\n\t\t\t\t\"\\n\"\n\t\t\t\t\"Please reconfigure your patch stack; otherwise, you might \"\n\t\t\t\t\"encounter errors or missing functionality after further \"\n\t\t\t\t\"updates.\\n\"\n\t\t\t);\n\t\t} else {\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tif (game_id >= TH135) {\n\t\treturn th135_init();\n\t}\n\telse {\n\t\treturn nsml_init();\n\t}\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n\nnamespace apache { namespace thrift { namespace util {\n\nPausableTimer::PausableTimer(int timeLimit) {\n isTimeLimitFinite_ = timeLimit > 0;\n timeLimit_.tv_sec = static_cast(timeLimit \/ 1000);\n timeLimit_.tv_usec = static_cast((timeLimit % 1000) * 1000);\n reset();\n}\n\nvoid PausableTimer::reset() {\n if (isTimeLimitFinite_) {\n totalTimed_ = (struct timeval){ 0 };\n lastRunningTime_ = (struct timeval){ 0 };\n paused_ = true;\n }\n}\n\nvoid PausableTimer::start() {\n if (isTimeLimitFinite_) {\n if (paused_) {\n gettimeofday(&startTime_, nullptr);\n paused_ = false;\n }\n }\n}\n\nvoid PausableTimer::stop() {\n if (isTimeLimitFinite_) {\n if (!paused_) {\n struct timeval end;\n gettimeofday(&end, nullptr);\n timersub(&end, &startTime_, &lastRunningTime_);\n timeradd(&lastRunningTime_, &totalTimed_, &totalTimed_);\n paused_ = true;\n }\n }\n}\n\nbool PausableTimer::hasExceededTimeLimit() {\n if (isTimeLimitFinite_) {\n return timercmp(&totalTimed_, &timeLimit_, >);\n }\n\n return false;\n}\n\n\nbool PausableTimer::didLastRunningTimeExceedLimit(\n uint64_t limit_in_microseconds)\n{\n if (limit_in_microseconds == 0) {\n return false;\n }\n\n return\n 1000 * 1000 * lastRunningTime_.tv_sec +\n (uint64_t) lastRunningTime_.tv_usec >\n limit_in_microseconds;\n}\n\n}}}\nConstruct timeval in a way that MSVC likes\/*\n * Copyright 2014 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n\nnamespace apache { namespace thrift { namespace util {\n\nPausableTimer::PausableTimer(int timeLimit) {\n isTimeLimitFinite_ = timeLimit > 0;\n timeLimit_.tv_sec = static_cast(timeLimit \/ 1000);\n timeLimit_.tv_usec = static_cast((timeLimit % 1000) * 1000);\n reset();\n}\n\nvoid PausableTimer::reset() {\n if (isTimeLimitFinite_) {\n totalTimed_ = timeval{ 0 };\n lastRunningTime_ = timeval{ 0 };\n paused_ = true;\n }\n}\n\nvoid PausableTimer::start() {\n if (isTimeLimitFinite_) {\n if (paused_) {\n gettimeofday(&startTime_, nullptr);\n paused_ = false;\n }\n }\n}\n\nvoid PausableTimer::stop() {\n if (isTimeLimitFinite_) {\n if (!paused_) {\n struct timeval end;\n gettimeofday(&end, nullptr);\n timersub(&end, &startTime_, &lastRunningTime_);\n timeradd(&lastRunningTime_, &totalTimed_, &totalTimed_);\n paused_ = true;\n }\n }\n}\n\nbool PausableTimer::hasExceededTimeLimit() {\n if (isTimeLimitFinite_) {\n return timercmp(&totalTimed_, &timeLimit_, >);\n }\n\n return false;\n}\n\n\nbool PausableTimer::didLastRunningTimeExceedLimit(\n uint64_t limit_in_microseconds)\n{\n if (limit_in_microseconds == 0) {\n return false;\n }\n\n return\n 1000 * 1000 * lastRunningTime_.tv_sec +\n (uint64_t) lastRunningTime_.tv_usec >\n limit_in_microseconds;\n}\n\n}}}\n<|endoftext|>"} {"text":"\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"generatorBase\/semanticTree\/switchNode.h\"\n\n#include \n\nusing namespace generatorBase::semantics;\nusing namespace qReal;\n\nSwitchNode::SwitchNode(const Id &idBinded, QObject *parent)\n\t: NonZoneNode(idBinded, parent)\n\t, mDefaultBranch(nullptr)\n\t, mBranchesMerged(false)\n\t, mGenerateIfs(false)\n{\n}\n\nvoid SwitchNode::addBranch(const QString &value, SemanticNode * const node)\n{\n\tZoneNode * const zone = new ZoneNode(this);\n\tzone->setParentNode(this);\n\tbind(value, zone);\n\tif (node) {\n\t\tzone->appendChild(node);\n\t}\n}\n\nvoid SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node)\n{\n\tQ_ASSERT(node);\n\tbind(value, node->parentZone());\n}\n\nbool SwitchNode::branchesMerged() const\n{\n\treturn mBranchesMerged;\n}\n\nvoid SwitchNode::setBranchesMergedFlag()\n{\n\tmBranchesMerged = true;\n}\n\nvoid SwitchNode::setGenerateIfs()\n{\n\tmGenerateIfs = true;\n}\n\nQString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const\n{\n\tQString result;\n\tbool isHead = true;\n\tfor (ZoneNode * const zone : mBranches.values().toSet()) {\n\t\tif (zone == mDefaultBranch) {\n\t\t\t\/\/ Branches merged with default on the diagram will be merged with it in code too\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult += generatePart(customizer, indent, indentString, zone, isHead\n\t\t\t\t? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())\n\t\t\t\t: customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone), mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));\n\n\t\tisHead = false;\n\t}\n\n\tif (result.isEmpty()) {\n\t\t\/\/ Then all branches lead to one block, we may ignore switch construction.\n\t\treturn mDefaultBranch->toString(customizer, indent, indentString);\n\t}\n\n\tresult += generatePart(customizer, indent, indentString, mDefaultBranch\n\t\t\t, customizer.factory()->switchDefaultGenerator(mId, customizer, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));\n\n\treturn result;\n}\n\nvoid SwitchNode::bind(const QString &value, ZoneNode *zone)\n{\n\tif (value.isEmpty()) {\n\t\tmDefaultBranch = zone;\n\t} else {\n\t\tmBranches[value] = zone;\n\t}\n}\n\nQString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer\n\t\t, int indent\n\t\t, const QString &indentString\n\t\t, ZoneNode * const zone\n\t\t, generatorBase::simple::AbstractSimpleGenerator *generator) const\n{\n\treturn utils::StringUtils::addIndent(generator->generate()\n\t\t\t.replace(\"@@BODY@@\", zone->toString(customizer, indent + 1, indentString)), indent, indentString);\n}\n\nQLinkedList SwitchNode::children() const\n{\n\tQLinkedList result;\n\tfor (ZoneNode * const zone : mBranches.values().toSet()) {\n\t\tresult << zone;\n\t}\n\n\tif (mDefaultBranch) {\n\t\tresult << mDefaultBranch;\n\t}\n\n\treturn result;\n}\nStyle guide fixes\/* Copyright 2007-2015 QReal Research Group\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License. *\/\n\n#include \"generatorBase\/semanticTree\/switchNode.h\"\n\n#include \n\nusing namespace generatorBase::semantics;\nusing namespace qReal;\n\nSwitchNode::SwitchNode(const Id &idBinded, QObject *parent)\n\t: NonZoneNode(idBinded, parent)\n\t, mDefaultBranch(nullptr)\n\t, mBranchesMerged(false)\n\t, mGenerateIfs(false)\n{\n}\n\nvoid SwitchNode::addBranch(const QString &value, SemanticNode * const node)\n{\n\tZoneNode * const zone = new ZoneNode(this);\n\tzone->setParentNode(this);\n\tbind(value, zone);\n\tif (node) {\n\t\tzone->appendChild(node);\n\t}\n}\n\nvoid SwitchNode::mergeBranch(const QString &value, NonZoneNode * const node)\n{\n\tQ_ASSERT(node);\n\tbind(value, node->parentZone());\n}\n\nbool SwitchNode::branchesMerged() const\n{\n\treturn mBranchesMerged;\n}\n\nvoid SwitchNode::setBranchesMergedFlag()\n{\n\tmBranchesMerged = true;\n}\n\nvoid SwitchNode::setGenerateIfs()\n{\n\tmGenerateIfs = true;\n}\n\nQString SwitchNode::toStringImpl(GeneratorCustomizer &customizer, int indent, const QString &indentString) const\n{\n\tQString result;\n\tbool isHead = true;\n\tfor (ZoneNode * const zone : mBranches.values().toSet()) {\n\t\tif (zone == mDefaultBranch) {\n\t\t\t\/\/ Branches merged with default on the diagram will be merged with it in code too\n\t\t\tcontinue;\n\t\t}\n\n\t\tresult += generatePart(customizer, indent, indentString, zone, isHead\n\t\t\t\t? customizer.factory()->switchHeadGenerator(mId, customizer, mBranches.keys(zone)\n\t\t\t\t\t\t, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks())\n\t\t\t\t: customizer.factory()->switchMiddleGenerator(mId, customizer, mBranches.keys(zone)\n\t\t\t\t\t\t, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));\n\n\t\tisHead = false;\n\t}\n\n\tif (result.isEmpty()) {\n\t\t\/\/ Then all branches lead to one block, we may ignore switch construction.\n\t\treturn mDefaultBranch->toString(customizer, indent, indentString);\n\t}\n\n\tresult += generatePart(customizer, indent, indentString, mDefaultBranch\n\t\t\t, customizer.factory()->switchDefaultGenerator(mId, customizer\n\t\t\t, mGenerateIfs || !customizer.supportsSwitchUnstableToBreaks()));\n\n\treturn result;\n}\n\nvoid SwitchNode::bind(const QString &value, ZoneNode *zone)\n{\n\tif (value.isEmpty()) {\n\t\tmDefaultBranch = zone;\n\t} else {\n\t\tmBranches[value] = zone;\n\t}\n}\n\nQString SwitchNode::generatePart(generatorBase::GeneratorCustomizer &customizer\n\t\t, int indent\n\t\t, const QString &indentString\n\t\t, ZoneNode * const zone\n\t\t, generatorBase::simple::AbstractSimpleGenerator *generator) const\n{\n\treturn utils::StringUtils::addIndent(generator->generate()\n\t\t\t.replace(\"@@BODY@@\", zone->toString(customizer, indent + 1, indentString)), indent, indentString);\n}\n\nQLinkedList SwitchNode::children() const\n{\n\tQLinkedList result;\n\tfor (ZoneNode * const zone : mBranches.values().toSet()) {\n\t\tresult << zone;\n\t}\n\n\tif (mDefaultBranch) {\n\t\tresult << mDefaultBranch;\n\t}\n\n\treturn result;\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/tmva $Id$\n\/\/ Author: Simon Pfreundschuh\n\n\/*************************************************************************\n * Copyright (C) 2016, Simon Pfreundschuh *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Concrete instantiation of the generic backpropagation test for \/\/\n\/\/ multi-threaded CPU architectures. \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TMatrix.h\"\n#include \"TMVA\/DNN\/Architectures\/Cpu.h\"\n#include \"TestBackpropagation.h\"\n\nusing namespace TMVA::DNN;\n\nint main()\n{\n using Scalar_t = Double_t;\n std::cout << \"Testing Backpropagation:\" << std::endl;\n\n double error;\n\n error = testBackpropagationWeightsLinear>(1.0);\n if (error > 1e-3)\n return 1;\n\n error = testBackpropagationL1Regularization>(1e-2);\n if (error > 1e-3)\n return 1;\n\n error = testBackpropagationL2Regularization>(1.0);\n if (error > 1e-3)\n return 1;\n\n error = testBackpropagationBiasesLinear>(1.0);\n if (error > 1e-3)\n return 1;\n\n return 0;\n}\nContinue testing if one test fails\/\/ @(#)root\/tmva $Id$\n\/\/ Author: Simon Pfreundschuh\n\n\/*************************************************************************\n * Copyright (C) 2016, Simon Pfreundschuh *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Concrete instantiation of the generic backpropagation test for \/\/\n\/\/ multi-threaded CPU architectures. \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TMatrix.h\"\n#include \"TMVA\/DNN\/Architectures\/Cpu.h\"\n#include \"TestBackpropagation.h\"\n\nusing namespace TMVA::DNN;\n\nint main()\n{\n using Scalar_t = Double_t;\n std::cout << \"Testing Backpropagation:\" << std::endl;\n\n double error;\n int iret = 0;\n\n error = testBackpropagationWeightsLinear>(1.0);\n if (error > 1e-3)\n iret++;\n\n error = testBackpropagationL1Regularization>(1e-2);\n if (error > 1e-3)\n iret++;\n\n error = testBackpropagationL2Regularization>(1.0);\n if (error > 1e-3)\n iret++;\n\n error = testBackpropagationBiasesLinear>(1.0);\n if (error > 1e-3)\n iret++;\n\n return iret;\n}\n<|endoftext|>"} {"text":"\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"keeper.hpp\"\n\n#include \n#include \n\n#include \"..\/common\/membership.hpp\"\n#include \"..\/common\/exception.hpp\"\n#include \"server_util.hpp\"\n\nusing namespace jubatus;\nusing namespace jubatus::framework;\n\nkeeper::keeper(const keeper_argv& a)\n : pfi::network::mprpc::rpc_server(a.timeout),\n a_(a),\n zk_(common::create_lock_service(\"cached_zk\", a.z, a.timeout))\n \/\/ zk_(common::create_lock_service(\"zk\", a.z, a.timeout))\n{\n ls = zk_;\n jubatus::common::prepare_jubatus(*zk_);\n if(!register_keeper(*zk_, a_.eth, a_.port) ){\n throw JUBATUS_EXCEPTION(membership_error(\"can't register to zookeeper.\"));\n }\n}\n\nkeeper::~keeper(){\n}\n\nint keeper::run()\n{\n try {\n { LOG(INFO) << \"running in port=\" << a_.port; }\n set_exit_on_term();\n return this->serv(a_.port, a_.threadnum);\n } catch (const jubatus::exception::jubatus_exception& e) {\n std::cout << e.diagnostic_information(true) << std::endl;\n return -1;\n }\n}\n\nvoid keeper::get_members_(const std::string& name, std::vector >& ret){\n using namespace std;\n ret.clear();\n vector list;\n string path = common::ACTOR_BASE_PATH + \"\/\" + name + \"\/nodes\";\n\n {\n pfi::concurrent::scoped_lock lk(mutex_);\n zk_->list(path, list);\n }\n vector::const_iterator it;\n \n \/\/ FIXME:\n \/\/ do you return all server list? it can be very large\n for(it = list.begin(); it!= list.end(); ++it){\n string ip;\n int port;\n common::revert(*it, ip, port);\n ret.push_back(make_pair(ip,port));\n }\n}\nFix ignoring SIGPIPE deleted by 877d3a9086c0e0cc58b07afe32514a0f76fa3a80\/\/ Jubatus: Online machine learning framework for distributed environment\n\/\/ Copyright (C) 2011,2012 Preferred Infrastructure and Nippon Telegraph and Telephone Corporation.\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n\n#include \"keeper.hpp\"\n\n#include \n#include \n\n#include \"..\/common\/membership.hpp\"\n#include \"..\/common\/exception.hpp\"\n#include \"server_util.hpp\"\n\nusing namespace jubatus;\nusing namespace jubatus::framework;\n\nkeeper::keeper(const keeper_argv& a)\n : pfi::network::mprpc::rpc_server(a.timeout),\n a_(a),\n zk_(common::create_lock_service(\"cached_zk\", a.z, a.timeout))\n \/\/ zk_(common::create_lock_service(\"zk\", a.z, a.timeout))\n{\n ls = zk_;\n jubatus::common::prepare_jubatus(*zk_);\n if(!register_keeper(*zk_, a_.eth, a_.port) ){\n throw JUBATUS_EXCEPTION(membership_error(\"can't register to zookeeper.\"));\n }\n}\n\nkeeper::~keeper(){\n}\n\nint keeper::run()\n{\n try {\n { LOG(INFO) << \"running in port=\" << a_.port; }\n set_exit_on_term();\n ignore_sigpipe();\n return this->serv(a_.port, a_.threadnum);\n } catch (const jubatus::exception::jubatus_exception& e) {\n std::cout << e.diagnostic_information(true) << std::endl;\n return -1;\n }\n}\n\nvoid keeper::get_members_(const std::string& name, std::vector >& ret){\n using namespace std;\n ret.clear();\n vector list;\n string path = common::ACTOR_BASE_PATH + \"\/\" + name + \"\/nodes\";\n\n {\n pfi::concurrent::scoped_lock lk(mutex_);\n zk_->list(path, list);\n }\n vector::const_iterator it;\n \n \/\/ FIXME:\n \/\/ do you return all server list? it can be very large\n for(it = list.begin(); it!= list.end(); ++it){\n string ip;\n int port;\n common::revert(*it, ip, port);\n ret.push_back(make_pair(ip,port));\n }\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2016, Jeff Hutchinson\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the project nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/-----------------------------------------------------------------------------\n\n#ifndef _GRAPHICS_CONTEXT_HPP_\n#define _GRAPHICS_CONTEXT_HPP_\n\n#include \"graphics\/renderer.hpp\"\n\nclass Window;\n\nenum ContextAPI : int {\n\tOpenGL,\n\t\/\/ WebGL,\n\tD3D11\n};\n\nclass Context {\npublic:\n\tvoid init(Window *window);\n\tvirtual void destroy() = 0;\n\n\tvirtual void swapBuffers() const = 0;\n\n\tvirtual Renderer* getRenderer() const = 0;\n\nprotected:\n\tRenderer *mRenderer;\n\tWindow *mWindow;\n\t\n\tvirtual void initContext() = 0;\n};\n\nclass ContextFactory {\npublic:\n\tstatic Context* createContext(ContextAPI api);\n\tstatic void releaseContext(Context *context);\n\n\tstatic void setCurrentContext(Context *current);\n};\n\nextern Context *gCurrentContext;\n#define RENDERER gCurrentContext->getRenderer()\n\n#endif \/\/ _GRAPHICS_CONTEXT_HPP_virtual destructor for Context\/\/-----------------------------------------------------------------------------\n\/\/ Copyright (c) 2016, Jeff Hutchinson\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the project nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n\/\/ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\n\/\/ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n\/\/ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n\/\/ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n\/\/ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\n\/\/ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n\/\/ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\/\/-----------------------------------------------------------------------------\n\n#ifndef _GRAPHICS_CONTEXT_HPP_\n#define _GRAPHICS_CONTEXT_HPP_\n\n#include \"graphics\/renderer.hpp\"\n\nclass Window;\n\nenum ContextAPI : int {\n\tOpenGL,\n\t\/\/ WebGL,\n\tD3D11\n};\n\nclass Context {\npublic:\n\tvirtual ~Context() {}\n\t\n\tvoid init(Window *window);\n\tvirtual void destroy() = 0;\n\n\tvirtual void swapBuffers() const = 0;\n\n\tvirtual Renderer* getRenderer() const = 0;\n\nprotected:\n\tRenderer *mRenderer;\n\tWindow *mWindow;\n\t\n\tvirtual void initContext() = 0;\n};\n\nclass ContextFactory {\npublic:\n\tstatic Context* createContext(ContextAPI api);\n\tstatic void releaseContext(Context *context);\n\n\tstatic void setCurrentContext(Context *current);\n};\n\nextern Context *gCurrentContext;\n#define RENDERER gCurrentContext->getRenderer()\n\n#endif \/\/ _GRAPHICS_CONTEXT_HPP_<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \"functions.h\"\n#include \"language-loader.h\"\n#include \"main-screen.h\"\n#include \"models\/image.h\"\n#include \"models\/profile.h\"\n#include \"models\/qml-auth.h\"\n#include \"models\/qml-auth-setting-field.h\"\n#include \"models\/qml-image.h\"\n#include \"models\/qml-site.h\"\n#include \"settings.h\"\n#include \"share\/share-utils.h\"\n#include \"syntax-highlighter-helper.h\"\n\n\n#if defined(Q_OS_ANDROID)\n\t#include \n\t#include \n\t#include \"logger.h\"\n\n\tbool checkPermission(const QString &perm)\n\t{\n\t\tauto already = QtAndroid::checkPermission(perm);\n\t\tif (already == QtAndroid::PermissionResult::Denied) {\n\t\t\tauto results = QtAndroid::requestPermissionsSync(QStringList() << perm);\n\t\t\tif (results[perm] == QtAndroid::PermissionResult::Denied) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n#endif\n\nint main(int argc, char *argv[])\n{\n\tQCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\n\tQGuiApplication app(argc, argv);\n\tapp.setApplicationName(\"Grabber\");\n\tapp.setApplicationVersion(VERSION);\n\tapp.setOrganizationName(\"Bionus\");\n\tapp.setOrganizationDomain(\"bionus.fr.cr\");\n\n\tqmlRegisterType(\"Grabber\", 1, 0, \"ShareUtils\");\n\tqmlRegisterType(\"Grabber\", 1, 0, \"SyntaxHighlighterHelper\");\n\tqRegisterMetaType>(\"QSharedPointer\");\n\tqRegisterMetaType(\"Settings*\");\n\tqRegisterMetaType(\"QmlImage*\");\n\tqRegisterMetaType>(\"QList>QmlImage*>\");\n\tqRegisterMetaType(\"QmlSite*\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType>(\"QList\");\n\n\t\/\/ Copy settings files to writable directory\n\tconst QStringList toCopy { \"sites\/\", \"themes\/\", \"webservices\/\" };\n\tfor (const QString &tgt : toCopy) {\n\t\tconst QString from = savePath(tgt, true, false);\n\t\tconst QString to = savePath(tgt, true, true);\n\t\tif (!QDir(to).exists() && QDir(from).exists()) {\n\t\t\tcopyRecursively(from, to);\n\t\t}\n\t}\n\n\tconst QUrl url(QStringLiteral(\"qrc:\/main-screen.qml\"));\n\n\tQQmlApplicationEngine engine;\n\tQObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {\n\t\tif (!obj && url == objUrl) {\n\t\t\tQCoreApplication::exit(-1);\n\t\t}\n\t}, Qt::QueuedConnection);\n\n\t\/\/ Define a few globals\n\tengine.rootContext()->setContextProperty(\"VERSION\", QString(VERSION));\n\t#ifdef NIGHTLY\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY\", true);\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY_COMMIT\", QString(NIGHTLY_COMMIT));\n\t#else\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY\", false);\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY_COMMIT\", QString());\n\t#endif\n\n\tProfile profile(savePath());\n\tMainScreen mainScreen(&profile, &engine);\n\tengine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);\n\tengine.rootContext()->setContextProperty(\"backend\", &mainScreen);\n\n\tSettings settings(profile.getSettings());\n\tengine.rootContext()->setContextProperty(\"settings\", &settings);\n\n\t\/\/ Load translations\n\tLanguageLoader languageLoader(savePath(\"languages\/\", true, false));\n\tlanguageLoader.install(qApp);\n\tlanguageLoader.setLanguage(profile.getSettings()->value(\"language\", \"English\").toString());\n\tengine.rootContext()->setContextProperty(\"languageLoader\", &languageLoader);\n\t#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))\n\t\tQObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate);\n\t#endif\n\n\t#if defined(Q_OS_ANDROID)\n\t\tif (!checkPermission(\"android.permission.WRITE_EXTERNAL_STORAGE\")) {\n\t\t\tlog(QStringLiteral(\"Android write permission not granted\"), Logger::Error);\n\t\t}\n\n\t\tif (settings.value(\"Save\/path\").toString().isEmpty()) {\n\t\t\tsettings.setValue(\"Save\/path\", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first() + \"\/Grabber\");\n\t\t}\n\t#endif\n\n\tengine.load(url);\n\n\t#if defined(Q_OS_ANDROID)\n\t\tQtAndroid::hideSplashScreen(250);\n\t#endif\n\n\treturn app.exec();\n}\nCopy words.txt file in QML version#include \n#include \n#include \n#include \n#include \n#include \"functions.h\"\n#include \"language-loader.h\"\n#include \"main-screen.h\"\n#include \"models\/image.h\"\n#include \"models\/profile.h\"\n#include \"models\/qml-auth.h\"\n#include \"models\/qml-auth-setting-field.h\"\n#include \"models\/qml-image.h\"\n#include \"models\/qml-site.h\"\n#include \"settings.h\"\n#include \"share\/share-utils.h\"\n#include \"syntax-highlighter-helper.h\"\n\n\n#if defined(Q_OS_ANDROID)\n\t#include \n\t#include \n\t#include \"logger.h\"\n\n\tbool checkPermission(const QString &perm)\n\t{\n\t\tauto already = QtAndroid::checkPermission(perm);\n\t\tif (already == QtAndroid::PermissionResult::Denied) {\n\t\t\tauto results = QtAndroid::requestPermissionsSync(QStringList() << perm);\n\t\t\tif (results[perm] == QtAndroid::PermissionResult::Denied) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\t\treturn true;\n\t}\n#endif\n\nint main(int argc, char *argv[])\n{\n\tQCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);\n\n\tQGuiApplication app(argc, argv);\n\tapp.setApplicationName(\"Grabber\");\n\tapp.setApplicationVersion(VERSION);\n\tapp.setOrganizationName(\"Bionus\");\n\tapp.setOrganizationDomain(\"bionus.fr.cr\");\n\n\tqmlRegisterType(\"Grabber\", 1, 0, \"ShareUtils\");\n\tqmlRegisterType(\"Grabber\", 1, 0, \"SyntaxHighlighterHelper\");\n\tqRegisterMetaType>(\"QSharedPointer\");\n\tqRegisterMetaType(\"Settings*\");\n\tqRegisterMetaType(\"QmlImage*\");\n\tqRegisterMetaType>(\"QList>QmlImage*>\");\n\tqRegisterMetaType(\"QmlSite*\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType>(\"QList\");\n\tqRegisterMetaType>(\"QList\");\n\n\t\/\/ Copy settings files to writable directory\n\tconst QStringList toCopy { \"sites\/\", \"themes\/\", \"webservices\/\" };\n\tfor (const QString &tgt : toCopy) {\n\t\tconst QString from = savePath(tgt, true, false);\n\t\tconst QString to = savePath(tgt, true, true);\n\t\tif (!QDir(to).exists() && QDir(from).exists()) {\n\t\t\tcopyRecursively(from, to);\n\t\t}\n\t}\n\tconst QStringList filesToCopy { \"words.txt\" };\n\tfor (const QString &tgt : filesToCopy) {\n\t\tconst QString from = savePath(tgt, true, false);\n\t\tconst QString to = savePath(tgt, true, true);\n\t\tif (!QFile::exists(to) && QFile::exists(from)) {\n\t\t\tQFile::copy(from, to);\n\t\t}\n\t}\n\n\tconst QUrl url(QStringLiteral(\"qrc:\/main-screen.qml\"));\n\n\tQQmlApplicationEngine engine;\n\tQObject::connect(&engine, &QQmlApplicationEngine::objectCreated, &app, [url](QObject *obj, const QUrl &objUrl) {\n\t\tif (!obj && url == objUrl) {\n\t\t\tQCoreApplication::exit(-1);\n\t\t}\n\t}, Qt::QueuedConnection);\n\n\t\/\/ Define a few globals\n\tengine.rootContext()->setContextProperty(\"VERSION\", QString(VERSION));\n\t#ifdef NIGHTLY\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY\", true);\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY_COMMIT\", QString(NIGHTLY_COMMIT));\n\t#else\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY\", false);\n\t\tengine.rootContext()->setContextProperty(\"NIGHTLY_COMMIT\", QString());\n\t#endif\n\n\tProfile profile(savePath());\n\tMainScreen mainScreen(&profile, &engine);\n\tengine.setObjectOwnership(&mainScreen, QQmlEngine::CppOwnership);\n\tengine.rootContext()->setContextProperty(\"backend\", &mainScreen);\n\n\tSettings settings(profile.getSettings());\n\tengine.rootContext()->setContextProperty(\"settings\", &settings);\n\n\t\/\/ Load translations\n\tLanguageLoader languageLoader(savePath(\"languages\/\", true, false));\n\tlanguageLoader.install(qApp);\n\tlanguageLoader.setLanguage(profile.getSettings()->value(\"language\", \"English\").toString());\n\tengine.rootContext()->setContextProperty(\"languageLoader\", &languageLoader);\n\t#if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0))\n\t\tQObject::connect(&languageLoader, &LanguageLoader::languageChanged, &engine, &QQmlEngine::retranslate);\n\t#endif\n\n\t#if defined(Q_OS_ANDROID)\n\t\tif (!checkPermission(\"android.permission.WRITE_EXTERNAL_STORAGE\")) {\n\t\t\tlog(QStringLiteral(\"Android write permission not granted\"), Logger::Error);\n\t\t}\n\n\t\tif (settings.value(\"Save\/path\").toString().isEmpty()) {\n\t\t\tsettings.setValue(\"Save\/path\", QStandardPaths::standardLocations(QStandardPaths::PicturesLocation).first() + \"\/Grabber\");\n\t\t}\n\t#endif\n\n\tengine.load(url);\n\n\t#if defined(Q_OS_ANDROID)\n\t\tQtAndroid::hideSplashScreen(250);\n\t#endif\n\n\treturn app.exec();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"unit_tests.hpp\"\n\n#include \"test_linearform_ext.hpp\"\n\nusing namespace mfem;\nusing namespace linearform_ext_tests;\n\nnamespace mfem\n{\n\nnamespace linearform_ext_tests\n{\n\nvoid LinearFormExtTest::Description()\n{\n mfem::out << \"[LinearFormExt]\"\n << \" p=\" << p\n << \" q=\" << q\n << \" \"<< dim << \"D\"\n << \" \"<< vdim << \"-\"\n << (problem%2?\"Scalar\":\"Vector\")\n << (problem>2?\"Grad\":\"\")\n \/\/<< (gll ? \"GLL\" : \"GL\")\n << std::endl;\n}\n\nvoid LinearFormExtTest::Run()\n{\n Description();\n AssembleBoth();\n REQUIRE((lf_full*lf_full) == MFEM_Approx(lf_legacy*lf_legacy));\n}\n\n} \/\/ namespace linearform_ext_tests\n\n} \/\/ namespace mfem\n\nTEST_CASE(\"Linear Form Extension\", \"[LinearformExt], [CUDA]\")\n{\n const auto N = GENERATE(2,3,4);\n const auto dim = GENERATE(2,3);\n const auto order = GENERATE(1,2,3);\n const auto gll = GENERATE(false,true); \/\/ q=p+2, q=p+1\n\n SECTION(\"Scalar\")\n {\n const auto vdim = 1;\n const auto problem = GENERATE(LinearFormExtTest::DomainLF,\n LinearFormExtTest::DomainLFGrad);\n LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();\n }\n\n SECTION(\"Vector\")\n {\n const auto vdim = GENERATE(1,2,24);\n const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF,\n LinearFormExtTest::VectorDomainLFGrad);\n LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();\n }\n\n} \/\/ test case\n\nInclude fix\/\/ Copyright (c) 2010-2021, Lawrence Livermore National Security, LLC. Produced\n\/\/ at the Lawrence Livermore National Laboratory. All Rights reserved. See files\n\/\/ LICENSE and NOTICE for details. LLNL-CODE-806117.\n\/\/\n\/\/ This file is part of the MFEM library. For more information and source code\n\/\/ availability visit https:\/\/mfem.org.\n\/\/\n\/\/ MFEM is free software; you can redistribute it and\/or modify it under the\n\/\/ terms of the BSD-3 license. We welcome feedback and contributions, see file\n\/\/ CONTRIBUTING.md for details.\n\n#include \"unit_tests.hpp\"\n\n#include \"tests\/unit\/fem\/test_linearform_ext.hpp\"\n\nusing namespace mfem;\nusing namespace linearform_ext_tests;\n\nnamespace mfem\n{\n\nnamespace linearform_ext_tests\n{\n\nvoid LinearFormExtTest::Description()\n{\n mfem::out << \"[LinearFormExt]\"\n << \" p=\" << p\n << \" q=\" << q\n << \" \"<< dim << \"D\"\n << \" \"<< vdim << \"-\"\n << (problem%2?\"Scalar\":\"Vector\")\n << (problem>2?\"Grad\":\"\")\n \/\/<< (gll ? \"GLL\" : \"GL\")\n << std::endl;\n}\n\nvoid LinearFormExtTest::Run()\n{\n Description();\n AssembleBoth();\n REQUIRE((lf_full*lf_full) == MFEM_Approx(lf_legacy*lf_legacy));\n}\n\n} \/\/ namespace linearform_ext_tests\n\n} \/\/ namespace mfem\n\nTEST_CASE(\"Linear Form Extension\", \"[LinearformExt], [CUDA]\")\n{\n const auto N = GENERATE(2,3,4);\n const auto dim = GENERATE(2,3);\n const auto order = GENERATE(1,2,3);\n const auto gll = GENERATE(false,true); \/\/ q=p+2, q=p+1\n\n SECTION(\"Scalar\")\n {\n const auto vdim = 1;\n const auto problem = GENERATE(LinearFormExtTest::DomainLF,\n LinearFormExtTest::DomainLFGrad);\n LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();\n }\n\n SECTION(\"Vector\")\n {\n const auto vdim = GENERATE(1,2,24);\n const auto problem = GENERATE(LinearFormExtTest::VectorDomainLF,\n LinearFormExtTest::VectorDomainLFGrad);\n LinearFormExtTest(N, dim, vdim, gll, problem, order, true).Run();\n }\n\n} \/\/ test case\n\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2014 pl8787\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nvoid create_fixed_data_kernel_small(CFeatures*& features_p,\n\t\tCFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)\n{\n\tindex_t m=2;\n\tindex_t d=3;\n\n\tSGMatrix p(d,2*m);\n\tfor (index_t i=0; i<2*d*m; ++i)\n\t\tp.matrix[i]=i;\n\n\/\/\tp.display_matrix(\"p\");\n\n\tSGMatrix q(d,2*m);\n\tfor (index_t i=0; i<2*d*m; ++i)\n\t\tq.matrix[i]=i+10;\n\n\/\/\tq.display_matrix(\"q\");\n\n\tfeatures_p=new CDenseFeatures(p);\n\tfeatures_q=new CDenseFeatures(q);\n\n\tfloat64_t sigma_x=2;\n\tfloat64_t sigma_y=3;\n\tfloat64_t sq_sigma_x_twice=sigma_x*sigma_x*2;\n\tfloat64_t sq_sigma_y_twice=sigma_y*sigma_y*2;\n\n\t\/* shoguns kernel width is different *\/\n\tkernel_p=new CGaussianKernel(10, sq_sigma_x_twice);\n\tkernel_q=new CGaussianKernel(10, sq_sigma_y_twice);\n}\n\nvoid create_fixed_data_kernel_big(CFeatures*& features_p,\n\t\tCFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)\n{\n\tindex_t m=10;\n\tindex_t d=7;\n\n\tSGMatrix p(d,m);\n\tfor (index_t i=0; i q(d,m);\n\tfor (index_t i=0; i(p);\n\tfeatures_q=new CDenseFeatures(q);\n\n\tfloat64_t sigma_x=2;\n\tfloat64_t sigma_y=3;\n\tfloat64_t sq_sigma_x_twice=sigma_x*sigma_x*2;\n\tfloat64_t sq_sigma_y_twice=sigma_y*sigma_y*2;\n\n\t\/* shoguns kernel width is different *\/\n\tkernel_p=new CGaussianKernel(10, sq_sigma_x_twice);\n\tkernel_q=new CGaussianKernel(10, sq_sigma_y_twice);\n}\n\n\/** tests the hsic statistic for a single fixed data case and ensures\n * equality with sma implementation *\/\nTEST(HSICTEST, hsic_fixed)\n{\n\tCFeatures* features_p=NULL;\n\tCFeatures* features_q=NULL;\n\tCKernel* kernel_p=NULL;\n\tCKernel* kernel_q=NULL;\n\tcreate_fixed_data_kernel_small(features_p, features_q, kernel_p, kernel_q);\n\n\tindex_t m=features_p->get_num_vectors();\n\n\tCHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);\n\n\t\/* assert matlab result, note that compute statistic computes m*hsic *\/\n\tfloat64_t difference=hsic->compute_statistic();\n\t\/\/SG_SPRINT(\"hsic fixed: %f\\n\", difference);\n\tEXPECT_NEAR(difference, m*0.164761446385339, 1e-15);\n\n\tSG_UNREF(hsic);\n}\n\nTEST(HSICTEST, hsic_gamma)\n{\n\tCFeatures* features_p=NULL;\n\tCFeatures* features_q=NULL;\n\tCKernel* kernel_p=NULL;\n\tCKernel* kernel_q=NULL;\n\tcreate_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);\n\n\tCHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);\n\n\thsic->set_null_approximation_method(HSIC_GAMMA);\n\tfloat64_t p=hsic->compute_p_value(0.05);\n\t\/\/SG_SPRINT(\"p-value: %f\\n\", p);\n\tEXPECT_NEAR(p, 0.172182287884256, 1e-14);\n\n\tSG_UNREF(hsic);\n}\n\nTEST(HSICTEST, hsic_sample_null)\n{\n\tCFeatures* features_p=NULL;\n\tCFeatures* features_q=NULL;\n\tCKernel* kernel_p=NULL;\n\tCKernel* kernel_q=NULL;\n\tcreate_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);\n\n\tCHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);\n\n\t\/* do sampling null *\/\n\thsic->set_null_approximation_method(PERMUTATION);\n\tfloat64_t p=hsic->compute_p_value(0.05);\n\t\/\/SG_SPRINT(\"p-value: %f\\n\", p);\n\t\/\/EXPECT_NEAR(p, 0.576000, 1e-14);\n\n\t\/* ensure that sampling null of hsic leads to same results as using\n\t * CKernelIndependenceTest *\/\n\tCMath::init_random(1);\n\tfloat64_t mean1=CStatistics::mean(hsic->sample_null());\n\tfloat64_t var1=CStatistics::variance(hsic->sample_null());\n\t\/\/SG_SPRINT(\"mean1=%f, var1=%f\\n\", mean1, var1);\n\n\tCMath::init_random(1);\n\tfloat64_t mean2=CStatistics::mean(\n\t\t\thsic->CKernelIndependenceTest::sample_null());\n\tfloat64_t var2=CStatistics::variance(hsic->sample_null());\n\t\/\/SG_SPRINT(\"mean2=%f, var2=%f\\n\", mean2, var2);\n\n\t\/* assert than results are the same from bot sampling null impl. *\/\n\tEXPECT_NEAR(mean1, mean2, 1e-7);\n\tEXPECT_NEAR(var1, var2, 1e-7);\n\n\tSG_UNREF(hsic);\n}\n\nCode format modify.\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2014 pl8787\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace shogun;\n\nvoid create_fixed_data_kernel_small(CFeatures*& features_p,\n\t\tCFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)\n{\n\tindex_t m=2;\n\tindex_t d=3;\n\n\tSGMatrix p(d,2*m);\n\tfor (index_t i=0; i<2*d*m; ++i)\n\t\tp.matrix[i]=i;\n\n\tSGMatrix q(d,2*m);\n\tfor (index_t i=0; i<2*d*m; ++i)\n\t\tq.matrix[i]=i+10;\n\n\tfeatures_p=new CDenseFeatures(p);\n\tfeatures_q=new CDenseFeatures(q);\n\n\tfloat64_t sigma_x=2;\n\tfloat64_t sigma_y=3;\n\tfloat64_t sq_sigma_x_twice=sigma_x*sigma_x*2;\n\tfloat64_t sq_sigma_y_twice=sigma_y*sigma_y*2;\n\n\t\/* shoguns kernel width is different *\/\n\tkernel_p=new CGaussianKernel(10, sq_sigma_x_twice);\n\tkernel_q=new CGaussianKernel(10, sq_sigma_y_twice);\n}\n\nvoid create_fixed_data_kernel_big(CFeatures*& features_p,\n\t\tCFeatures*& features_q, CKernel*& kernel_p, CKernel*& kernel_q)\n{\n\tindex_t m=10;\n\tindex_t d=7;\n\n\tSGMatrix p(d,m);\n\tfor (index_t i=0; i q(d,m);\n\tfor (index_t i=0; i(p);\n\tfeatures_q=new CDenseFeatures(q);\n\n\tfloat64_t sigma_x=2;\n\tfloat64_t sigma_y=3;\n\tfloat64_t sq_sigma_x_twice=sigma_x*sigma_x*2;\n\tfloat64_t sq_sigma_y_twice=sigma_y*sigma_y*2;\n\n\t\/* shoguns kernel width is different *\/\n\tkernel_p=new CGaussianKernel(10, sq_sigma_x_twice);\n\tkernel_q=new CGaussianKernel(10, sq_sigma_y_twice);\n}\n\n\/** tests the hsic statistic for a single fixed data case and ensures\n * equality with sma implementation *\/\nTEST(HSIC, hsic_fixed)\n{\n\tCFeatures* features_p=NULL;\n\tCFeatures* features_q=NULL;\n\tCKernel* kernel_p=NULL;\n\tCKernel* kernel_q=NULL;\n\tcreate_fixed_data_kernel_small(features_p, features_q, kernel_p, kernel_q);\n\n\tindex_t m=features_p->get_num_vectors();\n\n\tCHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);\n\n\t\/* assert matlab result, note that compute statistic computes m*hsic *\/\n\tfloat64_t difference=hsic->compute_statistic();\n\n\tEXPECT_NEAR(difference, m*0.164761446385339, 1e-15);\n\n\tSG_UNREF(hsic);\n}\n\nTEST(HSIC, hsic_gamma)\n{\n\tCFeatures* features_p=NULL;\n\tCFeatures* features_q=NULL;\n\tCKernel* kernel_p=NULL;\n\tCKernel* kernel_q=NULL;\n\tcreate_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);\n\n\tCHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);\n\n\thsic->set_null_approximation_method(HSIC_GAMMA);\n\tfloat64_t p=hsic->compute_p_value(0.05);\n\n\tEXPECT_NEAR(p, 0.172182287884256, 1e-14);\n\n\tSG_UNREF(hsic);\n}\n\nTEST(HSIC, hsic_sample_null)\n{\n\tCFeatures* features_p=NULL;\n\tCFeatures* features_q=NULL;\n\tCKernel* kernel_p=NULL;\n\tCKernel* kernel_q=NULL;\n\tcreate_fixed_data_kernel_big(features_p, features_q, kernel_p, kernel_q);\n\n\tCHSIC* hsic=new CHSIC(kernel_p, kernel_q, features_p, features_q);\n\n\t\/* do sampling null *\/\n\thsic->set_null_approximation_method(PERMUTATION);\n\thsic->compute_p_value(0.05);\n\n\t\/* ensure that sampling null of hsic leads to same results as using\n\t * CKernelIndependenceTest *\/\n\tCMath::init_random(1);\n\tfloat64_t mean1=CStatistics::mean(hsic->sample_null());\n\tfloat64_t var1=CStatistics::variance(hsic->sample_null());\n\n\tCMath::init_random(1);\n\tfloat64_t mean2=CStatistics::mean(\n\t\t\thsic->CKernelIndependenceTest::sample_null());\n\tfloat64_t var2=CStatistics::variance(hsic->sample_null());\n\n\t\/* assert than results are the same from bot sampling null impl. *\/\n\tEXPECT_NEAR(mean1, mean2, 1e-7);\n\tEXPECT_NEAR(var1, var2, 1e-7);\n\n\tSG_UNREF(hsic);\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2011 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef STORE_WATCHER_HPP\n#define STORE_WATCHER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace zippylog {\n\n\/\/\/ Parameters to instantiate a StoreWatcher class\nclass ZIPPYLOG_EXPORT StoreWatcherStartParams {\npublic:\n \/\/\/ 0MQ context to use\n ::zmq::context_t *zctx;\n\n \/\/\/ Store filesystem path to watch\n ::std::string store_path;\n\n \/\/\/ 0MQ socket endpoint to send change notifications to\n ::std::string endpoint;\n\n \/\/\/ 0MQ endpoint to send log messages to\n ::std::string logging_endpoint;\n\n \/\/\/ Semaphore to control whether device should run\n ::zippylog::platform::ConditionalWait *active;\n};\n\n\/\/\/ A directory watcher for file-based stores\n\/\/\/\n\/\/\/ This class watches the specified store directory for changes.\n\/\/\/ When changes are detected, it executes function callbacks, which\n\/\/\/ must be defined in an inherited class.\n\/\/\/\n\/\/\/ The directory watcher is currently designed to execute on its own\n\/\/\/ thread. Just instantiate a directory watcher and invoke Run(). This\n\/\/\/ function will block until the active semaphore contained in the start\n\/\/\/ parameters goes to false.\n\/\/\/\n\/\/\/ @todo move to device namespace\nclass ZIPPYLOG_EXPORT StoreWatcher : public ::zippylog::device::Device {\npublic:\n \/\/\/ Instantiate a store watcher with the given parameters\n \/\/\/\n \/\/\/ Will not actually start the store watcher. To do that, execute\n \/\/\/ Run().\n \/\/\/\n \/\/\/ @param params Parameters to construct watcher with\n StoreWatcher(StoreWatcherStartParams params);\n virtual ~StoreWatcher();\n\n \/\/\/ Performs work\n \/\/\/\n \/\/\/ @param timeout\n ::zippylog::device::PumpResult Pump(int32 timeout = 100000);\n\n \/\/\/@{\n \/\/\/ Device hooks\n virtual void OnRunStart();\n virtual void OnRunFinish();\n \/\/\/@}\n\nprotected:\n \/\/ Function that performs actions when something is created\n \/\/\n \/\/ Receives the path that was added as a store path (e.g.\n \/\/ \"\/bucket\/store\/20101107T1615\") and a stat record that describes\n \/\/ the filesystem entity.\n virtual void HandleAdded(::std::string path, platform::FileStat &stat) = 0;\n\n \/\/\/ Function that performs actions when something is deleted\n \/\/\/\n \/\/\/ @param path The path that was deleted\n virtual void HandleDeleted(::std::string path) = 0;\n\n \/\/\/ Performs actions when something (probably a stream) is modified\n \/\/\/\n \/\/\/ @param path The path that was modified\n \/\/\/ @param stat The result of a stat() on the modified path\n virtual void HandleModified(::std::string path, platform::FileStat &stat) = 0;\n\n \/\/\/ Sends a change notification across the socket\n \/\/\/\n \/\/\/ @param e Envelope to send\n void SendChangeMessage(Envelope &e);\n\n \/\/\/ The store we are watching\n SimpleDirectoryStore * _store;\n\n \/\/\/ 0MQ context\n ::zmq::context_t *_ctx;\n\n \/\/\/ 0MQ endpoint to send notification messages to\n ::std::string _endpoint;\n\n \/\/\/ 0MQ endpoint to send logging messages to\n ::std::string logging_endpoint;\n\n \/\/\/ Unique identifier of this device\n ::std::string id;\n\n \/\/\/ 0MQ socket we are sending notifications on\n ::zmq::socket_t * socket;\n\n \/\/\/ 0MQ socket we are sending logging messages on\n ::zmq::socket_t * logging_sock;\n\n \/\/\/ The underlying watcher looking for store changes\n platform::DirectoryWatcher watcher;\n\nprivate:\n \/\/ we don't provide these\n StoreWatcher(StoreWatcher const &orig);\n StoreWatcher & operator=(StoreWatcher const &orig);\n\n};\n\n}\n\n#endifdocumentation\/\/ Copyright 2011 Gregory Szorc\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef STORE_WATCHER_HPP\n#define STORE_WATCHER_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace zippylog {\n\n\/\/\/ Parameters to instantiate a StoreWatcher class\nclass ZIPPYLOG_EXPORT StoreWatcherStartParams {\npublic:\n \/\/\/ 0MQ context to use\n ::zmq::context_t *zctx;\n\n \/\/\/ Store filesystem path to watch\n ::std::string store_path;\n\n \/\/\/ 0MQ socket endpoint to send change notifications to\n ::std::string endpoint;\n\n \/\/\/ 0MQ endpoint to send log messages to\n ::std::string logging_endpoint;\n\n \/\/\/ Semaphore to control whether device should run\n ::zippylog::platform::ConditionalWait *active;\n};\n\n\/\/\/ A directory watcher for file-based stores\n\/\/\/\n\/\/\/ This class watches the specified store directory for changes.\n\/\/\/ When changes are detected, it executes function callbacks, which\n\/\/\/ must be defined in an inherited class.\n\/\/\/\n\/\/\/ The directory watcher is currently designed to execute on its own\n\/\/\/ thread. Just instantiate a directory watcher and invoke Run(). This\n\/\/\/ function will block until the active semaphore contained in the start\n\/\/\/ parameters goes to false.\n\/\/\/\n\/\/\/ @todo move to device namespace\nclass ZIPPYLOG_EXPORT StoreWatcher : public ::zippylog::device::Device {\npublic:\n \/\/\/ Instantiate a store watcher with the given parameters\n \/\/\/\n \/\/\/ Will not actually start the store watcher. To do that, execute\n \/\/\/ Run().\n \/\/\/\n \/\/\/ @param params Parameters to construct watcher with\n StoreWatcher(StoreWatcherStartParams params);\n virtual ~StoreWatcher();\n\n \/\/\/ Performs work\n \/\/\/\n \/\/\/ @param timeout\n ::zippylog::device::PumpResult Pump(int32 timeout = 100000);\n\n \/\/\/@{\n \/\/\/ Device hooks\n virtual void OnRunStart();\n virtual void OnRunFinish();\n \/\/\/@}\n\nprotected:\n \/\/\/ Function that performs actions when something is created\n \/\/\/\n \/\/\/ Receives the path that was added as a store path (e.g.\n \/\/\/ \"\/bucket\/store\/20101107T1615\") and a stat record that describes\n \/\/\/ the filesystem entity.\n \/\/\/\n \/\/\/ @param path Store path that was added\n \/\/\/ @param stat Filesystem stat result of new path\n virtual void HandleAdded(::std::string path, platform::FileStat &stat) = 0;\n\n \/\/\/ Function that performs actions when something is deleted\n \/\/\/\n \/\/\/ @param path The path that was deleted\n virtual void HandleDeleted(::std::string path) = 0;\n\n \/\/\/ Performs actions when something (probably a stream) is modified\n \/\/\/\n \/\/\/ @param path The path that was modified\n \/\/\/ @param stat The result of a stat() on the modified path\n virtual void HandleModified(::std::string path, platform::FileStat &stat) = 0;\n\n \/\/\/ Sends a change notification across the socket\n \/\/\/\n \/\/\/ @param e Envelope to send\n void SendChangeMessage(Envelope &e);\n\n \/\/\/ The store we are watching\n SimpleDirectoryStore * _store;\n\n \/\/\/ 0MQ context\n ::zmq::context_t *_ctx;\n\n \/\/\/ 0MQ endpoint to send notification messages to\n ::std::string _endpoint;\n\n \/\/\/ 0MQ endpoint to send logging messages to\n ::std::string logging_endpoint;\n\n \/\/\/ Unique identifier of this device\n ::std::string id;\n\n \/\/\/ 0MQ socket we are sending notifications on\n ::zmq::socket_t * socket;\n\n \/\/\/ 0MQ socket we are sending logging messages on\n ::zmq::socket_t * logging_sock;\n\n \/\/\/ The underlying watcher looking for store changes\n platform::DirectoryWatcher watcher;\n\nprivate:\n \/\/ we don't provide these\n StoreWatcher(StoreWatcher const &orig);\n StoreWatcher & operator=(StoreWatcher const &orig);\n\n};\n\n}\n\n#endif<|endoftext|>"} {"text":"\/*-------------------------------------------------------\n\n Spruce\n Filesystem Wrapper Library for C++11\n\n Copyright (c) 2014, Joseph Davis (@josephdavisco)\n All rights reserved. See LICENSE for license info.\n\n---------------------------------------------------------*\/\n#include \"spruce.hh\"\n\n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n #include \n}\n\/*-------------------------------------------------------\n\n Windows includes\n\n---------------------------------------------------------\nNotes:\n\nPOSIX functions named such as mkdir are deprecated on\nWindows. Functions are prefixed with an underscore (_),\nmkdir() becomes _mkdir().\n\n\"In Windows NT, both the (\\) and (\/) are valid path\ndelimiters in character strings in run-time routines.\"\n\nhttp:\/\/msdn.microsoft.com\/en-us\/library\/\n\n---------------------------------------------------------*\/\n#if defined(_WIN32) || defined(_WIN64)\n#define SPRUCE_WIN\n#include \nauto SPRUCE_CHDIR = _chdir;\nauto SPRUCE_GETCWD = _getcwd;\nauto SPRUCE_RMDIR = _rmdir;\nauto SPRUCE_MKDIR = _mkdir;\n#else\n\/*-------------------------------------------------------\n\n Unix\/Posix includes\n\n---------------------------------------------------------*\/\nextern \"C\" {\n #include \n #include \n}\nauto SPRUCE_CHDIR = chdir;\nauto SPRUCE_GETCWD = getcwd;\nauto SPRUCE_RMDIR = rmdir;\nauto SPRUCE_MKDIR = []( const char* pathTomake )\n{\n return mkdir( pathTomake, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH );\n};\n#endif\n\n\/*-------------------------------------------------------\n class path default constructor\n---------------------------------------------------------*\/\nspruce::path::path()\n{\n path_str = \"\";\n}\n\n\/*-------------------------------------------------------\n class path constructor\n---------------------------------------------------------*\/\nspruce::path::path( std::string path_ ) : path_str( path_ )\n{\n normalize();\n}\n\n\/*-------------------------------------------------------\n class path destructor\n---------------------------------------------------------*\/\nspruce::path::~path()\n{\n}\n\n\/*-------------------------------------------------------\n path.setStr\n---------------------------------------------------------*\/\nvoid spruce::path::setStr( std::string path_ )\n{\n path_str = path_;\n normalize();\n}\n\n\/*-------------------------------------------------------\n path.getStr\n---------------------------------------------------------*\/\nstd::string spruce::path::getStr() const\n{\n return path_str;\n}\n\n\/*-------------------------------------------------------\n class path.split\n---------------------------------------------------------*\/\nstd::vector spruce::path::split()\n{\n std::vector v;\n std::istringstream ss( path_str );\n while ( !ss.eof() )\n {\n std::string temp;\n std::getline( ss, temp, '\/' );\n v.push_back( temp );\n }\n return v;\n}\n\n\/*-------------------------------------------------------\n class path.extension\n---------------------------------------------------------*\/\nstd::string spruce::path::extension()\n{\n size_t dot( path_str.rfind( '.' ) );\n\n if ( dot == std::string::npos )\n {\n return \"\";\n }\n\n return path_str.substr( dot );\n}\n\nvoid spruce::path::append(std::string const & str)\n{\n if(isFile())\n return;\n std::string str_append;\n\n if(str.find('\/') == 0)\n str_append = str.substr(1, str.length());\n else\n str_append = str;\n\n if(path_str.rfind('\/') == path_str.length())\n path_str.append(str_append);\n else\n path_str.append(\"\/\" + str_append);\n}\n\nvoid spruce::path::setExtension(std::string const & str)\n{\n size_t ext = path_str.rfind(extension());\n if(ext == std::string::npos)\n ext = path_str.length();\n path_str = path_str.substr(0, ext) + str;\n}\n\n\/*-------------------------------------------------------\n class path.root\n---------------------------------------------------------*\/\nstd::string spruce::path::root()\n{\n size_t position( path_str.rfind( '\/' ) );\n\n if ( position == std::string::npos )\n {\n return \"\";\n }\n\n return path_str.substr( 0, position );\n}\n\n\/*-------------------------------------------------------\n class path.isFile\n---------------------------------------------------------*\/\nbool spruce::path::isFile() const\n{\n if ( !exists() ) return false;\n\n#ifdef SPRUCE_WIN\n\n struct _stat attributes;\n _stat( path_str.c_str(), &attributes );\n\n#else\n\n struct stat attributes;\n stat( path_str.c_str(), &attributes );\n\n#endif\n\n return S_ISREG( attributes.st_mode ) != 0;\n}\n\n\/*-------------------------------------------------------\n class path.isDir\n---------------------------------------------------------*\/\nbool spruce::path::isDir() const\n{\n if ( !exists() ) return false;\n\n#ifdef SPRUCE_WIN\n\n struct _stat attributes;\n _stat( path_str.c_str(), &attributes );\n\n#else\n\n struct stat attributes;\n stat( path_str.c_str(), &attributes );\n\n#endif\n\n return S_ISDIR( attributes.st_mode ) != 0;\n}\n\n\/*-------------------------------------------------------\n class path.exists\n---------------------------------------------------------*\/\nbool spruce::path::exists() const\n{\n#ifdef SPRUCE_WIN\n struct _stat attributes;\n return _stat( path_str.c_str(), &attributes ) == 0;\n#else\n struct stat attributes;\n return stat( path_str.c_str(), &attributes ) == 0;\n#endif\n}\n\n\/*-------------------------------------------------------\n class path.setAsHome\n---------------------------------------------------------*\/\nvoid spruce::path::setAsHome()\n{\n char* home;\n#ifdef SPRUCE_WIN\n home = std::getenv( \"HOMEPATH\" );\n#else\n home = std::getenv( \"HOME\" );\n#endif\n if ( home != NULL )\n {\n setStr( home );\n }\n}\n\n\/*-------------------------------------------------------\n class path.setAsTemp\n---------------------------------------------------------*\/\nvoid spruce::path::setAsTemp()\n{\n char* cwd = std::getenv( \"TMPDIR\" );\n if ( !cwd ) cwd = std::getenv( \"TEMPDIR\" );\n if ( !cwd ) cwd = std::getenv( \"TMP\" );\n if ( !cwd ) cwd = std::getenv( \"TEMP\" );\n if ( !cwd )\n {\n setStr( \"\/tmp\" );\n }\n else\n {\n setStr( cwd );\n }\n}\n\n\/*-------------------------------------------------------\n class path.setAsCurrent\n---------------------------------------------------------*\/\nvoid spruce::path::setAsCurrent()\n{\n setStr( SPRUCE_GETCWD( NULL, 0 ) );\n}\n\n\/*-------------------------------------------------------\n class path.normalize\n---------------------------------------------------------*\/\nvoid spruce::path::normalize()\n{\n std::replace( path_str.begin(), path_str.end(), '\\\\', '\/' );\n\n if ( path_str.back() == '\/' ) path_str = path_str.substr(0, path_str.length()-1);\n}\n\n\/*-------------------------------------------------------\n ostream operator<< class path\n---------------------------------------------------------*\/\nstd::ostream& operator<<( std::ostream& output, const spruce::path& p )\n{\n return output << p.getStr();\n}\n\n\/*-------------------------------------------------------\n file::remove\n---------------------------------------------------------*\/\nbool spruce::file::remove( const spruce::path& p )\n{\n if ( !p.isFile() || ( std::remove( ( p.getStr() ).c_str() ) != 0 ) )\n return false;\n return true;\n}\n\n\/*-------------------------------------------------------\n file::rename\n---------------------------------------------------------*\/\nbool spruce::file::rename( const spruce::path& source, const spruce::path& dest )\n{\n if ( std::rename( source.getStr().c_str(), dest.getStr().c_str() ) != 0 )\n return false;\n return true;\n}\n\n\/*-------------------------------------------------------\n file::copy\n---------------------------------------------------------*\/\nbool spruce::file::copy( const spruce::path& source, const spruce::path& dest )\n{\n std::ifstream in( source.getStr(), std::ios::binary );\n std::ofstream out( dest.getStr(), std::ios::binary );\n\n out << in.rdbuf();\n if ( out.fail() )\n {\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------\n file::readAsString\n---------------------------------------------------------*\/\nbool spruce::file::readAsString( const spruce::path& p,\n std::string& readTo )\n{\n\n std::ifstream file( p.getStr() );\n std::stringstream ss;\n\n if ( file.is_open() )\n {\n while ( !file.eof() )\n {\n ss << static_cast( file.get() );\n }\n file.close();\n }\n else\n {\n return false;\n }\n\n readTo = ss.str();\n\n return true;\n}\n\n\/*-------------------------------------------------------\n file::writeAsString\n---------------------------------------------------------*\/\nbool spruce::file::writeAsString( const spruce::path& p,\n const std::string& content, bool append )\n{\n\n std::ofstream out;\n\n if ( append )\n {\n out.open( ( p.getStr() ).c_str(),\n std::ios_base::out | std::ios_base::app );\n }\n\n else\n {\n out.open( ( p.getStr() ).c_str() );\n }\n\n if ( out.fail() )\n {\n return false;\n }\n\n out << content;\n\n out.close();\n\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::mkdir\n---------------------------------------------------------*\/\nbool spruce::dir::mkdir( const spruce::path& p )\n{\n if ( SPRUCE_MKDIR( ( p.getStr() ).c_str() ) != 0 )\n {\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::mkdirAll\n---------------------------------------------------------*\/\nbool spruce::dir::mkdirAll( const spruce::path& p )\n{\n size_t pos = 1;\n std::string temp( p.getStr() );\n\n if ( temp == \"\" ) return false;\n\n while ( ( pos = temp.find( '\/', pos + 1 ) ) != std::string::npos )\n {\n if ( ( path( temp.substr( 0, pos ) ) ).exists() ) continue;\n \/\/ if making a directory on the path fails we cannot continue\n if ( SPRUCE_MKDIR( ( temp.substr( 0, pos ) ).c_str() ) != 0 )\n return false;\n }\n\n if ( SPRUCE_MKDIR( temp.c_str() ) != 0 ) return false;\n\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::rmdir\n---------------------------------------------------------*\/\nbool spruce::dir::rmdir( const spruce::path& p )\n{\n if ( SPRUCE_RMDIR( ( p.getStr() ).c_str() ) != 0 )\n {\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::rename\n---------------------------------------------------------*\/\nbool spruce::dir::rename( const spruce::path& source, const spruce::path& dest )\n{\n \/\/ cstdio accepts the name of a file or directory\n return spruce::file::rename( source, dest );\n}\n\n\/*-------------------------------------------------------\n dir::chdir\n---------------------------------------------------------*\/\nbool spruce::dir::chdir( const spruce::path& p )\n{\n if ( SPRUCE_CHDIR( ( p.getStr() ).c_str() ) != 0 ) return false;\n return true;\n}\n\nadded alternative preprocessor macros for to S_ISREG and S_ISDIR\/*-------------------------------------------------------\n\n Spruce\n Filesystem Wrapper Library for C++11\n\n Copyright (c) 2014, Joseph Davis (@josephdavisco)\n All rights reserved. See LICENSE for license info.\n\n---------------------------------------------------------*\/\n#include \"spruce.hh\"\n\n#include \n#include \n#include \n#include \n#include \nextern \"C\" {\n #include \n}\n\/*-------------------------------------------------------\n\n Windows includes\n\n---------------------------------------------------------\nNotes:\n\nPOSIX functions named such as mkdir are deprecated on\nWindows. Functions are prefixed with an underscore (_),\nmkdir() becomes _mkdir().\n\n\"In Windows NT, both the (\\) and (\/) are valid path\ndelimiters in character strings in run-time routines.\"\n\nhttp:\/\/msdn.microsoft.com\/en-us\/library\/\n\n---------------------------------------------------------*\/\n#if defined(_WIN32) || defined(_WIN64)\n#define SPRUCE_WIN\n#include \nauto SPRUCE_CHDIR = _chdir;\nauto SPRUCE_GETCWD = _getcwd;\nauto SPRUCE_RMDIR = _rmdir;\nauto SPRUCE_MKDIR = _mkdir;\n#else\n\/*-------------------------------------------------------\n\n Unix\/Posix includes\n\n---------------------------------------------------------*\/\nextern \"C\" {\n #include \n #include \n}\nauto SPRUCE_CHDIR = chdir;\nauto SPRUCE_GETCWD = getcwd;\nauto SPRUCE_RMDIR = rmdir;\nauto SPRUCE_MKDIR = []( const char* pathTomake )\n{\n return mkdir( pathTomake, S_IRWXU | S_IRWXG | S_IROTH | S_IXOTH );\n};\n#endif\n\n#ifndef S_ISDIR\n#define S_ISDIR(mode) (((mode) & S_IFMT) == S_IFDIR)\n#endif\n\n#ifndef S_ISREG\n#define S_ISREG(mode) (((mode) & S_IFMT) == S_IFREG)\n#endif\n\n\/*-------------------------------------------------------\n class path default constructor\n---------------------------------------------------------*\/\nspruce::path::path()\n{\n path_str = \"\";\n}\n\n\/*-------------------------------------------------------\n class path constructor\n---------------------------------------------------------*\/\nspruce::path::path( std::string path_ ) : path_str( path_ )\n{\n normalize();\n}\n\n\/*-------------------------------------------------------\n class path destructor\n---------------------------------------------------------*\/\nspruce::path::~path()\n{\n}\n\n\/*-------------------------------------------------------\n path.setStr\n---------------------------------------------------------*\/\nvoid spruce::path::setStr( std::string path_ )\n{\n path_str = path_;\n normalize();\n}\n\n\/*-------------------------------------------------------\n path.getStr\n---------------------------------------------------------*\/\nstd::string spruce::path::getStr() const\n{\n return path_str;\n}\n\n\/*-------------------------------------------------------\n class path.split\n---------------------------------------------------------*\/\nstd::vector spruce::path::split()\n{\n std::vector v;\n std::istringstream ss( path_str );\n while ( !ss.eof() )\n {\n std::string temp;\n std::getline( ss, temp, '\/' );\n v.push_back( temp );\n }\n return v;\n}\n\n\/*-------------------------------------------------------\n class path.extension\n---------------------------------------------------------*\/\nstd::string spruce::path::extension()\n{\n size_t dot( path_str.rfind( '.' ) );\n\n if ( dot == std::string::npos )\n {\n return \"\";\n }\n\n return path_str.substr( dot );\n}\n\nvoid spruce::path::append(std::string const & str)\n{\n if(isFile())\n return;\n std::string str_append;\n\n if(str.find('\/') == 0)\n str_append = str.substr(1, str.length());\n else\n str_append = str;\n\n if(path_str.rfind('\/') == path_str.length())\n path_str.append(str_append);\n else\n path_str.append(\"\/\" + str_append);\n}\n\nvoid spruce::path::setExtension(std::string const & str)\n{\n size_t ext = path_str.rfind(extension());\n if(ext == std::string::npos)\n ext = path_str.length();\n path_str = path_str.substr(0, ext) + str;\n}\n\n\/*-------------------------------------------------------\n class path.root\n---------------------------------------------------------*\/\nstd::string spruce::path::root()\n{\n size_t position( path_str.rfind( '\/' ) );\n\n if ( position == std::string::npos )\n {\n return \"\";\n }\n\n return path_str.substr( 0, position );\n}\n\n\/*-------------------------------------------------------\n class path.isFile\n---------------------------------------------------------*\/\nbool spruce::path::isFile() const\n{\n if ( !exists() ) return false;\n\n#ifdef SPRUCE_WIN\n\n struct _stat attributes;\n _stat( path_str.c_str(), &attributes );\n\n#else\n\n struct stat attributes;\n stat( path_str.c_str(), &attributes );\n\n#endif\n\n return S_ISREG( attributes.st_mode ) != 0;\n}\n\n\/*-------------------------------------------------------\n class path.isDir\n---------------------------------------------------------*\/\nbool spruce::path::isDir() const\n{\n if ( !exists() ) return false;\n\n#ifdef SPRUCE_WIN\n\n struct _stat attributes;\n _stat( path_str.c_str(), &attributes );\n\n#else\n\n struct stat attributes;\n stat( path_str.c_str(), &attributes );\n\n#endif\n\n return S_ISDIR( attributes.st_mode ) != 0;\n}\n\n\/*-------------------------------------------------------\n class path.exists\n---------------------------------------------------------*\/\nbool spruce::path::exists() const\n{\n#ifdef SPRUCE_WIN\n struct _stat attributes;\n return _stat( path_str.c_str(), &attributes ) == 0;\n#else\n struct stat attributes;\n return stat( path_str.c_str(), &attributes ) == 0;\n#endif\n}\n\n\/*-------------------------------------------------------\n class path.setAsHome\n---------------------------------------------------------*\/\nvoid spruce::path::setAsHome()\n{\n char* home;\n#ifdef SPRUCE_WIN\n home = std::getenv( \"HOMEPATH\" );\n#else\n home = std::getenv( \"HOME\" );\n#endif\n if ( home != NULL )\n {\n setStr( home );\n }\n}\n\n\/*-------------------------------------------------------\n class path.setAsTemp\n---------------------------------------------------------*\/\nvoid spruce::path::setAsTemp()\n{\n char* cwd = std::getenv( \"TMPDIR\" );\n if ( !cwd ) cwd = std::getenv( \"TEMPDIR\" );\n if ( !cwd ) cwd = std::getenv( \"TMP\" );\n if ( !cwd ) cwd = std::getenv( \"TEMP\" );\n if ( !cwd )\n {\n setStr( \"\/tmp\" );\n }\n else\n {\n setStr( cwd );\n }\n}\n\n\/*-------------------------------------------------------\n class path.setAsCurrent\n---------------------------------------------------------*\/\nvoid spruce::path::setAsCurrent()\n{\n setStr( SPRUCE_GETCWD( NULL, 0 ) );\n}\n\n\/*-------------------------------------------------------\n class path.normalize\n---------------------------------------------------------*\/\nvoid spruce::path::normalize()\n{\n std::replace( path_str.begin(), path_str.end(), '\\\\', '\/' );\n\n if ( path_str.back() == '\/' ) path_str = path_str.substr(0, path_str.length()-1);\n}\n\n\/*-------------------------------------------------------\n ostream operator<< class path\n---------------------------------------------------------*\/\nstd::ostream& operator<<( std::ostream& output, const spruce::path& p )\n{\n return output << p.getStr();\n}\n\n\/*-------------------------------------------------------\n file::remove\n---------------------------------------------------------*\/\nbool spruce::file::remove( const spruce::path& p )\n{\n if ( !p.isFile() || ( std::remove( ( p.getStr() ).c_str() ) != 0 ) )\n return false;\n return true;\n}\n\n\/*-------------------------------------------------------\n file::rename\n---------------------------------------------------------*\/\nbool spruce::file::rename( const spruce::path& source, const spruce::path& dest )\n{\n if ( std::rename( source.getStr().c_str(), dest.getStr().c_str() ) != 0 )\n return false;\n return true;\n}\n\n\/*-------------------------------------------------------\n file::copy\n---------------------------------------------------------*\/\nbool spruce::file::copy( const spruce::path& source, const spruce::path& dest )\n{\n std::ifstream in( source.getStr(), std::ios::binary );\n std::ofstream out( dest.getStr(), std::ios::binary );\n\n out << in.rdbuf();\n if ( out.fail() )\n {\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------\n file::readAsString\n---------------------------------------------------------*\/\nbool spruce::file::readAsString( const spruce::path& p,\n std::string& readTo )\n{\n\n std::ifstream file( p.getStr() );\n std::stringstream ss;\n\n if ( file.is_open() )\n {\n while ( !file.eof() )\n {\n ss << static_cast( file.get() );\n }\n file.close();\n }\n else\n {\n return false;\n }\n\n readTo = ss.str();\n\n return true;\n}\n\n\/*-------------------------------------------------------\n file::writeAsString\n---------------------------------------------------------*\/\nbool spruce::file::writeAsString( const spruce::path& p,\n const std::string& content, bool append )\n{\n\n std::ofstream out;\n\n if ( append )\n {\n out.open( ( p.getStr() ).c_str(),\n std::ios_base::out | std::ios_base::app );\n }\n\n else\n {\n out.open( ( p.getStr() ).c_str() );\n }\n\n if ( out.fail() )\n {\n return false;\n }\n\n out << content;\n\n out.close();\n\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::mkdir\n---------------------------------------------------------*\/\nbool spruce::dir::mkdir( const spruce::path& p )\n{\n if ( SPRUCE_MKDIR( ( p.getStr() ).c_str() ) != 0 )\n {\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::mkdirAll\n---------------------------------------------------------*\/\nbool spruce::dir::mkdirAll( const spruce::path& p )\n{\n size_t pos = 1;\n std::string temp( p.getStr() );\n\n if ( temp == \"\" ) return false;\n\n while ( ( pos = temp.find( '\/', pos + 1 ) ) != std::string::npos )\n {\n if ( ( path( temp.substr( 0, pos ) ) ).exists() ) continue;\n \/\/ if making a directory on the path fails we cannot continue\n if ( SPRUCE_MKDIR( ( temp.substr( 0, pos ) ).c_str() ) != 0 )\n return false;\n }\n\n if ( SPRUCE_MKDIR( temp.c_str() ) != 0 ) return false;\n\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::rmdir\n---------------------------------------------------------*\/\nbool spruce::dir::rmdir( const spruce::path& p )\n{\n if ( SPRUCE_RMDIR( ( p.getStr() ).c_str() ) != 0 )\n {\n return false;\n }\n return true;\n}\n\n\/*-------------------------------------------------------\n dir::rename\n---------------------------------------------------------*\/\nbool spruce::dir::rename( const spruce::path& source, const spruce::path& dest )\n{\n \/\/ cstdio accepts the name of a file or directory\n return spruce::file::rename( source, dest );\n}\n\n\/*-------------------------------------------------------\n dir::chdir\n---------------------------------------------------------*\/\nbool spruce::dir::chdir( const spruce::path& p )\n{\n if ( SPRUCE_CHDIR( ( p.getStr() ).c_str() ) != 0 ) return false;\n return true;\n}\n\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* libwps\n * Copyright (C) 2009, 2011 Alonso Laurent (alonso@loria.fr)\n * Copyright (C) 2006, 2007 Andrew Ziem\n * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)\n * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)\n * Copyright (C) 2003-2005 William Lachance (william.lachance@sympatico.ca)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n *\n * For further information visit http:\/\/libwps.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by\n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n\n#include \n#include \n\n#include \n#include \n\n\n#include \"WPSDebug.h\"\n\n#if defined(DEBUG_WITH_FILES)\nnamespace libwps\n{\nbool DebugFile::open(std::string const &filename)\n{\n\tstd::string name=Debug::flattenFileName(filename);\n\tname += \".ascii\";\n\tm_file.open(name.c_str());\n\treturn m_on = m_file.is_open();\n}\n\nvoid DebugFile::addPos(long pos)\n{\n\tif (!m_on) return;\n\tm_actOffset = pos;\n}\n\nvoid DebugFile::addNote(char const *note)\n{\n\tif (!m_on || note == 0L) return;\n\n\tsize_t numNotes = m_notes.size();\n\n\tif (!numNotes || m_notes[numNotes-1].m_pos != m_actOffset)\n\t{\n\t\tstd::string empty(\"\");\n\t\tm_notes.push_back(NotePos(m_actOffset, empty));\n\t\tnumNotes++;\n\t}\n\n\tm_notes[numNotes-1].m_text += std::string(note);\n}\n\nvoid DebugFile::addDelimiter(long pos, char c)\n{\n\tif (!m_on) return;\n\tstd::string s;\n\ts+=c;\n\tm_notes.push_back(NotePos(pos,s,false));\n}\n\nvoid DebugFile::sort()\n{\n\tif (!m_on) return;\n\tsize_t numNotes = m_notes.size();\n\n\tif (m_actOffset >= 0 && (numNotes == 0 || m_notes[numNotes-1].m_pos != m_actOffset))\n\t{\n\t\tstd::string empty(\"\");\n\t\tm_notes.push_back(NotePos(m_actOffset, empty));\n\t\tnumNotes++;\n\t}\n\n\tNotePos::Map map;\n\tfor (size_t i = 0; i < numNotes; i++) map[m_notes[i]] = 0;\n\n\tsize_t i = 0;\n\tfor (NotePos::Map::iterator it = map.begin(); it != map.end(); i++, it++)\n\t\tm_notes[i] = it->first;\n\tif (i != numNotes) m_notes.resize(i);\n\n\tVec2i::MapX sMap;\n\tsize_t numSkip = m_skipZones.size();\n\tfor (size_t s = 0; s < numSkip; s++) sMap[m_skipZones[s]] = 0;\n\n\ti = 0;\n\tfor (Vec2i::MapX::iterator it = sMap.begin();\n\t it != sMap.end(); i++, it++)\n\t\tm_skipZones[i] = it->first;\n}\n\nvoid DebugFile::write()\n{\n\tif (!m_on || m_input.get() == 0) return;\n\n\tsort();\n\n\tlong readPos = m_input->tell();\n\n\tstd::vector::const_iterator noteIter = m_notes.begin();\n\n\t\/\/! write the notes which does not have any position\n\twhile(noteIter != m_notes.end() && noteIter->m_pos < 0)\n\t{\n\t\tif (!noteIter->m_text.empty())\n\t\t\tstd::cerr << \"DebugFile::write: skipped: \" << noteIter->m_text << std::endl;\n\t\tnoteIter++;\n\t}\n\n\tlong actualPos = 0;\n\tint numSkip = int(m_skipZones.size()), actSkip = (numSkip == 0) ? -1 : 0;\n\tlong actualSkipEndPos = (numSkip == 0) ? -1 : m_skipZones[0].x();\n\n\tm_input->seek(0,WPX_SEEK_SET);\n\tm_file << std::hex << std::right << std::setfill('0') << std::setw(6) << 0 << \" \";\n\n\tdo\n\t{\n\t\tbool printAdr = false;\n\t\tbool stop = false;\n\t\twhile (actualSkipEndPos != -1 && actualPos >= actualSkipEndPos)\n\t\t{\n\t\t\tprintAdr = true;\n\t\t\tactualPos = m_skipZones[size_t(actSkip)].y()+1;\n\t\t\tm_file << \"\\nSkip : \" << std::hex << std::setw(6) << actualSkipEndPos << \"-\"\n\t\t\t << actualPos-1 << \"\\n\\n\";\n\t\t\tm_input->seek(actualPos, WPX_SEEK_SET);\n\t\t\tstop = m_input->atEOS();\n\t\t\tactSkip++;\n\t\t\tactualSkipEndPos = (actSkip < numSkip) ? m_skipZones[size_t(actSkip)].x() : -1;\n\t\t}\n\t\tif (stop) break;\n\t\twhile(noteIter != m_notes.end() && noteIter->m_pos < actualPos)\n\t\t{\n\t\t\tif (!noteIter->m_text.empty())\n\t\t\t\tm_file << \"Skipped: \" << noteIter->m_text << std::endl;\n\t\t\tnoteIter++;\n\t\t}\n\t\tbool printNote = noteIter != m_notes.end() && noteIter->m_pos == actualPos;\n\t\tif (printAdr || (printNote && noteIter->m_breaking))\n\t\t\tm_file << \"\\n\" << std::setw(6) << actualPos << \" \";\n\t\twhile(noteIter != m_notes.end() && noteIter->m_pos == actualPos)\n\t\t{\n\t\t\tif (noteIter->m_text.empty())\n\t\t\t{\n\t\t\t\tnoteIter++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (noteIter->m_breaking)\n\t\t\t\tm_file << \"[\" << noteIter->m_text << \"]\";\n\t\t\telse\n\t\t\t\tm_file << noteIter->m_text;\n\t\t\tnoteIter++;\n\t\t}\n\n\t\tlong ch = libwps::readU8(m_input);\n\t\tm_file << std::setw(2) << ch;\n\t\tactualPos++;\n\n\t}\n\twhile (!m_input->atEOS());\n\n\tm_file << \"\\n\\n\";\n\n\tm_input->seek(readPos,WPX_SEEK_SET);\n\n\tm_actOffset=-1;\n\tm_notes.resize(0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ save WPXBinaryData in a file\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace Debug\n{\nbool dumpFile(WPXBinaryData &data, char const *fileName)\n{\n\tif (!fileName) return false;\n\tstd::string fName = Debug::flattenFileName(fileName);\n\tFILE *file = fopen(fName.c_str(), \"wb\");\n\tif (!file) return false;\n\n\tWPXInputStream *tmpStream =\n\t const_cast(data.getDataStream());\n\twhile (!tmpStream->atEOS())\n\t\tfprintf(file, \"%c\", libwps::readU8(tmpStream));\n\tfclose(file);\n\treturn true;\n}\n\nstd::string flattenFileName(std::string const &name)\n{\n\tstd::string res;\n\tfor (size_t i = 0; i < name.length(); i++)\n\t{\n\t\tchar c = name[i];\n\t\tswitch(c)\n\t\t{\n\t\tcase '\\0':\n\t\tcase '\/':\n\t\tcase '\\\\':\n\t\tcase ':': \/\/ potential file system separator\n\t\tcase ' ':\n\t\tcase '\\t':\n\t\tcase '\\n': \/\/ potential text separator\n\t\t\tres += '_';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (c <= 28) res += '#'; \/\/ potential trouble potential char\n\t\t\telse res += c;\n\t\t}\n\t}\n\treturn res;\n}\n}\n\n}\n#endif\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\nAdd safeguards to prevent problem if we can not read a picture in debug mode...\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*- *\/\n\/* libwps\n * Copyright (C) 2009, 2011 Alonso Laurent (alonso@loria.fr)\n * Copyright (C) 2006, 2007 Andrew Ziem\n * Copyright (C) 2004-2006 Fridrich Strba (fridrich.strba@bluewin.ch)\n * Copyright (C) 2004 Marc Maurer (uwog@uwog.net)\n * Copyright (C) 2003-2005 William Lachance (william.lachance@sympatico.ca)\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA\n *\n * For further information visit http:\/\/libwps.sourceforge.net\n *\/\n\n\/* \"This product is not manufactured, approved, or supported by\n * Corel Corporation or Corel Corporation Limited.\"\n *\/\n\n#include \n#include \n\n#include \n#include \n\n\n#include \"WPSDebug.h\"\n\n#if defined(DEBUG_WITH_FILES)\nnamespace libwps\n{\nbool DebugFile::open(std::string const &filename)\n{\n\tstd::string name=Debug::flattenFileName(filename);\n\tname += \".ascii\";\n\tm_file.open(name.c_str());\n\treturn m_on = m_file.is_open();\n}\n\nvoid DebugFile::addPos(long pos)\n{\n\tif (!m_on) return;\n\tm_actOffset = pos;\n}\n\nvoid DebugFile::addNote(char const *note)\n{\n\tif (!m_on || note == 0L) return;\n\n\tsize_t numNotes = m_notes.size();\n\n\tif (!numNotes || m_notes[numNotes-1].m_pos != m_actOffset)\n\t{\n\t\tstd::string empty(\"\");\n\t\tm_notes.push_back(NotePos(m_actOffset, empty));\n\t\tnumNotes++;\n\t}\n\n\tm_notes[numNotes-1].m_text += std::string(note);\n}\n\nvoid DebugFile::addDelimiter(long pos, char c)\n{\n\tif (!m_on) return;\n\tstd::string s;\n\ts+=c;\n\tm_notes.push_back(NotePos(pos,s,false));\n}\n\nvoid DebugFile::sort()\n{\n\tif (!m_on) return;\n\tsize_t numNotes = m_notes.size();\n\n\tif (m_actOffset >= 0 && (numNotes == 0 || m_notes[numNotes-1].m_pos != m_actOffset))\n\t{\n\t\tstd::string empty(\"\");\n\t\tm_notes.push_back(NotePos(m_actOffset, empty));\n\t\tnumNotes++;\n\t}\n\n\tNotePos::Map map;\n\tfor (size_t i = 0; i < numNotes; i++) map[m_notes[i]] = 0;\n\n\tsize_t i = 0;\n\tfor (NotePos::Map::iterator it = map.begin(); it != map.end(); i++, it++)\n\t\tm_notes[i] = it->first;\n\tif (i != numNotes) m_notes.resize(i);\n\n\tVec2i::MapX sMap;\n\tsize_t numSkip = m_skipZones.size();\n\tfor (size_t s = 0; s < numSkip; s++) sMap[m_skipZones[s]] = 0;\n\n\ti = 0;\n\tfor (Vec2i::MapX::iterator it = sMap.begin();\n\t it != sMap.end(); i++, it++)\n\t\tm_skipZones[i] = it->first;\n}\n\nvoid DebugFile::write()\n{\n\tif (!m_on || m_input.get() == 0) return;\n\n\tsort();\n\n\tlong readPos = m_input->tell();\n\n\tstd::vector::const_iterator noteIter = m_notes.begin();\n\n\t\/\/! write the notes which does not have any position\n\twhile(noteIter != m_notes.end() && noteIter->m_pos < 0)\n\t{\n\t\tif (!noteIter->m_text.empty())\n\t\t\tstd::cerr << \"DebugFile::write: skipped: \" << noteIter->m_text << std::endl;\n\t\tnoteIter++;\n\t}\n\n\tlong actualPos = 0;\n\tint numSkip = int(m_skipZones.size()), actSkip = (numSkip == 0) ? -1 : 0;\n\tlong actualSkipEndPos = (numSkip == 0) ? -1 : m_skipZones[0].x();\n\n\tm_input->seek(0,WPX_SEEK_SET);\n\tm_file << std::hex << std::right << std::setfill('0') << std::setw(6) << 0 << \" \";\n\n\tdo\n\t{\n\t\tbool printAdr = false;\n\t\tbool stop = false;\n\t\twhile (actualSkipEndPos != -1 && actualPos >= actualSkipEndPos)\n\t\t{\n\t\t\tprintAdr = true;\n\t\t\tactualPos = m_skipZones[size_t(actSkip)].y()+1;\n\t\t\tm_file << \"\\nSkip : \" << std::hex << std::setw(6) << actualSkipEndPos << \"-\"\n\t\t\t << actualPos-1 << \"\\n\\n\";\n\t\t\tm_input->seek(actualPos, WPX_SEEK_SET);\n\t\t\tstop = m_input->atEOS();\n\t\t\tactSkip++;\n\t\t\tactualSkipEndPos = (actSkip < numSkip) ? m_skipZones[size_t(actSkip)].x() : -1;\n\t\t}\n\t\tif (stop) break;\n\t\twhile(noteIter != m_notes.end() && noteIter->m_pos < actualPos)\n\t\t{\n\t\t\tif (!noteIter->m_text.empty())\n\t\t\t\tm_file << \"Skipped: \" << noteIter->m_text << std::endl;\n\t\t\tnoteIter++;\n\t\t}\n\t\tbool printNote = noteIter != m_notes.end() && noteIter->m_pos == actualPos;\n\t\tif (printAdr || (printNote && noteIter->m_breaking))\n\t\t\tm_file << \"\\n\" << std::setw(6) << actualPos << \" \";\n\t\twhile(noteIter != m_notes.end() && noteIter->m_pos == actualPos)\n\t\t{\n\t\t\tif (noteIter->m_text.empty())\n\t\t\t{\n\t\t\t\tnoteIter++;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (noteIter->m_breaking)\n\t\t\t\tm_file << \"[\" << noteIter->m_text << \"]\";\n\t\t\telse\n\t\t\t\tm_file << noteIter->m_text;\n\t\t\tnoteIter++;\n\t\t}\n\n\t\tlong ch = libwps::readU8(m_input);\n\t\tm_file << std::setw(2) << ch;\n\t\tactualPos++;\n\n\t}\n\twhile (!m_input->atEOS());\n\n\tm_file << \"\\n\\n\";\n\n\tm_input->seek(readPos,WPX_SEEK_SET);\n\n\tm_actOffset=-1;\n\tm_notes.resize(0);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ save WPXBinaryData in a file\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\nnamespace Debug\n{\nbool dumpFile(WPXBinaryData &data, char const *fileName)\n{\n\tif (!fileName) return false;\n\tstd::string fName = Debug::flattenFileName(fileName);\n\tFILE *file = fopen(fName.c_str(), \"wb\");\n\tif (!file) return false;\n\n\tWPXInputStream *tmpStream =\n\t const_cast(data.getDataStream());\n\tif (!tmpStream) return false;\n\twhile (!tmpStream->atEOS())\n\t\tfprintf(file, \"%c\", libwps::readU8(tmpStream));\n\tfclose(file);\n\treturn true;\n}\n\nstd::string flattenFileName(std::string const &name)\n{\n\tstd::string res;\n\tfor (size_t i = 0; i < name.length(); i++)\n\t{\n\t\tchar c = name[i];\n\t\tswitch(c)\n\t\t{\n\t\tcase '\\0':\n\t\tcase '\/':\n\t\tcase '\\\\':\n\t\tcase ':': \/\/ potential file system separator\n\t\tcase ' ':\n\t\tcase '\\t':\n\t\tcase '\\n': \/\/ potential text separator\n\t\t\tres += '_';\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tif (c <= 28) res += '#'; \/\/ potential trouble potential char\n\t\t\telse res += c;\n\t\t}\n\t}\n\treturn res;\n}\n}\n\n}\n#endif\n\/* vim:set shiftwidth=4 softtabstop=4 noexpandtab: *\/\n<|endoftext|>"} {"text":"#include \"types.hh\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace nix {\n\n\nstatic void sigsegvHandler(int signo, siginfo_t * info, void * ctx)\n{\n \/* Detect stack overflows by comparing the faulting address with\n the stack pointer. Unfortunately, getting the stack pointer is\n not portable. *\/\n bool haveSP = true;\n char * sp = 0;\n#if defined(__x86_64__) && defined(REG_RSP)\n sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_RSP];\n#elif defined(REG_ESP)\n sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_ESP];\n#else\n haveSP = false;\n#endif\n\n if (haveSP) {\n ptrdiff_t diff = (char *) info->si_addr - sp;\n if (diff < 0) diff = -diff;\n if (diff < 4096) {\n char msg[] = \"error: stack overflow (possible infinite recursion)\\n\";\n [[gnu::unused]] auto res = write(2, msg, strlen(msg));\n _exit(1); \/\/ maybe abort instead?\n }\n }\n\n \/* Restore default behaviour (i.e. segfault and dump core). *\/\n struct sigaction act;\n sigfillset(&act.sa_mask);\n act.sa_handler = SIG_DFL;\n act.sa_flags = 0;\n if (sigaction(SIGSEGV, &act, 0)) abort();\n}\n\n\nvoid detectStackOverflow()\n{\n#if defined(SA_SIGINFO) && defined (SA_ONSTACK)\n \/* Install a SIGSEGV handler to detect stack overflows. This\n requires an alternative stack, otherwise the signal cannot be\n delivered when we're out of stack space. *\/\n stack_t stack;\n stack.ss_size = 4096 * 4 + MINSIGSTKSZ;\n static auto stackBuf = std::make_unique>(stack.ss_size);\n stack.ss_sp = stackBuf->data();\n if (!stack.ss_sp) throw Error(\"cannot allocate alternative stack\");\n stack.ss_flags = 0;\n if (sigaltstack(&stack, 0) == -1) throw SysError(\"cannot set alternative stack\");\n\n struct sigaction act;\n sigfillset(&act.sa_mask);\n act.sa_sigaction = sigsegvHandler;\n act.sa_flags = SA_SIGINFO | SA_ONSTACK;\n if (sigaction(SIGSEGV, &act, 0))\n throw SysError(\"resetting SIGCHLD\");\n#endif\n}\n\n\n}\nFix typo#include \"types.hh\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nnamespace nix {\n\n\nstatic void sigsegvHandler(int signo, siginfo_t * info, void * ctx)\n{\n \/* Detect stack overflows by comparing the faulting address with\n the stack pointer. Unfortunately, getting the stack pointer is\n not portable. *\/\n bool haveSP = true;\n char * sp = 0;\n#if defined(__x86_64__) && defined(REG_RSP)\n sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_RSP];\n#elif defined(REG_ESP)\n sp = (char *) ((ucontext_t *) ctx)->uc_mcontext.gregs[REG_ESP];\n#else\n haveSP = false;\n#endif\n\n if (haveSP) {\n ptrdiff_t diff = (char *) info->si_addr - sp;\n if (diff < 0) diff = -diff;\n if (diff < 4096) {\n char msg[] = \"error: stack overflow (possible infinite recursion)\\n\";\n [[gnu::unused]] auto res = write(2, msg, strlen(msg));\n _exit(1); \/\/ maybe abort instead?\n }\n }\n\n \/* Restore default behaviour (i.e. segfault and dump core). *\/\n struct sigaction act;\n sigfillset(&act.sa_mask);\n act.sa_handler = SIG_DFL;\n act.sa_flags = 0;\n if (sigaction(SIGSEGV, &act, 0)) abort();\n}\n\n\nvoid detectStackOverflow()\n{\n#if defined(SA_SIGINFO) && defined (SA_ONSTACK)\n \/* Install a SIGSEGV handler to detect stack overflows. This\n requires an alternative stack, otherwise the signal cannot be\n delivered when we're out of stack space. *\/\n stack_t stack;\n stack.ss_size = 4096 * 4 + MINSIGSTKSZ;\n static auto stackBuf = std::make_unique>(stack.ss_size);\n stack.ss_sp = stackBuf->data();\n if (!stack.ss_sp) throw Error(\"cannot allocate alternative stack\");\n stack.ss_flags = 0;\n if (sigaltstack(&stack, 0) == -1) throw SysError(\"cannot set alternative stack\");\n\n struct sigaction act;\n sigfillset(&act.sa_mask);\n act.sa_sigaction = sigsegvHandler;\n act.sa_flags = SA_SIGINFO | SA_ONSTACK;\n if (sigaction(SIGSEGV, &act, 0))\n throw SysError(\"resetting SIGSEGV\");\n#endif\n}\n\n\n}\n<|endoftext|>"} {"text":"\/* ************************************************************************\n * Copyright 2013 Advanced Micro Devices, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ************************************************************************\/\n\n\n\/\/ clfft.repo.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"repo.h\"\n\nusing std::map;\nusing std::string;\n\n\/\/\tStatic initialization of the repo lock variable\nlockRAII FFTRepo::lockRepo( _T( \"FFTRepo\" ) );\n\n\/\/\tStatic initialization of the plan count variable\nsize_t FFTRepo::planCount\t= 1;\n\n\/\/\tHandle\/Address of the dynamic module that contains the timer, that we discover and load during runtime\nvoid* FFTRepo::timerHandle\t= NULL;\nGpuStatTimer* FFTRepo::pStatTimer\t= NULL;\n\n\n\n\nclfftStatus FFTRepo::releaseResources( )\n{\n\tscopedLock sLock( lockRepo, _T( \"releaseResources\" ) );\n\n\t\/\/\tRelease all handles to Kernels\n\t\/\/\n\tfor(Kernel_iterator iKern = mapKernels.begin( ); iKern != mapKernels.end( ); ++iKern )\n\t{\n\t\tcl_kernel k = iKern->second.kernel_fwd;\n\t\tiKern->second.kernel_fwd = NULL;\n\t\tif (NULL != k)\n\t\t\tclReleaseKernel( k );\n\t\tk = iKern->second.kernel_back;\n\t\tiKern->second.kernel_back = NULL;\n\t\tif (NULL != k)\n\t\t\tclReleaseKernel( k );\n\n\t\tif (NULL != iKern->second.kernel_fwd_lock)\n\t\t{\n\t\t\tdelete iKern->second.kernel_fwd_lock;\n\t\t\tiKern->second.kernel_fwd_lock = NULL;\n\t\t}\n\n\t\tif (NULL != iKern->second.kernel_back_lock)\n\t\t{\n\t\t\tdelete iKern->second.kernel_back_lock;\n\t\t\tiKern->second.kernel_back_lock = NULL;\n\t\t}\n\t}\n\tmapKernels.clear( );\n\n\t\/\/\tRelease all handles to programs\n\t\/\/\n\tfor (fftRepo_iterator iProg = mapFFTs.begin( ); iProg != mapFFTs.end( ); ++iProg )\n\t{\n if (iProg->first.data != NULL)\n {\n const_cast(&iProg->first)->deleteData();\n }\n\n\t\tcl_program p = iProg->second.clProgram;\n\t\tiProg->second.clProgram = NULL;\n\t\tif (NULL != p)\n\t\t\tclReleaseProgram (p);\n\t}\n\n\t\/\/\tFree all memory allocated in the repoPlans; represents cached plans that were not destroyed by the client\n\t\/\/\n\tfor( repoPlansType::iterator iter = repoPlans.begin( ); iter != repoPlans.end( ); ++iter )\n\t{\n\t\tFFTPlan* plan\t= iter->second.first;\n\t\tlockRAII* lock\t= iter->second.second;\n\t\tif( plan != NULL )\n\t\t{\n\t\t\tdelete plan;\n\t\t}\n\t\tif( lock != NULL )\n\t\t{\n\t\t\tdelete lock;\n\t\t}\n\t}\n\n\t\/\/\tReset the plan count to zero because we are guaranteed to have destroyed all plans\n\tplanCount\t= 1;\n\n\t\/\/\tRelease all strings\n\tmapFFTs.clear( );\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const std::string& kernel, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"setProgramCode\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n key.privatizeData();\n\n\t\/\/ Prefix copyright statement at the top of generated kernels\n\tstd::stringstream ss;\n\tss << \n\t\t\"\/* ************************************************************************\\n\"\n\t\t\" * Copyright 2013 Advanced Micro Devices, Inc.\\n\"\n\t\t\" *\\n\"\n\t\t\" * Licensed under the Apache License, Version 2.0 (the \\\"License\\\");\\n\"\n\t\t\" * you may not use this file except in compliance with the License.\\n\"\n\t\t\" * You may obtain a copy of the License at\\n\"\n\t\t\" *\\n\"\n\t\t\" * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\\n\"\n\t\t\" *\\n\"\n\t\t\" * Unless required by applicable law or agreed to in writing, software\\n\"\n\t\t\" * distributed under the License is distributed on an \\\"AS IS\\\" BASIS,\\n\"\n\t\t\" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n\"\n\t\t\" * See the License for the specific language governing permissions and\\n\"\n\t\t\" * limitations under the License.\\n\"\n\t\t\" * ************************************************************************\/\"\n\t<< std::endl << std::endl;\n\n\tstd::string prefixCopyright = ss.str();\n\n\tmapFFTs[ key ].ProgramString = prefixCopyright + kernel;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, std::string& kernel, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"getProgramCode\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key);\n\tif( pos == mapFFTs.end( ) )\n\t\treturn\tCLFFT_FILE_NOT_FOUND;\n\n kernel = pos->second.ProgramString;\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setProgramEntryPoints( const clfftGenerators gen, const FFTKernelSignatureHeader * data,\n\tconst char * kernel_fwd, const char * kernel_back, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"setProgramEntryPoints\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepoValue& fft = mapFFTs[ key ];\n\tfft.EntryPoint_fwd = kernel_fwd;\n\tfft.EntryPoint_back = kernel_back;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getProgramEntryPoint( const clfftGenerators gen, const FFTKernelSignatureHeader * data,\n\t\t\tclfftDirection dir, std::string& kernel, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"getProgramEntryPoint\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key );\n\tif( pos == mapFFTs.end( ) )\n\t\treturn\tCLFFT_FILE_NOT_FOUND;\n\n\tswitch (dir) {\n\tcase CLFFT_FORWARD:\n\t\tkernel = pos->second.EntryPoint_fwd;\n\t\tbreak;\n\tcase CLFFT_BACKWARD:\n\t\tkernel = pos->second.EntryPoint_back;\n\t\tbreak;\n\tdefault:\n\t\tassert (false);\n\t\treturn CLFFT_INVALID_ARG_VALUE;\n\t}\n\n\tif (0 == kernel.size())\n\t\treturn\tCLFFT_FILE_NOT_FOUND;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const cl_program& prog, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"setclProgram\" ) );\n\n \tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key );\n\tif( pos == mapFFTs.end( ) )\n\t{\n\t\tkey.privatizeData(); \/\/ the key owns the data\n\t\tmapFFTs[ key ].clProgram = prog;\n\t}\n\telse {\n\t\tcl_program p = pos->second.clProgram;\n\t\tassert (NULL == p);\n\t\tif (NULL != p)\n\t\t\tclReleaseProgram (p);\n\t\tpos->second.clProgram = prog;\n\t}\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, cl_program& prog, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"getclProgram\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key );\n\tif( pos == mapFFTs.end( ) )\n\t\treturn\tCLFFT_INVALID_PROGRAM;\n\tprog = pos->second.clProgram;\n\tif (NULL == prog)\n\t\treturn\tCLFFT_INVALID_PROGRAM;\n \n cl_context progContext;\n clGetProgramInfo(prog, CL_PROGRAM_CONTEXT, sizeof(cl_context), &progContext, NULL);\n if (planContext!=progContext)\n return\tCLFFT_INVALID_PROGRAM;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setclKernel( cl_program prog, clfftDirection dir, const cl_kernel& kernel )\n{\n\tscopedLock sLock( lockRepo, _T( \"setclKernel\" ) );\n\n\tfftKernels & Kernels = mapKernels[ prog ];\n\n\tcl_kernel * pk;\n\tlockRAII ** kernelLock;\n\n\tswitch (dir) {\n\tcase CLFFT_FORWARD:\n\t\tpk = & Kernels.kernel_fwd;\n\t\tkernelLock = & Kernels.kernel_fwd_lock;\n\t\tbreak;\n\tcase CLFFT_BACKWARD:\n\t\tpk = & Kernels.kernel_back;\n\t\tkernelLock = & Kernels.kernel_back_lock;\n\t\tbreak;\n\tdefault:\n\t\tassert (false);\n\t\treturn CLFFT_INVALID_ARG_VALUE;\n\t}\n\n\tassert (NULL == *pk);\n\tif (NULL != *pk)\n\t\tclReleaseKernel( *pk );\n\n\t*pk = kernel;\n\n\tif (NULL != *kernelLock)\n\t\t delete kernelLock;\n\n\t*kernelLock = new lockRAII;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getclKernel( cl_program prog, clfftDirection dir, cl_kernel& kernel, lockRAII*& kernelLock)\n{\n\tscopedLock sLock( lockRepo, _T( \"getclKernel\" ) );\n\n\tKernel_iterator pos = mapKernels.find( prog );\n\tif (pos == mapKernels.end( ) )\n\t\treturn\tCLFFT_INVALID_KERNEL;\n\n\tswitch (dir) {\n\tcase CLFFT_FORWARD:\n\t\tkernel = pos->second.kernel_fwd;\n\t\tkernelLock = pos->second.kernel_fwd_lock;\n\t\tbreak;\n\tcase CLFFT_BACKWARD:\n\t\tkernel = pos->second.kernel_back;\n\t\tkernelLock = pos->second.kernel_back_lock;\n\t\tbreak;\n\tdefault:\n\t\tassert (false);\n\t\treturn CLFFT_INVALID_ARG_VALUE;\n\t}\n\n\tif (NULL == kernel)\n\t\treturn\tCLFFT_INVALID_KERNEL;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::createPlan( clfftPlanHandle* plHandle, FFTPlan*& fftPlan )\n{\n\tscopedLock sLock( lockRepo, _T( \"insertPlan\" ) );\n\n\t\/\/\tWe keep track of this memory in our own collection class, to make sure it's freed in releaseResources\n\t\/\/\tThe lifetime of a plan is tracked by the client and is freed when the client calls ::clfftDestroyPlan()\n\tfftPlan\t= new FFTPlan;\n\n\t\/\/\tWe allocate a new lock here, and expect it to be freed in ::clfftDestroyPlan();\n\t\/\/\tThe lifetime of the lock is the same as the lifetime of the plan\n\tlockRAII* lockPlan\t= new lockRAII;\n\n\t\/\/\tAdd and remember the fftPlan in our map\n\trepoPlans[ planCount ] = std::make_pair( fftPlan, lockPlan );\n\n\t\/\/\tAssign the user handle the plan count (unique identifier), and bump the count for the next plan\n\t*plHandle\t= planCount++;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getPlan( clfftPlanHandle plHandle, FFTPlan*& fftPlan, lockRAII*& planLock )\n{\n\tscopedLock sLock( lockRepo, _T( \"getPlan\" ) );\n\n\t\/\/\tFirst, check if we have already created a plan with this exact same FFTPlan\n\trepoPlansType::iterator iter\t= repoPlans.find( plHandle );\n\tif( iter == repoPlans.end( ) )\n\t\treturn\tCLFFT_INVALID_PLAN;\n\n\t\/\/\tIf plan is valid, return fill out the output pointers\n\tfftPlan\t\t= iter->second.first;\n\tplanLock\t= iter->second.second;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::deletePlan( clfftPlanHandle* plHandle )\n{\n\tscopedLock sLock( lockRepo, _T( \"deletePlan\" ) );\n\n\t\/\/\tFirst, check if we have already created a plan with this exact same FFTPlan\n\trepoPlansType::iterator iter\t= repoPlans.find( *plHandle );\n\tif( iter == repoPlans.end( ) )\n\t\treturn\tCLFFT_INVALID_PLAN;\n\n\t\/\/\tWe lock the plan object while we are in the process of deleting it\n\t{\n\t\tscopedLock sLock( *iter->second.second, _T( \"clfftDestroyPlan\" ) );\n\t\tclReleaseContext( iter->second.first->context );\n\n\t\t\/\/\tDelete the FFTPlan\n\t\tdelete iter->second.first;\n\t}\n\n\t\t\/\/\tDelete the lockRAII\n\tdelete iter->second.second;\n\n\t\/\/\tRemove entry from our map object\n\trepoPlans.erase( iter );\n\n\t\/\/\tClear the client's handle to signify that the plan is gone\n\t*plHandle = 0;\n\n\treturn\tCLFFT_SUCCESS;\n}\nfixing a memory leak issue in key creation, fixes #172\/* ************************************************************************\n * Copyright 2013 Advanced Micro Devices, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * ************************************************************************\/\n\n\n\/\/ clfft.repo.cpp : Defines the entry point for the console application.\n\/\/\n\n#include \"stdafx.h\"\n#include \"repo.h\"\n\nusing std::map;\nusing std::string;\n\n\/\/\tStatic initialization of the repo lock variable\nlockRAII FFTRepo::lockRepo( _T( \"FFTRepo\" ) );\n\n\/\/\tStatic initialization of the plan count variable\nsize_t FFTRepo::planCount\t= 1;\n\n\/\/\tHandle\/Address of the dynamic module that contains the timer, that we discover and load during runtime\nvoid* FFTRepo::timerHandle\t= NULL;\nGpuStatTimer* FFTRepo::pStatTimer\t= NULL;\n\n\n\n\nclfftStatus FFTRepo::releaseResources( )\n{\n\tscopedLock sLock( lockRepo, _T( \"releaseResources\" ) );\n\n\t\/\/\tRelease all handles to Kernels\n\t\/\/\n\tfor(Kernel_iterator iKern = mapKernels.begin( ); iKern != mapKernels.end( ); ++iKern )\n\t{\n\t\tcl_kernel k = iKern->second.kernel_fwd;\n\t\tiKern->second.kernel_fwd = NULL;\n\t\tif (NULL != k)\n\t\t\tclReleaseKernel( k );\n\t\tk = iKern->second.kernel_back;\n\t\tiKern->second.kernel_back = NULL;\n\t\tif (NULL != k)\n\t\t\tclReleaseKernel( k );\n\n\t\tif (NULL != iKern->second.kernel_fwd_lock)\n\t\t{\n\t\t\tdelete iKern->second.kernel_fwd_lock;\n\t\t\tiKern->second.kernel_fwd_lock = NULL;\n\t\t}\n\n\t\tif (NULL != iKern->second.kernel_back_lock)\n\t\t{\n\t\t\tdelete iKern->second.kernel_back_lock;\n\t\t\tiKern->second.kernel_back_lock = NULL;\n\t\t}\n\t}\n\tmapKernels.clear( );\n\n\t\/\/\tRelease all handles to programs\n\t\/\/\n\tfor (fftRepo_iterator iProg = mapFFTs.begin( ); iProg != mapFFTs.end( ); ++iProg )\n\t{\n if (iProg->first.data != NULL)\n {\n const_cast(&iProg->first)->deleteData();\n }\n\n\t\tcl_program p = iProg->second.clProgram;\n\t\tiProg->second.clProgram = NULL;\n\t\tif (NULL != p)\n\t\t\tclReleaseProgram (p);\n\t}\n\n\t\/\/\tFree all memory allocated in the repoPlans; represents cached plans that were not destroyed by the client\n\t\/\/\n\tfor( repoPlansType::iterator iter = repoPlans.begin( ); iter != repoPlans.end( ); ++iter )\n\t{\n\t\tFFTPlan* plan\t= iter->second.first;\n\t\tlockRAII* lock\t= iter->second.second;\n\t\tif( plan != NULL )\n\t\t{\n\t\t\tdelete plan;\n\t\t}\n\t\tif( lock != NULL )\n\t\t{\n\t\t\tdelete lock;\n\t\t}\n\t}\n\n\t\/\/\tReset the plan count to zero because we are guaranteed to have destroyed all plans\n\tplanCount\t= 1;\n\n\t\/\/\tRelease all strings\n\tmapFFTs.clear( );\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const std::string& kernel, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"setProgramCode\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n key.privatizeData();\n\n\t\/\/ Prefix copyright statement at the top of generated kernels\n\tstd::stringstream ss;\n\tss << \n\t\t\"\/* ************************************************************************\\n\"\n\t\t\" * Copyright 2013 Advanced Micro Devices, Inc.\\n\"\n\t\t\" *\\n\"\n\t\t\" * Licensed under the Apache License, Version 2.0 (the \\\"License\\\");\\n\"\n\t\t\" * you may not use this file except in compliance with the License.\\n\"\n\t\t\" * You may obtain a copy of the License at\\n\"\n\t\t\" *\\n\"\n\t\t\" * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\\n\"\n\t\t\" *\\n\"\n\t\t\" * Unless required by applicable law or agreed to in writing, software\\n\"\n\t\t\" * distributed under the License is distributed on an \\\"AS IS\\\" BASIS,\\n\"\n\t\t\" * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\\n\"\n\t\t\" * See the License for the specific language governing permissions and\\n\"\n\t\t\" * limitations under the License.\\n\"\n\t\t\" * ************************************************************************\/\"\n\t<< std::endl << std::endl;\n\n\tstd::string prefixCopyright = ss.str();\n\n\tfftRepoType::iterator it = mapFFTs.find(key);\n\tif (it == mapFFTs.end())\n\t\tmapFFTs[key].ProgramString = prefixCopyright + kernel;\n\telse\n\t\tkey.deleteData();\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getProgramCode( const clfftGenerators gen, const FFTKernelSignatureHeader * data, std::string& kernel, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"getProgramCode\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key);\n\tif( pos == mapFFTs.end( ) )\n\t\treturn\tCLFFT_FILE_NOT_FOUND;\n\n kernel = pos->second.ProgramString;\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setProgramEntryPoints( const clfftGenerators gen, const FFTKernelSignatureHeader * data,\n\tconst char * kernel_fwd, const char * kernel_back, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"setProgramEntryPoints\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepoValue& fft = mapFFTs[ key ];\n\tfft.EntryPoint_fwd = kernel_fwd;\n\tfft.EntryPoint_back = kernel_back;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getProgramEntryPoint( const clfftGenerators gen, const FFTKernelSignatureHeader * data,\n\t\t\tclfftDirection dir, std::string& kernel, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"getProgramEntryPoint\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key );\n\tif( pos == mapFFTs.end( ) )\n\t\treturn\tCLFFT_FILE_NOT_FOUND;\n\n\tswitch (dir) {\n\tcase CLFFT_FORWARD:\n\t\tkernel = pos->second.EntryPoint_fwd;\n\t\tbreak;\n\tcase CLFFT_BACKWARD:\n\t\tkernel = pos->second.EntryPoint_back;\n\t\tbreak;\n\tdefault:\n\t\tassert (false);\n\t\treturn CLFFT_INVALID_ARG_VALUE;\n\t}\n\n\tif (0 == kernel.size())\n\t\treturn\tCLFFT_FILE_NOT_FOUND;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, const cl_program& prog, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"setclProgram\" ) );\n\n \tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key );\n\tif( pos == mapFFTs.end( ) )\n\t{\n\t\tkey.privatizeData(); \/\/ the key owns the data\n\t\tmapFFTs[ key ].clProgram = prog;\n\t}\n\telse {\n\t\tcl_program p = pos->second.clProgram;\n\t\tassert (NULL == p);\n\t\tif (NULL != p)\n\t\t\tclReleaseProgram (p);\n\t\tpos->second.clProgram = prog;\n\t}\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getclProgram( const clfftGenerators gen, const FFTKernelSignatureHeader * data, cl_program& prog, const cl_device_id &device, const cl_context& planContext )\n{\n\tscopedLock sLock( lockRepo, _T( \"getclProgram\" ) );\n\n\tFFTRepoKey key(gen, data, planContext, device);\n\n\tfftRepo_iterator pos = mapFFTs.find( key );\n\tif( pos == mapFFTs.end( ) )\n\t\treturn\tCLFFT_INVALID_PROGRAM;\n\tprog = pos->second.clProgram;\n\tif (NULL == prog)\n\t\treturn\tCLFFT_INVALID_PROGRAM;\n \n cl_context progContext;\n clGetProgramInfo(prog, CL_PROGRAM_CONTEXT, sizeof(cl_context), &progContext, NULL);\n if (planContext!=progContext)\n return\tCLFFT_INVALID_PROGRAM;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::setclKernel( cl_program prog, clfftDirection dir, const cl_kernel& kernel )\n{\n\tscopedLock sLock( lockRepo, _T( \"setclKernel\" ) );\n\n\tfftKernels & Kernels = mapKernels[ prog ];\n\n\tcl_kernel * pk;\n\tlockRAII ** kernelLock;\n\n\tswitch (dir) {\n\tcase CLFFT_FORWARD:\n\t\tpk = & Kernels.kernel_fwd;\n\t\tkernelLock = & Kernels.kernel_fwd_lock;\n\t\tbreak;\n\tcase CLFFT_BACKWARD:\n\t\tpk = & Kernels.kernel_back;\n\t\tkernelLock = & Kernels.kernel_back_lock;\n\t\tbreak;\n\tdefault:\n\t\tassert (false);\n\t\treturn CLFFT_INVALID_ARG_VALUE;\n\t}\n\n\tassert (NULL == *pk);\n\tif (NULL != *pk)\n\t\tclReleaseKernel( *pk );\n\n\t*pk = kernel;\n\n\tif (NULL != *kernelLock)\n\t\t delete kernelLock;\n\n\t*kernelLock = new lockRAII;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getclKernel( cl_program prog, clfftDirection dir, cl_kernel& kernel, lockRAII*& kernelLock)\n{\n\tscopedLock sLock( lockRepo, _T( \"getclKernel\" ) );\n\n\tKernel_iterator pos = mapKernels.find( prog );\n\tif (pos == mapKernels.end( ) )\n\t\treturn\tCLFFT_INVALID_KERNEL;\n\n\tswitch (dir) {\n\tcase CLFFT_FORWARD:\n\t\tkernel = pos->second.kernel_fwd;\n\t\tkernelLock = pos->second.kernel_fwd_lock;\n\t\tbreak;\n\tcase CLFFT_BACKWARD:\n\t\tkernel = pos->second.kernel_back;\n\t\tkernelLock = pos->second.kernel_back_lock;\n\t\tbreak;\n\tdefault:\n\t\tassert (false);\n\t\treturn CLFFT_INVALID_ARG_VALUE;\n\t}\n\n\tif (NULL == kernel)\n\t\treturn\tCLFFT_INVALID_KERNEL;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::createPlan( clfftPlanHandle* plHandle, FFTPlan*& fftPlan )\n{\n\tscopedLock sLock( lockRepo, _T( \"insertPlan\" ) );\n\n\t\/\/\tWe keep track of this memory in our own collection class, to make sure it's freed in releaseResources\n\t\/\/\tThe lifetime of a plan is tracked by the client and is freed when the client calls ::clfftDestroyPlan()\n\tfftPlan\t= new FFTPlan;\n\n\t\/\/\tWe allocate a new lock here, and expect it to be freed in ::clfftDestroyPlan();\n\t\/\/\tThe lifetime of the lock is the same as the lifetime of the plan\n\tlockRAII* lockPlan\t= new lockRAII;\n\n\t\/\/\tAdd and remember the fftPlan in our map\n\trepoPlans[ planCount ] = std::make_pair( fftPlan, lockPlan );\n\n\t\/\/\tAssign the user handle the plan count (unique identifier), and bump the count for the next plan\n\t*plHandle\t= planCount++;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::getPlan( clfftPlanHandle plHandle, FFTPlan*& fftPlan, lockRAII*& planLock )\n{\n\tscopedLock sLock( lockRepo, _T( \"getPlan\" ) );\n\n\t\/\/\tFirst, check if we have already created a plan with this exact same FFTPlan\n\trepoPlansType::iterator iter\t= repoPlans.find( plHandle );\n\tif( iter == repoPlans.end( ) )\n\t\treturn\tCLFFT_INVALID_PLAN;\n\n\t\/\/\tIf plan is valid, return fill out the output pointers\n\tfftPlan\t\t= iter->second.first;\n\tplanLock\t= iter->second.second;\n\n\treturn\tCLFFT_SUCCESS;\n}\n\nclfftStatus FFTRepo::deletePlan( clfftPlanHandle* plHandle )\n{\n\tscopedLock sLock( lockRepo, _T( \"deletePlan\" ) );\n\n\t\/\/\tFirst, check if we have already created a plan with this exact same FFTPlan\n\trepoPlansType::iterator iter\t= repoPlans.find( *plHandle );\n\tif( iter == repoPlans.end( ) )\n\t\treturn\tCLFFT_INVALID_PLAN;\n\n\t\/\/\tWe lock the plan object while we are in the process of deleting it\n\t{\n\t\tscopedLock sLock( *iter->second.second, _T( \"clfftDestroyPlan\" ) );\n\t\tclReleaseContext( iter->second.first->context );\n\n\t\t\/\/\tDelete the FFTPlan\n\t\tdelete iter->second.first;\n\t}\n\n\t\t\/\/\tDelete the lockRAII\n\tdelete iter->second.second;\n\n\t\/\/\tRemove entry from our map object\n\trepoPlans.erase( iter );\n\n\t\/\/\tClear the client's handle to signify that the plan is gone\n\t*plHandle = 0;\n\n\treturn\tCLFFT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/*\n\n Copyright (C) 2017 Tadeusz Puźniakowski\n\n This file is part of mhttp.\n\n\tThis program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n\n\tyou can contact me via http:\/\/www.puzniakowski.pl\n\n*\/\n\n#include \"http_session.hpp\"\n#include \"http_memorysessionstorage.hpp\"\n\n#include \"http_request.hpp\"\n#include \"http_response.hpp\"\n\n#include \n#include \n\nnamespace tp {\nnamespace http {\n\n\nstd::string MemorySessionStorage::generateSessionId() {\n\twhile ( true ) {\n\t\tint m = uniform_dist( e1 ) & 0x07fffffff;\n\t\tif ( sessions.count( std::to_string( m ) ) < 1 ) {\n\t\t\treturn std::to_string( m );\n\t\t}\n\t}\n}\n\nSession &MemorySessionStorage::getSessionForRequest ( Request &req ) {\n\tstd::lock_guard guard( session_mutex );\n\tstd::string sid = \"\";\n\tstd::string cookiestring = req.header[\"cookie\"];\n\n\t\/\/std::cout << \"getSessionForRequest cookie: \" << cookiestring << \" ; \" << std::endl;\n\n\tstd::regex pieces_regex( \"sessionId=([0123456789][0123456789]*)\" );\n\tstd::smatch pieces_match;\n\tif ( std::regex_match ( cookiestring, pieces_match, pieces_regex ) ) {\n\t\tfor ( size_t i = 0; i < pieces_match.size(); ++i ) {\n\t\t\tstd::ssub_match sub_match = pieces_match[i];\n\t\t\tauto fsid = sub_match.str();\n\t\t\tif ( sessions.count( fsid ) > 0 ) {\n\t\t\t\tsid = fsid;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\t\/\/std::cout << \"getSessionForRequest cookie - sid: \" << sid << \" ; \" << std::endl;\n\n\t\/\/ std::cout << cookiestring << std::endl;\n\tif ( sid == \"\" ) {\n\t\tsid = generateSessionId();\n\t\tif ((sessions.size() % sessionCleanupCycle) == 0) {\n\t\t\tstd::list < std::string > sessionToDelete;\n\t\t\tfor (auto &s : sessions) {\n\t\t\t\tif (s.second.getSecondsOfLife() > sessionTimeout) {\n\t\t\t\t\tsessionToDelete.push_back(s.first);\n\t\t\t\t}\t\n\t\t\t}\n\t\t\tfor (auto &sidd : sessionToDelete) {\n\t\t\t\tsessions.erase(sidd);\n\t\t\t}\n\t\t}\n\t\tif ((maxSessions == -1) || ((int)sessions.size() > maxSessions)) {\n\t\t\tthrow std::overflow_error(\"could not allocate another session\"); \n\t\t}\n\t\tsessions[sid].setId( sid );\n\t}\n\treturn sessions[sid];\n}\n\n\nvoid MemorySessionStorage::storeSession ( Session session ) {\n\tstd::lock_guard guard( session_mutex );\n\tsessions[session.getId()] = session;\n}\n\n\nt_Response MemorySessionStorage::storeSessionForRequest ( Session session, t_Response &res ) {\n\tstoreSession ( session );\n\tstd::stringstream setcookie;\n\tsetcookie << \"sessionId\" << \"=\" << session.getId();\n\tres.getHeader()[\"set-cookie\"] = setcookie.str();\n\t\/\/std::cout << \"set-cookie header: \" << res.getHeader()[\"set-cookie\"] << std::endl;\n\treturn res;\n}\n\n\nMemorySessionStorage::MemorySessionStorage(int sessionLifeTimeSeconds,int maxSessions_, int sessionCleanupCycle_)\n\t\t : e1( r() ), \n\t\t uniform_dist( 1001, 1 << ( sizeof( int ) * 8 - 2 ) ),\n\t\t sessionTimeout(sessionLifeTimeSeconds),\n\t\t maxSessions(maxSessions_),\n\t\t sessionCleanupCycle(sessionCleanupCycle_) {\n}\n\n\n\n\n\n}\n}\nbugfix in session handling - long info\/*\n\n Copyright (C) 2017 Tadeusz Puźniakowski\n\n This file is part of mhttp.\n\n\tThis program is free software: you can redistribute it and\/or modify\n it under the terms of the GNU Affero General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU Affero General Public License for more details.\n\n You should have received a copy of the GNU Affero General Public License\n along with this program. If not, see .\n\n\tyou can contact me via http:\/\/www.puzniakowski.pl\n\n*\/\n\n#include \"http_session.hpp\"\n#include \"http_memorysessionstorage.hpp\"\n\n#include \"http_request.hpp\"\n#include \"http_response.hpp\"\n\n#include \n#include \n\nnamespace tp {\nnamespace http {\n\n\nstd::string MemorySessionStorage::generateSessionId() {\n\twhile ( true ) {\n\t\tint m = uniform_dist( e1 ) & 0x07fffffff;\n\t\tif ( sessions.count( std::to_string( m ) ) < 1 ) {\n\t\t\treturn std::to_string( m );\n\t\t}\n\t}\n}\n\nSession &MemorySessionStorage::getSessionForRequest ( Request &req ) {\n\tstd::lock_guard guard( session_mutex );\n\tstd::string sid = \"\";\n\tstd::string cookiestring = req.header[\"cookie\"];\n\n\tstd::cout << \"getSessionForRequest cookie: \" << cookiestring << \" ; \" << std::endl;\n\n\tstd::regex pieces_regex( \"sessionId=([0123456789][0123456789]*)\" );\n\tstd::smatch pieces_match;\n\tif ( std::regex_match ( cookiestring, pieces_match, pieces_regex ) ) {\n\t\tfor ( size_t i = 0; i < pieces_match.size(); ++i ) {\n\t\t\tstd::ssub_match sub_match = pieces_match[i];\n\t\t\tauto fsid = sub_match.str();\n\t\t\tif ( sessions.count( fsid ) > 0 ) {\n\t\t\t\tsid = fsid;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\tstd::cout << \"getSessionForRequest cookie - sid: \" << sid << \" ; \" << std::endl;\n\n\t\/\/ std::cout << cookiestring << std::endl;\n\tif ( sid == \"\" ) {\n\t\tsid = generateSessionId();\n\t\tif ((sessions.size() % sessionCleanupCycle) == 0) {\n\t\t\tstd::list < std::string > sessionToDelete;\n\t\t\tfor (auto &s : sessions) {\n\t\t\t\tif (s.second.getSecondsOfLife() > sessionTimeout) {\n\t\t\t\t\tsessionToDelete.push_back(s.first);\n\t\t\t\t}\t\n\t\t\t}\n\t\t\tfor (auto &sidd : sessionToDelete) {\n\t\t\t\tsessions.erase(sidd);\n\t\t\t}\n\t\t}\n\t\tif ((maxSessions == -1) || ((int)sessions.size() > maxSessions)) {\n\t\t\tthrow std::overflow_error(\"could not allocate another session\"); \n\t\t}\n\t\tsessions[sid].setId( sid );\n\t}\n\treturn sessions[sid];\n}\n\n\nvoid MemorySessionStorage::storeSession ( Session session ) {\n\tstd::lock_guard guard( session_mutex );\n\tsessions[session.getId()] = session;\n}\n\n\nt_Response MemorySessionStorage::storeSessionForRequest ( Session session, t_Response &res ) {\n\tstoreSession ( session );\n\tstd::stringstream setcookie;\n\tsetcookie << \"sessionId\" << \"=\" << session.getId();\n\tres.getHeader()[\"set-cookie\"] = setcookie.str();\n\t\/\/std::cout << \"set-cookie header: \" << res.getHeader()[\"set-cookie\"] << std::endl;\n\treturn res;\n}\n\n\nMemorySessionStorage::MemorySessionStorage(int sessionLifeTimeSeconds,int maxSessions_, int sessionCleanupCycle_)\n\t\t : e1( r() ), \n\t\t uniform_dist( 1001, 1 << ( sizeof( int ) * 8 - 2 ) ),\n\t\t sessionTimeout(sessionLifeTimeSeconds),\n\t\t maxSessions(maxSessions_),\n\t\t sessionCleanupCycle(sessionCleanupCycle_) {\n}\n\n\n\n\n\n}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) [2017-2018] SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include \"storage\/Devices\/BlkDeviceImpl.h\"\n#include \"storage\/Filesystems\/ReiserfsImpl.h\"\n#include \"storage\/Utils\/StorageDefines.h\"\n#include \"storage\/Utils\/HumanString.h\"\n#include \"storage\/Utils\/SystemCmd.h\"\n#include \"storage\/FreeInfo.h\"\n#include \"storage\/UsedFeatures.h\"\n\n\nnamespace storage\n{\n\n using namespace std;\n\n\n const char* DeviceTraits::classname = \"Reiserfs\";\n\n\n Reiserfs::Impl::Impl(const xmlNode* node)\n\t: BlkFilesystem::Impl(node)\n {\n }\n\n\n string\n Reiserfs::Impl::get_pretty_classname() const\n {\n\t\/\/ TRANSLATORS: name of object\n\treturn _(\"Reiserfs\").translated;\n }\n\n\n uint64_t\n Reiserfs::Impl::used_features() const\n {\n\treturn UF_REISERFS | BlkFilesystem::Impl::used_features();\n }\n\n\n void\n Reiserfs::Impl::do_create()\n {\n\tconst BlkDevice* blk_device = get_blk_device();\n\n\tstring cmd_line = MKFSREISERFSBIN \" -f -f \" + get_mkfs_options() + \" \" +\n\t quote(blk_device->get_name());\n\n\twait_for_devices();\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n\n\t\/\/ uuid is included in mkfs output\n\n\tprobe_uuid();\n }\n\n\n void\n Reiserfs::Impl::do_set_label() const\n {\n\tconst BlkDevice* blk_device = get_blk_device();\n\n\t\/\/ TODO handle mounted\n\n\tstring cmd_line = TUNEREISERFSBIN \" -l \" + quote(get_label()) + \" \" +\n\t quote(blk_device->get_name());\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n }\n\n\n void\n Reiserfs::Impl::do_set_tune_options() const\n {\n\tconst BlkDevice* blk_device = get_blk_device();\n\n\tstring cmd_line = TUNEREISERFSBIN \" \" + get_tune_options() + \" \" + quote(blk_device->get_name());\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n }\n\n\n void\n Reiserfs::Impl::do_resize(const CommitData& commit_data, const Action::Resize* action) const\n {\n\tconst Reiserfs* reiserfs_rhs = to_reiserfs(action->get_device(commit_data.actiongraph, RHS));\n\n\tconst BlkDevice* blk_device_rhs = reiserfs_rhs->get_impl().get_blk_device();\n\n\tstring cmd_line = REISERFSRESIZEBIN \" -f\";\n\tif (action->resize_mode == ResizeMode::SHRINK)\n\t cmd_line = \"echo y | \" + cmd_line + \" -s \" +\n\t\tto_string(blk_device_rhs->get_size() \/ KiB) + \"K\";\n\tcmd_line += \" \" + quote(action->blk_device->get_name());\n\n\twait_for_devices();\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n }\n\n}\n- fixed message\/*\n * Copyright (c) [2017-2020] SUSE LLC\n *\n * All Rights Reserved.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of version 2 of the GNU General Public License as published\n * by the Free Software Foundation.\n *\n * This program is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for\n * more details.\n *\n * You should have received a copy of the GNU General Public License along\n * with this program; if not, contact Novell, Inc.\n *\n * To contact Novell about this file by physical or electronic mail, you may\n * find current contact information at www.novell.com.\n *\/\n\n\n#include \"storage\/Devices\/BlkDeviceImpl.h\"\n#include \"storage\/Filesystems\/ReiserfsImpl.h\"\n#include \"storage\/Utils\/StorageDefines.h\"\n#include \"storage\/Utils\/HumanString.h\"\n#include \"storage\/Utils\/SystemCmd.h\"\n#include \"storage\/FreeInfo.h\"\n#include \"storage\/UsedFeatures.h\"\n\n\nnamespace storage\n{\n\n using namespace std;\n\n\n const char* DeviceTraits::classname = \"Reiserfs\";\n\n\n Reiserfs::Impl::Impl(const xmlNode* node)\n\t: BlkFilesystem::Impl(node)\n {\n }\n\n\n string\n Reiserfs::Impl::get_pretty_classname() const\n {\n\t\/\/ TRANSLATORS: name of object\n\treturn _(\"ReiserFS\").translated;\n }\n\n\n uint64_t\n Reiserfs::Impl::used_features() const\n {\n\treturn UF_REISERFS | BlkFilesystem::Impl::used_features();\n }\n\n\n void\n Reiserfs::Impl::do_create()\n {\n\tconst BlkDevice* blk_device = get_blk_device();\n\n\tstring cmd_line = MKFSREISERFSBIN \" -f -f \" + get_mkfs_options() + \" \" +\n\t quote(blk_device->get_name());\n\n\twait_for_devices();\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n\n\t\/\/ uuid is included in mkfs output\n\n\tprobe_uuid();\n }\n\n\n void\n Reiserfs::Impl::do_set_label() const\n {\n\tconst BlkDevice* blk_device = get_blk_device();\n\n\t\/\/ TODO handle mounted\n\n\tstring cmd_line = TUNEREISERFSBIN \" -l \" + quote(get_label()) + \" \" +\n\t quote(blk_device->get_name());\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n }\n\n\n void\n Reiserfs::Impl::do_set_tune_options() const\n {\n\tconst BlkDevice* blk_device = get_blk_device();\n\n\tstring cmd_line = TUNEREISERFSBIN \" \" + get_tune_options() + \" \" + quote(blk_device->get_name());\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n }\n\n\n void\n Reiserfs::Impl::do_resize(const CommitData& commit_data, const Action::Resize* action) const\n {\n\tconst Reiserfs* reiserfs_rhs = to_reiserfs(action->get_device(commit_data.actiongraph, RHS));\n\n\tconst BlkDevice* blk_device_rhs = reiserfs_rhs->get_impl().get_blk_device();\n\n\tstring cmd_line = REISERFSRESIZEBIN \" -f\";\n\tif (action->resize_mode == ResizeMode::SHRINK)\n\t cmd_line = \"echo y | \" + cmd_line + \" -s \" +\n\t\tto_string(blk_device_rhs->get_size() \/ KiB) + \"K\";\n\tcmd_line += \" \" + quote(action->blk_device->get_name());\n\n\twait_for_devices();\n\n\tSystemCmd cmd(cmd_line, SystemCmd::DoThrow);\n }\n\n}\n<|endoftext|>"} {"text":"\/**\n * \\file Chebyshev1Filter.cpp\n *\/\n\n#include \n\n#include \"Chebyshev1Filter.h\"\n#include \"IIRFilter.h\"\n\nnamespace\n{\n template\n void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector >& z, std::vector >& p, DataType& k)\n {\n z.clear(); \/\/ no zeros for this filter type\n p.clear();\n if(order == 0)\n {\n k = std::pow(10, (-ripple \/ 20));\n return;\n }\n \n DataType eps = std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0);\n DataType mu = 1.0 \/ order * boost::math::asinh(1 \/ eps);\n \n for(int i = -order+1; i < order; i += 2)\n {\n DataType theta = boost::math::constants::pi() * i \/ (2*order);\n p.push_back(-std::sinh(std::complex(mu, theta)));\n }\n\n std::complex f = 1;\n \n for(int i = 0; i < p.size(); ++i)\n {\n f *= -p[i];\n }\n k = f.real();\n if(order % 2 == 0)\n {\n k = k \/ std::sqrt((1 + eps * eps));\n }\n }\n \n template\n void create_default_chebyshev1_coeffs(int order, DataType ripple, DataType Wn, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(order, ripple, z, p, k);\n DataType warped = 2 * fs * std::tan(boost::math::constants::pi() * Wn \/ fs);\n zpk_lp2lp(warped, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(int i = 0; i < order + 1; ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(int i = 0; i < order; ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n \n template\n void create_bp_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(order\/2, ripple, z, p, k);\n wc1 = 2 * fs * std::tan(boost::math::constants::pi() * wc1 \/ fs);\n wc2 = 2 * fs * std::tan(boost::math::constants::pi() * wc2 \/ fs);\n \n zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(int i = 0; i < order + 1; ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(int i = 0; i < order; ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n \n template\n void create_bs_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(order\/2, ripple, z, p, k);\n wc1 = 2 * fs * std::tan(boost::math::constants::pi() * wc1 \/ fs);\n wc2 = 2 * fs * std::tan(boost::math::constants::pi() * wc2 \/ fs);\n \n zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(int i = 0; i < order + 1; ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(int i = 0; i < order; ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n}\n\nnamespace ATK\n{\n template \n Chebyshev1LowPassCoefficients::Chebyshev1LowPassCoefficients()\n :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1LowPassCoefficients::DataType Chebyshev1LowPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_cut_frequency(DataType cut_frequency)\n {\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev1LowPassCoefficients::DataType Chebyshev1LowPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_order(int order)\n {\n in_order = out_order = order;\n setup();\n }\n \n template \n void Chebyshev1LowPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency \/ input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1HighPassCoefficients::Chebyshev1HighPassCoefficients()\n :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_cut_frequency(DataType cut_frequency)\n {\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev1HighPassCoefficients::DataType Chebyshev1HighPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1HighPassCoefficients::DataType Chebyshev1HighPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1HighPassCoefficients::set_order(int order)\n {\n in_order = out_order = order;\n setup();\n }\n \n template \n void Chebyshev1HighPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) \/ input_sampling_rate, coefficients_in, coefficients_out);\n for(int i = in_order - 1; i >= 0; i -= 2)\n {\n coefficients_in[i] = - coefficients_in[i];\n coefficients_out[i] = - coefficients_out[i];\n }\n }\n \n template \n Chebyshev1BandPassCoefficients::Chebyshev1BandPassCoefficients()\n :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(DataType f0, DataType f1)\n {\n this->cut_frequencies = std::make_pair(f0, f1);\n setup();\n }\n \n template \n std::pair::DataType, typename Chebyshev1BandPassCoefficients::DataType> Chebyshev1BandPassCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1BandPassCoefficients::DataType Chebyshev1BandPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandPassCoefficients::set_order(int order)\n {\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first \/ input_sampling_rate, 2 * cut_frequencies.second \/ input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1BandStopCoefficients::Chebyshev1BandStopCoefficients()\n :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(DataType f0, DataType f1)\n {\n this->cut_frequencies = std::make_pair(f0, f1);\n setup();\n }\n \n template \n std::pair::DataType, typename Chebyshev1BandStopCoefficients::DataType> Chebyshev1BandStopCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1BandStopCoefficients::DataType Chebyshev1BandStopCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandStopCoefficients::set_order(int order)\n {\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first \/ input_sampling_rate, 2 * cut_frequencies.second \/ input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template class Chebyshev1LowPassCoefficients;\n template class Chebyshev1LowPassCoefficients;\n template class Chebyshev1HighPassCoefficients;\n template class Chebyshev1HighPassCoefficients;\n template class Chebyshev1BandPassCoefficients;\n template class Chebyshev1BandPassCoefficients;\n template class Chebyshev1BandStopCoefficients;\n template class Chebyshev1BandStopCoefficients;\n \n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n \n}\nFixing Chebyshev type 1 setup\/**\n * \\file Chebyshev1Filter.cpp\n *\/\n\n#include \n\n#include \"Chebyshev1Filter.h\"\n#include \"IIRFilter.h\"\n\nnamespace\n{\n template\n void create_chebyshev1_analog_coefficients(int order, DataType ripple, std::vector >& z, std::vector >& p, DataType& k)\n {\n z.clear(); \/\/ no zeros for this filter type\n p.clear();\n if(ripple == 0)\n {\n return;\n }\n if(order == 0)\n {\n k = std::pow(10, (-ripple \/ 20));\n return;\n }\n \n DataType eps = std::sqrt(std::pow(10, (0.1 * ripple)) - 1.0);\n DataType mu = 1.0 \/ order * boost::math::asinh(1 \/ eps);\n \n for(int i = -order+1; i < order; i += 2)\n {\n DataType theta = boost::math::constants::pi() * i \/ (2*order);\n p.push_back(-std::sinh(std::complex(mu, theta)));\n }\n\n std::complex f = 1;\n \n for(int i = 0; i < p.size(); ++i)\n {\n f *= -p[i];\n }\n k = f.real();\n if(order % 2 == 0)\n {\n k = k \/ std::sqrt((1 + eps * eps));\n }\n }\n \n template\n void create_default_chebyshev1_coeffs(int order, DataType ripple, DataType Wn, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(order, ripple, z, p, k);\n DataType warped = 2 * fs * std::tan(boost::math::constants::pi() * Wn \/ fs);\n zpk_lp2lp(warped, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(int i = 0; i < order + 1; ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(int i = 0; i < order; ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n \n template\n void create_bp_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(order\/2, ripple, z, p, k);\n wc1 = 2 * fs * std::tan(boost::math::constants::pi() * wc1 \/ fs);\n wc2 = 2 * fs * std::tan(boost::math::constants::pi() * wc2 \/ fs);\n \n zpk_lp2bp(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(int i = 0; i < order + 1; ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(int i = 0; i < order; ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n \n template\n void create_bs_chebyshev1_coeffs(int order, DataType ripple, DataType wc1, DataType wc2, std::vector& coefficients_in, std::vector& coefficients_out)\n {\n std::vector > z;\n std::vector > p;\n DataType k;\n \n int fs = 2;\n create_chebyshev1_analog_coefficients(order\/2, ripple, z, p, k);\n wc1 = 2 * fs * std::tan(boost::math::constants::pi() * wc1 \/ fs);\n wc2 = 2 * fs * std::tan(boost::math::constants::pi() * wc2 \/ fs);\n \n zpk_lp2bs(std::sqrt(wc1 * wc2), wc2 - wc1, z, p, k);\n zpk_bilinear(fs, z, p, k);\n \n boost::math::tools::polynomial b;\n boost::math::tools::polynomial a;\n \n zpk2ba(fs, z, p, k, b, a);\n \n for(int i = 0; i < order + 1; ++i)\n {\n coefficients_in[i] = b[i];\n }\n for(int i = 0; i < order; ++i)\n {\n coefficients_out[i] = -a[i];\n }\n }\n}\n\nnamespace ATK\n{\n template \n Chebyshev1LowPassCoefficients::Chebyshev1LowPassCoefficients()\n :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1LowPassCoefficients::DataType Chebyshev1LowPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_cut_frequency(DataType cut_frequency)\n {\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev1LowPassCoefficients::DataType Chebyshev1LowPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1LowPassCoefficients::set_order(int order)\n {\n in_order = out_order = order;\n setup();\n }\n \n template \n void Chebyshev1LowPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_default_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequency \/ input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1HighPassCoefficients::Chebyshev1HighPassCoefficients()\n :Parent(1, 1), cut_frequency(0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_cut_frequency(DataType cut_frequency)\n {\n this->cut_frequency = cut_frequency;\n setup();\n }\n \n template \n typename Chebyshev1HighPassCoefficients::DataType Chebyshev1HighPassCoefficients::get_cut_frequency() const\n {\n return cut_frequency;\n }\n \n template \n void Chebyshev1HighPassCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1HighPassCoefficients::DataType Chebyshev1HighPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1HighPassCoefficients::set_order(int order)\n {\n in_order = out_order = order;\n setup();\n }\n \n template \n void Chebyshev1HighPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_default_chebyshev1_coeffs(in_order, ripple, (input_sampling_rate - 2 * cut_frequency) \/ input_sampling_rate, coefficients_in, coefficients_out);\n for(int i = in_order - 1; i >= 0; i -= 2)\n {\n coefficients_in[i] = - coefficients_in[i];\n coefficients_out[i] = - coefficients_out[i];\n }\n }\n \n template \n Chebyshev1BandPassCoefficients::Chebyshev1BandPassCoefficients()\n :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_cut_frequencies(DataType f0, DataType f1)\n {\n this->cut_frequencies = std::make_pair(f0, f1);\n setup();\n }\n \n template \n std::pair::DataType, typename Chebyshev1BandPassCoefficients::DataType> Chebyshev1BandPassCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandPassCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1BandPassCoefficients::DataType Chebyshev1BandPassCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandPassCoefficients::set_order(int order)\n {\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n void Chebyshev1BandPassCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_bp_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first \/ input_sampling_rate, 2 * cut_frequencies.second \/ input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template \n Chebyshev1BandStopCoefficients::Chebyshev1BandStopCoefficients()\n :Parent(1, 1), cut_frequencies(0, 0), ripple(0), in_order(1), out_order(1)\n {\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(std::pair cut_frequencies)\n {\n this->cut_frequencies = cut_frequencies;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_cut_frequencies(DataType f0, DataType f1)\n {\n this->cut_frequencies = std::make_pair(f0, f1);\n setup();\n }\n \n template \n std::pair::DataType, typename Chebyshev1BandStopCoefficients::DataType> Chebyshev1BandStopCoefficients::get_cut_frequencies() const\n {\n return cut_frequencies;\n }\n \n template \n void Chebyshev1BandStopCoefficients::set_ripple(DataType ripple)\n {\n this->ripple = ripple;\n setup();\n }\n \n template \n typename Chebyshev1BandStopCoefficients::DataType Chebyshev1BandStopCoefficients::get_ripple() const\n {\n return ripple;\n }\n\n template \n void Chebyshev1BandStopCoefficients::set_order(int order)\n {\n in_order = out_order = 2 * order;\n setup();\n }\n \n template \n void Chebyshev1BandStopCoefficients::setup()\n {\n Parent::setup();\n coefficients_in.assign(in_order+1, 0);\n coefficients_out.assign(out_order, 0);\n \n create_bs_chebyshev1_coeffs(in_order, ripple, 2 * cut_frequencies.first \/ input_sampling_rate, 2 * cut_frequencies.second \/ input_sampling_rate, coefficients_in, coefficients_out);\n }\n \n template class Chebyshev1LowPassCoefficients;\n template class Chebyshev1LowPassCoefficients;\n template class Chebyshev1HighPassCoefficients;\n template class Chebyshev1HighPassCoefficients;\n template class Chebyshev1BandPassCoefficients;\n template class Chebyshev1BandPassCoefficients;\n template class Chebyshev1BandStopCoefficients;\n template class Chebyshev1BandStopCoefficients;\n \n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n template class IIRFilter >;\n \n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n\n#include \"..\/stream\/stream.hh\"\n#include \"..\/stream\/buffer.hh\"\n#include \"..\/non-copyable.hh\"\n#include \"entry.hh\"\n\nnamespace mimosa\n{\n namespace archive\n {\n class Reader : public stream::Stream\n {\n public:\n MIMOSA_DEF_PTR(Reader);\n\n inline Reader() : archive_(archive_read_new()) {}\n inline ~Reader() { archive_read_free(archive_); }\n\n inline operator struct ::archive *() const { return archive_; }\n\n int open(stream::Stream::Ptr input);\n\n int nextHeader(Entry &e);\n\n int64_t read(char *data, uint64_t nbytes) override;\n int64_t write(const char *data, uint64_t nbytes) override;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Filter \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n inline int filterBzip2() { return archive_read_support_filter_bzip2(archive_); }\n inline int filterCompress() { return archive_read_support_filter_compress(archive_); }\n inline int filterGzip() { return archive_read_support_filter_gzip(archive_); }\n inline int filterLrzip() { return archive_read_support_filter_lrzip(archive_); }\n inline int filterLzip() { return archive_read_support_filter_lzip(archive_); }\n inline int filterLzma() { return archive_read_support_filter_lzma(archive_); }\n inline int filterLzop() { return archive_read_support_filter_lzop(archive_); }\n inline int filterNone() { return archive_read_support_filter_none(archive_); }\n inline int filterProgram(const std::string & cmd) {\n return archive_read_support_filter_program(archive_, cmd.c_str());\n }\n inline int filterXz() { return archive_read_support_filter_xz(archive_); }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Format \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n inline int format7zip() { return archive_read_support_format_7zip(archive_); }\n inline int formatAr() { return archive_read_support_format_ar(archive_); }\n inline int formatCpio() { return archive_read_support_format_cpio(archive_); }\n inline int formatGnutar() { return archive_read_support_format_gnutar(archive_); }\n inline int formatIso9660() { return archive_read_support_format_iso9660(archive_); }\n inline int formatMtree() { return archive_read_support_format_mtree(archive_); }\n inline int formatTar() { return archive_read_support_format_tar(archive_); }\n inline int formatXar() { return archive_read_support_format_xar(archive_); }\n inline int formatZip() { return archive_read_support_format_zip(archive_); }\n\n private:\n static int openCb(struct archive *, void *_client_data);\n static ssize_t readCb(struct archive *,\n void *_client_data, const void **_buffer);\n static int closeCb(struct archive *, void *_client_data);\n\n void close() { archive_read_close(archive_); }\n\n struct ::archive *archive_;\n stream::Stream::Ptr stream_;\n stream::Buffer::Ptr buffer_;\n };\n }\n}\nFix warning#pragma once\n\n#include \n\n#include \"..\/stream\/stream.hh\"\n#include \"..\/stream\/buffer.hh\"\n#include \"..\/non-copyable.hh\"\n#include \"entry.hh\"\n\nnamespace mimosa\n{\n namespace archive\n {\n class Reader : public stream::Stream\n {\n public:\n MIMOSA_DEF_PTR(Reader);\n\n inline Reader() : archive_(archive_read_new()) {}\n inline ~Reader() { archive_read_free(archive_); }\n\n inline operator struct ::archive *() const { return archive_; }\n\n int open(stream::Stream::Ptr input);\n\n int nextHeader(Entry &e);\n\n int64_t read(char *data, uint64_t nbytes) override;\n int64_t write(const char *data, uint64_t nbytes) override;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Filter \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n inline int filterBzip2() { return archive_read_support_filter_bzip2(archive_); }\n inline int filterCompress() { return archive_read_support_filter_compress(archive_); }\n inline int filterGzip() { return archive_read_support_filter_gzip(archive_); }\n inline int filterLrzip() { return archive_read_support_filter_lrzip(archive_); }\n inline int filterLzip() { return archive_read_support_filter_lzip(archive_); }\n inline int filterLzma() { return archive_read_support_filter_lzma(archive_); }\n inline int filterLzop() { return archive_read_support_filter_lzop(archive_); }\n inline int filterNone() { return archive_read_support_filter_none(archive_); }\n inline int filterProgram(const std::string & cmd) {\n return archive_read_support_filter_program(archive_, cmd.c_str());\n }\n inline int filterXz() { return archive_read_support_filter_xz(archive_); }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/\/ Format \/\/\/\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n inline int format7zip() { return archive_read_support_format_7zip(archive_); }\n inline int formatAr() { return archive_read_support_format_ar(archive_); }\n inline int formatCpio() { return archive_read_support_format_cpio(archive_); }\n inline int formatGnutar() { return archive_read_support_format_gnutar(archive_); }\n inline int formatIso9660() { return archive_read_support_format_iso9660(archive_); }\n inline int formatMtree() { return archive_read_support_format_mtree(archive_); }\n inline int formatTar() { return archive_read_support_format_tar(archive_); }\n inline int formatXar() { return archive_read_support_format_xar(archive_); }\n inline int formatZip() { return archive_read_support_format_zip(archive_); }\n\n private:\n static int openCb(struct archive *, void *_client_data);\n static ssize_t readCb(struct archive *,\n void *_client_data, const void **_buffer);\n static int closeCb(struct archive *, void *_client_data);\n\n void close() override { archive_read_close(archive_); }\n\n struct ::archive *archive_;\n stream::Stream::Ptr stream_;\n stream::Buffer::Ptr buffer_;\n };\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Archive.h\"\n\n#include \"lib\/7z\/7zCrc.h\"\n\n\/\/ gcc only offers a full c++11 implementation with >= v5.1\n\/\/ codecvt for unicode conversions is not always available\n\/\/ thus use iconv in such cases\n#include \n#if __GNUC_PREREQ(5,1)\n#include \n#else\n#include \n#endif\n\n\n#include \n#include \n#include \n#include \n\nnamespace lib33u\n{\nnamespace util\n{\nnamespace sz\n{\nstruct DefaultAlloc : public ISzAlloc\n{\n DefaultAlloc()\n {\n Alloc = SzAlloc;\n Free = SzFree;\n }\n};\n\nstruct TempAlloc : public ISzAlloc\n{\n TempAlloc()\n {\n Alloc = SzAllocTemp;\n Free = SzFreeTemp;\n }\n};\n\nint SzCrcGenerateTableOnce()\n{\n CrcGenerateTable();\n return 0;\n}\n\nArchive::Data::Data( const std::string& fn )\n{\n \/\/ static int x = SzCrcGenerateTableOnce();\n\n auto wres = InFile_Open( &archive_stream_.file, fn.c_str() );\n if( wres )\n {\n throw std::runtime_error( \"Unable to open archive file\" );\n }\n\n FileInStream_CreateVTable( &archive_stream_ );\n\n LookToRead_CreateVTable( &look_stream_, False );\n look_stream_.realStream = &archive_stream_.s;\n LookToRead_Init( &look_stream_ );\n\n SzArEx_Init( &db_ );\n\n DefaultAlloc default_alloc_;\n TempAlloc temp_alloc_;\n\n auto sres = SzArEx_Open(&db_, &look_stream_.s,\n &default_alloc_, &temp_alloc_);\n if( sres )\n {\n throw std::runtime_error( \"Failed to open archive\" );\n }\n\n struct ArchiveBuffer\n {\n UInt32 block_index_ = 0xFFFFFFFF;\n Byte* out_buffer_ = nullptr;\n size_t out_buffer_size_ = 0;\n\n ~ArchiveBuffer()\n {\n DefaultAlloc default_alloc;\n IAlloc_Free( &default_alloc, out_buffer_ );\n }\n };\n\n#ifdef __linux__\n typedef std::u16string utf16string;\n#else\n typedef std::wstring utf16string;\n#endif\n\n utf16string utf16name;\n auto buffer = std::make_shared();\n\n for( unsigned i = 0; i < db_.NumFiles; ++i )\n {\n size_t len = SzArEx_GetFileNameUtf16( &db_, i, nullptr );\n\n utf16name.resize(len);\n\n SzArEx_GetFileNameUtf16( &db_, i, (UInt16*)utf16name.data() );\n\n\n#if __GNUC_PREREQ(5,1)\n\n std::wstring_convert,\n utf16string::value_type> conversion;\n std::string utf8name = conversion.to_bytes( utf16name );\n\n#else\n\n iconv_t ico = iconv_open(\"UTF8\", \"UTF16\");\n\n size_t out_size = 1024;\n\n char buf [out_size];\n\n char* tmp = buf;\n const char16_t* tmp16 = utf16name.data();\n\n size_t in_size = len*2;\n\n size_t ret = iconv(ico, (char**)&tmp16, &in_size, &tmp, &out_size);\n\n std::string utf8name(buf);\n\n iconv_close(ico);\n\n#endif\n\n while( utf8name.back() == '\\0' )\n utf8name.pop_back();\n\n size_t offset = 0;\n size_t outSizeProcessed = 0;\n\n sres = SzArEx_Extract(&db_, &look_stream_.s, i,\n &buffer->block_index_,\n &buffer->out_buffer_,\n &buffer->out_buffer_size_,\n &offset,\n &outSizeProcessed,\n &default_alloc_,\n &temp_alloc_ );\n\n \/\/ file_index_.try_emplace( utf8name, std::shared_ptr( buffer, buffer->out_buffer_ + offset ), outSizeProcessed );\n file_index_.emplace(utf8name,\n Entry(std::shared_ptr(buffer, buffer->out_buffer_ + offset),\n outSizeProcessed ));\n }\n}\n\nArchive::Entry Archive::Data::read (const std::string& fn) const\n{\n auto it = file_index_.find(fn);\n if (it == file_index_.end())\n {\n throw std::runtime_error(\"Entry not found\");\n }\n return it->second;\n}\n\nArchive::Archive (const std::string& fn)\n : data { std::unique_ptr(new Data(fn)) }\n {\n }\n\nArchive Archive::open (const std::string& fn)\n{\n return Archive( fn );\n}\n\nArchive::Entry Archive::read (const std::string& fn) const\n{\n return data->read( fn );\n}\n} \/* namespace sz *\/\n} \/* namespace util *\/\n} \/* namespace lib33u *\/\nFix segfault in firmware-update for 33u cameras\/*\n * Copyright 2017 The Imaging Source Europe GmbH\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \"Archive.h\"\n\n#include \"lib\/7z\/7zCrc.h\"\n\n\/\/ gcc only offers a full c++11 implementation with >= v5.1\n\/\/ codecvt for unicode conversions is not always available\n\/\/ thus use iconv in such cases\n#include \n#if __GNUC_PREREQ(5,1)\n#include \n#else\n#include \n#endif\n\n\n#include \n#include \n#include \n#include \n\nnamespace lib33u\n{\nnamespace util\n{\nnamespace sz\n{\nstruct DefaultAlloc : public ISzAlloc\n{\n DefaultAlloc()\n {\n Alloc = SzAlloc;\n Free = SzFree;\n }\n};\n\nstruct TempAlloc : public ISzAlloc\n{\n TempAlloc()\n {\n Alloc = SzAllocTemp;\n Free = SzFreeTemp;\n }\n};\n\nint SzCrcGenerateTableOnce()\n{\n CrcGenerateTable();\n return 0;\n}\n\nArchive::Data::Data( const std::string& fn )\n{\n SzCrcGenerateTableOnce();\n\n auto wres = InFile_Open( &archive_stream_.file, fn.c_str() );\n if( wres )\n {\n throw std::runtime_error( \"Unable to open archive file\" );\n }\n\n FileInStream_CreateVTable( &archive_stream_ );\n\n LookToRead_CreateVTable( &look_stream_, False );\n look_stream_.realStream = &archive_stream_.s;\n LookToRead_Init( &look_stream_ );\n\n SzArEx_Init( &db_ );\n\n DefaultAlloc default_alloc_;\n TempAlloc temp_alloc_;\n\n auto sres = SzArEx_Open(&db_, &look_stream_.s,\n &default_alloc_, &temp_alloc_);\n if( sres )\n {\n throw std::runtime_error( \"Failed to open archive\" );\n }\n\n struct ArchiveBuffer\n {\n UInt32 block_index_ = 0xFFFFFFFF;\n Byte* out_buffer_ = nullptr;\n size_t out_buffer_size_ = 0;\n\n ~ArchiveBuffer()\n {\n DefaultAlloc default_alloc;\n IAlloc_Free( &default_alloc, out_buffer_ );\n }\n };\n\n#ifdef __linux__\n typedef std::u16string utf16string;\n#else\n typedef std::wstring utf16string;\n#endif\n\n utf16string utf16name;\n auto buffer = std::make_shared();\n\n for( unsigned i = 0; i < db_.NumFiles; ++i )\n {\n size_t len = SzArEx_GetFileNameUtf16( &db_, i, nullptr );\n\n utf16name.resize(len);\n\n SzArEx_GetFileNameUtf16( &db_, i, (UInt16*)utf16name.data() );\n\n\n#if __GNUC_PREREQ(5,1)\n\n std::wstring_convert,\n utf16string::value_type> conversion;\n std::string utf8name = conversion.to_bytes( utf16name );\n\n#else\n\n iconv_t ico = iconv_open(\"UTF8\", \"UTF16\");\n\n size_t out_size = 1024;\n\n char buf [out_size];\n\n char* tmp = buf;\n const char16_t* tmp16 = utf16name.data();\n\n size_t in_size = len*2;\n\n size_t ret = iconv(ico, (char**)&tmp16, &in_size, &tmp, &out_size);\n\n std::string utf8name(buf);\n\n iconv_close(ico);\n\n#endif\n\n while( utf8name.back() == '\\0' )\n utf8name.pop_back();\n\n size_t offset = 0;\n size_t outSizeProcessed = 0;\n\n sres = SzArEx_Extract(&db_, &look_stream_.s, i,\n &buffer->block_index_,\n &buffer->out_buffer_,\n &buffer->out_buffer_size_,\n &offset,\n &outSizeProcessed,\n &default_alloc_,\n &temp_alloc_ );\n\n \/\/ file_index_.try_emplace( utf8name, std::shared_ptr( buffer, buffer->out_buffer_ + offset ), outSizeProcessed );\n file_index_.emplace(utf8name,\n Entry(std::shared_ptr(buffer, buffer->out_buffer_ + offset),\n outSizeProcessed ));\n }\n}\n\nArchive::Entry Archive::Data::read (const std::string& fn) const\n{\n auto it = file_index_.find(fn);\n if (it == file_index_.end())\n {\n throw std::runtime_error(\"Entry not found\");\n }\n return it->second;\n}\n\nArchive::Archive (const std::string& fn)\n : data { std::unique_ptr(new Data(fn)) }\n {\n }\n\nArchive Archive::open (const std::string& fn)\n{\n return Archive( fn );\n}\n\nArchive::Entry Archive::read (const std::string& fn) const\n{\n return data->read( fn );\n}\n} \/* namespace sz *\/\n} \/* namespace util *\/\n} \/* namespace lib33u *\/\n<|endoftext|>"} {"text":"#include \"boid.h\"\n\n\/**\n * @brief Create a new boid\n *\n * Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and\n * the Boid.qml file.\n * After the component is created and ready, the QObject is created and parented to the\n * canvas object.\n * Lastly we set the position randomly, but staying within the boundaries.\n *\/\nBoid::Boid() {\n component = new QQmlComponent(getEngine(), QUrl(QStringLiteral(\"qrc:\/Boid.qml\")));\n if(component->status() == component->Ready) {\n object = component->create(getEngine()->rootContext());\n object->setProperty(\"parent\", QVariant::fromValue(getCanvas()));\n QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);\n }\n else\n qDebug() << component->errorString();\n\n setY(50 + ((double)rand()\/(double)(RAND_MAX)) * (getCanvasHeight() - 100));\n setX(50 + ((double)rand()\/(double)(RAND_MAX)) * (getCanvasWidth() - 100));\n\n lastVel = Vector2();\n}\n\nBoid::~Boid() {\n delete component;\n delete object;\n}\n\n\/**\n * @brief Boid logic\n *\/\nvoid Boid::update(){\n Vector2 v1 = Vector2();\n Vector2 v2 = Vector2();\n Vector2 v3 = Vector2();\n Vector2 v4 = Vector2();\n Vector2 center = Vector2();\n\n \/\/ Rule1: move to local center of mass ( center becomes average of surrounding boids)\n for(int i = 0; i < 3; i++){\n center = center + neighbours[i].position2;\n }\n center \/= 3;\n\n v1 = center - position;\n\n \/\/ Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course.\n center = Vector2();\n for(int i = 0; i < 3; i++){\n if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){\n center = center - (neighbours[i].position2 - position);\n }\n }\n v2 = center;\n\n \/\/ Rule3: Match velocity to surrounding Boids\n for(int i = 0; i < 3; i++){\n v3 = v3 + neighbours[i].velocity2;\n }\n v3 = v3\/3;\n\n \/\/ Rule 4: Follow mouse position\n Vector2 mp = getMousePosition();\n if(!(mp == Vector2(0, 0))) {\n if((mp - position).getSqrMagnitude() > 7500)\n v4 = mp - position;\n }\n\n \/\/ Rule 5: Stray away from the boundaries\n Vector2 v5 = Vector2();\n\n if(position.getX() < 80)\n v5.setX(1);\n else if(position.getX() >= getCanvasWidth() - 80)\n v5.setX(-1);\n\n if(position.getY() < 80)\n v5.setY(1);\n else if(position.getY() >= getCanvasHeight() - 80){\n v5.setY(-1);\n }\n\n \/\/Replace position with mouse position and look through the force-parameter with the mouse\n double power = 0.0;\n double power2 = 0.0;\n if(position.getX() < 80)\n power = 100 - position.getX();\n else if(position.getX() >= getCanvasWidth() - 80)\n power = 100 + position.getX() - getCanvasWidth() ;\n else if(position.getY() < 80)\n power2 = 100 - position.getY();\n else if(position.getY() >= getCanvasHeight() - 80)\n power2 = 100 + position.getY() - getCanvasHeight();\n\n double force = 10*exp((power+ power2) *0.05);\n\n \/\/qDebug << force;\n\n velocity = Vector2::lerp(lastVel,\n velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() +\n v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force,\n 0.016f);\n\n lastVel = velocity;\n}\nTweak threshold and function.#include \"boid.h\"\n\n\/**\n * @brief Create a new boid\n *\n * Creates a new QQmlComponent using the main QQmlApplicationEngine of the program and\n * the Boid.qml file.\n * After the component is created and ready, the QObject is created and parented to the\n * canvas object.\n * Lastly we set the position randomly, but staying within the boundaries.\n *\/\nBoid::Boid() {\n component = new QQmlComponent(getEngine(), QUrl(QStringLiteral(\"qrc:\/Boid.qml\")));\n if(component->status() == component->Ready) {\n object = component->create(getEngine()->rootContext());\n object->setProperty(\"parent\", QVariant::fromValue(getCanvas()));\n QQmlEngine::setObjectOwnership(object, QQmlEngine::CppOwnership);\n }\n else\n qDebug() << component->errorString();\n\n setY(50 + ((double)rand()\/(double)(RAND_MAX)) * (getCanvasHeight() - 100));\n setX(50 + ((double)rand()\/(double)(RAND_MAX)) * (getCanvasWidth() - 100));\n\n lastVel = Vector2();\n}\n\nBoid::~Boid() {\n delete component;\n delete object;\n}\n\n\/**\n * @brief Boid logic\n *\/\nvoid Boid::update(){\n Vector2 v1 = Vector2();\n Vector2 v2 = Vector2();\n Vector2 v3 = Vector2();\n Vector2 v4 = Vector2();\n Vector2 center = Vector2();\n\n \/\/ Rule1: move to local center of mass ( center becomes average of surrounding boids)\n for(int i = 0; i < 3; i++){\n center = center + neighbours[i].position2;\n }\n center \/= 3;\n\n v1 = center - position;\n\n \/\/ Rule2: Avoidance : if distance to next boid smaller than threshold T boid changes course.\n center = Vector2();\n for(int i = 0; i < 3; i++){\n if ((neighbours[i].position2 - position).getSqrMagnitude() < (getSize() + 10.0) * (getSize() + 10.0)){\n center = center - (neighbours[i].position2 - position);\n }\n }\n v2 = center;\n\n \/\/ Rule3: Match velocity to surrounding Boids\n for(int i = 0; i < 3; i++){\n v3 = v3 + neighbours[i].velocity2;\n }\n v3 = v3\/3;\n\n \/\/ Rule 4: Follow mouse position\n Vector2 mp = getMousePosition();\n if(!(mp == Vector2(0, 0))) {\n if((mp - position).getSqrMagnitude() > 7500)\n v4 = mp - position;\n }\n\n \/\/ Rule 5: Stray away from the boundaries\n Vector2 v5 = Vector2();\n\n if(position.getX() < 80)\n v5.setX(1);\n else if(position.getX() >= getCanvasWidth() - 80)\n v5.setX(-1);\n\n if(position.getY() < 80)\n v5.setY(1);\n else if(position.getY() >= getCanvasHeight() - 80){\n v5.setY(-1);\n }\n\n \/\/Replace position with mouse position and look through the force-parameter with the mouse\n double power = 0.0;\n double power2 = 0.0;\n if(position.getX() < 150)\n power = 150 - position.getX();\n else if(position.getX() >= getCanvasWidth() - 150)\n power = 150 + position.getX() - getCanvasWidth() ;\n else if(position.getY() < 150)\n power2 = 150 - position.getY();\n else if(position.getY() >= getCanvasHeight() - 150)\n power2 = 150 + position.getY() - getCanvasHeight();\n\n double force = 5.0 * ((power + power2));\n\n \/\/qDebug << force;\n\n velocity = Vector2::lerp(lastVel,\n velocity + v1.normalize()*getFlockingFactor() + v2.normalize()*getAvoidanceFactor() +\n v3.normalize()*getVelocityMatchFactor() + v4.normalize()*getTargetFactor() + v5 * force,\n 0.016f);\n\n lastVel = velocity;\n}\n<|endoftext|>"} {"text":"#include \"aquila\/source\/generator\/SineGenerator.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nvoid convertSourceToBuffer(const Aquila::SignalSource& source, sf::SoundBuffer& buffer)\r\n{\r\n sf::Int16* samples = new sf::Int16[source.getSamplesCount()];\r\n std::copy(source.begin(), source.end(), samples);\r\n buffer.LoadFromSamples(samples,\r\n source.getSamplesCount(),\r\n 1,\r\n static_cast(source.getSampleFrequency()));\r\n delete [] samples;\r\n}\r\n\r\n\r\nint main(int argc, char** argv)\r\n{\r\n const Aquila::FrequencyType SAMPLE_FREQUENCY = 44100;\r\n Aquila::SineGenerator generator(SAMPLE_FREQUENCY);\r\n generator.setFrequency(440).setAmplitude(8192).generate(2 * SAMPLE_FREQUENCY);\r\n\r\n sf::SoundBuffer buffer;\r\n convertSourceToBuffer(generator, buffer);\r\n\r\n sf::Sound sound;\r\n sound.SetBuffer(buffer);\r\n sound.Play();\r\n while (sound.GetStatus() == sf::Sound::Playing)\r\n {\r\n sf::Sleep(0.1f);\r\n }\r\n\r\n return 0;\r\n}\r\nIn the sfml_generator example, one can now choose signal type and frequency.#include \"aquila\/source\/generator\/SineGenerator.h\"\r\n#include \"aquila\/source\/generator\/SquareGenerator.h\"\r\n#include \"aquila\/source\/generator\/PinkNoiseGenerator.h\"\r\n#include \"aquila\/source\/generator\/WhiteNoiseGenerator.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\r\nvoid convertSourceToBuffer(const Aquila::SignalSource& source,\r\n sf::SoundBuffer& buffer)\r\n{\r\n sf::Int16* samples = new sf::Int16[source.getSamplesCount()];\r\n std::copy(source.begin(), source.end(), samples);\r\n buffer.LoadFromSamples(samples,\r\n source.getSamplesCount(),\r\n 1,\r\n static_cast(source.getSampleFrequency()));\r\n delete [] samples;\r\n}\r\n\r\n\r\nvoid handleGeneratorOptions(Aquila::Generator* generator)\r\n{\r\n Aquila::FrequencyType frequency, maxFrequency = generator->getSampleFrequency() \/ 2;\r\n std::cout << \"\\nSignal frequency in Hz: \\n\"\r\n \"Enter a number (0-\" << maxFrequency << \"): \";\r\n std::cin >> frequency;\r\n if (frequency < 0 || frequency > maxFrequency)\r\n {\r\n frequency = 1000;\r\n }\r\n generator->setFrequency(frequency);\r\n}\r\n\r\n\r\nAquila::Generator* createGenerator(unsigned int whichGenerator,\r\n Aquila::FrequencyType sampleFrequency)\r\n{\r\n Aquila::Generator* generator;\r\n switch (whichGenerator)\r\n {\r\n case 1:\r\n generator = new Aquila::SineGenerator(sampleFrequency);\r\n handleGeneratorOptions(generator);\r\n break;\r\n case 2:\r\n generator = new Aquila::SquareGenerator(sampleFrequency);\r\n handleGeneratorOptions(generator);\r\n break;\r\n case 3:\r\n generator = new Aquila::PinkNoiseGenerator(sampleFrequency);\r\n break;\r\n case 4:\r\n generator = new Aquila::WhiteNoiseGenerator(sampleFrequency);\r\n break;\r\n default:\r\n generator = new Aquila::SineGenerator(sampleFrequency);\r\n handleGeneratorOptions(generator);\r\n break;\r\n }\r\n generator->setAmplitude(8192);\r\n return generator;\r\n}\r\n\r\n\r\nint main(int argc, char** argv)\r\n{\r\n std::cout << \"Choose which kind of signal to play: \\n\"\r\n \"\\t 1: Sine wave \\n\"\r\n \"\\t 2: Square wave \\n\"\r\n \"\\t 3: Pink noise \\n\"\r\n \"\\t 4: White noise \\n\"\r\n \"Enter a number (1-4): \";\r\n unsigned int whichGenerator = 1;\r\n std::cin >> whichGenerator;\r\n const Aquila::FrequencyType SAMPLE_FREQUENCY = 44100;\r\n Aquila::Generator* generator = createGenerator(whichGenerator, SAMPLE_FREQUENCY);\r\n\r\n generator->generate(5 * SAMPLE_FREQUENCY);\r\n sf::SoundBuffer buffer;\r\n convertSourceToBuffer(*generator, buffer);\r\n sf::Sound sound;\r\n sound.SetBuffer(buffer);\r\n sound.Play();\r\n std::cout << \"Playing...\" << std::endl;\r\n while (sound.GetStatus() == sf::Sound::Playing)\r\n {\r\n std::cout << \".\";\r\n sf::Sleep(0.1f);\r\n }\r\n std::cout << \"\\nFinished.\" << std::endl;\r\n\r\n delete generator;\r\n\r\n return 0;\r\n}\r\n<|endoftext|>"} {"text":"Multipart cleanup of T3000 - 7<|endoftext|>"} {"text":"\/**\n * @file Vector.hpp\n *\n * Vector class.\n *\n * @author James Goppert \n *\/\n\n#pragma once\n#include \n\nnamespace matrix\n{\n\ntemplate \nclass Matrix;\n\ntemplate\nclass Vector : public Matrix\n{\npublic:\n virtual ~Vector() {};\n\n Vector() : Matrix()\n {\n }\n\n Vector(const Vector & other) :\n Matrix(other)\n {\n }\n\n Vector(const Matrix & other) :\n Matrix(other)\n {\n }\n\n inline Type operator()(size_t i) const\n {\n const Matrix &v = *this;\n return v(i, 0);\n }\n\n inline Type &operator()(size_t i)\n {\n Matrix &v = *this;\n return v(i, 0);\n }\n\n Type dot(const Vector & b) const {\n const Vector &a(*this);\n Type r = 0;\n for (int i = 0; i operator+(const Vector &other) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) + other(i);\n }\n\n return res;\n }\n\n Vector operator-(const Vector &other) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) - other(i);\n }\n\n return res;\n }\n\n void operator+=(const Vector &other)\n {\n Vector &self = *this;\n self = self + other;\n }\n\n void operator-=(const Vector &other)\n {\n Vector &self = *this;\n self = self - other;\n }\n\n \/**\n * Scalar Operations\n *\/\n\n Vector operator*(Type scalar) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) * scalar;\n }\n\n return res;\n }\n\n Vector operator\/(Type scalar) const\n {\n return (*this)*(1.0\/scalar);\n }\n\n Vector operator+(Type scalar) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) + scalar;\n }\n\n return res;\n }\n\n void operator*=(Type scalar)\n {\n Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n self(i) = self(i) * scalar;\n }\n }\n\n void operator\/=(Type scalar)\n {\n Vector &self = *this;\n self = self * (1.0f \/ scalar);\n }\n\n};\n\n}; \/\/ namespace matrix\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\nTravis fix.\/**\n * @file Vector.hpp\n *\n * Vector class.\n *\n * @author James Goppert \n *\/\n\n#pragma once\n#include \n\nnamespace matrix\n{\n\ntemplate \nclass Matrix;\n\ntemplate\nclass Vector : public Matrix\n{\npublic:\n virtual ~Vector() {};\n\n Vector() : Matrix()\n {\n }\n\n Vector(const Vector & other) :\n Matrix(other)\n {\n }\n\n Vector(const Matrix & other) :\n Matrix(other)\n {\n }\n\n inline Type operator()(size_t i) const\n {\n const Matrix &v = *this;\n return v(i, 0);\n }\n\n inline Type &operator()(size_t i)\n {\n Matrix &v = *this;\n return v(i, 0);\n }\n\n Type dot(const Vector & b) const {\n const Vector &a(*this);\n Type r = 0;\n for (int i = 0; i operator+(const Vector &other) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) + other(i);\n }\n\n return res;\n }\n\n Vector operator-(const Vector &other) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) - other(i);\n }\n\n return res;\n }\n\n void operator+=(const Vector &other)\n {\n Vector &self = *this;\n self = self + other;\n }\n\n void operator-=(const Vector &other)\n {\n Vector &self = *this;\n self = self - other;\n }\n\n \/**\n * Scalar Operations\n *\/\n\n Vector operator*(Type scalar) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) * scalar;\n }\n\n return res;\n }\n\n Vector operator\/(Type scalar) const\n {\n return (*this)*(Type(1.0)\/scalar);\n }\n\n Vector operator+(Type scalar) const\n {\n Vector res;\n const Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n res(i) = self(i) + scalar;\n }\n\n return res;\n }\n\n void operator*=(Type scalar)\n {\n Vector &self = *this;\n\n for (size_t i = 0; i < M; i++) {\n self(i) = self(i) * scalar;\n }\n }\n\n void operator\/=(Type scalar)\n {\n Vector &self = *this;\n self = self * (1.0f \/ scalar);\n }\n\n};\n\n}; \/\/ namespace matrix\n\n\/* vim: set et fenc=utf-8 ff=unix sts=0 sw=4 ts=4 : *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: taskmisc.cxx,v $\n *\n * $Revision: 1.1.1.1 $\n *\n * last change: $Author: hr $ $Date: 2000-09-18 16:58:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define _TASKBAR_CXX\n\n#ifndef _TOOLS_LIST_HXX\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#ifndef _SV_HELP_HXX\n#include \n#endif\n\n#include \n\n\/\/ =======================================================================\n\nTaskButtonBar::TaskButtonBar( Window* pParent, WinBits nWinStyle ) :\n ToolBox( pParent, nWinStyle | WB_3DLOOK )\n{\n SetAlign( WINDOWALIGN_BOTTOM );\n SetButtonType( BUTTON_SYMBOLTEXT );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nTaskButtonBar::~TaskButtonBar()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TaskButtonBar::RequestHelp( const HelpEvent& rHEvt )\n{\n ToolBox::RequestHelp( rHEvt );\n}\n\n\/\/ =======================================================================\n\nWindowArrange::WindowArrange()\n{\n mpWinList = new List;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nWindowArrange::~WindowArrange()\n{\n delete mpWinList;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic USHORT ImplCeilSqareRoot( USHORT nVal )\n{\n USHORT i;\n\n \/\/ Ueberlauf verhindern\n if ( nVal > 0xFE * 0xFE )\n return 0xFE;\n\n for ( i=0; i*i < nVal; i++ )\n {}\n\n return i;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPosSizeWindow( Window* pWindow,\n long nX, long nY, long nWidth, long nHeight )\n{\n if ( nWidth < 32 )\n nWidth = 32;\n if ( nHeight < 24 )\n nHeight = 24;\n pWindow->SetPosSizePixel( nX, nY, nWidth, nHeight );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplTile( const Rectangle& rRect )\n{\n USHORT nCount = (USHORT)mpWinList->Count();\n if ( nCount < 3 )\n {\n ImplVert( rRect );\n return;\n }\n\n USHORT i;\n USHORT j;\n USHORT nCols;\n USHORT nRows;\n USHORT nActRows;\n USHORT nOffset;\n long nOverWidth;\n long nOverHeight;\n Window* pWindow;\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectY = nY;\n long nRectWidth = nWidth;\n long nRectHeight = nHeight;\n long nTempWidth;\n long nTempHeight;\n\n nCols = ImplCeilSqareRoot( nCount );\n nOffset = (nCols*nCols) - nCount;\n if ( nOffset >= nCols )\n {\n nRows = nCols -1;\n nOffset -= nCols;\n }\n else\n nRows = nCols;\n\n nWidth \/= nCols;\n if ( nWidth < 1 )\n nWidth = 1;\n nOverWidth = nRectWidth-(nWidth*nCols);\n\n pWindow = (Window*)mpWinList->First();\n for ( i = 0; i < nCols; i++ )\n {\n if ( i < nOffset )\n nActRows = nRows - 1;\n else\n nActRows = nRows;\n\n nTempWidth = nWidth;\n if ( nOverWidth > 0 )\n {\n nTempWidth++;\n nOverWidth--;\n }\n\n nHeight = nRectHeight \/ nActRows;\n if ( nHeight < 1 )\n nHeight = 1;\n nOverHeight = nRectHeight-(nHeight*nActRows);\n for ( j = 0; j < nActRows; j++ )\n {\n \/\/ Ueberhang verteilen\n nTempHeight = nHeight;\n if ( nOverHeight > 0 )\n {\n nTempHeight++;\n nOverHeight--;\n }\n ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nTempHeight );\n nY += nTempHeight;\n\n pWindow = (Window*)mpWinList->Next();\n if ( !pWindow )\n break;\n }\n\n nX += nWidth;\n nY = nRectY;\n\n if ( !pWindow )\n break;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplHorz( const Rectangle& rRect )\n{\n long nCount = (long)mpWinList->Count();\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectHeight = nHeight;\n long nOver;\n long nTempHeight;\n Window* pWindow;\n\n nHeight \/= nCount;\n if ( nHeight < 1 )\n nHeight = 1;\n nOver = nRectHeight - (nCount*nHeight);\n pWindow = (Window*)mpWinList->First();\n while ( pWindow )\n {\n nTempHeight = nHeight;\n if ( nOver > 0 )\n {\n nTempHeight++;\n nOver--;\n }\n ImplPosSizeWindow( pWindow, nX, nY, nWidth, nTempHeight );\n nY += nTempHeight;\n\n pWindow = (Window*)mpWinList->Next();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplVert( const Rectangle& rRect )\n{\n long nCount = (long)mpWinList->Count();\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectWidth = nWidth;\n long nOver;\n long nTempWidth;\n Window* pWindow;\n\n nWidth \/= nCount;\n if ( nWidth < 1 )\n nWidth = 1;\n nOver = nRectWidth - (nCount*nWidth);\n pWindow = (Window*)mpWinList->First();\n while ( pWindow )\n {\n nTempWidth = nWidth;\n if ( nOver > 0 )\n {\n nTempWidth++;\n nOver--;\n }\n ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nHeight );\n nX += nTempWidth;\n\n pWindow = (Window*)mpWinList->Next();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplCascade( const Rectangle& rRect )\n{\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectWidth = nWidth;\n long nRectHeight = nHeight;\n long nOff;\n long nCascadeWins;\n long nLeftBorder;\n long nTopBorder;\n long nRightBorder;\n long nBottomBorder;\n long nStartOverWidth;\n long nStartOverHeight;\n long nOverWidth;\n long nOverHeight;\n long nTempX;\n long nTempY;\n long nTempWidth;\n long nTempHeight;\n long i;\n Window* pWindow;\n Window* pTempWindow;\n\n \/\/ Border-Fenster suchen um den Versatz zu ermitteln\n pTempWindow = (Window*)mpWinList->First();\n pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );\n while ( !nTopBorder )\n {\n Window* pBrdWin = pTempWindow->GetWindow( WINDOW_REALPARENT );\n if ( !pBrdWin || (pBrdWin->GetWindow( WINDOW_CLIENT ) != pTempWindow) )\n break;\n pTempWindow = pBrdWin;\n pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );\n }\n if ( !nTopBorder )\n nTopBorder = 22;\n nOff = nTopBorder;\n\n nCascadeWins = nRectHeight \/ 3 \/ nOff;\n if ( !nCascadeWins )\n nCascadeWins = 1;\n nWidth -= nCascadeWins*nOff;\n nHeight -= nCascadeWins*nOff;\n if ( nWidth < 1 )\n nWidth = 1;\n if ( nHeight < 1 )\n nHeight = 1;\n\n nStartOverWidth = nRectWidth-(nWidth+(nCascadeWins*nOff));\n nStartOverHeight = nRectHeight-(nHeight+(nCascadeWins*nOff));\n\n i = 0;\n pWindow = (Window*)mpWinList->First();\n while ( pWindow )\n {\n if ( !i )\n {\n nOverWidth = nStartOverWidth;\n nOverHeight = nStartOverHeight;\n }\n\n \/\/ Position\n nTempX = nX + (i*nOff);\n nTempY = nY + (i*nOff);\n\n \/\/ Ueberhang verteilen\n nTempWidth = nWidth;\n if ( nOverWidth > 0 )\n {\n nTempWidth++;\n nOverWidth--;\n }\n nTempHeight = nHeight;\n if ( nOverHeight > 0 )\n {\n nTempHeight++;\n nOverHeight--;\n }\n\n ImplPosSizeWindow( pWindow, nTempX, nTempY, nTempWidth, nTempHeight );\n\n if ( i < nCascadeWins )\n i++;\n else\n i = 0;\n\n pWindow = (Window*)mpWinList->Next();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::Arrange( USHORT nType, const Rectangle& rRect )\n{\n if ( !mpWinList->Count() )\n return;\n\n switch ( nType )\n {\n case WINDOWARRANGE_TILE:\n ImplTile( rRect );\n break;\n case WINDOWARRANGE_HORZ:\n ImplHorz( rRect );\n break;\n case WINDOWARRANGE_VERT:\n ImplVert( rRect );\n break;\n case WINDOWARRANGE_CASCADE:\n ImplCascade( rRect );\n break;\n }\n}\n\nINTEGRATION: CWS ooo20040509 (1.1.1.1.588); FILE MERGED 2004\/05\/06 13:40:19 waratah 1.1.1.1.588.1: Initialise variables where they need it\/*************************************************************************\n *\n * $RCSfile: taskmisc.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: rt $ $Date: 2004-06-16 10:13:08 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#define _TASKBAR_CXX\n\n#ifndef _TOOLS_LIST_HXX\n#include \n#endif\n#ifndef _TOOLS_DEBUG_HXX\n#include \n#endif\n\n#ifndef _SV_HELP_HXX\n#include \n#endif\n\n#include \n\n\/\/ =======================================================================\n\nTaskButtonBar::TaskButtonBar( Window* pParent, WinBits nWinStyle ) :\n ToolBox( pParent, nWinStyle | WB_3DLOOK )\n{\n SetAlign( WINDOWALIGN_BOTTOM );\n SetButtonType( BUTTON_SYMBOLTEXT );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nTaskButtonBar::~TaskButtonBar()\n{\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid TaskButtonBar::RequestHelp( const HelpEvent& rHEvt )\n{\n ToolBox::RequestHelp( rHEvt );\n}\n\n\/\/ =======================================================================\n\nWindowArrange::WindowArrange()\n{\n mpWinList = new List;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nWindowArrange::~WindowArrange()\n{\n delete mpWinList;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic USHORT ImplCeilSqareRoot( USHORT nVal )\n{\n USHORT i;\n\n \/\/ Ueberlauf verhindern\n if ( nVal > 0xFE * 0xFE )\n return 0xFE;\n\n for ( i=0; i*i < nVal; i++ )\n {}\n\n return i;\n}\n\n\/\/ -----------------------------------------------------------------------\n\nstatic void ImplPosSizeWindow( Window* pWindow,\n long nX, long nY, long nWidth, long nHeight )\n{\n if ( nWidth < 32 )\n nWidth = 32;\n if ( nHeight < 24 )\n nHeight = 24;\n pWindow->SetPosSizePixel( nX, nY, nWidth, nHeight );\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplTile( const Rectangle& rRect )\n{\n USHORT nCount = (USHORT)mpWinList->Count();\n if ( nCount < 3 )\n {\n ImplVert( rRect );\n return;\n }\n\n USHORT i;\n USHORT j;\n USHORT nCols;\n USHORT nRows;\n USHORT nActRows;\n USHORT nOffset;\n long nOverWidth;\n long nOverHeight;\n Window* pWindow;\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectY = nY;\n long nRectWidth = nWidth;\n long nRectHeight = nHeight;\n long nTempWidth;\n long nTempHeight;\n\n nCols = ImplCeilSqareRoot( nCount );\n nOffset = (nCols*nCols) - nCount;\n if ( nOffset >= nCols )\n {\n nRows = nCols -1;\n nOffset -= nCols;\n }\n else\n nRows = nCols;\n\n nWidth \/= nCols;\n if ( nWidth < 1 )\n nWidth = 1;\n nOverWidth = nRectWidth-(nWidth*nCols);\n\n pWindow = (Window*)mpWinList->First();\n for ( i = 0; i < nCols; i++ )\n {\n if ( i < nOffset )\n nActRows = nRows - 1;\n else\n nActRows = nRows;\n\n nTempWidth = nWidth;\n if ( nOverWidth > 0 )\n {\n nTempWidth++;\n nOverWidth--;\n }\n\n nHeight = nRectHeight \/ nActRows;\n if ( nHeight < 1 )\n nHeight = 1;\n nOverHeight = nRectHeight-(nHeight*nActRows);\n for ( j = 0; j < nActRows; j++ )\n {\n \/\/ Ueberhang verteilen\n nTempHeight = nHeight;\n if ( nOverHeight > 0 )\n {\n nTempHeight++;\n nOverHeight--;\n }\n ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nTempHeight );\n nY += nTempHeight;\n\n pWindow = (Window*)mpWinList->Next();\n if ( !pWindow )\n break;\n }\n\n nX += nWidth;\n nY = nRectY;\n\n if ( !pWindow )\n break;\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplHorz( const Rectangle& rRect )\n{\n long nCount = (long)mpWinList->Count();\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectHeight = nHeight;\n long nOver;\n long nTempHeight;\n Window* pWindow;\n\n nHeight \/= nCount;\n if ( nHeight < 1 )\n nHeight = 1;\n nOver = nRectHeight - (nCount*nHeight);\n pWindow = (Window*)mpWinList->First();\n while ( pWindow )\n {\n nTempHeight = nHeight;\n if ( nOver > 0 )\n {\n nTempHeight++;\n nOver--;\n }\n ImplPosSizeWindow( pWindow, nX, nY, nWidth, nTempHeight );\n nY += nTempHeight;\n\n pWindow = (Window*)mpWinList->Next();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplVert( const Rectangle& rRect )\n{\n long nCount = (long)mpWinList->Count();\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectWidth = nWidth;\n long nOver;\n long nTempWidth;\n Window* pWindow;\n\n nWidth \/= nCount;\n if ( nWidth < 1 )\n nWidth = 1;\n nOver = nRectWidth - (nCount*nWidth);\n pWindow = (Window*)mpWinList->First();\n while ( pWindow )\n {\n nTempWidth = nWidth;\n if ( nOver > 0 )\n {\n nTempWidth++;\n nOver--;\n }\n ImplPosSizeWindow( pWindow, nX, nY, nTempWidth, nHeight );\n nX += nTempWidth;\n\n pWindow = (Window*)mpWinList->Next();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::ImplCascade( const Rectangle& rRect )\n{\n long nX = rRect.Left();\n long nY = rRect.Top();\n long nWidth = rRect.GetWidth();\n long nHeight = rRect.GetHeight();\n long nRectWidth = nWidth;\n long nRectHeight = nHeight;\n long nOff;\n long nCascadeWins;\n long nLeftBorder;\n long nTopBorder;\n long nRightBorder;\n long nBottomBorder;\n long nStartOverWidth;\n long nStartOverHeight;\n long nOverWidth = 0;\n long nOverHeight = 0;\n long nTempX;\n long nTempY;\n long nTempWidth;\n long nTempHeight;\n long i;\n Window* pWindow;\n Window* pTempWindow;\n\n \/\/ Border-Fenster suchen um den Versatz zu ermitteln\n pTempWindow = (Window*)mpWinList->First();\n pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );\n while ( !nTopBorder )\n {\n Window* pBrdWin = pTempWindow->GetWindow( WINDOW_REALPARENT );\n if ( !pBrdWin || (pBrdWin->GetWindow( WINDOW_CLIENT ) != pTempWindow) )\n break;\n pTempWindow = pBrdWin;\n pTempWindow->GetBorder( nLeftBorder, nTopBorder, nRightBorder, nBottomBorder );\n }\n if ( !nTopBorder )\n nTopBorder = 22;\n nOff = nTopBorder;\n\n nCascadeWins = nRectHeight \/ 3 \/ nOff;\n if ( !nCascadeWins )\n nCascadeWins = 1;\n nWidth -= nCascadeWins*nOff;\n nHeight -= nCascadeWins*nOff;\n if ( nWidth < 1 )\n nWidth = 1;\n if ( nHeight < 1 )\n nHeight = 1;\n\n nStartOverWidth = nRectWidth-(nWidth+(nCascadeWins*nOff));\n nStartOverHeight = nRectHeight-(nHeight+(nCascadeWins*nOff));\n\n i = 0;\n pWindow = (Window*)mpWinList->First();\n while ( pWindow )\n {\n if ( !i )\n {\n nOverWidth = nStartOverWidth;\n nOverHeight = nStartOverHeight;\n }\n\n \/\/ Position\n nTempX = nX + (i*nOff);\n nTempY = nY + (i*nOff);\n\n \/\/ Ueberhang verteilen\n nTempWidth = nWidth;\n if ( nOverWidth > 0 )\n {\n nTempWidth++;\n nOverWidth--;\n }\n nTempHeight = nHeight;\n if ( nOverHeight > 0 )\n {\n nTempHeight++;\n nOverHeight--;\n }\n\n ImplPosSizeWindow( pWindow, nTempX, nTempY, nTempWidth, nTempHeight );\n\n if ( i < nCascadeWins )\n i++;\n else\n i = 0;\n\n pWindow = (Window*)mpWinList->Next();\n }\n}\n\n\/\/ -----------------------------------------------------------------------\n\nvoid WindowArrange::Arrange( USHORT nType, const Rectangle& rRect )\n{\n if ( !mpWinList->Count() )\n return;\n\n switch ( nType )\n {\n case WINDOWARRANGE_TILE:\n ImplTile( rRect );\n break;\n case WINDOWARRANGE_HORZ:\n ImplHorz( rRect );\n break;\n case WINDOWARRANGE_VERT:\n ImplVert( rRect );\n break;\n case WINDOWARRANGE_CASCADE:\n ImplCascade( rRect );\n break;\n }\n}\n\n<|endoftext|>"} {"text":"\/*\n * This file is part of ALVAR, A Library for Virtual and Augmented Reality.\n *\n * Copyright 2007-2012 VTT Technical Research Centre of Finland\n *\n * Contact: VTT Augmented Reality Team \n * \n *\n * ALVAR is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation; either version 2.1 of the License, or (at your option)\n * any later version.\n *\n * This library is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with ALVAR; if not, see\n * .\n *\/\n\n#include \"CaptureFactory_private.h\"\n\n#include \n\nnamespace alvar {\n\nvoid CaptureFactoryPrivate::setupPluginPaths()\n{\n \/\/ application path and default plugin path\n const int bufferSize = 4096;\n char applicationBuffer[bufferSize];\n int count = readlink(\"\/proc\/self\/exe\", applicationBuffer, bufferSize);\n if (count != 0 && count < bufferSize) {\n std::string applicationPath(applicationBuffer, count);\n applicationPath = std::string(applicationPath, 0, applicationPath.find_last_of(\"\/\"));\n mPluginPaths.push_back(applicationPath);\n mPluginPaths.push_back(applicationPath + \"\/alvarplugins\");\n }\n \n \/\/ ALVAR library path\n parseEnvironmentVariable(std::string(\"ALVAR_LIBRARY_PATH\"));\n\n \/\/ ALVAR plugin path\n parseEnvironmentVariable(std::string(\"ALVAR_PLUGIN_PATH\"));\n}\n\nvoid CaptureFactoryPrivate::parseEnvironmentVariable(const std::string &variable)\n{\n \/\/ acquire environment variable\n char *buffer;\n std::string path(\"\");\n buffer = getenv(variable.data());\n if (buffer) {\n path = std::string(buffer);\n }\n \n \/\/ tokenize paths\n char delimitor = ':';\n if (!path.empty()) {\n std::string::size_type start = 0;\n std::string::size_type end = 0;\n while ((end = path.find_first_of(delimitor, start)) != std::string::npos) {\n std::string tmp(path, start, end - start);\n if (!tmp.empty()) {\n mPluginPaths.push_back(tmp);\n }\n start = end + 1;\n }\n if (start != path.size()) {\n std::string tmp(path, start, std::string::npos);\n if (!tmp.empty()) {\n mPluginPaths.push_back(tmp);\n }\n }\n }\n}\n\nstd::string CaptureFactoryPrivate::pluginPrefix()\n{\n return std::string(\"lib\");\n}\n\nstd::string CaptureFactoryPrivate::pluginExtension()\n{\n return std::string(\"so\");\n}\n\n} \/\/ namespace alvar\nAdd missing unistd include\/*\n * This file is part of ALVAR, A Library for Virtual and Augmented Reality.\n *\n * Copyright 2007-2012 VTT Technical Research Centre of Finland\n *\n * Contact: VTT Augmented Reality Team \n * \n *\n * ALVAR is free software; you can redistribute it and\/or modify it under the\n * terms of the GNU Lesser General Public License as published by the Free\n * Software Foundation; either version 2.1 of the License, or (at your option)\n * any later version.\n *\n * This library is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or\n * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Lesser General Public License\n * along with ALVAR; if not, see\n * .\n *\/\n\n#include \"CaptureFactory_private.h\"\n\n#include \n#include \n\nnamespace alvar {\n\nvoid CaptureFactoryPrivate::setupPluginPaths()\n{\n \/\/ application path and default plugin path\n const int bufferSize = 4096;\n char applicationBuffer[bufferSize];\n int count = readlink(\"\/proc\/self\/exe\", applicationBuffer, bufferSize);\n if (count != 0 && count < bufferSize) {\n std::string applicationPath(applicationBuffer, count);\n applicationPath = std::string(applicationPath, 0, applicationPath.find_last_of(\"\/\"));\n mPluginPaths.push_back(applicationPath);\n mPluginPaths.push_back(applicationPath + \"\/alvarplugins\");\n }\n \n \/\/ ALVAR library path\n parseEnvironmentVariable(std::string(\"ALVAR_LIBRARY_PATH\"));\n\n \/\/ ALVAR plugin path\n parseEnvironmentVariable(std::string(\"ALVAR_PLUGIN_PATH\"));\n}\n\nvoid CaptureFactoryPrivate::parseEnvironmentVariable(const std::string &variable)\n{\n \/\/ acquire environment variable\n char *buffer;\n std::string path(\"\");\n buffer = getenv(variable.data());\n if (buffer) {\n path = std::string(buffer);\n }\n \n \/\/ tokenize paths\n char delimitor = ':';\n if (!path.empty()) {\n std::string::size_type start = 0;\n std::string::size_type end = 0;\n while ((end = path.find_first_of(delimitor, start)) != std::string::npos) {\n std::string tmp(path, start, end - start);\n if (!tmp.empty()) {\n mPluginPaths.push_back(tmp);\n }\n start = end + 1;\n }\n if (start != path.size()) {\n std::string tmp(path, start, std::string::npos);\n if (!tmp.empty()) {\n mPluginPaths.push_back(tmp);\n }\n }\n }\n}\n\nstd::string CaptureFactoryPrivate::pluginPrefix()\n{\n return std::string(\"lib\");\n}\n\nstd::string CaptureFactoryPrivate::pluginExtension()\n{\n return std::string(\"so\");\n}\n\n} \/\/ namespace alvar\n<|endoftext|>"} {"text":"#include \"ConfigController.h\"\n\n#include \"GameController.h\"\n\n#include \n#include \n\nextern \"C\" {\n#include \"platform\/commandline.h\"\n}\n\nusing namespace QGBA;\n\nConfigOption::ConfigOption(QObject* parent)\n\t: QObject(parent)\n{\n}\n\nvoid ConfigOption::connect(std::function slot) {\n\tm_slot = slot;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, value]() {\n\t\temit valueChanged(value);\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, value));\n\treturn action;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {\n\treturn addValue(text, QString(value), parent);\n}\n\nQAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, action]() {\n\t\temit valueChanged(action->isChecked());\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, true));\n\treturn action;\n}\n\nvoid ConfigOption::setValue(bool value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(int value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(unsigned value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(const char* value) {\n\tsetValue(QVariant(QString(value)));\n}\n\nvoid ConfigOption::setValue(const QVariant& value) {\n\tQPair action;\n\tforeach(action, m_actions) {\n\t\tbool signalsEnabled = action.first->blockSignals(true);\n\t\taction.first->setChecked(value == action.second);\n\t\taction.first->blockSignals(signalsEnabled);\n\t}\n\tm_slot(value);\n}\n\nConfigController::ConfigController(QObject* parent)\n\t: QObject(parent)\n\t, m_opts()\n{\n\tGBAConfigInit(&m_config, PORT);\n\n\tm_opts.audioSync = GameController::AUDIO_SYNC;\n\tm_opts.videoSync = GameController::VIDEO_SYNC;\n\tm_opts.fpsTarget = 60;\n\tm_opts.audioBuffers = 768;\n\tGBAConfigLoadDefaults(&m_config, &m_opts);\n\tGBAConfigLoad(&m_config);\n\tGBAConfigMap(&m_config, &m_opts);\n}\n\nConfigController::~ConfigController() {\n\twrite();\n\n\tGBAConfigDeinit(&m_config);\n\tGBAConfigFreeOpts(&m_opts);\n}\n\nbool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {\n\treturn ::parseArguments(args, &m_config, argc, argv, 0);\n}\n\nConfigOption* ConfigController::addOption(const char* key) {\n\tQString optionName(key);\n\n\tif (m_optionSet.contains(optionName)) {\n\t\treturn m_optionSet[optionName];\n\t}\n\tConfigOption* newOption = new ConfigOption(this);\n\tm_optionSet[optionName] = newOption;\n\tconnect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {\n\t\tsetOption(key, value);\n\t});\n\treturn newOption;\n}\n\nvoid ConfigController::updateOption(const char* key) {\n\tif (!key) {\n\t\treturn;\n\t}\n\n\tQString optionName(key);\n\n\tif (!m_optionSet.contains(optionName)) {\n\t\treturn;\n\t}\n\tm_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));\n}\n\nvoid ConfigController::setOption(const char* key, bool value) {\n\tsetOption(key, (int) value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, int value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, unsigned value) {\n\tGBAConfigSetUIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const char* value) {\n\tGBAConfigSetValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const QVariant& value) {\n\tQString stringValue(value.toString());\n\tsetOption(key, stringValue.toLocal8Bit().constData());\n}\n\nvoid ConfigController::write() {\n\tGBAConfigSave(&m_config);\n}\nQt: Fix boolean setting loading#include \"ConfigController.h\"\n\n#include \"GameController.h\"\n\n#include \n#include \n\nextern \"C\" {\n#include \"platform\/commandline.h\"\n}\n\nusing namespace QGBA;\n\nConfigOption::ConfigOption(QObject* parent)\n\t: QObject(parent)\n{\n}\n\nvoid ConfigOption::connect(std::function slot) {\n\tm_slot = slot;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, value]() {\n\t\temit valueChanged(value);\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, value));\n\treturn action;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {\n\treturn addValue(text, QString(value), parent);\n}\n\nQAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, action]() {\n\t\temit valueChanged(action->isChecked());\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, 1));\n\treturn action;\n}\n\nvoid ConfigOption::setValue(bool value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(int value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(unsigned value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(const char* value) {\n\tsetValue(QVariant(QString(value)));\n}\n\nvoid ConfigOption::setValue(const QVariant& value) {\n\tQPair action;\n\tforeach(action, m_actions) {\n\t\tbool signalsEnabled = action.first->blockSignals(true);\n\t\taction.first->setChecked(value == action.second);\n\t\taction.first->blockSignals(signalsEnabled);\n\t}\n\tm_slot(value);\n}\n\nConfigController::ConfigController(QObject* parent)\n\t: QObject(parent)\n\t, m_opts()\n{\n\tGBAConfigInit(&m_config, PORT);\n\n\tm_opts.audioSync = GameController::AUDIO_SYNC;\n\tm_opts.videoSync = GameController::VIDEO_SYNC;\n\tm_opts.fpsTarget = 60;\n\tm_opts.audioBuffers = 768;\n\tGBAConfigLoadDefaults(&m_config, &m_opts);\n\tGBAConfigLoad(&m_config);\n\tGBAConfigMap(&m_config, &m_opts);\n}\n\nConfigController::~ConfigController() {\n\twrite();\n\n\tGBAConfigDeinit(&m_config);\n\tGBAConfigFreeOpts(&m_opts);\n}\n\nbool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {\n\treturn ::parseArguments(args, &m_config, argc, argv, 0);\n}\n\nConfigOption* ConfigController::addOption(const char* key) {\n\tQString optionName(key);\n\n\tif (m_optionSet.contains(optionName)) {\n\t\treturn m_optionSet[optionName];\n\t}\n\tConfigOption* newOption = new ConfigOption(this);\n\tm_optionSet[optionName] = newOption;\n\tconnect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {\n\t\tsetOption(key, value);\n\t});\n\treturn newOption;\n}\n\nvoid ConfigController::updateOption(const char* key) {\n\tif (!key) {\n\t\treturn;\n\t}\n\n\tQString optionName(key);\n\n\tif (!m_optionSet.contains(optionName)) {\n\t\treturn;\n\t}\n\tm_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));\n}\n\nvoid ConfigController::setOption(const char* key, bool value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, int value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, unsigned value) {\n\tGBAConfigSetUIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const char* value) {\n\tGBAConfigSetValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const QVariant& value) {\n\tif (value.type() == QVariant::Bool) {\n\t\tsetOption(key, value.toBool());\n\t\treturn;\n\t}\n\tQString stringValue(value.toString());\n\tsetOption(key, stringValue.toLocal8Bit().constData());\n}\n\nvoid ConfigController::write() {\n\tGBAConfigSave(&m_config);\n}\n<|endoftext|>"} {"text":"#include \"HaxeRuntime.h\"\n#if WITH_EDITOR\n\n#include \"uhx\/DynamicClass.h\"\n\n#include \"Misc\/Paths.h\"\n#include \"uhx\/expose\/HxcppRuntime.h\"\n\n#ifndef UHX_NO_UOBJECT\n\nstatic int uhx_uniqueId = 0;\n\nstatic TMap getCrcMapPvt() {\n TMap map;\n FString path = FPaths::ConvertRelativePathToFull(FPaths::GameDir()) + TEXT(\"\/Binaries\/Haxe\/gameCrcs.data\");\n auto file = FPlatformFileManager::Get().GetPlatformFile().OpenRead(*path, false);\n if (file == nullptr) {\n return map;\n }\n\n uint8 classNameSize = 0;\n char className[257];\n uint32 crc = 0;\n bool success = true;\n int magic = 0;\n if (!file->Read((uint8*) &magic, 4) || magic != 0xC5CC991A) {\n UE_LOG(HaxeLog, Error, TEXT(\"Invalid gameCrcs magic\"));\n success = false;\n }\n\n int ntry = 0;\n\n if (!success || !file->Read((uint8*) &ntry, 4)) {\n success = false;\n }\n uhx_uniqueId = ntry;\n\n#define READ(destination, bytesToRead) if (!file->Read(destination, bytesToRead)) { success = false; break; }\n\n while(success) {\n READ(&classNameSize, 1);\n if (classNameSize == 0) {\n break;\n }\n\n READ((uint8 *) className, classNameSize);\n className[classNameSize] = 0;\n READ((uint8 *) &crc, 4);\n \/\/ crc += ntry;\n FName classFName = FName( UTF8_TO_TCHAR(className) );\n if (crc == 0) {\n UE_LOG(HaxeLog, Error, TEXT(\"Unreal.hx CRC for class %s was 0\"), *classFName.ToString());\n }\n map.Add(classFName, crc);\n }\n\n#undef READ\n\n if (!success) {\n UE_LOG(HaxeLog,Error,TEXT(\"Unreal.hx CRC data was corrupt\"));\n }\n\n delete file;\n return map;\n}\n\nTMap& ::uhx::DynamicClassHelper::getCrcMap() {\n static TMap map = getCrcMapPvt();\n return map;\n}\n\nTMap& ::uhx::DynamicClassHelper::getDynamicsMap() {\n static TMap map;\n return map;\n}\n\n\n#endif\n\n#if (WITH_EDITOR && !NO_DYNAMIC_UCLASS)\n\n\/**\n * In order to add cppia dynamic class support, we need to be able to call `addDynamicProperties` in a very precise location - which is\n * right before the CDO is created. We must call this before the class CDO is created because otherwise the CDO will have the wrong size,\n * and bad things will happen. This UHxBootstrap class implements an intrinsic class so we can have a callback right when the classes\n * are registering, which is the exact place where we should add the dynamic properties\n **\/\nclass UHxBootstrap : public UObject {\n#if UE_VER >= 416\n#define UHX_HOTRELOAD 1\n#else\n#define UHX_HOTRELOAD WITH_HOT_RELOAD_CTORS\n#endif\n\n#if UHX_HOTRELOAD\n DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR_NO_VTABLE_CTOR(UHxBootstrap, UObject, 0, TEXT(\"\/Script\/HaxeRuntime\"), 0, HAXERUNTIME_API)\n\n UHxBootstrap(FVTableHelper& Helper) : UObject(Helper) {\n }\n#else\n DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR(UHxBootstrap, UObject, 0, HaxeRuntime, 0, HAXERUNTIME_API)\n#endif\n UHxBootstrap(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : UObject(ObjectInitializer) {\n static bool endLoadingDynamicCalled = false;\n if (!endLoadingDynamicCalled) {\n endLoadingDynamicCalled = true;\n uhx::expose::HxcppRuntime::endLoadingDynamic();\n }\n }\n\n#undef UHX_HOTRELOAD\n};\n\n\/\/ make sure that UHxBootstrap is always hot reloaded, as its CRC constantly changes\ntemplate<>\nstruct TClassCompiledInDefer : public FFieldCompiledInInfo\n{\n TClassCompiledInDefer(const TCHAR* InName, SIZE_T InClassSize, uint32 InCrc)\n : FFieldCompiledInInfo(InClassSize, InCrc)\n {\n static FName className = FName(\"UHxBootstrap\");\n ::uhx::DynamicClassHelper::getCrcMap(); \/\/ make sure that the crc map is initialized\n this->Crc = uhx_uniqueId;\n UClassCompiledInDefer(this, InName, InClassSize, this->Crc);\n }\n virtual UClass* Register() const override {\n return UHxBootstrap::StaticClass();\n }\n\n#if UE_VER >= 416\n const TCHAR* ClassPackage() const {\n return UHxBootstrap::StaticPackage();\n }\n\n#endif\n};\n\n#if UE_VER >= 416\n#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, \"\/Script\/HaxeRuntime\", InitCode)\n#else\n#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode)\n#endif\n\nUHX_IMPLEMENT_INTRINSIC_CLASS(UHxBootstrap, HAXERUNTIME_API, UObject, COREUOBJECT_API,\n{\n check_hx_init();\n uhx::expose::HxcppRuntime::startLoadingDynamic();\n for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {\n UClass *val = It.Value();\n uhx::expose::HxcppRuntime::setDynamicNative((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));\n }\n uhx::expose::HxcppRuntime::setNativeTypes();\n for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {\n UClass *val = It.Value();\n uhx::expose::HxcppRuntime::addDynamicProperties((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));\n }\n});\n\n#undef UHX_IMPLEMENT_INTRINSIC_CLASS\n\n#endif\n\n#endif \/\/ WITH_EDITOR\n[CL-14383] Update to latest perforce change Change 14383 by waneck@wnk-asus-win-ls on 2017\/12\/06 22:37:05#include \"HaxeRuntime.h\"\n#if WITH_EDITOR\n\n#include \"uhx\/DynamicClass.h\"\n\n#include \"Misc\/Paths.h\"\n#include \"uhx\/expose\/HxcppRuntime.h\"\n\n#ifndef UHX_NO_UOBJECT\n\nstatic int uhx_uniqueId = 0;\n\nstatic TMap getCrcMapPvt() {\n TMap map;\n FString path = FPaths::ConvertRelativePathToFull(FPaths::GameDir()) + TEXT(\"\/Binaries\/Haxe\/gameCrcs.data\");\n auto file = FPlatformFileManager::Get().GetPlatformFile().OpenRead(*path, false);\n if (file == nullptr) {\n return map;\n }\n\n uint8 classNameSize = 0;\n char className[257];\n uint32 crc = 0;\n bool success = true;\n int magic = 0;\n if (!file->Read((uint8*) &magic, 4) || magic != 0xC5CC991A) {\n UE_LOG(HaxeLog, Error, TEXT(\"Invalid gameCrcs magic\"));\n success = false;\n }\n\n int ntry = 0;\n\n if (!success || !file->Read((uint8*) &ntry, 4)) {\n success = false;\n }\n uhx_uniqueId = ntry;\n\n#define READ(destination, bytesToRead) if (!file->Read(destination, bytesToRead)) { success = false; break; }\n\n while(success) {\n READ(&classNameSize, 1);\n if (classNameSize == 0) {\n break;\n }\n\n READ((uint8 *) className, classNameSize);\n className[classNameSize] = 0;\n READ((uint8 *) &crc, 4);\n \/\/ crc += ntry;\n FName classFName = FName( UTF8_TO_TCHAR(className) );\n if (crc == 0) {\n UE_LOG(HaxeLog, Error, TEXT(\"Unreal.hx CRC for class %s was 0\"), *classFName.ToString());\n }\n map.Add(classFName, crc);\n }\n\n#undef READ\n\n if (!success) {\n UE_LOG(HaxeLog,Error,TEXT(\"Unreal.hx CRC data was corrupt\"));\n }\n\n delete file;\n return map;\n}\n\nTMap& ::uhx::DynamicClassHelper::getCrcMap() {\n static TMap map = getCrcMapPvt();\n return map;\n}\n\nTMap& ::uhx::DynamicClassHelper::getDynamicsMap() {\n static TMap map;\n return map;\n}\n\n\n#endif\n\n#if (WITH_EDITOR && !NO_DYNAMIC_UCLASS)\n\n\/**\n * In order to add cppia dynamic class support, we need to be able to call `addDynamicProperties` in a very precise location - which is\n * right before the CDO is created. We must call this before the class CDO is created because otherwise the CDO will have the wrong size,\n * and bad things will happen. This UHxBootstrap class implements an intrinsic class so we can have a callback right when the classes\n * are registering, which is the exact place where we should add the dynamic properties\n **\/\nclass UHxBootstrap : public UObject {\n#if UE_VER >= 416\n#define UHX_HOTRELOAD 1\n#else\n#define UHX_HOTRELOAD WITH_HOT_RELOAD_CTORS\n#endif\n\n#if UHX_HOTRELOAD\n DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR_NO_VTABLE_CTOR(UHxBootstrap, UObject, 0, TEXT(\"\/Script\/HaxeRuntime\"), 0, HAXERUNTIME_API)\n\n UHxBootstrap(FVTableHelper& Helper) : UObject(Helper) {\n }\n#else\n DECLARE_CASTED_CLASS_INTRINSIC_NO_CTOR(UHxBootstrap, UObject, 0, HaxeRuntime, 0, HAXERUNTIME_API)\n#endif\n UHxBootstrap(const FObjectInitializer& ObjectInitializer = FObjectInitializer::Get()) : UObject(ObjectInitializer) {\n static bool endLoadingDynamicCalled = false;\n if (!endLoadingDynamicCalled) {\n endLoadingDynamicCalled = true;\n uhx::expose::HxcppRuntime::endLoadingDynamic();\n }\n }\n\n#undef UHX_HOTRELOAD\n};\n\n\/\/ make sure that UHxBootstrap is always hot reloaded, as its CRC constantly changes\ntemplate<>\nstruct TClassCompiledInDefer : public FFieldCompiledInInfo\n{\n TClassCompiledInDefer(const TCHAR* InName, SIZE_T InClassSize, uint32 InCrc)\n : FFieldCompiledInInfo(InClassSize, InCrc)\n {\n static FName className = FName(\"UHxBootstrap\");\n ::uhx::DynamicClassHelper::getCrcMap(); \/\/ make sure that the crc map is initialized\n this->Crc = uhx_uniqueId;\n UClassCompiledInDefer(this, InName, InClassSize, this->Crc);\n }\n virtual UClass* Register() const override {\n check_hx_init();\n return UHxBootstrap::StaticClass();\n }\n\n#if UE_VER >= 416\n const TCHAR* ClassPackage() const {\n return UHxBootstrap::StaticPackage();\n }\n\n#endif\n};\n\n#if UE_VER >= 416\n#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, \"\/Script\/HaxeRuntime\", InitCode)\n#else\n#define UHX_IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode) IMPLEMENT_INTRINSIC_CLASS(TClass, TRequiredAPI, TSuperClass, TSuperRequiredAPI, InitCode)\n#endif\n\nUHX_IMPLEMENT_INTRINSIC_CLASS(UHxBootstrap, HAXERUNTIME_API, UObject, COREUOBJECT_API,\n{\n check_hx_init();\n uhx::expose::HxcppRuntime::startLoadingDynamic();\n for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {\n UClass *val = It.Value();\n uhx::expose::HxcppRuntime::setDynamicNative((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));\n }\n uhx::expose::HxcppRuntime::setNativeTypes();\n for (auto It = ::uhx::DynamicClassHelper::getDynamicsMap().CreateIterator(); It; ++It) {\n UClass *val = It.Value();\n uhx::expose::HxcppRuntime::addDynamicProperties((unreal::UIntPtr) val, TCHAR_TO_UTF8(*It.Key().ToString()));\n }\n});\n\n#undef UHX_IMPLEMENT_INTRINSIC_CLASS\n\n#endif\n\n#endif \/\/ WITH_EDITOR\n<|endoftext|>"} {"text":"\/* Copyright (c) 2013-2014 Jeffrey Pfau\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n#include \"ConfigController.h\"\n\n#include \"GameController.h\"\n\n#include \n#include \n\nextern \"C\" {\n#include \"platform\/commandline.h\"\n}\n\nusing namespace QGBA;\n\nConfigOption::ConfigOption(QObject* parent)\n\t: QObject(parent)\n{\n}\n\nvoid ConfigOption::connect(std::function slot) {\n\tm_slot = slot;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, value]() {\n\t\temit valueChanged(value);\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, value));\n\treturn action;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {\n\treturn addValue(text, QString(value), parent);\n}\n\nQAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, action]() {\n\t\temit valueChanged(action->isChecked());\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, 1));\n\treturn action;\n}\n\nvoid ConfigOption::setValue(bool value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(int value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(unsigned value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(const char* value) {\n\tsetValue(QVariant(QString(value)));\n}\n\nvoid ConfigOption::setValue(const QVariant& value) {\n\tQPair action;\n\tforeach(action, m_actions) {\n\t\tbool signalsEnabled = action.first->blockSignals(true);\n\t\taction.first->setChecked(value == action.second);\n\t\taction.first->blockSignals(signalsEnabled);\n\t}\n\tm_slot(value);\n}\n\nConfigController::ConfigController(QObject* parent)\n\t: QObject(parent)\n\t, m_opts()\n{\n\tGBAConfigInit(&m_config, PORT);\n\n\tm_opts.audioSync = GameController::AUDIO_SYNC;\n\tm_opts.videoSync = GameController::VIDEO_SYNC;\n\tm_opts.fpsTarget = 60;\n\tm_opts.audioBuffers = 2048;\n\tGBAConfigLoadDefaults(&m_config, &m_opts);\n\tGBAConfigLoad(&m_config);\n\tGBAConfigMap(&m_config, &m_opts);\n}\n\nConfigController::~ConfigController() {\n\twrite();\n\n\tGBAConfigDeinit(&m_config);\n\tGBAConfigFreeOpts(&m_opts);\n}\n\nbool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {\n\treturn ::parseArguments(args, &m_config, argc, argv, 0);\n}\n\nConfigOption* ConfigController::addOption(const char* key) {\n\tQString optionName(key);\n\n\tif (m_optionSet.contains(optionName)) {\n\t\treturn m_optionSet[optionName];\n\t}\n\tConfigOption* newOption = new ConfigOption(this);\n\tm_optionSet[optionName] = newOption;\n\tconnect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {\n\t\tsetOption(key, value);\n\t});\n\treturn newOption;\n}\n\nvoid ConfigController::updateOption(const char* key) {\n\tif (!key) {\n\t\treturn;\n\t}\n\n\tQString optionName(key);\n\n\tif (!m_optionSet.contains(optionName)) {\n\t\treturn;\n\t}\n\tm_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));\n}\n\nvoid ConfigController::setOption(const char* key, bool value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, int value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, unsigned value) {\n\tGBAConfigSetUIntValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const char* value) {\n\tGBAConfigSetValue(&m_config, key, value);\n\tConfigOption* option = m_optionSet[QString(key)];\n\tif (option) {\n\t\toption->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const QVariant& value) {\n\tif (value.type() == QVariant::Bool) {\n\t\tsetOption(key, value.toBool());\n\t\treturn;\n\t}\n\tQString stringValue(value.toString());\n\tsetOption(key, stringValue.toLocal8Bit().constData());\n}\n\nvoid ConfigController::write() {\n\tGBAConfigSave(&m_config);\n}\nQt: Fix config options being erroneously added as null\/* Copyright (c) 2013-2014 Jeffrey Pfau\n *\n * This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this\n * file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/. *\/\n#include \"ConfigController.h\"\n\n#include \"GameController.h\"\n\n#include \n#include \n\nextern \"C\" {\n#include \"platform\/commandline.h\"\n}\n\nusing namespace QGBA;\n\nConfigOption::ConfigOption(QObject* parent)\n\t: QObject(parent)\n{\n}\n\nvoid ConfigOption::connect(std::function slot) {\n\tm_slot = slot;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const QVariant& value, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, value]() {\n\t\temit valueChanged(value);\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, value));\n\treturn action;\n}\n\nQAction* ConfigOption::addValue(const QString& text, const char* value, QMenu* parent) {\n\treturn addValue(text, QString(value), parent);\n}\n\nQAction* ConfigOption::addBoolean(const QString& text, QMenu* parent) {\n\tQAction* action = new QAction(text, parent);\n\taction->setCheckable(true);\n\tQObject::connect(action, &QAction::triggered, [this, action]() {\n\t\temit valueChanged(action->isChecked());\n\t});\n\tparent->addAction(action);\n\tm_actions.append(qMakePair(action, 1));\n\treturn action;\n}\n\nvoid ConfigOption::setValue(bool value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(int value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(unsigned value) {\n\tsetValue(QVariant(value));\n}\n\nvoid ConfigOption::setValue(const char* value) {\n\tsetValue(QVariant(QString(value)));\n}\n\nvoid ConfigOption::setValue(const QVariant& value) {\n\tQPair action;\n\tforeach(action, m_actions) {\n\t\tbool signalsEnabled = action.first->blockSignals(true);\n\t\taction.first->setChecked(value == action.second);\n\t\taction.first->blockSignals(signalsEnabled);\n\t}\n\tm_slot(value);\n}\n\nConfigController::ConfigController(QObject* parent)\n\t: QObject(parent)\n\t, m_opts()\n{\n\tGBAConfigInit(&m_config, PORT);\n\n\tm_opts.audioSync = GameController::AUDIO_SYNC;\n\tm_opts.videoSync = GameController::VIDEO_SYNC;\n\tm_opts.fpsTarget = 60;\n\tm_opts.audioBuffers = 2048;\n\tGBAConfigLoadDefaults(&m_config, &m_opts);\n\tGBAConfigLoad(&m_config);\n\tGBAConfigMap(&m_config, &m_opts);\n}\n\nConfigController::~ConfigController() {\n\twrite();\n\n\tGBAConfigDeinit(&m_config);\n\tGBAConfigFreeOpts(&m_opts);\n}\n\nbool ConfigController::parseArguments(GBAArguments* args, int argc, char* argv[]) {\n\treturn ::parseArguments(args, &m_config, argc, argv, 0);\n}\n\nConfigOption* ConfigController::addOption(const char* key) {\n\tQString optionName(key);\n\n\tif (m_optionSet.contains(optionName)) {\n\t\treturn m_optionSet[optionName];\n\t}\n\tConfigOption* newOption = new ConfigOption(this);\n\tm_optionSet[optionName] = newOption;\n\tconnect(newOption, &ConfigOption::valueChanged, [this, key](const QVariant& value) {\n\t\tsetOption(key, value);\n\t});\n\treturn newOption;\n}\n\nvoid ConfigController::updateOption(const char* key) {\n\tif (!key) {\n\t\treturn;\n\t}\n\n\tQString optionName(key);\n\n\tif (!m_optionSet.contains(optionName)) {\n\t\treturn;\n\t}\n\tm_optionSet[optionName]->setValue(GBAConfigGetValue(&m_config, key));\n}\n\nvoid ConfigController::setOption(const char* key, bool value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tQString optionName(key);\n\tif (m_optionSet.contains(optionName)) {\n\t\tm_optionSet[optionName]->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, int value) {\n\tGBAConfigSetIntValue(&m_config, key, value);\n\tQString optionName(key);\n\tif (m_optionSet.contains(optionName)) {\n\t\tm_optionSet[optionName]->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, unsigned value) {\n\tGBAConfigSetUIntValue(&m_config, key, value);\n\tQString optionName(key);\n\tif (m_optionSet.contains(optionName)) {\n\t\tm_optionSet[optionName]->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const char* value) {\n\tGBAConfigSetValue(&m_config, key, value);\n\tQString optionName(key);\n\tif (m_optionSet.contains(optionName)) {\n\t\tm_optionSet[optionName]->setValue(value);\n\t}\n}\n\nvoid ConfigController::setOption(const char* key, const QVariant& value) {\n\tif (value.type() == QVariant::Bool) {\n\t\tsetOption(key, value.toBool());\n\t\treturn;\n\t}\n\tQString stringValue(value.toString());\n\tsetOption(key, stringValue.toLocal8Bit().constData());\n}\n\nvoid ConfigController::write() {\n\tGBAConfigSave(&m_config);\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"Token.hpp\"\n#include \"TokenStream.hpp\"\n#include \"Calculator.hpp\"\n\nint main(int argc, char* argv[])\n{\n if(argc < 2)\n {\n std::cout << \"There aren't any operations send to Calculator\" << std::endl;\n return 1;\n }\n \n std::cout << \">> \" << argv[1] << std::endl;\n \n std::string expression{argv[1]};\n TokenStream tokenStream{expression + END_OF_EXPR + QUIT};\n\n try\n {\n double value = 0;\n Calculator parser{tokenStream};\n while (std::cin)\n {\n try\n {\n Token token = tokenStream.get();\n while (token.kind == END_OF_EXPR)\n {\n token = tokenStream.get();\n }\n if(token.kind == QUIT)\n {\n return 0;\n }\n tokenStream.putback(token);\n value = parser.expression();\n std::cout << \"= \" << value << std::endl;\n }\n catch (std::logic_error& error)\n {\n std::cerr << error.what() << std::endl;\n clean(tokenStream);\n }\n }\n return 0;\n }\n catch (std::logic_error& error)\n {\n std::cerr << error.what() << std::endl;\n return 1;\n }\n catch (...)\n {\n std::cerr << \"Unexpected exception\";\n return 2;\n }\n return 0;\n}\n\nSplitting body of main into functions#include \n#include \n\n#include \"Token.hpp\"\n#include \"TokenStream.hpp\"\n#include \"Calculator.hpp\"\n\nvoid calculate(ITokenStream& tokenStream)\n{\n double value = 0;\n Calculator parser{tokenStream};\n while (std::cin)\n {\n Token token = tokenStream.get();\n while (token.kind == END_OF_EXPR)\n {\n token = tokenStream.get();\n }\n if(token.kind == QUIT)\n {\n return;\n }\n tokenStream.putback(token);\n value = parser.expression();\n std::cout << \"= \" << value << std::endl;\n }\n}\n\nTokenStream passArgsToTokenStream(const char* argv[])\n{\n std::cout << \">> \" << argv[1] << std::endl;\n \n std::string expression{argv[1]};\n TokenStream tokenStream{expression + END_OF_EXPR + QUIT};\n return tokenStream;\n}\n\nint main(int argc, const char* argv[])\n{\n if(argc < 2)\n {\n std::cout << \"There aren't any operations send to Calculator\" << std::endl;\n return 1;\n }\n\n TokenStream tokenStream = passArgsToTokenStream(argv);\n \n try\n {\n calculate(tokenStream);\n return 0;\n }\n catch (std::logic_error& error)\n {\n std::cerr << error.what() << std::endl;\n clean(tokenStream);\n return 1;\n }\n catch (...)\n {\n std::cerr << \"Unexpected exception\";\n return 2;\n }\n \n}\n\n<|endoftext|>"} {"text":"\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n\n#include \"stackwindow.h\"\n#include \"stackhandler.h\"\n\n#include \"debuggeractions.h\"\n#include \"debuggercore.h\"\n#include \"debuggerengine.h\"\n#include \"debuggerdialogs.h\"\n#include \"memoryagent.h\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Debugger {\nnamespace Internal {\n\nstatic DebuggerEngine *currentEngine()\n{\n return debuggerCore()->currentEngine();\n}\n\nStackWindow::StackWindow(QWidget *parent)\n : BaseWindow(parent)\n{\n setWindowTitle(tr(\"Stack\"));\n setAlwaysAdjustColumnsAction(debuggerCore()->action(AlwaysAdjustStackColumnWidths));\n\n connect(debuggerCore()->action(UseAddressInStackView), SIGNAL(toggled(bool)),\n SLOT(showAddressColumn(bool)));\n connect(debuggerCore()->action(ExpandStack), SIGNAL(triggered()),\n SLOT(reloadFullStack()));\n connect(debuggerCore()->action(MaximalStackDepth), SIGNAL(triggered()),\n SLOT(reloadFullStack()));\n showAddressColumn(false);\n}\n\nvoid StackWindow::showAddressColumn(bool on)\n{\n setColumnHidden(4, !on);\n}\n\nvoid StackWindow::rowActivated(const QModelIndex &index)\n{\n currentEngine()->activateFrame(index.row());\n}\n\nvoid StackWindow::setModel(QAbstractItemModel *model)\n{\n BaseWindow::setModel(model);\n resizeColumnToContents(0);\n resizeColumnToContents(3);\n}\n\nvoid StackWindow::contextMenuEvent(QContextMenuEvent *ev)\n{\n DebuggerEngine *engine = currentEngine();\n StackHandler *handler = engine->stackHandler();\n const QModelIndex index = indexAt(ev->pos());\n const int row = index.row();\n const unsigned engineCapabilities = engine->debuggerCapabilities();\n StackFrame frame;\n if (row >= 0 && row < handler->stackSize())\n frame = handler->frameAt(row);\n const quint64 address = frame.address;\n\n QMenu menu;\n menu.addAction(debuggerCore()->action(ExpandStack));\n\n QAction *actCopyContents = menu.addAction(tr(\"Copy Contents to Clipboard\"));\n actCopyContents->setEnabled(model() != 0);\n\n if (engineCapabilities & CreateFullBacktraceCapability)\n menu.addAction(debuggerCore()->action(CreateFullBacktrace));\n\n QAction *actShowMemory = menu.addAction(QString());\n if (address == 0) {\n actShowMemory->setText(tr(\"Open Memory Editor\"));\n actShowMemory->setEnabled(false);\n } else {\n actShowMemory->setText(tr(\"Open Memory Editor at 0x%1\").arg(address, 0, 16));\n actShowMemory->setEnabled(engineCapabilities & ShowMemoryCapability);\n }\n\n QAction *actShowDisassemblerAt = menu.addAction(QString());\n QAction *actShowDisassembler = menu.addAction(tr(\"Open Disassembler...\"));\n actShowDisassembler->setEnabled(engineCapabilities & DisassemblerCapability);\n if (address == 0) {\n actShowDisassemblerAt->setText(tr(\"Open Disassembler\"));\n actShowDisassemblerAt->setEnabled(false);\n } else {\n actShowDisassemblerAt->setText(tr(\"Open Disassembler at 0x%1\").arg(address, 0, 16));\n actShowDisassemblerAt->setEnabled(engineCapabilities & DisassemblerCapability);\n }\n\n QAction *actLoadSymbols = 0;\n if (engineCapabilities & ShowModuleSymbolsCapability)\n actLoadSymbols = menu.addAction(tr(\"Try to Load Unknown Symbols\"));\n\n menu.addSeparator();\n#if 0 \/\/ @TODO: not implemented\n menu.addAction(debuggerCore()->action(UseToolTipsInStackView));\n#endif\n menu.addAction(debuggerCore()->action(UseAddressInStackView));\n\n addBaseContextActions(&menu);\n\n QAction *act = menu.exec(ev->globalPos());\n\n if (act == actCopyContents)\n copyContentsToClipboard();\n else if (act == actShowMemory) {\n const QString title = tr(\"Memory at Frame #%1 (%2) 0x%3\").\n arg(row).arg(frame.function).arg(address, 0, 16);\n QList ml;\n ml.push_back(MemoryMarkup(address, 1, QColor(Qt::blue).lighter(),\n tr(\"Frame #%1 (%2)\").arg(row).arg(frame.function)));\n engine->openMemoryView(address, 0, ml, QPoint(), title);\n } else if (act == actShowDisassembler) {\n AddressDialog dialog;\n if (address)\n dialog.setAddress(address);\n if (dialog.exec() == QDialog::Accepted)\n currentEngine()->openDisassemblerView(Location(dialog.address()));\n } else if (act == actShowDisassemblerAt)\n engine->openDisassemblerView(frame);\n else if (act == actLoadSymbols)\n engine->loadSymbolsForStack();\n else\n handleBaseContextAction(act);\n}\n\nvoid StackWindow::copyContentsToClipboard()\n{\n QString str;\n int n = model()->rowCount();\n int m = model()->columnCount();\n for (int i = 0; i != n; ++i) {\n for (int j = 0; j != m; ++j) {\n QModelIndex index = model()->index(i, j);\n str += model()->data(index).toString();\n str += '\\t';\n }\n str += '\\n';\n }\n QClipboard *clipboard = QApplication::clipboard();\n# ifdef Q_WS_X11\n clipboard->setText(str, QClipboard::Selection);\n# endif\n clipboard->setText(str, QClipboard::Clipboard);\n}\n\nvoid StackWindow::reloadFullStack()\n{\n currentEngine()->reloadFullStack();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\nDebugger: Show\/Hide Address Column in Stack Window\/**************************************************************************\n**\n** This file is part of Qt Creator\n**\n** Copyright (c) 2011 Nokia Corporation and\/or its subsidiary(-ies).\n**\n** Contact: Nokia Corporation (info@qt.nokia.com)\n**\n**\n** GNU Lesser General Public License Usage\n**\n** This file may be used under the terms of the GNU Lesser General Public\n** License version 2.1 as published by the Free Software Foundation and\n** appearing in the file LICENSE.LGPL included in the packaging of this file.\n** Please review the following information to ensure the GNU Lesser General\n** Public License version 2.1 requirements will be met:\n** http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** Other Usage\n**\n** Alternatively, this file may be used in accordance with the terms and\n** conditions contained in a signed written agreement between you and Nokia.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at info@qt.nokia.com.\n**\n**************************************************************************\/\n\n#include \"stackwindow.h\"\n#include \"stackhandler.h\"\n\n#include \"debuggeractions.h\"\n#include \"debuggercore.h\"\n#include \"debuggerengine.h\"\n#include \"debuggerdialogs.h\"\n#include \"memoryagent.h\"\n\n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Debugger {\nnamespace Internal {\n\nstatic DebuggerEngine *currentEngine()\n{\n return debuggerCore()->currentEngine();\n}\n\nStackWindow::StackWindow(QWidget *parent)\n : BaseWindow(parent)\n{\n setWindowTitle(tr(\"Stack\"));\n setAlwaysAdjustColumnsAction(debuggerCore()->action(AlwaysAdjustStackColumnWidths));\n\n connect(debuggerCore()->action(UseAddressInStackView), SIGNAL(toggled(bool)),\n SLOT(showAddressColumn(bool)));\n connect(debuggerCore()->action(ExpandStack), SIGNAL(triggered()),\n SLOT(reloadFullStack()));\n connect(debuggerCore()->action(MaximalStackDepth), SIGNAL(triggered()),\n SLOT(reloadFullStack()));\n showAddressColumn(false);\n}\n\nvoid StackWindow::showAddressColumn(bool on)\n{\n setColumnHidden(4, !on);\n}\n\nvoid StackWindow::rowActivated(const QModelIndex &index)\n{\n currentEngine()->activateFrame(index.row());\n}\n\nvoid StackWindow::setModel(QAbstractItemModel *model)\n{\n BaseWindow::setModel(model);\n resizeColumnToContents(0);\n resizeColumnToContents(3);\n showAddressColumn(debuggerCore()->action(UseAddressInStackView)->isChecked());\n}\n\nvoid StackWindow::contextMenuEvent(QContextMenuEvent *ev)\n{\n DebuggerEngine *engine = currentEngine();\n StackHandler *handler = engine->stackHandler();\n const QModelIndex index = indexAt(ev->pos());\n const int row = index.row();\n const unsigned engineCapabilities = engine->debuggerCapabilities();\n StackFrame frame;\n if (row >= 0 && row < handler->stackSize())\n frame = handler->frameAt(row);\n const quint64 address = frame.address;\n\n QMenu menu;\n menu.addAction(debuggerCore()->action(ExpandStack));\n\n QAction *actCopyContents = menu.addAction(tr(\"Copy Contents to Clipboard\"));\n actCopyContents->setEnabled(model() != 0);\n\n if (engineCapabilities & CreateFullBacktraceCapability)\n menu.addAction(debuggerCore()->action(CreateFullBacktrace));\n\n QAction *actShowMemory = menu.addAction(QString());\n if (address == 0) {\n actShowMemory->setText(tr(\"Open Memory Editor\"));\n actShowMemory->setEnabled(false);\n } else {\n actShowMemory->setText(tr(\"Open Memory Editor at 0x%1\").arg(address, 0, 16));\n actShowMemory->setEnabled(engineCapabilities & ShowMemoryCapability);\n }\n\n QAction *actShowDisassemblerAt = menu.addAction(QString());\n QAction *actShowDisassembler = menu.addAction(tr(\"Open Disassembler...\"));\n actShowDisassembler->setEnabled(engineCapabilities & DisassemblerCapability);\n if (address == 0) {\n actShowDisassemblerAt->setText(tr(\"Open Disassembler\"));\n actShowDisassemblerAt->setEnabled(false);\n } else {\n actShowDisassemblerAt->setText(tr(\"Open Disassembler at 0x%1\").arg(address, 0, 16));\n actShowDisassemblerAt->setEnabled(engineCapabilities & DisassemblerCapability);\n }\n\n QAction *actLoadSymbols = 0;\n if (engineCapabilities & ShowModuleSymbolsCapability)\n actLoadSymbols = menu.addAction(tr(\"Try to Load Unknown Symbols\"));\n\n menu.addSeparator();\n#if 0 \/\/ @TODO: not implemented\n menu.addAction(debuggerCore()->action(UseToolTipsInStackView));\n#endif\n menu.addAction(debuggerCore()->action(UseAddressInStackView));\n\n addBaseContextActions(&menu);\n\n QAction *act = menu.exec(ev->globalPos());\n\n if (act == actCopyContents)\n copyContentsToClipboard();\n else if (act == actShowMemory) {\n const QString title = tr(\"Memory at Frame #%1 (%2) 0x%3\").\n arg(row).arg(frame.function).arg(address, 0, 16);\n QList ml;\n ml.push_back(MemoryMarkup(address, 1, QColor(Qt::blue).lighter(),\n tr(\"Frame #%1 (%2)\").arg(row).arg(frame.function)));\n engine->openMemoryView(address, 0, ml, QPoint(), title);\n } else if (act == actShowDisassembler) {\n AddressDialog dialog;\n if (address)\n dialog.setAddress(address);\n if (dialog.exec() == QDialog::Accepted)\n currentEngine()->openDisassemblerView(Location(dialog.address()));\n } else if (act == actShowDisassemblerAt)\n engine->openDisassemblerView(frame);\n else if (act == actLoadSymbols)\n engine->loadSymbolsForStack();\n else\n handleBaseContextAction(act);\n}\n\nvoid StackWindow::copyContentsToClipboard()\n{\n QString str;\n int n = model()->rowCount();\n int m = model()->columnCount();\n for (int i = 0; i != n; ++i) {\n for (int j = 0; j != m; ++j) {\n QModelIndex index = model()->index(i, j);\n str += model()->data(index).toString();\n str += '\\t';\n }\n str += '\\n';\n }\n QClipboard *clipboard = QApplication::clipboard();\n# ifdef Q_WS_X11\n clipboard->setText(str, QClipboard::Selection);\n# endif\n clipboard->setText(str, QClipboard::Clipboard);\n}\n\nvoid StackWindow::reloadFullStack()\n{\n currentEngine()->reloadFullStack();\n}\n\n} \/\/ namespace Internal\n} \/\/ namespace Debugger\n<|endoftext|>"} {"text":"#include \"pipeline.h\"\n#include \n\nint main()\n{\n using namespace pipeline;\n\n auto for_each = [](auto&& rng){\n return source([rng](auto&& sink){\n for (auto const& x : rng) if (!sink(x)) return;\n });\n };\n\n auto pipeline = []{\n return filter ([](auto x){ return x>3; })\n | transform ([](auto x){ return x*x; })\n | filter ([](auto x){ return x<150; })\n | transform ([](auto x){ return x-10; })\n | take(3)\n | repeat(2)\n ;\n };\n\n auto p = pipeline() | sink([](auto x) { std::cout << \"sink: \" << x << std::endl; return true; });\n\n int n = 0;\n do { std::cout << \"source: \" << n << std::endl; }\n while ( p(n++) );\n\n std::cout << \"cancelled\" << std::endl;\n\n for_each(std::initializer_list{1,2,3,4,5,6,7,8,9,10,11})\n | pipeline()\n | sink([](auto x) { std::cout << \"sink: \" << x << std::endl; return true; });;\n\n std::cout << \"cancelled\" << std::endl;\n}\nfixing for_each source to not capture range by value.#include \"pipeline.h\"\n#include \n\nint main()\n{\n using namespace pipeline;\n\n auto for_each = [](auto&& rng){\n return source([&rng](auto&& sink){\n for (auto const& x : rng) if (!sink(x)) return;\n });\n };\n\n auto pipeline = []{\n return filter ([](auto x){ return x>3; })\n | transform ([](auto x){ return x*x; })\n | filter ([](auto x){ return x<150; })\n | transform ([](auto x){ return x-10; })\n | take(3)\n | repeat(2)\n ;\n };\n\n auto p = pipeline() | sink([](auto x) { std::cout << \"sink: \" << x << std::endl; return true; });\n\n int n = 0;\n do { std::cout << \"source: \" << n << std::endl; }\n while ( p(n++) );\n\n std::cout << \"cancelled\" << std::endl;\n\n for_each(std::initializer_list{1,2,3,4,5,6,7,8,9,10,11})\n | pipeline()\n | sink([](auto x) { std::cout << \"sink: \" << x << std::endl; return true; });;\n\n std::cout << \"cancelled\" << std::endl;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Execution_IntervalTimer_inl_\n#define _Stroika_Foundation_Execution_IntervalTimer_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\nnamespace Stroika::Foundation::Execution {\n\n \/*\n ********************************************************************************\n *************************** IntervalTimer::Manager *****************************\n ********************************************************************************\n *\/\n inline IntervalTimer::Manager::Manager (const shared_ptr& rep)\n : fRep_{rep}\n {\n }\n inline void IntervalTimer::Manager::AddOneShot (const TimerCallback& intervalTimer, const Time::Duration& when)\n {\n AssertNotNull (fRep_); \/\/ If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.\n fRep_->AddOneShot (intervalTimer, when);\n }\n inline void IntervalTimer::Manager ::AddRepeating (const TimerCallback& intervalTimer, const Time::Duration& repeatInterval, const optional& hysteresis)\n {\n AssertNotNull (fRep_); \/\/ If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.\n fRep_->AddRepeating (intervalTimer, repeatInterval, hysteresis);\n }\n inline void IntervalTimer::Manager::RemoveRepeating (const TimerCallback& intervalTimer) noexcept\n {\n AssertNotNull (fRep_); \/\/ If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.\n fRep_->RemoveRepeating (intervalTimer);\n }\n inline IntervalTimer::Manager IntervalTimer::Manager::sThe{nullptr};\n\n \/*\n ********************************************************************************\n ***************************** IntervalTimer::Adder *****************************\n ********************************************************************************\n *\/\n inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional& hysteresis)\n : fRepeatInterval_{repeatInterval}\n , fHysteresis_{hysteresis}\n , fManager_{&manager}\n , fFunction_{f}\n {\n Manager::sThe.AddRepeating (fFunction_, repeatInterval, hysteresis);\n if (runImmediately == RunImmediatelyFlag::eRunImmediately) {\n fFunction_ ();\n }\n }\n inline IntervalTimer::Adder::Adder (const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional& hysteresis)\n : Adder{Manager::sThe, f, repeatInterval, runImmediately, hysteresis}\n {\n }\n inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)\n : Adder{manager, f, repeatInterval, runImmediately, nullopt}\n {\n }\n inline IntervalTimer::Adder::Adder (const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)\n : Adder{f, repeatInterval, runImmediately, nullopt}\n {\n }\n inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function& f, const Time::Duration& repeatInterval, const optional& hysteresis)\n : Adder{manager, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}\n {\n }\n inline IntervalTimer::Adder::Adder (const Function& f, const Time::Duration& repeatInterval, const optional& hysteresis)\n : Adder{Manager::sThe, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}\n {\n }\n inline IntervalTimer::Adder::Adder (Adder&& src)\n : fRepeatInterval_{move (src.fRepeatInterval_)}\n , fHysteresis_{move (src.fHysteresis_)}\n , fManager_{src.fManager_}\n , fFunction_{move (src.fFunction_)}\n {\n \/\/ Move does not trigger re-add to manager\n src.fManager_ = nullptr; \/\/ so its DTOR does nothing\n }\n inline IntervalTimer::Adder::~Adder ()\n {\n if (fManager_ != nullptr) { \/\/ null check cuz Adder can be moved\n fManager_->RemoveRepeating (fFunction_);\n }\n }\n inline IntervalTimer::Adder& IntervalTimer::Adder::operator= (Adder&& rhs)\n {\n if (this != &rhs) {\n if (fManager_ != nullptr) { \/\/ null check cuz Adder can be moved\n fManager_->RemoveRepeating (fFunction_);\n }\n fManager_ = rhs.fManager_;\n rhs.fManager_ = nullptr; \/\/ so its DTOR doesnt remove\n fFunction_ = move (rhs.fFunction_);\n Manager::sThe.AddRepeating (fFunction_, fRepeatInterval_, fHysteresis_);\n }\n return *this;\n }\n inline Function IntervalTimer::Adder::GetCallback () const\n {\n return fFunction_;\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Execution_IntervalTimer_inl_*\/\ntweak last checkin\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2022. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Execution_IntervalTimer_inl_\n#define _Stroika_Foundation_Execution_IntervalTimer_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n\nnamespace Stroika::Foundation::Execution {\n\n \/*\n ********************************************************************************\n *************************** IntervalTimer::Manager *****************************\n ********************************************************************************\n *\/\n inline IntervalTimer::Manager::Manager (const shared_ptr& rep)\n : fRep_{rep}\n {\n }\n inline void IntervalTimer::Manager::AddOneShot (const TimerCallback& intervalTimer, const Time::Duration& when)\n {\n AssertNotNull (fRep_); \/\/ If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.\n fRep_->AddOneShot (intervalTimer, when);\n }\n inline void IntervalTimer::Manager ::AddRepeating (const TimerCallback& intervalTimer, const Time::Duration& repeatInterval, const optional& hysteresis)\n {\n AssertNotNull (fRep_); \/\/ If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.\n fRep_->AddRepeating (intervalTimer, repeatInterval, hysteresis);\n }\n inline void IntervalTimer::Manager::RemoveRepeating (const TimerCallback& intervalTimer) noexcept\n {\n AssertNotNull (fRep_); \/\/ If this fails, and its accessed through IntervalTimer::Manager::sThe, its probably because of lack of construction of IntervalTimer::Manager::Active object.\n fRep_->RemoveRepeating (intervalTimer);\n }\n inline IntervalTimer::Manager IntervalTimer::Manager::sThe{nullptr};\n\n \/*\n ********************************************************************************\n ***************************** IntervalTimer::Adder *****************************\n ********************************************************************************\n *\/\n inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional& hysteresis)\n : fRepeatInterval_{repeatInterval}\n , fHysteresis_{hysteresis}\n , fManager_{&manager}\n , fFunction_{f}\n {\n Manager::sThe.AddRepeating (fFunction_, repeatInterval, hysteresis);\n if (runImmediately == RunImmediatelyFlag::eRunImmediately) {\n IgnoreExceptionsExceptThreadAbortForCall (fFunction_ ());\n }\n }\n inline IntervalTimer::Adder::Adder (const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately, const optional& hysteresis)\n : Adder{Manager::sThe, f, repeatInterval, runImmediately, hysteresis}\n {\n }\n inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)\n : Adder{manager, f, repeatInterval, runImmediately, nullopt}\n {\n }\n inline IntervalTimer::Adder::Adder (const Function& f, const Time::Duration& repeatInterval, RunImmediatelyFlag runImmediately)\n : Adder{f, repeatInterval, runImmediately, nullopt}\n {\n }\n inline IntervalTimer::Adder::Adder (IntervalTimer::Manager& manager, const Function& f, const Time::Duration& repeatInterval, const optional& hysteresis)\n : Adder{manager, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}\n {\n }\n inline IntervalTimer::Adder::Adder (const Function& f, const Time::Duration& repeatInterval, const optional& hysteresis)\n : Adder{Manager::sThe, f, repeatInterval, RunImmediatelyFlag::eDontRunImmediately, hysteresis}\n {\n }\n inline IntervalTimer::Adder::Adder (Adder&& src)\n : fRepeatInterval_{move (src.fRepeatInterval_)}\n , fHysteresis_{move (src.fHysteresis_)}\n , fManager_{src.fManager_}\n , fFunction_{move (src.fFunction_)}\n {\n \/\/ Move does not trigger re-add to manager\n src.fManager_ = nullptr; \/\/ so its DTOR does nothing\n }\n inline IntervalTimer::Adder::~Adder ()\n {\n if (fManager_ != nullptr) { \/\/ null check cuz Adder can be moved\n fManager_->RemoveRepeating (fFunction_);\n }\n }\n inline IntervalTimer::Adder& IntervalTimer::Adder::operator= (Adder&& rhs)\n {\n if (this != &rhs) {\n if (fManager_ != nullptr) { \/\/ null check cuz Adder can be moved\n fManager_->RemoveRepeating (fFunction_);\n }\n fManager_ = rhs.fManager_;\n rhs.fManager_ = nullptr; \/\/ so its DTOR doesnt remove\n fFunction_ = move (rhs.fFunction_);\n Manager::sThe.AddRepeating (fFunction_, fRepeatInterval_, fHysteresis_);\n }\n return *this;\n }\n inline Function IntervalTimer::Adder::GetCallback () const\n {\n return fFunction_;\n }\n\n}\n\n#endif \/*_Stroika_Foundation_Execution_IntervalTimer_inl_*\/\n<|endoftext|>"} {"text":"\n#include \n#include \n\n#include \"format.h\"\n#include \"config.h\"\n#include \"error.h\"\n#include \"udp_socket.h\"\n#include \"strutils.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string pack_name( const std::string &name )\n{\n\tstd::string ret;\n\tsize_t loc = 0;\n\tret.push_back( '\\0' );\n\tfor ( size_t i = 0; i < name.size(); ++i )\n\t{\n\t\tif ( std::isalnum( name[i] ) )\n\t\t{\n\t\t\tret.push_back( name[i] );\n\t\t\tret[loc]++;\n\t\t}\n\t\telse if ( name[i] == '.' )\n\t\t{\n\t\t\tloc = ret.size();\n\t\t\tret.push_back( '\\0' );\n\t\t}\n\t\telse if ( !std::isspace( name[i] ) )\n\t\t\terror( \"Invalid character in domain name\" );\n\t}\n\n\tif ( ret.back() == '\\0' )\n\t\terror( \"Domain name ended with '.'\" );\n\n\tif ( ret.empty() )\n\t\terror( \"Domain name is empty.\" );\n\n\tret.push_back( '\\0' );\n\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid unpack_names( const std::string &str, std::vector &n )\n{\n\tstd::string ret;\n\n\tfor ( size_t i = 0; i < str.size(); )\n\t{\n\t\tuint8_t s = str[i++];\n\t\tif ( s == 0 )\n\t\t{\n\t\t\tif ( !ret.empty() )\n\t\t\t\tn.push_back( ret );\n\t\t\tret.clear();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( !ret.empty() )\n\t\t\t\tret.push_back( '.' );\n\t\t\tret += str.substr( i, s );\n\t\t\ti += s;\n\t\t}\n\t}\n\n\tif ( !ret.empty() )\n\t\tn.push_back( ret );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string from_hex( const std::string &h )\n{\n\tstd::string ret;\n\tfor ( size_t i = 0; i+1 < h.size(); i += 2 )\n\t\tret.push_back( std::stoul( h.substr( i, 2 ), NULL, 16 ) );\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string parse_mac( const std::string &opt )\n{\n\tstd::string ret( 6, '\\0' );\n\n\tsize_t p = 0;\n\tfor ( size_t i = 0; i < ret.size(); ++i )\n\t{\n\t\tsize_t tmp = p;\n\t\tuint32_t v = std::stoi( opt.substr( p ), &tmp, 16 );\n\t\tret[i] = v;\n\t\tp += tmp + 1;\n\t}\n\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string parse_option( const std::string &opt )\n{\n\tstd::string name;\n\tstd::vector args;\n\n\tparse_function( opt, name, args );\n\n\tif ( dhcp_options.find( name ) == dhcp_options.end() )\n\t\terror( format( \"Unknown DHCP option '{0}'\", name ) );\n\n\tint o = dhcp_options[name];\n\tstd::vector &argtypes = dhcp_args[o];\n\n\tif ( argtypes.back() == TYPE_MORE )\n\t{\n\t\targtypes.pop_back();\n\t\twhile ( argtypes.size() < args.size() )\n\t\t\targtypes.push_back( argtypes.back() );\n\t}\n\tif ( argtypes.size() == 1 && argtypes[0] == TYPE_NAMES )\n\t{\n\t\twhile ( argtypes.size() < args.size() )\n\t\t\targtypes.push_back( argtypes.back() );\n\t}\n\n\tif ( argtypes.size() != args.size() )\n\t\terror( format( \"Expected {0} arguments, got {1} instead\", argtypes.size(), args.size() ) );\n\n\tstd::string ret;\n\tret.push_back( o );\n\tret.push_back( '\\0' );\n\n\tsize_t size = 0;\n\n\tfor ( size_t i = 0; i < args.size(); ++i )\n\t{\n\t\tswitch ( argtypes[i] )\n\t\t{\n\t\t\tcase TYPE_ADDRESS:\n\t\t\t{\n\t\t\t\tsize += 4;\n\t\t\t\tuint32_t ip = dns_lookup( args[i].c_str() );\n\t\t\t\tret.append( std::string( reinterpret_cast(&ip), 4 ) );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_HWADDR:\n\t\t\t\terror( \"Not yet implemented\" );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_STRING:\n\t\t\t\tsize += args[i].size();\n\t\t\t\tret.append( args[i] );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_NAMES:\n\t\t\t{\n\t\t\t\tstd::string tmp = pack_name( args[i] );\n\t\t\t\tret.append( tmp );\n\t\t\t\tsize += tmp.size();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT32:\n\t\t\t{\n\t\t\t\tsize += 4;\n\t\t\t\tuint32_t ip = std::stoul( args[i] );\n\t\t\t\tret.append( reinterpret_cast(&ip), 4 );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT16:\n\t\t\t{\n\t\t\t\tsize += 2;\n\t\t\t\tuint16_t n = htons( std::stoul( args[i] ) );\n\t\t\t\tret.append( reinterpret_cast( &n ), 2 );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT8:\n\t\t\t{\n\t\t\t\tsize += 1;\n\t\t\t\tuint32_t n = std::stoul( args[0] );\n\t\t\t\tif ( n > 255 )\n\t\t\t\t\terror( format( \"Number (argument {0}) too large for option {1}\", i, name ) );\n\t\t\t\tret.push_back( n );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_HEX:\n\t\t\t{\n\t\t\t\tstd::string hex = from_hex( args[i] );\n\t\t\t\tret.push_back( hex.size() );\n\t\t\t\tret.append( hex );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\terror( \"Unknown option type\" );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tret[1] = size;\n\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string print_options( const std::string &opt )\n{\n\tstd::string ret;\n\n\tif ( opt.empty() )\n\t\terror( \"Invalid empty option\" );\n\n\tauto name = dhcp_names.find( uint8_t(opt[0]) );\n\tif ( name == dhcp_names.end() )\n\t{\n\t\tret = format( \"{0,B16,w2,f0}\", as_hex( opt ) );\n\t\treturn ret;\n\t}\n\n\tret += name->second;\n\tret.push_back( '(' );\n\n\tstd::vector &argtypes = dhcp_args[uint8_t(opt[0])];\n\n\tsize_t p = 2;\n\tType last = TYPE_MORE;\n\tfor ( size_t i = 0; i < argtypes.size(); ++i )\n\t{\n\t\tif ( i > 0 )\n\t\t\tret.push_back( ',' );\n\t\tret.push_back( ' ' );\n\n\t\tType atype = argtypes[i];\n\t\tif ( atype == TYPE_MORE )\n\t\t\tatype = last;\n\n\t\tif ( atype == TYPE_MORE )\n\t\t\terror( \"Invalid option specification\" );\n\n\t\tswitch ( atype )\n\t\t{\n\t\t\tcase TYPE_ADDRESS:\n\t\t\t\tif ( p+4 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for IP address\" );\n\t\t\t\tret += format( \"{0}\", as_hex( &opt[p], 4, '.' ) );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_HWADDR:\n\t\t\t\terror( \"Not yet implemented\" );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_UINT32:\n\t\t\t{\n\t\t\t\tif ( p+4 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for uint32\" );\n\t\t\t\tuint32_t n = 0;\n\t\t\t\tfor ( int i = 0; i < 4; ++i )\n\t\t\t\t\tn = ( n << 8 ) + uint8_t(opt[p+i]);\n\t\t\t\tret += format( \"{0}\", n );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT16:\n\t\t\t{\n\t\t\t\tif ( p+2 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for uint16\" );\n\t\t\t\tuint32_t n = 0;\n\t\t\t\tfor ( int i = 0; i < 2; ++i )\n\t\t\t\t\tn = ( n << 8 ) + uint8_t(opt[p+i]);\n\t\t\t\tret += format( \"{0}\", n );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT8:\n\t\t\t{\n\t\t\t\tif ( p+1 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for uint8\" );\n\t\t\t\tuint32_t n = uint8_t(opt[p]);\n\t\t\t\tret += format( \"{0}\", n );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_STRING:\n\t\t\t\tret += opt.substr( p, size_t(uint8_t(opt[1])) );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_HEX:\n\t\t\t{\n\t\t\t\tif ( opt.size() < 3 )\n\t\t\t\t\terror( format( \"Invalid option size {0}\", opt.size() ) );\n\t\t\t\tret += format( \"{0,B16,w2,f0}\", as_hex( opt.substr( 2, opt[1] ) ) );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_NAMES:\n\t\t\t{\n\t\t\t\tstd::vector names;\n\t\t\t\tunpack_names( opt.substr( p, size_t(uint8_t(opt[1])) ), names );\n\t\t\t\tfor ( size_t i = 0; i < names.size(); ++i )\n\t\t\t\t{\n\t\t\t\t\tif ( i > 0 )\n\t\t\t\t\t\tret.append( \", \" );\n\t\t\t\t\tret += names[i];\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\terror( \"Unknown option type\" );\n\t\t\t\tbreak;\n\t\t}\n\t\tlast = atype;\n\t}\n\tret += \" )\";\n\n\treturn ret;\n}\n\nFixed various bugs when printing options.\n#include \n#include \n\n#include \"format.h\"\n#include \"config.h\"\n#include \"error.h\"\n#include \"udp_socket.h\"\n#include \"strutils.h\"\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string pack_name( const std::string &name )\n{\n\tstd::string ret;\n\tsize_t loc = 0;\n\tret.push_back( '\\0' );\n\tfor ( size_t i = 0; i < name.size(); ++i )\n\t{\n\t\tif ( std::isalnum( name[i] ) )\n\t\t{\n\t\t\tret.push_back( name[i] );\n\t\t\tret[loc]++;\n\t\t}\n\t\telse if ( name[i] == '.' )\n\t\t{\n\t\t\tloc = ret.size();\n\t\t\tret.push_back( '\\0' );\n\t\t}\n\t\telse if ( !std::isspace( name[i] ) )\n\t\t\terror( \"Invalid character in domain name\" );\n\t}\n\n\tif ( ret.back() == '\\0' )\n\t\terror( \"Domain name ended with '.'\" );\n\n\tif ( ret.empty() )\n\t\terror( \"Domain name is empty.\" );\n\n\tret.push_back( '\\0' );\n\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nvoid unpack_names( const std::string &str, std::vector &n )\n{\n\tstd::string ret;\n\n\tfor ( size_t i = 0; i < str.size(); )\n\t{\n\t\tuint8_t s = str[i++];\n\t\tif ( s == 0 )\n\t\t{\n\t\t\tif ( !ret.empty() )\n\t\t\t\tn.push_back( ret );\n\t\t\tret.clear();\n\t\t}\n\t\telse\n\t\t{\n\t\t\tif ( !ret.empty() )\n\t\t\t\tret.push_back( '.' );\n\t\t\tret += str.substr( i, s );\n\t\t\ti += s;\n\t\t}\n\t}\n\n\tif ( !ret.empty() )\n\t\tn.push_back( ret );\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string from_hex( const std::string &h )\n{\n\tstd::string ret;\n\tfor ( size_t i = 0; i+1 < h.size(); i += 2 )\n\t\tret.push_back( std::stoul( h.substr( i, 2 ), NULL, 16 ) );\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string parse_mac( const std::string &opt )\n{\n\tstd::string ret( 6, '\\0' );\n\n\tsize_t p = 0;\n\tfor ( size_t i = 0; i < ret.size(); ++i )\n\t{\n\t\tsize_t tmp = p;\n\t\tuint32_t v = std::stoi( opt.substr( p ), &tmp, 16 );\n\t\tret[i] = v;\n\t\tp += tmp + 1;\n\t}\n\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string parse_option( const std::string &opt )\n{\n\tstd::string name;\n\tstd::vector args;\n\n\tparse_function( opt, name, args );\n\n\tif ( dhcp_options.find( name ) == dhcp_options.end() )\n\t\terror( format( \"Unknown DHCP option '{0}'\", name ) );\n\n\tint o = dhcp_options[name];\n\tstd::vector argtypes = dhcp_args[o];\n\n\tif ( argtypes.back() == TYPE_MORE )\n\t{\n\t\targtypes.pop_back();\n\t\twhile ( argtypes.size() < args.size() )\n\t\t\targtypes.push_back( argtypes.back() );\n\t}\n\tif ( argtypes.size() == 1 && argtypes[0] == TYPE_NAMES )\n\t{\n\t\twhile ( argtypes.size() < args.size() )\n\t\t\targtypes.push_back( argtypes.back() );\n\t}\n\n\tif ( argtypes.size() != args.size() )\n\t\terror( format( \"Expected {0} arguments, got {1} instead\", argtypes.size(), args.size() ) );\n\n\tstd::string ret;\n\tret.push_back( o );\n\tret.push_back( '\\0' );\n\n\tsize_t size = 0;\n\n\tfor ( size_t i = 0; i < args.size(); ++i )\n\t{\n\t\tswitch ( argtypes[i] )\n\t\t{\n\t\t\tcase TYPE_ADDRESS:\n\t\t\t{\n\t\t\t\tsize += 4;\n\t\t\t\tuint32_t ip = dns_lookup( args[i].c_str() );\n\t\t\t\tret.append( std::string( reinterpret_cast(&ip), 4 ) );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_HWADDR:\n\t\t\t\terror( \"Not yet implemented\" );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_STRING:\n\t\t\t\tsize += args[i].size();\n\t\t\t\tret.append( args[i] );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_NAMES:\n\t\t\t{\n\t\t\t\tstd::string tmp = pack_name( args[i] );\n\t\t\t\tret.append( tmp );\n\t\t\t\tsize += tmp.size();\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT32:\n\t\t\t{\n\t\t\t\tsize += 4;\n\t\t\t\tuint32_t ip = std::stoul( args[i] );\n\t\t\t\tret.append( reinterpret_cast(&ip), 4 );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT16:\n\t\t\t{\n\t\t\t\tsize += 2;\n\t\t\t\tuint16_t n = htons( std::stoul( args[i] ) );\n\t\t\t\tret.append( reinterpret_cast( &n ), 2 );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT8:\n\t\t\t{\n\t\t\t\tsize += 1;\n\t\t\t\tuint32_t n = std::stoul( args[i] );\n\t\t\t\tif ( n > 255 )\n\t\t\t\t\terror( format( \"Number (argument {0}) too large for option {1}\", i, name ) );\n\t\t\t\tret.push_back( n );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_HEX:\n\t\t\t{\n\t\t\t\tstd::string hex = from_hex( args[i] );\n\t\t\t\tret.push_back( hex.size() );\n\t\t\t\tret.append( hex );\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\terror( \"Unknown option type\" );\n\t\t\t\tbreak;\n\t\t}\n\t}\n\n\tret[1] = size;\n\n\treturn ret;\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nstd::string print_options( const std::string &opt )\n{\n\tstd::string ret;\n\n\tif ( opt.empty() )\n\t\terror( \"Invalid empty option\" );\n\n\tauto name = dhcp_names.find( uint8_t(opt[0]) );\n\tif ( name == dhcp_names.end() )\n\t{\n\t\tret = format( \"{0,B16,w2,f0}\", as_hex( opt ) );\n\t\treturn ret;\n\t}\n\n\tret += name->second;\n\tret.push_back( '(' );\n\n\tstd::vector argtypes = dhcp_args[uint8_t(opt[0])];\n\n\tsize_t p = 2;\n\tType last = TYPE_MORE;\n\tfor ( size_t i = 0; i < argtypes.size() && p != opt.size(); ++i )\n\t{\n\t\tif ( i > 0 )\n\t\t\tret.push_back( ',' );\n\t\tret.push_back( ' ' );\n\n\t\tType atype = argtypes[i];\n\t\tif ( atype == TYPE_MORE )\n\t\t{\n\t\t\tatype = last;\n\t\t\targtypes.push_back( TYPE_MORE );\n\t\t}\n\n\t\tif ( atype == TYPE_MORE )\n\t\t\terror( \"Invalid option specification\" );\n\n\t\tswitch ( atype )\n\t\t{\n\t\t\tcase TYPE_ADDRESS:\n\t\t\t\tif ( p+4 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for IP address\" );\n\t\t\t\tret += format( \"{0}\", as_hex( &opt[p], 4, '.' ) );\n\t\t\t\tp += 4;\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_HWADDR:\n\t\t\t\terror( \"Not yet implemented\" );\n\t\t\t\tbreak;\n\n\t\t\tcase TYPE_UINT32:\n\t\t\t{\n\t\t\t\tif ( p+4 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for uint32\" );\n\t\t\t\tuint32_t n = 0;\n\t\t\t\tfor ( int i = 0; i < 4; ++i )\n\t\t\t\t\tn = ( n << 8 ) + uint8_t(opt[p+i]);\n\t\t\t\tret += format( \"{0}\", n );\n\t\t\t\tp += 4;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT16:\n\t\t\t{\n\t\t\t\tif ( p+2 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for uint16\" );\n\t\t\t\tuint32_t n = 0;\n\t\t\t\tfor ( int i = 0; i < 2; ++i )\n\t\t\t\t\tn = ( n << 8 ) + uint8_t(opt[p+i]);\n\t\t\t\tret += format( \"{0}\", n );\n\t\t\t\tp += 2;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_UINT8:\n\t\t\t{\n\t\t\t\tif ( p+1 > opt.size() )\n\t\t\t\t\terror( \"Not enough data for uint8\" );\n\t\t\t\tuint32_t n = uint8_t(opt[p]);\n\t\t\t\tret += format( \"{0}\", n );\n\t\t\t\tp += 1;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_STRING:\n\t\t\t{\n\t\t\t\tsize_t size = uint8_t( opt[1] );\n\t\t\t\tret += opt.substr( p, size );\n\t\t\t\tp += size;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_HEX:\n\t\t\t{\n\t\t\t\tif ( opt.size() < 3 )\n\t\t\t\t\terror( format( \"Invalid option size {0}\", opt.size() ) );\n\n\t\t\t\tsize_t size = uint8_t( opt[1] );\n\t\t\t\tret += format( \"{0,B16,w2,f0}\", as_hex( opt.substr( 2, size ) ) );\n\t\t\t\tp += size;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tcase TYPE_NAMES:\n\t\t\t{\n\t\t\t\tstd::vector names;\n\n\t\t\t\tsize_t size = uint8_t( opt[1] );\n\t\t\t\tunpack_names( opt.substr( p, size ), names );\n\t\t\t\tfor ( size_t i = 0; i < names.size(); ++i )\n\t\t\t\t{\n\t\t\t\t\tif ( i > 0 )\n\t\t\t\t\t\tret.append( \", \" );\n\t\t\t\t\tret += names[i];\n\t\t\t\t}\n\t\t\t\tp += size;\n\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\tdefault:\n\t\t\t\terror( \"Unknown option type\" );\n\t\t\t\tbreak;\n\t\t}\n\t\tlast = atype;\n\t}\n\tret += \" )\";\n\n\treturn ret;\n}\n\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Memory_SmallStackBuffer_inl_\n#define _Stroika_Foundation_Memory_SmallStackBuffer_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \n#include \n#include \n\n#include \"..\/Debug\/Assertions.h\"\n#include \"..\/Execution\/Exceptions.h\"\n#include \"Common.h\"\n\nnamespace Stroika::Foundation::Memory {\n\n \/*\n ********************************************************************************\n ************************* SmallStackBuffer ************************\n ********************************************************************************\n *\/\n template \n inline SmallStackBuffer::SmallStackBuffer ()\n : fLiveData_ (BufferAsT_ ())\n {\n#if qDebug\n ::memcpy (fGuard1_, kGuard1_, sizeof (kGuard1_));\n ::memcpy (fGuard2_, kGuard2_, sizeof (kGuard2_));\n#endif\n Invariant ();\n }\n template \n inline SmallStackBuffer::SmallStackBuffer (size_t nElements)\n : SmallStackBuffer ()\n {\n resize (nElements);\n Invariant ();\n }\n template \n inline SmallStackBuffer::SmallStackBuffer (UninitializedConstructorFlag, size_t nElements)\n : SmallStackBuffer ()\n {\n static_assert (is_trivially_default_constructible_v);\n resize_uninitialized (nElements);\n Invariant ();\n }\n template \n template , char>*>\n SmallStackBuffer::SmallStackBuffer (ITERATOR_OF_T start, ITERATOR_OF_T end)\n : SmallStackBuffer (distance (start, end))\n {\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (start, end, this->begin ());\n#else\n uninitialized_copy (start, end, this->begin ());\n#endif\n Invariant ();\n }\n template \n template \n SmallStackBuffer::SmallStackBuffer (const SmallStackBuffer& from)\n : SmallStackBuffer (from.begin (), from.end ())\n {\n }\n template \n inline SmallStackBuffer::SmallStackBuffer (const SmallStackBuffer& from)\n : SmallStackBuffer (from.begin (), from.end ())\n {\n }\n template \n inline SmallStackBuffer::~SmallStackBuffer ()\n {\n Invariant ();\n DestroyElts_ (this->begin (), this->end ());\n if (fLiveData_ != BufferAsT_ ()) {\n \/\/ we must have used the heap...\n Deallocate_ (LiveDataAsAllocatedBytes_ ());\n }\n }\n template \n template \n SmallStackBuffer& SmallStackBuffer::operator= (const SmallStackBuffer& rhs)\n {\n Invariant ();\n \/\/ @todo this simple implementation could be more efficient\n DestroyElts_ (this->begin (), this->end ());\n fSize_ = 0;\n ReserveAtLeast (rhs.size ());\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());\n#else\n uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());\n#endif\n Invariant ();\n return *this;\n }\n template \n SmallStackBuffer& SmallStackBuffer::operator= (const SmallStackBuffer& rhs)\n {\n Invariant ();\n if (this != &rhs) {\n \/\/ @todo this simple implementation could be more efficient\n DestroyElts_ (this->begin (), this->end ());\n fSize_ = 0;\n ReserveAtLeast (rhs.size ());\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());\n#else\n uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());\n#endif\n Invariant ();\n }\n return *this;\n }\n template \n inline void SmallStackBuffer::GrowToSize (size_t nElements)\n {\n if (nElements > size ()) {\n resize (nElements);\n }\n }\n template \n inline void SmallStackBuffer::GrowToSize_uninitialized (size_t nElements)\n {\n static_assert (is_trivially_default_constructible_v);\n if (nElements > size ()) {\n resize_uninitialized (nElements);\n }\n }\n template \n inline void SmallStackBuffer::resize (size_t nElements)\n {\n if (nElements > fSize_) {\n \/\/ Growing\n if (nElements > capacity ()) {\n \/*\n * If we REALLY must grow, the double in size so unlikely we'll have to grow\/malloc\/copy again.\n *\/\n reserve (max (nElements, capacity () * 2));\n }\n uninitialized_fill (this->begin () + fSize_, this->begin () + nElements, T{});\n fSize_ = nElements;\n }\n else if (nElements < fSize_) {\n \/\/ Shrinking\n DestroyElts_ (this->begin () + nElements, this->end ());\n fSize_ = nElements;\n }\n Assert (fSize_ == nElements);\n Ensure (size () <= capacity ());\n }\n template \n inline void SmallStackBuffer::resize_uninitialized (size_t nElements)\n {\n static_assert (is_trivially_default_constructible_v);\n if (nElements > fSize_) {\n \/\/ Growing\n if (nElements > capacity ())\n [[UNLIKELY_ATTR]]\n {\n \/*\n * If we REALLY must grow, the double in size so unlikely we'll have to grow\/malloc\/copy again.\n *\/\n reserve (max (nElements, capacity () * 2));\n }\n fSize_ = nElements;\n }\n else if (nElements < fSize_) {\n \/\/ Shrinking\n DestroyElts_ (this->begin () + nElements, this->end ());\n fSize_ = nElements;\n }\n Assert (fSize_ == nElements);\n Ensure (size () <= capacity ());\n }\n template \n void SmallStackBuffer::reserve_ (size_t nElements)\n {\n Assert (nElements >= size ());\n Invariant ();\n size_t oldEltCount = capacity ();\n if (nElements != oldEltCount) {\n bool oldInPlaceBuffer = oldEltCount <= BUF_SIZE;\n bool newInPlaceBuffer = nElements <= BUF_SIZE;\n \/\/ Only if we changed if using inplace buffer, or if was and is using ramBuffer, and eltCount changed do we need to do anything\n if (oldInPlaceBuffer != newInPlaceBuffer or (not newInPlaceBuffer)) {\n bool memoryAllocationNeeded = not newInPlaceBuffer;\n Memory::Byte* newPtr = memoryAllocationNeeded ? Allocate_ (SizeInBytes_ (nElements)) : std::begin (fInlinePreallocatedBuffer_);\n\n \/\/ Initialize new memory from old\n Assert (this->begin () != reinterpret_cast (newPtr));\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (this->begin (), this->end (), reinterpret_cast (newPtr));\n#else\n uninitialized_copy (this->begin (), this->end (), reinterpret_cast (newPtr));\n#endif\n\n \/\/ destroy objects in old memory\n DestroyElts_ (this->begin (), this->end ());\n\n \/\/ free old memory if needed\n if (not oldInPlaceBuffer) {\n Assert (fLiveData_ != BufferAsT_ ());\n Deallocate_ (LiveDataAsAllocatedBytes_ ());\n }\n\n fLiveData_ = reinterpret_cast (newPtr);\n if (not newInPlaceBuffer) {\n fCapacityOfFreeStoreAllocation_ = nElements;\n }\n }\n }\n Ensure ((nElements <= BUF_SIZE && capacity () == BUF_SIZE) or (nElements > BUF_SIZE and nElements == capacity ()));\n Invariant ();\n }\n template \n inline typename SmallStackBuffer::iterator SmallStackBuffer::begin ()\n {\n return fLiveData_;\n }\n template \n inline typename SmallStackBuffer::iterator SmallStackBuffer::end ()\n {\n return fLiveData_ + fSize_;\n }\n template \n inline typename SmallStackBuffer::const_iterator SmallStackBuffer::begin () const\n {\n return fLiveData_;\n }\n template \n inline typename SmallStackBuffer::const_iterator SmallStackBuffer::end () const\n {\n return fLiveData_ + fSize_;\n }\n template \n inline size_t SmallStackBuffer::capacity () const\n {\n return (fLiveData_ == BufferAsT_ ()) ? BUF_SIZE : fCapacityOfFreeStoreAllocation_; \/\/ @see class Design Note\n }\n template \n inline void SmallStackBuffer::reserve (size_t newCapacity)\n {\n Require (newCapacity >= size ());\n reserve_ (newCapacity);\n }\n template \n inline void SmallStackBuffer::ReserveAtLeast (size_t newCapacity)\n {\n if (newCapacity > capacity ()) {\n reserve_ (newCapacity);\n }\n }\n template \n inline size_t SmallStackBuffer::GetSize () const\n {\n Ensure (fSize_ <= capacity ());\n return fSize_;\n }\n template \n inline size_t SmallStackBuffer::size () const\n {\n Ensure (fSize_ <= capacity ());\n return fSize_;\n }\n template \n inline typename SmallStackBuffer::reference SmallStackBuffer::at (size_t i)\n {\n Require (i < fSize_);\n return *(fLiveData_ + i);\n }\n template \n inline typename SmallStackBuffer::const_reference SmallStackBuffer::at (size_t i) const\n {\n Require (i < fSize_);\n return *(fLiveData_ + i);\n }\n template \n inline void SmallStackBuffer::push_back (Configuration::ArgByValueType e)\n {\n size_t s = size ();\n if (s < capacity ()) {\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (&e, &e + 1, this->end ());\n#else\n uninitialized_copy (&e, &e + 1, this->end ());\n#endif\n this->fSize_++;\n }\n else {\n if constexpr (is_trivially_default_constructible_v) {\n resize_uninitialized (s + 1);\n }\n else {\n resize (s + 1);\n }\n fLiveData_[s] = e;\n }\n }\n template \n inline SmallStackBuffer::operator T* ()\n {\n AssertNotNull (fLiveData_);\n return fLiveData_;\n }\n template \n inline SmallStackBuffer::operator const T* () const\n {\n AssertNotNull (fLiveData_);\n return fLiveData_;\n }\n template \n inline void SmallStackBuffer::Invariant () const\n {\n#if qDebug\n Invariant_ ();\n#endif\n }\n#if qDebug\n template \n void SmallStackBuffer::Invariant_ () const\n {\n Assert (capacity () >= size ());\n ValidateGuards_ ();\n }\n#if qCompiler_cpp17InlineStaticMemberOfTemplateLinkerUndefined_Buggy\n template \n constexpr Byte SmallStackBuffer::kGuard1_[8];\n template \n constexpr Byte SmallStackBuffer::kGuard2_[8];\n#endif\n template \n void SmallStackBuffer::ValidateGuards_ () const\n {\n Assert (::memcmp (kGuard1_, fGuard1_, sizeof (kGuard1_)) == 0);\n Assert (::memcmp (kGuard2_, fGuard2_, sizeof (kGuard2_)) == 0);\n }\n#endif\n template \n inline T* SmallStackBuffer::BufferAsT_ () noexcept\n {\n return reinterpret_cast (&fInlinePreallocatedBuffer_[0]);\n }\n template \n inline const T* SmallStackBuffer::BufferAsT_ () const noexcept\n {\n return reinterpret_cast (&fInlinePreallocatedBuffer_[0]);\n }\n template \n inline void SmallStackBuffer::DestroyElts_ (T* start, T* end) noexcept\n {\n for (auto i = start; i != end; ++i) {\n i->~T ();\n }\n }\n template \n inline Memory::Byte* SmallStackBuffer::LiveDataAsAllocatedBytes_ ()\n {\n Require (fLiveData_ != BufferAsT_ ());\n return reinterpret_cast (fLiveData_);\n }\n template \n inline Memory::Byte* SmallStackBuffer::Allocate_ (size_t bytes)\n {\n void* p = ::malloc (bytes);\n Execution::ThrowIfNull (p);\n return reinterpret_cast (p);\n }\n template \n inline void SmallStackBuffer::Deallocate_ (Memory::Byte* bytes)\n {\n if (bytes != nullptr) {\n ::free (bytes);\n }\n }\n}\n\n#endif \/*_Stroika_Foundation_Memory_SmallStackBuffer_inl_*\/\nCosmetic\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2018. All rights reserved\n *\/\n#ifndef _Stroika_Foundation_Memory_SmallStackBuffer_inl_\n#define _Stroika_Foundation_Memory_SmallStackBuffer_inl_ 1\n\n\/*\n ********************************************************************************\n ***************************** Implementation Details ***************************\n ********************************************************************************\n *\/\n#include \n#include \n#include \n\n#include \"..\/Debug\/Assertions.h\"\n#include \"..\/Execution\/Exceptions.h\"\n#include \"Common.h\"\n\nnamespace Stroika::Foundation::Memory {\n\n \/*\n ********************************************************************************\n ************************* SmallStackBuffer ************************\n ********************************************************************************\n *\/\n template \n inline SmallStackBuffer::SmallStackBuffer ()\n : fLiveData_ (BufferAsT_ ())\n {\n#if qDebug\n ::memcpy (fGuard1_, kGuard1_, sizeof (kGuard1_));\n ::memcpy (fGuard2_, kGuard2_, sizeof (kGuard2_));\n#endif\n Invariant ();\n }\n template \n inline SmallStackBuffer::SmallStackBuffer (size_t nElements)\n : SmallStackBuffer ()\n {\n resize (nElements);\n Invariant ();\n }\n template \n inline SmallStackBuffer::SmallStackBuffer (UninitializedConstructorFlag, size_t nElements)\n : SmallStackBuffer ()\n {\n static_assert (is_trivially_default_constructible_v);\n resize_uninitialized (nElements);\n Invariant ();\n }\n template \n template , char>*>\n SmallStackBuffer::SmallStackBuffer (ITERATOR_OF_T start, ITERATOR_OF_T end)\n : SmallStackBuffer (distance (start, end))\n {\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (start, end, this->begin ());\n#else\n uninitialized_copy (start, end, this->begin ());\n#endif\n Invariant ();\n }\n template \n template \n SmallStackBuffer::SmallStackBuffer (const SmallStackBuffer& from)\n : SmallStackBuffer (from.begin (), from.end ())\n {\n }\n template \n inline SmallStackBuffer::SmallStackBuffer (const SmallStackBuffer& from)\n : SmallStackBuffer (from.begin (), from.end ())\n {\n }\n template \n inline SmallStackBuffer::~SmallStackBuffer ()\n {\n Invariant ();\n DestroyElts_ (this->begin (), this->end ());\n if (fLiveData_ != BufferAsT_ ()) {\n \/\/ we must have used the heap...\n Deallocate_ (LiveDataAsAllocatedBytes_ ());\n }\n }\n template \n template \n SmallStackBuffer& SmallStackBuffer::operator= (const SmallStackBuffer& rhs)\n {\n Invariant ();\n \/\/ @todo this simple implementation could be more efficient\n DestroyElts_ (this->begin (), this->end ());\n fSize_ = 0;\n ReserveAtLeast (rhs.size ());\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());\n#else\n uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());\n#endif\n Invariant ();\n return *this;\n }\n template \n SmallStackBuffer& SmallStackBuffer::operator= (const SmallStackBuffer& rhs)\n {\n Invariant ();\n if (this != &rhs) {\n \/\/ @todo this simple implementation could be more efficient\n DestroyElts_ (this->begin (), this->end ());\n fSize_ = 0;\n ReserveAtLeast (rhs.size ());\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (rhs.begin (), rhs.end (), this->begin ());\n#else\n uninitialized_copy (rhs.begin (), rhs.end (), this->begin ());\n#endif\n Invariant ();\n }\n return *this;\n }\n template \n inline void SmallStackBuffer::GrowToSize (size_t nElements)\n {\n if (nElements > size ()) {\n resize (nElements);\n }\n }\n template \n inline void SmallStackBuffer::GrowToSize_uninitialized (size_t nElements)\n {\n static_assert (is_trivially_default_constructible_v);\n if (nElements > size ()) {\n resize_uninitialized (nElements);\n }\n }\n template \n inline void SmallStackBuffer::resize (size_t nElements)\n {\n if (nElements > fSize_) {\n \/\/ Growing\n if (nElements > capacity ()) {\n \/*\n * If we REALLY must grow, the double in size so unlikely we'll have to grow\/malloc\/copy again.\n *\/\n reserve (max (nElements, capacity () * 2));\n }\n uninitialized_fill (this->begin () + fSize_, this->begin () + nElements, T{});\n fSize_ = nElements;\n }\n else if (nElements < fSize_) {\n \/\/ Shrinking\n DestroyElts_ (this->begin () + nElements, this->end ());\n fSize_ = nElements;\n }\n Assert (fSize_ == nElements);\n Ensure (size () <= capacity ());\n }\n template \n inline void SmallStackBuffer::resize_uninitialized (size_t nElements)\n {\n static_assert (is_trivially_default_constructible_v);\n if (nElements > fSize_) {\n \/\/ Growing\n if (nElements > capacity ())\n [[UNLIKELY_ATTR]]\n {\n \/*\n * If we REALLY must grow, the double in size so unlikely we'll have to grow\/malloc\/copy again.\n *\/\n reserve (max (nElements, capacity () * 2));\n }\n fSize_ = nElements;\n }\n else if (nElements < fSize_) {\n \/\/ Shrinking\n DestroyElts_ (this->begin () + nElements, this->end ());\n fSize_ = nElements;\n }\n Assert (fSize_ == nElements);\n Ensure (size () <= capacity ());\n }\n template \n void SmallStackBuffer::reserve_ (size_t nElements)\n {\n Assert (nElements >= size ());\n Invariant ();\n size_t oldEltCount = capacity ();\n if (nElements != oldEltCount) {\n bool oldInPlaceBuffer = oldEltCount <= BUF_SIZE;\n bool newInPlaceBuffer = nElements <= BUF_SIZE;\n \/\/ Only if we changed if using inplace buffer, or if was and is using ramBuffer, and eltCount changed do we need to do anything\n if (oldInPlaceBuffer != newInPlaceBuffer or (not newInPlaceBuffer)) {\n bool memoryAllocationNeeded = not newInPlaceBuffer;\n Memory::Byte* newPtr = memoryAllocationNeeded ? Allocate_ (SizeInBytes_ (nElements)) : std::begin (fInlinePreallocatedBuffer_);\n\n \/\/ Initialize new memory from old\n Assert (this->begin () != reinterpret_cast (newPtr));\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (this->begin (), this->end (), reinterpret_cast (newPtr));\n#else\n uninitialized_copy (this->begin (), this->end (), reinterpret_cast (newPtr));\n#endif\n\n \/\/ destroy objects in old memory\n DestroyElts_ (this->begin (), this->end ());\n\n \/\/ free old memory if needed\n if (not oldInPlaceBuffer) {\n Assert (fLiveData_ != BufferAsT_ ());\n Deallocate_ (LiveDataAsAllocatedBytes_ ());\n }\n\n fLiveData_ = reinterpret_cast (newPtr);\n if (not newInPlaceBuffer) {\n fCapacityOfFreeStoreAllocation_ = nElements;\n }\n }\n }\n Ensure ((nElements <= BUF_SIZE && capacity () == BUF_SIZE) or (nElements > BUF_SIZE and nElements == capacity ()));\n Invariant ();\n }\n template \n inline typename SmallStackBuffer::iterator SmallStackBuffer::begin ()\n {\n return fLiveData_;\n }\n template \n inline typename SmallStackBuffer::iterator SmallStackBuffer::end ()\n {\n return fLiveData_ + fSize_;\n }\n template \n inline typename SmallStackBuffer::const_iterator SmallStackBuffer::begin () const\n {\n return fLiveData_;\n }\n template \n inline typename SmallStackBuffer::const_iterator SmallStackBuffer::end () const\n {\n return fLiveData_ + fSize_;\n }\n template \n inline size_t SmallStackBuffer::capacity () const\n {\n return (fLiveData_ == BufferAsT_ ()) ? BUF_SIZE : fCapacityOfFreeStoreAllocation_; \/\/ @see class Design Note\n }\n template \n inline void SmallStackBuffer::reserve (size_t newCapacity)\n {\n Require (newCapacity >= size ());\n reserve_ (newCapacity);\n }\n template \n inline void SmallStackBuffer::ReserveAtLeast (size_t newCapacity)\n {\n if (newCapacity > capacity ()) {\n reserve_ (newCapacity);\n }\n }\n template \n inline size_t SmallStackBuffer::GetSize () const\n {\n Ensure (fSize_ <= capacity ());\n return fSize_;\n }\n template \n inline size_t SmallStackBuffer::size () const\n {\n Ensure (fSize_ <= capacity ());\n return fSize_;\n }\n template \n inline typename SmallStackBuffer::reference SmallStackBuffer::at (size_t i)\n {\n Require (i < fSize_);\n return *(fLiveData_ + i);\n }\n template \n inline typename SmallStackBuffer::const_reference SmallStackBuffer::at (size_t i) const\n {\n Require (i < fSize_);\n return *(fLiveData_ + i);\n }\n template \n inline void SmallStackBuffer::push_back (Configuration::ArgByValueType e)\n {\n size_t s = size ();\n if (s < capacity ()) {\n#if qCompilerAndStdLib_uninitialized_copy_n_Warning_Buggy\n Configuration::uninitialized_copy_MSFT_BWA (&e, &e + 1, this->end ());\n#else\n uninitialized_copy (&e, &e + 1, this->end ());\n#endif\n this->fSize_++;\n }\n else {\n if constexpr (is_trivially_default_constructible_v) {\n resize_uninitialized (s + 1);\n }\n else {\n resize (s + 1);\n }\n fLiveData_[s] = e;\n }\n }\n template \n inline SmallStackBuffer::operator T* ()\n {\n AssertNotNull (fLiveData_);\n return fLiveData_;\n }\n template \n inline SmallStackBuffer::operator const T* () const\n {\n AssertNotNull (fLiveData_);\n return fLiveData_;\n }\n template \n inline void SmallStackBuffer::Invariant () const\n {\n#if qDebug\n Invariant_ ();\n#endif\n }\n#if qDebug\n template \n void SmallStackBuffer::Invariant_ () const\n {\n Assert (capacity () >= size ());\n ValidateGuards_ ();\n }\n#if qCompiler_cpp17InlineStaticMemberOfTemplateLinkerUndefined_Buggy\n template \n constexpr Byte SmallStackBuffer::kGuard1_[8];\n template \n constexpr Byte SmallStackBuffer::kGuard2_[8];\n#endif\n template \n void SmallStackBuffer::ValidateGuards_ () const\n {\n Assert (::memcmp (kGuard1_, fGuard1_, sizeof (kGuard1_)) == 0);\n Assert (::memcmp (kGuard2_, fGuard2_, sizeof (kGuard2_)) == 0);\n }\n#endif\n template \n inline T* SmallStackBuffer::BufferAsT_ () noexcept\n {\n return reinterpret_cast (&fInlinePreallocatedBuffer_[0]);\n }\n template \n inline const T* SmallStackBuffer::BufferAsT_ () const noexcept\n {\n return reinterpret_cast (&fInlinePreallocatedBuffer_[0]);\n }\n template \n inline void SmallStackBuffer::DestroyElts_ (T* start, T* end) noexcept\n {\n for (auto i = start; i != end; ++i) {\n i->~T ();\n }\n }\n template \n inline Memory::Byte* SmallStackBuffer::LiveDataAsAllocatedBytes_ ()\n {\n Require (fLiveData_ != BufferAsT_ ());\n return reinterpret_cast (fLiveData_);\n }\n template \n inline Memory::Byte* SmallStackBuffer::Allocate_ (size_t bytes)\n {\n void* p = ::malloc (bytes);\n Execution::ThrowIfNull (p);\n return reinterpret_cast (p);\n }\n template \n inline void SmallStackBuffer::Deallocate_ (Memory::Byte* bytes)\n {\n if (bytes != nullptr) {\n ::free (bytes);\n }\n }\n}\n\n#endif \/*_Stroika_Foundation_Memory_SmallStackBuffer_inl_*\/\n<|endoftext|>"} {"text":"#include \"balance.h\"\n\nint count = 0;\n\nBalanceState::BalanceState(Adafruit_BNO055* imu)\n : imu(imu),\n drive(&leftServo, &rightServo),\n pid(&pidInput, &pidOutput, &pidTarget, 10, 1, 1, DIRECT) {}\n\nvoid BalanceState::enter() {\n Serial.println(F(\"\\n\\nEntering: Robot Balance State\"));\n\n if (!readConfig(cd)) {\n Serial.println(F(\"ERROR: Config Not found\"));\n stateGoto(NULL);\n return;\n }\n\n drive.setServoConfig(cd.lconfig, cd.rconfig);\n leftServo.attach(servoLeftPin);\n rightServo.attach(servoRightPin);\n\n pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);\n pid.SetOutputLimits(-1.0, 1.0);\n pid.SetSampleTime(10);\n drive.drive(0);\n pid.SetMode(AUTOMATIC);\n pidTarget = 0;\n}\n\nvoid BalanceState::action() {\n sensors_event_t event;\n imu->getEvent(&event);\n\n pidInput = event.orientation.y \/ 90.0;\n pid.Compute();\n\n if (event.orientation.y < 10.0 && event.orientation.y > -10.0)\n drive.drive(1000 * pidOutput);\n else\n drive.drive(0);\n\n delay(5);\n int ch = Serial.read();\n if (ch == 'q') {\n stateGoto(NULL);\n }\n\n switch (ch) {\n case 'p':\n cd.Kp += 0.1;\n break;\n case 'P':\n cd.Kp -= 0.1;\n break;\n\n case 'i':\n cd.Ki += 0.1;\n break;\n case 'I':\n cd.Ki -= 0.1;\n break;\n\n case 'd':\n cd.Kd += 0.1;\n break;\n case 'D':\n cd.Kd -= 0.1;\n break;\n\n case 'w':\n pidTarget += 0.01;\n break;\n case 's':\n pidTarget -= 0.01;\n break;\n }\n\n pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);\n\n if (count == 100) {\n Serial.print(\"Y: \");\n Serial.print(event.orientation.y, 2);\n\n Serial.print(\"\\tKp: \");\n Serial.print(cd.Kp, 2);\n Serial.print(\"\\tKi: \");\n Serial.print(cd.Ki, 2);\n Serial.print(\"\\tKd: \");\n Serial.print(cd.Kd, 2);\n Serial.println(\"\");\n count = 0;\n }\n\n count++;\n}\n\nvoid BalanceState::leave() {\n leftServo.detach();\n rightServo.detach();\n\n writeConfig(cd);\n}\nsuspend pid calculation if angle is exceeded#include \"balance.h\"\n\nint count = 0;\n\nBalanceState::BalanceState(Adafruit_BNO055* imu)\n : imu(imu),\n drive(&leftServo, &rightServo),\n pid(&pidInput, &pidOutput, &pidTarget, 10, 1, 1, DIRECT) {}\n\nvoid BalanceState::enter() {\n Serial.println(F(\"\\n\\nEntering: Robot Balance State\"));\n\n if (!readConfig(cd)) {\n Serial.println(F(\"ERROR: Config Not found\"));\n stateGoto(NULL);\n return;\n }\n\n drive.setServoConfig(cd.lconfig, cd.rconfig);\n leftServo.attach(servoLeftPin);\n rightServo.attach(servoRightPin);\n\n pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);\n pid.SetOutputLimits(-1.0, 1.0);\n pid.SetSampleTime(10);\n drive.drive(0);\n pid.SetMode(AUTOMATIC);\n pidTarget = 0;\n}\n\nvoid BalanceState::action() {\n sensors_event_t event;\n imu->getEvent(&event);\n\n if (event.orientation.y < 10.0 && event.orientation.y > -10.0) {\n pidInput = event.orientation.y \/ 90.0;\n pid.Compute();\n\n drive.drive(1000 * pidOutput);\n } else {\n drive.drive(0);\n }\n\n delay(5);\n int ch = Serial.read();\n if (ch == 'q') {\n stateGoto(NULL);\n }\n\n switch (ch) {\n case 'p':\n cd.Kp += 0.1;\n break;\n case 'P':\n cd.Kp -= 0.1;\n break;\n\n case 'i':\n cd.Ki += 0.1;\n break;\n case 'I':\n cd.Ki -= 0.1;\n break;\n\n case 'd':\n cd.Kd += 0.1;\n break;\n case 'D':\n cd.Kd -= 0.1;\n break;\n\n case 'w':\n pidTarget += 0.01;\n break;\n case 's':\n pidTarget -= 0.01;\n break;\n }\n\n pid.SetTunings(cd.Kp, cd.Ki, cd.Kd);\n\n if (count == 100) {\n Serial.print(\"Y: \");\n Serial.print(event.orientation.y, 2);\n\n Serial.print(\"\\tKp: \");\n Serial.print(cd.Kp, 2);\n Serial.print(\"\\tKi: \");\n Serial.print(cd.Ki, 2);\n Serial.print(\"\\tKd: \");\n Serial.print(cd.Kd, 2);\n Serial.println(\"\");\n count = 0;\n }\n\n count++;\n}\n\nvoid BalanceState::leave() {\n leftServo.detach();\n rightServo.detach();\n\n writeConfig(cd);\n}\n<|endoftext|>"} {"text":"\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"cmsis_os.h\"\n#include \"fvp_emac.h\"\n#include \"mbed_interface.h\"\n#include \"mbed_assert.h\"\n#include \"netsocket\/nsapi_types.h\"\n#include \"mbed_shared_queues.h\"\n\n\n\/********************************************************************************\n * Internal data\n ********************************************************************************\/\n\n#define THREAD_STACKSIZE 512\n\n\/* Flags for worker thread *\/\n#define FLAG_TX (0x1u << 0)\n#define FLAG_RX (0x1u << 1)\n\n\/** \\brief Driver thread priority *\/\n#define THREAD_PRIORITY (osPriorityNormal)\n\n#define PHY_TASK_PERIOD_MS 200\n\n\nfvp_EMAC::fvp_EMAC() : _thread(THREAD_PRIORITY,THREAD_STACKSIZE,NULL,\"fvp_emac_thread\")\n\n{\n}\n\nvoid fvp_EMAC::ethernet_callback(lan91_event_t event, void *param)\n{\n fvp_EMAC *enet = static_cast(param);\n switch (event)\n {\n case LAN91_RxEvent:\n enet->rx_isr();\n break;\n case LAN91_TxEvent:\n enet->tx_isr();\n break;\n default:\n break;\n }\n}\n\n\/** \\brief Ethernet receive interrupt handler *\/\nvoid fvp_EMAC::rx_isr()\n{\n _thread.flags_set(FLAG_RX);\n}\n\n\/** \\brief Ethernet transmit interrupt handler *\/\nvoid fvp_EMAC::tx_isr()\n{\n _thread.flags_set(FLAG_TX);\n}\n\n\/** \\brief Low level init of the MAC and PHY. *\/\nbool fvp_EMAC::low_level_init_successful()\n{\n LAN91_init();\n LAN91_SetCallback(&fvp_EMAC::ethernet_callback, this);\n return true;\n}\n\n\/** \\brief Worker thread.\n *\n * Woken by thread flags to receive packets or clean up transmit\n *\n * \\param[in] pvParameters pointer to the interface data\n *\/\nvoid fvp_EMAC::thread_function(void* pvParameters)\n{\n struct fvp_EMAC *fvp_enet = static_cast(pvParameters);\n\n for (;;) {\n uint32_t flags = ThisThread::flags_wait_any(FLAG_RX|FLAG_TX);\n if (flags & FLAG_RX) {\n fvp_enet->packet_rx();\n }\n }\n}\n\n\n\/** \\brief Packet reception task\n *\n * This task is called when a packet is received. It will\n * pass the packet to the LWIP core.\n *\/\nvoid fvp_EMAC::packet_rx()\n{\n while(!LAN91_RxFIFOEmpty())\n {\n emac_mem_buf_t *temp_rxbuf = NULL;\n uint32_t *rx_payload_ptr;\n uint32_t rx_length = 0;\n\n temp_rxbuf = _memory_manager->alloc_heap(FVP_ETH_MAX_FLEN, LAN91_BUFF_ALIGNMENT);\n\n \/* no memory been allocated*\/\n if (NULL != temp_rxbuf) {\n\n rx_payload_ptr = (uint32_t*)_memory_manager->get_ptr(temp_rxbuf);\n rx_length = _memory_manager->get_len(temp_rxbuf);\n bool state;\n\n#ifdef LOCK_RX_THREAD\n \/* Get exclusive access *\/\n _TXLockMutex.lock();\n#endif\n state = LAN91_receive_frame(rx_payload_ptr, &rx_length);\n \n#ifdef LOCK_RX_THREAD\n _TXLockMutex.unlock();\n#endif\n if(!state)\n {\n _memory_manager->free(temp_rxbuf);\n continue;\n }\n else\n {\n _memory_manager->set_len(temp_rxbuf, rx_length);\n }\n _emac_link_input_cb(temp_rxbuf);\n }\n }\n LAN91_SetInterruptMasks(MSK_RCV);\n}\n\n\n\/** \\brief Low level output of a packet. Never call this from an\n * interrupt context, as it may block until TX descriptors\n * become available.\n *\n * \\param[in] buf the MAC packet to send (e.g. IP packet including MAC addresses and type)\n * \\return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent\n *\/\nbool fvp_EMAC::link_out(emac_mem_buf_t *buf)\n{\n \/\/ If buffer is chained or not aligned then make a contiguous aligned copy of it\n if (_memory_manager->get_next(buf) ||\n reinterpret_cast(_memory_manager->get_ptr(buf)) % LAN91_BUFF_ALIGNMENT) {\n emac_mem_buf_t *copy_buf;\n copy_buf = _memory_manager->alloc_heap(_memory_manager->get_total_len(buf), LAN91_BUFF_ALIGNMENT);\n if (NULL == copy_buf) {\n _memory_manager->free(buf);\n return false;\n }\n\n \/\/ Copy to new buffer and free original\n _memory_manager->copy(copy_buf, buf);\n _memory_manager->free(buf);\n buf = copy_buf;\n }\n\n \/* Save the buffer so that it can be freed when transmit is done *\/\n uint32_t * buffer;\n uint32_t tx_length = 0;\n bool state;\n buffer = (uint32_t *)(_memory_manager->get_ptr(buf));\n tx_length = _memory_manager->get_len(buf);\n\n \/* Get exclusive access *\/\n _TXLockMutex.lock();\n\n \/* Setup transfers *\/\n state = LAN91_send_frame(buffer,&tx_length);\n _TXLockMutex.unlock();\n \/* Restore access *\/\n\n\n if(!state){\n return false;\n }\n \/* Free the buffer *\/\n _memory_manager->free(buf);\n \n return true;\n}\n\n\/** \\brief PHY task monitoring the link *\/\nvoid fvp_EMAC::phy_task()\n{\n \/\/ Get current status\n lan91_phy_status_t connection_status;\n connection_status = LAN91_GetLinkStatus();\n\n if (connection_status != _prev_state && _emac_link_state_cb) {\n _emac_link_state_cb(connection_status);\n }\n _prev_state = connection_status;\n}\n\nbool fvp_EMAC::power_up()\n{\n \/* Initialize the hardware *\/\n if (!low_level_init_successful()) {\n return false;\n }\n\n \/* Start ethernet Worker thread *\/\n _thread.start(callback(&fvp_EMAC::thread_function, this));\n\n \/* Trigger thread to deal with any RX packets that arrived before thread was started *\/\n rx_isr();\n\n \/* PHY monitoring task *\/\n _prev_state = STATE_LINK_DOWN;\n\n mbed::mbed_event_queue()->call(mbed::callback(this, &fvp_EMAC::phy_task));\n\n \/* Allow the PHY task to detect the initial link state and set up the proper flags *\/\n wait_ms(10);\n\n _phy_task_handle = mbed::mbed_event_queue()->call_every(PHY_TASK_PERIOD_MS, mbed::callback(this, &fvp_EMAC::phy_task));\n\n return true;\n}\n\nuint32_t fvp_EMAC::get_mtu_size() const\n{\n return LAN91_ETH_MTU_SIZE;\n}\n\nuint32_t fvp_EMAC::get_align_preference() const\n{\n return LAN91_BUFF_ALIGNMENT;\n}\n\nvoid fvp_EMAC::get_ifname(char *name, uint8_t size) const\n{\n memcpy(name, FVP_ETH_IF_NAME, (size < sizeof(FVP_ETH_IF_NAME)) ? size : sizeof(FVP_ETH_IF_NAME));\n}\n\nuint8_t fvp_EMAC::get_hwaddr_size() const\n{\n return FVP_HWADDR_SIZE;\n}\n\nbool fvp_EMAC::get_hwaddr(uint8_t *addr) const\n{\n read_MACaddr(addr);\n return true;\n}\n\nvoid fvp_EMAC::set_hwaddr(const uint8_t *addr)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)\n{\n _emac_link_input_cb = input_cb;\n}\n\nvoid fvp_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)\n{\n _emac_link_state_cb = state_cb;\n}\n\nvoid fvp_EMAC::add_multicast_group(const uint8_t *addr)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::remove_multicast_group(const uint8_t *addr)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::set_all_multicast(bool all)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::power_down()\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)\n{\n _memory_manager = &mem_mngr;\n}\n\n\nfvp_EMAC &fvp_EMAC::get_instance() {\n static fvp_EMAC emac;\n return emac;\n}\n\n\/\/ Weak so a module can override\nMBED_WEAK EMAC &EMAC::get_default_instance() {\n return fvp_EMAC::get_instance();\n}\n\n\/** @} *\/\n\n\/* --------------------------------- End Of File ------------------------------ *\/\nupdate wait_ms() to sleep_for()\/* mbed Microcontroller Library\n * Copyright (c) 2018 ARM Limited\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \"cmsis_os.h\"\n#include \"fvp_emac.h\"\n#include \"mbed_interface.h\"\n#include \"mbed_assert.h\"\n#include \"netsocket\/nsapi_types.h\"\n#include \"mbed_shared_queues.h\"\n\n\n\/********************************************************************************\n * Internal data\n ********************************************************************************\/\n\n#define THREAD_STACKSIZE 512\n\n\/* Flags for worker thread *\/\n#define FLAG_TX (0x1u << 0)\n#define FLAG_RX (0x1u << 1)\n\n\/** \\brief Driver thread priority *\/\n#define THREAD_PRIORITY (osPriorityNormal)\n\n#define PHY_TASK_PERIOD_MS 200\n\n\nfvp_EMAC::fvp_EMAC() : _thread(THREAD_PRIORITY,THREAD_STACKSIZE,NULL,\"fvp_emac_thread\")\n\n{\n}\n\nvoid fvp_EMAC::ethernet_callback(lan91_event_t event, void *param)\n{\n fvp_EMAC *enet = static_cast(param);\n switch (event)\n {\n case LAN91_RxEvent:\n enet->rx_isr();\n break;\n case LAN91_TxEvent:\n enet->tx_isr();\n break;\n default:\n break;\n }\n}\n\n\/** \\brief Ethernet receive interrupt handler *\/\nvoid fvp_EMAC::rx_isr()\n{\n _thread.flags_set(FLAG_RX);\n}\n\n\/** \\brief Ethernet transmit interrupt handler *\/\nvoid fvp_EMAC::tx_isr()\n{\n _thread.flags_set(FLAG_TX);\n}\n\n\/** \\brief Low level init of the MAC and PHY. *\/\nbool fvp_EMAC::low_level_init_successful()\n{\n LAN91_init();\n LAN91_SetCallback(&fvp_EMAC::ethernet_callback, this);\n return true;\n}\n\n\/** \\brief Worker thread.\n *\n * Woken by thread flags to receive packets or clean up transmit\n *\n * \\param[in] pvParameters pointer to the interface data\n *\/\nvoid fvp_EMAC::thread_function(void* pvParameters)\n{\n struct fvp_EMAC *fvp_enet = static_cast(pvParameters);\n\n for (;;) {\n uint32_t flags = ThisThread::flags_wait_any(FLAG_RX|FLAG_TX);\n if (flags & FLAG_RX) {\n fvp_enet->packet_rx();\n }\n }\n}\n\n\n\/** \\brief Packet reception task\n *\n * This task is called when a packet is received. It will\n * pass the packet to the LWIP core.\n *\/\nvoid fvp_EMAC::packet_rx()\n{\n while(!LAN91_RxFIFOEmpty())\n {\n emac_mem_buf_t *temp_rxbuf = NULL;\n uint32_t *rx_payload_ptr;\n uint32_t rx_length = 0;\n\n temp_rxbuf = _memory_manager->alloc_heap(FVP_ETH_MAX_FLEN, LAN91_BUFF_ALIGNMENT);\n\n \/* no memory been allocated*\/\n if (NULL != temp_rxbuf) {\n\n rx_payload_ptr = (uint32_t*)_memory_manager->get_ptr(temp_rxbuf);\n rx_length = _memory_manager->get_len(temp_rxbuf);\n bool state;\n\n#ifdef LOCK_RX_THREAD\n \/* Get exclusive access *\/\n _TXLockMutex.lock();\n#endif\n state = LAN91_receive_frame(rx_payload_ptr, &rx_length);\n \n#ifdef LOCK_RX_THREAD\n _TXLockMutex.unlock();\n#endif\n if(!state)\n {\n _memory_manager->free(temp_rxbuf);\n continue;\n }\n else\n {\n _memory_manager->set_len(temp_rxbuf, rx_length);\n }\n _emac_link_input_cb(temp_rxbuf);\n }\n }\n LAN91_SetInterruptMasks(MSK_RCV);\n}\n\n\n\/** \\brief Low level output of a packet. Never call this from an\n * interrupt context, as it may block until TX descriptors\n * become available.\n *\n * \\param[in] buf the MAC packet to send (e.g. IP packet including MAC addresses and type)\n * \\return ERR_OK if the packet could be sent or an err_t value if the packet couldn't be sent\n *\/\nbool fvp_EMAC::link_out(emac_mem_buf_t *buf)\n{\n \/\/ If buffer is chained or not aligned then make a contiguous aligned copy of it\n if (_memory_manager->get_next(buf) ||\n reinterpret_cast(_memory_manager->get_ptr(buf)) % LAN91_BUFF_ALIGNMENT) {\n emac_mem_buf_t *copy_buf;\n copy_buf = _memory_manager->alloc_heap(_memory_manager->get_total_len(buf), LAN91_BUFF_ALIGNMENT);\n if (NULL == copy_buf) {\n _memory_manager->free(buf);\n return false;\n }\n\n \/\/ Copy to new buffer and free original\n _memory_manager->copy(copy_buf, buf);\n _memory_manager->free(buf);\n buf = copy_buf;\n }\n\n \/* Save the buffer so that it can be freed when transmit is done *\/\n uint32_t * buffer;\n uint32_t tx_length = 0;\n bool state;\n buffer = (uint32_t *)(_memory_manager->get_ptr(buf));\n tx_length = _memory_manager->get_len(buf);\n\n \/* Get exclusive access *\/\n _TXLockMutex.lock();\n\n \/* Setup transfers *\/\n state = LAN91_send_frame(buffer,&tx_length);\n _TXLockMutex.unlock();\n \/* Restore access *\/\n\n\n if(!state){\n return false;\n }\n \/* Free the buffer *\/\n _memory_manager->free(buf);\n \n return true;\n}\n\n\/** \\brief PHY task monitoring the link *\/\nvoid fvp_EMAC::phy_task()\n{\n \/\/ Get current status\n lan91_phy_status_t connection_status;\n connection_status = LAN91_GetLinkStatus();\n\n if (connection_status != _prev_state && _emac_link_state_cb) {\n _emac_link_state_cb(connection_status);\n }\n _prev_state = connection_status;\n}\n\nbool fvp_EMAC::power_up()\n{\n \/* Initialize the hardware *\/\n if (!low_level_init_successful()) {\n return false;\n }\n\n \/* Start ethernet Worker thread *\/\n _thread.start(callback(&fvp_EMAC::thread_function, this));\n\n \/* Trigger thread to deal with any RX packets that arrived before thread was started *\/\n rx_isr();\n\n \/* PHY monitoring task *\/\n _prev_state = STATE_LINK_DOWN;\n\n mbed::mbed_event_queue()->call(mbed::callback(this, &fvp_EMAC::phy_task));\n\n \/* Allow the PHY task to detect the initial link state and set up the proper flags *\/\n ThisThread::sleep_for(10);\n\n _phy_task_handle = mbed::mbed_event_queue()->call_every(PHY_TASK_PERIOD_MS, mbed::callback(this, &fvp_EMAC::phy_task));\n\n return true;\n}\n\nuint32_t fvp_EMAC::get_mtu_size() const\n{\n return LAN91_ETH_MTU_SIZE;\n}\n\nuint32_t fvp_EMAC::get_align_preference() const\n{\n return LAN91_BUFF_ALIGNMENT;\n}\n\nvoid fvp_EMAC::get_ifname(char *name, uint8_t size) const\n{\n memcpy(name, FVP_ETH_IF_NAME, (size < sizeof(FVP_ETH_IF_NAME)) ? size : sizeof(FVP_ETH_IF_NAME));\n}\n\nuint8_t fvp_EMAC::get_hwaddr_size() const\n{\n return FVP_HWADDR_SIZE;\n}\n\nbool fvp_EMAC::get_hwaddr(uint8_t *addr) const\n{\n read_MACaddr(addr);\n return true;\n}\n\nvoid fvp_EMAC::set_hwaddr(const uint8_t *addr)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::set_link_input_cb(emac_link_input_cb_t input_cb)\n{\n _emac_link_input_cb = input_cb;\n}\n\nvoid fvp_EMAC::set_link_state_cb(emac_link_state_change_cb_t state_cb)\n{\n _emac_link_state_cb = state_cb;\n}\n\nvoid fvp_EMAC::add_multicast_group(const uint8_t *addr)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::remove_multicast_group(const uint8_t *addr)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::set_all_multicast(bool all)\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::power_down()\n{\n \/* No-op at this stage *\/\n}\n\nvoid fvp_EMAC::set_memory_manager(EMACMemoryManager &mem_mngr)\n{\n _memory_manager = &mem_mngr;\n}\n\n\nfvp_EMAC &fvp_EMAC::get_instance() {\n static fvp_EMAC emac;\n return emac;\n}\n\n\/\/ Weak so a module can override\nMBED_WEAK EMAC &EMAC::get_default_instance() {\n return fvp_EMAC::get_instance();\n}\n\n\/** @} *\/\n\n\/* --------------------------------- End Of File ------------------------------ *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2015 Dan Leinir Turthra Jensen \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) version 3, or any\n * later version accepted by the membership of KDE e.V. (or its\n * successor approved by the membership of KDE e.V.), which shall\n * act as a proxy defined in Section 6 of version 3 of the license.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see .\n *\n *\/\n\n#include \"CategoryEntriesModel.h\"\n#include \"PropertyContainer.h\"\n#include \n#include \n#include \n#include \n\nclass CategoryEntriesModel::Private {\npublic:\n Private(CategoryEntriesModel* qq)\n : q(qq)\n {};\n ~Private()\n {\n \/\/ No deleting the entries - this is done by the master BookListModel already, so do that at your own risk\n }\n CategoryEntriesModel* q;\n QString name;\n QList entries;\n QList categoryModels;\n\n QObject* wrapBookEntry(const BookEntry* entry) {\n PropertyContainer* obj = new PropertyContainer(\"book\", q);\n obj->setProperty(\"author\", entry->author);\n obj->setProperty(\"currentPage\", QString::number(entry->currentPage));\n obj->setProperty(\"filename\", entry->filename);\n obj->setProperty(\"filetitle\", entry->filetitle);\n obj->setProperty(\"created\", entry->created);\n obj->setProperty(\"lastOpenedTime\", entry->lastOpenedTime);\n obj->setProperty(\"publisher\", entry->publisher);\n obj->setProperty(\"series\", entry->series);\n obj->setProperty(\"title\", entry->title);\n obj->setProperty(\"totalPages\", entry->totalPages);\n obj->setProperty(\"thumbnail\", entry->thumbnail);\n return obj;\n }\n};\n\nCategoryEntriesModel::CategoryEntriesModel(QObject* parent)\n : QAbstractListModel(parent)\n , d(new Private(this))\n{\n connect(this, SIGNAL(entryDataUpdated(BookEntry*)), this, SLOT(entryDataChanged(BookEntry*)));\n connect(this, SIGNAL(entryRemoved(BookEntry*)), this, SLOT(entryRemove(BookEntry*)));\n}\n\nCategoryEntriesModel::~CategoryEntriesModel()\n{\n delete d;\n}\n\nQHash CategoryEntriesModel::roleNames() const\n{\n QHash roles;\n roles[FilenameRole] = \"filename\";\n roles[FiletitleRole] = \"filetitle\";\n roles[TitleRole] = \"title\";\n roles[SeriesRole] = \"series\";\n roles[AuthorRole] = \"author\";\n roles[PublisherRole] = \"publisher\";\n roles[CreatedRole] = \"created\";\n roles[LastOpenedTimeRole] = \"lastOpenedTime\";\n roles[TotalPagesRole] = \"totalPages\";\n roles[CurrentPageRole] = \"currentPage\";\n roles[CategoryEntriesModelRole] = \"categoryEntriesModel\";\n roles[CategoryEntryCountRole] = \"categoryEntriesCount\";\n roles[ThumbnailRole] = \"thumbnail\";\n return roles;\n}\n\nQVariant CategoryEntriesModel::data(const QModelIndex& index, int role) const\n{\n QVariant result;\n if(index.isValid() && index.row() > -1)\n {\n if(index.row() < d->categoryModels.count())\n {\n CategoryEntriesModel* model = d->categoryModels[index.row()];\n switch(role)\n {\n case Qt::DisplayRole:\n case TitleRole:\n result.setValue(model->name());\n break;\n case CategoryEntryCountRole:\n result.setValue(model->bookCount());\n break;\n case CategoryEntriesModelRole:\n result.setValue(model);\n break;\n default:\n result.setValue(QString(\"Unknown role\"));\n break;\n }\n }\n else\n {\n const BookEntry* entry = d->entries[index.row() - d->categoryModels.count()];\n switch(role)\n {\n case Qt::DisplayRole:\n case FilenameRole:\n result.setValue(entry->filename);\n break;\n case FiletitleRole:\n result.setValue(entry->filetitle);\n break;\n case TitleRole:\n result.setValue(entry->title);\n break;\n case SeriesRole:\n result.setValue(entry->series);\n break;\n case AuthorRole:\n result.setValue(entry->author);\n break;\n case PublisherRole:\n result.setValue(entry->publisher);\n break;\n case CreatedRole:\n result.setValue(entry->created);\n break;\n case LastOpenedTimeRole:\n result.setValue(entry->lastOpenedTime);\n break;\n case TotalPagesRole:\n result.setValue(entry->totalPages);\n break;\n case CurrentPageRole:\n result.setValue(entry->currentPage);\n break;\n case CategoryEntriesModelRole:\n \/\/ Nothing, if we're not equipped with one such...\n break;\n case CategoryEntryCountRole:\n result.setValue(0);\n break;\n case ThumbnailRole:\n result.setValue(entry->thumbnail);\n break;\n default:\n result.setValue(QString(\"Unknown role\"));\n break;\n }\n }\n }\n return result;\n}\n\nint CategoryEntriesModel::rowCount(const QModelIndex& parent) const\n{\n if(parent.isValid())\n return 0;\n return d->categoryModels.count() + d->entries.count();\n}\n\nvoid CategoryEntriesModel::append(BookEntry* entry, Roles compareRole)\n{\n int insertionIndex = 0;\n for(; insertionIndex < d->entries.count(); ++insertionIndex)\n {\n if(compareRole == CreatedRole)\n {\n if(entry->created <= d->entries.at(insertionIndex)->created)\n { continue; }\n break;\n }\n else\n {\n if(QString::localeAwareCompare(d->entries.at(insertionIndex)->title, entry->title) > 0)\n { break; }\n }\n }\n beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);\n d->entries.insert(insertionIndex, entry);\n endInsertRows();\n}\n\nQString CategoryEntriesModel::name() const\n{\n return d->name;\n}\n\nvoid CategoryEntriesModel::setName(const QString& newName)\n{\n d->name = newName;\n}\n\nQObject * CategoryEntriesModel::leafModelForEntry(BookEntry* entry)\n{\n QObject* model(0);\n if(d->categoryModels.count() == 0)\n {\n if(d->entries.contains(entry)) {\n model = this;\n }\n }\n else\n {\n Q_FOREACH(CategoryEntriesModel* testModel, d->categoryModels)\n {\n model = testModel->leafModelForEntry(entry);\n if(model) {\n break;\n }\n }\n }\n return model;\n}\n\nvoid CategoryEntriesModel::addCategoryEntry(const QString& categoryName, BookEntry* entry)\n{\n if(categoryName.length() > 0)\n {\n QStringList splitName = categoryName.split(\"\/\");\n\/\/ qDebug() << \"Parsing\" << categoryName;\n QString nextCategory = splitName.takeFirst();\n CategoryEntriesModel* categoryModel = 0;\n Q_FOREACH(CategoryEntriesModel* existingModel, d->categoryModels)\n {\n if(existingModel->name() == nextCategory)\n {\n categoryModel = existingModel;\n break;\n }\n }\n if(!categoryModel)\n {\n categoryModel = new CategoryEntriesModel(this);\n connect(this, SIGNAL(entryDataUpdated(BookEntry*)), categoryModel, SIGNAL(entryDataUpdated(BookEntry*)));\n connect(this, SIGNAL(entryRemoved(BookEntry*)), categoryModel, SIGNAL(entryRemoved(BookEntry*)));\n categoryModel->setName(nextCategory);\n\n int insertionIndex = 0;\n for(; insertionIndex < d->categoryModels.count(); ++insertionIndex)\n {\n if(QString::localeAwareCompare(d->categoryModels.at(insertionIndex)->name(), categoryModel->name()) > 0)\n {\n break;\n }\n }\n beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);\n d->categoryModels.insert(insertionIndex, categoryModel);\n endInsertRows();\n }\n categoryModel->append(entry);\n categoryModel->addCategoryEntry(splitName.join(\"\/\"), entry);\n }\n}\n\nQObject* CategoryEntriesModel::get(int index)\n{\n BookEntry* entry = new BookEntry();\n bool deleteEntry = true;\n if(index > -1 && index < d->entries.count())\n {\n entry = d->entries.at(index);\n deleteEntry = false;\n }\n QObject* obj = d->wrapBookEntry(entry);\n if(deleteEntry)\n {\n delete entry;\n }\n return obj;\n}\n\nint CategoryEntriesModel::indexOfFile(QString filename)\n{\n int index = -1, i = 0;\n if(QFile::exists(filename))\n {\n Q_FOREACH(BookEntry* entry, d->entries)\n {\n if(entry->filename == filename)\n {\n index = i;\n break;\n }\n ++i;\n }\n }\n return index;\n}\n\nbool CategoryEntriesModel::indexIsBook(int index)\n{\n if(index < d->categoryModels.count() || index >= rowCount()) {\n return false;\n }\n return true;\n}\n\nint CategoryEntriesModel::bookCount() const\n{\n return d->entries.count();\n}\n\nQObject* CategoryEntriesModel::getEntry(int index)\n{\n PropertyContainer* obj = new PropertyContainer(\"book\", this);\n if(index < 0 && index > rowCount() -1) {\n \/\/ don't be a silly person, you can't get a nothing...\n }\n else if(index > d->categoryModels.count()) {\n \/\/ This is a book - get a book!\n obj = qobject_cast(get(index - d->categoryModels.count()));\n }\n else {\n CategoryEntriesModel* catEntry = d->categoryModels.at(index);\n obj->setProperty(\"title\", catEntry->name());\n obj->setProperty(\"categoryEntriesCount\", catEntry->rowCount());\n obj->setProperty(\"entriesModel\", QVariant::fromValue(catEntry));\n }\n return obj;\n}\n\nQObject* CategoryEntriesModel::bookFromFile(QString filename)\n{\n PropertyContainer* obj = qobject_cast(get(indexOfFile(filename)));\n if(obj->property(\"filename\").toString().isEmpty()) {\n if(QFileInfo::exists(filename)) {\n QFileInfo info(filename);\n obj->setProperty(\"title\", info.completeBaseName());\n obj->setProperty(\"created\", info.created());\n\n KFileMetaData::UserMetaData data(filename);\n if (data.hasAttribute(\"peruse.currentPage\")) {\n int currentPage = data.attribute(\"peruse.currentPage\").toInt();\n obj->setProperty(\"currentPage\", QVariant::fromValue(currentPage));\n }\n if (data.hasAttribute(\"peruse.totalPages\")) {\n int totalPages = data.attribute(\"peruse.totalPages\").toInt();\n obj->setProperty(\"totalPages\", QVariant::fromValue(totalPages));\n }\n obj->setProperty(\"filename\", filename);\n\n QString thumbnail;\n if(filename.toLower().endsWith(\"cbr\")) {\n thumbnail = QString(\"image:\/\/comiccover\/\").append(filename);\n }\n#ifdef USE_PERUSE_PDFTHUMBNAILER\n else if(filename.toLower().endsWith(\"pdf\")) {\n thumbnail = QString(\"image:\/\/pdfcover\/\").append(filename);\n }\n#endif\n else {\n thumbnail = QString(\"image:\/\/preview\/\").append(filename);\n }\n obj->setProperty(\"thumbnail\", thumbnail);\n }\n }\n return obj;\n}\n\nvoid CategoryEntriesModel::entryDataChanged(BookEntry* entry)\n{\n int entryIndex = d->entries.indexOf(entry) + d->categoryModels.count();\n QModelIndex changed = index(entryIndex);\n dataChanged(changed, changed);\n}\n\nvoid CategoryEntriesModel::entryRemove(BookEntry* entry)\n{\n int listIndex = d->entries.indexOf(entry);\n if(listIndex > -1) {\n int entryIndex = listIndex + d->categoryModels.count();\n beginRemoveRows(QModelIndex(), entryIndex, entryIndex);\n d->entries.removeAll(entry);\n endRemoveRows();\n }\n}\nMake the category get function return count as well\/*\n * Copyright (C) 2015 Dan Leinir Turthra Jensen \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) version 3, or any\n * later version accepted by the membership of KDE e.V. (or its\n * successor approved by the membership of KDE e.V.), which shall\n * act as a proxy defined in Section 6 of version 3 of the license.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library. If not, see .\n *\n *\/\n\n#include \"CategoryEntriesModel.h\"\n#include \"PropertyContainer.h\"\n#include \n#include \n#include \n#include \n\nclass CategoryEntriesModel::Private {\npublic:\n Private(CategoryEntriesModel* qq)\n : q(qq)\n {};\n ~Private()\n {\n \/\/ No deleting the entries - this is done by the master BookListModel already, so do that at your own risk\n }\n CategoryEntriesModel* q;\n QString name;\n QList entries;\n QList categoryModels;\n\n QObject* wrapBookEntry(const BookEntry* entry) {\n PropertyContainer* obj = new PropertyContainer(\"book\", q);\n obj->setProperty(\"author\", entry->author);\n obj->setProperty(\"currentPage\", QString::number(entry->currentPage));\n obj->setProperty(\"filename\", entry->filename);\n obj->setProperty(\"filetitle\", entry->filetitle);\n obj->setProperty(\"created\", entry->created);\n obj->setProperty(\"lastOpenedTime\", entry->lastOpenedTime);\n obj->setProperty(\"publisher\", entry->publisher);\n obj->setProperty(\"series\", entry->series);\n obj->setProperty(\"title\", entry->title);\n obj->setProperty(\"totalPages\", entry->totalPages);\n obj->setProperty(\"thumbnail\", entry->thumbnail);\n return obj;\n }\n};\n\nCategoryEntriesModel::CategoryEntriesModel(QObject* parent)\n : QAbstractListModel(parent)\n , d(new Private(this))\n{\n connect(this, SIGNAL(entryDataUpdated(BookEntry*)), this, SLOT(entryDataChanged(BookEntry*)));\n connect(this, SIGNAL(entryRemoved(BookEntry*)), this, SLOT(entryRemove(BookEntry*)));\n}\n\nCategoryEntriesModel::~CategoryEntriesModel()\n{\n delete d;\n}\n\nQHash CategoryEntriesModel::roleNames() const\n{\n QHash roles;\n roles[FilenameRole] = \"filename\";\n roles[FiletitleRole] = \"filetitle\";\n roles[TitleRole] = \"title\";\n roles[SeriesRole] = \"series\";\n roles[AuthorRole] = \"author\";\n roles[PublisherRole] = \"publisher\";\n roles[CreatedRole] = \"created\";\n roles[LastOpenedTimeRole] = \"lastOpenedTime\";\n roles[TotalPagesRole] = \"totalPages\";\n roles[CurrentPageRole] = \"currentPage\";\n roles[CategoryEntriesModelRole] = \"categoryEntriesModel\";\n roles[CategoryEntryCountRole] = \"categoryEntriesCount\";\n roles[ThumbnailRole] = \"thumbnail\";\n return roles;\n}\n\nQVariant CategoryEntriesModel::data(const QModelIndex& index, int role) const\n{\n QVariant result;\n if(index.isValid() && index.row() > -1)\n {\n if(index.row() < d->categoryModels.count())\n {\n CategoryEntriesModel* model = d->categoryModels[index.row()];\n switch(role)\n {\n case Qt::DisplayRole:\n case TitleRole:\n result.setValue(model->name());\n break;\n case CategoryEntryCountRole:\n result.setValue(model->bookCount());\n break;\n case CategoryEntriesModelRole:\n result.setValue(model);\n break;\n default:\n result.setValue(QString(\"Unknown role\"));\n break;\n }\n }\n else\n {\n const BookEntry* entry = d->entries[index.row() - d->categoryModels.count()];\n switch(role)\n {\n case Qt::DisplayRole:\n case FilenameRole:\n result.setValue(entry->filename);\n break;\n case FiletitleRole:\n result.setValue(entry->filetitle);\n break;\n case TitleRole:\n result.setValue(entry->title);\n break;\n case SeriesRole:\n result.setValue(entry->series);\n break;\n case AuthorRole:\n result.setValue(entry->author);\n break;\n case PublisherRole:\n result.setValue(entry->publisher);\n break;\n case CreatedRole:\n result.setValue(entry->created);\n break;\n case LastOpenedTimeRole:\n result.setValue(entry->lastOpenedTime);\n break;\n case TotalPagesRole:\n result.setValue(entry->totalPages);\n break;\n case CurrentPageRole:\n result.setValue(entry->currentPage);\n break;\n case CategoryEntriesModelRole:\n \/\/ Nothing, if we're not equipped with one such...\n break;\n case CategoryEntryCountRole:\n result.setValue(0);\n break;\n case ThumbnailRole:\n result.setValue(entry->thumbnail);\n break;\n default:\n result.setValue(QString(\"Unknown role\"));\n break;\n }\n }\n }\n return result;\n}\n\nint CategoryEntriesModel::rowCount(const QModelIndex& parent) const\n{\n if(parent.isValid())\n return 0;\n return d->categoryModels.count() + d->entries.count();\n}\n\nvoid CategoryEntriesModel::append(BookEntry* entry, Roles compareRole)\n{\n int insertionIndex = 0;\n for(; insertionIndex < d->entries.count(); ++insertionIndex)\n {\n if(compareRole == CreatedRole)\n {\n if(entry->created <= d->entries.at(insertionIndex)->created)\n { continue; }\n break;\n }\n else\n {\n if(QString::localeAwareCompare(d->entries.at(insertionIndex)->title, entry->title) > 0)\n { break; }\n }\n }\n beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);\n d->entries.insert(insertionIndex, entry);\n endInsertRows();\n}\n\nQString CategoryEntriesModel::name() const\n{\n return d->name;\n}\n\nvoid CategoryEntriesModel::setName(const QString& newName)\n{\n d->name = newName;\n}\n\nQObject * CategoryEntriesModel::leafModelForEntry(BookEntry* entry)\n{\n QObject* model(0);\n if(d->categoryModels.count() == 0)\n {\n if(d->entries.contains(entry)) {\n model = this;\n }\n }\n else\n {\n Q_FOREACH(CategoryEntriesModel* testModel, d->categoryModels)\n {\n model = testModel->leafModelForEntry(entry);\n if(model) {\n break;\n }\n }\n }\n return model;\n}\n\nvoid CategoryEntriesModel::addCategoryEntry(const QString& categoryName, BookEntry* entry)\n{\n if(categoryName.length() > 0)\n {\n QStringList splitName = categoryName.split(\"\/\");\n\/\/ qDebug() << \"Parsing\" << categoryName;\n QString nextCategory = splitName.takeFirst();\n CategoryEntriesModel* categoryModel = 0;\n Q_FOREACH(CategoryEntriesModel* existingModel, d->categoryModels)\n {\n if(existingModel->name() == nextCategory)\n {\n categoryModel = existingModel;\n break;\n }\n }\n if(!categoryModel)\n {\n categoryModel = new CategoryEntriesModel(this);\n connect(this, SIGNAL(entryDataUpdated(BookEntry*)), categoryModel, SIGNAL(entryDataUpdated(BookEntry*)));\n connect(this, SIGNAL(entryRemoved(BookEntry*)), categoryModel, SIGNAL(entryRemoved(BookEntry*)));\n categoryModel->setName(nextCategory);\n\n int insertionIndex = 0;\n for(; insertionIndex < d->categoryModels.count(); ++insertionIndex)\n {\n if(QString::localeAwareCompare(d->categoryModels.at(insertionIndex)->name(), categoryModel->name()) > 0)\n {\n break;\n }\n }\n beginInsertRows(QModelIndex(), insertionIndex, insertionIndex);\n d->categoryModels.insert(insertionIndex, categoryModel);\n endInsertRows();\n }\n categoryModel->append(entry);\n categoryModel->addCategoryEntry(splitName.join(\"\/\"), entry);\n }\n}\n\nQObject* CategoryEntriesModel::get(int index)\n{\n BookEntry* entry = new BookEntry();\n bool deleteEntry = true;\n if(index > -1 && index < d->entries.count())\n {\n entry = d->entries.at(index);\n deleteEntry = false;\n }\n QObject* obj = d->wrapBookEntry(entry);\n if(deleteEntry)\n {\n delete entry;\n }\n return obj;\n}\n\nint CategoryEntriesModel::indexOfFile(QString filename)\n{\n int index = -1, i = 0;\n if(QFile::exists(filename))\n {\n Q_FOREACH(BookEntry* entry, d->entries)\n {\n if(entry->filename == filename)\n {\n index = i;\n break;\n }\n ++i;\n }\n }\n return index;\n}\n\nbool CategoryEntriesModel::indexIsBook(int index)\n{\n if(index < d->categoryModels.count() || index >= rowCount()) {\n return false;\n }\n return true;\n}\n\nint CategoryEntriesModel::bookCount() const\n{\n return d->entries.count();\n}\n\nQObject* CategoryEntriesModel::getEntry(int index)\n{\n PropertyContainer* obj = new PropertyContainer(\"book\", this);\n if(index < 0 && index > rowCount() -1) {\n \/\/ don't be a silly person, you can't get a nothing...\n }\n else if(index > d->categoryModels.count()) {\n \/\/ This is a book - get a book!\n obj = qobject_cast(get(index - d->categoryModels.count()));\n }\n else {\n CategoryEntriesModel* catEntry = d->categoryModels.at(index);\n obj->setProperty(\"title\", catEntry->name());\n obj->setProperty(\"categoryEntriesCount\", catEntry->bookCount());\n obj->setProperty(\"entriesModel\", QVariant::fromValue(catEntry));\n }\n return obj;\n}\n\nQObject* CategoryEntriesModel::bookFromFile(QString filename)\n{\n PropertyContainer* obj = qobject_cast(get(indexOfFile(filename)));\n if(obj->property(\"filename\").toString().isEmpty()) {\n if(QFileInfo::exists(filename)) {\n QFileInfo info(filename);\n obj->setProperty(\"title\", info.completeBaseName());\n obj->setProperty(\"created\", info.created());\n\n KFileMetaData::UserMetaData data(filename);\n if (data.hasAttribute(\"peruse.currentPage\")) {\n int currentPage = data.attribute(\"peruse.currentPage\").toInt();\n obj->setProperty(\"currentPage\", QVariant::fromValue(currentPage));\n }\n if (data.hasAttribute(\"peruse.totalPages\")) {\n int totalPages = data.attribute(\"peruse.totalPages\").toInt();\n obj->setProperty(\"totalPages\", QVariant::fromValue(totalPages));\n }\n obj->setProperty(\"filename\", filename);\n\n QString thumbnail;\n if(filename.toLower().endsWith(\"cbr\")) {\n thumbnail = QString(\"image:\/\/comiccover\/\").append(filename);\n }\n#ifdef USE_PERUSE_PDFTHUMBNAILER\n else if(filename.toLower().endsWith(\"pdf\")) {\n thumbnail = QString(\"image:\/\/pdfcover\/\").append(filename);\n }\n#endif\n else {\n thumbnail = QString(\"image:\/\/preview\/\").append(filename);\n }\n obj->setProperty(\"thumbnail\", thumbnail);\n }\n }\n return obj;\n}\n\nvoid CategoryEntriesModel::entryDataChanged(BookEntry* entry)\n{\n int entryIndex = d->entries.indexOf(entry) + d->categoryModels.count();\n QModelIndex changed = index(entryIndex);\n dataChanged(changed, changed);\n}\n\nvoid CategoryEntriesModel::entryRemove(BookEntry* entry)\n{\n int listIndex = d->entries.indexOf(entry);\n if(listIndex > -1) {\n int entryIndex = listIndex + d->categoryModels.count();\n beginRemoveRows(QModelIndex(), entryIndex, entryIndex);\n d->entries.removeAll(entry);\n endRemoveRows();\n }\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n\n#include \n\nusing DataType = float;\nusing VertexType = unsigned;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\nusing Filtration = aleph::topology::filtrations::Data;\n\nint main( int argc, char** argv )\n{\n bool useSuperlevelSets = false;\n\n {\n static option commandLineOptions[] = {\n { \"sublevel\" , no_argument, nullptr, 's' },\n { \"superlevel\" , no_argument, nullptr, 'S' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n int option = -1;\n while( ( option = getopt_long( argc, argv, \"sS\", commandLineOptions, nullptr ) ) != - 1)\n {\n switch( option )\n {\n case 's':\n useSuperlevelSets = false;\n break;\n case 'S':\n useSuperlevelSets = true;\n break;\n default:\n break;\n }\n }\n }\n\n if( ( argc - optind ) < 1 )\n return -1;\n\n std::string filename = argv[1];\n\n SimplicialComplex K;\n\n aleph::topology::io::MatrixReader reader;\n reader( filename, K );\n\n K.sort( Filtration() );\n\n auto diagrams = aleph::calculatePersistenceDiagrams( K );\n\n for( auto&& D : diagrams )\n {\n D.removeDiagonal();\n\n std::cout << D << \"\\n\";\n }\n}\nAdded superlevel set filtration support#include \n\n#include \n#include \n\n#include \n\n#include \n\n#include \n#include \n#include \n\n#include \n\nusing DataType = float;\nusing VertexType = unsigned;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\nusing Filtration = aleph::topology::filtrations::Data;\n\nint main( int argc, char** argv )\n{\n bool useSuperlevelSets = false;\n\n {\n static option commandLineOptions[] = {\n { \"sublevel\" , no_argument, nullptr, 's' },\n { \"superlevel\" , no_argument, nullptr, 'S' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n int option = -1;\n while( ( option = getopt_long( argc, argv, \"sS\", commandLineOptions, nullptr ) ) != - 1)\n {\n switch( option )\n {\n case 's':\n useSuperlevelSets = false;\n break;\n case 'S':\n useSuperlevelSets = true;\n break;\n default:\n break;\n }\n }\n }\n\n if( ( argc - optind ) < 1 )\n return -1;\n\n std::string filename = argv[1];\n\n SimplicialComplex K;\n\n aleph::topology::io::MatrixReader reader;\n reader( filename, K );\n\n if( useSuperlevelSets )\n {\n using Filtration = \n aleph::topology::filtrations::Data >;\n \n K.sort( Filtration() );\n }\n else\n K.sort( Filtration() );\n\n auto diagrams = aleph::calculatePersistenceDiagrams( K );\n\n for( auto&& D : diagrams )\n {\n D.removeDiagonal();\n\n std::cout << D << \"\\n\";\n }\n}\n<|endoftext|>"} {"text":"#ifndef AMGCL_IO_MM_HPP\n#define AMGCL_IO_MM_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2018 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file amgcl\/io\/mm.hpp\n * \\author Denis Demidov \n * \\brief Readers for Matrix Market sparse matrices and dense vectors.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace amgcl {\nnamespace io {\n\n\/\/\/ Matrix market reader.\nclass mm_reader {\n public:\n \/\/\/ Open the file by name\n mm_reader(const std::string &fname) : f(fname.c_str()) {\n precondition(f, \"Failed to open file \\\"\" + fname + \"\\\"\");\n\n \/\/ Read banner.\n std::string line;\n precondition(std::getline(f, line), format_error());\n\n std::istringstream is(line);\n std::string banner, mtx, coord, dtype, storage;\n\n precondition(\n is >> banner >> mtx >> coord >> dtype >> storage,\n format_error());\n\n precondition(banner == \"%%MatrixMarket\", format_error(\"no banner\"));\n precondition(mtx == \"matrix\", format_error(\"not a matrix\"));\n\n if (storage == \"general\") {\n _symmetric = false;\n } else if (storage == \"symmetric\") {\n _symmetric = true;\n } else {\n precondition(false, \"unsupported storage type\");\n }\n\n if (coord == \"coordinate\") {\n _sparse = true;\n } else if (coord == \"array\") {\n _sparse = false;\n } else {\n precondition(false, format_error(\"unsupported coordinate type\"));\n }\n\n if (dtype == \"real\") {\n _complex = false;\n _integer = false;\n } else if (dtype == \"complex\") {\n _complex = true;\n _integer = false;\n } else if (dtype == \"integer\") {\n _complex = false;\n _integer = true;\n } else {\n precondition(false, format_error(\"unsupported data type\"));\n }\n\n \/\/ Skip comments.\n std::streampos pos;\n do {\n pos = f.tellg();\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n } while (line[0] == '%');\n\n \/\/ Get back to the first non-comment line.\n f.seekg(pos);\n\n \/\/ Read matrix size\n is.clear(); is.str(line);\n precondition(is >> nrows >> ncols, format_error());\n }\n\n \/\/\/ Matrix in the file is symmetric.\n bool is_symmetric() const { return _symmetric; }\n\n \/\/\/ Matrix in the file is sparse.\n bool is_sparse() const { return _sparse; }\n\n \/\/\/ Matrix in the file is complex-valued.\n bool is_complex() const { return _complex; }\n\n \/\/\/ Matrix in the file is integer-valued.\n bool is_integer() const { return _integer; }\n\n \/\/\/ Number of rows.\n size_t rows() const { return nrows; }\n\n \/\/\/ Number of rows.\n size_t cols() const { return ncols; }\n\n \/\/\/ Read sparse matrix from the file.\n template \n boost::tuple operator()(\n std::vector &ptr,\n std::vector &col,\n std::vector &val,\n ptrdiff_t row_beg = -1,\n ptrdiff_t row_end = -1\n )\n {\n precondition(_sparse, format_error(\"not a sparse matrix\"));\n precondition(boost::is_complex::value == _complex,\n _complex ?\n \"attempt to read complex values into real vector\" :\n \"attempt to read real values into complex vector\"\n );\n precondition(boost::is_integral::value == _integer,\n _integer ?\n \"attempt to read integer values into real vector\" :\n \"attempt to read real values into integer vector\"\n );\n\n \/\/ Read sizes\n ptrdiff_t n, m;\n size_t nnz;\n std::string line;\n std::istringstream is;\n {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n is.clear(); is.str(line);\n precondition(is >> n >> m >> nnz, format_error());\n }\n\n if (row_beg < 0) row_beg = 0;\n if (row_end < 0) row_end = n;\n\n precondition(row_beg >= 0 && row_end <= n,\n \"Wrong subset of rows is requested\");\n\n ptrdiff_t _nnz = _symmetric ? 2 * nnz : nnz;\n\n if (row_beg != 0 || row_end != n)\n _nnz *= 1.2 * (row_end - row_beg) \/ n;\n\n std::vector _row; _row.reserve(_nnz);\n std::vector _col; _col.reserve(_nnz);\n std::vector _val; _val.reserve(_nnz);\n\n ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0);\n\n for(size_t k = 0; k < nnz; ++k) {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n is.clear(); is.str(line);\n\n Idx i, j;\n Val v;\n\n precondition(is >> i >> j, format_error());\n\n i -= 1;\n j -= 1;\n\n v = read_value(is);\n\n if (row_beg <= i && i < row_end) {\n ++ptr[i - row_beg + 1];\n\n _row.push_back(i - row_beg);\n _col.push_back(j);\n _val.push_back(v);\n }\n\n if (_symmetric && i != j && row_beg <= j && j < row_end) {\n ++ptr[j - row_beg + 1];\n\n _row.push_back(j - row_beg);\n _col.push_back(i);\n _val.push_back(v);\n }\n }\n\n std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());\n\n col.resize(ptr.back());\n val.resize(ptr.back());\n\n for(size_t k = 0, e = val.size(); k < e; ++k) {\n Idx i = _row[k];\n Idx j = _col[k];\n Val v = _val[k];\n\n Idx head = ptr[i]++;\n col[head] = j;\n val[head] = v;\n }\n\n std::rotate(ptr.begin(), ptr.end() - 1, ptr.end());\n ptr.front() = 0;\n\n#pragma omp parallel for\n for(ptrdiff_t i = 0; i < n; ++i) {\n Idx beg = ptr[i];\n Idx end = ptr[i+1];\n\n amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg);\n }\n\n return boost::make_tuple(row_end - row_beg, m);\n }\n\n \/\/\/ Read dense array from the file.\n template \n boost::tuple operator()(\n std::vector &val,\n ptrdiff_t row_beg = -1,\n ptrdiff_t row_end = -1\n )\n {\n precondition(!_sparse, format_error(\"not a dense array\"));\n precondition(boost::is_complex::value == _complex,\n _complex ?\n \"attempt to read complex values into real vector\" :\n \"attempt to read real values into complex vector\"\n );\n precondition(boost::is_integral::value == _integer,\n _integer ?\n \"attempt to read integer values into real vector\" :\n \"attempt to read real values into integer vector\"\n );\n\n \/\/ Read sizes\n ptrdiff_t n, m;\n std::string line;\n std::istringstream is;\n {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n is.clear(); is.str(line);\n precondition(is >> n >> m, format_error());\n }\n\n if (row_beg < 0) row_beg = 0;\n if (row_end < 0) row_end = n;\n\n precondition(row_beg >= 0 && row_end <= n,\n \"Wrong subset of rows is requested\");\n\n val.resize((row_end - row_beg) * m);\n\n for(ptrdiff_t j = 0; j < m; ++j) {\n for(ptrdiff_t i = 0; i < n; ++i) {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n if (row_beg >= i && i < row_end) {\n is.clear(); is.str(line);\n val[(i - row_beg) * m + j] = read_value(is);\n }\n }\n }\n\n return boost::make_tuple(row_end - row_beg, m);\n }\n private:\n std::ifstream f;\n\n bool _sparse;\n bool _symmetric;\n bool _complex;\n bool _integer;\n\n size_t nrows, ncols;\n\n std::string format_error(const std::string &msg = \"\") const {\n std::string err_string = \"MatrixMarket format error\";\n if (!msg.empty())\n err_string += \" (\" + msg + \")\";\n return err_string;\n }\n\n template \n typename boost::enable_if::type, T>::type\n read_value(std::istream &s) {\n typename math::scalar_of::type x,y;\n precondition(s >> x >> y, format_error());\n return T(x,y);\n }\n\n template \n typename boost::disable_if::type, T>::type\n read_value(std::istream &s) {\n T x;\n if (boost::is_same::value) {\n \/\/ Special case:\n \/\/ We want to read 8bit integers from MatrixMarket, not chars.\n int i;\n precondition(s >> i, format_error());\n x = static_cast(i);\n } else {\n precondition(s >> x, format_error());\n }\n return x;\n }\n\n};\n\nnamespace detail {\ntemplate \ntypename boost::enable_if::type, std::ostream&>::type\nwrite_value(std::ostream &s, Val v) {\n return s << std::real(v) << \" \" << std::imag(v);\n}\n\ntemplate \ntypename boost::disable_if::type, std::ostream&>::type\nwrite_value(std::ostream &s, Val v) {\n return s << v;\n}\n\n} \/\/ namespace detail\n\n\/\/\/ Write dense array in Matrix Market format.\ntemplate \nvoid mm_write(\n const std::string &fname,\n const Val *data,\n size_t rows,\n size_t cols = 1\n )\n{\n std::ofstream f(fname.c_str());\n precondition(f, \"Failed to open file \\\"\" + fname + \"\\\" for writing\");\n\n \/\/ Banner\n f << \"%%MatrixMarket matrix array \";\n if (boost::is_complex::value) {\n f << \"complex \";\n } else if(boost::is_integral::value) {\n f << \"integer \";\n } else {\n f << \"real \";\n }\n f << \"general\\n\";\n\n \/\/ Sizes\n f << rows << \" \" << cols << \"\\n\";\n\n \/\/ Data\n for(size_t j = 0; j < cols; ++j) {\n for(size_t i = 0; i < rows; ++i) {\n detail::write_value(f, data[i * cols + j]) << \"\\n\";\n }\n }\n}\n\n\/\/\/ Write sparse matrix in Matrix Market format.\ntemplate \nvoid mm_write(const std::string &fname, const Matrix &A) {\n typedef typename backend::value_type::type Val;\n typedef typename backend::row_iterator::type row_iterator;\n\n const size_t rows = backend::rows(A);\n const size_t cols = backend::cols(A);\n const size_t nnz = backend::nonzeros(A);\n\n std::ofstream f(fname.c_str());\n precondition(f, \"Failed to open file \\\"\" + fname + \"\\\" for writing\");\n\n \/\/ Banner\n f << \"%%MatrixMarket matrix coordinate \";\n if (boost::is_complex::value) {\n f << \"complex \";\n } else if(boost::is_integral::value) {\n f << \"integer \";\n } else {\n f << \"real \";\n }\n f << \"general\\n\";\n\n \/\/ Sizes\n f << rows << \" \" << cols << \" \" << nnz << \"\\n\";\n\n \/\/ Data\n for(size_t i = 0; i < rows; ++i) {\n for(row_iterator a = backend::row_begin(A, i); a; ++a) {\n f << i + 1 << \" \" << a.col() + 1 << \" \";\n detail::write_value(f, a.value()) << \"\\n\";\n }\n }\n}\n\n} \/\/ namespace io\n} \/\/ namespace amgcl\n\n\n#endif\nFix a bug in chunked MatrixMarket reader#ifndef AMGCL_IO_MM_HPP\n#define AMGCL_IO_MM_HPP\n\n\/*\nThe MIT License\n\nCopyright (c) 2012-2018 Denis Demidov \n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n\/**\n * \\file amgcl\/io\/mm.hpp\n * \\author Denis Demidov \n * \\brief Readers for Matrix Market sparse matrices and dense vectors.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace amgcl {\nnamespace io {\n\n\/\/\/ Matrix market reader.\nclass mm_reader {\n public:\n \/\/\/ Open the file by name\n mm_reader(const std::string &fname) : f(fname.c_str()) {\n precondition(f, \"Failed to open file \\\"\" + fname + \"\\\"\");\n\n \/\/ Read banner.\n std::string line;\n precondition(std::getline(f, line), format_error());\n\n std::istringstream is(line);\n std::string banner, mtx, coord, dtype, storage;\n\n precondition(\n is >> banner >> mtx >> coord >> dtype >> storage,\n format_error());\n\n precondition(banner == \"%%MatrixMarket\", format_error(\"no banner\"));\n precondition(mtx == \"matrix\", format_error(\"not a matrix\"));\n\n if (storage == \"general\") {\n _symmetric = false;\n } else if (storage == \"symmetric\") {\n _symmetric = true;\n } else {\n precondition(false, \"unsupported storage type\");\n }\n\n if (coord == \"coordinate\") {\n _sparse = true;\n } else if (coord == \"array\") {\n _sparse = false;\n } else {\n precondition(false, format_error(\"unsupported coordinate type\"));\n }\n\n if (dtype == \"real\") {\n _complex = false;\n _integer = false;\n } else if (dtype == \"complex\") {\n _complex = true;\n _integer = false;\n } else if (dtype == \"integer\") {\n _complex = false;\n _integer = true;\n } else {\n precondition(false, format_error(\"unsupported data type\"));\n }\n\n \/\/ Skip comments.\n std::streampos pos;\n do {\n pos = f.tellg();\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n } while (line[0] == '%');\n\n \/\/ Get back to the first non-comment line.\n f.seekg(pos);\n\n \/\/ Read matrix size\n is.clear(); is.str(line);\n precondition(is >> nrows >> ncols, format_error());\n }\n\n \/\/\/ Matrix in the file is symmetric.\n bool is_symmetric() const { return _symmetric; }\n\n \/\/\/ Matrix in the file is sparse.\n bool is_sparse() const { return _sparse; }\n\n \/\/\/ Matrix in the file is complex-valued.\n bool is_complex() const { return _complex; }\n\n \/\/\/ Matrix in the file is integer-valued.\n bool is_integer() const { return _integer; }\n\n \/\/\/ Number of rows.\n size_t rows() const { return nrows; }\n\n \/\/\/ Number of rows.\n size_t cols() const { return ncols; }\n\n \/\/\/ Read sparse matrix from the file.\n template \n boost::tuple operator()(\n std::vector &ptr,\n std::vector &col,\n std::vector &val,\n ptrdiff_t row_beg = -1,\n ptrdiff_t row_end = -1\n )\n {\n precondition(_sparse, format_error(\"not a sparse matrix\"));\n precondition(boost::is_complex::value == _complex,\n _complex ?\n \"attempt to read complex values into real vector\" :\n \"attempt to read real values into complex vector\"\n );\n precondition(boost::is_integral::value == _integer,\n _integer ?\n \"attempt to read integer values into real vector\" :\n \"attempt to read real values into integer vector\"\n );\n\n \/\/ Read sizes\n ptrdiff_t n, m;\n size_t nnz;\n std::string line;\n std::istringstream is;\n {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n is.clear(); is.str(line);\n precondition(is >> n >> m >> nnz, format_error());\n }\n\n if (row_beg < 0) row_beg = 0;\n if (row_end < 0) row_end = n;\n\n precondition(row_beg >= 0 && row_end <= n,\n \"Wrong subset of rows is requested\");\n\n ptrdiff_t _nnz = _symmetric ? 2 * nnz : nnz;\n\n if (row_beg != 0 || row_end != n)\n _nnz *= 1.2 * (row_end - row_beg) \/ n;\n\n std::vector _row; _row.reserve(_nnz);\n std::vector _col; _col.reserve(_nnz);\n std::vector _val; _val.reserve(_nnz);\n\n ptr.resize(n+1); std::fill(ptr.begin(), ptr.end(), 0);\n\n for(size_t k = 0; k < nnz; ++k) {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n is.clear(); is.str(line);\n\n Idx i, j;\n Val v;\n\n precondition(is >> i >> j, format_error());\n\n i -= 1;\n j -= 1;\n\n v = read_value(is);\n\n if (row_beg <= i && i < row_end) {\n ++ptr[i - row_beg + 1];\n\n _row.push_back(i - row_beg);\n _col.push_back(j);\n _val.push_back(v);\n }\n\n if (_symmetric && i != j && row_beg <= j && j < row_end) {\n ++ptr[j - row_beg + 1];\n\n _row.push_back(j - row_beg);\n _col.push_back(i);\n _val.push_back(v);\n }\n }\n\n std::partial_sum(ptr.begin(), ptr.end(), ptr.begin());\n\n col.resize(ptr.back());\n val.resize(ptr.back());\n\n for(size_t k = 0, e = val.size(); k < e; ++k) {\n Idx i = _row[k];\n Idx j = _col[k];\n Val v = _val[k];\n\n Idx head = ptr[i]++;\n col[head] = j;\n val[head] = v;\n }\n\n std::rotate(ptr.begin(), ptr.end() - 1, ptr.end());\n ptr.front() = 0;\n\n#pragma omp parallel for\n for(ptrdiff_t i = 0; i < n; ++i) {\n Idx beg = ptr[i];\n Idx end = ptr[i+1];\n\n amgcl::detail::sort_row(&col[0] + beg, &val[0] + beg, end - beg);\n }\n\n return boost::make_tuple(row_end - row_beg, m);\n }\n\n \/\/\/ Read dense array from the file.\n template \n boost::tuple operator()(\n std::vector &val,\n ptrdiff_t row_beg = -1,\n ptrdiff_t row_end = -1\n )\n {\n precondition(!_sparse, format_error(\"not a dense array\"));\n precondition(boost::is_complex::value == _complex,\n _complex ?\n \"attempt to read complex values into real vector\" :\n \"attempt to read real values into complex vector\"\n );\n precondition(boost::is_integral::value == _integer,\n _integer ?\n \"attempt to read integer values into real vector\" :\n \"attempt to read real values into integer vector\"\n );\n\n \/\/ Read sizes\n ptrdiff_t n, m;\n std::string line;\n std::istringstream is;\n {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n is.clear(); is.str(line);\n precondition(is >> n >> m, format_error());\n }\n\n if (row_beg < 0) row_beg = 0;\n if (row_end < 0) row_end = n;\n\n precondition(row_beg >= 0 && row_end <= n,\n \"Wrong subset of rows is requested\");\n\n val.resize((row_end - row_beg) * m);\n\n for(ptrdiff_t j = 0; j < m; ++j) {\n for(ptrdiff_t i = 0; i < n; ++i) {\n precondition(std::getline(f, line), format_error(\"unexpected eof\"));\n if (row_beg <= i && i < row_end) {\n is.clear(); is.str(line);\n val[(i - row_beg) * m + j] = read_value(is);\n }\n }\n }\n\n return boost::make_tuple(row_end - row_beg, m);\n }\n private:\n std::ifstream f;\n\n bool _sparse;\n bool _symmetric;\n bool _complex;\n bool _integer;\n\n size_t nrows, ncols;\n\n std::string format_error(const std::string &msg = \"\") const {\n std::string err_string = \"MatrixMarket format error\";\n if (!msg.empty())\n err_string += \" (\" + msg + \")\";\n return err_string;\n }\n\n template \n typename boost::enable_if::type, T>::type\n read_value(std::istream &s) {\n typename math::scalar_of::type x,y;\n precondition(s >> x >> y, format_error());\n return T(x,y);\n }\n\n template \n typename boost::disable_if::type, T>::type\n read_value(std::istream &s) {\n T x;\n if (boost::is_same::value) {\n \/\/ Special case:\n \/\/ We want to read 8bit integers from MatrixMarket, not chars.\n int i;\n precondition(s >> i, format_error());\n x = static_cast(i);\n } else {\n precondition(s >> x, format_error());\n }\n return x;\n }\n\n};\n\nnamespace detail {\ntemplate \ntypename boost::enable_if::type, std::ostream&>::type\nwrite_value(std::ostream &s, Val v) {\n return s << std::real(v) << \" \" << std::imag(v);\n}\n\ntemplate \ntypename boost::disable_if::type, std::ostream&>::type\nwrite_value(std::ostream &s, Val v) {\n return s << v;\n}\n\n} \/\/ namespace detail\n\n\/\/\/ Write dense array in Matrix Market format.\ntemplate \nvoid mm_write(\n const std::string &fname,\n const Val *data,\n size_t rows,\n size_t cols = 1\n )\n{\n std::ofstream f(fname.c_str());\n precondition(f, \"Failed to open file \\\"\" + fname + \"\\\" for writing\");\n\n \/\/ Banner\n f << \"%%MatrixMarket matrix array \";\n if (boost::is_complex::value) {\n f << \"complex \";\n } else if(boost::is_integral::value) {\n f << \"integer \";\n } else {\n f << \"real \";\n }\n f << \"general\\n\";\n\n \/\/ Sizes\n f << rows << \" \" << cols << \"\\n\";\n\n \/\/ Data\n for(size_t j = 0; j < cols; ++j) {\n for(size_t i = 0; i < rows; ++i) {\n detail::write_value(f, data[i * cols + j]) << \"\\n\";\n }\n }\n}\n\n\/\/\/ Write sparse matrix in Matrix Market format.\ntemplate \nvoid mm_write(const std::string &fname, const Matrix &A) {\n typedef typename backend::value_type::type Val;\n typedef typename backend::row_iterator::type row_iterator;\n\n const size_t rows = backend::rows(A);\n const size_t cols = backend::cols(A);\n const size_t nnz = backend::nonzeros(A);\n\n std::ofstream f(fname.c_str());\n precondition(f, \"Failed to open file \\\"\" + fname + \"\\\" for writing\");\n\n \/\/ Banner\n f << \"%%MatrixMarket matrix coordinate \";\n if (boost::is_complex::value) {\n f << \"complex \";\n } else if(boost::is_integral::value) {\n f << \"integer \";\n } else {\n f << \"real \";\n }\n f << \"general\\n\";\n\n \/\/ Sizes\n f << rows << \" \" << cols << \" \" << nnz << \"\\n\";\n\n \/\/ Data\n for(size_t i = 0; i < rows; ++i) {\n for(row_iterator a = backend::row_begin(A, i); a; ++a) {\n f << i + 1 << \" \" << a.col() + 1 << \" \";\n detail::write_value(f, a.value()) << \"\\n\";\n }\n }\n}\n\n} \/\/ namespace io\n} \/\/ namespace amgcl\n\n\n#endif\n<|endoftext|>"} {"text":"\/\/ This file may be redistributed and modified under the terms of the\n\/\/ GNU Lesser General Public License (See COPYING for details).\n\/\/ Copyright (C) 2000 Stefanus Du Toit\n\n#include \"..\/Stream\/Codec.h\"\n\n#include \"Utility.h\"\n\nusing namespace std;\nusing namespace Atlas::Stream;\n\n\/** Packed ASCII codec\n\n[type][name]=[data]\n \n{} for message\n() for lists\n[] for maps\n$ for string\n@ for int\n# for float\n\n*\/\n\nclass PackedAscii : public Codec\n{\npublic:\n \n PackedAscii(iostream&, Filter*, Bridge*);\n\n virtual void Initialise(iostream&, Filter*, Bridge*);\n\n virtual void MessageBegin();\n virtual void MessageMapBegin();\n virtual void MessageEnd();\n \n virtual void MapItem(const std::string& name, const Map&);\n virtual void MapItem(const std::string& name, const List&);\n virtual void MapItem(const std::string& name, int);\n virtual void MapItem(const std::string& name, float);\n virtual void MapItem(const std::string& name, const std::string&);\n virtual void MapItem(const std::string& name, const Atlas::Object&);\n virtual void MapEnd();\n \n virtual void ListItem(const Map&);\n virtual void ListItem(const List&);\n virtual void ListItem(int);\n virtual void ListItem(float);\n virtual void ListItem(const std::string&);\n virtual void ListItem(const Atlas::Object&);\n virtual void ListEnd();\n\nprotected:\n \n iostream& socket;\n Filter* filter;\n Bridge* bridge;\n};\n\nnamespace {\n Codec::Factory factor(\"PackedAscii\", Codec::Metrics(1, 2));\n}\n\nPackedAscii::PackedAscii(iostream& socket, Filter* f, Bridge* b) :\n socket(socket), filter(f), bridge(b)\n{\n}\n\nvoid PackedAscii::MessageBegin()\n{\n socket << \"{\";\n}\n\nvoid PackedAscii::MessageMapBegin()\n{\n socket << \"[=\";\n}\n\nvoid PackedAscii::MessageEnd()\n{\n socket << \"}\";\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const Map&)\n{\n socket << \"[\" << name << \"=\";\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const List&)\n{\n socket << \"(\" << name << \"=\";\n}\n\nvoid PackedAscii::MapItem(const std::string& name, int data)\n{\n socket << \"@\" << name << \"=\" << data;\n}\n\nvoid PackedAscii::MapItem(const std::string& name, float data)\n{\n socket << \"#\" << name << \"=\" << data;\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const std::string& data)\n{\n socket << \"$\" << name << \"=\" << data;\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const Atlas::Object& data)\n{\n \/\/ FIXME recursive...\n}\n\nvoid PackedAscii::MapEnd()\n{\n socket << \"]\";\n}\n\nvoid PackedAscii::ListItem(const Map&)\n{\n socket << \"[=\";\n}\n\nvoid PackedAscii::ListItem(const List&)\n{\n socket << \"(=\";\n}\n\nvoid PackedAscii::ListItem(int data)\n{\n socket << \"@=\" << data;\n}\n\nvoid PackedAscii::ListItem(float data)\n{\n socket << \"#=\" << data;\n}\n\nvoid PackedAscii::ListItem(const std::string& data)\n{\n socket << \"$=\" << data;\n}\n\nvoid PackedAscii::ListItem(const Atlas::Object& data)\n{\n \/\/ FIXME recursive...\n}\n\nvoid PackedAscii::ListEnd()\n{\n socket << \")\";\n}\nIt actually *uses* hexEncode() now :)\/\/ This file may be redistributed and modified under the terms of the\n\/\/ GNU Lesser General Public License (See COPYING for details).\n\/\/ Copyright (C) 2000 Stefanus Du Toit\n\n#include \"..\/Stream\/Codec.h\"\n\n#include \"Utility.h\"\n\nusing namespace std;\nusing namespace Atlas::Stream;\n\n\/** Packed ASCII codec\n\n[type][name]=[data]\n \n{} for message\n() for lists\n[] for maps\n$ for string\n@ for int\n# for float\n\n*\/\n\nclass PackedAscii : public Codec\n{\npublic:\n \n PackedAscii(iostream&, Filter*, Bridge*);\n\n virtual void Initialise(iostream&, Filter*, Bridge*);\n\n virtual void MessageBegin();\n virtual void MessageMapBegin();\n virtual void MessageEnd();\n \n virtual void MapItem(const std::string& name, const Map&);\n virtual void MapItem(const std::string& name, const List&);\n virtual void MapItem(const std::string& name, int);\n virtual void MapItem(const std::string& name, float);\n virtual void MapItem(const std::string& name, const std::string&);\n virtual void MapItem(const std::string& name, const Atlas::Object&);\n virtual void MapEnd();\n \n virtual void ListItem(const Map&);\n virtual void ListItem(const List&);\n virtual void ListItem(int);\n virtual void ListItem(float);\n virtual void ListItem(const std::string&);\n virtual void ListItem(const Atlas::Object&);\n virtual void ListEnd();\n\nprotected:\n \n iostream& socket;\n Filter* filter;\n Bridge* bridge;\n};\n\nnamespace {\n Codec::Factory factor(\"PackedAscii\", Codec::Metrics(1, 2));\n}\n\nPackedAscii::PackedAscii(iostream& socket, Filter* f, Bridge* b) :\n socket(socket), filter(f), bridge(b)\n{\n}\n\nvoid PackedAscii::MessageBegin()\n{\n socket << \"{\";\n}\n\nvoid PackedAscii::MessageMapBegin()\n{\n socket << \"[=\";\n}\n\nvoid PackedAscii::MessageEnd()\n{\n socket << \"}\";\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const Map&)\n{\n socket << \"[\" << hexEncode(\"+\", \"\", \"+{}[]()@#$=\", name) << \"=\";\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const List&)\n{\n socket << \"(\" << hexEncode(\"+\", \"\", \"+{}[]()@#$=\", name) << \"=\";\n}\n\nvoid PackedAscii::MapItem(const std::string& name, int data)\n{\n socket << \"@\" << hexEncode(\"+\", \"\", \"+{}[]()@#$=\", name) << \"=\" << data;\n}\n\nvoid PackedAscii::MapItem(const std::string& name, float data)\n{\n socket << \"#\" << hexEncode(\"+\", \"\", \"+{}[]()@#$=\", name) << \"=\" << data;\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const std::string& data)\n{\n socket << \"$\" << hexEncode(\"+\", \"\", \"+{}[]()@#$=\", name) << \"=\" <<\n hexEncode(\"+\", \"+{}[]()@#$=\", \"\", data);\n}\n\nvoid PackedAscii::MapItem(const std::string& name, const Atlas::Object& data)\n{\n \/\/ FIXME recursive...\n}\n\nvoid PackedAscii::MapEnd()\n{\n socket << \"]\";\n}\n\nvoid PackedAscii::ListItem(const Map&)\n{\n socket << \"[=\";\n}\n\nvoid PackedAscii::ListItem(const List&)\n{\n socket << \"(=\";\n}\n\nvoid PackedAscii::ListItem(int data)\n{\n socket << \"@=\" << data;\n}\n\nvoid PackedAscii::ListItem(float data)\n{\n socket << \"#=\" << data;\n}\n\nvoid PackedAscii::ListItem(const std::string& data)\n{\n socket << \"$=\" << hexEncode(\"+\", \"\", \"+{}[]()@#$=\", data);\n}\n\nvoid PackedAscii::ListItem(const Atlas::Object& data)\n{\n \/\/ FIXME recursive...\n}\n\nvoid PackedAscii::ListEnd()\n{\n socket << \")\";\n}\n<|endoftext|>"} {"text":"#ifndef __ARRAYS_HPP__\n#define __ARRAYS_HPP__\n\n#include \n#include \n\n#ifdef __CYGWIN__\n#include \nnamespace std {\n\tinline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }\n}\n#endif\n\n\nnamespace {\nnamespace __typedecl {\n\n\nstruct split_string {\n\tstd::string begin;\n\tstd::string end;\n\texplicit operator std::string() const {\n\t\treturn begin + end;\n\t}\n};\n\ninline split_string operator+(const std::string& s, const split_string& ss) {\n\treturn { s + ss.begin, ss.end };\n}\n\ninline split_string operator+(const split_string& ss, const std::string& s) {\n\treturn { ss.begin, ss.end + s };\n}\n\n\nenum type_type { BASICTYPE, COMPOSITION };\nstruct basic_type { static constexpr type_type type = BASICTYPE; };\nstruct composition { static constexpr type_type type = COMPOSITION; };\n\n\ntemplate \nstruct impl;\n\n\ntemplate ::type>\nstruct prefix_cv_qual_if_basictype;\n\ntemplate \nstruct prefix_cv_qual_if_basictype {\n\tinline static split_string value(const std::string& cv_qual, const split_string& suffix) {\n\t\treturn impl::value_with_cv_qual(cv_qual, suffix);\n\t}\n};\n\ntemplate \nstruct prefix_cv_qual_if_basictype {\n\tinline static split_string value(const std::string& cv_qual, const split_string& suffix) {\n\t\treturn impl::value(cv_qual + suffix);\n\t}\n};\n\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn prefix_cv_qual_if_basictype::value(\"const\", suffix);\n\t}\n};\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn prefix_cv_qual_if_basictype::value(\"volatile\", suffix);\n\t}\n};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn prefix_cv_qual_if_basictype::value(\"const volatile\", suffix);\n\t}\n};\n\n\ntemplate ::value || std::is_function::value>\nstruct parenthesize_if_array_or_function;\n\ntemplate \nstruct parenthesize_if_array_or_function {\n\tinline static split_string value(const split_string& arg) {\n\t\treturn impl::value(arg);\n\t}\n};\n\ntemplate \nstruct parenthesize_if_array_or_function {\n\tinline static split_string value(const split_string& arg) {\n\t\treturn impl::value(\"(\" + arg + \")\");\n\t}\n};\n\n\ntemplate \nstruct impl : composition {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn parenthesize_if_array_or_function::value(\"*\" + suffix);\n\t}\n};\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn parenthesize_if_array_or_function::value(\"&\" + suffix);\n\t}\n};\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn parenthesize_if_array_or_function::value(\"&&\" + suffix);\n\t}\n};\n\n\ntemplate \nstruct array_impl : composition {\n\tinline static split_string value(const split_string& prefix = {}) {\n\t\treturn impl::value(prefix + \"[]\");\n\t}\n};\n\ntemplate \nstruct impl : array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : array_impl {};\n\n\/\/ Required to disambiguate between , , , , and \ntemplate \nstruct impl : array_impl {};\n\n\ntemplate \nstruct sized_array_impl : composition {\n\tinline static split_string value(const split_string& prefix = {}) {\n\t\treturn impl::value(prefix + (\"[\" + std::to_string(N) + \"]\"));\n\t}\n};\n\ntemplate \nstruct impl : sized_array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : sized_array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : sized_array_impl {};\n\n\/\/ Required to disambiguate between , , , , and \ntemplate \nstruct impl : sized_array_impl {};\n\n\ntemplate \nstruct type_list_impl;\n\ntemplate \nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn VA ? \"...\" : \"\";\n\t}\n};\n\ntemplate \nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn static_cast(impl::value()) + (VA ? \", ...\" : \"\");\n\t}\n};\n\ntemplate \nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn static_cast(impl::value()) + \", \" + type_list_impl::value();\n\t}\n};\n\n\ntemplate \nstruct function_impl;\n\ntemplate \nstruct function_impl {\n\tinline static split_string value(const split_string& infix = {}) {\n\t\treturn static_cast(impl::value()) + infix + \"(\" + type_list_impl::value() + \")\";\n\t}\n};\n\ntemplate \nstruct function_impl {\n\tinline static split_string value(const split_string& prefix = {}) {\n\t\treturn impl::value(prefix + \"(\" + type_list_impl::value() + \")\");\n\t}\n};\n\ntemplate \nstruct is_pointer_or_reference : std::integral_constant<\n\tbool,\n\tstd::is_pointer::value || std::is_reference::value\n> {};\n\n\ntemplate \nstruct impl : function_impl::type>::value, R, false, A...> {};\n\ntemplate \nstruct impl : function_impl::type>::value, R, true, A...> {};\n\n\n} \/* namespace __typedecl *\/\n} \/* unnamed namespace *\/\n\n\ntemplate \ninline std::string typedecl() {\n\t__typedecl::split_string ss = __typedecl::impl::value();\n\treturn ss.begin + ss.end;\n}\n\ntemplate \ninline std::string namedecl(const std::string& name) {\n\t__typedecl::split_string ss = __typedecl::impl::value();\n\treturn ss.begin + \" \" + name + ss.end;\n}\n\n\n#define DEFINE_TYPEDECL(T) \\\n\tnamespace { \\\n\tnamespace __typedecl { \\\n\ttemplate <> \\\n\tstruct impl : basic_type { \\\n\t\tinline static split_string value(const split_string& suffix = {}) { \\\n\t\t\treturn #T + suffix; \\\n\t\t} \\\n\t\tinline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \\\n\t\t\treturn (cv_qual + \" \" #T) + suffix; \\\n\t\t} \\\n\t}; \\\n\t} \/* namespace __typedecl *\/ \\\n\t} \/* unnamed namespace *\/\n\n\nDEFINE_TYPEDECL(void);\nDEFINE_TYPEDECL(char);\nDEFINE_TYPEDECL(int);\n\n\n#endif\nSplit template specializations where a bool template argument was used#ifndef __ARRAYS_HPP__\n#define __ARRAYS_HPP__\n\n#include \n#include \n\n#ifdef __CYGWIN__\n#include \nnamespace std {\n\tinline std::string to_string(unsigned long val) { ostringstream os; os << val; return os.str(); }\n}\n#endif\n\n\nnamespace {\nnamespace __typedecl {\n\n\nstruct split_string {\n\tstd::string begin;\n\tstd::string end;\n\texplicit operator std::string() const {\n\t\treturn begin + end;\n\t}\n};\n\ninline split_string operator+(const std::string& s, const split_string& ss) {\n\treturn { s + ss.begin, ss.end };\n}\n\ninline split_string operator+(const split_string& ss, const std::string& s) {\n\treturn { ss.begin, ss.end + s };\n}\n\n\nenum type_type { BASICTYPE, COMPOSITION };\nstruct basic_type { static constexpr type_type type = BASICTYPE; };\nstruct composition { static constexpr type_type type = COMPOSITION; };\n\n\ntemplate \nstruct impl;\n\n\ntemplate ::type>\nstruct prefix_cv_qual_if_basictype;\n\ntemplate \nstruct prefix_cv_qual_if_basictype {\n\tinline static split_string value(const std::string& cv_qual, const split_string& suffix) {\n\t\treturn impl::value_with_cv_qual(cv_qual, suffix);\n\t}\n};\n\ntemplate \nstruct prefix_cv_qual_if_basictype {\n\tinline static split_string value(const std::string& cv_qual, const split_string& suffix) {\n\t\treturn impl::value(cv_qual + suffix);\n\t}\n};\n\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn prefix_cv_qual_if_basictype::value(\"const\", suffix);\n\t}\n};\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn prefix_cv_qual_if_basictype::value(\"volatile\", suffix);\n\t}\n};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn prefix_cv_qual_if_basictype::value(\"const volatile\", suffix);\n\t}\n};\n\n\ntemplate ::value || std::is_function::value>\nstruct parenthesize_if_array_or_function;\n\ntemplate \nstruct parenthesize_if_array_or_function {\n\tinline static split_string value(const split_string& arg) {\n\t\treturn impl::value(arg);\n\t}\n};\n\ntemplate \nstruct parenthesize_if_array_or_function {\n\tinline static split_string value(const split_string& arg) {\n\t\treturn impl::value(\"(\" + arg + \")\");\n\t}\n};\n\n\ntemplate \nstruct impl : composition {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn parenthesize_if_array_or_function::value(\"*\" + suffix);\n\t}\n};\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn parenthesize_if_array_or_function::value(\"&\" + suffix);\n\t}\n};\n\ntemplate \nstruct impl {\n\tinline static split_string value(const split_string& suffix = {}) {\n\t\treturn parenthesize_if_array_or_function::value(\"&&\" + suffix);\n\t}\n};\n\n\ntemplate \nstruct array_impl : composition {\n\tinline static split_string value(const split_string& prefix = {}) {\n\t\treturn impl::value(prefix + \"[]\");\n\t}\n};\n\ntemplate \nstruct impl : array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : array_impl {};\n\n\/\/ Required to disambiguate between , , , , and \ntemplate \nstruct impl : array_impl {};\n\n\ntemplate \nstruct sized_array_impl : composition {\n\tinline static split_string value(const split_string& prefix = {}) {\n\t\treturn impl::value(prefix + (\"[\" + std::to_string(N) + \"]\"));\n\t}\n};\n\ntemplate \nstruct impl : sized_array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : sized_array_impl {};\n\n\/\/ Required to disambiguate between and \ntemplate \nstruct impl : sized_array_impl {};\n\n\/\/ Required to disambiguate between , , , , and \ntemplate \nstruct impl : sized_array_impl {};\n\n\ntemplate \nstruct type_list_impl;\n\ntemplate <>\nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn \"...\";\n\t}\n};\n\ntemplate <>\nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn \"\";\n\t}\n};\n\ntemplate \nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn static_cast(impl::value()) + \", ...\";\n\t}\n};\n\ntemplate \nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn static_cast(impl::value());\n\t}\n};\n\ntemplate \nstruct type_list_impl {\n\tinline static std::string value() {\n\t\treturn static_cast(impl::value()) + \", \" + type_list_impl::value();\n\t}\n};\n\n\ntemplate \nstruct function_impl;\n\ntemplate \nstruct function_impl {\n\tinline static split_string value(const split_string& infix = {}) {\n\t\treturn static_cast(impl::value()) + infix + \"(\" + type_list_impl::value() + \")\";\n\t}\n};\n\ntemplate \nstruct function_impl {\n\tinline static split_string value(const split_string& prefix = {}) {\n\t\treturn impl::value(prefix + \"(\" + type_list_impl::value() + \")\");\n\t}\n};\n\ntemplate \nstruct is_pointer_or_reference : std::integral_constant<\n\tbool,\n\tstd::is_pointer::value || std::is_reference::value\n> {};\n\n\ntemplate \nstruct impl : function_impl::type>::value, R, false, A...> {};\n\ntemplate \nstruct impl : function_impl::type>::value, R, true, A...> {};\n\n\n} \/* namespace __typedecl *\/\n} \/* unnamed namespace *\/\n\n\ntemplate \ninline std::string typedecl() {\n\t__typedecl::split_string ss = __typedecl::impl::value();\n\treturn ss.begin + ss.end;\n}\n\ntemplate \ninline std::string namedecl(const std::string& name) {\n\t__typedecl::split_string ss = __typedecl::impl::value();\n\treturn ss.begin + \" \" + name + ss.end;\n}\n\n\n#define DEFINE_TYPEDECL(T) \\\n\tnamespace { \\\n\tnamespace __typedecl { \\\n\ttemplate <> \\\n\tstruct impl : basic_type { \\\n\t\tinline static split_string value(const split_string& suffix = {}) { \\\n\t\t\treturn #T + suffix; \\\n\t\t} \\\n\t\tinline static split_string value_with_cv_qual(const std::string& cv_qual, const split_string& suffix) { \\\n\t\t\treturn (cv_qual + \" \" #T) + suffix; \\\n\t\t} \\\n\t}; \\\n\t} \/* namespace __typedecl *\/ \\\n\t} \/* unnamed namespace *\/\n\n\nDEFINE_TYPEDECL(void);\nDEFINE_TYPEDECL(char);\nDEFINE_TYPEDECL(int);\n\n\n#endif\n<|endoftext|>"} {"text":"\/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n Module: FGRocket.cpp\n Author: Jon S. Berndt\n Date started: 09\/12\/2000\n Purpose: This module models a rocket engine\n\n ------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) --------------\n\n This program is free software; you can redistribute it and\/or modify it under\n the terms of the GNU Lesser General Public License as published by the Free Software\n Foundation; either version 2 of the License, or (at your option) any later\n version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n details.\n\n You should have received a copy of the GNU Lesser General Public License along with\n this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n Place - Suite 330, Boston, MA 02111-1307, USA.\n\n Further information about the GNU Lesser General Public License can also be found on\n the world wide web at http:\/\/www.gnu.org.\n\nFUNCTIONAL DESCRIPTION\n--------------------------------------------------------------------------------\n\nThis class descends from the FGEngine class and models a rocket engine based on\nparameters given in the engine config file for this class\n\nHISTORY\n--------------------------------------------------------------------------------\n09\/12\/2000 JSB Created\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nINCLUDES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*\/\n\n#include \n#include \n#include \"FGRocket.h\"\n#include \"FGThruster.h\"\n\nusing namespace std;\n\nnamespace JSBSim {\n\nstatic const char *IdSrc = \"$Id: FGRocket.cpp,v 1.29 2013\/01\/12 21:11:59 jberndt Exp $\";\nstatic const char *IdHdr = ID_ROCKET;\n\n\/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nCLASS IMPLEMENTATION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*\/\n\nFGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number, struct Inputs& input)\n : FGEngine(exec, el, engine_number, input), isp_function(0L)\n{\n Type = etRocket;\n Element* thrust_table_element = 0;\n ThrustTable = 0L;\n BurnTime = 0.0;\n previousFuelNeedPerTank = 0.0;\n previousOxiNeedPerTank = 0.0;\n PropellantFlowRate = 0.0;\n TotalPropellantExpended = 0.0;\n FuelFlowRate = FuelExpended = 0.0;\n OxidizerFlowRate = OxidizerExpended = 0.0;\n SLOxiFlowMax = SLFuelFlowMax = PropFlowMax = 0.0;\n MxR = 0.0;\n BuildupTime = 0.0;\n It = ItVac = 0.0;\n ThrustVariation = 0.0;\n TotalIspVariation = 0.0;\n VacThrust = 0.0;\n Flameout = false;\n\n \/\/ Defaults\n MinThrottle = 0.0;\n MaxThrottle = 1.0;\n\n string base_property_name = CreateIndexedPropertyName(\"propulsion\/engine\", EngineNumber);\n\n std::stringstream strEngineNumber;\n strEngineNumber << EngineNumber;\n\n Element* isp_el = el->FindElement(\"isp\");\n Element* isp_func_el=0;\n\n bindmodel(); \/\/ Bind model properties first, since they might be needed in functions.\n\n \/\/ Specific impulse may be specified as a constant value or as a function - perhaps as a function of mixture ratio.\n if (isp_el) {\n isp_func_el = isp_el->FindElement(\"function\");\n if (isp_func_el) {\n isp_function = new FGFunction(exec->GetPropertyManager(),isp_func_el, strEngineNumber.str());\n } else {\n Isp = el->FindElementValueAsNumber(\"isp\");\n }\n } else {\n throw(\"Specific Impulse must be specified for a rocket engine\");\n }\n \n if (el->FindElement(\"builduptime\"))\n BuildupTime = el->FindElementValueAsNumber(\"builduptime\");\n if (el->FindElement(\"maxthrottle\"))\n MaxThrottle = el->FindElementValueAsNumber(\"maxthrottle\");\n if (el->FindElement(\"minthrottle\"))\n MinThrottle = el->FindElementValueAsNumber(\"minthrottle\");\n\n if (el->FindElement(\"slfuelflowmax\")) {\n SLFuelFlowMax = el->FindElementValueAsNumberConvertTo(\"slfuelflowmax\", \"LBS\/SEC\");\n if (el->FindElement(\"sloxiflowmax\")) {\n SLOxiFlowMax = el->FindElementValueAsNumberConvertTo(\"sloxiflowmax\", \"LBS\/SEC\");\n }\n PropFlowMax = SLOxiFlowMax + SLFuelFlowMax;\n MxR = SLOxiFlowMax\/SLFuelFlowMax;\n } else if (el->FindElement(\"propflowmax\")) {\n PropFlowMax = el->FindElementValueAsNumberConvertTo(\"propflowmax\", \"LBS\/SEC\");\n \/\/ Mixture ratio may be specified here, but it can also be specified as a function or via property\n if (el->FindElement(\"mixtureratio\")) {\n MxR = el->FindElementValueAsNumber(\"mixtureratio\");\n }\n }\n\n if (isp_function) Isp = isp_function->GetValue(); \/\/ cause Isp function to be executed if present.\n \/\/ If there is a thrust table element, this is a solid propellant engine.\n thrust_table_element = el->FindElement(\"thrust_table\");\n if (thrust_table_element) {\n ThrustTable = new FGTable(PropertyManager, thrust_table_element);\n Element* variation_element = el->FindElement(\"variation\");\n if (variation_element) {\n if (variation_element->FindElement(\"thrust\")) {\n ThrustVariation = variation_element->FindElementValueAsNumber(\"thrust\");\n }\n if (variation_element->FindElement(\"total_isp\")) {\n TotalIspVariation = variation_element->FindElementValueAsNumber(\"total_isp\");\n }\n }\n }\n\n\n Debug(0);\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nFGRocket::~FGRocket(void)\n{\n delete ThrustTable;\n Debug(1);\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvoid FGRocket::Calculate(void)\n{\n if (FDMExec->IntegrationSuspended()) return;\n\n RunPreFunctions();\n\n PropellantFlowRate = (FuelExpended + OxidizerExpended)\/in.TotalDeltaT;\n TotalPropellantExpended += FuelExpended + OxidizerExpended;\n \/\/ If Isp has been specified as a function, override the value of Isp to that, otherwise\n \/\/ assume a constant value is given.\n if (isp_function) Isp = isp_function->GetValue();\n\n \/\/ If there is a thrust table, it is a function of propellant burned. The\n \/\/ engine is started when the throttle is advanced to 1.0. After that, it\n \/\/ burns without regard to throttle setting.\n\n if (ThrustTable != 0L) { \/\/ Thrust table given -> Solid fuel used\n\n if ((in.ThrottlePos[EngineNumber] == 1 || BurnTime > 0.0 ) && !Starved) {\n\n VacThrust = ThrustTable->GetValue(TotalPropellantExpended)\n * (ThrustVariation + 1)\n * (TotalIspVariation + 1);\n if (BurnTime <= BuildupTime && BuildupTime > 0.0) {\n VacThrust *= sin((BurnTime\/BuildupTime)*M_PI\/2.0);\n \/\/ VacThrust *= (1-cos((BurnTime\/BuildupTime)*M_PI))\/2.0; \/\/ 1 - cos approach\n }\n BurnTime += in.TotalDeltaT; \/\/ Increment burn time\n } else {\n VacThrust = 0.0;\n }\n\n } else { \/\/ liquid fueled rocket assumed\n\n if (in.ThrottlePos[EngineNumber] < MinThrottle || Starved) { \/\/ Combustion not supported\n\n PctPower = 0.0; \/\/ desired thrust\n Flameout = true;\n VacThrust = 0.0;\n\n } else { \/\/ Calculate thrust\n\n \/\/ PctPower = Throttle \/ MaxThrottle; \/\/ Min and MaxThrottle range from 0.0 to 1.0, normally.\n \n PctPower = in.ThrottlePos[EngineNumber];\n Flameout = false;\n VacThrust = Isp * PropellantFlowRate;\n\n }\n\n } \/\/ End thrust calculations\n\n LoadThrusterInputs();\n It += Thruster->Calculate(VacThrust) * in.TotalDeltaT;\n ItVac += VacThrust * in.TotalDeltaT;\n\n RunPostFunctions();\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\/\/ \n\/\/ The FuelFlowRate can be affected by the TotalIspVariation value (settable\n\/\/ in a config file or via properties). The TotalIspVariation parameter affects\n\/\/ thrust, but the thrust determines fuel flow rate, so it must be adjusted\n\/\/ for Total Isp Variation.\n\ndouble FGRocket::CalcFuelNeed(void)\n{\n if (ThrustTable != 0L) { \/\/ Thrust table given - infers solid fuel\n FuelFlowRate = VacThrust\/Isp; \/\/ This calculates wdot (weight flow rate in lbs\/sec)\n FuelFlowRate \/= (1 + TotalIspVariation);\n } else {\n SLFuelFlowMax = PropFlowMax \/ (1 + MxR);\n FuelFlowRate = SLFuelFlowMax * PctPower;\n }\n\n FuelExpended = FuelFlowRate * in.TotalDeltaT; \/\/ For this time step ...\n return FuelExpended;\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndouble FGRocket::CalcOxidizerNeed(void)\n{\n SLOxiFlowMax = PropFlowMax * MxR \/ (1 + MxR);\n OxidizerFlowRate = SLOxiFlowMax * PctPower;\n OxidizerExpended = OxidizerFlowRate * in.TotalDeltaT;\n return OxidizerExpended;\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nstring FGRocket::GetEngineLabels(const string& delimiter)\n{\n std::ostringstream buf;\n\n buf << Name << \" Total Impulse (engine \" << EngineNumber << \" in psf)\" << delimiter\n << Name << \" Total Vacuum Impulse (engine \" << EngineNumber << \" in psf)\" << delimiter\n << Thruster->GetThrusterLabels(EngineNumber, delimiter);\n\n return buf.str();\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nstring FGRocket::GetEngineValues(const string& delimiter)\n{\n std::ostringstream buf;\n\n buf << It << delimiter \n << ItVac << delimiter \n << Thruster->GetThrusterValues(EngineNumber, delimiter);\n\n return buf.str();\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\/\/ This function should tie properties to rocket engine specific properties\n\/\/ that are not bound in the base class (FGEngine) code.\n\/\/\nvoid FGRocket::bindmodel()\n{\n string property_name, base_property_name;\n base_property_name = CreateIndexedPropertyName(\"propulsion\/engine\", EngineNumber);\n\n property_name = base_property_name + \"\/total-impulse\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalImpulse);\n property_name = base_property_name + \"\/vacuum-thrust_lbs\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetVacThrust);\n\n if (ThrustTable) { \/\/ Solid rocket motor\n property_name = base_property_name + \"\/thrust-variation_pct\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetThrustVariation,\n &FGRocket::SetThrustVariation);\n property_name = base_property_name + \"\/total-isp-variation_pct\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalIspVariation,\n &FGRocket::SetTotalIspVariation);\n } else { \/\/ Liquid rocket motor\n property_name = base_property_name + \"\/oxi-flow-rate-pps\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetOxiFlowRate);\n property_name = base_property_name + \"\/mixture-ratio\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetMixtureRatio,\n &FGRocket::SetMixtureRatio);\n property_name = base_property_name + \"\/isp\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetIsp,\n &FGRocket::SetIsp);\n }\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\/\/ The bitmasked value choices are as follows:\n\/\/ unset: In this case (the default) JSBSim would only print\n\/\/ out the normally expected messages, essentially echoing\n\/\/ the config files as they are read. If the environment\n\/\/ variable is not set, debug_lvl is set to 1 internally\n\/\/ 0: This requests JSBSim not to output any messages\n\/\/ whatsoever.\n\/\/ 1: This value explicity requests the normal JSBSim\n\/\/ startup messages\n\/\/ 2: This value asks for a message to be printed out when\n\/\/ a class is instantiated\n\/\/ 4: When this value is set, a message is displayed when a\n\/\/ FGModel object executes its Run() method\n\/\/ 8: When this value is set, various runtime state variables\n\/\/ are printed out periodically\n\/\/ 16: When set various parameters are sanity checked and\n\/\/ a message is printed out when they go out of bounds\n\nvoid FGRocket::Debug(int from)\n{\n if (debug_lvl <= 0) return;\n\n if (debug_lvl & 1) { \/\/ Standard console startup message output\n if (from == 0) { \/\/ Constructor\n cout << \" Engine Name: \" << Name << endl;\n cout << \" Vacuum Isp = \" << Isp << endl;\n cout << \" Maximum Throttle = \" << MaxThrottle << endl;\n cout << \" Minimum Throttle = \" << MinThrottle << endl;\n cout << \" Fuel Flow (max) = \" << SLFuelFlowMax << endl;\n cout << \" Oxidizer Flow (max) = \" << SLOxiFlowMax << endl;\n if (SLFuelFlowMax > 0)\n cout << \" Mixture ratio = \" << SLOxiFlowMax\/SLFuelFlowMax << endl;\n }\n }\n if (debug_lvl & 2 ) { \/\/ Instantiation\/Destruction notification\n if (from == 0) cout << \"Instantiated: FGRocket\" << endl;\n if (from == 1) cout << \"Destroyed: FGRocket\" << endl;\n }\n if (debug_lvl & 4 ) { \/\/ Run() method entry print for FGModel-derived objects\n }\n if (debug_lvl & 8 ) { \/\/ Runtime state variables\n }\n if (debug_lvl & 16) { \/\/ Sanity checking\n }\n if (debug_lvl & 64) {\n if (from == 0) { \/\/ Constructor\n cout << IdSrc << endl;\n cout << IdHdr << endl;\n }\n }\n}\n}\nFixed units text in output\/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\n Module: FGRocket.cpp\n Author: Jon S. Berndt\n Date started: 09\/12\/2000\n Purpose: This module models a rocket engine\n\n ------------- Copyright (C) 2000 Jon S. Berndt (jon@jsbsim.org) --------------\n\n This program is free software; you can redistribute it and\/or modify it under\n the terms of the GNU Lesser General Public License as published by the Free Software\n Foundation; either version 2 of the License, or (at your option) any later\n version.\n\n This program is distributed in the hope that it will be useful, but WITHOUT\n ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more\n details.\n\n You should have received a copy of the GNU Lesser General Public License along with\n this program; if not, write to the Free Software Foundation, Inc., 59 Temple\n Place - Suite 330, Boston, MA 02111-1307, USA.\n\n Further information about the GNU Lesser General Public License can also be found on\n the world wide web at http:\/\/www.gnu.org.\n\nFUNCTIONAL DESCRIPTION\n--------------------------------------------------------------------------------\n\nThis class descends from the FGEngine class and models a rocket engine based on\nparameters given in the engine config file for this class\n\nHISTORY\n--------------------------------------------------------------------------------\n09\/12\/2000 JSB Created\n\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nINCLUDES\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*\/\n\n#include \n#include \n#include \"FGRocket.h\"\n#include \"FGThruster.h\"\n\nusing namespace std;\n\nnamespace JSBSim {\n\nstatic const char *IdSrc = \"$Id: FGRocket.cpp,v 1.30 2013\/06\/10 02:00:11 jberndt Exp $\";\nstatic const char *IdHdr = ID_ROCKET;\n\n\/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\nCLASS IMPLEMENTATION\n%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*\/\n\nFGRocket::FGRocket(FGFDMExec* exec, Element *el, int engine_number, struct Inputs& input)\n : FGEngine(exec, el, engine_number, input), isp_function(0L)\n{\n Type = etRocket;\n Element* thrust_table_element = 0;\n ThrustTable = 0L;\n BurnTime = 0.0;\n previousFuelNeedPerTank = 0.0;\n previousOxiNeedPerTank = 0.0;\n PropellantFlowRate = 0.0;\n TotalPropellantExpended = 0.0;\n FuelFlowRate = FuelExpended = 0.0;\n OxidizerFlowRate = OxidizerExpended = 0.0;\n SLOxiFlowMax = SLFuelFlowMax = PropFlowMax = 0.0;\n MxR = 0.0;\n BuildupTime = 0.0;\n It = ItVac = 0.0;\n ThrustVariation = 0.0;\n TotalIspVariation = 0.0;\n VacThrust = 0.0;\n Flameout = false;\n\n \/\/ Defaults\n MinThrottle = 0.0;\n MaxThrottle = 1.0;\n\n string base_property_name = CreateIndexedPropertyName(\"propulsion\/engine\", EngineNumber);\n\n std::stringstream strEngineNumber;\n strEngineNumber << EngineNumber;\n\n Element* isp_el = el->FindElement(\"isp\");\n Element* isp_func_el=0;\n\n bindmodel(); \/\/ Bind model properties first, since they might be needed in functions.\n\n \/\/ Specific impulse may be specified as a constant value or as a function - perhaps as a function of mixture ratio.\n if (isp_el) {\n isp_func_el = isp_el->FindElement(\"function\");\n if (isp_func_el) {\n isp_function = new FGFunction(exec->GetPropertyManager(),isp_func_el, strEngineNumber.str());\n } else {\n Isp = el->FindElementValueAsNumber(\"isp\");\n }\n } else {\n throw(\"Specific Impulse must be specified for a rocket engine\");\n }\n \n if (el->FindElement(\"builduptime\"))\n BuildupTime = el->FindElementValueAsNumber(\"builduptime\");\n if (el->FindElement(\"maxthrottle\"))\n MaxThrottle = el->FindElementValueAsNumber(\"maxthrottle\");\n if (el->FindElement(\"minthrottle\"))\n MinThrottle = el->FindElementValueAsNumber(\"minthrottle\");\n\n if (el->FindElement(\"slfuelflowmax\")) {\n SLFuelFlowMax = el->FindElementValueAsNumberConvertTo(\"slfuelflowmax\", \"LBS\/SEC\");\n if (el->FindElement(\"sloxiflowmax\")) {\n SLOxiFlowMax = el->FindElementValueAsNumberConvertTo(\"sloxiflowmax\", \"LBS\/SEC\");\n }\n PropFlowMax = SLOxiFlowMax + SLFuelFlowMax;\n MxR = SLOxiFlowMax\/SLFuelFlowMax;\n } else if (el->FindElement(\"propflowmax\")) {\n PropFlowMax = el->FindElementValueAsNumberConvertTo(\"propflowmax\", \"LBS\/SEC\");\n \/\/ Mixture ratio may be specified here, but it can also be specified as a function or via property\n if (el->FindElement(\"mixtureratio\")) {\n MxR = el->FindElementValueAsNumber(\"mixtureratio\");\n }\n }\n\n if (isp_function) Isp = isp_function->GetValue(); \/\/ cause Isp function to be executed if present.\n \/\/ If there is a thrust table element, this is a solid propellant engine.\n thrust_table_element = el->FindElement(\"thrust_table\");\n if (thrust_table_element) {\n ThrustTable = new FGTable(PropertyManager, thrust_table_element);\n Element* variation_element = el->FindElement(\"variation\");\n if (variation_element) {\n if (variation_element->FindElement(\"thrust\")) {\n ThrustVariation = variation_element->FindElementValueAsNumber(\"thrust\");\n }\n if (variation_element->FindElement(\"total_isp\")) {\n TotalIspVariation = variation_element->FindElementValueAsNumber(\"total_isp\");\n }\n }\n }\n\n\n Debug(0);\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nFGRocket::~FGRocket(void)\n{\n delete ThrustTable;\n Debug(1);\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nvoid FGRocket::Calculate(void)\n{\n if (FDMExec->IntegrationSuspended()) return;\n\n RunPreFunctions();\n\n PropellantFlowRate = (FuelExpended + OxidizerExpended)\/in.TotalDeltaT;\n TotalPropellantExpended += FuelExpended + OxidizerExpended;\n \/\/ If Isp has been specified as a function, override the value of Isp to that, otherwise\n \/\/ assume a constant value is given.\n if (isp_function) Isp = isp_function->GetValue();\n\n \/\/ If there is a thrust table, it is a function of propellant burned. The\n \/\/ engine is started when the throttle is advanced to 1.0. After that, it\n \/\/ burns without regard to throttle setting.\n\n if (ThrustTable != 0L) { \/\/ Thrust table given -> Solid fuel used\n\n if ((in.ThrottlePos[EngineNumber] == 1 || BurnTime > 0.0 ) && !Starved) {\n\n VacThrust = ThrustTable->GetValue(TotalPropellantExpended)\n * (ThrustVariation + 1)\n * (TotalIspVariation + 1);\n if (BurnTime <= BuildupTime && BuildupTime > 0.0) {\n VacThrust *= sin((BurnTime\/BuildupTime)*M_PI\/2.0);\n \/\/ VacThrust *= (1-cos((BurnTime\/BuildupTime)*M_PI))\/2.0; \/\/ 1 - cos approach\n }\n BurnTime += in.TotalDeltaT; \/\/ Increment burn time\n } else {\n VacThrust = 0.0;\n }\n\n } else { \/\/ liquid fueled rocket assumed\n\n if (in.ThrottlePos[EngineNumber] < MinThrottle || Starved) { \/\/ Combustion not supported\n\n PctPower = 0.0; \/\/ desired thrust\n Flameout = true;\n VacThrust = 0.0;\n\n } else { \/\/ Calculate thrust\n\n \/\/ PctPower = Throttle \/ MaxThrottle; \/\/ Min and MaxThrottle range from 0.0 to 1.0, normally.\n \n PctPower = in.ThrottlePos[EngineNumber];\n Flameout = false;\n VacThrust = Isp * PropellantFlowRate;\n\n }\n\n } \/\/ End thrust calculations\n\n LoadThrusterInputs();\n It += Thruster->Calculate(VacThrust) * in.TotalDeltaT;\n ItVac += VacThrust * in.TotalDeltaT;\n\n RunPostFunctions();\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\/\/ \n\/\/ The FuelFlowRate can be affected by the TotalIspVariation value (settable\n\/\/ in a config file or via properties). The TotalIspVariation parameter affects\n\/\/ thrust, but the thrust determines fuel flow rate, so it must be adjusted\n\/\/ for Total Isp Variation.\n\ndouble FGRocket::CalcFuelNeed(void)\n{\n if (ThrustTable != 0L) { \/\/ Thrust table given - infers solid fuel\n FuelFlowRate = VacThrust\/Isp; \/\/ This calculates wdot (weight flow rate in lbs\/sec)\n FuelFlowRate \/= (1 + TotalIspVariation);\n } else {\n SLFuelFlowMax = PropFlowMax \/ (1 + MxR);\n FuelFlowRate = SLFuelFlowMax * PctPower;\n }\n\n FuelExpended = FuelFlowRate * in.TotalDeltaT; \/\/ For this time step ...\n return FuelExpended;\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\ndouble FGRocket::CalcOxidizerNeed(void)\n{\n SLOxiFlowMax = PropFlowMax * MxR \/ (1 + MxR);\n OxidizerFlowRate = SLOxiFlowMax * PctPower;\n OxidizerExpended = OxidizerFlowRate * in.TotalDeltaT;\n return OxidizerExpended;\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nstring FGRocket::GetEngineLabels(const string& delimiter)\n{\n std::ostringstream buf;\n\n buf << Name << \" Total Impulse (engine \" << EngineNumber << \" in lbf)\" << delimiter\n << Name << \" Total Vacuum Impulse (engine \" << EngineNumber << \" in lbf)\" << delimiter\n << Thruster->GetThrusterLabels(EngineNumber, delimiter);\n\n return buf.str();\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\nstring FGRocket::GetEngineValues(const string& delimiter)\n{\n std::ostringstream buf;\n\n buf << It << delimiter \n << ItVac << delimiter \n << Thruster->GetThrusterValues(EngineNumber, delimiter);\n\n return buf.str();\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\/\/ This function should tie properties to rocket engine specific properties\n\/\/ that are not bound in the base class (FGEngine) code.\n\/\/\nvoid FGRocket::bindmodel()\n{\n string property_name, base_property_name;\n base_property_name = CreateIndexedPropertyName(\"propulsion\/engine\", EngineNumber);\n\n property_name = base_property_name + \"\/total-impulse\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalImpulse);\n property_name = base_property_name + \"\/vacuum-thrust_lbs\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetVacThrust);\n\n if (ThrustTable) { \/\/ Solid rocket motor\n property_name = base_property_name + \"\/thrust-variation_pct\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetThrustVariation,\n &FGRocket::SetThrustVariation);\n property_name = base_property_name + \"\/total-isp-variation_pct\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetTotalIspVariation,\n &FGRocket::SetTotalIspVariation);\n } else { \/\/ Liquid rocket motor\n property_name = base_property_name + \"\/oxi-flow-rate-pps\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetOxiFlowRate);\n property_name = base_property_name + \"\/mixture-ratio\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetMixtureRatio,\n &FGRocket::SetMixtureRatio);\n property_name = base_property_name + \"\/isp\";\n PropertyManager->Tie( property_name.c_str(), this, &FGRocket::GetIsp,\n &FGRocket::SetIsp);\n }\n}\n\n\/\/%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n\/\/ The bitmasked value choices are as follows:\n\/\/ unset: In this case (the default) JSBSim would only print\n\/\/ out the normally expected messages, essentially echoing\n\/\/ the config files as they are read. If the environment\n\/\/ variable is not set, debug_lvl is set to 1 internally\n\/\/ 0: This requests JSBSim not to output any messages\n\/\/ whatsoever.\n\/\/ 1: This value explicity requests the normal JSBSim\n\/\/ startup messages\n\/\/ 2: This value asks for a message to be printed out when\n\/\/ a class is instantiated\n\/\/ 4: When this value is set, a message is displayed when a\n\/\/ FGModel object executes its Run() method\n\/\/ 8: When this value is set, various runtime state variables\n\/\/ are printed out periodically\n\/\/ 16: When set various parameters are sanity checked and\n\/\/ a message is printed out when they go out of bounds\n\nvoid FGRocket::Debug(int from)\n{\n if (debug_lvl <= 0) return;\n\n if (debug_lvl & 1) { \/\/ Standard console startup message output\n if (from == 0) { \/\/ Constructor\n cout << \" Engine Name: \" << Name << endl;\n cout << \" Vacuum Isp = \" << Isp << endl;\n cout << \" Maximum Throttle = \" << MaxThrottle << endl;\n cout << \" Minimum Throttle = \" << MinThrottle << endl;\n cout << \" Fuel Flow (max) = \" << SLFuelFlowMax << endl;\n cout << \" Oxidizer Flow (max) = \" << SLOxiFlowMax << endl;\n if (SLFuelFlowMax > 0)\n cout << \" Mixture ratio = \" << SLOxiFlowMax\/SLFuelFlowMax << endl;\n }\n }\n if (debug_lvl & 2 ) { \/\/ Instantiation\/Destruction notification\n if (from == 0) cout << \"Instantiated: FGRocket\" << endl;\n if (from == 1) cout << \"Destroyed: FGRocket\" << endl;\n }\n if (debug_lvl & 4 ) { \/\/ Run() method entry print for FGModel-derived objects\n }\n if (debug_lvl & 8 ) { \/\/ Runtime state variables\n }\n if (debug_lvl & 16) { \/\/ Sanity checking\n }\n if (debug_lvl & 64) {\n if (from == 0) { \/\/ Constructor\n cout << IdSrc << endl;\n cout << IdHdr << endl;\n }\n }\n}\n}\n<|endoftext|>"} {"text":"#include \"scanner\/api\/kernel.h\"\n#include \"scanner\/api\/op.h\"\n#include \"scanner\/util\/memory.h\"\n\nnamespace scanner {\n\nclass DiscardKernel : public BatchedKernel {\n public:\n DiscardKernel(const KernelConfig& config)\n : BatchedKernel(config),\n device_(config.devices[0]),\n work_item_size_(config.work_item_size) {}\n\n void execute(const BatchedColumns& input_columns,\n BatchedColumns& output_columns) override {\n i32 input_count = (i32)num_rows(input_columns[0]);\n u8* output_block = new_block_buffer(device_, 1, input_count);\n for (i32 i = 0; i < input_count; ++i) {\n insert_element(output_columns[0], output_block, 1);\n }\n }\n\n private:\n DeviceHandle device_;\n i32 work_item_size_;\n};\n\nREGISTER_OP(Discard).input(\"ignore\").output(\"dummy\");\n\nREGISTER_OP(DiscardFrame).frame_input(\"ignore\").output(\"dummy\");\n\nREGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);\n\nREGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);\n\nREGISTER_KERNEL(DiscardFrame, DiscardKernel)\n .device(DeviceType::CPU)\n .num_devices(1);\n\nREGISTER_KERNEL(DiscardFrame, DiscardKernel)\n .device(DeviceType::GPU)\n .num_devices(1);\n}\nSupport batching on discard kernel#include \"scanner\/api\/kernel.h\"\n#include \"scanner\/api\/op.h\"\n#include \"scanner\/util\/memory.h\"\n\nnamespace scanner {\n\nclass DiscardKernel : public BatchedKernel {\n public:\n DiscardKernel(const KernelConfig& config)\n : BatchedKernel(config),\n device_(config.devices[0]),\n work_item_size_(config.work_item_size) {}\n\n void execute(const BatchedColumns& input_columns,\n BatchedColumns& output_columns) override {\n i32 input_count = (i32)num_rows(input_columns[0]);\n u8* output_block = new_block_buffer(device_, 1, input_count);\n for (i32 i = 0; i < input_count; ++i) {\n insert_element(output_columns[0], output_block, 1);\n }\n }\n\n private:\n DeviceHandle device_;\n i32 work_item_size_;\n};\n\nREGISTER_OP(Discard).input(\"ignore\").output(\"dummy\");\n\nREGISTER_OP(DiscardFrame).frame_input(\"ignore\").output(\"dummy\");\n\nREGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::CPU).num_devices(1);\n\nREGISTER_KERNEL(Discard, DiscardKernel).device(DeviceType::GPU).num_devices(1);\n\nREGISTER_KERNEL(DiscardFrame, DiscardKernel)\n .device(DeviceType::CPU)\n .batch()\n .num_devices(1);\n\nREGISTER_KERNEL(DiscardFrame, DiscardKernel)\n .device(DeviceType::GPU)\n .batch()\n .num_devices(1);\n}\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 2014 Alexandr Akulich \n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*\/\n\n#ifndef CTELEGRAMCONNECTION_HPP\n#define CTELEGRAMCONNECTION_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"TLTypes.hpp\"\n#include \"crypto-rsa.hpp\"\n#include \"crypto-aes.hpp\"\n\nclass CAppInformation;\nclass CTelegramStream;\nclass CTelegramTransport;\n\nclass CTelegramConnection : public QObject\n{\n Q_OBJECT\npublic:\n enum AuthState {\n AuthStateNone,\n AuthStatePqRequested,\n AuthStateDhRequested,\n AuthStateDhGenerationResultRequested,\n AuthStateSuccess,\n AuthStateSignedIn\n };\n\n enum DeltaTimeHeuristicState {\n DeltaTimeIsOk,\n DeltaTimeCorrectionForward,\n DeltaTimeCorrectionBackward,\n };\n\n explicit CTelegramConnection(const CAppInformation *appInfo, QObject *parent = 0);\n\n void setDcInfo(const TLDcOption &newDcInfo);\n\n inline TLDcOption dcInfo() const { return m_dcInfo; }\n\n void connectToDc();\n\n bool isConnected() const;\n\n static quint64 formatTimeStamp(qint64 timeInMs);\n static inline quint64 formatClientTimeStamp(qint64 timeInMs) { return formatTimeStamp(timeInMs) & ~quint64(3); }\n\n static quint64 timeStampToMSecsSinceEpoch(quint64 ts);\n\n void initAuth();\n void getConfiguration();\n\n void requestPhoneStatus(const QString &phoneNumber);\n void requestPhoneCode(const QString &phoneNumber);\n void signIn(const QString &phoneNumber, const QString &authCode);\n void signUp(const QString &phoneNumber, const QString &authCode, const QString &firstName, const QString &lastName);\n\n void requestContacts();\n void getFile(const TLInputFileLocation &location, quint32 fileId);\n\n void addContacts(const QStringList &phoneNumbers, bool replace);\n\n void sendMessage(const TLInputPeer &peer, const QString &message);\n\n AuthState authState() { return m_authState; }\n\n void requestPqAuthorization();\n bool answerPqAuthorization(const QByteArray &payload);\n void requestDhParameters();\n bool answerDh(const QByteArray &payload);\n void requestDhGenerationResult();\n bool processServersDHAnswer(const QByteArray &payload);\n\n inline TLNumber128 clientNonce() const { return m_clientNonce; }\n inline TLNumber128 serverNonce() const { return m_serverNonce; }\n\n inline quint64 pq() const { return m_pq; }\n inline quint64 p() const { return m_p; }\n inline quint64 q() const { return m_q; }\n\n inline quint64 serverPublicFingersprint() const { return m_serverPublicFingersprint; }\n\n inline QByteArray authKey() const { return m_authKey; }\n void setAuthKey(const QByteArray &newAuthKey);\n inline quint64 authId() const { return m_authId; }\n\n inline quint64 serverSalt() const { return m_serverSalt; }\n void setServerSalt(const quint64 salt) { m_serverSalt = salt; }\n inline quint64 sessionId() const { return m_sessionId; }\n\n inline QVector dcConfiguration() const { return m_dcConfiguration; }\n\n inline qint32 deltaTime() const { return m_deltaTime; }\n void setDeltaTime(const qint32 delta) { m_deltaTime = delta; }\n\n void processRedirectedPackage(const QByteArray &data);\n\nsignals:\n void wantedActiveDcChanged(int dc);\n void newRedirectedPackage(const QByteArray &data, int dc);\n\n void selfPhoneReceived(const QString &phoneNumber);\n void authStateChanged(int dc, int state);\n void actualDcIdReceived(int dc, int newDcId);\n void dcConfigurationReceived(int dc);\n void phoneStatusReceived(const QString &phone, bool registered, bool invited);\n void phoneCodeRequired();\n void phoneCodeIsInvalid();\n void usersReceived(const QVector &users);\n void usersAdded(const QVector &users);\n void fileReceived(const TLUploadFile &file, quint32 fileId);\n\n void updatesReceived(const TLUpdates &update);\n\nprivate slots:\n void whenConnected();\n void whenReadyRead();\n\nprotected:\n void processRpcQuery(const QByteArray &data);\n\n void processSessionCreated(CTelegramStream &stream);\n void processContainer(CTelegramStream &stream);\n void processRpcResult(CTelegramStream &stream);\n void processGzipPacked(CTelegramStream &stream);\n bool processRpcError(CTelegramStream &stream, quint64 id, TLValue request);\n\n void processMessageAck(CTelegramStream &stream);\n void processIgnoredMessageNotification(CTelegramStream &stream);\n\n TLValue processHelpGetConfig(CTelegramStream &stream, quint64 id);\n TLValue processContactsGetContacts(CTelegramStream &stream, quint64 id);\n TLValue processContactsImportContacts(CTelegramStream &stream, quint64 id);\n TLValue processAuthCheckPhone(CTelegramStream &stream, quint64 id);\n TLValue processAuthSendCode(CTelegramStream &stream, quint64 id);\n TLValue processAuthSign(CTelegramStream &stream, quint64 id);\n TLValue processUploadGetFile(CTelegramStream &stream, quint64 id);\n TLValue processMessagesSendMessage(CTelegramStream &stream, quint64 id);\n\n bool processErrorSeeOther(const QString errorMessage, quint64 id);\n\n TLValue processUpdate(CTelegramStream &stream);\n\n SAesKey generateTmpAesKey() const;\n SAesKey generateClientToServerAesKey(const QByteArray &messageKey) const;\n SAesKey generateServerToClientAesKey(const QByteArray &messageKey) const;\n\n SAesKey generateAesKey(const QByteArray &messageKey, int xValue) const;\n\n void insertInitConnection(QByteArray *data) const;\n\n quint64 sendPlainPackage(const QByteArray &buffer);\n quint64 sendEncryptedPackage(const QByteArray &buffer);\n void setTransport(CTelegramTransport *newTransport);\n\n void setAuthState(AuthState newState);\n\n quint64 newMessageId();\n\n const CAppInformation *m_appInfo;\n\n QMap m_submittedPackages; \/\/ \n QMap m_requestedFilesIds; \/\/ \n\n CTelegramTransport *m_transport;\n\n AuthState m_authState;\n\n QByteArray m_authKey;\n quint64 m_authId;\n quint64 m_authKeyAuxHash;\n quint64 m_serverSalt;\n quint64 m_receivedServerSalt;\n quint64 m_sessionId;\n quint64 m_lastMessageId;\n quint32 m_sequenceNumber;\n quint32 m_contentRelatedMessages;\n\n qint32 m_deltaTime;\n DeltaTimeHeuristicState m_deltaTimeHeuristicState;\n\n TLNumber128 m_clientNonce;\n TLNumber128 m_serverNonce;\n TLNumber256 m_newNonce;\n\n quint64 m_pq;\n quint32 m_p;\n quint32 m_q;\n\n quint64 m_serverPublicFingersprint;\n SRsaKey m_rsaKey;\n SAesKey m_tmpAesKey;\n\n quint32 m_g;\n QByteArray m_dhPrime;\n QByteArray m_gA;\n QByteArray m_b;\n\n quint64 m_authRetryId;\n\n TLDcOption m_dcInfo;\n\n QVector m_dcConfiguration;\n\n QString m_authCodeHash;\n\n};\n\ninline SAesKey CTelegramConnection::generateClientToServerAesKey(const QByteArray &messageKey) const\n{\n return generateAesKey(messageKey, 0);\n}\n\ninline SAesKey CTelegramConnection::generateServerToClientAesKey(const QByteArray &messageKey) const\n{\n return generateAesKey(messageKey, 8);\n}\n\n#endif \/\/ CTELEGRAMCONNECTION_HPP\nFixed compilation.\/*\n Copyright (C) 2014 Alexandr Akulich \n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION\n WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n*\/\n\n#ifndef CTELEGRAMCONNECTION_HPP\n#define CTELEGRAMCONNECTION_HPP\n\n#include \n#include \n#include \n#include \n#include \n\n#include \"TLTypes.hpp\"\n#include \"crypto-rsa.hpp\"\n#include \"crypto-aes.hpp\"\n\nclass CAppInformation;\nclass CTelegramStream;\nclass CTelegramTransport;\n\nclass CTelegramConnection : public QObject\n{\n Q_OBJECT\npublic:\n enum AuthState {\n AuthStateNone,\n AuthStatePqRequested,\n AuthStateDhRequested,\n AuthStateDhGenerationResultRequested,\n AuthStateSuccess,\n AuthStateSignedIn\n };\n\n enum DeltaTimeHeuristicState {\n DeltaTimeIsOk,\n DeltaTimeCorrectionForward,\n DeltaTimeCorrectionBackward,\n };\n\n explicit CTelegramConnection(const CAppInformation *appInfo, QObject *parent = 0);\n\n void setDcInfo(const TLDcOption &newDcInfo);\n\n inline TLDcOption dcInfo() const { return m_dcInfo; }\n\n void connectToDc();\n\n bool isConnected() const;\n\n static quint64 formatTimeStamp(qint64 timeInMs);\n static inline quint64 formatClientTimeStamp(qint64 timeInMs) { return formatTimeStamp(timeInMs) & ~quint64(3); }\n\n static quint64 timeStampToMSecsSinceEpoch(quint64 ts);\n\n void initAuth();\n void getConfiguration();\n\n void requestPhoneStatus(const QString &phoneNumber);\n void requestPhoneCode(const QString &phoneNumber);\n void signIn(const QString &phoneNumber, const QString &authCode);\n void signUp(const QString &phoneNumber, const QString &authCode, const QString &firstName, const QString &lastName);\n\n void requestContacts();\n void getFile(const TLInputFileLocation &location, quint32 fileId);\n\n void addContacts(const QStringList &phoneNumbers, bool replace);\n\n void sendMessage(const TLInputPeer &peer, const QString &message);\n\n AuthState authState() { return m_authState; }\n\n void requestPqAuthorization();\n bool answerPqAuthorization(const QByteArray &payload);\n void requestDhParameters();\n bool answerDh(const QByteArray &payload);\n void requestDhGenerationResult();\n bool processServersDHAnswer(const QByteArray &payload);\n\n inline TLNumber128 clientNonce() const { return m_clientNonce; }\n inline TLNumber128 serverNonce() const { return m_serverNonce; }\n\n inline quint64 pq() const { return m_pq; }\n inline quint64 p() const { return m_p; }\n inline quint64 q() const { return m_q; }\n\n inline quint64 serverPublicFingersprint() const { return m_serverPublicFingersprint; }\n\n inline QByteArray authKey() const { return m_authKey; }\n void setAuthKey(const QByteArray &newAuthKey);\n inline quint64 authId() const { return m_authId; }\n\n inline quint64 serverSalt() const { return m_serverSalt; }\n void setServerSalt(const quint64 salt) { m_serverSalt = salt; }\n inline quint64 sessionId() const { return m_sessionId; }\n\n inline QVector dcConfiguration() const { return m_dcConfiguration; }\n\n inline qint32 deltaTime() const { return m_deltaTime; }\n void setDeltaTime(const qint32 delta) { m_deltaTime = delta; }\n\n void processRedirectedPackage(const QByteArray &data);\n\nsignals:\n void wantedActiveDcChanged(int dc);\n void newRedirectedPackage(const QByteArray &data, int dc);\n\n void selfPhoneReceived(const QString &phoneNumber);\n void authStateChanged(int dc, int state);\n void actualDcIdReceived(int dc, int newDcId);\n void dcConfigurationReceived(int dc);\n void phoneStatusReceived(const QString &phone, bool registered, bool invited);\n void phoneCodeRequired();\n void phoneCodeIsInvalid();\n void usersReceived(const QVector &users);\n void usersAdded(const QVector &users);\n void fileReceived(const TLUploadFile &file, quint32 fileId);\n\n void updatesReceived(const TLUpdates &update);\n\nprivate slots:\n void whenConnected();\n void whenReadyRead();\n\nprotected:\n void processRpcQuery(const QByteArray &data);\n\n void processSessionCreated(CTelegramStream &stream);\n void processContainer(CTelegramStream &stream);\n void processRpcResult(CTelegramStream &stream);\n void processGzipPacked(CTelegramStream &stream);\n bool processRpcError(CTelegramStream &stream, quint64 id, TLValue request);\n\n void processMessageAck(CTelegramStream &stream);\n void processIgnoredMessageNotification(CTelegramStream &stream);\n\n TLValue processHelpGetConfig(CTelegramStream &stream, quint64 id);\n TLValue processContactsGetContacts(CTelegramStream &stream, quint64 id);\n TLValue processContactsImportContacts(CTelegramStream &stream, quint64 id);\n TLValue processAuthCheckPhone(CTelegramStream &stream, quint64 id);\n TLValue processAuthSendCode(CTelegramStream &stream, quint64 id);\n TLValue processAuthSign(CTelegramStream &stream, quint64 id);\n TLValue processUploadGetFile(CTelegramStream &stream, quint64 id);\n TLValue processMessagesSendMessage(CTelegramStream &stream, quint64 id);\n\n bool processErrorSeeOther(const QString errorMessage, quint64 id);\n\n TLValue processUpdate(CTelegramStream &stream, bool *ok);\n\n SAesKey generateTmpAesKey() const;\n SAesKey generateClientToServerAesKey(const QByteArray &messageKey) const;\n SAesKey generateServerToClientAesKey(const QByteArray &messageKey) const;\n\n SAesKey generateAesKey(const QByteArray &messageKey, int xValue) const;\n\n void insertInitConnection(QByteArray *data) const;\n\n quint64 sendPlainPackage(const QByteArray &buffer);\n quint64 sendEncryptedPackage(const QByteArray &buffer);\n void setTransport(CTelegramTransport *newTransport);\n\n void setAuthState(AuthState newState);\n\n quint64 newMessageId();\n\n const CAppInformation *m_appInfo;\n\n QMap m_submittedPackages; \/\/ \n QMap m_requestedFilesIds; \/\/ \n\n CTelegramTransport *m_transport;\n\n AuthState m_authState;\n\n QByteArray m_authKey;\n quint64 m_authId;\n quint64 m_authKeyAuxHash;\n quint64 m_serverSalt;\n quint64 m_receivedServerSalt;\n quint64 m_sessionId;\n quint64 m_lastMessageId;\n quint32 m_sequenceNumber;\n quint32 m_contentRelatedMessages;\n\n qint32 m_deltaTime;\n DeltaTimeHeuristicState m_deltaTimeHeuristicState;\n\n TLNumber128 m_clientNonce;\n TLNumber128 m_serverNonce;\n TLNumber256 m_newNonce;\n\n quint64 m_pq;\n quint32 m_p;\n quint32 m_q;\n\n quint64 m_serverPublicFingersprint;\n SRsaKey m_rsaKey;\n SAesKey m_tmpAesKey;\n\n quint32 m_g;\n QByteArray m_dhPrime;\n QByteArray m_gA;\n QByteArray m_b;\n\n quint64 m_authRetryId;\n\n TLDcOption m_dcInfo;\n\n QVector m_dcConfiguration;\n\n QString m_authCodeHash;\n\n};\n\ninline SAesKey CTelegramConnection::generateClientToServerAesKey(const QByteArray &messageKey) const\n{\n return generateAesKey(messageKey, 0);\n}\n\ninline SAesKey CTelegramConnection::generateServerToClientAesKey(const QByteArray &messageKey) const\n{\n return generateAesKey(messageKey, 8);\n}\n\n#endif \/\/ CTELEGRAMCONNECTION_HPP\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: jvmargs.cxx,v $\n *\n * $Revision: 1.16 $\n *\n * last change: $Author: rt $ $Date: 2005-09-08 07:59:29 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"jvmargs.hxx\"\n#include \n\n\n#define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))\n\nusing namespace rtl;\n\nnamespace stoc_javavm {\n\nJVM::JVM() throw()\/\/: _enabled(sal_False)\n{\n}\n\nvoid JVM::pushProp(const OUString & property)\n{\n sal_Int32 index = property.indexOf((sal_Unicode)'=');\n if(index > 0)\n {\n OUString left = property.copy(0, index).trim();\n OUString right(property.copy(index + 1).trim());\n _props.push_back(property);\n }\n else\n { \/\/ no '=', could be -X\n _props.push_back(property);\n }\n}\n\n\nconst ::std::vector< ::rtl::OUString > & JVM::getProperties() const\n{\n return _props;\n}\n\n}\nINTEGRATION: CWS pchfix02 (1.16.36); FILE MERGED 2006\/09\/01 17:41:13 kaib 1.16.36.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: jvmargs.cxx,v $\n *\n * $Revision: 1.17 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 17:31:17 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_stoc.hxx\"\n\n#include \"jvmargs.hxx\"\n#include \n\n\n#define OUSTR(x) rtl::OUString(RTL_CONSTASCII_USTRINGPARAM( x ))\n\nusing namespace rtl;\n\nnamespace stoc_javavm {\n\nJVM::JVM() throw()\/\/: _enabled(sal_False)\n{\n}\n\nvoid JVM::pushProp(const OUString & property)\n{\n sal_Int32 index = property.indexOf((sal_Unicode)'=');\n if(index > 0)\n {\n OUString left = property.copy(0, index).trim();\n OUString right(property.copy(index + 1).trim());\n _props.push_back(property);\n }\n else\n { \/\/ no '=', could be -X\n _props.push_back(property);\n }\n}\n\n\nconst ::std::vector< ::rtl::OUString > & JVM::getProperties() const\n{\n return _props;\n}\n\n}\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2014 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"StringComponents.h\"\n\n#include \"ModelBase\/src\/nodes\/Node.h\"\n#include \"..\/expression_editor\/CompoundObjectDescriptor.h\"\n\n#include \"OOModel\/src\/allOOModelNodes.h\"\n\nnamespace OOInteraction {\n\nQMap& StringComponents::componentFunctions()\n{\n\tstatic QMap funcs;\n\treturn funcs;\n}\n\nStringComponents::StringComponents(Model::Node* node) : node_{node}\n{}\n\nStringComponents::~StringComponents()\n{}\n\nQStringList StringComponents::components()\n{\n\t\/\/if (!node_) return QStringList{};\n\tQ_ASSERT(node_);\n\n\tauto iter = componentFunctions().find(node_->typeId());\n\tif (iter != componentFunctions().end()) return iter.value()(node_);\n\tif (auto listNode = DCast(node_)) return c( list(listNode) );\n\n\tthrow OOInteractionException{\"No string component function registered for node of type \" + node_->typeName()};\n}\n\nQString StringComponents::stringForNode(Model::Node* node)\n{\n\tQString res = componentsForNode(node).join(\"\");\n\tif (res.isNull()) res = \"\";\n\treturn res;\n}\n\nQStringList StringComponents::componentsForNode(Model::Node* node)\n{\n\tif (!node) return QStringList{};\n\telse return StringComponents{node}.components();\n}\n\nStringComponents::Optional StringComponents::list(Model::List* listNode)\n{\n\tQStringList result;\n\tif (!listNode) return result;\n\n\tfor (int i=0; i< listNode->size(); ++i)\n\t\tresult << stringForNode(listNode->at(i));\n\n\treturn result;\n}\n\nStringComponents::Optional StringComponents::list(Model::List* listNode, const QString& prefix,\n\t\tconst QString& separator, const QString& postfix, bool nothingIfEmpty, bool collapse)\n{\n\tif (nothingIfEmpty && listNode->size() == 0)\n\t\treturn Optional{};\n\n\tQStringList list;\n\tlist << prefix;\n\tfor (int i=0; i< listNode->size(); ++i)\n\t{\n\t\tif (i>0) list << separator;\n\t\tlist << stringForNode(listNode->at(i));\n\t}\n\tlist << postfix;\n\n\tif (collapse) return list.join(\"\");\n\telse return list;\n}\n\nusing namespace OOModel;\nvoid StringComponents::initConversions()\n{\n\t\/\/ Types\n\tadd([](ArrayTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, \"[]\"); });\n\tadd([](ReferenceTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, \"&\"); });\n\tadd([](PointerTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, \"*\"); });\n\tadd([](ClassTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO} ); });\n\tadd([](PrimitiveTypeExpression* e){ return c(\n\t\tchoose(e->typeValue(),\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::INT, \"int\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::LONG, \"long\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_INT, \"uint\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_LONG, \"ulong\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::FLOAT, \"float\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::DOUBLE, \"double\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::BOOLEAN, \"bool\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::CHAR, \"char\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::VOID, \"void\")\n\t); });\n\tadd([](TypeQualifierExpression* e ){ return c(\n\t\t\tchoose(e->qualifier(),\n\t\t\t\t\tTypeQualifierExpression::Qualifier::CONST, \"const\",\n\t\t\t\t\tTypeQualifierExpression::Qualifier::VOLATILE, \"volatile\"),\n\t\t\t\" \", e->typeExpression() ); });\n\tadd([](AutoTypeExpression* ){ return c( \"auto\" ); });\n\tadd([](FunctionTypeExpression* e){ return c( \"[]\",\n\t\t\tlist(e->arguments(), \"(\", \",\", \")\", false, true),\n\t\t\tOptional{\"->\", e->results()->size() > 0},\n\t\t\tlist(e->results(), \"(\", \",\", \")\", true, true)\n\t);});\n\n\t\/\/ Operators\n\tadd([](AssignmentExpression* e){ return c(\n\t\tQString{}, e->left(), choose(e->op(),\n\t\t\tAssignmentExpression::ASSIGN, \"=\",\n\t\t\tAssignmentExpression::PLUS_ASSIGN, \"+=\",\n\t\t\tAssignmentExpression::MINUS_ASSIGN, \"-=\",\n\t\t\tAssignmentExpression::TIMES_ASSIGN, \"*=\",\n\t\t\tAssignmentExpression::DIVIDE_ASSIGN, \"\/=\",\n\t\t\tAssignmentExpression::BIT_AND_ASSIGN, \"&=\",\n\t\t\tAssignmentExpression::BIT_OR_ASSIGN, \"|=\",\n\t\t\tAssignmentExpression::BIT_XOR_ASSIGN, \"^=\",\n\t\t\tAssignmentExpression::REMAINDER_ASSIGN, \"%=\",\n\t\t\tAssignmentExpression::LEFT_SHIFT_ASSIGN, \"<<=\",\n\t\t\tAssignmentExpression::RIGHT_SHIFT_SIGNED_ASSIGN, \">>=\",\n\t\t\tAssignmentExpression::RIGHT_SHIFT_UNSIGNED_ASSIGN, \">>>=\"),\n\t\te->right(), QString{}\n\t); });\n\tadd([](BinaryOperation* e){ return c(\n\t\tQString{}, e->left(), choose(e->op(),\n\t\t\tBinaryOperation::TIMES, \"*\",\n\t\t\tBinaryOperation::DIVIDE, \"\/\",\n\t\t\tBinaryOperation::REMAINDER, \"%\",\n\t\t\tBinaryOperation::PLUS, \"+\",\n\t\t\tBinaryOperation::MINUS, \"-\",\n\t\t\tBinaryOperation::LEFT_SHIFT, \"<<\",\n\t\t\tBinaryOperation::RIGHT_SHIFT_SIGNED, \">>\",\n\t\t\tBinaryOperation::RIGHT_SHIFT_UNSIGNED, \">>>\",\n\t\t\tBinaryOperation::LESS, \"<\",\n\t\t\tBinaryOperation::GREATER, \">\",\n\t\t\tBinaryOperation::LESS_EQUALS, \"<=\",\n\t\t\tBinaryOperation::GREATER_EQUALS, \">=\",\n\t\t\tBinaryOperation::EQUALS, \"==\",\n\t\t\tBinaryOperation::NOT_EQUALS, \"!=\",\n\t\t\tBinaryOperation::XOR, \"^\",\n\t\t\tBinaryOperation::AND, \"&\",\n\t\t\tBinaryOperation::OR, \"|\",\n\t\t\tBinaryOperation::CONDITIONAL_AND, \"&&\",\n\t\t\tBinaryOperation::CONDITIONAL_OR, \"||\",\n\t\t\tBinaryOperation::ARRAY_INDEX, \"[\"),\n\t\te->right(),\n\t\te->op() == OOModel::BinaryOperation::ARRAY_INDEX ? \"]\" : QString{}\n\t); });\n\tadd([](UnaryOperation* e){ return c(\n\t\tchoose(e->op(),\n\t\t\tUnaryOperation::PREINCREMENT, \"++\",\n\t\t\tUnaryOperation::PREDECREMENT, \"--\",\n\t\t\tUnaryOperation::POSTINCREMENT, Optional{},\n\t\t\tUnaryOperation::POSTDECREMENT, Optional{},\n\t\t\tUnaryOperation::PLUS, \"+\",\n\t\t\tUnaryOperation::MINUS, \"-\",\n\t\t\tUnaryOperation::NOT, \"!\",\n\t\t\tUnaryOperation::COMPLEMENT, \"~\",\n\t\t\tUnaryOperation::PARENTHESIS, \"(\",\n\t\t\tUnaryOperation::DEREFERENCE, \"*\",\n\t\t\tUnaryOperation::ADDRESSOF, \"&\"),\n\t\te->operand(),\n\t\tchoose(e->op(),\n\t\t\tUnaryOperation::PREINCREMENT, Optional{},\n\t\t\tUnaryOperation::PREDECREMENT, Optional{},\n\t\t\tUnaryOperation::POSTINCREMENT, \"++\",\n\t\t\tUnaryOperation::POSTDECREMENT, \"--\",\n\t\t\tUnaryOperation::PLUS, Optional{},\n\t\t\tUnaryOperation::MINUS, Optional{},\n\t\t\tUnaryOperation::NOT, Optional{},\n\t\t\tUnaryOperation::COMPLEMENT, Optional{},\n\t\t\tUnaryOperation::PARENTHESIS, \")\",\n\t\t\tUnaryOperation::DEREFERENCE, Optional{},\n\t\t\tUnaryOperation::ADDRESSOF, Optional{})\n\t); });\n\tadd([](TypeTraitExpression* e){ return c(\n\t\t\tchoose( static_cast(e->typeTraitKind()),\n\t\t\t\tstatic_cast(TypeTraitExpression::TypeTraitKind::SizeOf), \"sizeof\",\n\t\t\t\tstatic_cast(TypeTraitExpression::TypeTraitKind::AlignOf), \"alignof\",\n\t\t\t\tstatic_cast(TypeTraitExpression::TypeTraitKind::TypeId), \"typeid\"),\n\t\t\t\"(\",\n\t\t\te->operand(),\n\t\t\t\")\"\n\t); });\n\n\n\t\/\/ Literals\n\tadd([](BooleanLiteral* e){ return c( e->value() ? \"true\" : \"false\" ); });\n\tadd([](IntegerLiteral* e){ return c( e->value() ); });\n\tadd([](FloatLiteral* e){ return c( e->value() ); });\n\tadd([](NullLiteral*){ return c( \"null\" ); });\n\tadd([](StringLiteral* e){ return c( \"\\\"\", e->value(), \"\\\"\" ); });\n\tadd([](CharacterLiteral* e){ return c( \"'\", e->value(), \"'\" ); });\n\n\t\/\/ Misc\n\tadd([](CastExpression* e){ return c( \"(\", e->castType(), \")\", e->expr() ); });\n\tadd(\n\t\t\t[](InstanceOfExpression* e){ return c( e->expr(), \" \", \"instanceof\", \" \", e->typeExpression() ); });\n\tadd([](CommaExpression* e){ return c( QString{}, e->left(), \",\", e->right(), QString{} ); });\n\tadd([](ConditionalExpression* e){ return c(\n\t\tQString{}, e->condition(), \"?\", e->trueExpression(), \":\", e->falseExpression(), QString{} ); });\n\tadd([](SuperExpression* ){ return c( \"super\" ); });\n\tadd([](ThisExpression* ){ return c( \"this\" ); });\n\tadd([](GlobalScopeExpression* ){ return c( \"::\" ); });\n\tadd([](ThrowExpression* e ){ return c( \"throw\", \" \", e->expr() ); });\n\tadd([](TypeNameOperator* e ){ return c( \"typename\", \" \", e->typeExpression() ); });\n\tadd([](DeleteExpression* e ){ return c( e->isArray() ? \"delete[]\":\"delete\", \" \", e->expr() ); });\n\tadd([](VariableDeclarationExpression* e ){ return c( e->decl()->typeExpression(), \" \",\n\t\t\te->decl()->name(), Optional{\"=\", e->decl()->initialValue()}, Optional{e->decl()->initialValue()}); });\n\n\tadd([](LambdaExpression* e ){ return c( CompoundObjectDescriptor::storeExpression(e)); });\n\n\tadd([](ArrayInitializer* e){ return c( list(e->values(), \"{\", \",\", \"}\", false, false) ); });\n\n\tadd([](MethodCallExpression* e){ return c(\n\t\te->callee(), list(e->arguments(), \"(\", \",\", \")\", false, true) ); });\n\n\tadd([](MetaCallExpression* e){ return c( \"#\",\n\t\te->callee(), list(e->arguments(), \"(\", \",\", \")\", false, true) ); });\n\n\tadd([](NewExpression* e){ return c( \"new\", \" \",\n\t\t\tOptional{ (e->dimensions()->size() > 0 || !e->initializer()) ? e->newType() : nullptr, AUTO},\n\t\t\tlist(e->dimensions(), \"[\", \",\", \"]\", true, true), Optional{e->initializer(), AUTO} ); });\n\n\tadd([](ReferenceExpression* e){ return c(\n\t\tOptional{e->prefix(), AUTO}, Optional{\n\t\t\t\t\t\t(e->memberKind() == ReferenceExpression::MemberKind::Dot ? \".\" :\n\t\t\t\t\t\t e->memberKind() == ReferenceExpression::MemberKind::Pointer ? \"->\" :\n\t\t\t\t\t\t e->memberKind() == ReferenceExpression::MemberKind::Static ? \"::\" : \"::template\"),\n\t\t\t\t\t\te->prefix()}, e->name(),\n\t\tlist(e->typeArguments(), \"<\", \",\", \">\", true, true) ); });\n\n\tadd([](OOReference* e){ return c( e->name() ); });\n\n\t\/\/ Flexible input expressions\n\tadd([](EmptyExpression*){ return c( \"\" ); });\n\tadd([](ErrorExpression* e){ return c(\n\t\tOptional{e->prefix(), !e->prefix().isEmpty()}, e->arg(), Optional{e->postfix(), !e->postfix().isEmpty()} ); });\n\tadd([](UnfinishedOperator* e)\n\t{\n\t\tQStringList result;\n\n\t\tfor (int i=0; i< e->operands()->size(); ++i)\n\t\t{\n\t\t\tQString delim = e->delimiters()->at(i)->get();\n\n\t\t\tresult << delim << stringForNode(e->operands()->at(i));\n\t\t}\n\n\t\tif (e->delimiters()->size() > e->operands()->size())\n\t\t{\n\t\t\tQString delim = e->delimiters()->last()->get();\n\t\t\tresult << delim;\n\t\t}\n\n\t\t\/\/ Insert spaces on the insdie of the result to make sure they don't stick to each other\n\t\tint i = 0;\n\t\tint lastNonEmpty = -1;\n\t\twhile (i= 0)\n\t\t\t\t{\n\t\t\t\t\tresult.insert(lastNonEmpty + 1, \" \");\n\t\t\t\t\t++i;\n\t\t\t\t}\n\t\t\t\tlastNonEmpty = i;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\treturn result;\n\t});\n}\n\n}\nAdd a clarification comment\/***********************************************************************************************************************\n **\n ** Copyright (c) 2011, 2014 ETH Zurich\n ** All rights reserved.\n **\n ** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the\n ** following conditions are met:\n **\n ** * Redistributions of source code must retain the above copyright notice, this list of conditions and the\n ** following disclaimer.\n ** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the\n ** following disclaimer in the documentation and\/or other materials provided with the distribution.\n ** * Neither the name of the ETH Zurich nor the names of its contributors may be used to endorse or promote products\n ** derived from this software without specific prior written permission.\n **\n **\n ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES,\n ** INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\n ** DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\n ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n ** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,\n ** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n **\n **********************************************************************************************************************\/\n\n#include \"StringComponents.h\"\n\n#include \"ModelBase\/src\/nodes\/Node.h\"\n#include \"..\/expression_editor\/CompoundObjectDescriptor.h\"\n\n#include \"OOModel\/src\/allOOModelNodes.h\"\n\nnamespace OOInteraction {\n\nQMap& StringComponents::componentFunctions()\n{\n\tstatic QMap funcs;\n\treturn funcs;\n}\n\nStringComponents::StringComponents(Model::Node* node) : node_{node}\n{}\n\nStringComponents::~StringComponents()\n{}\n\nQStringList StringComponents::components()\n{\n\t\/\/if (!node_) return QStringList{};\n\tQ_ASSERT(node_);\n\n\tauto iter = componentFunctions().find(node_->typeId());\n\tif (iter != componentFunctions().end()) return iter.value()(node_);\n\tif (auto listNode = DCast(node_)) return c( list(listNode) );\n\n\tthrow OOInteractionException{\"No string component function registered for node of type \" + node_->typeName()};\n}\n\nQString StringComponents::stringForNode(Model::Node* node)\n{\n\tQString res = componentsForNode(node).join(\"\");\n\tif (res.isNull()) res = \"\";\n\treturn res;\n}\n\nQStringList StringComponents::componentsForNode(Model::Node* node)\n{\n\tif (!node) return QStringList{};\n\telse return StringComponents{node}.components();\n}\n\nStringComponents::Optional StringComponents::list(Model::List* listNode)\n{\n\tQStringList result;\n\tif (!listNode) return result;\n\n\tfor (int i=0; i< listNode->size(); ++i)\n\t\tresult << stringForNode(listNode->at(i));\n\n\treturn result;\n}\n\nStringComponents::Optional StringComponents::list(Model::List* listNode, const QString& prefix,\n\t\tconst QString& separator, const QString& postfix, bool nothingIfEmpty, bool collapse)\n{\n\tif (nothingIfEmpty && listNode->size() == 0)\n\t\treturn Optional{};\n\n\tQStringList list;\n\tlist << prefix;\n\tfor (int i=0; i< listNode->size(); ++i)\n\t{\n\t\tif (i>0) list << separator;\n\t\tlist << stringForNode(listNode->at(i));\n\t}\n\tlist << postfix;\n\n\tif (collapse) return list.join(\"\");\n\telse return list;\n}\n\nusing namespace OOModel;\nvoid StringComponents::initConversions()\n{\n\t\/\/ Types\n\tadd([](ArrayTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, \"[]\"); });\n\tadd([](ReferenceTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, \"&\"); });\n\tadd([](PointerTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO}, \"*\"); });\n\tadd([](ClassTypeExpression* e){ return c( Optional{e->typeExpression(), AUTO} ); });\n\tadd([](PrimitiveTypeExpression* e){ return c(\n\t\tchoose(e->typeValue(),\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::INT, \"int\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::LONG, \"long\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_INT, \"uint\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::UNSIGNED_LONG, \"ulong\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::FLOAT, \"float\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::DOUBLE, \"double\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::BOOLEAN, \"bool\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::CHAR, \"char\",\n\t\t\tPrimitiveTypeExpression::PrimitiveTypes::VOID, \"void\")\n\t); });\n\tadd([](TypeQualifierExpression* e ){ return c(\n\t\t\tchoose(e->qualifier(),\n\t\t\t\t\tTypeQualifierExpression::Qualifier::CONST, \"const\",\n\t\t\t\t\tTypeQualifierExpression::Qualifier::VOLATILE, \"volatile\"),\n\t\t\t\" \", e->typeExpression() ); });\n\tadd([](AutoTypeExpression* ){ return c( \"auto\" ); });\n\tadd([](FunctionTypeExpression* e){ return c( \"[]\",\n\t\t\tlist(e->arguments(), \"(\", \",\", \")\", false, true),\n\t\t\tOptional{\"->\", e->results()->size() > 0},\n\t\t\tlist(e->results(), \"(\", \",\", \")\", true, true)\n\t);});\n\n\t\/\/ Operators\n\tadd([](AssignmentExpression* e){ return c(\n\t\tQString{}, e->left(), choose(e->op(),\n\t\t\tAssignmentExpression::ASSIGN, \"=\",\n\t\t\tAssignmentExpression::PLUS_ASSIGN, \"+=\",\n\t\t\tAssignmentExpression::MINUS_ASSIGN, \"-=\",\n\t\t\tAssignmentExpression::TIMES_ASSIGN, \"*=\",\n\t\t\tAssignmentExpression::DIVIDE_ASSIGN, \"\/=\",\n\t\t\tAssignmentExpression::BIT_AND_ASSIGN, \"&=\",\n\t\t\tAssignmentExpression::BIT_OR_ASSIGN, \"|=\",\n\t\t\tAssignmentExpression::BIT_XOR_ASSIGN, \"^=\",\n\t\t\tAssignmentExpression::REMAINDER_ASSIGN, \"%=\",\n\t\t\tAssignmentExpression::LEFT_SHIFT_ASSIGN, \"<<=\",\n\t\t\tAssignmentExpression::RIGHT_SHIFT_SIGNED_ASSIGN, \">>=\",\n\t\t\tAssignmentExpression::RIGHT_SHIFT_UNSIGNED_ASSIGN, \">>>=\"),\n\t\te->right(), QString{}\n\t); });\n\tadd([](BinaryOperation* e){ return c(\n\t\tQString{}, e->left(), choose(e->op(),\n\t\t\tBinaryOperation::TIMES, \"*\",\n\t\t\tBinaryOperation::DIVIDE, \"\/\",\n\t\t\tBinaryOperation::REMAINDER, \"%\",\n\t\t\tBinaryOperation::PLUS, \"+\",\n\t\t\tBinaryOperation::MINUS, \"-\",\n\t\t\tBinaryOperation::LEFT_SHIFT, \"<<\",\n\t\t\tBinaryOperation::RIGHT_SHIFT_SIGNED, \">>\",\n\t\t\tBinaryOperation::RIGHT_SHIFT_UNSIGNED, \">>>\",\n\t\t\tBinaryOperation::LESS, \"<\",\n\t\t\tBinaryOperation::GREATER, \">\",\n\t\t\tBinaryOperation::LESS_EQUALS, \"<=\",\n\t\t\tBinaryOperation::GREATER_EQUALS, \">=\",\n\t\t\tBinaryOperation::EQUALS, \"==\",\n\t\t\tBinaryOperation::NOT_EQUALS, \"!=\",\n\t\t\tBinaryOperation::XOR, \"^\",\n\t\t\tBinaryOperation::AND, \"&\",\n\t\t\tBinaryOperation::OR, \"|\",\n\t\t\tBinaryOperation::CONDITIONAL_AND, \"&&\",\n\t\t\tBinaryOperation::CONDITIONAL_OR, \"||\",\n\t\t\tBinaryOperation::ARRAY_INDEX, \"[\"),\n\t\te->right(),\n\t\te->op() == OOModel::BinaryOperation::ARRAY_INDEX ? \"]\" : QString{}\n\t); });\n\tadd([](UnaryOperation* e){ return c(\n\t\tchoose(e->op(),\n\t\t\tUnaryOperation::PREINCREMENT, \"++\",\n\t\t\tUnaryOperation::PREDECREMENT, \"--\",\n\t\t\tUnaryOperation::POSTINCREMENT, Optional{},\n\t\t\tUnaryOperation::POSTDECREMENT, Optional{},\n\t\t\tUnaryOperation::PLUS, \"+\",\n\t\t\tUnaryOperation::MINUS, \"-\",\n\t\t\tUnaryOperation::NOT, \"!\",\n\t\t\tUnaryOperation::COMPLEMENT, \"~\",\n\t\t\tUnaryOperation::PARENTHESIS, \"(\",\n\t\t\tUnaryOperation::DEREFERENCE, \"*\",\n\t\t\tUnaryOperation::ADDRESSOF, \"&\"),\n\t\te->operand(),\n\t\tchoose(e->op(),\n\t\t\tUnaryOperation::PREINCREMENT, Optional{},\n\t\t\tUnaryOperation::PREDECREMENT, Optional{},\n\t\t\tUnaryOperation::POSTINCREMENT, \"++\",\n\t\t\tUnaryOperation::POSTDECREMENT, \"--\",\n\t\t\tUnaryOperation::PLUS, Optional{},\n\t\t\tUnaryOperation::MINUS, Optional{},\n\t\t\tUnaryOperation::NOT, Optional{},\n\t\t\tUnaryOperation::COMPLEMENT, Optional{},\n\t\t\tUnaryOperation::PARENTHESIS, \")\",\n\t\t\tUnaryOperation::DEREFERENCE, Optional{},\n\t\t\tUnaryOperation::ADDRESSOF, Optional{})\n\t); });\n\tadd([](TypeTraitExpression* e){ return c(\n\t\t\tchoose( static_cast(e->typeTraitKind()),\n\t\t\t\tstatic_cast(TypeTraitExpression::TypeTraitKind::SizeOf), \"sizeof\",\n\t\t\t\tstatic_cast(TypeTraitExpression::TypeTraitKind::AlignOf), \"alignof\",\n\t\t\t\tstatic_cast(TypeTraitExpression::TypeTraitKind::TypeId), \"typeid\"),\n\t\t\t\"(\",\n\t\t\te->operand(),\n\t\t\t\")\"\n\t); });\n\n\n\t\/\/ Literals\n\tadd([](BooleanLiteral* e){ return c( e->value() ? \"true\" : \"false\" ); });\n\tadd([](IntegerLiteral* e){ return c( e->value() ); });\n\tadd([](FloatLiteral* e){ return c( e->value() ); });\n\tadd([](NullLiteral*){ return c( \"null\" ); });\n\tadd([](StringLiteral* e){ return c( \"\\\"\", e->value(), \"\\\"\" ); });\n\tadd([](CharacterLiteral* e){ return c( \"'\", e->value(), \"'\" ); });\n\n\t\/\/ Misc\n\tadd([](CastExpression* e){ return c( \"(\", e->castType(), \")\", e->expr() ); });\n\tadd(\n\t\t\t[](InstanceOfExpression* e){ return c( e->expr(), \" \", \"instanceof\", \" \", e->typeExpression() ); });\n\tadd([](CommaExpression* e){ return c( QString{}, e->left(), \",\", e->right(), QString{} ); });\n\tadd([](ConditionalExpression* e){ return c(\n\t\tQString{}, e->condition(), \"?\", e->trueExpression(), \":\", e->falseExpression(), QString{} ); });\n\tadd([](SuperExpression* ){ return c( \"super\" ); });\n\tadd([](ThisExpression* ){ return c( \"this\" ); });\n\tadd([](GlobalScopeExpression* ){ return c( \"::\" ); });\n\tadd([](ThrowExpression* e ){ return c( \"throw\", \" \", e->expr() ); });\n\tadd([](TypeNameOperator* e ){ return c( \"typename\", \" \", e->typeExpression() ); });\n\tadd([](DeleteExpression* e ){ return c( e->isArray() ? \"delete[]\":\"delete\", \" \", e->expr() ); });\n\tadd([](VariableDeclarationExpression* e ){ return c( e->decl()->typeExpression(), \" \",\n\t\t\te->decl()->name(), Optional{\"=\", e->decl()->initialValue()}, Optional{e->decl()->initialValue()}); });\n\n\tadd([](LambdaExpression* e ){ return c( CompoundObjectDescriptor::storeExpression(e)); });\n\n\tadd([](ArrayInitializer* e){ return c( list(e->values(), \"{\", \",\", \"}\", false, false) ); });\n\n\tadd([](MethodCallExpression* e){ return c(\n\t\te->callee(), list(e->arguments(), \"(\", \",\", \")\", false, true) ); });\n\n\tadd([](MetaCallExpression* e){ return c( \"#\",\n\t\te->callee(), list(e->arguments(), \"(\", \",\", \")\", false, true) ); });\n\n\tadd([](NewExpression* e){ return c( \"new\", \" \",\n\t\t\tOptional{ (e->dimensions()->size() > 0 || !e->initializer()) ? e->newType() : nullptr, AUTO},\n\t\t\tlist(e->dimensions(), \"[\", \",\", \"]\", true, true), Optional{e->initializer(), AUTO} ); });\n\n\tadd([](ReferenceExpression* e){ return c(\n\t\tOptional{e->prefix(), AUTO}, Optional{\n\t\t\t\t\t\t(e->memberKind() == ReferenceExpression::MemberKind::Dot ? \".\" :\n\t\t\t\t\t\t e->memberKind() == ReferenceExpression::MemberKind::Pointer ? \"->\" :\n\t\t\t\t\t\t e->memberKind() == ReferenceExpression::MemberKind::Static ? \"::\" : \"::template\"),\n\t\t\t\t\t\te->prefix()}, e->name(),\n\t\tlist(e->typeArguments(), \"<\", \",\", \">\", true, true) ); });\n\n\tadd([](OOReference* e){ return c( e->name() ); });\n\n\t\/\/ Flexible input expressions\n\tadd([](EmptyExpression*){ return c( \"\" ); });\n\tadd([](ErrorExpression* e){ return c(\n\t\tOptional{e->prefix(), !e->prefix().isEmpty()}, e->arg(), Optional{e->postfix(), !e->postfix().isEmpty()} ); });\n\tadd([](UnfinishedOperator* e)\n\t{\n\t\tQStringList result;\n\n\t\tfor (int i=0; i< e->operands()->size(); ++i)\n\t\t{\n\t\t\tQString delim = e->delimiters()->at(i)->get();\n\n\t\t\tresult << delim << stringForNode(e->operands()->at(i));\n\t\t}\n\n\t\tif (e->delimiters()->size() > e->operands()->size())\n\t\t{\n\t\t\tQString delim = e->delimiters()->last()->get();\n\t\t\tresult << delim;\n\t\t}\n\n\t\t\/\/ Insert spaces on the insdie of the result to make sure they don't stick to each other\n\t\t\/\/ E.g. when typing 'delete new foo'\n\t\tint i = 0;\n\t\tint lastNonEmpty = -1;\n\t\twhile (i= 0)\n\t\t\t\t{\n\t\t\t\t\tresult.insert(lastNonEmpty + 1, \" \");\n\t\t\t\t\t++i;\n\t\t\t\t}\n\t\t\t\tlastNonEmpty = i;\n\t\t\t}\n\t\t\t++i;\n\t\t}\n\n\t\treturn result;\n\t});\n}\n\n}\n<|endoftext|>"} {"text":"CEQU - Crucial Equation.cpp<|endoftext|>"} {"text":"#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"gfx\/gl_lost_manager.h\"\n\nstd::vector *holders;\n\nstatic bool inLost;\n\nvoid register_gl_resource_holder(GfxResourceHolder *holder) {\n\tif (inLost) {\n\t\tFLOG(\"BAD: Should not call register_gl_resource_holder from lost path\");\n\t\treturn;\n\t}\n\tif (holders) {\n\t\tholders->push_back(holder);\n\t} else {\n\t\tWLOG(\"GL resource holder not initialized, cannot register resource\");\n\t}\n}\n\nvoid unregister_gl_resource_holder(GfxResourceHolder *holder) {\n\tif (inLost) {\n\t\tFLOG(\"BAD: Should not call unregister_gl_resource_holder from lost path\");\n\t\treturn;\n\t}\n\tif (holders) {\n\t\tfor (size_t i = 0; i < holders->size(); i++) {\n\t\t\tif ((*holders)[i] == holder) {\n\t\t\t\tholders->erase(holders->begin() + i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tWLOG(\"unregister_gl_resource_holder: Resource not registered\");\n\t} else {\n\t\tWLOG(\"GL resource holder not initialized or already shutdown, cannot unregister resource\");\n\t}\n}\n\nvoid gl_lost() {\n\tinLost = true;\n\tif (!holders) {\n\t\tWLOG(\"GL resource holder not initialized, cannot process lost request\");\n\t\tinLost = false;\n\t\treturn;\n\t}\n\n\t\/\/ TODO: We should really do this when we get the context back, not during gl_lost...\n\tILOG(\"gl_lost() restoring %i items:\", (int)holders->size());\n\tfor (size_t i = 0; i < holders->size(); i++) {\n\t\tILOG(\"GLLost(%i \/ %i, %p)\", (int)(i + 1), (int) holders->size(), (*holders)[i]);\n\t\t(*holders)[i]->GLLost();\n\t}\n\tILOG(\"gl_lost() completed restoring %i items:\", (int)holders->size());\n\tinLost = false;\n}\n\nvoid gl_lost_manager_init() {\n\tif (holders) {\n\t\tFLOG(\"Double GL lost manager init\");\n\t\t\/\/ Dead here (FLOG), no need to delete holders\n\t}\n\tholders = new std::vector();\n}\n\nvoid gl_lost_manager_shutdown() {\n\tif (!holders) {\n\t\tFLOG(\"Lost manager already shutdown\");\n\t}\n\tdelete holders;\n\tholders = 0;\n}\nLog an error if lost manager exits with objects still registered#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"gfx\/gl_lost_manager.h\"\n\nstd::vector *holders;\n\nstatic bool inLost;\n\nvoid register_gl_resource_holder(GfxResourceHolder *holder) {\n\tif (inLost) {\n\t\tFLOG(\"BAD: Should not call register_gl_resource_holder from lost path\");\n\t\treturn;\n\t}\n\tif (holders) {\n\t\tholders->push_back(holder);\n\t} else {\n\t\tWLOG(\"GL resource holder not initialized, cannot register resource\");\n\t}\n}\n\nvoid unregister_gl_resource_holder(GfxResourceHolder *holder) {\n\tif (inLost) {\n\t\tFLOG(\"BAD: Should not call unregister_gl_resource_holder from lost path\");\n\t\treturn;\n\t}\n\tif (holders) {\n\t\tfor (size_t i = 0; i < holders->size(); i++) {\n\t\t\tif ((*holders)[i] == holder) {\n\t\t\t\tholders->erase(holders->begin() + i);\n\t\t\t\treturn;\n\t\t\t}\n\t\t}\n\t\tWLOG(\"unregister_gl_resource_holder: Resource not registered\");\n\t} else {\n\t\tWLOG(\"GL resource holder not initialized or already shutdown, cannot unregister resource\");\n\t}\n}\n\nvoid gl_lost() {\n\tinLost = true;\n\tif (!holders) {\n\t\tWLOG(\"GL resource holder not initialized, cannot process lost request\");\n\t\tinLost = false;\n\t\treturn;\n\t}\n\n\t\/\/ TODO: We should really do this when we get the context back, not during gl_lost...\n\tILOG(\"gl_lost() restoring %i items:\", (int)holders->size());\n\tfor (size_t i = 0; i < holders->size(); i++) {\n\t\tILOG(\"GLLost(%i \/ %i, %p)\", (int)(i + 1), (int) holders->size(), (*holders)[i]);\n\t\t(*holders)[i]->GLLost();\n\t}\n\tILOG(\"gl_lost() completed restoring %i items:\", (int)holders->size());\n\tinLost = false;\n}\n\nvoid gl_lost_manager_init() {\n\tif (holders) {\n\t\tFLOG(\"Double GL lost manager init\");\n\t\t\/\/ Dead here (FLOG), no need to delete holders\n\t}\n\tholders = new std::vector();\n}\n\nvoid gl_lost_manager_shutdown() {\n\tif (!holders) {\n\t\tFLOG(\"Lost manager already shutdown\");\n\t} else if (holders->size() > 0) {\n\t\tELOG(\"Lost manager shutdown with %i objects still registered\", (int)holders->size());\n\t}\n\n\tdelete holders;\n\tholders = 0;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n *\n * package: Log4Qt\n * file: loggingevent.cpp\n * created: September 2007\n * author: Martin Heinrich\n *\n * \n * Copyright 2007 Martin Heinrich\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n * \n *****************************************************************************\/\n\n\n\n\/******************************************************************************\n * Dependencies\n ******************************************************************************\/\n\n\n#include \"loggingevent.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"helpers\/datetime.h\"\n#include \"helpers\/initialisationhelper.h\"\n#include \"logger.h\"\n#include \"mdc.h\"\n#include \"ndc.h\"\n\n\n\nnamespace Log4Qt\n{\n\t\n\t\n\t\/**************************************************************************\n\t * Declarations\n\t **************************************************************************\/\n\t\n\t \n\tLOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)\n\t\n\t\n\t\n\t\/**************************************************************************\n\t * C helper functions\n\t **************************************************************************\/\n\t\n\t\n\t\n\t\/**************************************************************************\n\t * Class implementation: LoggingEvent\n\t **************************************************************************\/\n\t\n\t\n\tLoggingEvent::LoggingEvent() :\n\t\tmLevel(Level::NULL_INT),\n\t mpLogger(0),\n\t mMessage(),\n\t mNdc(NDC::peek()),\n\t mProperties(MDC::context()),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(),\n\t mTimeStamp(DateTime::currentDateTime().toMilliSeconds())\n\t{\n\t\tsetThreadNameToCurrent();\n\t}\n\t\n\t\n\tLoggingEvent::LoggingEvent(const Logger *pLogger, \n\t Level level,\n\t const QString &rMessage) :\n\t mLevel(level),\n\t mpLogger(pLogger),\n\t mMessage(rMessage),\n\t mNdc(NDC::peek()),\n\t mProperties(MDC::context()),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(),\n\t mTimeStamp(DateTime::currentDateTime().toMilliSeconds())\n\t{\n\t\tsetThreadNameToCurrent();\n\t}\n\t\n\t\n\tLoggingEvent::LoggingEvent(const Logger *pLogger,\n\t Level level,\n\t const QString &rMessage,\n\t qint64 timeStamp) :\n\t mLevel(level),\n\t mpLogger(pLogger),\n\t mMessage(rMessage),\n\t mNdc(NDC::peek()),\n\t mProperties(MDC::context()),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(),\n\t mTimeStamp(timeStamp)\n\t{\n\t\tsetThreadNameToCurrent();\n\t}\n\t\n\t\n\tLoggingEvent::LoggingEvent(const Logger *pLogger, \n\t Level level, \n\t const QString &rMessage,\n\t const QString &rNdc,\n\t const QHash &rProperties,\n\t const QString &rThreadName,\n\t qint64 timeStamp) :\n\t mLevel(level),\n\t mpLogger(pLogger),\n\t mMessage(rMessage),\n\t mNdc(rNdc),\n\t mProperties(rProperties),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(rThreadName),\n\t mTimeStamp(timeStamp)\n\t{\n\t}\n\t\n\t\n\tQString LoggingEvent::loggerName() const\n\t{\t\n\t\tif (mpLogger)\n\t\t\treturn mpLogger->name();\n\t\telse\n\t\t\treturn QString();\n\t}\n\t\n\t\n\tQString LoggingEvent::toString() const\n\t{ \n\t return level().toString() + QLatin1Char(':') + message();\n\t}\n\t\n\t\n\tqint64 LoggingEvent::sequenceCount()\n\t{\n\t QMutexLocker locker(sequence_guard());\n\t \n\t return msSequenceCount;\n\t} \n\t\n\t\n\tqint64 LoggingEvent::startTime()\n\t{\n\t\treturn InitialisationHelper::startTime();\n\t}\n\t\n\t\n\tvoid LoggingEvent::setThreadNameToCurrent()\n\t{\n\t\tif (QThread::currentThread())\n\t\t\tmThreadName = QThread::currentThread()->objectName();\n\t}\n\t\n\t\n\tqint64 LoggingEvent::nextSequenceNumber()\n\t{ \n\t QMutexLocker locker(sequence_guard());\n\t \n\t return ++msSequenceCount; \n\t}\n\t\n\t\n\tqint64 LoggingEvent::msSequenceCount = 0;\n\t\n\t\n\t\n\t\/**************************************************************************\n\t * Implementation: Operators, Helper\n\t **************************************************************************\/\n\t\n\t\n#ifndef QT_NO_DATASTREAM\n QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)\n {\n QBuffer buffer;\n buffer.open(QIODevice::WriteOnly);\n QDataStream stream(&buffer);\n \n \/\/ version\n quint16 version = 0; \n stream << version;\n \/\/ version 0 data\n stream << rLoggingEvent.mLevel\n << rLoggingEvent.loggerName()\n << rLoggingEvent.mMessage\n << rLoggingEvent.mNdc\n << rLoggingEvent.mProperties\n << rLoggingEvent.mSequenceNumber\n << rLoggingEvent.mThreadName\n << rLoggingEvent.mTimeStamp;\n \n buffer.close();\n rStream << buffer.buffer();\n return rStream; \n }\n \n \n QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)\n {\n QByteArray array;\n rStream >> array;\n QBuffer buffer(&array);\n buffer.open(QIODevice::ReadOnly);\n QDataStream stream(&buffer);\n \n \/\/ version\n quint16 version; \n stream >> version;\n \/\/ Version 0 data\n QString logger;\n stream >> rLoggingEvent.mLevel\n >> logger\n >> rLoggingEvent.mMessage\n >> rLoggingEvent.mNdc\n >> rLoggingEvent.mProperties\n >> rLoggingEvent.mSequenceNumber\n >> rLoggingEvent.mThreadName\n >> rLoggingEvent.mTimeStamp;\n if (logger.isEmpty())\n rLoggingEvent.mpLogger = 0;\n else\n rLoggingEvent.mpLogger = Logger::logger(logger);\n \n buffer.close();\n return rStream; \n }\n#endif \/\/ QT_NO_DATASTREAM\n\n \n#ifndef QT_NO_DEBUG_STREAM\n\tQDebug operator<<(QDebug debug, \n\t const LoggingEvent &rLoggingEvent)\n\t{\n\t QString logger;\n\t if (rLoggingEvent.logger() != 0)\n\t logger = rLoggingEvent.logger()->name();\n\t \n\t debug.nospace() << \"LoggingEvent(\" \n\t << \"level:\" << rLoggingEvent.level().toString() << \" \"\n\t << \"logger:\" << logger << \" \"\n\t << \"message:\" << rLoggingEvent.message() << \" \"\n\t << \"sequencenumber:\" << rLoggingEvent.sequenceNumber() << \" \"\n\t << \"threadname:\" << rLoggingEvent.threadName() << \" \"\n\t << \"timestamp:\" << rLoggingEvent.timeStamp()\n\t \t<< \"(\" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << \")\"\n\t << \"sequenceCount:\" << rLoggingEvent.sequenceCount()\n\t << \")\";\n\t return debug.space();\n\t}\n#endif \/\/ QT_NO_DEBUG_STREAM\n\t\n\t\n} \/\/ namespace Log4Qt\nIf object name is not defined for thread use thread ID instead if object name for thread identification\/******************************************************************************\n *\n * package: Log4Qt\n * file: loggingevent.cpp\n * created: September 2007\n * author: Martin Heinrich\n *\n *\n * Copyright 2007 Martin Heinrich\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n *****************************************************************************\/\n\n\n\n\/******************************************************************************\n * Dependencies\n ******************************************************************************\/\n\n\n#include \"loggingevent.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"helpers\/datetime.h\"\n#include \"helpers\/initialisationhelper.h\"\n#include \"logger.h\"\n#include \"mdc.h\"\n#include \"ndc.h\"\n\n\n\nnamespace Log4Qt\n{\n\n\n\t\/**************************************************************************\n\t * Declarations\n\t **************************************************************************\/\n\n\n\tLOG4QT_GLOBAL_STATIC(QMutex, sequence_guard)\n\n\n\n\t\/**************************************************************************\n\t * C helper functions\n\t **************************************************************************\/\n\n\n\n\t\/**************************************************************************\n\t * Class implementation: LoggingEvent\n\t **************************************************************************\/\n\n\n\tLoggingEvent::LoggingEvent() :\n\t\tmLevel(Level::NULL_INT),\n\t mpLogger(0),\n\t mMessage(),\n\t mNdc(NDC::peek()),\n\t mProperties(MDC::context()),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(),\n\t mTimeStamp(DateTime::currentDateTime().toMilliSeconds())\n\t{\n\t\tsetThreadNameToCurrent();\n\t}\n\n\n\tLoggingEvent::LoggingEvent(const Logger *pLogger,\n\t Level level,\n\t const QString &rMessage) :\n\t mLevel(level),\n\t mpLogger(pLogger),\n\t mMessage(rMessage),\n\t mNdc(NDC::peek()),\n\t mProperties(MDC::context()),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(),\n\t mTimeStamp(DateTime::currentDateTime().toMilliSeconds())\n\t{\n\t\tsetThreadNameToCurrent();\n\t}\n\n\n\tLoggingEvent::LoggingEvent(const Logger *pLogger,\n\t Level level,\n\t const QString &rMessage,\n\t qint64 timeStamp) :\n\t mLevel(level),\n\t mpLogger(pLogger),\n\t mMessage(rMessage),\n\t mNdc(NDC::peek()),\n\t mProperties(MDC::context()),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(),\n\t mTimeStamp(timeStamp)\n\t{\n\t\tsetThreadNameToCurrent();\n\t}\n\n\n\tLoggingEvent::LoggingEvent(const Logger *pLogger,\n\t Level level,\n\t const QString &rMessage,\n\t const QString &rNdc,\n\t const QHash &rProperties,\n\t const QString &rThreadName,\n\t qint64 timeStamp) :\n\t mLevel(level),\n\t mpLogger(pLogger),\n\t mMessage(rMessage),\n\t mNdc(rNdc),\n\t mProperties(rProperties),\n\t mSequenceNumber(nextSequenceNumber()),\n\t mThreadName(rThreadName),\n\t mTimeStamp(timeStamp)\n\t{\n\t}\n\n\n\tQString LoggingEvent::loggerName() const\n\t{\n\t\tif (mpLogger)\n\t\t\treturn mpLogger->name();\n\t\telse\n\t\t\treturn QString();\n\t}\n\n\n\tQString LoggingEvent::toString() const\n\t{\n\t return level().toString() + QLatin1Char(':') + message();\n\t}\n\n\n\tqint64 LoggingEvent::sequenceCount()\n\t{\n\t QMutexLocker locker(sequence_guard());\n\n\t return msSequenceCount;\n\t}\n\n\n\tqint64 LoggingEvent::startTime()\n\t{\n\t\treturn InitialisationHelper::startTime();\n\t}\n\n\n\tvoid LoggingEvent::setThreadNameToCurrent()\n\t{\n\t\tif (QThread::currentThread())\n\t\t{\n\t\t\tmThreadName = QThread::currentThread()->objectName();\n\t\t\t\/\/ if object name is not set use thread id for thead identification\n\t\t\tif (mThreadName.isEmpty())\n\t\t\t\tmThreadName = QString(\"0x%0\").arg(QThread::currentThreadId(),4,16);\n\t\t}\n\t}\n\n\n\tqint64 LoggingEvent::nextSequenceNumber()\n\t{\n\t QMutexLocker locker(sequence_guard());\n\n\t return ++msSequenceCount;\n\t}\n\n\n\tqint64 LoggingEvent::msSequenceCount = 0;\n\n\n\n\t\/**************************************************************************\n\t * Implementation: Operators, Helper\n\t **************************************************************************\/\n\n\n#ifndef QT_NO_DATASTREAM\n QDataStream &operator<<(QDataStream &rStream, const LoggingEvent &rLoggingEvent)\n {\n QBuffer buffer;\n buffer.open(QIODevice::WriteOnly);\n QDataStream stream(&buffer);\n\n \/\/ version\n quint16 version = 0;\n stream << version;\n \/\/ version 0 data\n stream << rLoggingEvent.mLevel\n << rLoggingEvent.loggerName()\n << rLoggingEvent.mMessage\n << rLoggingEvent.mNdc\n << rLoggingEvent.mProperties\n << rLoggingEvent.mSequenceNumber\n << rLoggingEvent.mThreadName\n << rLoggingEvent.mTimeStamp;\n\n buffer.close();\n rStream << buffer.buffer();\n return rStream;\n }\n\n\n QDataStream &operator>>(QDataStream &rStream, LoggingEvent &rLoggingEvent)\n {\n QByteArray array;\n rStream >> array;\n QBuffer buffer(&array);\n buffer.open(QIODevice::ReadOnly);\n QDataStream stream(&buffer);\n\n \/\/ version\n quint16 version;\n stream >> version;\n \/\/ Version 0 data\n QString logger;\n stream >> rLoggingEvent.mLevel\n >> logger\n >> rLoggingEvent.mMessage\n >> rLoggingEvent.mNdc\n >> rLoggingEvent.mProperties\n >> rLoggingEvent.mSequenceNumber\n >> rLoggingEvent.mThreadName\n >> rLoggingEvent.mTimeStamp;\n if (logger.isEmpty())\n rLoggingEvent.mpLogger = 0;\n else\n rLoggingEvent.mpLogger = Logger::logger(logger);\n\n buffer.close();\n return rStream;\n }\n#endif \/\/ QT_NO_DATASTREAM\n\n\n#ifndef QT_NO_DEBUG_STREAM\n\tQDebug operator<<(QDebug debug,\n\t const LoggingEvent &rLoggingEvent)\n\t{\n\t QString logger;\n\t if (rLoggingEvent.logger() != 0)\n\t logger = rLoggingEvent.logger()->name();\n\n\t debug.nospace() << \"LoggingEvent(\"\n\t << \"level:\" << rLoggingEvent.level().toString() << \" \"\n\t << \"logger:\" << logger << \" \"\n\t << \"message:\" << rLoggingEvent.message() << \" \"\n\t << \"sequencenumber:\" << rLoggingEvent.sequenceNumber() << \" \"\n\t << \"threadname:\" << rLoggingEvent.threadName() << \" \"\n\t << \"timestamp:\" << rLoggingEvent.timeStamp()\n\t \t<< \"(\" << DateTime::fromMilliSeconds(rLoggingEvent.timeStamp()) << \")\"\n\t << \"sequenceCount:\" << rLoggingEvent.sequenceCount()\n\t << \")\";\n\t return debug.space();\n\t}\n#endif \/\/ QT_NO_DEBUG_STREAM\n\n\n} \/\/ namespace Log4Qt\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: Edit.hxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: rt $ $Date: 2004-05-07 16:06:52 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FORMS_EDIT_HXX_\n#define _FORMS_EDIT_HXX_\n\n#ifndef _FORMS_EDITBASE_HXX_\n#include \"EditBase.hxx\"\n#endif\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include \n#endif\n\n\/\/.........................................................................\nnamespace frm\n{\n\n\/\/==================================================================\n\/\/= OEditModel\n\/\/==================================================================\nclass OEditModel\n :public OEditBaseModel\n ,public ::comphelper::OAggregationArrayUsageHelper< OEditModel >\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter;\n ::rtl::OUString m_aSaveValue;\n sal_Int32 m_nFormatKey;\n ::com::sun::star::util::Date m_aNullDate;\n sal_Int32 m_nFieldType;\n sal_Int16 m_nKeyType;\n sal_Bool m_bMaxTextLenModified : 1; \/\/ set to when we change the MaxTextLen of the aggregate\n\n sal_Bool m_bWritingFormattedFake : 1;\n \/\/ are we writing something which should be interpreted as formatted upon reading?\n sal_Bool m_bNumericField : 1;\n \/\/ are we bound to some kind of numeric field?\n\nprotected:\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\n DECLARE_DEFAULT_LEAF_XTOR( OEditModel );\n\n void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; }\n void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; }\n sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; }\n\n friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);\n friend class OFormattedFieldWrapper;\n friend class OFormattedModel; \/\/ temporary\n\npublic:\n virtual void SAL_CALL disposing();\n\n \/\/ XPropertySet\n virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;\n\/\/ ::com::sun::star::io::XPersistObject\n virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::beans::XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n\n\/\/ XReset\n virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(OEditModel);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n\n\/\/ OAggregationArrayUsageHelper\n virtual void fillProperties(\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rProps,\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rAggregateProps\n ) const;\n IMPLEMENT_INFO_SERVICE()\n\nprotected:\n \/\/ OControlModel overridables\n virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const;\n virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream );\n\n \/\/ OBoundControlModel overridables\n virtual ::com::sun::star::uno::Any\n translateDbColumnToControlValue( );\n virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );\n\n virtual ::com::sun::star::uno::Any\n getDefaultForReset() const;\n\n virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );\n virtual void onDisconnectedDbColumn();\n\n virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );\n virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType );\n\nprotected:\n virtual sal_Int16 getPersistenceFlags() const;\n\n DECLARE_XCLONEABLE();\n\nprivate:\n bool implActsAsRichText( ) const;\n};\n\n\/\/==================================================================\n\/\/= OEditControl\n\/\/==================================================================\ntypedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,\n ::com::sun::star::awt::XKeyListener,\n ::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE;\n\nclass OEditControl : public OBoundControl\n ,public OEditControl_BASE\n{\n ::cppu::OInterfaceContainerHelper\n m_aChangeListeners;\n\n ::rtl::OUString m_aHtmlChangeValue;\n sal_uInt32 m_nKeyEvent;\n\npublic:\n OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);\n virtual ~OEditControl();\n\n DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl);\n virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\n\/\/ OComponentHelper\n virtual void SAL_CALL disposing();\n\n\/\/ ::com::sun::star::lang::XEventListener\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(OEditControl);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n\n\/\/ ::com::sun::star::form::XChangeBroadcaster\n virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::awt::XFocusListener\n virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::awt::XKeyListener\n virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);\n\nprivate:\n DECL_LINK( OnKeyPressed, void* );\n};\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_EDIT_HXX_\n\nINTEGRATION: CWS dba12 (1.9.6); FILE MERGED 2004\/06\/14 20:59:21 fs 1.9.6.2: RESYNC: (1.9-1.10); FILE MERGED 2004\/04\/26 09:18:43 fs 1.9.6.1: #i27072# disable Java-like text notifications on the peer\/*************************************************************************\n *\n * $RCSfile: Edit.hxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: hjs $ $Date: 2004-06-28 17:08:39 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _FORMS_EDIT_HXX_\n#define _FORMS_EDIT_HXX_\n\n#ifndef _FORMS_EDITBASE_HXX_\n#include \"EditBase.hxx\"\n#endif\n#ifndef _CPPUHELPER_IMPLBASE3_HXX_\n#include \n#endif\n\n\/\/.........................................................................\nnamespace frm\n{\n\n\/\/==================================================================\n\/\/= OEditModel\n\/\/==================================================================\nclass OEditModel\n :public OEditBaseModel\n ,public ::comphelper::OAggregationArrayUsageHelper< OEditModel >\n{\n ::com::sun::star::uno::Reference< ::com::sun::star::util::XNumberFormatter> m_xFormatter;\n ::rtl::OUString m_aSaveValue;\n sal_Int32 m_nFormatKey;\n ::com::sun::star::util::Date m_aNullDate;\n sal_Int32 m_nFieldType;\n sal_Int16 m_nKeyType;\n sal_Bool m_bMaxTextLenModified : 1; \/\/ set to when we change the MaxTextLen of the aggregate\n\n sal_Bool m_bWritingFormattedFake : 1;\n \/\/ are we writing something which should be interpreted as formatted upon reading?\n sal_Bool m_bNumericField : 1;\n \/\/ are we bound to some kind of numeric field?\n\nprotected:\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\n DECLARE_DEFAULT_LEAF_XTOR( OEditModel );\n\n void enableFormattedWriteFake() { m_bWritingFormattedFake = sal_True; }\n void disableFormattedWriteFake() { m_bWritingFormattedFake = sal_False; }\n sal_Bool lastReadWasFormattedFake() const { return (getLastReadVersion() & PF_FAKE_FORMATTED_FIELD) != 0; }\n\n friend InterfaceRef SAL_CALL OEditModel_CreateInstance(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);\n friend class OFormattedFieldWrapper;\n friend class OFormattedModel; \/\/ temporary\n\npublic:\n virtual void SAL_CALL disposing();\n\n \/\/ XPropertySet\n virtual void SAL_CALL getFastPropertyValue(::com::sun::star::uno::Any& rValue, sal_Int32 nHandle ) const;\n\/\/ ::com::sun::star::io::XPersistObject\n virtual void SAL_CALL write(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream>& _rxOutStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL read(const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream>& _rxInStream) throw ( ::com::sun::star::io::IOException, ::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL getServiceName() throw ( ::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::beans::XPropertySet\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::beans::XPropertySetInfo> SAL_CALL getPropertySetInfo() throw(::com::sun::star::uno::RuntimeException);\n virtual ::cppu::IPropertyArrayHelper& SAL_CALL getInfoHelper();\n\n\/\/ XReset\n virtual void SAL_CALL reset( ) throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(OEditModel);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n\n\/\/ OAggregationArrayUsageHelper\n virtual void fillProperties(\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rProps,\n ::com::sun::star::uno::Sequence< ::com::sun::star::beans::Property >& \/* [out] *\/ _rAggregateProps\n ) const;\n IMPLEMENT_INFO_SERVICE()\n\nprotected:\n \/\/ OControlModel overridables\n virtual void writeAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectOutputStream >& _rxOutStream ) const;\n virtual void readAggregate( const ::com::sun::star::uno::Reference< ::com::sun::star::io::XObjectInputStream >& _rxInStream );\n\n \/\/ OBoundControlModel overridables\n virtual ::com::sun::star::uno::Any\n translateDbColumnToControlValue( );\n virtual sal_Bool commitControlValueToDbColumn( bool _bPostReset );\n\n virtual ::com::sun::star::uno::Any\n getDefaultForReset() const;\n\n virtual void onConnectedDbColumn( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& _rxForm );\n virtual void onDisconnectedDbColumn();\n\n virtual sal_Bool approveValueBinding( const ::com::sun::star::uno::Reference< ::com::sun::star::form::binding::XValueBinding >& _rxBinding );\n virtual sal_Bool approveDbColumnType( sal_Int32 _nColumnType );\n\nprotected:\n virtual sal_Int16 getPersistenceFlags() const;\n\n DECLARE_XCLONEABLE();\n\nprivate:\n bool implActsAsRichText( ) const;\n};\n\n\/\/==================================================================\n\/\/= OEditControl\n\/\/==================================================================\ntypedef ::cppu::ImplHelper3< ::com::sun::star::awt::XFocusListener,\n ::com::sun::star::awt::XKeyListener,\n ::com::sun::star::form::XChangeBroadcaster > OEditControl_BASE;\n\nclass OEditControl : public OBoundControl\n ,public OEditControl_BASE\n{\n ::cppu::OInterfaceContainerHelper\n m_aChangeListeners;\n\n ::rtl::OUString m_aHtmlChangeValue;\n sal_uInt32 m_nKeyEvent;\n\npublic:\n OEditControl(const ::com::sun::star::uno::Reference< ::com::sun::star::lang::XMultiServiceFactory>& _rxFactory);\n virtual ~OEditControl();\n\n DECLARE_UNO3_AGG_DEFAULTS(OEditControl, OBoundControl);\n virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation(const ::com::sun::star::uno::Type& _rType) throw(::com::sun::star::uno::RuntimeException);\n\n virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type> _getTypes();\n\n\/\/ OComponentHelper\n virtual void SAL_CALL disposing();\n\n\/\/ ::com::sun::star::lang::XEventListener\n virtual void SAL_CALL disposing(const ::com::sun::star::lang::EventObject& _rSource) throw(::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::lang::XServiceInfo\n IMPLEMENTATION_NAME(OEditControl);\n virtual StringSequence SAL_CALL getSupportedServiceNames() throw();\n\n\/\/ ::com::sun::star::form::XChangeBroadcaster\n virtual void SAL_CALL addChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL removeChangeListener(const ::com::sun::star::uno::Reference< ::com::sun::star::form::XChangeListener>& _rxListener) throw ( ::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::awt::XFocusListener\n virtual void SAL_CALL focusGained( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL focusLost( const ::com::sun::star::awt::FocusEvent& e ) throw ( ::com::sun::star::uno::RuntimeException);\n\n\/\/ ::com::sun::star::awt::XKeyListener\n virtual void SAL_CALL keyPressed(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL keyReleased(const ::com::sun::star::awt::KeyEvent& e) throw ( ::com::sun::star::uno::RuntimeException);\n\n \/\/ XControl\n virtual void SAL_CALL createPeer( const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XToolkit >& _rxToolkit, const ::com::sun::star::uno::Reference< ::com::sun::star::awt::XWindowPeer >& _rxParent ) throw ( ::com::sun::star::uno::RuntimeException );\n\nprivate:\n DECL_LINK( OnKeyPressed, void* );\n};\n\n\/\/.........................................................................\n}\n\/\/.........................................................................\n\n#endif \/\/ _FORMS_EDIT_HXX_\n\n<|endoftext|>"} {"text":"\/**\nCopyright (c) 2017, Philip Deegan.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and\/or other materials provided with the\ndistribution.\n * Neither the name of Philip Deegan nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n#include \"maiken.hpp\"\n\nvoid maiken::Application::link(const kul::hash::set::String& objects)\n KTHROW(kul::Exception) {\n showConfig();\n if (objects.size() > 0) {\n buildDir().mk();\n if (!main.empty())\n buildExecutable(objects);\n else\n buildLibrary(objects);\n if (CommandStateMachine::INSTANCE().commands().count(STR_TEST) &&\n !tests.empty())\n buildTest(objects);\n kul::os::PushDir pushd(this->project().dir());\n kul::Dir build(\".mkn\/build\");\n build.mk();\n kul::File ts(\"timestamp\", build);\n if (ts) ts.rm();\n {\n kul::io::Writer w(ts);\n w << kul::Now::MILLIS();\n }\n } else\n KEXIT(1, \"No link objects found, try compile or build.\");\n}\n\nvoid maiken::Application::checkErrors(const CompilerProcessCapture& cpc)\n KTHROW(kul::Exception) {\n auto o = [](const std::string& s) {\n if (s.size()) KOUT(NON) << s;\n };\n auto e = [](const std::string& s) {\n if (s.size()) KERR << s;\n };\n if (kul::LogMan::INSTANCE().inf() || cpc.exception()) o(cpc.outs());\n if (kul::LogMan::INSTANCE().err() || cpc.exception()) e(cpc.errs());\n if (cpc.exception()) std::rethrow_exception(cpc.exception());\n}\n\nbool maiken::Application::is_build_required() {\n kul::os::PushDir pushd(this->project().dir());\n kul::Dir bDir(\".mkn\/build\");\n return !bDir || bDir.dirs().size() == 0\n || bDir.files().size() == 0;;\n}\n\nbool maiken::Application::is_build_stale() {\n kul::os::PushDir pushd(this->project().dir());\n kul::Dir d(\".mkn\/build\");\n kul::File f(\"timestamp\", d);\n if (!d || !f) return true;\n kul::io::Reader r(f);\n try {\n size_t then = (size_t)43200 * ((size_t)60 * (size_t)1000);\n size_t now = kul::Now::MILLIS();\n size_t _MKN_BUILD_IS_STALE_MINUTES = now - then;\n const char* c = r.readLine();\n size_t timestamp = kul::String::UINT64(std::string(c));\n if (_MKN_BUILD_IS_STALE_MINUTES > timestamp) return true;\n } catch (const kul::Exception& e) {\n KERR << e.stack();\n } catch (const std::exception& e) {\n KERR << e.what();\n }\n return false;\n}\nto build or not to build (modules\/**\nCopyright (c) 2017, Philip Deegan.\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are\nmet:\n\n * Redistributions of source code must retain the above copyright\nnotice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above\ncopyright notice, this list of conditions and the following disclaimer\nin the documentation and\/or other materials provided with the\ndistribution.\n * Neither the name of Philip Deegan nor the names of its\ncontributors may be used to endorse or promote products derived from\nthis software without specific prior written permission.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\nA PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT\nOWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,\nSPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT\nLIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\nDATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\nTHEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n#include \"maiken.hpp\"\n\nvoid maiken::Application::link(const kul::hash::set::String& objects)\n KTHROW(kul::Exception) {\n showConfig();\n if (objects.size() > 0) {\n buildDir().mk();\n if (!main.empty())\n buildExecutable(objects);\n else\n buildLibrary(objects);\n if (CommandStateMachine::INSTANCE().commands().count(STR_TEST) &&\n !tests.empty())\n buildTest(objects);\n kul::os::PushDir pushd(this->project().dir());\n kul::Dir build(\".mkn\/build\");\n build.mk();\n kul::File ts(\"timestamp\", build);\n if (ts) ts.rm();\n {\n kul::io::Writer w(ts);\n w << kul::Now::MILLIS();\n }\n } else\n KEXIT(1, \"No link objects found, try compile or build.\");\n}\n\nvoid maiken::Application::checkErrors(const CompilerProcessCapture& cpc)\n KTHROW(kul::Exception) {\n auto o = [](const std::string& s) {\n if (s.size()) KOUT(NON) << s;\n };\n auto e = [](const std::string& s) {\n if (s.size()) KERR << s;\n };\n if (kul::LogMan::INSTANCE().inf() || cpc.exception()) o(cpc.outs());\n if (kul::LogMan::INSTANCE().err() || cpc.exception()) e(cpc.errs());\n if (cpc.exception()) std::rethrow_exception(cpc.exception());\n}\n\nbool maiken::Application::is_build_required() {\n kul::os::PushDir pushd(this->project().dir());\n kul::Dir bDir(\".mkn\/build\");\n return !bDir || bDir.files().size() == 0\n || buildDir().dirs().size() == 0\n || buildDir().files().size() == 0;\n}\n\nbool maiken::Application::is_build_stale() {\n kul::os::PushDir pushd(this->project().dir());\n kul::Dir d(\".mkn\/build\");\n kul::File f(\"timestamp\", d);\n if (!d || !f) return true;\n kul::io::Reader r(f);\n try {\n size_t then = (size_t)43200 * ((size_t)60 * (size_t)1000);\n size_t now = kul::Now::MILLIS();\n size_t _MKN_BUILD_IS_STALE_MINUTES = now - then;\n const char* c = r.readLine();\n size_t timestamp = kul::String::UINT64(std::string(c));\n if (_MKN_BUILD_IS_STALE_MINUTES > timestamp) return true;\n } catch (const kul::Exception& e) {\n KERR << e.stack();\n } catch (const std::exception& e) {\n KERR << e.what();\n }\n return false;\n}\n<|endoftext|>"} {"text":"\/**\n * @file DenseMatrix.cpp\n *\/\n\n\/\/ Copyright 2001 California Institute of Technology\n\n#ifdef WIN32\n#pragma warning(disable:4786)\n#pragma warning(disable:4503)\n#endif\n\n#include \"ct_defs.h\"\n#include \"ctlapack.h\"\n#include \"utilities.h\"\n#include \"DenseMatrix.h\"\n\nnamespace Cantera {\n\n \/\/\/ assignment.\n DenseMatrix& DenseMatrix::operator=(const DenseMatrix& y) {\n if (&y == this) return *this;\n Array2D::operator=(y);\n m_ipiv = y.ipiv();\n\t return *this;\n }\n\n void DenseMatrix::resize(int n, int m, doublereal v) {\n Array2D::resize(n,m,v);\n m_ipiv.resize( max(n,m) );\n }\n\n void DenseMatrix::mult(const double* b, double* prod) const {\n ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, nRows(), \n nRows(), 1.0, begin(), nRows(), b, 1, 0.0, prod, 1);\n }\n\n void DenseMatrix::leftMult(const double* b, double* prod) const {\n int nc = nColumns();\n int nr = nRows();\n int n, i;\n double sum = 0.0;\n for (n = 0; n < nc; n++) {\n sum = 0.0;\n for (i = 0; i < nr; i++) {\n sum += value(i,n)*b[i];\n }\n prod[n] = sum;\n }\n }\n\n \/**\n * Solve Ax = b. Array b is overwritten on exit with x.\n *\/\n int solve(DenseMatrix& A, double* b) {\n int info=0;\n ct_dgetrf(A.nRows(), A.nColumns(), A.begin(), A.nRows(), \n A.ipiv().begin(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRF returned INFO = \"+int2str(info));\n ct_dgetrs(ctlapack::NoTranspose, A.nRows(), 1, A.begin(), A.nRows(), \n A.ipiv().begin(), b, A.nColumns(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRS returned INFO = \"+int2str(info));\n return 0;\n }\n\n \/** Solve Ax = b for multiple right-hand-side vectors. *\/\n int solve(DenseMatrix& A, DenseMatrix& b) {\n int info=0;\n ct_dgetrf(A.nRows(), A.nColumns(), A.begin(), A.nRows(), \n A.ipiv().begin(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRF returned INFO = \"+int2str(info)); \n ct_dgetrs(ctlapack::NoTranspose, A.nRows(), b.nColumns(), \n A.begin(), A.nRows(), \n A.ipiv().begin(), b.begin(), b.nRows(), info);\n if (info != 0)\n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRS returned INFO = \"+int2str(info));\n return 0;\n }\n\n\n \/** @todo fix lwork *\/\n int leastSquares(DenseMatrix& A, double* b) {\n int info = 0;\n int rank = 0;\n double rcond = -1.0;\n \/\/ fix this!\n int lwork = 6000; \/\/ 2*(3*min(m,n) + max(2*min(m,n), max(m,n)));\n vector_fp work(lwork);\n vector_fp s(min(A.nRows(),A.nColumns()));\n ct_dgelss(A.nRows(), A.nColumns(), 1, A.begin(), \n A.nRows(), b, A.nColumns(), s.begin(),\n rcond, rank, work.begin(), work.size(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::leaseSquares\",\n \"DGELSS returned INFO = \"+int2str(info));\n return 0;\n }\n\n \/**\n * Multiply \\c A*b and return the result in \\c prod. Uses BLAS\n * routine DGEMV.\n *\/\n void multiply(const DenseMatrix& A, const double* b, double* prod) {\n ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, \n A.nRows(), A.nRows(), 1.0, \n A.begin(), A.nRows(), b, 1, 0.0, prod, 1);\n }\n\n void increment(const DenseMatrix& A, \n const double* b, double* prod) {\n ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, \n A.nRows(), A.nRows(), 1.0, \n A.begin(), A.nRows(), b, 1, 1.0, prod, 1);\n }\n\n\n \/**\n * invert A. A is overwritten with A^-1.\n *\/\n int invert(DenseMatrix& A, int nn) {\n integer n = (nn > 0 ? nn : A.nRows());\n integer info=0;\n ct_dgetrf(n, n, A.begin(), A.nRows(), A.ipiv().begin(), info);\n if (info != 0) \n throw CanteraError(\"invert\",\n \"DGETRF returned INFO=\"+int2str(info));\n\n vector_fp work(n);\n integer lwork = work.size(); \n ct_dgetri(n, A.begin(), A.nRows(), A.ipiv().begin(), \n work.begin(), lwork, info);\n if (info != 0) \n throw CanteraError(\"invert\",\n \"DGETRI returned INFO=\"+int2str(info));\n return 0;\n }\n}\n\nstatic_cast to eliminate VC++ warnings\/**\n * @file DenseMatrix.cpp\n *\/\n\n\/\/ Copyright 2001 California Institute of Technology\n\n#ifdef WIN32\n#pragma warning(disable:4786)\n#pragma warning(disable:4503)\n#endif\n\n#include \"ct_defs.h\"\n#include \"ctlapack.h\"\n#include \"utilities.h\"\n#include \"DenseMatrix.h\"\n\nnamespace Cantera {\n\n \/\/\/ assignment.\n DenseMatrix& DenseMatrix::operator=(const DenseMatrix& y) {\n if (&y == this) return *this;\n Array2D::operator=(y);\n m_ipiv = y.ipiv();\n\t return *this;\n }\n\n void DenseMatrix::resize(int n, int m, doublereal v) {\n Array2D::resize(n,m,v);\n m_ipiv.resize( max(n,m) );\n }\n\n void DenseMatrix::mult(const double* b, double* prod) const {\n ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, \n\t\t\t\tstatic_cast(nRows()), \n static_cast(nRows()), 1.0, begin(),\n\t\t\t\tstatic_cast(nRows()), b, 1, 0.0, prod, 1);\n }\n\n void DenseMatrix::leftMult(const double* b, double* prod) const {\n int nc = static_cast(nColumns());\n int nr = static_cast(nRows());\n int n, i;\n double sum = 0.0;\n for (n = 0; n < nc; n++) {\n sum = 0.0;\n for (i = 0; i < nr; i++) {\n sum += value(i,n)*b[i];\n }\n prod[n] = sum;\n }\n }\n\n \/**\n * Solve Ax = b. Array b is overwritten on exit with x.\n *\/\n int solve(DenseMatrix& A, double* b) {\n int info=0;\n ct_dgetrf(static_cast(A.nRows()), \n\t\t\tstatic_cast(A.nColumns()), A.begin(), \n\t\t\tstatic_cast(A.nRows()), A.ipiv().begin(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRF returned INFO = \"+int2str(info));\n ct_dgetrs(ctlapack::NoTranspose, \n\t\t\tstatic_cast(A.nRows()), 1, A.begin(), \n\t\t\tstatic_cast(A.nRows()), \n A.ipiv().begin(), b, \n\t\t\tstatic_cast(A.nColumns()), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRS returned INFO = \"+int2str(info));\n return 0;\n }\n\n \/** Solve Ax = b for multiple right-hand-side vectors. *\/\n int solve(DenseMatrix& A, DenseMatrix& b) {\n int info=0;\n ct_dgetrf(static_cast(A.nRows()), \n\t\t\tstatic_cast(A.nColumns()), A.begin(), \n\t\t\tstatic_cast(A.nRows()), A.ipiv().begin(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRF returned INFO = \"+int2str(info)); \n ct_dgetrs(ctlapack::NoTranspose, static_cast(A.nRows()),\n\t\t\tstatic_cast(b.nColumns()), \n A.begin(), static_cast(A.nRows()), \n A.ipiv().begin(), b.begin(), \n\t\t\tstatic_cast(b.nRows()), info);\n if (info != 0)\n throw CanteraError(\"DenseMatrix::solve\",\n \"DGETRS returned INFO = \"+int2str(info));\n return 0;\n }\n\n\n \/** @todo fix lwork *\/\n int leastSquares(DenseMatrix& A, double* b) {\n int info = 0;\n int rank = 0;\n double rcond = -1.0;\n \/\/ fix this!\n int lwork = 6000; \/\/ 2*(3*min(m,n) + max(2*min(m,n), max(m,n)));\n vector_fp work(lwork);\n vector_fp s(min(static_cast(A.nRows()),\n\t\t\t\t\t static_cast(A.nColumns())));\n ct_dgelss(static_cast(A.nRows()), \n\t\t\tstatic_cast(A.nColumns()), 1, A.begin(), \n static_cast(A.nRows()), b, \n\t\t\tstatic_cast(A.nColumns()), s.begin(),\n rcond, rank, work.begin(), work.size(), info);\n if (info != 0) \n throw CanteraError(\"DenseMatrix::leaseSquares\",\n \"DGELSS returned INFO = \"+int2str(info));\n return 0;\n }\n\n \/**\n * Multiply \\c A*b and return the result in \\c prod. Uses BLAS\n * routine DGEMV.\n *\/\n void multiply(const DenseMatrix& A, const double* b, double* prod) {\n ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, \n static_cast(A.nRows()), static_cast(A.nRows()), 1.0, \n A.begin(), static_cast(A.nRows()), b, 1, 0.0, prod, 1);\n }\n\n void increment(const DenseMatrix& A, \n const double* b, double* prod) {\n ct_dgemv(ctlapack::ColMajor, ctlapack::NoTranspose, \n static_cast(A.nRows()), static_cast(A.nRows()), 1.0, \n A.begin(), static_cast(A.nRows()), b, 1, 1.0, prod, 1);\n }\n\n\n \/**\n * invert A. A is overwritten with A^-1.\n *\/\n int invert(DenseMatrix& A, int nn) {\n integer n = (nn > 0 ? nn : static_cast(A.nRows()));\n integer info=0;\n ct_dgetrf(n, n, A.begin(), static_cast(A.nRows()), \n\t\t\tA.ipiv().begin(), info);\n if (info != 0) \n throw CanteraError(\"invert\",\n \"DGETRF returned INFO=\"+int2str(info));\n\n vector_fp work(n);\n integer lwork = static_cast(work.size()); \n ct_dgetri(n, A.begin(), static_cast(A.nRows()),\n\t\t\tA.ipiv().begin(), \n work.begin(), lwork, info);\n if (info != 0) \n throw CanteraError(\"invert\",\n \"DGETRI returned INFO=\"+int2str(info));\n return 0;\n }\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"runtime\/core\/arithmetic_impl.h\"\n#include \"errors\/error_factory.h\"\n#include \"system\/globalenv.h\"\n#include \"types\/root_typemanager.h\"\n#include \"types\/casting.h\"\n#include \"util\/Assert.h\"\n#include \"runtime\/numerics\/NumericsImpl.h\"\n#include \"runtime\/dateTime\/DurationsDatesTimes.h\"\n#include \"errors\/error_factory.h\"\n#include \"system\/zorba.h\"\n#include \"store\/api\/item_factory.h\"\n#include \"system\/zorba_engine.h\"\n#include \"context\/dynamic_context.h\"\n\nnamespace zorba {\n\nvoid ArithOperationsCommons::createError(\n const char* aOp, \n const QueryLoc* aLoc, \n TypeConstants::atomic_type_code_t aType0,\n TypeConstants::atomic_type_code_t aType1\n)\n{\n AtomicXQType lAType0(aType0, TypeConstants::QUANT_ONE);\n AtomicXQType lAType1(aType1, TypeConstants::QUANT_ONE);\n std::stringstream lStream;\n lStream << \"The operation '\";\n lStream << aOp;\n lStream << \"' is not possible with parameters of the type \";\n lAType0.serialize(lStream);\n lStream << \" and \";\n lAType1.serialize(lStream);\n lStream << \"!\";\n ZORBA_ERROR_ALERT(\n ZorbaError::XPTY0004,\n aLoc,\n DONT_CONTINUE_EXECUTION,\n lStream.str()\n );\n}\n\n\/* begin class GenericArithIterator *\/\ntemplate< class Operations>\nGenericArithIterator::GenericArithIterator\n( const QueryLoc& loc, PlanIter_t& iter0, PlanIter_t& iter1 )\n :\n BinaryBaseIterator, PlanIteratorState > ( loc, iter0, iter1 )\n{ }\n\ntemplate < class Operation >\nstore::Item_t GenericArithIterator::nextImpl ( PlanState& planState ) const\n{\n store::Item_t n0;\n store::Item_t n1;\n store::Item_t res;\n\n PlanIteratorState* state;\n DEFAULT_STACK_INIT ( PlanIteratorState, state, planState );\n n0 = consumeNext( this->theChild0.getp(), planState );\n if ( n0 != NULL )\n {\n n1 = consumeNext( this->theChild1.getp(), planState );\n if ( n1 != NULL )\n {\n res = compute(this->loc, n0, n1);\n \n if ( consumeNext(this->theChild0.getp(), planState ) != NULL\n || consumeNext(this->theChild1.getp(), planState ) != NULL )\n ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,\n NULL, DONT_CONTINUE_EXECUTION, \"Arithmetic operation has a sequences greater than one as an operator.\");\n STACK_PUSH ( res, state );\n }\n }\n STACK_END();\n}\n\ntemplate < class Operation >\nstore::Item_t GenericArithIterator::compute(const QueryLoc& aLoc, store::Item_t n0, store::Item_t n1)\n{\n n0 = n0->getAtomizationValue();\n n1 = n1->getAtomizationValue();\n\n xqtref_t type0 = GENV_TYPESYSTEM.create_type ( n0->getType(), TypeConstants::QUANT_ONE );\n xqtref_t type1 = GENV_TYPESYSTEM.create_type ( n1->getType(), TypeConstants::QUANT_ONE );\n\n if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DURATION_TYPE_ONE ) )\n {\n if(GENV_TYPESYSTEM.is_numeric(*type1))\n {\n if(GENV_TYPESYSTEM.is_equal( *type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE) ||\n GENV_TYPESYSTEM.is_equal( *type0, *GENV_TYPESYSTEM.DT_DURATION_TYPE_ONE))\n {\n n1 = GenericCast::instance()->cast ( n1, GENV_TYPESYSTEM.DOUBLE_TYPE_ONE );\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n }\n else \n return Operation::template computeSingleType ( &aLoc, n0, n1 );\n }\n else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))\n return Operation::template compute ( &aLoc, n0, n1 );\n else\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))\n return Operation::template compute ( &aLoc, n0, n1 );\n else\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))\n return Operation::template compute ( &aLoc, n0, n1 );\n else\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if (( GENV_TYPESYSTEM.is_numeric(*type0)\n || GENV_TYPESYSTEM.is_numeric(*type1)\n || GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE)\n || GENV_TYPESYSTEM.is_subtype(*type1, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE)))\n {\n return NumArithIterator::computeAtomic(aLoc, n0, type0, n1, type1);\n }\n else\n {\n ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,\n NULL, DONT_CONTINUE_EXECUTION, \"Arithmetic operation not defined between the given types(\" + type0->toString() + \" and \" + type1->toString() + \").\");\n }\n return 0;\n}\n\n\/**\n * Information: It is not possible to move this function to\n * runtime\/visitors\/accept.cpp!\n *\/\ntemplate < class Operation >\nvoid GenericArithIterator::accept(PlanIterVisitor& v) const { \n v.beginVisit(*this); \n this->theChild0->accept(v); \n this->theChild1->accept(v); \n v.endVisit(*this); \n}\n\n\/\/ FIXME Why can the following template specializations not be moved to src\/runtime\/dateTime\/DurationsDatesTimes.cpp?\n\/\/moved from DurationsDatesTimes\n \/* begin class AddOperations *\/\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d = *i0->getDurationValue() + *i1->getDurationValue();\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toDuration();\n return Zorba::getItemFactory()->createDateTime (d);\n}\n\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toDuration();\n return Zorba::getItemFactory()->createDate (d);\n}\n\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toDuration();\n return Zorba::getItemFactory()->createTime (t);\n}\n \/* end class AddOperations *\/\n\n\/* start class SubtractOperations *\/\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d = *i0->getDurationValue() - *i1->getDurationValue();\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toNegDuration();\n return Zorba::getItemFactory()->createDateTime (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toNegDuration();\n return Zorba::getItemFactory()->createDate (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toNegDuration();\n return Zorba::getItemFactory()->createTime (t);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n int timezone_secs = ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();\n xqp_duration d = *i0->getDateTimeValue()->normalizeTimeZone(timezone_secs) - \n *i1->getDateTimeValue()->normalizeTimeZone(timezone_secs);\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n long timezone_sec = \/*18000;*\/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();\n xqp_duration d = *i0->getDateValue()->normalize(timezone_sec) - *i1->getDateValue()->normalize(timezone_sec);\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n long timezone_sec = \/*-18000;*\/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();\n xqp_duration d = *i0->getTimeValue()->normalize(timezone_sec) - * i1->getTimeValue()->normalize(timezone_sec);\n return Zorba::getItemFactory()->createDuration (d);\n}\n\/* end class SubtractOperations *\/\n\n\/* start class MultiplyOperations *\/\ntemplate<>\nstore::Item_t MultiplyOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d;\n\n if( i1->getDoubleValue().isZero() )\n {\n xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);\n if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))\n d = new YearMonthDuration();\n else\n d = new DayTimeDuration();\n\n return Zorba::getItemFactory()->createDuration(d);\n }\n else if ( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )\n ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, \"Overflow\/underflow in duration operation.\");\n else if ( i1->getDoubleValue().isNaN() )\n ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, \"NaN supplied as float\/double value\");\n else\n d = *i0->getDurationValue() * (i1->getDoubleValue());\n \n return Zorba::getItemFactory()->createDuration (d);\n}\n\/* end class MultiplyOperations *\/\n\n\/* start class DivideOperations *\/\ntemplate<>\nstore::Item_t DivideOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d;\n\n if( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )\n {\n xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);\n if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))\n d = new YearMonthDuration();\n else\n d = new DayTimeDuration();\n \n return Zorba::getItemFactory()->createDuration(d);\n }\n else if ( i1->getDoubleValue().isZero() )\n ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, \"Overflow\/underflow in duration operation.\");\n else if ( i1->getDoubleValue().isNaN() )\n ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, \"NaN supplied as float\/double value\");\n else\n d= *i0->getDurationValue() \/ i1->getDoubleValue();\n\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t DivideOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_decimal d = *i0->getDurationValue() \/ *i1->getDurationValue();\n return Zorba::getItemFactory()->createDecimal(d);\n}\n\/* end class DivideOperations *\/\n\n\/* instantiate GenericArithIterator for all types *\/\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\n\/* end class GenericArithIterator *\/\n\n\n}\nSoved trac #278.#include \n#include \n\n#include \"runtime\/core\/arithmetic_impl.h\"\n#include \"errors\/error_factory.h\"\n#include \"system\/globalenv.h\"\n#include \"types\/root_typemanager.h\"\n#include \"types\/casting.h\"\n#include \"util\/Assert.h\"\n#include \"runtime\/numerics\/NumericsImpl.h\"\n#include \"runtime\/dateTime\/DurationsDatesTimes.h\"\n#include \"errors\/error_factory.h\"\n#include \"system\/zorba.h\"\n#include \"store\/api\/item_factory.h\"\n#include \"system\/zorba_engine.h\"\n#include \"context\/dynamic_context.h\"\n\nnamespace zorba {\n\nvoid ArithOperationsCommons::createError(\n const char* aOp, \n const QueryLoc* aLoc, \n TypeConstants::atomic_type_code_t aType0,\n TypeConstants::atomic_type_code_t aType1\n)\n{\n AtomicXQType lAType0(aType0, TypeConstants::QUANT_ONE);\n AtomicXQType lAType1(aType1, TypeConstants::QUANT_ONE);\n std::stringstream lStream;\n lStream << \"The operation '\";\n lStream << aOp;\n lStream << \"' is not possible with parameters of the type \";\n lAType0.serialize(lStream);\n lStream << \" and \";\n lAType1.serialize(lStream);\n lStream << \"!\";\n ZORBA_ERROR_ALERT(\n ZorbaError::XPTY0004,\n aLoc,\n DONT_CONTINUE_EXECUTION,\n lStream.str()\n );\n}\n\n\/* begin class GenericArithIterator *\/\ntemplate< class Operations>\nGenericArithIterator::GenericArithIterator\n( const QueryLoc& loc, PlanIter_t& iter0, PlanIter_t& iter1 )\n :\n BinaryBaseIterator, PlanIteratorState > ( loc, iter0, iter1 )\n{ }\n\ntemplate < class Operation >\nstore::Item_t GenericArithIterator::nextImpl ( PlanState& planState ) const\n{\n store::Item_t n0;\n store::Item_t n1;\n store::Item_t res;\n\n PlanIteratorState* state;\n DEFAULT_STACK_INIT ( PlanIteratorState, state, planState );\n n0 = consumeNext( this->theChild0.getp(), planState );\n if ( n0 != NULL )\n {\n n1 = consumeNext( this->theChild1.getp(), planState );\n if ( n1 != NULL )\n {\n res = compute(this->loc, n0, n1);\n \n if ( consumeNext(this->theChild0.getp(), planState ) != NULL\n || consumeNext(this->theChild1.getp(), planState ) != NULL )\n ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,\n NULL, DONT_CONTINUE_EXECUTION, \"Arithmetic operation has a sequences greater than one as an operator.\");\n STACK_PUSH ( res, state );\n }\n }\n STACK_END();\n}\n\ntemplate < class Operation >\nstore::Item_t GenericArithIterator::compute(const QueryLoc& aLoc, store::Item_t n0, store::Item_t n1)\n{\n n0 = n0->getAtomizationValue();\n n1 = n1->getAtomizationValue();\n\n xqtref_t type0 = GENV_TYPESYSTEM.create_type ( n0->getType(), TypeConstants::QUANT_ONE );\n xqtref_t type1 = GENV_TYPESYSTEM.create_type ( n1->getType(), TypeConstants::QUANT_ONE );\n\n if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE )\n || GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DT_DURATION_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_numeric(*type1))\n {\n n1 = GenericCast::instance()->cast ( n1, GENV_TYPESYSTEM.DOUBLE_TYPE_ONE );\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if(GENV_TYPESYSTEM.is_equal(*type0, *type1))\n return Operation::template computeSingleType ( &aLoc, n0, n1 );\n else\n ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,\n NULL, DONT_CONTINUE_EXECUTION, \"Arithmetic operation not defined between the given types(\" + type0->toString() + \" and \" + type1->toString() + \").\");\n }\n else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATETIME_TYPE_ONE ))\n return Operation::template compute ( &aLoc, n0, n1 );\n else\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.DATE_TYPE_ONE ))\n return Operation::template compute ( &aLoc, n0, n1 );\n else\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if(GENV_TYPESYSTEM.is_subtype ( *type0, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))\n {\n if(GENV_TYPESYSTEM.is_subtype ( *type1, *GENV_TYPESYSTEM.TIME_TYPE_ONE ))\n return Operation::template compute ( &aLoc, n0, n1 );\n else\n return Operation::template compute ( &aLoc, n0, n1 );\n }\n else if (\n (GENV_TYPESYSTEM.is_numeric(*type0)\n || GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE))\n && ( GENV_TYPESYSTEM.is_numeric(*type1)\n || GENV_TYPESYSTEM.is_subtype(*type1, *GENV_TYPESYSTEM.UNTYPED_ATOMIC_TYPE_ONE))\n )\n {\n return NumArithIterator::computeAtomic(aLoc, n0, type0, n1, type1);\n }\n else\n {\n ZORBA_ERROR_ALERT(ZorbaError::XPTY0004,\n NULL, DONT_CONTINUE_EXECUTION, \"Arithmetic operation not defined between the given types(\" + type0->toString() + \" and \" + type1->toString() + \").\");\n }\n return 0;\n}\n\n\/**\n * Information: It is not possible to move this function to\n * runtime\/visitors\/accept.cpp!\n *\/\ntemplate < class Operation >\nvoid GenericArithIterator::accept(PlanIterVisitor& v) const { \n v.beginVisit(*this); \n this->theChild0->accept(v); \n this->theChild1->accept(v); \n v.endVisit(*this); \n}\n\n\/\/ FIXME Why can the following template specializations not be moved to src\/runtime\/dateTime\/DurationsDatesTimes.cpp?\n\/\/moved from DurationsDatesTimes\n \/* begin class AddOperations *\/\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d = *i0->getDurationValue() + *i1->getDurationValue();\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toDuration();\n return Zorba::getItemFactory()->createDateTime (d);\n}\n\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toDuration();\n return Zorba::getItemFactory()->createDate (d);\n}\n\ntemplate<>\nstore::Item_t AddOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toDuration();\n return Zorba::getItemFactory()->createTime (t);\n}\n \/* end class AddOperations *\/\n\n\/* start class SubtractOperations *\/\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d = *i0->getDurationValue() - *i1->getDurationValue();\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_dateTime d = *i0->getDateTimeValue() + *i1->getDurationValue()->toNegDuration();\n return Zorba::getItemFactory()->createDateTime (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_date d = *i0->getDateValue() + *i1->getDurationValue()->toNegDuration();\n return Zorba::getItemFactory()->createDate (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_time t = *i0->getTimeValue() + *i1->getDurationValue()->toNegDuration();\n return Zorba::getItemFactory()->createTime (t);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n int timezone_secs = ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();\n xqp_duration d = *i0->getDateTimeValue()->normalizeTimeZone(timezone_secs) - \n *i1->getDateTimeValue()->normalizeTimeZone(timezone_secs);\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n long timezone_sec = \/*18000;*\/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();\n xqp_duration d = *i0->getDateValue()->normalize(timezone_sec) - *i1->getDateValue()->normalize(timezone_sec);\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t SubtractOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n long timezone_sec = \/*-18000;*\/ ZORBA_FOR_CURRENT_THREAD()->get_base_dynamic_context()->get_implicit_timezone();\n xqp_duration d = *i0->getTimeValue()->normalize(timezone_sec) - * i1->getTimeValue()->normalize(timezone_sec);\n return Zorba::getItemFactory()->createDuration (d);\n}\n\/* end class SubtractOperations *\/\n\n\/* start class MultiplyOperations *\/\ntemplate<>\nstore::Item_t MultiplyOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d;\n\n if( i1->getDoubleValue().isZero() )\n {\n xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);\n if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))\n d = new YearMonthDuration();\n else\n d = new DayTimeDuration();\n\n return Zorba::getItemFactory()->createDuration(d);\n }\n else if ( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )\n ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, \"Overflow\/underflow in duration operation.\");\n else if ( i1->getDoubleValue().isNaN() )\n ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, \"NaN supplied as float\/double value\");\n else\n d = *i0->getDurationValue() * (i1->getDoubleValue());\n \n return Zorba::getItemFactory()->createDuration (d);\n}\n\/* end class MultiplyOperations *\/\n\n\/* start class DivideOperations *\/\ntemplate<>\nstore::Item_t DivideOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_duration d;\n\n if( i1->getDoubleValue().isPosInf() || i1->getDoubleValue().isNegInf() )\n {\n xqtref_t type0 = GENV_TYPESYSTEM.create_type(i0->getType(), TypeConstants::QUANT_ONE);\n if( GENV_TYPESYSTEM.is_subtype(*type0, *GENV_TYPESYSTEM.YM_DURATION_TYPE_ONE))\n d = new YearMonthDuration();\n else\n d = new DayTimeDuration();\n \n return Zorba::getItemFactory()->createDuration(d);\n }\n else if ( i1->getDoubleValue().isZero() )\n ZORBA_ERROR_ALERT( ZorbaError::FODT0002, NULL, DONT_CONTINUE_EXECUTION, \"Overflow\/underflow in duration operation.\");\n else if ( i1->getDoubleValue().isNaN() )\n ZORBA_ERROR_ALERT( ZorbaError::FOCA0005, NULL, DONT_CONTINUE_EXECUTION, \"NaN supplied as float\/double value\");\n else\n d= *i0->getDurationValue() \/ i1->getDoubleValue();\n\n return Zorba::getItemFactory()->createDuration (d);\n}\n\ntemplate<>\nstore::Item_t DivideOperation::compute\n( const QueryLoc* loc, const store::Item* i0, const store::Item* i1 )\n{\n xqp_decimal d = *i0->getDurationValue() \/ *i1->getDurationValue();\n return Zorba::getItemFactory()->createDecimal(d);\n}\n\/* end class DivideOperations *\/\n\n\/* instantiate GenericArithIterator for all types *\/\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\ntemplate class GenericArithIterator;\n\/* end class GenericArithIterator *\/\n\n\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \n#include \n\n#include \"zorbaerrors\/error_manager.h\"\n\n#include \"runtime\/core\/var_iterators.h\"\n#include \"runtime\/core\/fncall_iterator.h\"\n#include \"runtime\/misc\/MiscImpl.h\" \/\/ for ExitException\n#include \"runtime\/api\/plan_iterator_wrapper.h\"\n#include \"functions\/function.h\"\n\n#include \"api\/unmarshaller.h\"\n\nnamespace zorba {\n\nUDFunctionCallIteratorState::UDFunctionCallIteratorState()\n :\n theFnBodyStateBlock(NULL),\n thePlan(NULL),\n thePlanStateSize(0),\n thePlanOpen(false) \n{ \n}\n\n\nUDFunctionCallIteratorState::~UDFunctionCallIteratorState()\n{\n}\n\n\nvoid UDFunctionCallIteratorState::openPlan()\n{\n uint32_t planOffset = 0;\n if (!thePlanOpen) {\n thePlan->open(*theFnBodyStateBlock, planOffset);\n }\n thePlanOpen = true;\n}\n\n\nvoid UDFunctionCallIteratorState::closePlan()\n{\n if (thePlanOpen) {\n thePlan->close(*theFnBodyStateBlock);\n }\n thePlanOpen = false;\n}\n\n\nvoid UDFunctionCallIteratorState::resetPlan()\n{\n if (thePlanOpen) {\n thePlan->reset(*theFnBodyStateBlock);\n }\n}\n\nvoid UDFunctionCallIteratorState::resetChildIters()\n{\n std::vector::const_iterator lIter = theChildIterators.begin();\n std::vector::const_iterator lEnd = theChildIterators.end();\n for ( ; lIter != lEnd; ++lIter)\n (*lIter)->close();\n\n theChildIterators.clear();\n}\n\n\nbool UDFunctionCallIterator::isUpdating() const \n{ \n return theUDF->isUpdating(); \n}\n\n\nvoid UDFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)\n{\n NaryBaseIterator::openImpl(planState, offset);\n\n UDFunctionCallIteratorState *state = StateTraitsImpl::getState(planState, this->stateOffset);\n\n state->thePlan = theUDF->get_plan(planState.theCompilerCB).getp();\n state->thePlanStateSize = state->thePlan->getStateSizeOfSubtree();\n state->theFnBodyStateBlock = new PlanState(state->thePlanStateSize, planState.theStackDepth + 1);\n state->theFnBodyStateBlock->checkDepth (loc);\n state->theFnBodyStateBlock->theRuntimeCB = planState.theRuntimeCB;\n state->theFnBodyStateBlock->theCompilerCB = planState.theCompilerCB;\n}\n\n\nvoid UDFunctionCallIterator::closeImpl(PlanState& planState)\n{\n UDFunctionCallIteratorState *state = StateTraitsImpl::getState(planState, this->stateOffset);\n\n state->closePlan();\n delete state->theFnBodyStateBlock;\n state->resetChildIters();\n\n NaryBaseIterator::closeImpl(planState);\n}\n\n\nvoid UDFunctionCallIterator::resetImpl(PlanState& planState) const\n{\n NaryBaseIterator::resetImpl(planState);\n UDFunctionCallIteratorState *state = StateTraitsImpl::getState(planState, this->stateOffset);\n\n state->resetPlan();\n state->resetChildIters();\n}\n\nbool UDFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n UDFunctionCallIteratorState *state;\n bool success;\n\n DEFAULT_STACK_INIT(UDFunctionCallIteratorState, state, planState);\n\n {\n \/\/ Bind the args.\n state->openPlan();\n std::vector& iters = theUDF->get_param_iters();\n for (uint32_t i = 0; i < iters.size (); ++i) \n {\n LetVarIter_t& ref = iters[i];\n if ( ref != NULL) \n {\n state->theChildIterators.push_back(new PlanIteratorWrapper(theChildren[i], planState));\n state->theChildIterators.back()->open();\n ref->bind(state->theChildIterators.back(), *state->theFnBodyStateBlock);\n }\n }\n }\n\n for (;;) {\n try {\n success = consumeNext (result, state->thePlan, *state->theFnBodyStateBlock);\n } catch (FlowCtlIterator::ExitException &e) {\n state->exitValue = e.val;\n success = false;\n }\n \n if (success)\n STACK_PUSH(true, state);\n else break;\n }\n\n if (state->exitValue != NULL)\n while (state->exitValue->next (result))\n STACK_PUSH(true, state);\n\n STACK_END (state);\n}\n\n\n\/\/ external functions\nclass ExtFuncArgItemSequence : public ItemSequence \n{\n public:\n ExtFuncArgItemSequence(PlanIter_t child, PlanState& stateBlock)\n : m_child(child),\n m_stateBlock(stateBlock) { }\n\n bool next(Item& item) \n {\n store::Item_t result;\n bool status = m_child->consumeNext(result, m_child.getp(), m_stateBlock);\n item = status ? result : NULL;\n return status;\n }\n\n private:\n PlanIter_t m_child;\n PlanState& m_stateBlock;\n};\n\n\nStatelessExtFunctionCallIteratorState::StatelessExtFunctionCallIteratorState() { }\n\n\nStatelessExtFunctionCallIteratorState::~StatelessExtFunctionCallIteratorState() { }\n\n\nvoid StatelessExtFunctionCallIteratorState::reset(PlanState& planState)\n{\n PlanIteratorState::reset(planState);\n m_result.reset();\n}\n\n\nStatelessExtFunctionCallIterator::StatelessExtFunctionCallIterator(const QueryLoc& loc,\n std::vector& args,\n const StatelessExternalFunction *function,\n bool aIsUpdating)\n :\n NaryBaseIterator(loc, args),\n m_function(function),\n theIsUpdating(aIsUpdating) \n{ \n}\n\n\nvoid StatelessExtFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)\n{\n NaryBaseIterator::openImpl(planState, offset);\n\n StatelessExtFunctionCallIteratorState \n *state = StateTraitsImpl::getState(planState, \n this->stateOffset);\n int n = theChildren.size();\n state->m_extArgs.resize(n);\n for(int i = 0; i < n; ++i) \n {\n state->m_extArgs[i] = new ExtFuncArgItemSequence(theChildren[i], planState);\n }\n}\n\n\nbool StatelessExtFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n StatelessExtFunctionCallIteratorState *state;\n Item lOutsideItem;\n DEFAULT_STACK_INIT(StatelessExtFunctionCallIteratorState, state, planState);\n\n state->m_result = m_function->evaluate(state->m_extArgs);\n while (state->m_result->next(lOutsideItem)) \n {\n result = Unmarshaller::getInternalItem(lOutsideItem);\n if (theIsUpdating)\n {\n if (!result->isPul())\n {\n ZORBA_ERROR_LOC(XUDY0019, loc);\n }\n }\n else \n {\n if (result->isPul())\n {\n ZORBA_ERROR_LOC(XUDY0018, loc); \n }\n }\n STACK_PUSH(true, state);\n }\n\n STACK_END (state);\n}\n\n\nvoid StatelessExtFunctionCallIterator::closeImpl(PlanState& planState)\n{\n StatelessExtFunctionCallIteratorState *state = \n StateTraitsImpl::getState(planState, this->stateOffset);\n\n \/\/ we have the ownership for the item sequences\n int n = theChildren.size();\n for(int i = 0; i < n; ++i) {\n delete state->m_extArgs[i];\n }\n\n NaryBaseIterator::closeImpl(planState);\n}\n\n\n}\n\n\/* vim:set ts=2 sw=2: *\/\nAdded error reporting ability to external functions\/*\n * Copyright 2006-2008 The FLWOR Foundation.\n * \n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n * \n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n * \n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n#include \n#include \n#include \n#include \n\n#include \"zorbaerrors\/error_manager.h\"\n\n#include \"runtime\/core\/var_iterators.h\"\n#include \"runtime\/core\/fncall_iterator.h\"\n#include \"runtime\/misc\/MiscImpl.h\" \/\/ for ExitException\n#include \"runtime\/api\/plan_iterator_wrapper.h\"\n#include \"functions\/function.h\"\n\n#include \"api\/unmarshaller.h\"\n\nnamespace zorba {\n\nUDFunctionCallIteratorState::UDFunctionCallIteratorState()\n :\n theFnBodyStateBlock(NULL),\n thePlan(NULL),\n thePlanStateSize(0),\n thePlanOpen(false) \n{ \n}\n\n\nUDFunctionCallIteratorState::~UDFunctionCallIteratorState()\n{\n}\n\n\nvoid UDFunctionCallIteratorState::openPlan()\n{\n uint32_t planOffset = 0;\n if (!thePlanOpen) {\n thePlan->open(*theFnBodyStateBlock, planOffset);\n }\n thePlanOpen = true;\n}\n\n\nvoid UDFunctionCallIteratorState::closePlan()\n{\n if (thePlanOpen) {\n thePlan->close(*theFnBodyStateBlock);\n }\n thePlanOpen = false;\n}\n\n\nvoid UDFunctionCallIteratorState::resetPlan()\n{\n if (thePlanOpen) {\n thePlan->reset(*theFnBodyStateBlock);\n }\n}\n\nvoid UDFunctionCallIteratorState::resetChildIters()\n{\n std::vector::const_iterator lIter = theChildIterators.begin();\n std::vector::const_iterator lEnd = theChildIterators.end();\n for ( ; lIter != lEnd; ++lIter)\n (*lIter)->close();\n\n theChildIterators.clear();\n}\n\n\nbool UDFunctionCallIterator::isUpdating() const \n{ \n return theUDF->isUpdating(); \n}\n\n\nvoid UDFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)\n{\n NaryBaseIterator::openImpl(planState, offset);\n\n UDFunctionCallIteratorState *state = StateTraitsImpl::getState(planState, this->stateOffset);\n\n state->thePlan = theUDF->get_plan(planState.theCompilerCB).getp();\n state->thePlanStateSize = state->thePlan->getStateSizeOfSubtree();\n state->theFnBodyStateBlock = new PlanState(state->thePlanStateSize, planState.theStackDepth + 1);\n state->theFnBodyStateBlock->checkDepth (loc);\n state->theFnBodyStateBlock->theRuntimeCB = planState.theRuntimeCB;\n state->theFnBodyStateBlock->theCompilerCB = planState.theCompilerCB;\n}\n\n\nvoid UDFunctionCallIterator::closeImpl(PlanState& planState)\n{\n UDFunctionCallIteratorState *state = StateTraitsImpl::getState(planState, this->stateOffset);\n\n state->closePlan();\n delete state->theFnBodyStateBlock;\n state->resetChildIters();\n\n NaryBaseIterator::closeImpl(planState);\n}\n\n\nvoid UDFunctionCallIterator::resetImpl(PlanState& planState) const\n{\n NaryBaseIterator::resetImpl(planState);\n UDFunctionCallIteratorState *state = StateTraitsImpl::getState(planState, this->stateOffset);\n\n state->resetPlan();\n state->resetChildIters();\n}\n\nbool UDFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n UDFunctionCallIteratorState *state;\n bool success;\n\n DEFAULT_STACK_INIT(UDFunctionCallIteratorState, state, planState);\n\n {\n \/\/ Bind the args.\n state->openPlan();\n std::vector& iters = theUDF->get_param_iters();\n for (uint32_t i = 0; i < iters.size (); ++i) \n {\n LetVarIter_t& ref = iters[i];\n if ( ref != NULL) \n {\n state->theChildIterators.push_back(new PlanIteratorWrapper(theChildren[i], planState));\n state->theChildIterators.back()->open();\n ref->bind(state->theChildIterators.back(), *state->theFnBodyStateBlock);\n }\n }\n }\n\n for (;;) {\n try {\n success = consumeNext (result, state->thePlan, *state->theFnBodyStateBlock);\n } catch (FlowCtlIterator::ExitException &e) {\n state->exitValue = e.val;\n success = false;\n }\n \n if (success)\n STACK_PUSH(true, state);\n else break;\n }\n\n if (state->exitValue != NULL)\n while (state->exitValue->next (result))\n STACK_PUSH(true, state);\n\n STACK_END (state);\n}\n\n\n\/\/ external functions\nclass ExtFuncArgItemSequence : public ItemSequence \n{\n public:\n ExtFuncArgItemSequence(PlanIter_t child, PlanState& stateBlock)\n : m_child(child),\n m_stateBlock(stateBlock) { }\n\n bool next(Item& item) \n {\n store::Item_t result;\n bool status = m_child->consumeNext(result, m_child.getp(), m_stateBlock);\n item = status ? result : NULL;\n return status;\n }\n\n private:\n PlanIter_t m_child;\n PlanState& m_stateBlock;\n};\n\n\nStatelessExtFunctionCallIteratorState::StatelessExtFunctionCallIteratorState() { }\n\n\nStatelessExtFunctionCallIteratorState::~StatelessExtFunctionCallIteratorState() { }\n\n\nvoid StatelessExtFunctionCallIteratorState::reset(PlanState& planState)\n{\n PlanIteratorState::reset(planState);\n m_result.reset();\n}\n\n\nStatelessExtFunctionCallIterator::StatelessExtFunctionCallIterator(const QueryLoc& loc,\n std::vector& args,\n const StatelessExternalFunction *function,\n bool aIsUpdating)\n :\n NaryBaseIterator(loc, args),\n m_function(function),\n theIsUpdating(aIsUpdating) \n{ \n}\n\n\nvoid StatelessExtFunctionCallIterator::openImpl(PlanState& planState, uint32_t& offset)\n{\n NaryBaseIterator::openImpl(planState, offset);\n\n StatelessExtFunctionCallIteratorState \n *state = StateTraitsImpl::getState(planState, \n this->stateOffset);\n int n = theChildren.size();\n state->m_extArgs.resize(n);\n for(int i = 0; i < n; ++i) \n {\n state->m_extArgs[i] = new ExtFuncArgItemSequence(theChildren[i], planState);\n }\n}\n\n\nbool StatelessExtFunctionCallIterator::nextImpl(store::Item_t& result, PlanState& planState) const\n{\n StatelessExtFunctionCallIteratorState *state;\n Item lOutsideItem;\n DEFAULT_STACK_INIT(StatelessExtFunctionCallIteratorState, state, planState);\n\n try {\n state->m_result = m_function->evaluate(state->m_extArgs);\n } catch(const ZorbaException& e) {\n ZORBA_ERROR_LOC(e.getErrorCode(), loc);\n }\n while (true)\n {\n try {\n if (!state->m_result->next(lOutsideItem)) {\n break;\n }\n } catch(const ZorbaException& e) {\n ZORBA_ERROR_LOC(e.getErrorCode(), loc);\n }\n result = Unmarshaller::getInternalItem(lOutsideItem);\n if (theIsUpdating)\n {\n if (!result->isPul())\n {\n ZORBA_ERROR_LOC(XUDY0019, loc);\n }\n }\n else \n {\n if (result->isPul())\n {\n ZORBA_ERROR_LOC(XUDY0018, loc); \n }\n }\n STACK_PUSH(true, state);\n }\n\n STACK_END (state);\n}\n\n\nvoid StatelessExtFunctionCallIterator::closeImpl(PlanState& planState)\n{\n StatelessExtFunctionCallIteratorState *state = \n StateTraitsImpl::getState(planState, this->stateOffset);\n\n \/\/ we have the ownership for the item sequences\n int n = theChildren.size();\n for(int i = 0; i < n; ++i) {\n delete state->m_extArgs[i];\n }\n\n NaryBaseIterator::closeImpl(planState);\n}\n\n\n}\n\n\/* vim:set ts=2 sw=2: *\/\n<|endoftext|>"} {"text":"\/********************************************************************\n * AUTHORS: Vijay Ganesh\n *\n * BEGIN DATE: November, 2005\n *\n * LICENSE: Please view LICENSE file in the home dir of this Program\n ********************************************************************\/\n\/\/ -*- c++ -*-\n\n#include \"..\/AST\/AST.h\"\nnamespace BEEV\n{\n \/\/some global variables that are set through commandline options. it\n \/\/is best that these variables remain global. Default values set\n \/\/here\n \/\/\n \/\/collect statistics on certain functions\n bool stats_flag = false;\n \/\/print DAG nodes\n bool print_nodes_flag = false;\n \/\/run STP in optimized mode\n bool optimize_flag = true;\n \/\/do sat refinement, i.e. underconstraint the problem, and feed to\n \/\/SAT. if this works, great. else, add a set of suitable constraints\n \/\/to re-constraint the problem correctly, and call SAT again, until\n \/\/all constraints have been added.\n bool arrayread_refinement_flag = true;\n \/\/flag to control write refinement\n bool arraywrite_refinement_flag = true;\n \/\/check the counterexample against the original input to STP\n bool check_counterexample_flag = false;\n \/\/construct the counterexample in terms of original variable based\n \/\/on the counterexample returned by SAT solver\n bool construct_counterexample_flag = true;\n bool print_counterexample_flag = false;\n bool print_binary_flag = false;\n \/\/if this option is true then print the way dawson wants using a\n \/\/different printer. do not use this printer.\n bool print_arrayval_declaredorder_flag = false;\n \/\/flag to decide whether to print \"valid\/invalid\" or not\n bool print_output_flag = false;\n \/\/print the variable order chosen by the sat solver while it is\n \/\/solving.\n bool print_sat_varorder_flag = false;\n \/\/turn on word level bitvector solver\n bool wordlevel_solve_flag = true;\n \/\/turn off XOR flattening\n bool xor_flatten_flag = false;\n \/\/Flag to switch on the smtlib parser\n bool smtlib_parser_flag = false;\n \/\/print the input back\n bool print_STPinput_back_flag = false;\n\n \/\/ If enabled. division, mod and remainder by zero will evaluate to\n \/\/ 1.\n bool division_by_zero_returns_one = false;\n\n enum inputStatus input_status = NOT_DECLARED;\n\n\n \/\/global BEEVMGR for the parser\n BeevMgr * GlobalBeevMgr;\n\n void (*vc_error_hdlr)(const char* err_msg) = NULL;\n \/** This is reusable empty vector, for representing empty children\n arrays *\/\n ASTVec _empty_ASTVec;\n\n \/\/Some global vars for the Main function.\n const std::string version = \"$Id: main.cpp 174 2009-09-03 19:22:47Z vijay_ganesh $\";\n const char * prog = \"stp\";\n int linenum = 1;\n const char * usage = \"Usage: %s [-option] [infile]\\n\";\n std::string helpstring = \"\\n\\n\"; \n}; \/\/end of namespace BEEV\nAdding SVN property to replace $Id$ with the version number\/********************************************************************\n * AUTHORS: Vijay Ganesh\n *\n * BEGIN DATE: November, 2005\n *\n * LICENSE: Please view LICENSE file in the home dir of this Program\n ********************************************************************\/\n\/\/ -*- c++ -*-\n\n#include \"..\/AST\/AST.h\"\nnamespace BEEV\n{\n \/\/some global variables that are set through commandline options. it\n \/\/is best that these variables remain global. Default values set\n \/\/here\n \/\/\n \/\/collect statistics on certain functions\n bool stats_flag = false;\n \/\/print DAG nodes\n bool print_nodes_flag = false;\n \/\/run STP in optimized mode\n bool optimize_flag = true;\n \/\/do sat refinement, i.e. underconstraint the problem, and feed to\n \/\/SAT. if this works, great. else, add a set of suitable constraints\n \/\/to re-constraint the problem correctly, and call SAT again, until\n \/\/all constraints have been added.\n bool arrayread_refinement_flag = true;\n \/\/flag to control write refinement\n bool arraywrite_refinement_flag = true;\n \/\/check the counterexample against the original input to STP\n bool check_counterexample_flag = false;\n \/\/construct the counterexample in terms of original variable based\n \/\/on the counterexample returned by SAT solver\n bool construct_counterexample_flag = true;\n bool print_counterexample_flag = false;\n bool print_binary_flag = false;\n \/\/if this option is true then print the way dawson wants using a\n \/\/different printer. do not use this printer.\n bool print_arrayval_declaredorder_flag = false;\n \/\/flag to decide whether to print \"valid\/invalid\" or not\n bool print_output_flag = false;\n \/\/print the variable order chosen by the sat solver while it is\n \/\/solving.\n bool print_sat_varorder_flag = false;\n \/\/turn on word level bitvector solver\n bool wordlevel_solve_flag = true;\n \/\/turn off XOR flattening\n bool xor_flatten_flag = false;\n \/\/Flag to switch on the smtlib parser\n bool smtlib_parser_flag = false;\n \/\/print the input back\n bool print_STPinput_back_flag = false;\n\n \/\/ If enabled. division, mod and remainder by zero will evaluate to\n \/\/ 1.\n bool division_by_zero_returns_one = false;\n\n enum inputStatus input_status = NOT_DECLARED;\n\n\n \/\/global BEEVMGR for the parser\n BeevMgr * GlobalBeevMgr;\n\n void (*vc_error_hdlr)(const char* err_msg) = NULL;\n \/** This is reusable empty vector, for representing empty children\n arrays *\/\n ASTVec _empty_ASTVec;\n\n \/\/Some global vars for the Main function.\n const std::string version = \"$Id$\";\n const char * prog = \"stp\";\n int linenum = 1;\n const char * usage = \"Usage: %s [-option] [infile]\\n\";\n std::string helpstring = \"\\n\\n\"; \n}; \/\/end of namespace BEEV\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ stochasticPerfectHash\n\/\/ Uses stochastic remainder sampling to derive a Pearson mixing table for small sets of alphabetic keys\n\/\/ orthopteroid@gmail.com\n\/\/ g++ -std=c++0x -O3 -lrt sph.cpp -o sph\n\/\/\n\/\/ for background, read:\n\/\/ http:\/\/cs.mwsu.edu\/~griffin\/courses\/2133\/downloads\/Spring11\/p677-pearson.pdf\n\n\/\/ stochastic remainder sampler\nsize_t sample( uint8_t* counts, uint32_t sum )\n{\n\tint32_t target = rand() % sum;\n\tsize_t i = 0;\n\twhile( (target -= counts[ i ]) > 0 ) { i++; }\n\treturn i;\n}\n\n\/\/ calculates a mixtable for the pearson hash to create a perfect hash.\n\/\/ restrictions are keys can only be ascii lowercase, but can be of any length.\n\/\/ keys are seperated in the input string using the ! delimiter. ! must also be at end of string.\nsize_t calcMixTable( char* sz )\n{\n\tconst size_t MAXITER = 25000;\n\n\t\/\/ special marker '!' in the string designates the end of a key\n\tsize_t keyCount = 0;\n\tfor( size_t i=0;sz[i];i++ ) { if( sz[i] == '!' ) { keyCount++; } }\n\tbool hashed[ keyCount ];\n\n\t\/\/ the defualt mix table is a null transform\n\tuint8_t mix[32] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};\n\n\t\/\/ these weights influence convergence rate.\n\t\/\/ they are used by the stochastic sampling method that adjusts the mixing table to resolve hash collisions\n\tconst uint8_t DEFAULT = 1;\n\tconst uint8_t SIGNAL = 100;\n\t\n\t\/\/ reset flags...\n\tsize_t iterations = 0;\n\tdo {\n\t\t\/\/ counts will track mix table usage each iteration we evaluate the hashed\n\t\tuint8_t counts[32];\n\t\t\n\t\tfor( size_t i=0;i<32;i++ ) { counts[i] = DEFAULT; }\n\t\tfor( size_t i=0;ishort int rand fixup#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ stochasticPerfectHash\n\/\/ Uses stochastic remainder sampling to derive a Pearson mixing table for small sets of alphabetic keys\n\/\/ orthopteroid@gmail.com\n\/\/ g++ -std=c++0x -O3 -lrt sph.cpp -o sph\n\/\/\n\/\/ for background, read:\n\/\/ http:\/\/cs.mwsu.edu\/~griffin\/courses\/2133\/downloads\/Spring11\/p677-pearson.pdf\n\n\/\/ stochastic remainder sampler\nsize_t sample( uint8_t* counts, uint32_t sum )\n{\n\tint32_t target = (((int32_t)rand() << 20) + ((int32_t)rand() << 10) + (int32_t)rand()) % sum; \/\/ impl fix for short int rand()\n\tsize_t i = 0;\n\twhile( (target -= counts[ i ]) > 0 ) { i++; }\n\treturn i;\n}\n\n\/\/ calculates a mixtable for the pearson hash to create a perfect hash.\n\/\/ restrictions are keys can only be ascii lowercase, but can be of any length.\n\/\/ keys are seperated in the input string using the ! delimiter. ! must also be at end of string.\nsize_t calcMixTable( char* sz )\n{\n\tconst size_t MAXITER = 25000;\n\n\t\/\/ special marker '!' in the string designates the end of a key\n\tsize_t keyCount = 0;\n\tfor( size_t i=0;sz[i];i++ ) { if( sz[i] == '!' ) { keyCount++; } }\n\tbool hashed[ keyCount ];\n\n\t\/\/ the defualt mix table is a null transform\n\tuint8_t mix[32] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31};\n\n\t\/\/ these weights influence convergence rate.\n\t\/\/ they are used by the stochastic sampling method that adjusts the mixing table to resolve hash collisions\n\tconst uint8_t DEFAULT = 1;\n\tconst uint8_t SIGNAL = 100;\n\t\n\t\/\/ reset flags...\n\tsize_t iterations = 0;\n\tdo {\n\t\t\/\/ counts will track mix table usage each iteration we evaluate the hashed\n\t\tuint8_t counts[32];\n\t\t\n\t\tfor( size_t i=0;i<32;i++ ) { counts[i] = DEFAULT; }\n\t\tfor( size_t i=0;i"} {"text":"#ifndef __NODE_MAPNIK_FONTS_H__\n#define __NODE_MAPNIK_FONTS_H__\n\n\n\/\/ v8\n#include \n\n\/\/ node\n#include \n\n\/\/ mapnik\n#include \n\n\/\/ stl\n#include \n\n#include \"utils.hpp\"\n\nusing namespace v8;\nusing namespace node;\n\nnamespace node_mapnik {\n\nstatic inline Handle register_fonts(const Arguments& args)\n{\n HandleScope scope;\n \n try\n {\n if (!args.Length() >= 1 || !args[0]->IsString())\n return ThrowException(Exception::TypeError(\n String::New(\"first argument must be a path to a directory of fonts\")));\n \n bool found = false;\n \n std::vector const names_before = mapnik::freetype_engine::face_names();\n \n \/\/ option hash\n if (args.Length() == 2){\n if (!args[1]->IsObject())\n return ThrowException(Exception::TypeError(\n String::New(\"second argument is optional, but if provided must be an object, eg. { recurse:Boolean }\")));\n \n Local options = args[1]->ToObject();\n if (options->Has(String::New(\"recurse\")))\n {\n Local recurse_opt = options->Get(String::New(\"recurse\"));\n if (!recurse_opt->IsBoolean())\n return ThrowException(Exception::TypeError(\n String::New(\"'recurse' must be a Boolean\")));\n \n bool recurse = recurse_opt->BooleanValue();\n std::string const& path = TOSTR(args[0]);\n found = mapnik::freetype_engine::register_fonts(path,recurse);\n }\n }\n else\n {\n std::string const& path = TOSTR(args[0]);\n found = mapnik::freetype_engine::register_fonts(path);\n }\n \n std::vector const& names_after = mapnik::freetype_engine::face_names();\n if (names_after.size() == names_before.size())\n found = false;\n \n return scope.Close(Boolean::New(found)); \n }\n catch (const std::exception & ex)\n {\n return ThrowException(Exception::Error(\n String::New(ex.what())));\n }\n}\n\nstatic inline Handle available_font_faces(const Arguments& args)\n{\n HandleScope scope;\n std::vector const& names = mapnik::freetype_engine::face_names();\n Local a = Array::New(names.size());\n for (unsigned i = 0; i < names.size(); ++i)\n {\n a->Set(i, String::New(names[i].c_str()));\n }\n return scope.Close(a);\n}\n\nstatic inline Handle available_font_files(const Arguments& args)\n{\n HandleScope scope;\n std::map const& mapping = mapnik::freetype_engine::get_mapping();\n Local obj = Object::New();\n std::map::const_iterator itr;\n for (itr = mapping.begin();itr!=mapping.end();++itr)\n {\n obj->Set(String::NewSymbol(itr->first.c_str()),String::New(itr->second.c_str()));\n }\n return scope.Close(obj);\n}\n\n\n}\n\n#endif \/\/ __NODE_MAPNIK_FONTS_H__\nupgrade to new mapnik::freetype_engine::get_mapping signature#ifndef __NODE_MAPNIK_FONTS_H__\n#define __NODE_MAPNIK_FONTS_H__\n\n\n\/\/ v8\n#include \n\n\/\/ node\n#include \n\n\/\/ mapnik\n#include \n\n\/\/ stl\n#include \n\n#include \"utils.hpp\"\n\nusing namespace v8;\nusing namespace node;\n\nnamespace node_mapnik {\n\nstatic inline Handle register_fonts(const Arguments& args)\n{\n HandleScope scope;\n \n try\n {\n if (!args.Length() >= 1 || !args[0]->IsString())\n return ThrowException(Exception::TypeError(\n String::New(\"first argument must be a path to a directory of fonts\")));\n \n bool found = false;\n \n std::vector const names_before = mapnik::freetype_engine::face_names();\n \n \/\/ option hash\n if (args.Length() == 2){\n if (!args[1]->IsObject())\n return ThrowException(Exception::TypeError(\n String::New(\"second argument is optional, but if provided must be an object, eg. { recurse:Boolean }\")));\n \n Local options = args[1]->ToObject();\n if (options->Has(String::New(\"recurse\")))\n {\n Local recurse_opt = options->Get(String::New(\"recurse\"));\n if (!recurse_opt->IsBoolean())\n return ThrowException(Exception::TypeError(\n String::New(\"'recurse' must be a Boolean\")));\n \n bool recurse = recurse_opt->BooleanValue();\n std::string const& path = TOSTR(args[0]);\n found = mapnik::freetype_engine::register_fonts(path,recurse);\n }\n }\n else\n {\n std::string const& path = TOSTR(args[0]);\n found = mapnik::freetype_engine::register_fonts(path);\n }\n \n std::vector const& names_after = mapnik::freetype_engine::face_names();\n if (names_after.size() == names_before.size())\n found = false;\n \n return scope.Close(Boolean::New(found)); \n }\n catch (const std::exception & ex)\n {\n return ThrowException(Exception::Error(\n String::New(ex.what())));\n }\n}\n\nstatic inline Handle available_font_faces(const Arguments& args)\n{\n HandleScope scope;\n std::vector const& names = mapnik::freetype_engine::face_names();\n Local a = Array::New(names.size());\n for (unsigned i = 0; i < names.size(); ++i)\n {\n a->Set(i, String::New(names[i].c_str()));\n }\n return scope.Close(a);\n}\n\nstatic inline Handle available_font_files(const Arguments& args)\n{\n HandleScope scope;\n std::map > const& mapping = mapnik::freetype_engine::get_mapping();\n Local obj = Object::New();\n std::map >::const_iterator itr;\n for (itr = mapping.begin();itr!=mapping.end();++itr)\n {\n obj->Set(String::NewSymbol(itr->first.c_str()),String::New(itr->second.second.c_str()));\n }\n return scope.Close(obj);\n}\n\n\n}\n\n#endif \/\/ __NODE_MAPNIK_FONTS_H__\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace supermarx\n{\n\nvoid init_serializer(request& r, response_handler::serializer_ptr& s)\n{\n\tconst guard g([&]()\n\t{\n\t\t\/\/Fall back to XML\n\t\tif(s == nullptr)\n\t\t{\n\t\t\ts.reset(new xml_serializer());\n\t\t\tr.write_header(\"Content-Type\", \"application\/xml\");\n\t\t}\n\t});\n\n\tconst auto& format = r.env().gets.find(\"format\");\n\tif(format == r.env().gets.end() || format->second == \"xml\")\n\t{\n\t\ts.reset(new xml_serializer());\n\t\tr.write_header(\"Content-Type\", \"application\/xml\");\n\t}\n\telse if(format->second == \"json\")\n\t\ts.reset(new json_serializer());\n\telse if(format->second == \"msgpack\")\n\t\ts.reset(new msgpack_serializer());\n\telse if(format->second == \"msgpack_compact\")\n\t\ts.reset(new msgpack_compact_serializer());\n\telse\n\t\tthrow api_exception::format_unknown;\n}\n\nbool url_decode(const std::string& in, std::string& out)\n{\n\tout.clear();\n\tout.reserve(in.size());\n\n\tfor(std::size_t i = 0; i < in.size(); ++i)\n\t{\n\t\tif(in[i] == '%')\n\t\t{\n\t\t\tif(i + 3 <= in.size())\n\t\t\t{\n\t\t\t\tint value = 0;\n\t\t\t\tstd::istringstream is(in.substr(i + 1, 2));\n\n\t\t\t\tif(is >> std::hex >> value)\n\t\t\t\t{\n\t\t\t\t\tout += static_cast(value);\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn false;\n\t\t}\n\t\telse if(in[i] == '+')\n\t\t\tout += ' ';\n\t\telse\n\t\t\tout += in[i];\n\t}\n\n\treturn true;\n}\n\nvoid write_exception(request& r, response_handler::serializer_ptr& s, api_exception e)\n{\n\ts->clear(); \/\/Clear any previous content\n\n\tr.write_header(\"Status\", api_exception_status(e));\n\n\ts->write_object(\"exception\", 3);\n\ts->write(\"code\", e);\n\ts->write(\"message\", api_exception_message(e));\n\ts->write(\"help\", \"http:\/\/supermarx.nl\/docs\/api_exception\/\" + boost::lexical_cast(e) + \"\/\");\n}\n\nstd::string fetch_payload(const request& r)\n{\n\tconst auto payload_itr = r.env().posts.find(\"payload\");\n\tif(payload_itr == r.env().posts.end())\n\t\tthrow api_exception::payload_expected;\n\n\treturn payload_itr->second.value;\n}\n\ntemplate\nT deserialize_payload(const request& r, const std::string& name)\n{\n\tstd::unique_ptr d(new msgpack_deserializer);\n\td->feed(fetch_payload(r));\n\n\treturn deserialize(d, name);\n}\n\ntemplate\nvoid package(response_handler::serializer_ptr& s, const T& x, const std::string& name)\n{\n\tserialize(s, name, x);\n}\n\nbool process(request& r, response_handler::serializer_ptr& s, karl& k, const uri& u)\n{\n\tif(u.match_path(0, \"find_products\"))\n\t{\n\t\tif(u.path.size() != 3)\n\t\t\treturn false;\n\n\t\tid_t supermarket_id = boost::lexical_cast(u.path[1]);\n\t\tstd::string name = u.path[2];\n\n\t\tserialize(s, \"products\", k.get_products(name, supermarket_id));\n\t\treturn true;\n\t}\n\n\tif(u.match_path(0, \"add_product\"))\n\t{\n\t\tif(u.path.size() != 2)\n\t\t\treturn false;\n\n\t\tid_t supermarket_id = boost::lexical_cast(u.path[1]);\n\t\tapi::add_product request = deserialize_payload(r, \"addproduct\");\n\n\t\tk.add_product(request.p, supermarket_id, request.retrieved_on, request.c);\n\t\ts->write_object(\"response\", 1);\n\t\ts->write(\"status\", std::string(\"done\"));\n\t\treturn true;\n\t}\n\n\tif(u.match_path(0, \"get_product_summary\"))\n\t{\n\t\tif(u.path.size() != 3)\n\t\t\treturn false;\n\n\t\tid_t supermarket_id = boost::lexical_cast(u.path[1]);\n\t\tstd::string identifier = u.path[2];\n\n\t\tauto p_opt = k.get_product_summary(identifier, supermarket_id);\n\t\tif(!p_opt)\n\t\t\tthrow api_exception::product_not_found;\n\n\t\tserialize(s, \"product_summary\", *p_opt);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid response_handler::respond(request& r, karl& k)\n{\n\tr.write_header(\"Server\", \"karl\/0.1\");\n\n\t\/\/ Decode url to path.\n\tstd::string request_path;\n\tif(!url_decode(r.env().requestUri, request_path))\n\t{\n\t\tr.write_header(\"Status\", \"400 Bad Request\");\n\t\tr.write_endofheader();\n\t\treturn;\n\t}\n\n\t\/\/ Request path must be absolute and not contain \"..\".\n\tif(request_path.empty() || request_path[0] != '\/' || request_path.find(\"..\") != std::string::npos)\n\t{\n\t\tr.write_header(\"Status\", \"400 Bad Request\");\n\t\tr.write_endofheader();\n\t\tr.write_text(\"400 bad request\");\n\t\treturn;\n\t}\n\n\turi u(request_path);\n\n\tserializer_ptr s(nullptr);\n\n\ttry\n\t{\n\t\tinit_serializer(r, s);\n\n\t\tif(process(r, s, k, u))\n\t\t\tr.write_header(\"Status\", \"200 OK\");\n\t\telse\n\t\t\tthrow api_exception::path_unknown;\n\t}\n\tcatch(api_exception e)\n\t{\n\t\tlog(\"api::response_handler\", log::WARNING)() << \"api_exception - \" << api_exception_message(e) << \" (\" << e << \")\";\n\n\t\twrite_exception(r, s, e);\n\t}\n\tcatch(std::exception& e)\n\t{\n\t\tlog(\"api::response_handler\", log::ERROR)() << \"Uncaught exception: \" << e.what();\n\n\t\twrite_exception(r, s, api_exception::unknown);\n\t}\n\tcatch( ... )\n\t{\n\t\tlog(\"api::response_handler\", log::ERROR)() << \"Unknown exception\";\n\n\t\twrite_exception(r, s, api_exception::unknown);\n\t}\n\n\tr.write_endofheader();\n\ts->dump([&](const char* data, size_t size){ r.write_bytes(data, size); });\n}\n\n}\nAdded application\/json stanza to json output#include \n\n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace supermarx\n{\n\nvoid init_serializer(request& r, response_handler::serializer_ptr& s)\n{\n\tconst guard g([&]()\n\t{\n\t\t\/\/Fall back to XML\n\t\tif(s == nullptr)\n\t\t{\n\t\t\ts.reset(new xml_serializer());\n\t\t\tr.write_header(\"Content-Type\", \"application\/xml\");\n\t\t}\n\t});\n\n\tconst auto& format = r.env().gets.find(\"format\");\n\tif(format == r.env().gets.end() || format->second == \"xml\")\n\t{\n\t\ts.reset(new xml_serializer());\n\t\tr.write_header(\"Content-Type\", \"application\/xml\");\n\t}\n\telse if(format->second == \"json\")\n\t{\n\t\ts.reset(new json_serializer());\n\t\tr.write_header(\"Content-Type\", \"application\/json\");\n\t}\n\telse if(format->second == \"msgpack\")\n\t\ts.reset(new msgpack_serializer());\n\telse if(format->second == \"msgpack_compact\")\n\t\ts.reset(new msgpack_compact_serializer());\n\telse\n\t\tthrow api_exception::format_unknown;\n}\n\nbool url_decode(const std::string& in, std::string& out)\n{\n\tout.clear();\n\tout.reserve(in.size());\n\n\tfor(std::size_t i = 0; i < in.size(); ++i)\n\t{\n\t\tif(in[i] == '%')\n\t\t{\n\t\t\tif(i + 3 <= in.size())\n\t\t\t{\n\t\t\t\tint value = 0;\n\t\t\t\tstd::istringstream is(in.substr(i + 1, 2));\n\n\t\t\t\tif(is >> std::hex >> value)\n\t\t\t\t{\n\t\t\t\t\tout += static_cast(value);\n\t\t\t\t\ti += 2;\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t\treturn false;\n\t\t\t}\n\t\t\telse\n\t\t\t\treturn false;\n\t\t}\n\t\telse if(in[i] == '+')\n\t\t\tout += ' ';\n\t\telse\n\t\t\tout += in[i];\n\t}\n\n\treturn true;\n}\n\nvoid write_exception(request& r, response_handler::serializer_ptr& s, api_exception e)\n{\n\ts->clear(); \/\/Clear any previous content\n\n\tr.write_header(\"Status\", api_exception_status(e));\n\n\ts->write_object(\"exception\", 3);\n\ts->write(\"code\", e);\n\ts->write(\"message\", api_exception_message(e));\n\ts->write(\"help\", \"http:\/\/supermarx.nl\/docs\/api_exception\/\" + boost::lexical_cast(e) + \"\/\");\n}\n\nstd::string fetch_payload(const request& r)\n{\n\tconst auto payload_itr = r.env().posts.find(\"payload\");\n\tif(payload_itr == r.env().posts.end())\n\t\tthrow api_exception::payload_expected;\n\n\treturn payload_itr->second.value;\n}\n\ntemplate\nT deserialize_payload(const request& r, const std::string& name)\n{\n\tstd::unique_ptr d(new msgpack_deserializer);\n\td->feed(fetch_payload(r));\n\n\treturn deserialize(d, name);\n}\n\ntemplate\nvoid package(response_handler::serializer_ptr& s, const T& x, const std::string& name)\n{\n\tserialize(s, name, x);\n}\n\nbool process(request& r, response_handler::serializer_ptr& s, karl& k, const uri& u)\n{\n\tif(u.match_path(0, \"find_products\"))\n\t{\n\t\tif(u.path.size() != 3)\n\t\t\treturn false;\n\n\t\tid_t supermarket_id = boost::lexical_cast(u.path[1]);\n\t\tstd::string name = u.path[2];\n\n\t\tserialize(s, \"products\", k.get_products(name, supermarket_id));\n\t\treturn true;\n\t}\n\n\tif(u.match_path(0, \"add_product\"))\n\t{\n\t\tif(u.path.size() != 2)\n\t\t\treturn false;\n\n\t\tid_t supermarket_id = boost::lexical_cast(u.path[1]);\n\t\tapi::add_product request = deserialize_payload(r, \"addproduct\");\n\n\t\tk.add_product(request.p, supermarket_id, request.retrieved_on, request.c);\n\t\ts->write_object(\"response\", 1);\n\t\ts->write(\"status\", std::string(\"done\"));\n\t\treturn true;\n\t}\n\n\tif(u.match_path(0, \"get_product_summary\"))\n\t{\n\t\tif(u.path.size() != 3)\n\t\t\treturn false;\n\n\t\tid_t supermarket_id = boost::lexical_cast(u.path[1]);\n\t\tstd::string identifier = u.path[2];\n\n\t\tauto p_opt = k.get_product_summary(identifier, supermarket_id);\n\t\tif(!p_opt)\n\t\t\tthrow api_exception::product_not_found;\n\n\t\tserialize(s, \"product_summary\", *p_opt);\n\t\treturn true;\n\t}\n\n\treturn false;\n}\n\nvoid response_handler::respond(request& r, karl& k)\n{\n\tr.write_header(\"Server\", \"karl\/0.1\");\n\n\t\/\/ Decode url to path.\n\tstd::string request_path;\n\tif(!url_decode(r.env().requestUri, request_path))\n\t{\n\t\tr.write_header(\"Status\", \"400 Bad Request\");\n\t\tr.write_endofheader();\n\t\treturn;\n\t}\n\n\t\/\/ Request path must be absolute and not contain \"..\".\n\tif(request_path.empty() || request_path[0] != '\/' || request_path.find(\"..\") != std::string::npos)\n\t{\n\t\tr.write_header(\"Status\", \"400 Bad Request\");\n\t\tr.write_endofheader();\n\t\tr.write_text(\"400 bad request\");\n\t\treturn;\n\t}\n\n\turi u(request_path);\n\n\tserializer_ptr s(nullptr);\n\n\ttry\n\t{\n\t\tinit_serializer(r, s);\n\n\t\tif(process(r, s, k, u))\n\t\t\tr.write_header(\"Status\", \"200 OK\");\n\t\telse\n\t\t\tthrow api_exception::path_unknown;\n\t}\n\tcatch(api_exception e)\n\t{\n\t\tlog(\"api::response_handler\", log::WARNING)() << \"api_exception - \" << api_exception_message(e) << \" (\" << e << \")\";\n\n\t\twrite_exception(r, s, e);\n\t}\n\tcatch(std::exception& e)\n\t{\n\t\tlog(\"api::response_handler\", log::ERROR)() << \"Uncaught exception: \" << e.what();\n\n\t\twrite_exception(r, s, api_exception::unknown);\n\t}\n\tcatch( ... )\n\t{\n\t\tlog(\"api::response_handler\", log::ERROR)() << \"Unknown exception\";\n\n\t\twrite_exception(r, s, api_exception::unknown);\n\t}\n\n\tr.write_endofheader();\n\ts->dump([&](const char* data, size_t size){ r.write_bytes(data, size); });\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"bsestartup.hh\"\n#include \"..\/config\/config.h\" \/\/ BST_VERSION\n#include \"bsemain.hh\"\n#include \"bse\/internal.hh\"\n#include \n#include \/\/ init_server_connection\n\nnamespace Bse {\n\n\/\/ == BSE Initialization ==\n\n\/** Create SFI glue layer context.\n * Create and push an SFI glue layer context for the calling thread, to enable communications with the\n * main BSE thread library.\n *\/\nSfiGlueContext*\ninit_glue_context (const gchar *client, const std::function &caller_wakeup)\n{\n return _bse_glue_context_create (client, caller_wakeup);\n}\n\n\/** Initialize and start BSE.\n * Initialize the BSE library and start the main BSE thread. Arguments specific to BSE are removed\n * from @a argc \/ @a argv.\n *\/\nvoid\ninit_async (int *argc, char **argv, const char *app_name, const StringVector &args)\n{\n _bse_init_async (argc, argv, app_name, args);\n}\n\n\/\/\/ Check wether init_async() still needs to be called.\nbool\ninit_needed ()\n{\n return _bse_initialized() == false;\n}\n\n\/\/ == TaskRegistry ==\nstatic std::mutex task_registry_mutex_;\nstatic TaskRegistry::List task_registry_tasks_;\n\nvoid\nTaskRegistry::add (const std::string &name, int pid, int tid)\n{\n Bse::TaskStatus task (pid, tid);\n task.name = name;\n task.update();\n std::lock_guard locker (task_registry_mutex_);\n task_registry_tasks_.push_back (task);\n}\n\nbool\nTaskRegistry::remove (int tid)\n{\n std::lock_guard locker (task_registry_mutex_);\n for (auto it = task_registry_tasks_.begin(); it != task_registry_tasks_.end(); it++)\n if (it->task_id == tid)\n {\n task_registry_tasks_.erase (it);\n return true;\n }\n return false;\n}\n\nvoid\nTaskRegistry::update ()\n{\n std::lock_guard locker (task_registry_mutex_);\n for (auto &task : task_registry_tasks_)\n task.update();\n}\n\nTaskRegistry::List\nTaskRegistry::list ()\n{\n std::lock_guard locker (task_registry_mutex_);\n return task_registry_tasks_;\n}\n\nclass AidaGlibSourceImpl : public AidaGlibSource {\n static AidaGlibSourceImpl* self_ (GSource *src) { return (AidaGlibSourceImpl*) src; }\n static int glib_prepare (GSource *src, int *timeoutp) { return self_ (src)->prepare (timeoutp); }\n static int glib_check (GSource *src) { return self_ (src)->check(); }\n static int glib_dispatch (GSource *src, GSourceFunc, void*) { return self_ (src)->dispatch(); }\n static void glib_finalize (GSource *src) { self_ (src)->~AidaGlibSourceImpl(); }\n Aida::BaseConnection *connection_;\n GPollFD pfd_;\n AidaGlibSourceImpl (Aida::BaseConnection *connection) :\n connection_ (connection), pfd_ { -1, 0, 0 }\n {\n pfd_.fd = connection_->notify_fd();\n pfd_.events = G_IO_IN;\n g_source_add_poll (this, &pfd_);\n }\n ~AidaGlibSourceImpl ()\n {\n g_source_remove_poll (this, &pfd_);\n }\n bool\n prepare (int *timeoutp)\n {\n return pfd_.revents || connection_->pending();\n }\n bool\n check ()\n {\n return pfd_.revents || connection_->pending();\n }\n bool\n dispatch ()\n {\n pfd_.revents = 0;\n connection_->dispatch();\n return true;\n }\npublic:\n static AidaGlibSourceImpl*\n create (Aida::BaseConnection *connection)\n {\n assert_return (connection != NULL, NULL);\n static GSourceFuncs glib_source_funcs = { glib_prepare, glib_check, glib_dispatch, glib_finalize, NULL, NULL };\n GSource *src = g_source_new (&glib_source_funcs, sizeof (AidaGlibSourceImpl));\n return new (src) AidaGlibSourceImpl (connection);\n }\n};\n\nAidaGlibSource*\nAidaGlibSource::create (Aida::BaseConnection *connection)\n{\n return AidaGlibSourceImpl::create (connection);\n}\n\nstatic Aida::ClientConnectionP *client_connection = NULL;\n\n\/\/\/ Retrieve a handle for the Bse::Server instance managing the Bse thread.\nServerHandle\ninit_server_instance () \/\/ bse.hh\n{\n ServerH server;\n Aida::ClientConnectionP connection = init_server_connection();\n if (connection)\n server = connection->remote_origin();\n return server;\n}\n\n\/\/\/ Retrieve the ClientConnection used for RPC communication with the Bse thread.\nAida::ClientConnectionP\ninit_server_connection () \/\/ bse.hh\n{\n if (!client_connection)\n {\n Aida::ClientConnectionP connection = Aida::ClientConnection::connect (\"inproc:\/\/BSE-\" BST_VERSION);\n ServerH bseconnection_server_handle;\n if (connection)\n bseconnection_server_handle = connection->remote_origin(); \/\/ sets errno\n assert_return (bseconnection_server_handle != NULL, NULL);\n constexpr SfiProxy BSE_SERVER = 1;\n assert_return (bseconnection_server_handle.proxy_id() == BSE_SERVER, NULL);\n assert_return (bseconnection_server_handle.from_proxy (BSE_SERVER) == bseconnection_server_handle, NULL);\n assert_return (client_connection == NULL, NULL);\n client_connection = new Aida::ClientConnectionP (connection);\n }\n return *client_connection;\n}\n\n} \/\/ Bse\n\n#include \"bseapi_handles.cc\" \/\/ build IDL client interface\nBSE: bsestartup: fix Bse::version() usage\/\/ Licensed GNU LGPL v2.1 or later: http:\/\/www.gnu.org\/licenses\/lgpl.html\n#include \"bsestartup.hh\"\n#include \"bsemain.hh\"\n#include \"bse\/internal.hh\"\n#include \n#include \/\/ init_server_connection\n\nnamespace Bse {\n\n\/\/ == BSE Initialization ==\n\n\/** Create SFI glue layer context.\n * Create and push an SFI glue layer context for the calling thread, to enable communications with the\n * main BSE thread library.\n *\/\nSfiGlueContext*\ninit_glue_context (const gchar *client, const std::function &caller_wakeup)\n{\n return _bse_glue_context_create (client, caller_wakeup);\n}\n\n\/** Initialize and start BSE.\n * Initialize the BSE library and start the main BSE thread. Arguments specific to BSE are removed\n * from @a argc \/ @a argv.\n *\/\nvoid\ninit_async (int *argc, char **argv, const char *app_name, const StringVector &args)\n{\n _bse_init_async (argc, argv, app_name, args);\n}\n\n\/\/\/ Check wether init_async() still needs to be called.\nbool\ninit_needed ()\n{\n return _bse_initialized() == false;\n}\n\n\/\/ == TaskRegistry ==\nstatic std::mutex task_registry_mutex_;\nstatic TaskRegistry::List task_registry_tasks_;\n\nvoid\nTaskRegistry::add (const std::string &name, int pid, int tid)\n{\n Bse::TaskStatus task (pid, tid);\n task.name = name;\n task.update();\n std::lock_guard locker (task_registry_mutex_);\n task_registry_tasks_.push_back (task);\n}\n\nbool\nTaskRegistry::remove (int tid)\n{\n std::lock_guard locker (task_registry_mutex_);\n for (auto it = task_registry_tasks_.begin(); it != task_registry_tasks_.end(); it++)\n if (it->task_id == tid)\n {\n task_registry_tasks_.erase (it);\n return true;\n }\n return false;\n}\n\nvoid\nTaskRegistry::update ()\n{\n std::lock_guard locker (task_registry_mutex_);\n for (auto &task : task_registry_tasks_)\n task.update();\n}\n\nTaskRegistry::List\nTaskRegistry::list ()\n{\n std::lock_guard locker (task_registry_mutex_);\n return task_registry_tasks_;\n}\n\nclass AidaGlibSourceImpl : public AidaGlibSource {\n static AidaGlibSourceImpl* self_ (GSource *src) { return (AidaGlibSourceImpl*) src; }\n static int glib_prepare (GSource *src, int *timeoutp) { return self_ (src)->prepare (timeoutp); }\n static int glib_check (GSource *src) { return self_ (src)->check(); }\n static int glib_dispatch (GSource *src, GSourceFunc, void*) { return self_ (src)->dispatch(); }\n static void glib_finalize (GSource *src) { self_ (src)->~AidaGlibSourceImpl(); }\n Aida::BaseConnection *connection_;\n GPollFD pfd_;\n AidaGlibSourceImpl (Aida::BaseConnection *connection) :\n connection_ (connection), pfd_ { -1, 0, 0 }\n {\n pfd_.fd = connection_->notify_fd();\n pfd_.events = G_IO_IN;\n g_source_add_poll (this, &pfd_);\n }\n ~AidaGlibSourceImpl ()\n {\n g_source_remove_poll (this, &pfd_);\n }\n bool\n prepare (int *timeoutp)\n {\n return pfd_.revents || connection_->pending();\n }\n bool\n check ()\n {\n return pfd_.revents || connection_->pending();\n }\n bool\n dispatch ()\n {\n pfd_.revents = 0;\n connection_->dispatch();\n return true;\n }\npublic:\n static AidaGlibSourceImpl*\n create (Aida::BaseConnection *connection)\n {\n assert_return (connection != NULL, NULL);\n static GSourceFuncs glib_source_funcs = { glib_prepare, glib_check, glib_dispatch, glib_finalize, NULL, NULL };\n GSource *src = g_source_new (&glib_source_funcs, sizeof (AidaGlibSourceImpl));\n return new (src) AidaGlibSourceImpl (connection);\n }\n};\n\nAidaGlibSource*\nAidaGlibSource::create (Aida::BaseConnection *connection)\n{\n return AidaGlibSourceImpl::create (connection);\n}\n\nstatic Aida::ClientConnectionP *client_connection = NULL;\n\n\/\/\/ Retrieve a handle for the Bse::Server instance managing the Bse thread.\nServerHandle\ninit_server_instance () \/\/ bse.hh\n{\n ServerH server;\n Aida::ClientConnectionP connection = init_server_connection();\n if (connection)\n server = connection->remote_origin();\n return server;\n}\n\n\/\/\/ Retrieve the ClientConnection used for RPC communication with the Bse thread.\nAida::ClientConnectionP\ninit_server_connection () \/\/ bse.hh\n{\n if (!client_connection)\n {\n Aida::ClientConnectionP connection = Aida::ClientConnection::connect (\"inproc:\/\/BSE-\" + Bse::version());\n ServerH bseconnection_server_handle;\n if (connection)\n bseconnection_server_handle = connection->remote_origin(); \/\/ sets errno\n assert_return (bseconnection_server_handle != NULL, NULL);\n constexpr SfiProxy BSE_SERVER = 1;\n assert_return (bseconnection_server_handle.proxy_id() == BSE_SERVER, NULL);\n assert_return (bseconnection_server_handle.from_proxy (BSE_SERVER) == bseconnection_server_handle, NULL);\n assert_return (client_connection == NULL, NULL);\n client_connection = new Aida::ClientConnectionP (connection);\n }\n return *client_connection;\n}\n\n} \/\/ Bse\n\n#include \"bse\/bseapi_handles.cc\" \/\/ build IDL client interface\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"constants.hpp\"\n#include \"file_monitor.hpp\"\n#include \"filesystem.hpp\"\n#include \"gcd_utility.hpp\"\n#include \"logger.hpp\"\n#include \n\nnamespace krbn {\nclass grabber_alerts_monitor final {\npublic:\n typedef std::function callback;\n\n grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;\n\n grabber_alerts_monitor(const callback& callback) : callback_(callback) {\n auto file_path = constants::get_grabber_alerts_json_file_path();\n auto directory = filesystem::dirname(file_path);\n\n std::vector>> targets = {\n {directory, {file_path}},\n };\n file_monitor_ = std::make_unique(targets,\n [this](const std::string&) {\n std::ifstream stream(constants::get_grabber_alerts_json_file_path());\n if (stream) {\n auto json = nlohmann::json::parse(stream);\n\n \/\/ json example\n \/\/\n \/\/ {\n \/\/ \"alerts\": [\n \/\/ \"system_policy_prevents_loading_kext\"\n \/\/ ]\n \/\/ }\n\n const std::string key = \"alerts\";\n if (json.find(key) != std::end(json)) {\n auto alerts = json[key];\n if (alerts.is_array() && !alerts.empty()) {\n auto s = json.dump();\n if (json_string_ != s) {\n json_string_ = s;\n if (callback_) {\n callback_();\n }\n }\n }\n }\n }\n });\n }\n\n ~grabber_alerts_monitor(void) {\n gcd_utility::dispatch_sync_in_main_queue(^{\n file_monitor_ = nullptr;\n });\n }\n\nprivate:\n callback callback_;\n\n std::string json_string_;\n std::unique_ptr file_monitor_;\n};\n} \/\/ namespace krbn\ncatch json::parse error#pragma once\n\n#include \"constants.hpp\"\n#include \"file_monitor.hpp\"\n#include \"filesystem.hpp\"\n#include \"gcd_utility.hpp\"\n#include \"logger.hpp\"\n#include \n\nnamespace krbn {\nclass grabber_alerts_monitor final {\npublic:\n typedef std::function callback;\n\n grabber_alerts_monitor(const grabber_alerts_monitor&) = delete;\n\n grabber_alerts_monitor(const callback& callback) : callback_(callback) {\n auto file_path = constants::get_grabber_alerts_json_file_path();\n auto directory = filesystem::dirname(file_path);\n\n std::vector>> targets = {\n {directory, {file_path}},\n };\n file_monitor_ = std::make_unique(targets,\n [this](const std::string&) {\n auto file_path = constants::get_grabber_alerts_json_file_path();\n std::ifstream stream(file_path);\n if (stream) {\n try {\n auto json = nlohmann::json::parse(stream);\n\n \/\/ json example\n \/\/\n \/\/ {\n \/\/ \"alerts\": [\n \/\/ \"system_policy_prevents_loading_kext\"\n \/\/ ]\n \/\/ }\n\n const std::string key = \"alerts\";\n if (json.find(key) != std::end(json)) {\n auto alerts = json[key];\n if (alerts.is_array() && !alerts.empty()) {\n auto s = json.dump();\n if (json_string_ != s) {\n json_string_ = s;\n if (callback_) {\n callback_();\n }\n }\n }\n }\n } catch (std::exception& e) {\n logger::get_logger().error(\"parse error in {0}: {1}\", file_path, e.what());\n }\n }\n });\n }\n\n ~grabber_alerts_monitor(void) {\n gcd_utility::dispatch_sync_in_main_queue(^{\n file_monitor_ = nullptr;\n });\n }\n\nprivate:\n callback callback_;\n\n std::string json_string_;\n std::unique_ptr file_monitor_;\n};\n} \/\/ namespace krbn\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net)\n* All rights reserved.\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in the\n* documentation and\/or other materials provided with the distribution.\n* * Neither the name of Ondrej Danek nor the\n* names of its contributors may be used to endorse or promote products\n* derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"Level.h\"\n#include \"json\/JsonParser.h\"\n\nnamespace Duel6\n{\n\tLevel::Level(const std::string& path, bool mirror, const Block::Meta& blockMeta)\n\t\t: blockMeta(blockMeta)\n\t{\n\t\tload(path, mirror);\n\t}\n\n\tvoid Level::load(const std::string& path, bool mirror)\n\t{\n\t\tlevelData.clear();\n\t\twaterLevel = 0;\n\t\tJson::Parser parser;\n\t\tJson::Value root = parser.parse(path);\n\n\t\twidth = root.get(\"width\").asInt();\n\t\theight = root.get(\"height\").asInt();\n\n\t\tInt32 blockCount = width * height;\n\t\tJson::Value blocks = root.get(\"blocks\");\n\t\tlevelData.resize(blockCount);\n\t\tfor (Size i = 0; i < blocks.getLength(); i++)\n\t\t{\n\t\t\tlevelData[i] = blocks.get(i).asInt();\n\t\t}\n\n\t\tif (mirror)\n\t\t{\n\t\t\tmirrorLevelData();\n\t\t}\n\t\twaterBlock = findWaterType();\n\t}\n\n\tvoid Level::mirrorLevelData()\n\t{\n\t\tfor (Int32 y = 0; y < height; y++)\n\t\t{\n\t\t\tfor (Int32 x = 0; x < width \/ 2; x++)\n\t\t\t{\n\t\t\t\tstd::swap(levelData[y * width + x], levelData[y * width + width - 1 - x]);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Level::raiseWater()\n\t{\n\t\tif(waterLevel < getHeight() - 2)\n\t\t{\n\t\t\twaterLevel++;\n\t\t\tfor(Int32 x = 1; x < getWidth() - 1; x++)\n\t\t\t{\n\t\t\t\tif(!isWall(x, waterLevel, false))\n\t\t\t\t{\n\t\t\t\t\tsetBlock(waterBlock, x, waterLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tUint16 Level::findWaterType() const\n\t{\n\t\tfor (Int32 y = 0; y < getHeight(); y++)\n\t\t{\n\t\t\tfor (Int32 x = 0; x < getWidth(); x++)\n\t\t\t{\n\t\t\t\tif (isWater(x, y))\n\t\t\t\t{\n\t\t\t\t\treturn getBlock(x, y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstatic Uint16 waterBlocks[] = { 4, 16, 33 };\n\t\treturn waterBlocks[rand() % 3];\n\t}\n\n\tWater::Type Level::getWaterType(Int32 x, Int32 y) const\n\t{\n\t\tif (isWater(x, y))\n\t\t{\n\t\t\tUint16 block = getBlock(x, y);\n\t\t\tif (block == 4)\n\t\t\t{\n\t\t\t\treturn Water::Type::Blue;\n\t\t\t}\n\t\t\telse if (block == 16)\n\t\t\t{\n\t\t\t\treturn Water::Type::Red;\n\t\t\t}\n\t\t\telse if (block == 33)\n\t\t\t{\n\t\t\t\treturn Water::Type::Green;\n\t\t\t}\n\t\t}\n\n\t\treturn Water::Type::None;\n\t}\n}Fix water raising\/*\n* Copyright (c) 2006, Ondrej Danek (www.ondrej-danek.net)\n* All rights reserved.\n* Redistribution and use in source and binary forms, with or without\n* modification, are permitted provided that the following conditions are met:\n*\n* * Redistributions of source code must retain the above copyright\n* notice, this list of conditions and the following disclaimer.\n* * Redistributions in binary form must reproduce the above copyright\n* notice, this list of conditions and the following disclaimer in the\n* documentation and\/or other materials provided with the distribution.\n* * Neither the name of Ondrej Danek nor the\n* names of its contributors may be used to endorse or promote products\n* derived from this software without specific prior written permission.\n*\n* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE\n* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE\n* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)\n* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT\n* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \"Level.h\"\n#include \"json\/JsonParser.h\"\n\nnamespace Duel6\n{\n\tLevel::Level(const std::string& path, bool mirror, const Block::Meta& blockMeta)\n\t\t: blockMeta(blockMeta)\n\t{\n\t\tload(path, mirror);\n\t}\n\n\tvoid Level::load(const std::string& path, bool mirror)\n\t{\n\t\tlevelData.clear();\n\t\twaterLevel = 0;\n\t\tJson::Parser parser;\n\t\tJson::Value root = parser.parse(path);\n\n\t\twidth = root.get(\"width\").asInt();\n\t\theight = root.get(\"height\").asInt();\n\n\t\tInt32 blockCount = width * height;\n\t\tJson::Value blocks = root.get(\"blocks\");\n\t\tlevelData.resize(blockCount);\n\t\tfor (Size i = 0; i < blocks.getLength(); i++)\n\t\t{\n\t\t\tlevelData[i] = blocks.get(i).asInt();\n\t\t}\n\n\t\tif (mirror)\n\t\t{\n\t\t\tmirrorLevelData();\n\t\t}\n\t\twaterBlock = findWaterType();\n\t}\n\n\tvoid Level::mirrorLevelData()\n\t{\n\t\tfor (Int32 y = 0; y < height; y++)\n\t\t{\n\t\t\tfor (Int32 x = 0; x < width \/ 2; x++)\n\t\t\t{\n\t\t\t\tstd::swap(levelData[y * width + x], levelData[y * width + width - 1 - x]);\n\t\t\t}\n\t\t}\n\t}\n\n\tvoid Level::raiseWater()\n\t{\n\t\tif(waterLevel < getHeight() - 1)\n\t\t{\n\t\t\twaterLevel++;\n\t\t\tfor(Int32 x = 0; x < getWidth(); x++)\n\t\t\t{\n\t\t\t\tif(!isWall(x, waterLevel, false))\n\t\t\t\t{\n\t\t\t\t\tsetBlock(waterBlock, x, waterLevel);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tUint16 Level::findWaterType() const\n\t{\n\t\tfor (Int32 y = 0; y < getHeight(); y++)\n\t\t{\n\t\t\tfor (Int32 x = 0; x < getWidth(); x++)\n\t\t\t{\n\t\t\t\tif (isWater(x, y))\n\t\t\t\t{\n\t\t\t\t\treturn getBlock(x, y);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tstatic Uint16 waterBlocks[] = { 4, 16, 33 };\n\t\treturn waterBlocks[rand() % 3];\n\t}\n\n\tWater::Type Level::getWaterType(Int32 x, Int32 y) const\n\t{\n\t\tif (isWater(x, y))\n\t\t{\n\t\t\tUint16 block = getBlock(x, y);\n\t\t\tif (block == 4)\n\t\t\t{\n\t\t\t\treturn Water::Type::Blue;\n\t\t\t}\n\t\t\telse if (block == 16)\n\t\t\t{\n\t\t\t\treturn Water::Type::Red;\n\t\t\t}\n\t\t\telse if (block == 33)\n\t\t\t{\n\t\t\t\treturn Water::Type::Green;\n\t\t\t}\n\t\t}\n\n\t\treturn Water::Type::None;\n\t}\n}<|endoftext|>"} {"text":"#include \"HdmiDisplay.h\"\n\nHdmiDisplayIndications::HdmiDisplayIndications()\n{\n}\nHdmiDisplayIndications::~HdmiDisplayIndications()\n{\n}\n\nstruct HdmiDisplayIndicationsvsyncMSG : public PortalMessage\n{\n\/\/fix Adapter.bsv to unreverse these\n unsigned long long v:64;\n\n};\n\nvoid HdmiDisplayIndications::handleMessage(PortalMessage *msg)\n{\n switch (msg->channel) {\n case 0: vsync(((HdmiDisplayIndicationsvsyncMSG *)msg)->v); break;\n\n default: break;\n }\n}\n\nHdmiDisplay *HdmiDisplay::createHdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)\n{\n HdmiDisplay *instance = new HdmiDisplay(instanceName, indications);\n return instance;\n}\n\nHdmiDisplay::HdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)\n : PortalInstance(instanceName, indications)\n{\n}\nHdmiDisplay::~HdmiDisplay()\n{\n close();\n}\n\nstruct HdmiDisplaysetPatternRegMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long yuv422;\n\n } request;\n};\n\nvoid HdmiDisplay::setPatternReg ( unsigned long yuv422 )\n{\n HdmiDisplaysetPatternRegMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 0;\n msg.request.yuv422 = yuv422;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaystartFrameBuffer0MSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long base;\n\n } request;\n};\n\nvoid HdmiDisplay::startFrameBuffer0 ( unsigned long base )\n{\n HdmiDisplaystartFrameBuffer0MSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 1;\n msg.request.base = base;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaystartFrameBuffer1MSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long base;\n\n } request;\n};\n\nvoid HdmiDisplay::startFrameBuffer1 ( unsigned long base )\n{\n HdmiDisplaystartFrameBuffer1MSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 2;\n msg.request.base = base;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaywaitForVsyncMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long unused;\n\n } request;\n};\n\nvoid HdmiDisplay::waitForVsync ( unsigned long unused )\n{\n HdmiDisplaywaitForVsyncMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 3;\n msg.request.unused = unused;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiLinesPixelsMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiLinesPixels ( unsigned long value )\n{\n HdmiDisplayhdmiLinesPixelsMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 4;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiBlankLinesPixelsMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiBlankLinesPixels ( unsigned long value )\n{\n HdmiDisplayhdmiBlankLinesPixelsMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 5;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiStrideBytesMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long strideBytes;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiStrideBytes ( unsigned long strideBytes )\n{\n HdmiDisplayhdmiStrideBytesMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 6;\n msg.request.strideBytes = strideBytes;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiLineCountMinMaxMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiLineCountMinMax ( unsigned long value )\n{\n HdmiDisplayhdmiLineCountMinMaxMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 7;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiPixelCountMinMaxMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiPixelCountMinMax ( unsigned long value )\n{\n HdmiDisplayhdmiPixelCountMinMaxMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 8;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiSyncWidthsMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiSyncWidths ( unsigned long value )\n{\n HdmiDisplayhdmiSyncWidthsMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 9;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaybeginTranslationTableMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long index:8;\n\n } request;\n};\n\nvoid HdmiDisplay::beginTranslationTable ( unsigned long index )\n{\n HdmiDisplaybeginTranslationTableMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 10;\n msg.request.index = index;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayaddTranslationEntryMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long length:12;\n unsigned long address:20;\n\n } request;\n};\n\nvoid HdmiDisplay::addTranslationEntry ( unsigned long address, unsigned long length )\n{\n HdmiDisplayaddTranslationEntryMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 11;\n msg.request.address = address;\n msg.request.length = length;\n\n sendMessage(&msg);\n};\nupdated HdmiDisplay.cpp#include \"HdmiDisplay.h\"\n\nHdmiDisplayIndications::HdmiDisplayIndications()\n{\n}\nHdmiDisplayIndications::~HdmiDisplayIndications()\n{\n}\n\nstruct HdmiDisplayIndicationsvsyncMSG : public PortalMessage\n{\n\/\/fix Adapter.bsv to unreverse these\n unsigned long long v:64;\n\n};\n\nvoid HdmiDisplayIndications::handleMessage(PortalMessage *msg)\n{\n switch (msg->channel) {\n case 12: vsync(((HdmiDisplayIndicationsvsyncMSG *)msg)->v); break;\n\n default: break;\n }\n}\n\nHdmiDisplay *HdmiDisplay::createHdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)\n{\n HdmiDisplay *instance = new HdmiDisplay(instanceName, indications);\n return instance;\n}\n\nHdmiDisplay::HdmiDisplay(const char *instanceName, HdmiDisplayIndications *indications)\n : PortalInstance(instanceName, indications)\n{\n}\nHdmiDisplay::~HdmiDisplay()\n{\n close();\n}\n\nstruct HdmiDisplaysetPatternRegMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long yuv422;\n\n } request;\n};\n\nvoid HdmiDisplay::setPatternReg ( unsigned long yuv422 )\n{\n HdmiDisplaysetPatternRegMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 0;\n msg.request.yuv422 = yuv422;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaystartFrameBuffer0MSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long base;\n\n } request;\n};\n\nvoid HdmiDisplay::startFrameBuffer0 ( unsigned long base )\n{\n HdmiDisplaystartFrameBuffer0MSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 1;\n msg.request.base = base;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaystartFrameBuffer1MSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long base;\n\n } request;\n};\n\nvoid HdmiDisplay::startFrameBuffer1 ( unsigned long base )\n{\n HdmiDisplaystartFrameBuffer1MSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 2;\n msg.request.base = base;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaywaitForVsyncMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long unused;\n\n } request;\n};\n\nvoid HdmiDisplay::waitForVsync ( unsigned long unused )\n{\n HdmiDisplaywaitForVsyncMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 3;\n msg.request.unused = unused;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiLinesPixelsMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiLinesPixels ( unsigned long value )\n{\n HdmiDisplayhdmiLinesPixelsMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 4;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiBlankLinesPixelsMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiBlankLinesPixels ( unsigned long value )\n{\n HdmiDisplayhdmiBlankLinesPixelsMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 5;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiStrideBytesMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long strideBytes;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiStrideBytes ( unsigned long strideBytes )\n{\n HdmiDisplayhdmiStrideBytesMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 6;\n msg.request.strideBytes = strideBytes;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiLineCountMinMaxMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiLineCountMinMax ( unsigned long value )\n{\n HdmiDisplayhdmiLineCountMinMaxMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 7;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiPixelCountMinMaxMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiPixelCountMinMax ( unsigned long value )\n{\n HdmiDisplayhdmiPixelCountMinMaxMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 8;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayhdmiSyncWidthsMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long value;\n\n } request;\n};\n\nvoid HdmiDisplay::hdmiSyncWidths ( unsigned long value )\n{\n HdmiDisplayhdmiSyncWidthsMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 9;\n msg.request.value = value;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplaybeginTranslationTableMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long index:8;\n\n } request;\n};\n\nvoid HdmiDisplay::beginTranslationTable ( unsigned long index )\n{\n HdmiDisplaybeginTranslationTableMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 10;\n msg.request.index = index;\n\n sendMessage(&msg);\n};\n\nstruct HdmiDisplayaddTranslationEntryMSG : public PortalMessage\n{\n struct Request {\n \/\/fix Adapter.bsv to unreverse these\n unsigned long length:12;\n unsigned long address:20;\n\n } request;\n};\n\nvoid HdmiDisplay::addTranslationEntry ( unsigned long address, unsigned long length )\n{\n HdmiDisplayaddTranslationEntryMSG msg;\n msg.size = sizeof(msg.request);\n msg.channel = 11;\n msg.request.address = address;\n msg.request.length = length;\n\n sendMessage(&msg);\n};\n<|endoftext|>"} {"text":"#include \"library\/sp.h\"\n#include \"game\/apocresources\/loftemps.h\"\n#include \"framework\/logger.h\"\n#include \"framework\/data.h\"\n\nnamespace OpenApoc\n{\n\nLOFTemps::LOFTemps(IFile &datFile, IFile &tabFile)\n{\n\tif (!tabFile)\n\t{\n\t\tLogError(\"Invalid TAB file\");\n\t\treturn;\n\t}\n\n\tif (!datFile)\n\t{\n\t\tLogError(\"Invalid DAT file\");\n\t\treturn;\n\t}\n\n\tuint32_t offset;\n\twhile (tabFile.readule32(offset))\n\t{\n\t\tdatFile.seekg(offset * 4, std::ios::beg);\n\t\tif (!datFile)\n\t\t{\n\t\t\tLogError(\"Seeking beyond end of file reading offset %u\", offset * 4);\n\t\t\treturn;\n\t\t}\n\n\t\tuint32_t width;\n\t\tif (!datFile.readule32(width))\n\t\t{\n\t\t\tLogError(\"Failed to read width\");\n\t\t\treturn;\n\t\t}\n\t\tuint32_t height;\n\t\tif (!datFile.readule32(height))\n\t\t{\n\t\t\tLogError(\"Failed to read height\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (width % 8)\n\t\t{\n\t\t\tLogError(\"Non-8-bit-aligned width: %u\", width);\n\t\t\treturn;\n\t\t}\n\n\t\tauto slice = std::make_shared(Vec2{width, height});\n\n\t\tfor (unsigned int y = 0; y < height; y++)\n\t\t{\n\t\t\t\/\/ Bitmasks are packed into a 32-bit word, so all strides will\n\t\t\t\/\/ be 4-byte aligned\n\t\t\tfor (unsigned int x = 0; x < width; x += 32)\n\t\t\t{\n\t\t\t\tuint32_t bitmask;\n\t\t\t\tif (!datFile.readule32(bitmask))\n\t\t\t\t{\n\t\t\t\t\tLogError(\"Failed to read bitmask at {%u,%u}\", x, y);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (unsigned int bit = 0; bit < 32; bit++)\n\t\t\t\t{\n\t\t\t\t\tif (x >= width)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tbool b;\n\t\t\t\t\tif (bitmask & 0x80000000)\n\t\t\t\t\t\tb = true;\n\t\t\t\t\telse\n\t\t\t\t\t\tb = false;\n\t\t\t\t\tbitmask >>= 1;\n\t\t\t\t\tslice->setBit(Vec2{x + bit, y}, b);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLogInfo(\"Read voxel slice of size {%u,%u}\", width, height);\n\t\tthis->slices.push_back(slice);\n\t}\n}\n\nsp LOFTemps::getSlice(unsigned int idx)\n{\n\tif (idx >= this->slices.size())\n\t{\n\t\tLogError(\"Requested slice %d - only %u in file\", idx, this->slices.size());\n\t\treturn nullptr;\n\t}\n\treturn this->slices[idx];\n}\n\n}; \/\/ namespace OpenApoc\nFix collisions#include \"library\/sp.h\"\n#include \"game\/apocresources\/loftemps.h\"\n#include \"framework\/logger.h\"\n#include \"framework\/data.h\"\n\nnamespace OpenApoc\n{\n\nLOFTemps::LOFTemps(IFile &datFile, IFile &tabFile)\n{\n\tif (!tabFile)\n\t{\n\t\tLogError(\"Invalid TAB file\");\n\t\treturn;\n\t}\n\n\tif (!datFile)\n\t{\n\t\tLogError(\"Invalid DAT file\");\n\t\treturn;\n\t}\n\n\tuint32_t offset;\n\twhile (tabFile.readule32(offset))\n\t{\n\t\tdatFile.seekg(offset * 4, std::ios::beg);\n\t\tif (!datFile)\n\t\t{\n\t\t\tLogError(\"Seeking beyond end of file reading offset %u\", offset * 4);\n\t\t\treturn;\n\t\t}\n\n\t\tuint32_t width;\n\t\tif (!datFile.readule32(width))\n\t\t{\n\t\t\tLogError(\"Failed to read width\");\n\t\t\treturn;\n\t\t}\n\t\tuint32_t height;\n\t\tif (!datFile.readule32(height))\n\t\t{\n\t\t\tLogError(\"Failed to read height\");\n\t\t\treturn;\n\t\t}\n\n\t\tif (width % 8)\n\t\t{\n\t\t\tLogError(\"Non-8-bit-aligned width: %u\", width);\n\t\t\treturn;\n\t\t}\n\n\t\tauto slice = std::make_shared(Vec2{width, height});\n\n\t\tfor (unsigned int y = 0; y < height; y++)\n\t\t{\n\t\t\t\/\/ Bitmasks are packed into a 32-bit word, so all strides will\n\t\t\t\/\/ be 4-byte aligned\n\t\t\tfor (unsigned int x = 0; x < width; x += 32)\n\t\t\t{\n\t\t\t\tuint32_t bitmask;\n\t\t\t\tif (!datFile.readule32(bitmask))\n\t\t\t\t{\n\t\t\t\t\tLogError(\"Failed to read bitmask at {%u,%u}\", x, y);\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tfor (unsigned int bit = 0; bit < 32; bit++)\n\t\t\t\t{\n\t\t\t\t\tif (x >= width)\n\t\t\t\t\t\tbreak;\n\t\t\t\t\tbool b;\n\t\t\t\t\tif (bitmask & 0x80000000)\n\t\t\t\t\t\tb = true;\n\t\t\t\t\telse\n\t\t\t\t\t\tb = false;\n\t\t\t\t\tbitmask <<= 1;\n\t\t\t\t\tslice->setBit(Vec2{x + bit, y}, b);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tLogInfo(\"Read voxel slice of size {%u,%u}\", width, height);\n\t\tthis->slices.push_back(slice);\n\t}\n}\n\nsp LOFTemps::getSlice(unsigned int idx)\n{\n\tif (idx >= this->slices.size())\n\t{\n\t\tLogError(\"Requested slice %d - only %u in file\", idx, this->slices.size());\n\t\treturn nullptr;\n\t}\n\treturn this->slices[idx];\n}\n\n}; \/\/ namespace OpenApoc\n<|endoftext|>"} {"text":"\/* Copyright (c) 2013 Fabian Schuiki *\/\n#pragma once\n#include \"..\/math.hpp\"\n#include \"..\/matrix.hpp\"\n#define GAMMA_HAS_TRANSFORM_PERSPECTIVE\n\nnamespace gamma {\nnamespace transform {\n\n\/** A perspective projection, as it would be generated by the gluPerspective\n * OpenGL call. Note that the field-of-view is vertical, aspect is the ratio\n * between the horizontal and vertical field-of-view, and near and far refer to\n * the near and far clipping planes. *\/\ntemplate struct perspective\n{\n\ttypedef perspective self;\n\ttypedef T scalar_type;\n\ttypedef matrix4 matrix_type;\n\n\tconst T fov; \/\/ vertical field of view [radians]\n\tconst T aspect;\n\tconst T near, far; \/\/ clipping planes\n\n\tperspective(): m(1) {}\n\tperspective(T fov, T aspect, T near, T far): fov(fov), aspect(aspect), near(near), far(far)\n\t{\n\t\tT f = tan(M_PI_2 - fov\/2); \/\/ cot(x) = tan(pi\/2 - x)\n\t\tT g = f\/aspect;\n\t\tT a = near+far;\n\t\tT b = near-far;\n\t\tT c = 2*near*far;\n\t\tm = matrix_type(\n\t\t\tg, 0, 0, 0,\n\t\t\t0, f, 0, 0,\n\t\t\t0, 0, a\/b, c\/b,\n\t\t\t0, 0, -1, 0\n\t\t);\n\t}\n\n\toperator matrix_type() const { return m; }\n\nprotected:\n\tmatrix_type m;\n};\n\ntypedef perspective perspectivef;\ntypedef perspective perspectived;\n\n} \/\/ namespace transform\n} \/\/ namespace gammafixed: perspective now follows gluPerspective\/* Copyright (c) 2013 Fabian Schuiki *\/\n#pragma once\n#include \"..\/math.hpp\"\n#include \"..\/matrix.hpp\"\n#define GAMMA_HAS_TRANSFORM_PERSPECTIVE\n\nnamespace gamma {\nnamespace transform {\n\n\/** A perspective projection, as it would be generated by the gluPerspective\n * OpenGL call. Note that the field-of-view is vertical, aspect is the ratio\n * between the horizontal and vertical field-of-view, and near and far refer to\n * the near and far clipping planes. *\/\ntemplate struct perspective\n{\n\ttypedef perspective self;\n\ttypedef T scalar_type;\n\ttypedef matrix4 matrix_type;\n\n\tconst T fov; \/\/ vertical field of view [radians]\n\tconst T aspect;\n\tconst T near, far; \/\/ clipping planes\n\n\tperspective(): m(1) {}\n\tperspective(T fov, T aspect, T near, T far): fov(fov), aspect(aspect), near(near), far(far)\n\t{\n\t\tT f = tan(M_PI_2 - fov\/2); \/\/ cot(x) = tan(pi\/2 - x)\n\t\tT g = f\/aspect;\n\t\tT a = far+near;\n\t\tT b = far-near;\n\t\tT c = 2*near*far;\n\t\tm = matrix_type(\n\t\t\tg, 0, 0, 0,\n\t\t\t0, f, 0, 0,\n\t\t\t0, 0, -a\/b, -c\/b,\n\t\t\t0, 0, -1, 0\n\t\t);\n\t}\n\n\toperator matrix_type() const { return m; }\n\nprotected:\n\tmatrix_type m;\n};\n\ntypedef perspective perspectivef;\ntypedef perspective perspectived;\n\n} \/\/ namespace transform\n} \/\/ namespace gamma<|endoftext|>"} {"text":"#if defined(__linux__) || defined(__APPLE__)\n#include \n#include \n\n#include \"dobby_internal.h\"\n\n#include \"Interceptor.h\"\n\n__attribute__((constructor)) static void ctor() {\n DLOG(-1, \"================================\");\n DLOG(-1, \"Dobby\");\n DLOG(-1, \"================================\");\n\n DLOG(-1, \"dobby in debug log mode, disable with cmake flag \\\"-DDOBBY_DEBUG=OFF\\\"\");\n}\n\nPUBLIC const char *DobbyBuildVersion() {\n return __DOBBY_BUILD_VERSION__;\n}\n\nPUBLIC int DobbyDestroy(void *address) {\n Interceptor *interceptor = Interceptor::SharedInstance();\n\n \/\/ check if we already hook\n HookEntry *entry = interceptor->FindHookEntry(address);\n if (entry) {\n uint8_t *buffer = entry->origin_chunk_.chunk_buffer;\n uint32_t buffer_size = entry->origin_chunk_.chunk.length;\n#if defined(TARGET_ARCH_ARM)\n address = (void *)((addr_t)address - 1);\n#endif\n CodePatch(address, buffer, buffer_size);\n return RT_SUCCESS;\n }\n\n return RT_FAILED;\n}\n\n#endif[misc] update#if defined(__linux__) || defined(__APPLE__)\n#include \n#include \n\n#include \"dobby_internal.h\"\n\n#include \"Interceptor.h\"\n\n__attribute__((constructor)) static void ctor() {\n DLOG(-1, \"================================\");\n DLOG(-1, \"Dobby\");\n DLOG(-1, \"================================\");\n\n DLOG(-1, \"dobby in debug log mode, disable with cmake flag \\\"-DDOBBY_DEBUG=OFF\\\"\");\n}\n\nPUBLIC const char *DobbyBuildVersion() {\n return __DOBBY_BUILD_VERSION__;\n}\n\nPUBLIC int DobbyDestroy(void *address) {\n \/\/ check if we already hook\n HookEntry *entry = Interceptor::SharedInstance()->FindHookEntry(address);\n if (entry) {\n uint8_t *buffer = entry->origin_chunk_.chunk_buffer;\n uint32_t buffer_size = entry->origin_chunk_.chunk.length;\n#if defined(TARGET_ARCH_ARM)\n address = (void *)((addr_t)address - 1);\n#endif\n CodePatch(address, buffer, buffer_size);\n Interceptor::SharedInstance()->RemoveHookEntry(address);\n return RT_SUCCESS;\n }\n\n return RT_FAILED;\n}\n\n#endif<|endoftext|>"} {"text":"\/*\nCopyright (c) 2014, William Magato\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of the copyright holder(s) or contributors.\n*\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::istringstream;\nusing std::vector;\n\nusing namespace llamaos;\nusing llamaos::xen::Hypervisor;\nusing llamaos::xen::Shared_memory;\nusing llamaos::xen::Shared_memory_creator;\nusing llamaos::xen::Shared_memory_user;\n\n\/\/ static const int SHARED_PAGES = 6080;\n\/\/ static const int SHARED_PAGES = 4096;\nstatic const int SHARED_PAGES = 2048;\n\n\/\/ static const int MAX_ENTRIES = 31; \/\/ NEED MORE !!!!\nstatic const int MAX_ENTRIES = 28;\n\/\/ static const int MAX_ENTRIES = 48;\nstatic const int MAX_NAME = 55;\nstatic const int MAX_ALIAS = 47;\n\n#pragma pack(1)\ntypedef struct\n{\n uint8_t name [MAX_NAME+1];\n uint8_t alias [MAX_ALIAS+1];\n uint64_t lock;\n uint64_t lock2;\n uint64_t offset;\n uint64_t size;\n\n} directory_entry_t;\n\ntypedef struct\n{\n uint64_t nodes;\n uint64_t barrier_count;\n bool barrier_sense;\n\n uint64_t next_offset;\n\n directory_entry_t entries [MAX_ENTRIES];\n\n} directory_t;\n#pragma pack()\n\nShared_memory *Shared_memory::create (const std::string &name, domid_t domid)\n{\n \/\/ check if resource node\n size_t pos = name.find(\"-r.\");\n\n if (pos != string::npos)\n {\n istringstream s(name.substr(pos+3));\n int nodes;\n s >> nodes;\n\n return new Shared_memory_creator (domid, nodes); \n }\n\n pos = name.find(\"-\");\n\n if (pos != string::npos)\n {\n istringstream s(name.substr(pos+1));\n int node;\n s >> node;\n\n return new Shared_memory_user (domid, node); \n }\n\n return nullptr;\n}\n\nShared_memory::Shared_memory ()\n : barrier_sense(false)\n{\n \n}\n\nShared_memory::~Shared_memory ()\n{\n \n}\n\nint Shared_memory::open (const std::string &name) const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n\/\/ cout << \"opening \" << name << endl;\n\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ cout << \" [\" << i << \"] \" << directory->entries [i].name << endl;\n\n \/\/ if (__sync_lock_test_and_set(&directory->entries [i].lock, 1) == 0)\n if (__sync_fetch_and_add(&directory->entries [i].lock, 1) == 0)\n {\n cout << \" writing to entry \" << i << \", \" << name.c_str () << endl;\n strncpy(reinterpret_cast(directory->entries [i].name), name.c_str (), MAX_NAME);\n wmb();\n return i + 200;\n }\n\n\/\/ cout << \" searching in entry \" << i << endl;\n\n while (directory->entries [i].name [0] == '\\0')\n {\n cout << \" open waiting for entry name to be written: \" << i << endl;\n mb();\n }\n\n if (strncmp(name.c_str(), reinterpret_cast(directory->entries [i].name), MAX_NAME) == 0)\n {\n\/\/ cout << \" found in entry \" << i << endl;\n return i + 200;\n }\n }\n }\n\n return -1;\n}\n\nvoid *Shared_memory::map (int fd, uint64_t size) const\n{\n uint8_t *pointer = get_pointer ();\n directory_t *directory = reinterpret_cast(pointer);\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n cout << \"mapping fd \" << fd << \", size \" << size << endl;\n int index = fd - 200;\n \/\/ uint64_t offset = PAGE_SIZE;\n\n if (__sync_fetch_and_add(&directory->entries [index].lock2, 1) == 0)\n {\n uint64_t offset = __sync_fetch_and_add(&directory->next_offset, size);\n\n directory->entries [index].offset = offset;\n directory->entries [index].size = size;\n wmb();\n }\n\n while (directory->entries [index].offset == 0)\n {\n cout << \" map waiting for entry offset to be written...\" << index << endl;\n mb();\n }\n\n \/\/ for (int i = 0; i < index; i++)\n \/\/ {\n \/\/ offset += directory->entries [i].size;\n \/\/ }\n\n \/\/ directory->entries [index].offset = offset;\n\n if ((directory->entries [index].offset + size) > (SHARED_PAGES * PAGE_SIZE))\n {\n cout << \"exceeded shared memory space!!!!!\" << endl;\n \/\/ throw\n for (;;);\n return nullptr;\n }\n\n cout << \" mapped to offset \" << directory->entries [index].offset << endl;\n return pointer + directory->entries [index].offset;\n }\n\n return nullptr;\n}\n\nvoid Shared_memory::unmap (int ) const\n{\n \n}\n\nvoid *Shared_memory::get (int fd) const\n{\n uint8_t *pointer = get_pointer ();\n directory_t *directory = reinterpret_cast(pointer);\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n return pointer + directory->entries [fd - 200].offset;\n }\n\n return nullptr;\n}\n\nint Shared_memory::get_size () const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n if (!directory->entries [i].lock)\n {\n return i;\n }\n }\n\n return MAX_ENTRIES;\n }\n\n return 0;\n}\n\nvector Shared_memory::get_names () const\n{\n vector names;\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ if (directory->entries [i].name [0] == '\\0')\n\/\/ {\n\/\/ break;\n\/\/ }\n\n if (!directory->entries [i].lock)\n {\n break;\n }\n\n while (directory->entries [i].name [0] == '\\0')\n {\n cout << \" get_names waiting for entry to be written...\" << i << endl;\n mb();\n }\n\n names.push_back (reinterpret_cast(directory->entries [i].name));\n }\n }\n\n return names;\n}\n\nvoid Shared_memory::put_alias (const string &name, const string &alias) const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ if (directory->entries [i].name [0] == '\\0')\n\/\/ {\n\/\/ break;\n\/\/ }\n if (!directory->entries [i].lock)\n {\n break;\n }\n\n while (directory->entries [i].name [0] == '\\0')\n {\n cout << \" put_alias waiting for entry name to be written...\" << i << endl;\n mb();\n }\n\n if (strncmp(name.c_str(), reinterpret_cast(directory->entries [i].name), MAX_NAME) == 0)\n {\n strncpy(reinterpret_cast(directory->entries [i].alias), alias.c_str (), MAX_ALIAS);\n break;\n }\n }\n }\n}\n\nstring Shared_memory::get_name (const string &alias) const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ if (directory->entries [i].name [0] == '\\0')\n\/\/ {\n\/\/ break;\n\/\/ }\n if (!directory->entries [i].lock)\n {\n break;\n }\n\n while (directory->entries [i].alias [0] == '\\0')\n {\n cout << \" get_name waiting for entry alias to be written...\" << i << endl;\n mb();\n }\n\n if (strncmp(alias.c_str(), reinterpret_cast(directory->entries [i].alias), MAX_ALIAS) == 0)\n {\n return reinterpret_cast(directory->entries [i].name);\n }\n }\n }\n\n return \"name not found\";\n}\n\nvoid Shared_memory::barrier ()\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n\n barrier_sense ^= true;\n\n if (__sync_sub_and_fetch (&directory->barrier_count, 1) == 0)\n {\n cout << \"resetting barrier...\" << endl;\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n\n directory->barrier_count = directory->nodes;\n wmb();\n\n directory->barrier_sense = barrier_sense;\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n }\n else\n {\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n while (barrier_sense != directory->barrier_sense)\n {\n mb();\n }\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n }\n}\n\nstatic uint8_t *create_pointer (domid_t domid, int nodes)\n{\n Hypervisor *hypervisor = Hypervisor::get_instance ();\n\n const unsigned int size = SHARED_PAGES * PAGE_SIZE;\n uint8_t *pointer = static_cast(aligned_alloc (PAGE_SIZE, size));\n memset(static_cast(pointer), 0, size);\n\n for (int i = 0; i < nodes; i++)\n {\n for (int j = 0; j < SHARED_PAGES; j++)\n {\n hypervisor->grant_table.grant_access (domid + 1 + i, &pointer [j * PAGE_SIZE]);\n }\n }\n\n return pointer;\n}\n\nShared_memory_creator::Shared_memory_creator (domid_t domid, int nodes)\n : pointer(create_pointer(domid, nodes))\n{\n directory_t *directory = reinterpret_cast(pointer);\n\n directory->nodes = nodes;\n directory->barrier_count = nodes;\n directory->barrier_sense = false;\n\n directory->next_offset = 2 * PAGE_SIZE;\n\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n}\n\nShared_memory_creator::~Shared_memory_creator ()\n{\n delete pointer;\n}\n\nuint8_t *Shared_memory_creator::get_pointer () const\n{\n return pointer;\n}\n\nShared_memory_user::Shared_memory_user (domid_t domid, int node)\n : grant_map(domid-1-node, (node * SHARED_PAGES), SHARED_PAGES)\n\/\/ : grant_map(domid-1-node, 49151 - (node * SHARED_PAGES), SHARED_PAGES)\n\/\/ : grant_map(domid-1-node, 32767 - (node * SHARED_PAGES), SHARED_PAGES)\n\/\/ : grant_map(domid-1-node, 16383 - (node * SHARED_PAGES), SHARED_PAGES)\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n cout << \"nodes: \" << directory->nodes << endl;\n}\n\nuint8_t *Shared_memory_user::get_pointer () const\n{\n return reinterpret_cast(grant_map.get_pointer ());\n}\ntemp commit, force shared memory to 96 grant frame size\/*\nCopyright (c) 2014, William Magato\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n 1. Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n 2. Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER(S) AND CONTRIBUTORS ''AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\nThe views and conclusions contained in the software and documentation are those\nof the authors and should not be interpreted as representing official policies,\neither expressed or implied, of the copyright holder(s) or contributors.\n*\/\n\n#include \n\n#include \n#include \n\n#include \n#include \n#include \n\nusing std::cout;\nusing std::endl;\nusing std::string;\nusing std::istringstream;\nusing std::vector;\n\nusing namespace llamaos;\nusing llamaos::xen::Hypervisor;\nusing llamaos::xen::Shared_memory;\nusing llamaos::xen::Shared_memory_creator;\nusing llamaos::xen::Shared_memory_user;\n\n\/\/ !BAM TEMP - this will not work on default xen config\nstatic const int SHARED_PAGES = 6080;\n\/\/ static const int SHARED_PAGES = 4096;\n\/\/ static const int SHARED_PAGES = 2048;\n\n\/\/ static const int MAX_ENTRIES = 31; \/\/ NEED MORE !!!!\n\/\/ static const int MAX_ENTRIES = 28;\nstatic const int MAX_ENTRIES = 48;\nstatic const int MAX_NAME = 55;\nstatic const int MAX_ALIAS = 47;\n\n#pragma pack(1)\ntypedef struct\n{\n uint8_t name [MAX_NAME+1];\n uint8_t alias [MAX_ALIAS+1];\n uint64_t lock;\n uint64_t lock2;\n uint64_t offset;\n uint64_t size;\n\n} directory_entry_t;\n\ntypedef struct\n{\n uint64_t nodes;\n uint64_t barrier_count;\n bool barrier_sense;\n\n uint64_t next_offset;\n\n directory_entry_t entries [MAX_ENTRIES];\n\n} directory_t;\n#pragma pack()\n\nShared_memory *Shared_memory::create (const std::string &name, domid_t domid)\n{\n \/\/ check if resource node\n size_t pos = name.find(\"-r.\");\n\n if (pos != string::npos)\n {\n istringstream s(name.substr(pos+3));\n int nodes;\n s >> nodes;\n\n return new Shared_memory_creator (domid, nodes); \n }\n\n pos = name.find(\"-\");\n\n if (pos != string::npos)\n {\n istringstream s(name.substr(pos+1));\n int node;\n s >> node;\n\n return new Shared_memory_user (domid, node); \n }\n\n return nullptr;\n}\n\nShared_memory::Shared_memory ()\n : barrier_sense(false)\n{\n \n}\n\nShared_memory::~Shared_memory ()\n{\n \n}\n\nint Shared_memory::open (const std::string &name) const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n\/\/ cout << \"opening \" << name << endl;\n\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ cout << \" [\" << i << \"] \" << directory->entries [i].name << endl;\n\n \/\/ if (__sync_lock_test_and_set(&directory->entries [i].lock, 1) == 0)\n if (__sync_fetch_and_add(&directory->entries [i].lock, 1) == 0)\n {\n cout << \" writing to entry \" << i << \", \" << name.c_str () << endl;\n strncpy(reinterpret_cast(directory->entries [i].name), name.c_str (), MAX_NAME);\n wmb();\n return i + 200;\n }\n\n\/\/ cout << \" searching in entry \" << i << endl;\n\n while (directory->entries [i].name [0] == '\\0')\n {\n cout << \" open waiting for entry name to be written: \" << i << endl;\n mb();\n }\n\n if (strncmp(name.c_str(), reinterpret_cast(directory->entries [i].name), MAX_NAME) == 0)\n {\n\/\/ cout << \" found in entry \" << i << endl;\n return i + 200;\n }\n }\n }\n\n return -1;\n}\n\nvoid *Shared_memory::map (int fd, uint64_t size) const\n{\n uint8_t *pointer = get_pointer ();\n directory_t *directory = reinterpret_cast(pointer);\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n cout << \"mapping fd \" << fd << \", size \" << size << endl;\n int index = fd - 200;\n \/\/ uint64_t offset = PAGE_SIZE;\n\n if (__sync_fetch_and_add(&directory->entries [index].lock2, 1) == 0)\n {\n uint64_t offset = __sync_fetch_and_add(&directory->next_offset, size);\n\n directory->entries [index].offset = offset;\n directory->entries [index].size = size;\n wmb();\n }\n\n while (directory->entries [index].offset == 0)\n {\n cout << \" map waiting for entry offset to be written...\" << index << endl;\n mb();\n }\n\n \/\/ for (int i = 0; i < index; i++)\n \/\/ {\n \/\/ offset += directory->entries [i].size;\n \/\/ }\n\n \/\/ directory->entries [index].offset = offset;\n\n if ((directory->entries [index].offset + size) > (SHARED_PAGES * PAGE_SIZE))\n {\n cout << \"exceeded shared memory space!!!!!\" << endl;\n \/\/ throw\n for (;;);\n return nullptr;\n }\n\n cout << \" mapped to offset \" << directory->entries [index].offset << endl;\n return pointer + directory->entries [index].offset;\n }\n\n return nullptr;\n}\n\nvoid Shared_memory::unmap (int ) const\n{\n \n}\n\nvoid *Shared_memory::get (int fd) const\n{\n uint8_t *pointer = get_pointer ();\n directory_t *directory = reinterpret_cast(pointer);\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n return pointer + directory->entries [fd - 200].offset;\n }\n\n return nullptr;\n}\n\nint Shared_memory::get_size () const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n if (!directory->entries [i].lock)\n {\n return i;\n }\n }\n\n return MAX_ENTRIES;\n }\n\n return 0;\n}\n\nvector Shared_memory::get_names () const\n{\n vector names;\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ if (directory->entries [i].name [0] == '\\0')\n\/\/ {\n\/\/ break;\n\/\/ }\n\n if (!directory->entries [i].lock)\n {\n break;\n }\n\n while (directory->entries [i].name [0] == '\\0')\n {\n cout << \" get_names waiting for entry to be written...\" << i << endl;\n mb();\n }\n\n names.push_back (reinterpret_cast(directory->entries [i].name));\n }\n }\n\n return names;\n}\n\nvoid Shared_memory::put_alias (const string &name, const string &alias) const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ if (directory->entries [i].name [0] == '\\0')\n\/\/ {\n\/\/ break;\n\/\/ }\n if (!directory->entries [i].lock)\n {\n break;\n }\n\n while (directory->entries [i].name [0] == '\\0')\n {\n cout << \" put_alias waiting for entry name to be written...\" << i << endl;\n mb();\n }\n\n if (strncmp(name.c_str(), reinterpret_cast(directory->entries [i].name), MAX_NAME) == 0)\n {\n strncpy(reinterpret_cast(directory->entries [i].alias), alias.c_str (), MAX_ALIAS);\n break;\n }\n }\n }\n}\n\nstring Shared_memory::get_name (const string &alias) const\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n if (directory != nullptr)\n {\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n for (int i = 0; i < MAX_ENTRIES; i++)\n {\n\/\/ if (directory->entries [i].name [0] == '\\0')\n\/\/ {\n\/\/ break;\n\/\/ }\n if (!directory->entries [i].lock)\n {\n break;\n }\n\n while (directory->entries [i].alias [0] == '\\0')\n {\n cout << \" get_name waiting for entry alias to be written...\" << i << endl;\n mb();\n }\n\n if (strncmp(alias.c_str(), reinterpret_cast(directory->entries [i].alias), MAX_ALIAS) == 0)\n {\n return reinterpret_cast(directory->entries [i].name);\n }\n }\n }\n\n return \"name not found\";\n}\n\nvoid Shared_memory::barrier ()\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n\n barrier_sense ^= true;\n\n if (__sync_sub_and_fetch (&directory->barrier_count, 1) == 0)\n {\n cout << \"resetting barrier...\" << endl;\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n\n directory->barrier_count = directory->nodes;\n wmb();\n\n directory->barrier_sense = barrier_sense;\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n }\n else\n {\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n while (barrier_sense != directory->barrier_sense)\n {\n mb();\n }\n cout << \"barrier: \" << directory->barrier_count\n << \", \" << directory->barrier_sense\n << \", \" << barrier_sense << endl;\n cout << \"nodes: \" << directory->nodes << endl;\n }\n}\n\nstatic uint8_t *create_pointer (domid_t domid, int nodes)\n{\n Hypervisor *hypervisor = Hypervisor::get_instance ();\n\n const unsigned int size = SHARED_PAGES * PAGE_SIZE;\n uint8_t *pointer = static_cast(aligned_alloc (PAGE_SIZE, size));\n memset(static_cast(pointer), 0, size);\n\n for (int i = 0; i < nodes; i++)\n {\n for (int j = 0; j < SHARED_PAGES; j++)\n {\n hypervisor->grant_table.grant_access (domid + 1 + i, &pointer [j * PAGE_SIZE]);\n }\n }\n\n return pointer;\n}\n\nShared_memory_creator::Shared_memory_creator (domid_t domid, int nodes)\n : pointer(create_pointer(domid, nodes))\n{\n directory_t *directory = reinterpret_cast(pointer);\n\n directory->nodes = nodes;\n directory->barrier_count = nodes;\n directory->barrier_sense = false;\n\n directory->next_offset = 2 * PAGE_SIZE;\n\n\/\/ cout << \"nodes: \" << directory->nodes << endl;\n}\n\nShared_memory_creator::~Shared_memory_creator ()\n{\n delete pointer;\n}\n\nuint8_t *Shared_memory_creator::get_pointer () const\n{\n return pointer;\n}\n\nShared_memory_user::Shared_memory_user (domid_t domid, int node)\n : grant_map(domid-1-node, (node * SHARED_PAGES), SHARED_PAGES)\n\/\/ : grant_map(domid-1-node, 49151 - (node * SHARED_PAGES), SHARED_PAGES)\n\/\/ : grant_map(domid-1-node, 32767 - (node * SHARED_PAGES), SHARED_PAGES)\n\/\/ : grant_map(domid-1-node, 16383 - (node * SHARED_PAGES), SHARED_PAGES)\n{\n directory_t *directory = reinterpret_cast(get_pointer ());\n\n cout << \"nodes: \" << directory->nodes << endl;\n}\n\nuint8_t *Shared_memory_user::get_pointer () const\n{\n return reinterpret_cast(grant_map.get_pointer ());\n}\n<|endoftext|>"} {"text":"\/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-\n * \n * Quadra, an action puzzle game\n * Copyright (C) 1998-2000 Ludus Design\n * \n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \n#include \n#include \n#include \"config.h\"\n#include \"url.h\"\n#include \"http_post.h\"\n#include \"dict.h\"\n#include \"stringtable.h\"\n#include \"video.h\"\n#include \"qserv.h\"\n\nRCSID(\"$Id$\")\n\nDword Qserv::http_addr=0;\nint Qserv::http_port=0;\n\nQserv::Qserv() {\n\treq=NULL;\n\tstatus[0]=0;\n\treply=NULL;\n\n\tconst char* host;\n\tint port;\n\tchar path[256];\n\n\tUrl url(config.info.game_server_address);\n\tif(!url.getPort())\n\t\turl.setPort(80);\n\tif(!strcmp(url.getHost(), \"\"))\n\t\turl.setHost(\"ludusdesign.com:80\");\n\tif(!strcmp(url.getPath(), \"\/\"))\n\t\turl.setPath(\"\/cgibin\/qserv.pl\");\n\n\tUrl proxy(config.info2.proxy_address);\n\tif(!proxy.getPort())\n\t\tproxy.setPort(80);\n\n\tif(strlen(proxy.getHost())) {\n\t\t\/\/Use proxy info for host and port, and full game server address for path\n\t\thost = proxy.getHost();\n\t\tport = proxy.getPort();\n\t\turl.getFull(path);\n\t}\n\telse {\n\t\t\/\/No proxy configuration, use game server address for everything\n\t\thost = url.getHost();\n\t\tport = url.getPort();\n\t\tstrcpy(path, url.getPath());\n\t}\n\n\t\/\/Use IP cache if set\n\tif(http_addr)\n\t\treq=new Http_post(host, http_addr, http_port, path);\n\telse\n\t\treq=new Http_post(host, port, path);\n\n\treq->add_data_raw(\"data=\");\n}\n\nQserv::~Qserv() {\n\tif(req)\n\t\tdelete req;\n\tif(reply)\n\t\tdelete reply;\n}\n\nbool Qserv::done() {\n\tif(!req)\n\t\treturn true;\n\tif(!req->done())\n\t\treturn false;\n\n\t\/\/Save ip info for future requests\n\tQserv::http_addr = req->gethostaddr();\n\tQserv::http_port = req->gethostport();\n\n\t\/\/Parse reply\n\treply=new Dict();\n\tif(!req->getsize()) {\n\t\tstrcpy(status, \"\");\n\t}\n\telse {\n\t\tStringtable st(req->getbuf(), req->getsize());\n\t\tint i=0;\n\t\tfor(i=0; i=st.size())\n\t\t\t\t\tstrcpy(status, \"\");\n\t\t\t\telse {\n\t\t\t\t\tstrncpy(status, st.get(i), sizeof(status)-1);\n\t\t\t\t\tstatus[sizeof(status)-1]=0;\n\t\t\t\t\ti++; \/\/ Skip status line\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\twhile(iadd(st.get(i));\n\t\t\ti++;\n\t\t}\n\t}\n\tdelete req;\n\treq=NULL;\n\tmsgbox(\"Qserv::done: done\\n\");\n\treturn true;\n}\n\nvoid Qserv::add_data(const char *s, ...) {\n\tchar st[32768];\n\tTextbuf buf;\n\tva_list marker;\n\tva_start(marker, s);\n\tvsprintf(st, s, marker);\n\tva_end(marker);\n\tHttp_request::url_encode(st, buf);\n\treq->add_data_raw(buf.get());\n}\n\nvoid Qserv::send() {\n\treq->add_data_encode(\"info\/language %i\\n\", config.info.language);\n\treq->add_data_encode(\"info\/registered %i\\n\", 1);\n\treq->add_data_encode(\"info\/quadra_version %i.%i.%i\\n\", config.major, config.minor, config.patchlevel);\n\treq->add_data_encode(\"info\/platform\/os %s\\n\",\n\t\t#if defined(UGS_DIRECTX)\n\t\t\t\"Windows\"\n\t\t#elif defined(UGS_LINUX)\n\t\t\t\"Linux i386\"\n\t\t#else\n\t\t\t#error \"What platform???\"\n\t\t#endif\n\t);\n\tif(video_is_dumb)\n\t\treq->add_data_encode(\"info\/platform\/display None\\n\");\n\telse {\n\t\t#if defined(UGS_LINUX)\n\t\treq->add_data_encode(\"info\/platform\/display %s\\n\", video->xwindow ? \"Xlib\":\"Svgalib\");\n\t\t#endif\n\t\t#if defined(UGS_DIRECTX)\n\t\treq->add_data_encode(\"info\/platform\/display DirectX\\n\");\n\t\t#endif\n\t}\n\treq->send();\n}\n\nconst char *Qserv::get_status() {\n\tif(status[0])\n\t\treturn status;\n\telse\n\t\treturn NULL;\n}\n\nDict *Qserv::get_reply() {\n\treturn reply;\n}\n\nbool Qserv::isconnected() const {\n\tif(req && req->isconnected())\n\t\treturn true;\n\treturn false;\n}\n\nDword Qserv::getnbrecv() const {\n\tint val = 0;\n\tif(req) {\n\t\tval = req->getsize();\n\t\tif(val < 0)\n\t\t\tval = 0;\n\t}\n\treturn val;\n}\nStarted changing the URL for qserv.\/* -*- Mode: C++; c-basic-offset: 2; tab-width: 2; indent-tabs-mode: nil -*-\n * \n * Quadra, an action puzzle game\n * Copyright (C) 1998-2000 Ludus Design\n * \n * This program is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n * \n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n * \n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n *\/\n\n#include \n#include \n#include \n#include \"config.h\"\n#include \"url.h\"\n#include \"http_post.h\"\n#include \"dict.h\"\n#include \"stringtable.h\"\n#include \"video.h\"\n#include \"qserv.h\"\n\nRCSID(\"$Id$\")\n\nDword Qserv::http_addr=0;\nint Qserv::http_port=0;\n\nQserv::Qserv() {\n\treq=NULL;\n\tstatus[0]=0;\n\treply=NULL;\n\n\tconst char* host;\n\tint port;\n\tchar path[256];\n\n\tUrl url(config.info.game_server_address);\n\tif(!url.getPort())\n\t\turl.setPort(80);\n\tif(!strcmp(url.getHost(), \"\"))\n\t\turl.setHost(\"ludusdesign.com:80\");\n\tif(!strcmp(url.getPath(), \"\/\"))\n\t\turl.setPath(\"\/cgi-bin\/qserv.pl\");\n\n\tUrl proxy(config.info2.proxy_address);\n\tif(!proxy.getPort())\n\t\tproxy.setPort(80);\n\n\tif(strlen(proxy.getHost())) {\n\t\t\/\/Use proxy info for host and port, and full game server address for path\n\t\thost = proxy.getHost();\n\t\tport = proxy.getPort();\n\t\turl.getFull(path);\n\t}\n\telse {\n\t\t\/\/No proxy configuration, use game server address for everything\n\t\thost = url.getHost();\n\t\tport = url.getPort();\n\t\tstrcpy(path, url.getPath());\n\t}\n\n\t\/\/Use IP cache if set\n\tif(http_addr)\n\t\treq=new Http_post(host, http_addr, http_port, path);\n\telse\n\t\treq=new Http_post(host, port, path);\n\n\treq->add_data_raw(\"data=\");\n}\n\nQserv::~Qserv() {\n\tif(req)\n\t\tdelete req;\n\tif(reply)\n\t\tdelete reply;\n}\n\nbool Qserv::done() {\n\tif(!req)\n\t\treturn true;\n\tif(!req->done())\n\t\treturn false;\n\n\t\/\/Save ip info for future requests\n\tQserv::http_addr = req->gethostaddr();\n\tQserv::http_port = req->gethostport();\n\n\t\/\/Parse reply\n\treply=new Dict();\n\tif(!req->getsize()) {\n\t\tstrcpy(status, \"\");\n\t}\n\telse {\n\t\tStringtable st(req->getbuf(), req->getsize());\n\t\tint i=0;\n\t\tfor(i=0; i=st.size())\n\t\t\t\t\tstrcpy(status, \"\");\n\t\t\t\telse {\n\t\t\t\t\tstrncpy(status, st.get(i), sizeof(status)-1);\n\t\t\t\t\tstatus[sizeof(status)-1]=0;\n\t\t\t\t\ti++; \/\/ Skip status line\n\t\t\t\t}\n\t\t\t\tbreak;\n\t\t\t}\n\t\twhile(iadd(st.get(i));\n\t\t\ti++;\n\t\t}\n\t}\n\tdelete req;\n\treq=NULL;\n\tmsgbox(\"Qserv::done: done\\n\");\n\treturn true;\n}\n\nvoid Qserv::add_data(const char *s, ...) {\n\tchar st[32768];\n\tTextbuf buf;\n\tva_list marker;\n\tva_start(marker, s);\n\tvsprintf(st, s, marker);\n\tva_end(marker);\n\tHttp_request::url_encode(st, buf);\n\treq->add_data_raw(buf.get());\n}\n\nvoid Qserv::send() {\n\treq->add_data_encode(\"info\/language %i\\n\", config.info.language);\n\treq->add_data_encode(\"info\/registered %i\\n\", 1);\n\treq->add_data_encode(\"info\/quadra_version %i.%i.%i\\n\", config.major, config.minor, config.patchlevel);\n\treq->add_data_encode(\"info\/platform\/os %s\\n\",\n\t\t#if defined(UGS_DIRECTX)\n\t\t\t\"Windows\"\n\t\t#elif defined(UGS_LINUX)\n\t\t\t\"Linux i386\"\n\t\t#else\n\t\t\t#error \"What platform???\"\n\t\t#endif\n\t);\n\tif(video_is_dumb)\n\t\treq->add_data_encode(\"info\/platform\/display None\\n\");\n\telse {\n\t\t#if defined(UGS_LINUX)\n\t\treq->add_data_encode(\"info\/platform\/display %s\\n\", video->xwindow ? \"Xlib\":\"Svgalib\");\n\t\t#endif\n\t\t#if defined(UGS_DIRECTX)\n\t\treq->add_data_encode(\"info\/platform\/display DirectX\\n\");\n\t\t#endif\n\t}\n\treq->send();\n}\n\nconst char *Qserv::get_status() {\n\tif(status[0])\n\t\treturn status;\n\telse\n\t\treturn NULL;\n}\n\nDict *Qserv::get_reply() {\n\treturn reply;\n}\n\nbool Qserv::isconnected() const {\n\tif(req && req->isconnected())\n\t\treturn true;\n\treturn false;\n}\n\nDword Qserv::getnbrecv() const {\n\tint val = 0;\n\tif(req) {\n\t\tval = req->getsize();\n\t\tif(val < 0)\n\t\t\tval = 0;\n\t}\n\treturn val;\n}\n<|endoftext|>"} {"text":"\/* BSD 3-Clause License:\n * Copyright (c) 2018, bitsofcotton.\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n *\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation or other materials provided with the distribution.\n * Neither the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n *\n * 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.\n *\/\n\n#if !defined(_TILT_)\n\n#include \n#include \n#include \n#include \n\nusing namespace Eigen;\nusing std::min;\nusing std::max;\nusing std::ceil;\nusing std::sqrt;\nusing std::cerr;\nusing std::endl;\nusing std::flush;\nusing std::vector;\nusing std::abs;\nusing std::isfinite;\n\ntemplate class triangles_t {\npublic:\n Eigen::Matrix p;\n Eigen::Matrix n;\n T c;\n T z;\n triangles_t& rotate(const Eigen::Matrix& R, const Eigen::Matrix& origin) {\n for(int i = 0; i < 3; i ++)\n p.col(i) = R * (p.col(i) - origin) + origin;\n return *this;\n }\n triangles_t& solveN() {\n const auto pq(p.col(1) - p.col(0));\n const auto pr(p.col(2) - p.col(0));\n n[0] = (pq[1] * pr[2] - pq[2] * pr[1]);\n n[1] = - (pq[0] * pr[2] - pq[2] * pr[0]);\n n[2] = (pq[0] * pr[1] - pq[1] * pr[0]);\n if(n.dot(n) > 0)\n n \/= sqrt(n.dot(n));\n z = n.dot(p.col(0));\n return *this;\n }\n};\n\ntemplate class match_t;\ntemplate class tilter {\npublic:\n typedef Matrix Mat;\n typedef Matrix Mat3x3;\n typedef Matrix Vec3;\n typedef Matrix Vec2;\n typedef triangles_t Triangles;\n \n tilter();\n ~tilter();\n void initialize(const T& z_ratio);\n \n Mat tilt(const Mat& in, const Mat& bump, const int& idx, const int& samples, const T& psi);\n Mat tilt(const Mat& in, const Mat& bump, const match_t& m);\n Mat tilt(const Mat& in, const vector& triangles0, const match_t& m);\n Mat tilt(const Mat& in, const vector& triangles);\n Triangles makeTriangle(const int& u, const int& v, const Mat& in, const Mat& bump, const int& flg);\n bool sameSide2(const Vec2& p0, const Vec2& p1, const Vec2& p, const Vec2& q, const bool& extend = true, const T& err = T(1e-5));\n bool sameSide2(const Vec3& p0, const Vec3& p1, const Vec3& p, const Vec3& q, const bool& extend = true, const T& err = T(1e-5));\n \nprivate:\n T sgn(const T& x);\n bool onTriangle(T& z, const Triangles& tri, const Vec2& geom);\n T Pi;\n T z_ratio;\n};\n\ntemplate tilter::tilter() {\n initialize(1.);\n return;\n}\n\ntemplate tilter::~tilter() {\n ;\n}\n\ntemplate void tilter::initialize(const T& z_ratio) {\n this->z_ratio = z_ratio;\n Pi = atan2(T(1), T(1)) * T(4);\n return;\n}\n\ntemplate T tilter::sgn(const T& x) {\n if(x < T(0))\n return - T(1);\n if(x > T(0))\n return T(1);\n return T(0);\n}\n\ntemplate triangles_t tilter::makeTriangle(const int& u, const int& v, const Mat& in, const Mat& bump, const int& flg) {\n Triangles work;\n if(flg) {\n work.p(0, 0) = u;\n work.p(1, 0) = v;\n work.p(0, 1) = u + 1;\n work.p(1, 1) = v;\n work.p(0, 2) = u + 1;\n work.p(1, 2) = v + 1;\n } else {\n work.p(0, 0) = u;\n work.p(1, 0) = v;\n work.p(0, 1) = u;\n work.p(1, 1) = v + 1;\n work.p(0, 2) = u + 1;\n work.p(1, 2) = v + 1;\n }\n work.c = T(0);\n for(int i = 0; i < 3; i ++) {\n work.p(2, i) = bump(int(work.p(0, i)), int(work.p(1, i))) * z_ratio;\n work.c += in(int(work.p(0, i)), int(work.p(1, i)));\n }\n work.c \/= T(3);\n return work.solveN();\n}\n\ntemplate bool tilter::sameSide2(const Vec2& p0, const Vec2& p1, const Vec2& p2, const Vec2& q, const bool& extend, const T& err) {\n const Vec2 dlt(p1 - p0);\n Vec2 dp(p2 - p0);\n dp -= dlt.dot(dp) * dlt \/ dlt.dot(dlt);\n \/\/ N.B. dp.dot(p1 - p0) >> 0.\n return dp.dot(q - p0) >= (extend ? - T(1) : T(1)) * (abs(dp[0]) + abs(dp[1])) * err;\n}\n\ntemplate bool tilter::sameSide2(const Vec3& p0, const Vec3& p1, const Vec3& p2, const Vec3& q, const bool& extend, const T& err) {\n return sameSide2(Vec2(p0[0], p0[1]), Vec2(p1[0], p1[1]),\n Vec2(p2[0], p2[1]), Vec2(q[0], q[1]),\n extend, err);\n}\n\n\/\/ <[x, y, t], triangle.n> == triangle.z\ntemplate bool tilter::onTriangle(T& z, const Triangles& tri, const Vec2& geom) {\n Vec3 v0;\n Vec3 camera;\n v0[0] = 0;\n v0[1] = 0;\n v0[2] = 1;\n camera[0] = geom[0];\n camera[1] = geom[1];\n camera[2] = 0;\n \/\/ = tri.z\n const T t((tri.z - tri.n.dot(camera)) \/ (tri.n.dot(v0)));\n z = camera[2] + v0[2] * t;\n return (sameSide2(tri.p.col(0), tri.p.col(1), tri.p.col(2), camera, true, T(.125)) &&\n sameSide2(tri.p.col(1), tri.p.col(2), tri.p.col(0), camera, true, T(.125)) &&\n sameSide2(tri.p.col(2), tri.p.col(0), tri.p.col(1), camera, true, T(.125)));\n}\n\ntemplate Eigen::Matrix tilter::tilt(const Mat& in, const Mat& bump, const int& idx, const int& samples, const T& psi) {\n const T theta(2. * Pi * idx \/ samples);\n const T lpsi(Pi * psi);\n Mat3x3 R0;\n Mat3x3 R1;\n R0(0, 0) = cos(theta);\n R0(0, 1) = - sin(theta);\n R0(0, 2) = 0.;\n R0(1, 0) = sin(theta);\n R0(1, 1) = cos(theta);\n R0(1, 2) = 0.;\n R0(2, 0) = 0.;\n R0(2, 1) = 0.;\n R0(2, 2) = 1.;\n R1(0, 0) = 1.;\n R1(0, 1) = 0.;\n R1(0, 2) = 0.;\n R1(1, 0) = 0.;\n R1(1, 1) = cos(lpsi);\n R1(1, 2) = - sin(lpsi);\n R1(2, 0) = 0.;\n R1(2, 1) = sin(lpsi);\n R1(2, 2) = cos(lpsi);\n Vec3 pcenter;\n pcenter[0] = T(in.rows() - 1.) \/ 2;\n pcenter[1] = T(in.cols() - 1.) \/ 2;\n pcenter[2] = T(.5);\n match_t m;\n m.rot = R0.transpose() * R1 * R0;\n m.offset = pcenter - m.rot * pcenter;\n m.ratio = T(1);\n return tilt(in, bump, m);\n}\n\ntemplate Eigen::Matrix tilter::tilt(const Mat& in, const Mat& bump, const match_t& m) {\n assert(in.rows() == bump.rows() && in.cols() == bump.cols());\n vector triangles;\n triangles.reserve((in.rows() - 1) * (in.cols() - 1) * 2);\n for(int i = 0; i < in.rows() - 1; i ++)\n for(int j = 0; j < in.cols() - 1; j ++) {\n triangles.push_back(makeTriangle(i, j, in, bump, false));\n triangles.push_back(makeTriangle(i, j, in, bump, true));\n }\n return tilt(in, triangles, m);\n}\n\ntemplate Eigen::Matrix tilter::tilt(const Mat& in, const vector& triangles0, const match_t& m) {\n vector triangles(triangles0);\n for(int j = 0; j < triangles.size(); j ++) {\n for(int k = 0; k < 3; k ++)\n triangles[j].p.col(k) = m.transform(triangles[j].p.col(k));\n triangles[j].solveN();\n }\n return tilt(in, triangles);\n}\n\ntemplate Eigen::Matrix tilter::tilt(const Mat& in, const vector& triangles) {\n Mat result(in.rows(), in.cols());\n for(int i = 0; i < in.rows(); i ++)\n for(int j = 0; j < in.cols(); j ++)\n result(i, j) = 0.;\n cerr << \"t\" << flush;\n Mat zb(in.rows(), in.cols());\n for(int j = 0; j < zb.rows(); j ++)\n for(int k = 0; k < zb.cols(); k ++)\n zb(j, k) = - T(1e8);\n \/\/ able to boost with divide and conquer.\n#if defined(_OPENMP)\n#pragma omp parallel for schedule(static, 1)\n#endif\n for(int j = 0; j < triangles.size(); j ++) {\n const Triangles& tri(triangles[j]);\n int ll = int( min(min(tri.p(0, 0), tri.p(0, 1)), tri.p(0, 2)));\n int rr = ceil(max(max(tri.p(0, 0), tri.p(0, 1)), tri.p(0, 2))) + 1;\n int bb = int( min(min(tri.p(1, 0), tri.p(1, 1)), tri.p(1, 2)));\n int tt = ceil(max(max(tri.p(1, 0), tri.p(1, 1)), tri.p(1, 2))) + 1;\n for(int y = max(0, ll); y < min(rr, int(in.rows())); y ++)\n for(int x = max(0, bb); x < min(tt, int(in.cols())); x ++) {\n T z;\n Vec2 midgeom;\n midgeom[0] = y;\n midgeom[1] = x;\n#if defined(_OPENMP)\n#pragma omp critical\n#endif\n {\n if(onTriangle(z, tri, midgeom) && isfinite(z) && zb(y, x) < z) {\n result(y, x) = tri.c;\n zb(y, x) = z;\n }\n }\n }\n }\n return result;\n}\n\n#define _TILT_\n#endif\n\nDelete tilt.hh<|endoftext|>"} {"text":"\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ C++ includes\n\n\/\/ Local includes\n#include \"libmesh\/libmesh_config.h\"\n\n#ifdef LIBMESH_HAVE_EIGEN\n\n#include \"libmesh\/eigen_sparse_vector.h\"\n#include \"libmesh\/eigen_sparse_matrix.h\"\n#include \"libmesh\/dense_matrix.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/sparsity_pattern.h\"\n\nnamespace libMesh\n{\n\n\n\/\/-----------------------------------------------------------------------\n\/\/ EigenSparseMatrix members\ntemplate \nvoid EigenSparseMatrix::init (const numeric_index_type m_in,\n const numeric_index_type n_in,\n const numeric_index_type libmesh_dbg_var(m_l),\n const numeric_index_type libmesh_Dbg_var(n_l),\n const numeric_index_type nnz,\n const numeric_index_type,\n const numeric_index_type)\n{\n \/\/ noz ignored... only used for multiple processors!\n libmesh_assert_equal_to (m_in, m_l);\n libmesh_assert_equal_to (n_in, n_l);\n libmesh_assert_equal_to (m_in, n_in);\n libmesh_assert_greater (nnz, 0);\n\n _mat.resize(m_in, n_in);\n _mat.reserve(Eigen::Matrix::Constant(m_in,nnz));\n\n this->_is_initialized = true;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::init ()\n{\n \/\/ Ignore calls on initialized objects\n if (this->initialized())\n return;\n\n \/\/ We need the DofMap for this!\n libmesh_assert(this->_dof_map);\n\n \/\/ Clear intialized matrices\n if (this->initialized())\n this->clear();\n\n const numeric_index_type n_rows = this->_dof_map->n_dofs();\n const numeric_index_type n_cols = n_rows;\n\n#ifndef NDEBUG\n \/\/ The following variables are only used for assertions,\n \/\/ so avoid declaring them when asserts are inactive.\n const numeric_index_type n_l = this->_dof_map->n_dofs_on_processor(0);\n const numeric_index_type m_l = n_l;\n#endif\n\n \/\/ Laspack Matrices only work for uniprocessor cases\n libmesh_assert_equal_to (n_rows, n_cols);\n libmesh_assert_equal_to (m_l, n_rows);\n libmesh_assert_equal_to (n_l, n_cols);\n\n const std::vector& n_nz = this->_dof_map->get_n_nz();\n\n#ifndef NDEBUG\n \/\/ The following variables are only used for assertions,\n \/\/ so avoid declaring them when asserts are inactive.\n const std::vector& n_oz = this->_dof_map->get_n_oz();\n#endif\n\n \/\/ Make sure the sparsity pattern isn't empty\n libmesh_assert_equal_to (n_nz.size(), n_l);\n libmesh_assert_equal_to (n_oz.size(), n_l);\n\n if (n_rows==0)\n {\n _mat.resize(0,0);\n return;\n }\n\n _mat.resize(n_rows,n_cols);\n _mat.reserve(n_nz);\n\n this->_is_initialized = true;\n\n libmesh_assert_equal_to (n_rows, this->m());\n libmesh_assert_equal_to (n_cols, this->n());\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add_matrix(const DenseMatrix& dm,\n const std::vector& rows,\n const std::vector& cols)\n\n{\n libmesh_assert (this->initialized());\n unsigned int n_rows = cast_int(rows.size());\n unsigned int n_cols = cast_int(cols.size());\n libmesh_assert_equal_to (dm.m(), n_rows);\n libmesh_assert_equal_to (dm.n(), n_cols);\n\n\n for (unsigned int i=0; iadd(rows[i],cols[j],dm(i,j));\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::get_diagonal (NumericVector& dest_in) const\n{\n EigenSparseVector& dest = cast_ref&>(dest_in);\n\n dest._vec = _mat.diagonal();\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::get_transpose (SparseMatrix& dest_in) const\n{\n EigenSparseMatrix& dest = cast_ref&>(dest_in);\n\n dest._mat = _mat.transpose();\n}\n\n\n\ntemplate \nEigenSparseMatrix::EigenSparseMatrix\n (const Parallel::Communicator &comm_in) :\n SparseMatrix(comm_in),\n _closed (false)\n{\n}\n\n\n\ntemplate \nEigenSparseMatrix::~EigenSparseMatrix ()\n{\n this->clear ();\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::clear ()\n{\n _mat.resize(0,0);\n\n _closed = false;\n this->_is_initialized = false;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::zero ()\n{\n _mat.setZero();\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::m () const\n{\n libmesh_assert (this->initialized());\n\n return _mat.rows();\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::n () const\n{\n libmesh_assert (this->initialized());\n\n return _mat.cols();\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::row_start () const\n{\n return 0;\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::row_stop () const\n{\n return this->m();\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::set (const numeric_index_type i,\n const numeric_index_type j,\n const T value)\n{\n libmesh_assert (this->initialized());\n libmesh_assert_less (i, this->m());\n libmesh_assert_less (j, this->n());\n\n _mat.coeffRef(i,j) = value;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add (const numeric_index_type i,\n const numeric_index_type j,\n const T value)\n{\n libmesh_assert (this->initialized());\n libmesh_assert_less (i, this->m());\n libmesh_assert_less (j, this->n());\n\n _mat.coeffRef(i,j) += value;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add_matrix(const DenseMatrix& dm,\n const std::vector& dof_indices)\n{\n this->add_matrix (dm, dof_indices, dof_indices);\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add (const T a_in, SparseMatrix &X_in)\n{\n libmesh_assert (this->initialized());\n libmesh_assert_equal_to (this->m(), X_in.m());\n libmesh_assert_equal_to (this->n(), X_in.n());\n\n EigenSparseMatrix &X = cast_ref&> (X_in);\n\n _mat += X._mat*a_in;\n}\n\n\n\n\ntemplate \nT EigenSparseMatrix::operator () (const numeric_index_type i,\n const numeric_index_type j) const\n{\n libmesh_assert (this->initialized());\n libmesh_assert_less (i, this->m());\n libmesh_assert_less (j, this->n());\n\n return _mat.coeff(i,j);\n}\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class EigenSparseMatrix;\n\n} \/\/ namespace libMesh\n\n\n#endif \/\/ #ifdef LIBMESH_HAVE_EIGEN\nTypo fix\/\/ The libMesh Finite Element Library.\n\/\/ Copyright (C) 2002-2014 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner\n\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation; either\n\/\/ version 2.1 of the License, or (at your option) any later version.\n\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n\n\n\n\/\/ C++ includes\n\n\/\/ Local includes\n#include \"libmesh\/libmesh_config.h\"\n\n#ifdef LIBMESH_HAVE_EIGEN\n\n#include \"libmesh\/eigen_sparse_vector.h\"\n#include \"libmesh\/eigen_sparse_matrix.h\"\n#include \"libmesh\/dense_matrix.h\"\n#include \"libmesh\/dof_map.h\"\n#include \"libmesh\/sparsity_pattern.h\"\n\nnamespace libMesh\n{\n\n\n\/\/-----------------------------------------------------------------------\n\/\/ EigenSparseMatrix members\ntemplate \nvoid EigenSparseMatrix::init (const numeric_index_type m_in,\n const numeric_index_type n_in,\n const numeric_index_type libmesh_dbg_var(m_l),\n const numeric_index_type libmesh_dbg_var(n_l),\n const numeric_index_type nnz,\n const numeric_index_type,\n const numeric_index_type)\n{\n \/\/ noz ignored... only used for multiple processors!\n libmesh_assert_equal_to (m_in, m_l);\n libmesh_assert_equal_to (n_in, n_l);\n libmesh_assert_equal_to (m_in, n_in);\n libmesh_assert_greater (nnz, 0);\n\n _mat.resize(m_in, n_in);\n _mat.reserve(Eigen::Matrix::Constant(m_in,nnz));\n\n this->_is_initialized = true;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::init ()\n{\n \/\/ Ignore calls on initialized objects\n if (this->initialized())\n return;\n\n \/\/ We need the DofMap for this!\n libmesh_assert(this->_dof_map);\n\n \/\/ Clear intialized matrices\n if (this->initialized())\n this->clear();\n\n const numeric_index_type n_rows = this->_dof_map->n_dofs();\n const numeric_index_type n_cols = n_rows;\n\n#ifndef NDEBUG\n \/\/ The following variables are only used for assertions,\n \/\/ so avoid declaring them when asserts are inactive.\n const numeric_index_type n_l = this->_dof_map->n_dofs_on_processor(0);\n const numeric_index_type m_l = n_l;\n#endif\n\n \/\/ Laspack Matrices only work for uniprocessor cases\n libmesh_assert_equal_to (n_rows, n_cols);\n libmesh_assert_equal_to (m_l, n_rows);\n libmesh_assert_equal_to (n_l, n_cols);\n\n const std::vector& n_nz = this->_dof_map->get_n_nz();\n\n#ifndef NDEBUG\n \/\/ The following variables are only used for assertions,\n \/\/ so avoid declaring them when asserts are inactive.\n const std::vector& n_oz = this->_dof_map->get_n_oz();\n#endif\n\n \/\/ Make sure the sparsity pattern isn't empty\n libmesh_assert_equal_to (n_nz.size(), n_l);\n libmesh_assert_equal_to (n_oz.size(), n_l);\n\n if (n_rows==0)\n {\n _mat.resize(0,0);\n return;\n }\n\n _mat.resize(n_rows,n_cols);\n _mat.reserve(n_nz);\n\n this->_is_initialized = true;\n\n libmesh_assert_equal_to (n_rows, this->m());\n libmesh_assert_equal_to (n_cols, this->n());\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add_matrix(const DenseMatrix& dm,\n const std::vector& rows,\n const std::vector& cols)\n\n{\n libmesh_assert (this->initialized());\n unsigned int n_rows = cast_int(rows.size());\n unsigned int n_cols = cast_int(cols.size());\n libmesh_assert_equal_to (dm.m(), n_rows);\n libmesh_assert_equal_to (dm.n(), n_cols);\n\n\n for (unsigned int i=0; iadd(rows[i],cols[j],dm(i,j));\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::get_diagonal (NumericVector& dest_in) const\n{\n EigenSparseVector& dest = cast_ref&>(dest_in);\n\n dest._vec = _mat.diagonal();\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::get_transpose (SparseMatrix& dest_in) const\n{\n EigenSparseMatrix& dest = cast_ref&>(dest_in);\n\n dest._mat = _mat.transpose();\n}\n\n\n\ntemplate \nEigenSparseMatrix::EigenSparseMatrix\n (const Parallel::Communicator &comm_in) :\n SparseMatrix(comm_in),\n _closed (false)\n{\n}\n\n\n\ntemplate \nEigenSparseMatrix::~EigenSparseMatrix ()\n{\n this->clear ();\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::clear ()\n{\n _mat.resize(0,0);\n\n _closed = false;\n this->_is_initialized = false;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::zero ()\n{\n _mat.setZero();\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::m () const\n{\n libmesh_assert (this->initialized());\n\n return _mat.rows();\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::n () const\n{\n libmesh_assert (this->initialized());\n\n return _mat.cols();\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::row_start () const\n{\n return 0;\n}\n\n\n\ntemplate \nnumeric_index_type EigenSparseMatrix::row_stop () const\n{\n return this->m();\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::set (const numeric_index_type i,\n const numeric_index_type j,\n const T value)\n{\n libmesh_assert (this->initialized());\n libmesh_assert_less (i, this->m());\n libmesh_assert_less (j, this->n());\n\n _mat.coeffRef(i,j) = value;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add (const numeric_index_type i,\n const numeric_index_type j,\n const T value)\n{\n libmesh_assert (this->initialized());\n libmesh_assert_less (i, this->m());\n libmesh_assert_less (j, this->n());\n\n _mat.coeffRef(i,j) += value;\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add_matrix(const DenseMatrix& dm,\n const std::vector& dof_indices)\n{\n this->add_matrix (dm, dof_indices, dof_indices);\n}\n\n\n\ntemplate \nvoid EigenSparseMatrix::add (const T a_in, SparseMatrix &X_in)\n{\n libmesh_assert (this->initialized());\n libmesh_assert_equal_to (this->m(), X_in.m());\n libmesh_assert_equal_to (this->n(), X_in.n());\n\n EigenSparseMatrix &X = cast_ref&> (X_in);\n\n _mat += X._mat*a_in;\n}\n\n\n\n\ntemplate \nT EigenSparseMatrix::operator () (const numeric_index_type i,\n const numeric_index_type j) const\n{\n libmesh_assert (this->initialized());\n libmesh_assert_less (i, this->m());\n libmesh_assert_less (j, this->n());\n\n return _mat.coeff(i,j);\n}\n\n\n\n\/\/------------------------------------------------------------------\n\/\/ Explicit instantiations\ntemplate class EigenSparseMatrix;\n\n} \/\/ namespace libMesh\n\n\n#endif \/\/ #ifdef LIBMESH_HAVE_EIGEN\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"parser.hpp\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace pegtl;\n\nnamespace realm {\nnamespace parser {\n\n\/\/ strings\nstruct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\\\' > > {};\nstruct escaped_char : one< '\"', '\\'', '\\\\', '\/', 'b', 'f', 'n', 'r', 't' > {};\nstruct escaped : sor< escaped_char, unicode > {};\nstruct unescaped : utf8::range< 0x20, 0x10FFFF > {};\nstruct char_ : if_then_else< one< '\\\\' >, must< escaped >, unescaped > {};\n\nstruct dq_string_content : until< at< one< '\"' > >, must< char_ > > {};\nstruct dq_string : seq< one< '\"' >, must< dq_string_content >, any > {};\n\nstruct sq_string_content : until< at< one< '\\'' > >, must< char_ > > {};\nstruct sq_string : seq< one< '\\'' >, must< sq_string_content >, any > {};\n\n\/\/ numbers\nstruct minus : opt< one< '-' > > {};\nstruct dot : one< '.' > {};\n\nstruct float_num : sor<\n seq< plus< digit >, dot, star< digit > >,\n seq< star< digit >, dot, plus< digit > >\n> {};\nstruct hex_num : seq< one< '0' >, one< 'x', 'X' >, plus< xdigit > > {};\nstruct int_num : plus< digit > {};\n\nstruct number : seq< minus, sor< float_num, hex_num, int_num > > {};\n\nstruct true_value : pegtl_istring_t(\"true\") {};\nstruct false_value : pegtl_istring_t(\"false\") {};\n\n\/\/ key paths\nstruct key_path : list< seq< sor< alpha, one< '_' > >, star< sor< alnum, one< '_', '-' > > > >, one< '.' > > {};\n\n\/\/ argument\nstruct argument_index : until< at< one< '}' > >, must< digit > > {};\nstruct argument : seq< one< '{' >, must< argument_index >, any > {};\n\n\/\/ expressions and operators\nstruct expr : sor< dq_string, sq_string, number, argument, true_value, false_value, key_path > {};\n\nstruct eq : sor< two< '=' >, one< '=' > > {};\nstruct noteq : pegtl::string< '!', '=' > {};\nstruct lteq : pegtl::string< '<', '=' > {};\nstruct lt : one< '<' > {};\nstruct gteq : pegtl::string< '>', '=' > {};\nstruct gt : one< '>' > {};\nstruct contains : pegtl_istring_t(\"contains\") {};\nstruct begins : pegtl_istring_t(\"beginswith\") {};\nstruct ends : pegtl_istring_t(\"endswith\") {};\n\ntemplate\nstruct pad_plus : seq< plus< B >, A, plus< B > > {};\n\nstruct padded_oper : pad_plus< sor< contains, begins, ends >, blank > {};\nstruct symbolic_oper : pad< sor< eq, noteq, lteq, lt, gteq, gt >, blank > {};\n\n\/\/ predicates\nstruct comparison_pred : seq< expr, sor< padded_oper, symbolic_oper >, expr > {};\n\nstruct pred;\nstruct group_pred : if_must< one< '(' >, pad< pred, blank >, one< ')' > > {};\nstruct true_pred : pegtl_istring_t(\"truepredicate\") {};\nstruct false_pred : pegtl_istring_t(\"falsepredicate\") {};\n\nstruct not_pre : sor< seq< one< '!' >, star< blank > >, seq< pegtl_istring_t(\"not\"), plus< blank > > > {};\nstruct atom_pred : seq< opt< not_pre >, pad< sor< group_pred, true_pred, false_pred, comparison_pred >, blank > > {};\n\nstruct and_op : sor< pad< two< '&' >, blank >, pad_plus< pegtl_istring_t(\"and\"), blank > > {};\nstruct or_op : sor< pad< two< '|' >, blank> , pad_plus< pegtl_istring_t(\"or\"), blank > > {};\n\nstruct or_ext : if_must< or_op, pred > {};\nstruct and_ext : if_must< and_op, pred > {};\nstruct and_pred : seq< atom_pred, star< and_ext > > {};\n\nstruct pred : seq< and_pred, star< or_ext > > {};\n\n\/\/ state\nstruct ParserState\n{\n std::vector predicate_stack;\n Predicate ¤t() {\n return *predicate_stack.back();\n }\n\n bool negate_next = false;\n\n void addExpression(Expression && exp)\n {\n if (current().type == Predicate::Type::Comparison) {\n current().cmpr.expr[1] = std::move(exp);\n predicate_stack.pop_back();\n }\n else {\n Predicate p(Predicate::Type::Comparison);\n p.cmpr.expr[0] = std::move(exp);\n if (negate_next) {\n p.negate = true;\n negate_next = false;\n }\n current().cpnd.sub_predicates.emplace_back(std::move(p));\n predicate_stack.push_back(¤t().cpnd.sub_predicates.back());\n }\n }\n};\n\n\/\/ rules\ntemplate< typename Rule >\nstruct action : nothing< Rule > {};\n\ntemplate<> struct action< and_ext >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << \"\" << in.string() << std::endl;\n\n \/\/ if we were put into an OR group we need to rearrange\n auto ¤t = state.current();\n if (current.type == Predicate::Type::Or) {\n auto &sub_preds = state.current().cpnd.sub_predicates;\n auto &second_last = sub_preds[sub_preds.size()-2];\n if (second_last.type == Predicate::Type::And) {\n \/\/ if we are in an OR group and second to last predicate group is\n \/\/ an AND group then move the last predicate inside\n second_last.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));\n sub_preds.pop_back();\n }\n else {\n \/\/ otherwise combine last two into a new AND group\n Predicate pred(Predicate::Type::And);\n pred.cpnd.sub_predicates.emplace_back(std::move(second_last));\n pred.cpnd.sub_predicates.emplace_back(std::move(sub_preds.back()));\n sub_preds.pop_back();\n sub_preds.pop_back();\n sub_preds.push_back(std::move(pred));\n }\n }\n }\n};\n\ntemplate<> struct action< or_ext >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << \"\" << in.string() << std::endl;\n\n \/\/ if already an OR group do nothing\n auto ¤t = state.current();\n if (current.type == Predicate::Type::Or) {\n return;\n }\n\n \/\/ if only two predicates in the group, then convert to OR\n auto &sub_preds = state.current().cpnd.sub_predicates;\n if (sub_preds.size()) {\n current.type = Predicate::Type::Or;\n return;\n }\n\n \/\/ split the current group into to groups which are ORed together\n Predicate pred1(Predicate::Type::And), pred2(Predicate::Type::And);\n pred1.cpnd.sub_predicates.insert(sub_preds.begin(), sub_preds.back());\n pred2.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));\n\n current.type = Predicate::Type::Or;\n sub_preds.clear();\n sub_preds.emplace_back(std::move(pred1));\n sub_preds.emplace_back(std::move(pred2));\n }\n};\n\n\n#define EXPRESSION_ACTION(rule, type) \\\ntemplate<> struct action< rule > { \\\n static void apply( const input & in, ParserState & state ) { \\\n std::cout << in.string() << std::endl; \\\n state.addExpression(Expression(type, in.string())); }};\n\nEXPRESSION_ACTION(dq_string_content, Expression::Type::String)\nEXPRESSION_ACTION(sq_string_content, Expression::Type::String)\nEXPRESSION_ACTION(key_path, Expression::Type::KeyPath)\nEXPRESSION_ACTION(number, Expression::Type::Number)\nEXPRESSION_ACTION(true_value, Expression::Type::True)\nEXPRESSION_ACTION(false_value, Expression::Type::False)\nEXPRESSION_ACTION(argument_index, Expression::Type::Argument)\n\n\ntemplate<> struct action< true_pred >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << in.string() << std::endl;\n state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::True);\n }\n};\n\ntemplate<> struct action< false_pred >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << in.string() << std::endl;\n state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::False);\n }\n};\n\n#define OPERATOR_ACTION(rule, oper) \\\ntemplate<> struct action< rule > { \\\n static void apply( const input & in, ParserState & state ) { \\\n std::cout << in.string() << std::endl; \\\n state.current().cmpr.op = oper; }};\n\nOPERATOR_ACTION(eq, Predicate::Operator::Equal)\nOPERATOR_ACTION(noteq, Predicate::Operator::NotEqual)\nOPERATOR_ACTION(gteq, Predicate::Operator::GreaterThanOrEqual)\nOPERATOR_ACTION(gt, Predicate::Operator::GreaterThan)\nOPERATOR_ACTION(lteq, Predicate::Operator::LessThanOrEqual)\nOPERATOR_ACTION(lt, Predicate::Operator::LessThan)\nOPERATOR_ACTION(begins, Predicate::Operator::BeginsWith)\nOPERATOR_ACTION(ends, Predicate::Operator::EndsWith)\nOPERATOR_ACTION(contains, Predicate::Operator::Contains)\n\ntemplate<> struct action< one< '(' > >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << \"\" << std::endl;\n\n Predicate group(Predicate::Type::And);\n if (state.negate_next) {\n group.negate = true;\n state.negate_next = false;\n }\n\n state.current().cpnd.sub_predicates.emplace_back(std::move(group));\n state.predicate_stack.push_back(&state.current().cpnd.sub_predicates.back());\n }\n};\n\ntemplate<> struct action< group_pred >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << \"\" << std::endl;\n state.predicate_stack.pop_back();\n }\n};\n\ntemplate<> struct action< not_pre >\n{\n static void apply( const input & in, ParserState & state )\n {\n std::cout << \"\" << std::endl;\n state.negate_next = true;\n }\n};\n\nPredicate parse(const std::string &query)\n{\n analyze< pred >();\n const std::string source = \"user query\";\n\n Predicate out_predicate(Predicate::Type::And);\n\n ParserState state;\n state.predicate_stack.push_back(&out_predicate);\n\n pegtl::parse< must< pred, eof >, action >(query, source, state);\n if (out_predicate.type == Predicate::Type::And && out_predicate.cpnd.sub_predicates.size() == 1) {\n return std::move(out_predicate.cpnd.sub_predicates.back());\n }\n return std::move(out_predicate);\n}\n\n}}\n\n\nadd macro to enable\/disable debug token printing\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ Copyright 2015 Realm Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"parser.hpp\"\n\n#include \n\n#include \n#include \n#include \n\nusing namespace pegtl;\n\nnamespace realm {\nnamespace parser {\n\n\/\/ strings\nstruct unicode : list< seq< one< 'u' >, rep< 4, must< xdigit > > >, one< '\\\\' > > {};\nstruct escaped_char : one< '\"', '\\'', '\\\\', '\/', 'b', 'f', 'n', 'r', 't' > {};\nstruct escaped : sor< escaped_char, unicode > {};\nstruct unescaped : utf8::range< 0x20, 0x10FFFF > {};\nstruct char_ : if_then_else< one< '\\\\' >, must< escaped >, unescaped > {};\n\nstruct dq_string_content : until< at< one< '\"' > >, must< char_ > > {};\nstruct dq_string : seq< one< '\"' >, must< dq_string_content >, any > {};\n\nstruct sq_string_content : until< at< one< '\\'' > >, must< char_ > > {};\nstruct sq_string : seq< one< '\\'' >, must< sq_string_content >, any > {};\n\n\/\/ numbers\nstruct minus : opt< one< '-' > > {};\nstruct dot : one< '.' > {};\n\nstruct float_num : sor<\n seq< plus< digit >, dot, star< digit > >,\n seq< star< digit >, dot, plus< digit > >\n> {};\nstruct hex_num : seq< one< '0' >, one< 'x', 'X' >, plus< xdigit > > {};\nstruct int_num : plus< digit > {};\n\nstruct number : seq< minus, sor< float_num, hex_num, int_num > > {};\n\nstruct true_value : pegtl_istring_t(\"true\") {};\nstruct false_value : pegtl_istring_t(\"false\") {};\n\n\/\/ key paths\nstruct key_path : list< seq< sor< alpha, one< '_' > >, star< sor< alnum, one< '_', '-' > > > >, one< '.' > > {};\n\n\/\/ argument\nstruct argument_index : until< at< one< '}' > >, must< digit > > {};\nstruct argument : seq< one< '{' >, must< argument_index >, any > {};\n\n\/\/ expressions and operators\nstruct expr : sor< dq_string, sq_string, number, argument, true_value, false_value, key_path > {};\n\nstruct eq : sor< two< '=' >, one< '=' > > {};\nstruct noteq : pegtl::string< '!', '=' > {};\nstruct lteq : pegtl::string< '<', '=' > {};\nstruct lt : one< '<' > {};\nstruct gteq : pegtl::string< '>', '=' > {};\nstruct gt : one< '>' > {};\nstruct contains : pegtl_istring_t(\"contains\") {};\nstruct begins : pegtl_istring_t(\"beginswith\") {};\nstruct ends : pegtl_istring_t(\"endswith\") {};\n\ntemplate\nstruct pad_plus : seq< plus< B >, A, plus< B > > {};\n\nstruct padded_oper : pad_plus< sor< contains, begins, ends >, blank > {};\nstruct symbolic_oper : pad< sor< eq, noteq, lteq, lt, gteq, gt >, blank > {};\n\n\/\/ predicates\nstruct comparison_pred : seq< expr, sor< padded_oper, symbolic_oper >, expr > {};\n\nstruct pred;\nstruct group_pred : if_must< one< '(' >, pad< pred, blank >, one< ')' > > {};\nstruct true_pred : pegtl_istring_t(\"truepredicate\") {};\nstruct false_pred : pegtl_istring_t(\"falsepredicate\") {};\n\nstruct not_pre : sor< seq< one< '!' >, star< blank > >, seq< pegtl_istring_t(\"not\"), plus< blank > > > {};\nstruct atom_pred : seq< opt< not_pre >, pad< sor< group_pred, true_pred, false_pred, comparison_pred >, blank > > {};\n\nstruct and_op : sor< pad< two< '&' >, blank >, pad_plus< pegtl_istring_t(\"and\"), blank > > {};\nstruct or_op : sor< pad< two< '|' >, blank> , pad_plus< pegtl_istring_t(\"or\"), blank > > {};\n\nstruct or_ext : if_must< or_op, pred > {};\nstruct and_ext : if_must< and_op, pred > {};\nstruct and_pred : seq< atom_pred, star< and_ext > > {};\n\nstruct pred : seq< and_pred, star< or_ext > > {};\n\n\/\/ state\nstruct ParserState\n{\n std::vector predicate_stack;\n Predicate ¤t() {\n return *predicate_stack.back();\n }\n\n bool negate_next = false;\n\n void addExpression(Expression && exp)\n {\n if (current().type == Predicate::Type::Comparison) {\n current().cmpr.expr[1] = std::move(exp);\n predicate_stack.pop_back();\n }\n else {\n Predicate p(Predicate::Type::Comparison);\n p.cmpr.expr[0] = std::move(exp);\n if (negate_next) {\n p.negate = true;\n negate_next = false;\n }\n current().cpnd.sub_predicates.emplace_back(std::move(p));\n predicate_stack.push_back(¤t().cpnd.sub_predicates.back());\n }\n }\n};\n\n\/\/ rules\ntemplate< typename Rule >\nstruct action : nothing< Rule > {};\n\n#define REALM_PARSER_PRINT_TOKENS\n#ifdef REALM_PARSER_PRINT_TOKENS\n #define DEBUG_PRINT_TOKEN(string) std::cout << string << std::endl\n#else\n #define DEBUG_PRINT_TOKEN(string)\n#endif\n\ntemplate<> struct action< and_ext >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(\"\");\n\n \/\/ if we were put into an OR group we need to rearrange\n auto ¤t = state.current();\n if (current.type == Predicate::Type::Or) {\n auto &sub_preds = state.current().cpnd.sub_predicates;\n auto &second_last = sub_preds[sub_preds.size()-2];\n if (second_last.type == Predicate::Type::And) {\n \/\/ if we are in an OR group and second to last predicate group is\n \/\/ an AND group then move the last predicate inside\n second_last.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));\n sub_preds.pop_back();\n }\n else {\n \/\/ otherwise combine last two into a new AND group\n Predicate pred(Predicate::Type::And);\n pred.cpnd.sub_predicates.emplace_back(std::move(second_last));\n pred.cpnd.sub_predicates.emplace_back(std::move(sub_preds.back()));\n sub_preds.pop_back();\n sub_preds.pop_back();\n sub_preds.push_back(std::move(pred));\n }\n }\n }\n};\n\ntemplate<> struct action< or_ext >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(\"\");\n\n \/\/ if already an OR group do nothing\n auto ¤t = state.current();\n if (current.type == Predicate::Type::Or) {\n return;\n }\n\n \/\/ if only two predicates in the group, then convert to OR\n auto &sub_preds = state.current().cpnd.sub_predicates;\n if (sub_preds.size()) {\n current.type = Predicate::Type::Or;\n return;\n }\n\n \/\/ split the current group into to groups which are ORed together\n Predicate pred1(Predicate::Type::And), pred2(Predicate::Type::And);\n pred1.cpnd.sub_predicates.insert(sub_preds.begin(), sub_preds.back());\n pred2.cpnd.sub_predicates.push_back(std::move(sub_preds.back()));\n\n current.type = Predicate::Type::Or;\n sub_preds.clear();\n sub_preds.emplace_back(std::move(pred1));\n sub_preds.emplace_back(std::move(pred2));\n }\n};\n\n\n#define EXPRESSION_ACTION(rule, type) \\\ntemplate<> struct action< rule > { \\\n static void apply( const input & in, ParserState & state ) { \\\n DEBUG_PRINT_TOKEN(in.string()); \\\n state.addExpression(Expression(type, in.string())); }};\n\nEXPRESSION_ACTION(dq_string_content, Expression::Type::String)\nEXPRESSION_ACTION(sq_string_content, Expression::Type::String)\nEXPRESSION_ACTION(key_path, Expression::Type::KeyPath)\nEXPRESSION_ACTION(number, Expression::Type::Number)\nEXPRESSION_ACTION(true_value, Expression::Type::True)\nEXPRESSION_ACTION(false_value, Expression::Type::False)\nEXPRESSION_ACTION(argument_index, Expression::Type::Argument)\n\n\ntemplate<> struct action< true_pred >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(in.string());\n state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::True);\n }\n};\n\ntemplate<> struct action< false_pred >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(in.string());\n state.current().cpnd.sub_predicates.emplace_back(Predicate::Type::False);\n }\n};\n\n#define OPERATOR_ACTION(rule, oper) \\\ntemplate<> struct action< rule > { \\\n static void apply( const input & in, ParserState & state ) { \\\n DEBUG_PRINT_TOKEN(in.string()); \\\n state.current().cmpr.op = oper; }};\n\nOPERATOR_ACTION(eq, Predicate::Operator::Equal)\nOPERATOR_ACTION(noteq, Predicate::Operator::NotEqual)\nOPERATOR_ACTION(gteq, Predicate::Operator::GreaterThanOrEqual)\nOPERATOR_ACTION(gt, Predicate::Operator::GreaterThan)\nOPERATOR_ACTION(lteq, Predicate::Operator::LessThanOrEqual)\nOPERATOR_ACTION(lt, Predicate::Operator::LessThan)\nOPERATOR_ACTION(begins, Predicate::Operator::BeginsWith)\nOPERATOR_ACTION(ends, Predicate::Operator::EndsWith)\nOPERATOR_ACTION(contains, Predicate::Operator::Contains)\n\ntemplate<> struct action< one< '(' > >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(\"\");\n\n Predicate group(Predicate::Type::And);\n if (state.negate_next) {\n group.negate = true;\n state.negate_next = false;\n }\n\n state.current().cpnd.sub_predicates.emplace_back(std::move(group));\n state.predicate_stack.push_back(&state.current().cpnd.sub_predicates.back());\n }\n};\n\ntemplate<> struct action< group_pred >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(\"\");\n state.predicate_stack.pop_back();\n }\n};\n\ntemplate<> struct action< not_pre >\n{\n static void apply( const input & in, ParserState & state )\n {\n DEBUG_PRINT_TOKEN(\"\");\n state.negate_next = true;\n }\n};\n\nPredicate parse(const std::string &query)\n{\n analyze< pred >();\n const std::string source = \"user query\";\n\n Predicate out_predicate(Predicate::Type::And);\n\n ParserState state;\n state.predicate_stack.push_back(&out_predicate);\n\n pegtl::parse< must< pred, eof >, action >(query, source, state);\n if (out_predicate.type == Predicate::Type::And && out_predicate.cpnd.sub_predicates.size() == 1) {\n return std::move(out_predicate.cpnd.sub_predicates.back());\n }\n return std::move(out_predicate);\n}\n\n}}\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: xmlexchg.cxx,v $\n *\n * $Revision: 1.2 $\n *\n * last change: $Author: obo $ $Date: 2004-11-16 11:21:11 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVX_XMLEXCHG_HXX_\n#include \"xmlexchg.hxx\"\n#endif\n\n#ifndef _SOT_FORMATS_HXX\n#include \n#endif\n#ifndef _SOT_EXCHANGE_HXX\n#include \n#endif\n\n\/\/........................................................................\nnamespace svx\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::datatransfer;\n\n \/\/====================================================================\n \/\/= OXFormsTransferable\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OXFormsTransferable::OXFormsTransferable()\n {\n }\n \/\/--------------------------------------------------------------------\n sal_uInt32 OXFormsTransferable::getDescriptorFormatId()\n {\n static sal_uInt32 s_nFormat = (sal_uInt32)-1;\n if ((sal_uInt32)-1 == s_nFormat)\n {\n s_nFormat = SotExchange::RegisterFormatName( String::CreateFromAscii(\"application\/x-openoffice;windows_formatname=\\\"???\\\"\") );\n OSL_ENSURE( (sal_uInt32)-1 != s_nFormat, \"OXFormsTransferable::getDescriptorFormatId: bad exchange id!\" );\n }\n return s_nFormat;\n }\n \/\/--------------------------------------------------------------------\n void OXFormsTransferable::AddSupportedFormats()\n {\n AddFormat( SOT_FORMATSTR_ID_XFORMS );\n }\n \/\/--------------------------------------------------------------------\n sal_Bool OXFormsTransferable::GetData( const DataFlavor& _rFlavor )\n {\n const sal_uInt32 nFormatId = SotExchange::GetFormat( _rFlavor );\n if ( SOT_FORMATSTR_ID_XFORMS == nFormatId )\n {\n return SetString( ::rtl::OUString( String::CreateFromAscii(\"XForms-Transferable\") ), _rFlavor );\n }\n return sal_False;\n }\n\n\n\/\/........................................................................\n} \/\/ namespace svx\n\/\/........................................................................\n\n\nINTEGRATION: CWS eforms4 (1.2.22); FILE MERGED 2004\/12\/06 09:27:42 mbu 1.2.22.1: OXFormsDescriptor handling added\/*************************************************************************\n *\n * $RCSfile: xmlexchg.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2005-03-23 11:48:57 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc..\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifndef _SVX_XMLEXCHG_HXX_\n#include \"xmlexchg.hxx\"\n#endif\n#ifndef _SOT_FORMATS_HXX\n#include \n#endif\n#ifndef _SOT_EXCHANGE_HXX\n#include \n#endif\n#ifndef _DEBUG_HXX\n#include \n#endif\n\n\/\/........................................................................\nnamespace svx\n{\n\/\/........................................................................\n\n using namespace ::com::sun::star::datatransfer;\n\n \/\/====================================================================\n \/\/= OXFormsTransferable\n \/\/====================================================================\n \/\/--------------------------------------------------------------------\n OXFormsTransferable::OXFormsTransferable( const OXFormsDescriptor &rhs ) :\n m_aDescriptor(rhs)\n {\n }\n \/\/--------------------------------------------------------------------\n sal_uInt32 OXFormsTransferable::getDescriptorFormatId()\n {\n static sal_uInt32 s_nFormat = (sal_uInt32)-1;\n if ((sal_uInt32)-1 == s_nFormat)\n {\n s_nFormat = SotExchange::RegisterFormatName( String::CreateFromAscii(\"application\/x-openoffice;windows_formatname=\\\"???\\\"\") );\n OSL_ENSURE( (sal_uInt32)-1 != s_nFormat, \"OXFormsTransferable::getDescriptorFormatId: bad exchange id!\" );\n }\n return s_nFormat;\n }\n \/\/--------------------------------------------------------------------\n void OXFormsTransferable::AddSupportedFormats()\n {\n AddFormat( SOT_FORMATSTR_ID_XFORMS );\n }\n \/\/--------------------------------------------------------------------\n sal_Bool OXFormsTransferable::GetData( const DataFlavor& _rFlavor )\n {\n const sal_uInt32 nFormatId = SotExchange::GetFormat( _rFlavor );\n if ( SOT_FORMATSTR_ID_XFORMS == nFormatId )\n {\n return SetString( ::rtl::OUString( String::CreateFromAscii(\"XForms-Transferable\") ), _rFlavor );\n }\n return sal_False;\n }\n \/\/--------------------------------------------------------------------\n const OXFormsDescriptor &OXFormsTransferable::extractDescriptor( const TransferableDataHelper &_rData ) {\n\n using namespace ::com::sun::star::uno;\n using namespace ::com::sun::star::datatransfer;\n Reference &transfer = const_cast &>(_rData.GetTransferable());\n XTransferable *pInterface = transfer.get();\n OXFormsTransferable *pThis = dynamic_cast(pInterface);\n DBG_ASSERT(pThis,\"XTransferable is NOT an OXFormsTransferable???\");\n return pThis->m_aDescriptor;\n }\n\n\n\/\/........................................................................\n} \/\/ namespace svx\n\/\/........................................................................\n\n\n<|endoftext|>"} {"text":"Resolves: #i123181# Corrected mirroring of shear angle...<|endoftext|>"} {"text":"fixed the German translations<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: colmgr.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-16 23:01:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#include \"hintids.hxx\"\n\n#ifndef _SVX_LRSPITEM_HXX \/\/autogen\n#include \n#endif\n\n#include \"frmmgr.hxx\"\n#include \"frmfmt.hxx\"\n#include \"colmgr.hxx\"\n\n\n\/\/ PRIVATE METHODES ------------------------------------------------------\n\/*------------------------------------------------------------------------\n Beschreibung: Spaltenbreite auf aktuelle Breite einstellen\n------------------------------------------------------------------------*\/\n\n\n\nvoid FitToActualSize(SwFmtCol& rCol, USHORT nWidth)\n{\n const USHORT nCount = rCol.GetColumns().Count();\n for(USHORT i = 0; i < nCount; ++i)\n {\n const USHORT nTmp = rCol.CalcColWidth(i, nWidth);\n rCol.GetColumns()[i]->SetWishWidth(nTmp);\n }\n rCol.SetWishWidth(nWidth);\n}\n\n\n\/\/ PUBLIC METHODES -------------------------------------------------------\n\/*------------------------------------------------------------------------\n Beschreibung: Setzen Spaltenanzahl und Gutterwidth\n------------------------------------------------------------------------*\/\n\n\n\nvoid SwColMgr::SetCount(USHORT nCount, USHORT nGutterWidth)\n{\n aFmtCol.Init(nCount, nGutterWidth, nWidth);\n aFmtCol.SetWishWidth(nWidth);\n aFmtCol.SetGutterWidth(nGutterWidth, nWidth);\n}\n\n\n\nUSHORT SwColMgr::GetGutterWidth( USHORT nPos ) const\n{\n USHORT nRet;\n if(nPos == USHRT_MAX )\n nRet = GetCount() > 1 ? aFmtCol.GetGutterWidth() : DEF_GUTTER_WIDTH;\n else\n {\n DBG_ASSERT(nPos < GetCount() - 1, \"Spalte ueberindiziert\" )\n const SwColumns& rCols = aFmtCol.GetColumns();\n nRet = rCols.GetObject(nPos)->GetRight() + rCols.GetObject(nPos + 1)->GetLeft();\n }\n return nRet;\n}\n\n\/*-----------------22.10.96 14.28-------------------\n\n--------------------------------------------------*\/\n\n\nvoid SwColMgr::SetGutterWidth(USHORT nGutterWidth, USHORT nPos )\n{\n if(nPos == USHRT_MAX)\n aFmtCol.SetGutterWidth(nGutterWidth, nWidth);\n else\n {\n DBG_ASSERT(nPos < GetCount() - 1, \"Spalte ueberindiziert\" )\n SwColumns& rCols = aFmtCol.GetColumns();\n USHORT nGutterWidth2 = nGutterWidth \/ 2;\n rCols.GetObject(nPos)->SetRight(nGutterWidth2);\n rCols.GetObject(nPos + 1)->SetLeft(nGutterWidth2);\n }\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Hoehe Trennlinie\n------------------------------------------------------------------------*\/\n\n\n\nshort SwColMgr::GetLineHeightPercent() const\n{\n return (short)aFmtCol.GetLineHeight();\n}\n\n\n\nvoid SwColMgr::SetLineHeightPercent(short nPercent)\n{\n ASSERT(nPercent <= 100, LineHeight darf nur bis 100 % gross sein);\n aFmtCol.SetLineHeight((BYTE)nPercent);\n}\n\/*------------------------------------------------------------------------\n Beschreibung: Spaltenbreite\n------------------------------------------------------------------------*\/\n\n\n\nUSHORT SwColMgr::GetColWidth(USHORT nIdx) const\n{\n ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);\n return aFmtCol.CalcPrtColWidth(nIdx, nWidth);\n}\n\n\n\nvoid SwColMgr::SetColWidth(USHORT nIdx, USHORT nWd)\n{\n ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);\n aFmtCol.GetColumns()[nIdx]->SetWishWidth(nWd);\n\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Groesse neu setzen\n --------------------------------------------------------------------*\/\n\n\n\nvoid SwColMgr::SetActualWidth(USHORT nW)\n{\n nWidth = nW;\n ::FitToActualSize(aFmtCol, nW);\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: ctor\n --------------------------------------------------------------------*\/\n\n\n\nSwColMgr::SwColMgr(const SfxItemSet& rSet, USHORT nActWidth) :\n aFmtCol((const SwFmtCol&)rSet.Get(RES_COL)),\n nWidth(nActWidth)\n{\n if(nWidth == USHRT_MAX)\n {\n nWidth = (USHORT)((const SwFmtFrmSize&)rSet.Get(RES_FRM_SIZE)).GetWidth();\n if (nWidth < MINLAY)\n nWidth = USHRT_MAX;\n const SvxLRSpaceItem &rLR = (const SvxLRSpaceItem&)rSet.Get(RES_LR_SPACE);\n nWidth -= (USHORT)rLR.GetLeft();\n nWidth -= (USHORT)rLR.GetRight();\n }\n ::FitToActualSize(aFmtCol, nWidth);\n}\n\n\n\n\nSwColMgr::~SwColMgr() {}\n\n\n\n\n\n\nINTEGRATION: CWS swwarnings (1.5.222); FILE MERGED 2007\/04\/03 13:01:11 tl 1.5.222.1: #i69287# warning-free code\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: colmgr.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 11:51:07 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#include \"hintids.hxx\"\n\n#ifndef _SVX_LRSPITEM_HXX \/\/autogen\n#include \n#endif\n\n#include \"frmmgr.hxx\"\n#include \"frmfmt.hxx\"\n#include \"colmgr.hxx\"\n\n\n\/\/ PRIVATE METHODES ------------------------------------------------------\n\/*------------------------------------------------------------------------\n Beschreibung: Spaltenbreite auf aktuelle Breite einstellen\n------------------------------------------------------------------------*\/\n\n\n\nvoid FitToActualSize(SwFmtCol& rCol, USHORT nWidth)\n{\n const USHORT nCount = rCol.GetColumns().Count();\n for(USHORT i = 0; i < nCount; ++i)\n {\n const USHORT nTmp = rCol.CalcColWidth(i, nWidth);\n rCol.GetColumns()[i]->SetWishWidth(nTmp);\n }\n rCol.SetWishWidth(nWidth);\n}\n\n\n\/\/ PUBLIC METHODES -------------------------------------------------------\n\/*------------------------------------------------------------------------\n Beschreibung: Setzen Spaltenanzahl und Gutterwidth\n------------------------------------------------------------------------*\/\n\n\n\nvoid SwColMgr::SetCount(USHORT nCount, USHORT nGutterWidth)\n{\n aFmtCol.Init(nCount, nGutterWidth, nWidth);\n aFmtCol.SetWishWidth(nWidth);\n aFmtCol.SetGutterWidth(nGutterWidth, nWidth);\n}\n\n\n\nUSHORT SwColMgr::GetGutterWidth( USHORT nPos ) const\n{\n USHORT nRet;\n if(nPos == USHRT_MAX )\n nRet = GetCount() > 1 ? aFmtCol.GetGutterWidth() : DEF_GUTTER_WIDTH;\n else\n {\n DBG_ASSERT(nPos < GetCount() - 1, \"Spalte ueberindiziert\" )\n const SwColumns& rCols = aFmtCol.GetColumns();\n nRet = rCols.GetObject(nPos)->GetRight() + rCols.GetObject(nPos + 1)->GetLeft();\n }\n return nRet;\n}\n\n\/*-----------------22.10.96 14.28-------------------\n\n--------------------------------------------------*\/\n\n\nvoid SwColMgr::SetGutterWidth(USHORT nGutterWidth, USHORT nPos )\n{\n if(nPos == USHRT_MAX)\n aFmtCol.SetGutterWidth(nGutterWidth, nWidth);\n else\n {\n DBG_ASSERT(nPos < GetCount() - 1, \"Spalte ueberindiziert\" )\n SwColumns& rCols = aFmtCol.GetColumns();\n USHORT nGutterWidth2 = nGutterWidth \/ 2;\n rCols.GetObject(nPos)->SetRight(nGutterWidth2);\n rCols.GetObject(nPos + 1)->SetLeft(nGutterWidth2);\n }\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Hoehe Trennlinie\n------------------------------------------------------------------------*\/\n\n\n\nshort SwColMgr::GetLineHeightPercent() const\n{\n return (short)aFmtCol.GetLineHeight();\n}\n\n\n\nvoid SwColMgr::SetLineHeightPercent(short nPercent)\n{\n ASSERT(nPercent <= 100, LineHeight darf nur bis 100 % gross sein);\n aFmtCol.SetLineHeight((BYTE)nPercent);\n}\n\/*------------------------------------------------------------------------\n Beschreibung: Spaltenbreite\n------------------------------------------------------------------------*\/\n\n\n\nUSHORT SwColMgr::GetColWidth(USHORT nIdx) const\n{\n ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);\n return aFmtCol.CalcPrtColWidth(nIdx, nWidth);\n}\n\n\n\nvoid SwColMgr::SetColWidth(USHORT nIdx, USHORT nWd)\n{\n ASSERT(nIdx < GetCount(), Spaltenarray ueberindiziert.);\n aFmtCol.GetColumns()[nIdx]->SetWishWidth(nWd);\n\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Groesse neu setzen\n --------------------------------------------------------------------*\/\n\n\n\nvoid SwColMgr::SetActualWidth(USHORT nW)\n{\n nWidth = nW;\n ::FitToActualSize(aFmtCol, nW);\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: ctor\n --------------------------------------------------------------------*\/\n\n\n\nSwColMgr::SwColMgr(const SfxItemSet& rSet, USHORT nActWidth) :\n aFmtCol((const SwFmtCol&)rSet.Get(RES_COL)),\n nWidth(nActWidth)\n{\n if(nWidth == USHRT_MAX)\n {\n nWidth = (USHORT)((const SwFmtFrmSize&)rSet.Get(RES_FRM_SIZE)).GetWidth();\n if (nWidth < MINLAY)\n nWidth = USHRT_MAX;\n const SvxLRSpaceItem &rLR = (const SvxLRSpaceItem&)rSet.Get(RES_LR_SPACE);\n nWidth = nWidth - (USHORT)rLR.GetLeft();\n nWidth = nWidth - (USHORT)rLR.GetRight();\n }\n ::FitToActualSize(aFmtCol, nWidth);\n}\n\n\n\n\nSwColMgr::~SwColMgr() {}\n\n\n\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: bookmark.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: os $ $Date: 2002-12-05 12:45:04 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n\n\n#include \"view.hxx\"\n#include \"basesh.hxx\"\n#include \"wrtsh.hxx\" \/\/\n#include \"cmdid.h\"\n#include \"bookmark.hxx\" \/\/ SwInsertBookmarkDlg\n#include \"bookmrk.hxx\" \/\/ SwBookmark\n#include \"bookmark.hrc\"\n#include \"misc.hrc\"\n\n\nconst String BookmarkCombo::aForbiddenChars = String::CreateFromAscii(\"\/\\\\@:*?\\\";,.#\");\n\n\nIMPL_LINK( SwInsertBookmarkDlg, ModifyHdl, BookmarkCombo *, pBox )\n{\n BOOL bSelEntries = pBox->GetSelectEntryCount() != 0;\n \/\/ if a string has been pasted from the clipboard then\n \/\/ there may be illegal characters in the box\n if(!bSelEntries)\n {\n String sTmp = pBox->GetText();\n USHORT nLen = sTmp.Len();\n String sMsg;\n for(USHORT i = 0; i < BookmarkCombo::aForbiddenChars.Len(); i++)\n {\n USHORT nTmpLen = sTmp.Len();\n sTmp.EraseAllChars(BookmarkCombo::aForbiddenChars.GetChar(i));\n if(sTmp.Len() != nTmpLen)\n sMsg += BookmarkCombo::aForbiddenChars.GetChar(i);\n }\n if(sTmp.Len() != nLen)\n {\n pBox->SetText(sTmp);\n String sWarning(sRemoveWarning);\n sWarning += sMsg;\n InfoBox(this, sWarning).Execute();\n }\n\n\n }\n\n aOkBtn.Enable(!bSelEntries); \/\/ neue Textmarke\n aDeleteBtn.Enable(bSelEntries); \/\/ loeschbar?\n\n return 0;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Callback zum Loeschen einer Textmarke\n -----------------------------------------------------------------------*\/\n\nIMPL_LINK( SwInsertBookmarkDlg, DeleteHdl, Button *, EMPTYARG )\n{\n \/\/ Textmarken aus der ComboBox entfernen\n\n for (USHORT i = aBookmarkBox.GetSelectEntryCount(); i; i-- )\n aBookmarkBox.RemoveEntry(aBookmarkBox.GetSelectEntryPos(i - 1));\n\n aBookmarkBox.SetText(aEmptyStr);\n aDeleteBtn.Enable(FALSE); \/\/ keine weiteren Eintraege vorhanden\n \/\/ aBookmarkBox.SetText(aEmptyStr);\n\n aOkBtn.Enable(); \/\/ Im OK Handler wird geloescht\n return 0;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Callback fuer OKButton. Fuegt eine neue Textmarke\n an die akt. Position ein. Geloeschte Textmarken werden auch am Modell\n entfernt.\n -----------------------------------------------------------------------*\/\n\n\nvoid SwInsertBookmarkDlg::Apply()\n{\n \/\/ Textmarke einfuegen\n USHORT nLen = aBookmarkBox.GetText().Len();\n SwBoxEntry aTmpEntry(aBookmarkBox.GetText(), 0 );\n\n if ( nLen && (aBookmarkBox.GetEntryPos(aTmpEntry) == COMBOBOX_ENTRY_NOTFOUND) )\n {\n String sEntry(aBookmarkBox.GetText());\n sEntry.EraseAllChars(aBookmarkBox.GetMultiSelectionSeparator());\n\n rSh.SetBookmark( KeyCode(), sEntry, aEmptyStr );\n rReq.AppendItem( SfxStringItem( FN_INSERT_BOOKMARK, sEntry ) );\n rReq.Done();\n }\n\n if ( !rReq.IsDone() )\n rReq.Ignore();\n\n for (USHORT nCount = aBookmarkBox.GetRemovedCount(); nCount > 0; nCount--)\n {\n String sRemoved = aBookmarkBox.GetRemovedEntry( nCount -1 ).aName;\n rSh.DelBookmark( sRemoved );\n SfxRequest aReq( rSh.GetView().GetViewFrame(), FN_DELETE_BOOKMARK );\n aReq.AppendItem( SfxStringItem( FN_DELETE_BOOKMARK, sRemoved ) );\n aReq.Done();\n }\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: CTOR\n -----------------------------------------------------------------------*\/\n\n\nSwInsertBookmarkDlg::SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rS, SfxRequest& rRequest ) :\n\n SvxStandardDialog(pParent,SW_RES(DLG_INSERT_BOOKMARK)),\n\n aBookmarkBox(this,SW_RES(CB_BOOKMARK)),\n aBookmarkFl(this,SW_RES(FL_BOOKMARK)),\n aOkBtn(this,SW_RES(BT_OK)),\n aCancelBtn(this,SW_RES(BT_CANCEL)),\n aDeleteBtn(this,SW_RES(BT_DELETE)),\n rSh( rS ),\n rReq( rRequest )\n{\n aBookmarkBox.SetModifyHdl(LINK(this, SwInsertBookmarkDlg, ModifyHdl));\n aBookmarkBox.EnableMultiSelection(TRUE);\n aBookmarkBox.EnableAutocomplete( TRUE, TRUE );\n\n aDeleteBtn.SetClickHdl(LINK(this, SwInsertBookmarkDlg, DeleteHdl));\n\n \/\/ Combobox mit vorhandenen Bookmarks fuellen\n USHORT nCount = rSh.GetBookmarkCnt(TRUE);\n\n for( USHORT nId = 0; nId < nCount; nId++ )\n {\n SwBookmark& rBkmk = rSh.GetBookmark( nId, TRUE );\n aBookmarkBox.InsertEntry( SwBoxEntry( rBkmk.GetName(), nId ) );\n }\n\n FreeResource();\n sRemoveWarning = String(SW_RES(STR_REMOVE_WARNING));\n\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nSwInsertBookmarkDlg::~SwInsertBookmarkDlg()\n{\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nBookmarkCombo::BookmarkCombo( Window* pWin, const ResId& rResId ) :\n SwComboBox(pWin, rResId)\n{\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetFirstSelEntryPos() const\n{\n return GetSelEntryPos(0);\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetNextSelEntryPos(USHORT nPos) const\n{\n return GetSelEntryPos(nPos + 1);\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetSelEntryPos(USHORT nPos) const\n{\n char cSep = GetMultiSelectionSeparator();\n\n USHORT nCnt = GetText().GetTokenCount(cSep);\n\n for (; nPos < nCnt; nPos++)\n {\n String sEntry(GetText().GetToken(nPos, cSep));\n sEntry.EraseLeadingChars();\n sEntry.EraseTrailingChars();\n if (GetEntryPos(sEntry) != COMBOBOX_ENTRY_NOTFOUND)\n return nPos;\n }\n\n return COMBOBOX_ENTRY_NOTFOUND;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetSelectEntryCount() const\n{\n USHORT nCnt = 0;\n\n USHORT nPos = GetFirstSelEntryPos();\n while (nPos != COMBOBOX_ENTRY_NOTFOUND)\n {\n nPos = GetNextSelEntryPos(nPos);\n nCnt++;\n }\n\n return nCnt;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nString BookmarkCombo::GetSelectEntry( USHORT nSelIndex ) const\n{\n USHORT nCnt = 0;\n USHORT nPos = GetFirstSelEntryPos();\n String sEntry;\n\n while (nPos != COMBOBOX_ENTRY_NOTFOUND)\n {\n if (nSelIndex == nCnt)\n {\n char cSep = GetMultiSelectionSeparator();\n sEntry = GetText().GetToken(nPos, cSep);\n sEntry.EraseLeadingChars();\n sEntry.EraseTrailingChars();\n\n break;\n }\n nPos = GetNextSelEntryPos(nPos);\n nCnt++;\n }\n\n return sEntry;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Position in der Listbox (der ComboBox)\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetSelectEntryPos( USHORT nSelIndex ) const\n{\n USHORT nCnt = 0;\n USHORT nPos = GetFirstSelEntryPos();\n\n while (nPos != COMBOBOX_ENTRY_NOTFOUND)\n {\n if (nSelIndex == nCnt)\n {\n char cSep = GetMultiSelectionSeparator();\n String sEntry(GetText().GetToken(nPos, cSep));\n sEntry.EraseLeadingChars();\n sEntry.EraseTrailingChars();\n\n return GetEntryPos(sEntry);\n }\n nPos = GetNextSelEntryPos(nPos);\n nCnt++;\n }\n\n return COMBOBOX_ENTRY_NOTFOUND;\n}\n\/* -----------------05.02.99 08:39-------------------\n *\n * --------------------------------------------------*\/\nlong BookmarkCombo::PreNotify( NotifyEvent& rNEvt )\n{\n long nHandled = 0;\n if( EVENT_KEYINPUT == rNEvt.GetType() &&\n rNEvt.GetKeyEvent()->GetCharCode() )\n {\n String sKey( rNEvt.GetKeyEvent()->GetCharCode() );\n if(STRING_NOTFOUND != aForbiddenChars.Search(sKey))\n nHandled = 1;\n }\n if(!nHandled)\n nHandled = SwComboBox::PreNotify( rNEvt );\n return nHandled;\n}\n\n\n\nINTEGRATION: CWS os8 (1.5.138); FILE MERGED 2003\/04\/03 07:14:39 os 1.5.138.1: #108583# precompiled headers removed\/*************************************************************************\n *\n * $RCSfile: bookmark.cxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: vg $ $Date: 2003-04-17 15:35:10 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#ifndef _SFXREQUEST_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSTRITEM_HXX \/\/autogen\n#include \n#endif\n\n#ifndef _SV_MSGBOX_HXX \/\/autogen\n#include \n#endif\n\n\n#include \"view.hxx\"\n#include \"basesh.hxx\"\n#include \"wrtsh.hxx\" \/\/\n#include \"cmdid.h\"\n#include \"bookmark.hxx\" \/\/ SwInsertBookmarkDlg\n#include \"bookmrk.hxx\" \/\/ SwBookmark\n#include \"bookmark.hrc\"\n#include \"misc.hrc\"\n\n\nconst String BookmarkCombo::aForbiddenChars = String::CreateFromAscii(\"\/\\\\@:*?\\\";,.#\");\n\n\nIMPL_LINK( SwInsertBookmarkDlg, ModifyHdl, BookmarkCombo *, pBox )\n{\n BOOL bSelEntries = pBox->GetSelectEntryCount() != 0;\n \/\/ if a string has been pasted from the clipboard then\n \/\/ there may be illegal characters in the box\n if(!bSelEntries)\n {\n String sTmp = pBox->GetText();\n USHORT nLen = sTmp.Len();\n String sMsg;\n for(USHORT i = 0; i < BookmarkCombo::aForbiddenChars.Len(); i++)\n {\n USHORT nTmpLen = sTmp.Len();\n sTmp.EraseAllChars(BookmarkCombo::aForbiddenChars.GetChar(i));\n if(sTmp.Len() != nTmpLen)\n sMsg += BookmarkCombo::aForbiddenChars.GetChar(i);\n }\n if(sTmp.Len() != nLen)\n {\n pBox->SetText(sTmp);\n String sWarning(sRemoveWarning);\n sWarning += sMsg;\n InfoBox(this, sWarning).Execute();\n }\n\n\n }\n\n aOkBtn.Enable(!bSelEntries); \/\/ neue Textmarke\n aDeleteBtn.Enable(bSelEntries); \/\/ loeschbar?\n\n return 0;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Callback zum Loeschen einer Textmarke\n -----------------------------------------------------------------------*\/\n\nIMPL_LINK( SwInsertBookmarkDlg, DeleteHdl, Button *, EMPTYARG )\n{\n \/\/ Textmarken aus der ComboBox entfernen\n\n for (USHORT i = aBookmarkBox.GetSelectEntryCount(); i; i-- )\n aBookmarkBox.RemoveEntry(aBookmarkBox.GetSelectEntryPos(i - 1));\n\n aBookmarkBox.SetText(aEmptyStr);\n aDeleteBtn.Enable(FALSE); \/\/ keine weiteren Eintraege vorhanden\n \/\/ aBookmarkBox.SetText(aEmptyStr);\n\n aOkBtn.Enable(); \/\/ Im OK Handler wird geloescht\n return 0;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Callback fuer OKButton. Fuegt eine neue Textmarke\n an die akt. Position ein. Geloeschte Textmarken werden auch am Modell\n entfernt.\n -----------------------------------------------------------------------*\/\n\n\nvoid SwInsertBookmarkDlg::Apply()\n{\n \/\/ Textmarke einfuegen\n USHORT nLen = aBookmarkBox.GetText().Len();\n SwBoxEntry aTmpEntry(aBookmarkBox.GetText(), 0 );\n\n if ( nLen && (aBookmarkBox.GetEntryPos(aTmpEntry) == COMBOBOX_ENTRY_NOTFOUND) )\n {\n String sEntry(aBookmarkBox.GetText());\n sEntry.EraseAllChars(aBookmarkBox.GetMultiSelectionSeparator());\n\n rSh.SetBookmark( KeyCode(), sEntry, aEmptyStr );\n rReq.AppendItem( SfxStringItem( FN_INSERT_BOOKMARK, sEntry ) );\n rReq.Done();\n }\n\n if ( !rReq.IsDone() )\n rReq.Ignore();\n\n for (USHORT nCount = aBookmarkBox.GetRemovedCount(); nCount > 0; nCount--)\n {\n String sRemoved = aBookmarkBox.GetRemovedEntry( nCount -1 ).aName;\n rSh.DelBookmark( sRemoved );\n SfxRequest aReq( rSh.GetView().GetViewFrame(), FN_DELETE_BOOKMARK );\n aReq.AppendItem( SfxStringItem( FN_DELETE_BOOKMARK, sRemoved ) );\n aReq.Done();\n }\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: CTOR\n -----------------------------------------------------------------------*\/\n\n\nSwInsertBookmarkDlg::SwInsertBookmarkDlg( Window *pParent, SwWrtShell &rS, SfxRequest& rRequest ) :\n\n SvxStandardDialog(pParent,SW_RES(DLG_INSERT_BOOKMARK)),\n\n aBookmarkBox(this,SW_RES(CB_BOOKMARK)),\n aBookmarkFl(this,SW_RES(FL_BOOKMARK)),\n aOkBtn(this,SW_RES(BT_OK)),\n aCancelBtn(this,SW_RES(BT_CANCEL)),\n aDeleteBtn(this,SW_RES(BT_DELETE)),\n rSh( rS ),\n rReq( rRequest )\n{\n aBookmarkBox.SetModifyHdl(LINK(this, SwInsertBookmarkDlg, ModifyHdl));\n aBookmarkBox.EnableMultiSelection(TRUE);\n aBookmarkBox.EnableAutocomplete( TRUE, TRUE );\n\n aDeleteBtn.SetClickHdl(LINK(this, SwInsertBookmarkDlg, DeleteHdl));\n\n \/\/ Combobox mit vorhandenen Bookmarks fuellen\n USHORT nCount = rSh.GetBookmarkCnt(TRUE);\n\n for( USHORT nId = 0; nId < nCount; nId++ )\n {\n SwBookmark& rBkmk = rSh.GetBookmark( nId, TRUE );\n aBookmarkBox.InsertEntry( SwBoxEntry( rBkmk.GetName(), nId ) );\n }\n\n FreeResource();\n sRemoveWarning = String(SW_RES(STR_REMOVE_WARNING));\n\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nSwInsertBookmarkDlg::~SwInsertBookmarkDlg()\n{\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nBookmarkCombo::BookmarkCombo( Window* pWin, const ResId& rResId ) :\n SwComboBox(pWin, rResId)\n{\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetFirstSelEntryPos() const\n{\n return GetSelEntryPos(0);\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetNextSelEntryPos(USHORT nPos) const\n{\n return GetSelEntryPos(nPos + 1);\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetSelEntryPos(USHORT nPos) const\n{\n char cSep = GetMultiSelectionSeparator();\n\n USHORT nCnt = GetText().GetTokenCount(cSep);\n\n for (; nPos < nCnt; nPos++)\n {\n String sEntry(GetText().GetToken(nPos, cSep));\n sEntry.EraseLeadingChars();\n sEntry.EraseTrailingChars();\n if (GetEntryPos(sEntry) != COMBOBOX_ENTRY_NOTFOUND)\n return nPos;\n }\n\n return COMBOBOX_ENTRY_NOTFOUND;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetSelectEntryCount() const\n{\n USHORT nCnt = 0;\n\n USHORT nPos = GetFirstSelEntryPos();\n while (nPos != COMBOBOX_ENTRY_NOTFOUND)\n {\n nPos = GetNextSelEntryPos(nPos);\n nCnt++;\n }\n\n return nCnt;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung:\n -----------------------------------------------------------------------*\/\n\nString BookmarkCombo::GetSelectEntry( USHORT nSelIndex ) const\n{\n USHORT nCnt = 0;\n USHORT nPos = GetFirstSelEntryPos();\n String sEntry;\n\n while (nPos != COMBOBOX_ENTRY_NOTFOUND)\n {\n if (nSelIndex == nCnt)\n {\n char cSep = GetMultiSelectionSeparator();\n sEntry = GetText().GetToken(nPos, cSep);\n sEntry.EraseLeadingChars();\n sEntry.EraseTrailingChars();\n\n break;\n }\n nPos = GetNextSelEntryPos(nPos);\n nCnt++;\n }\n\n return sEntry;\n}\n\n\/*------------------------------------------------------------------------\n Beschreibung: Position in der Listbox (der ComboBox)\n -----------------------------------------------------------------------*\/\n\nUSHORT BookmarkCombo::GetSelectEntryPos( USHORT nSelIndex ) const\n{\n USHORT nCnt = 0;\n USHORT nPos = GetFirstSelEntryPos();\n\n while (nPos != COMBOBOX_ENTRY_NOTFOUND)\n {\n if (nSelIndex == nCnt)\n {\n char cSep = GetMultiSelectionSeparator();\n String sEntry(GetText().GetToken(nPos, cSep));\n sEntry.EraseLeadingChars();\n sEntry.EraseTrailingChars();\n\n return GetEntryPos(sEntry);\n }\n nPos = GetNextSelEntryPos(nPos);\n nCnt++;\n }\n\n return COMBOBOX_ENTRY_NOTFOUND;\n}\n\/* -----------------05.02.99 08:39-------------------\n *\n * --------------------------------------------------*\/\nlong BookmarkCombo::PreNotify( NotifyEvent& rNEvt )\n{\n long nHandled = 0;\n if( EVENT_KEYINPUT == rNEvt.GetType() &&\n rNEvt.GetKeyEvent()->GetCharCode() )\n {\n String sKey( rNEvt.GetKeyEvent()->GetCharCode() );\n if(STRING_NOTFOUND != aForbiddenChars.Search(sKey))\n nHandled = 1;\n }\n if(!nHandled)\n nHandled = SwComboBox::PreNotify( rNEvt );\n return nHandled;\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: tbxmgr.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: obo $ $Date: 2004-07-06 11:33:21 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"cmdid.h\"\n#include \"swtypes.hxx\" \/\/ nur wegen aEmptyString??\n#include \"errhdl.hxx\"\n#include \"wdocsh.hxx\"\n#include \"tbxmgr.hxx\"\n\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\n\/*\nSwPopupWindowTbxMgr::SwPopupWindowTbxMgr( USHORT nId, WindowAlign eAlign,\n ResId aRIdWin, ResId aRIdTbx,\n SfxBindings& rBindings ) :\n SvxPopupWindowTbxMgr( nId, eAlign, aRIdWin, aRIdTbx ),\n bWeb(FALSE),\n aRIdWinTemp(aRIdWin),\n aRIdTbxTemp(aRIdTbx),\n eAlignment( eAlign ),\n mrBindings( rBindings )\n{\n SfxObjectShell* pObjShell = SfxObjectShell::Current();\n if(PTR_CAST(SwWebDocShell, pObjShell))\n {\n bWeb = TRUE;\n ToolBox& rTbx = GetTbxMgr().GetToolBox();\n \/\/ jetzt muessen ein paar Items aus der Toolbox versteckt werden:\n switch(nId)\n {\n case FN_INSERT_CTRL:\n rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n rTbx.HideItem(FN_INSERT_FRAME_INTERACT);\n rTbx.HideItem(FN_INSERT_FOOTNOTE);\n rTbx.HideItem(FN_INSERT_ENDNOTE);\n rTbx.HideItem(FN_PAGE_STYLE_SET_COLS);\n rTbx.HideItem(FN_INSERT_IDX_ENTRY_DLG);\n\n break;\n case FN_INSERT_FIELD_CTRL:\n rTbx.HideItem(FN_INSERT_FLD_PGNUMBER);\n rTbx.HideItem(FN_INSERT_FLD_PGCOUNT);\n rTbx.HideItem(FN_INSERT_FLD_TOPIC);\n rTbx.HideItem(FN_INSERT_FLD_TITLE);\n break;\n }\n }\n else if( FN_INSERT_CTRL == nId)\n {\n ToolBox& rTbx = GetTbxMgr().GetToolBox();\n rTbx.ShowItem(FN_INSERT_FRAME_INTERACT);\n rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n }\n\n Size aSize = GetTbxMgr().CalcWindowSizePixel();\n GetTbxMgr().SetPosSizePixel( Point(), aSize );\n SetOutputSizePixel( aSize );\n}\n*\/\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\n\/*\nvoid SwPopupWindowTbxMgr::StateChanged(USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState)\n{\n static USHORT __READONLY_DATA aInsertCtrl[] =\n {\n FN_INSERT_FRAME_INTERACT,\n FN_INSERT_FOOTNOTE,\n FN_INSERT_ENDNOTE,\n FN_PAGE_STYLE_SET_COLS,\n FN_INSERT_IDX_ENTRY_DLG,\n 0\n };\n static USHORT __READONLY_DATA aInsertFld[] =\n {\n FN_INSERT_FLD_PGNUMBER,\n FN_INSERT_FLD_PGCOUNT,\n FN_INSERT_FLD_TOPIC,\n FN_INSERT_FLD_TITLE,\n 0\n };\n\n SfxObjectShell* pObjShell = SfxObjectShell::Current();\n BOOL bNewWeb = 0 != PTR_CAST(SwWebDocShell, pObjShell);\n\n if(bWeb != bNewWeb)\n {\n bWeb = bNewWeb;\n ToolBox& rTbx = GetTbxMgr().GetToolBox();\n \/\/ jetzt muessen ein paar Items aus der Toolbox versteckt werden:\n const USHORT* pSid = 0;\n\n switch(nSID)\n {\n case FN_INSERT_CTRL:\n pSid = &aInsertCtrl[0];\n if(bWeb)\n rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n else\n rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n break;\n case FN_INSERT_FIELD_CTRL:\n pSid = & aInsertFld[0];\n break;\n }\n if(pSid)\n {\n if(bWeb)\n while(*pSid)\n {\n rTbx.HideItem(*pSid);\n pSid++;\n }\n else\n while(*pSid)\n {\n rTbx.ShowItem(*pSid);\n pSid++;\n }\n Size aSize = GetTbxMgr().CalcWindowSizePixel();\n GetTbxMgr().SetPosSizePixel( Point(), aSize );\n SetOutputSizePixel( aSize );\n }\n }\n\n SfxPopupWindow::StateChanged(nSID, eState, pState);\n}\n*\/\n\/*\nSfxPopupWindow* SwPopupWindowTbxMgr::Clone() const\n{\n return new SwPopupWindowTbxMgr(\n GetId(),\n eAlignment,\n\/\/ ((SwPopupWindowTbxMgr*)this)->GetTbxMgr().GetToolBox().GetAlign(),\n aRIdWinTemp,\n aRIdTbxTemp,\n mrBindings\n\/\/ (SfxBindings&)GetBindings()\n );\n}\n*\/\n\nINTEGRATION: CWS ooo19126 (1.4.692); FILE MERGED 2005\/09\/05 13:47:07 rt 1.4.692.1: #i54170# Change license header: remove SISSL\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tbxmgr.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-09 10:47:20 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"cmdid.h\"\n#include \"swtypes.hxx\" \/\/ nur wegen aEmptyString??\n#include \"errhdl.hxx\"\n#include \"wdocsh.hxx\"\n#include \"tbxmgr.hxx\"\n\n\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\n\/*\nSwPopupWindowTbxMgr::SwPopupWindowTbxMgr( USHORT nId, WindowAlign eAlign,\n ResId aRIdWin, ResId aRIdTbx,\n SfxBindings& rBindings ) :\n SvxPopupWindowTbxMgr( nId, eAlign, aRIdWin, aRIdTbx ),\n bWeb(FALSE),\n aRIdWinTemp(aRIdWin),\n aRIdTbxTemp(aRIdTbx),\n eAlignment( eAlign ),\n mrBindings( rBindings )\n{\n SfxObjectShell* pObjShell = SfxObjectShell::Current();\n if(PTR_CAST(SwWebDocShell, pObjShell))\n {\n bWeb = TRUE;\n ToolBox& rTbx = GetTbxMgr().GetToolBox();\n \/\/ jetzt muessen ein paar Items aus der Toolbox versteckt werden:\n switch(nId)\n {\n case FN_INSERT_CTRL:\n rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n rTbx.HideItem(FN_INSERT_FRAME_INTERACT);\n rTbx.HideItem(FN_INSERT_FOOTNOTE);\n rTbx.HideItem(FN_INSERT_ENDNOTE);\n rTbx.HideItem(FN_PAGE_STYLE_SET_COLS);\n rTbx.HideItem(FN_INSERT_IDX_ENTRY_DLG);\n\n break;\n case FN_INSERT_FIELD_CTRL:\n rTbx.HideItem(FN_INSERT_FLD_PGNUMBER);\n rTbx.HideItem(FN_INSERT_FLD_PGCOUNT);\n rTbx.HideItem(FN_INSERT_FLD_TOPIC);\n rTbx.HideItem(FN_INSERT_FLD_TITLE);\n break;\n }\n }\n else if( FN_INSERT_CTRL == nId)\n {\n ToolBox& rTbx = GetTbxMgr().GetToolBox();\n rTbx.ShowItem(FN_INSERT_FRAME_INTERACT);\n rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n }\n\n Size aSize = GetTbxMgr().CalcWindowSizePixel();\n GetTbxMgr().SetPosSizePixel( Point(), aSize );\n SetOutputSizePixel( aSize );\n}\n*\/\n\/*************************************************************************\n|*\n|*\n|*\n\\************************************************************************\/\n\/*\nvoid SwPopupWindowTbxMgr::StateChanged(USHORT nSID, SfxItemState eState,\n const SfxPoolItem* pState)\n{\n static USHORT __READONLY_DATA aInsertCtrl[] =\n {\n FN_INSERT_FRAME_INTERACT,\n FN_INSERT_FOOTNOTE,\n FN_INSERT_ENDNOTE,\n FN_PAGE_STYLE_SET_COLS,\n FN_INSERT_IDX_ENTRY_DLG,\n 0\n };\n static USHORT __READONLY_DATA aInsertFld[] =\n {\n FN_INSERT_FLD_PGNUMBER,\n FN_INSERT_FLD_PGCOUNT,\n FN_INSERT_FLD_TOPIC,\n FN_INSERT_FLD_TITLE,\n 0\n };\n\n SfxObjectShell* pObjShell = SfxObjectShell::Current();\n BOOL bNewWeb = 0 != PTR_CAST(SwWebDocShell, pObjShell);\n\n if(bWeb != bNewWeb)\n {\n bWeb = bNewWeb;\n ToolBox& rTbx = GetTbxMgr().GetToolBox();\n \/\/ jetzt muessen ein paar Items aus der Toolbox versteckt werden:\n const USHORT* pSid = 0;\n\n switch(nSID)\n {\n case FN_INSERT_CTRL:\n pSid = &aInsertCtrl[0];\n if(bWeb)\n rTbx.ShowItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n else\n rTbx.HideItem(FN_INSERT_FRAME_INTERACT_NOCOL);\n break;\n case FN_INSERT_FIELD_CTRL:\n pSid = & aInsertFld[0];\n break;\n }\n if(pSid)\n {\n if(bWeb)\n while(*pSid)\n {\n rTbx.HideItem(*pSid);\n pSid++;\n }\n else\n while(*pSid)\n {\n rTbx.ShowItem(*pSid);\n pSid++;\n }\n Size aSize = GetTbxMgr().CalcWindowSizePixel();\n GetTbxMgr().SetPosSizePixel( Point(), aSize );\n SetOutputSizePixel( aSize );\n }\n }\n\n SfxPopupWindow::StateChanged(nSID, eState, pState);\n}\n*\/\n\/*\nSfxPopupWindow* SwPopupWindowTbxMgr::Clone() const\n{\n return new SwPopupWindowTbxMgr(\n GetId(),\n eAlignment,\n\/\/ ((SwPopupWindowTbxMgr*)this)->GetTbxMgr().GetToolBox().GetAlign(),\n aRIdWinTemp,\n aRIdTbxTemp,\n mrBindings\n\/\/ (SfxBindings&)GetBindings()\n );\n}\n*\/\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: uiitems.cxx,v $\n *\n * $Revision: 1.11 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 12:49:33 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SVX_ITEMTYPE_HXX\n#include \n#endif\n#ifndef _UNOSETT_HXX\n#include \n#endif\n\n#include \"swtypes.hxx\"\n#include \"cmdid.h\"\n#include \"pagedesc.hxx\"\n#include \"uiitems.hxx\"\n\n#include \"utlui.hrc\"\n#include \"attrdesc.hrc\"\n#ifndef _UNOMID_H\n#include \n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\n\/\/ Breitenangaben der Fussnotenlinien, mit TabPage abstimmen\nstatic const USHORT __FAR_DATA nFtnLines[] = {\n 0,\n 10,\n 50,\n 80,\n 100,\n 150\n};\n\n#define FTN_LINE_STYLE_COUNT 5\n\n\nSwPageFtnInfoItem::SwPageFtnInfoItem( const USHORT nId, SwPageFtnInfo& rInfo) :\n SfxPoolItem( nId ),\n aFtnInfo(rInfo)\n{\n}\n\n\nSwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :\n SfxPoolItem( rItem ),\n aFtnInfo(rItem.GetPageFtnInfo())\n{\n}\n\n\n SwPageFtnInfoItem::~SwPageFtnInfoItem()\n{\n}\n\n\nSfxPoolItem* SwPageFtnInfoItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwPageFtnInfoItem( *this );\n}\n\n\nint SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( Which() == rAttr.Which(), \"keine gleichen Attribute\" );\n return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());\n}\n\n\nSfxItemPresentation SwPageFtnInfoItem::GetPresentation\n(\n SfxItemPresentation ePres,\n SfxMapUnit eCoreUnit,\n SfxMapUnit ePresUnit,\n String& rText,\n const IntlWrapper* pIntl\n) const\n{\n switch ( ePres )\n {\n case SFX_ITEM_PRESENTATION_NONE:\n rText.Erase();\n return SFX_ITEM_PRESENTATION_NONE;\n case SFX_ITEM_PRESENTATION_NAMELESS:\n case SFX_ITEM_PRESENTATION_COMPLETE:\n {\n USHORT nHght = (USHORT) GetPageFtnInfo().GetHeight();\n if ( nHght )\n {\n rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );\n rText += ' ';\n rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );\n rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );\n }\n return ePres;\n }\n default:; \/\/prevent warning\n }\n return SFX_ITEM_PRESENTATION_NONE;\n}\n\/* -----------------------------26.04.01 12:25--------------------------------\n\n ---------------------------------------------------------------------------*\/\nBOOL SwPageFtnInfoItem::QueryValue( Any& rVal, BYTE nMemberId ) const\n{\n sal_Bool bRet = sal_True;\n switch(nMemberId & ~CONVERT_TWIPS)\n {\n case MID_FTN_HEIGHT : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;\n case MID_LINE_WEIGHT : rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;\n case MID_LINE_COLOR : rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;\n case MID_LINE_RELWIDTH :\n {\n Fraction aTmp( 100, 1 );\n aTmp *= aFtnInfo.GetWidth();\n rVal <<= (sal_Int8)(long)aTmp;\n }\n break;\n case MID_LINE_ADJUST : rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;\/\/text::HorizontalAdjust\n case MID_LINE_TEXT_DIST : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;\n case MID_LINE_FOOTNOTE_DIST: rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;\n default:\n bRet = sal_False;\n }\n return bRet;\n}\n\/* -----------------------------26.04.01 12:26--------------------------------\n\n ---------------------------------------------------------------------------*\/\nBOOL SwPageFtnInfoItem::PutValue(const Any& rVal, BYTE nMemberId)\n{\n sal_Int32 nSet32;\n sal_Bool bRet = sal_True;\n switch(nMemberId & ~CONVERT_TWIPS)\n {\n case MID_LINE_COLOR :\n rVal >>= nSet32;\n aFtnInfo.SetLineColor(nSet32);\n break;\n case MID_FTN_HEIGHT:\n case MID_LINE_TEXT_DIST :\n case MID_LINE_FOOTNOTE_DIST:\n rVal >>= nSet32;\n if(nSet32 < 0)\n bRet = sal_False;\n else\n {\n nSet32 = MM100_TO_TWIP(nSet32);\n switch(nMemberId & ~CONVERT_TWIPS)\n {\n case MID_FTN_HEIGHT: aFtnInfo.SetHeight(nSet32); break;\n case MID_LINE_TEXT_DIST: aFtnInfo.SetTopDist(nSet32);break;\n case MID_LINE_FOOTNOTE_DIST: aFtnInfo.SetBottomDist(nSet32);break;\n }\n }\n break;\n case MID_LINE_WEIGHT :\n {\n sal_Int16 nSet; rVal >>= nSet;\n if(nSet >= 0)\n aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));\n else\n bRet = sal_False;\n }\n break;\n case MID_LINE_RELWIDTH :\n {\n sal_Int8 nSet; rVal >>= nSet;\n if(nSet < 0)\n bRet = sal_False;\n else\n aFtnInfo.SetWidth(Fraction(nSet, 100));\n }\n break;\n case MID_LINE_ADJUST :\n {\n sal_Int16 nSet; rVal >>= nSet;\n if(nSet >= 0 && nSet < 3) \/\/text::HorizontalAdjust\n aFtnInfo.SetAdj((SwFtnAdj)nSet);\n else\n bRet = sal_False;\n }\n break;\n default:\n bRet = sal_False;\n }\n return bRet;\n}\n\nSwPtrItem::SwPtrItem( const USHORT nId, void* pPtr ) :\n SfxPoolItem( nId ),\n pMisc(pPtr)\n{\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Copy-Konstruktor\n --------------------------------------------------------------------*\/\n\n\nSwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )\n{\n pMisc = rItem.pMisc;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Clonen\n --------------------------------------------------------------------*\/\n\n\nSfxPoolItem* SwPtrItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwPtrItem( *this );\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\n\nint SwPtrItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n const SwPtrItem& rItem = (SwPtrItem&)rAttr;\n return ( pMisc == rItem.pMisc );\n}\n\n\n\/*-----------------12.11.97 12:55-------------------------------\n SwUINumRuleItem fuer die NumTabPages der FormatNumRule\/Stylisten\n---------------------------------------------------------------*\/\nSwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const USHORT nId )\n : SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )\n{\n}\n\nSwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )\n : SfxPoolItem( rItem ),\n pRule( new SwNumRule( *rItem.pRule ))\n{\n}\n\n SwUINumRuleItem::~SwUINumRuleItem()\n{\n delete pRule;\n}\n\n\nSfxPoolItem* SwUINumRuleItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwUINumRuleItem( *this );\n}\n\nint SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n return *pRule == *((SwUINumRuleItem&)rAttr).pRule;\n}\n\nBOOL SwUINumRuleItem::QueryValue( uno::Any& rVal, BYTE \/*nMemberId*\/ ) const\n{\n uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);\n rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));\n return TRUE;\n}\nBOOL SwUINumRuleItem::PutValue( const uno::Any& rVal, BYTE \/*nMemberId*\/ )\n{\n uno::Reference< container::XIndexReplace> xRulesRef;\n if(rVal >>= xRulesRef)\n {\n uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);\n SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast(\n xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;\n if(pSwXRules)\n {\n *pRule = *pSwXRules->GetNumRule();\n }\n }\n return TRUE;\n}\n\/* -----------------17.06.98 17:43-------------------\n *\n * --------------------------------------------------*\/\nSwBackgroundDestinationItem::SwBackgroundDestinationItem(USHORT _nWhich, USHORT nValue) :\n SfxUInt16Item(_nWhich, nValue)\n{\n}\n\/* -----------------17.06.98 17:44-------------------\n *\n * --------------------------------------------------*\/\nSfxPoolItem* SwBackgroundDestinationItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwBackgroundDestinationItem(Which(), GetValue());\n}\n\n\n\nINTEGRATION: CWS pj86 (1.11.4); FILE MERGED 2007\/09\/28 21:36:50 pjanik 1.11.4.1: #i81574#: Initialize variable(s) to prevent warnings on Mac OS X with gcc-4.0.1.\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: uiitems.cxx,v $\n *\n * $Revision: 1.12 $\n *\n * last change: $Author: rt $ $Date: 2007-11-12 16:33:40 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SVX_ITEMTYPE_HXX\n#include \n#endif\n#ifndef _UNOSETT_HXX\n#include \n#endif\n\n#include \"swtypes.hxx\"\n#include \"cmdid.h\"\n#include \"pagedesc.hxx\"\n#include \"uiitems.hxx\"\n\n#include \"utlui.hrc\"\n#include \"attrdesc.hrc\"\n#ifndef _UNOMID_H\n#include \n#endif\n\nusing namespace ::com::sun::star;\nusing namespace ::com::sun::star::uno;\n\n\/\/ Breitenangaben der Fussnotenlinien, mit TabPage abstimmen\nstatic const USHORT __FAR_DATA nFtnLines[] = {\n 0,\n 10,\n 50,\n 80,\n 100,\n 150\n};\n\n#define FTN_LINE_STYLE_COUNT 5\n\n\nSwPageFtnInfoItem::SwPageFtnInfoItem( const USHORT nId, SwPageFtnInfo& rInfo) :\n SfxPoolItem( nId ),\n aFtnInfo(rInfo)\n{\n}\n\n\nSwPageFtnInfoItem::SwPageFtnInfoItem( const SwPageFtnInfoItem& rItem ) :\n SfxPoolItem( rItem ),\n aFtnInfo(rItem.GetPageFtnInfo())\n{\n}\n\n\n SwPageFtnInfoItem::~SwPageFtnInfoItem()\n{\n}\n\n\nSfxPoolItem* SwPageFtnInfoItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwPageFtnInfoItem( *this );\n}\n\n\nint SwPageFtnInfoItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( Which() == rAttr.Which(), \"keine gleichen Attribute\" );\n return ( aFtnInfo == ((SwPageFtnInfoItem&)rAttr).GetPageFtnInfo());\n}\n\n\nSfxItemPresentation SwPageFtnInfoItem::GetPresentation\n(\n SfxItemPresentation ePres,\n SfxMapUnit eCoreUnit,\n SfxMapUnit ePresUnit,\n String& rText,\n const IntlWrapper* pIntl\n) const\n{\n switch ( ePres )\n {\n case SFX_ITEM_PRESENTATION_NONE:\n rText.Erase();\n return SFX_ITEM_PRESENTATION_NONE;\n case SFX_ITEM_PRESENTATION_NAMELESS:\n case SFX_ITEM_PRESENTATION_COMPLETE:\n {\n USHORT nHght = (USHORT) GetPageFtnInfo().GetHeight();\n if ( nHght )\n {\n rText = SW_RESSTR( STR_MAX_FTN_HEIGHT );\n rText += ' ';\n rText += ::GetMetricText( nHght, eCoreUnit, ePresUnit, pIntl );\n rText += ::GetSvxString( ::GetMetricId( ePresUnit ) );\n }\n return ePres;\n }\n default:; \/\/prevent warning\n }\n return SFX_ITEM_PRESENTATION_NONE;\n}\n\/* -----------------------------26.04.01 12:25--------------------------------\n\n ---------------------------------------------------------------------------*\/\nBOOL SwPageFtnInfoItem::QueryValue( Any& rVal, BYTE nMemberId ) const\n{\n sal_Bool bRet = sal_True;\n switch(nMemberId & ~CONVERT_TWIPS)\n {\n case MID_FTN_HEIGHT : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetHeight());break;\n case MID_LINE_WEIGHT : rVal <<= (sal_Int16)TWIP_TO_MM100_UNSIGNED(aFtnInfo.GetLineWidth());break;\n case MID_LINE_COLOR : rVal <<= (sal_Int32)aFtnInfo.GetLineColor().GetColor();break;\n case MID_LINE_RELWIDTH :\n {\n Fraction aTmp( 100, 1 );\n aTmp *= aFtnInfo.GetWidth();\n rVal <<= (sal_Int8)(long)aTmp;\n }\n break;\n case MID_LINE_ADJUST : rVal <<= (sal_Int16)aFtnInfo.GetAdj();break;\/\/text::HorizontalAdjust\n case MID_LINE_TEXT_DIST : rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetTopDist());break;\n case MID_LINE_FOOTNOTE_DIST: rVal <<= (sal_Int32)TWIP_TO_MM100(aFtnInfo.GetBottomDist());break;\n default:\n bRet = sal_False;\n }\n return bRet;\n}\n\/* -----------------------------26.04.01 12:26--------------------------------\n\n ---------------------------------------------------------------------------*\/\nBOOL SwPageFtnInfoItem::PutValue(const Any& rVal, BYTE nMemberId)\n{\n sal_Int32 nSet32 = 0;\n sal_Bool bRet = sal_True;\n switch(nMemberId & ~CONVERT_TWIPS)\n {\n case MID_LINE_COLOR :\n rVal >>= nSet32;\n aFtnInfo.SetLineColor(nSet32);\n break;\n case MID_FTN_HEIGHT:\n case MID_LINE_TEXT_DIST :\n case MID_LINE_FOOTNOTE_DIST:\n rVal >>= nSet32;\n if(nSet32 < 0)\n bRet = sal_False;\n else\n {\n nSet32 = MM100_TO_TWIP(nSet32);\n switch(nMemberId & ~CONVERT_TWIPS)\n {\n case MID_FTN_HEIGHT: aFtnInfo.SetHeight(nSet32); break;\n case MID_LINE_TEXT_DIST: aFtnInfo.SetTopDist(nSet32);break;\n case MID_LINE_FOOTNOTE_DIST: aFtnInfo.SetBottomDist(nSet32);break;\n }\n }\n break;\n case MID_LINE_WEIGHT :\n {\n sal_Int16 nSet = 0;\n rVal >>= nSet;\n if(nSet >= 0)\n aFtnInfo.SetLineWidth(MM100_TO_TWIP(nSet));\n else\n bRet = sal_False;\n }\n break;\n case MID_LINE_RELWIDTH :\n {\n sal_Int8 nSet = 0;\n rVal >>= nSet;\n if(nSet < 0)\n bRet = sal_False;\n else\n aFtnInfo.SetWidth(Fraction(nSet, 100));\n }\n break;\n case MID_LINE_ADJUST :\n {\n sal_Int16 nSet = 0;\n rVal >>= nSet;\n if(nSet >= 0 && nSet < 3) \/\/text::HorizontalAdjust\n aFtnInfo.SetAdj((SwFtnAdj)nSet);\n else\n bRet = sal_False;\n }\n break;\n default:\n bRet = sal_False;\n }\n return bRet;\n}\n\nSwPtrItem::SwPtrItem( const USHORT nId, void* pPtr ) :\n SfxPoolItem( nId ),\n pMisc(pPtr)\n{\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Copy-Konstruktor\n --------------------------------------------------------------------*\/\n\n\nSwPtrItem::SwPtrItem( const SwPtrItem& rItem ) : SfxPoolItem( rItem )\n{\n pMisc = rItem.pMisc;\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung: Clonen\n --------------------------------------------------------------------*\/\n\n\nSfxPoolItem* SwPtrItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwPtrItem( *this );\n}\n\n\/*--------------------------------------------------------------------\n Beschreibung:\n --------------------------------------------------------------------*\/\n\n\nint SwPtrItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n const SwPtrItem& rItem = (SwPtrItem&)rAttr;\n return ( pMisc == rItem.pMisc );\n}\n\n\n\/*-----------------12.11.97 12:55-------------------------------\n SwUINumRuleItem fuer die NumTabPages der FormatNumRule\/Stylisten\n---------------------------------------------------------------*\/\nSwUINumRuleItem::SwUINumRuleItem( const SwNumRule& rRul, const USHORT nId )\n : SfxPoolItem( nId ), pRule( new SwNumRule( rRul ) )\n{\n}\n\nSwUINumRuleItem::SwUINumRuleItem( const SwUINumRuleItem& rItem )\n : SfxPoolItem( rItem ),\n pRule( new SwNumRule( *rItem.pRule ))\n{\n}\n\n SwUINumRuleItem::~SwUINumRuleItem()\n{\n delete pRule;\n}\n\n\nSfxPoolItem* SwUINumRuleItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwUINumRuleItem( *this );\n}\n\nint SwUINumRuleItem::operator==( const SfxPoolItem& rAttr ) const\n{\n DBG_ASSERT( SfxPoolItem::operator==(rAttr), \"unequal types\" );\n return *pRule == *((SwUINumRuleItem&)rAttr).pRule;\n}\n\nBOOL SwUINumRuleItem::QueryValue( uno::Any& rVal, BYTE \/*nMemberId*\/ ) const\n{\n uno::Reference< container::XIndexReplace >xRules = new SwXNumberingRules(*pRule);\n rVal.setValue(&xRules, ::getCppuType((uno::Reference< container::XIndexReplace>*)0));\n return TRUE;\n}\nBOOL SwUINumRuleItem::PutValue( const uno::Any& rVal, BYTE \/*nMemberId*\/ )\n{\n uno::Reference< container::XIndexReplace> xRulesRef;\n if(rVal >>= xRulesRef)\n {\n uno::Reference< lang::XUnoTunnel > xTunnel(xRulesRef, uno::UNO_QUERY);\n SwXNumberingRules* pSwXRules = xTunnel.is() ? reinterpret_cast(\n xTunnel->getSomething(SwXNumberingRules::getUnoTunnelId())) : 0;\n if(pSwXRules)\n {\n *pRule = *pSwXRules->GetNumRule();\n }\n }\n return TRUE;\n}\n\/* -----------------17.06.98 17:43-------------------\n *\n * --------------------------------------------------*\/\nSwBackgroundDestinationItem::SwBackgroundDestinationItem(USHORT _nWhich, USHORT nValue) :\n SfxUInt16Item(_nWhich, nValue)\n{\n}\n\/* -----------------17.06.98 17:44-------------------\n *\n * --------------------------------------------------*\/\nSfxPoolItem* SwBackgroundDestinationItem::Clone( SfxItemPool * \/*pPool*\/ ) const\n{\n return new SwBackgroundDestinationItem(Which(), GetValue());\n}\n\n\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: wrtundo.cxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: jp $ $Date: 2001-09-11 14:57:42 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#define _SVSTDARR_STRINGSDTOR\n\n#ifndef _TOOLS_RESID_HXX\n#include \n#endif\n#ifndef _SFXAPP_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSLSTITM_HXX\n#include \n#endif\n\n#ifndef _WRTSH_HXX\n#include \n#endif\n#ifndef _SWUNDO_HXX\n#include \/\/ fuer Undo-Ids\n#endif\n#ifndef _SWDTFLVR_HXX\n#include \n#endif\n\n#ifndef _WRTSH_HRC\n#include \n#endif\n#include \n\n\n\/\/ Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden\n\/\/ ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.\n\n\nvoid SwWrtShell::Do( DoType eDoType, USHORT nCnt )\n{\n StartAllAction();\n switch( eDoType )\n {\n case UNDO:\n \/\/ Modi zuruecksetzen\n EnterStdMode();\n SwEditShell::Undo(0, nCnt );\n break;\n case REDO:\n \/\/ Modi zuruecksetzen\n EnterStdMode();\n SwEditShell::Redo( nCnt );\n break;\n case REPEAT:\n SwEditShell::Repeat( nCnt );\n break;\n }\n EndAllAction();\n\n BOOL bCreateXSelection = FALSE;\n const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();\n if ( IsSelection() )\n {\n if ( bFrmSelected )\n UnSelectFrm();\n\n \/\/ Funktionspointer fuer das Aufheben der Selektion setzen\n \/\/ bei Cursor setzen\n fnKillSel = &SwWrtShell::ResetSelect;\n fnSetCrsr = &SwWrtShell::SetCrsrKillSel;\n bCreateXSelection = TRUE;\n }\n else if ( bFrmSelected )\n {\n EnterSelFrmMode();\n bCreateXSelection = TRUE;\n }\n else if( (CNT_GRF | CNT_OLE ) & GetCntType() )\n {\n SelectObj( GetCharRect().Pos() );\n EnterSelFrmMode();\n bCreateXSelection = TRUE;\n }\n\n if( bCreateXSelection )\n SwTransferable::CreateSelection( *this );\n\n \/\/ Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen\n \/\/ Warum wird hier nicht immer ein CallChgLink gerufen?\n CallChgLnk();\n}\n\n\nString SwWrtShell::GetDoString( DoType eDoType ) const\n{\n String aStr;\n USHORT nId = 0, nResStr;\n switch( eDoType )\n {\n case UNDO:\n nResStr = STR_UNDO;\n nId = GetUndoIds( &aStr );\n break;\n case REDO:\n nResStr = STR_REDO;\n nId = GetRedoIds( &aStr );\n break;\n }\n\n if( UNDO_END < nId )\n {\n aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager() )), 0 );\n if( UNDO_DRAWUNDO != nId )\n aStr += SW_RESSTR( UNDO_BASE + nId );\n }\n return aStr;\n}\n\nUSHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const\n{\n SwUndoIds aIds;\n switch( eDoType )\n {\n case UNDO:\n GetUndoIds( 0, &aIds );\n break;\n case REDO:\n GetRedoIds( 0, &aIds );\n break;\n }\n\n String sList;\n for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )\n {\n const SwUndoIdAndName& rIdNm = *aIds[ n ];\n if( UNDO_DRAWUNDO != rIdNm.GetUndoId() )\n sList += String( ResId( UNDO_BASE + rIdNm.GetUndoId(), pSwResMgr ));\n else if( rIdNm.GetUndoStr() )\n sList += *rIdNm.GetUndoStr();\n else\n {\n ASSERT( !this, \"no Undo\/Redo Test set\" );\n }\n sList += '\\n';\n }\n rStrs.SetString( sList );\n return aIds.Count();\n}\n\n\nString SwWrtShell::GetRepeatString() const\n{\n String aStr;\n USHORT nId = GetRepeatIds( &aStr );\n if( UNDO_END < nId )\n {\n aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );\n if( UNDO_DRAWUNDO != nId )\n aStr += SW_RESSTR( UNDO_BASE + nId );\n }\n return aStr;\n}\n\n\/*************************************************************************\n\n $Log: not supported by cvs2svn $\n Revision 1.2 2001\/04\/09 07:28:55 tl\n Undo\/Redo controller modifications\n\n Revision 1.1.1.1 2000\/09\/18 17:14:53 hr\n initial import\n\n Revision 1.53 2000\/09\/18 16:06:27 willem.vandorp\n OpenOffice header added.\n\n Revision 1.52 2000\/07\/27 21:01:41 jp\n Bug #76923#: Do - clamp the enterstdmode and Undo\/Redo\/Repeat call\n\n Revision 1.51 2000\/03\/03 15:17:06 os\n StarView remainders removed\n\n Revision 1.50 1998\/04\/15 14:35:34 OS\n STR_UNDO\/REDO\/REPEAT aus dem Sfx\n\n\n Rev 1.49 15 Apr 1998 16:35:34 OS\n STR_UNDO\/REDO\/REPEAT aus dem Sfx\n\n Rev 1.48 24 Nov 1997 14:35:02 MA\n includes\n\n Rev 1.47 03 Nov 1997 14:02:56 MA\n precomp entfernt\n\n Rev 1.46 22 Jan 1997 11:55:56 MA\n opt: bSelection entfernt\n\n Rev 1.45 11 Nov 1996 10:18:48 MA\n ResMgr\n\n Rev 1.44 31 Oct 1996 18:32:30 JP\n Bug #32918#: nach Undo der View sagen, das sich was getan hat\n\n Rev 1.43 29 Aug 1996 09:25:56 OS\n includes\n\n Rev 1.42 24 Nov 1995 16:59:06 OM\n PCH->PRECOMPILED\n\n Rev 1.41 19 Sep 1995 19:11:52 JP\n Bug 19431: Repeat funkt. wieder\n\n Rev 1.40 12 Sep 1995 17:59:32 JP\n Bug19137: vor Undo den Cursor in den StandardMode setzen\n\n Rev 1.39 28 Aug 1995 15:59:40 MA\n Renovierung: IDL, Shells, Textshell-Doktrin aufgegeben\n\n Rev 1.38 22 Aug 1995 17:30:04 JP\n GetUndo-\/-Redo-\/-RepeatIds: optional mit String-Ptr - DrawUndo-Objecte erzeuge die Strings selbst\n\n Rev 1.37 15 Aug 1995 19:52:20 JP\n Nach Undo\/Redo kann der Cursor in OLE oder GRF stehen, selektieren dann den Frame\n\n Rev 1.36 27 Apr 1995 13:14:16 AMA\n Fix (JP): ResId-Ueberpruef. bei Undo\n\n Rev 1.35 23 Feb 1995 17:51:58 MA\n Rudimentaer Undo\/Redo fuer Zeichenobjekte.\n\n Rev 1.34 08 Feb 1995 23:36:12 ER\n undo.hxx -> swundo.hxx wegen solar undo.hxx\n\n Rev 1.33 08 Feb 1995 19:01:30 JP\n UI-UndoIds ins undo.hxx verschoben\n\n*************************************************************************\/\n\n\n#105332# SwWrtShell::Do: Unable undo while doing Undo\/Redo\/Repeat\/*************************************************************************\n *\n * $RCSfile: wrtundo.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hbrinkm $ $Date: 2002-11-22 15:00:50 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n#ifdef PRECOMPILED\n#include \"ui_pch.hxx\"\n#endif\n\n#pragma hdrstop\n\n#define _SVSTDARR_STRINGSDTOR\n\n#ifndef _TOOLS_RESID_HXX\n#include \n#endif\n#ifndef _SFXAPP_HXX \/\/autogen\n#include \n#endif\n#ifndef _SFXSLSTITM_HXX\n#include \n#endif\n\n#ifndef _WRTSH_HXX\n#include \n#endif\n#ifndef _SWUNDO_HXX\n#include \/\/ fuer Undo-Ids\n#endif\n#ifndef _SWDTFLVR_HXX\n#include \n#endif\n\n#ifndef _WRTSH_HRC\n#include \n#endif\n#include \n\n\n\/\/ Undo beendet alle Modi. Falls eine Selektion durch das Undo entstanden\n\/\/ ist, muss die fuer die weiteren Aktionen beruecksichtigt werden.\n\n\nvoid SwWrtShell::Do( DoType eDoType, USHORT nCnt )\n{\n \/\/ #105332# save current state of DoesUndo() and disable undo.\n sal_Bool bSaveDoesUndo = DoesUndo();\n\n DoUndo(sal_False);\n StartAllAction();\n switch( eDoType )\n {\n case UNDO:\n \/\/ Modi zuruecksetzen\n EnterStdMode();\n SwEditShell::Undo(0, nCnt );\n break;\n case REDO:\n \/\/ Modi zuruecksetzen\n EnterStdMode();\n SwEditShell::Redo( nCnt );\n break;\n case REPEAT:\n SwEditShell::Repeat( nCnt );\n break;\n }\n EndAllAction();\n \/\/ #105332# restore undo state\n DoUndo(bSaveDoesUndo);\n\n BOOL bCreateXSelection = FALSE;\n const FASTBOOL bFrmSelected = IsFrmSelected() || IsObjSelected();\n if ( IsSelection() )\n {\n if ( bFrmSelected )\n UnSelectFrm();\n\n \/\/ Funktionspointer fuer das Aufheben der Selektion setzen\n \/\/ bei Cursor setzen\n fnKillSel = &SwWrtShell::ResetSelect;\n fnSetCrsr = &SwWrtShell::SetCrsrKillSel;\n bCreateXSelection = TRUE;\n }\n else if ( bFrmSelected )\n {\n EnterSelFrmMode();\n bCreateXSelection = TRUE;\n }\n else if( (CNT_GRF | CNT_OLE ) & GetCntType() )\n {\n SelectObj( GetCharRect().Pos() );\n EnterSelFrmMode();\n bCreateXSelection = TRUE;\n }\n\n if( bCreateXSelection )\n SwTransferable::CreateSelection( *this );\n\n \/\/ Bug 32918: nach loeschen der Numerierung bleibt die Obj. Leiste stehen\n \/\/ Warum wird hier nicht immer ein CallChgLink gerufen?\n CallChgLnk();\n}\n\n\nString SwWrtShell::GetDoString( DoType eDoType ) const\n{\n String aStr;\n USHORT nId = 0, nResStr;\n switch( eDoType )\n {\n case UNDO:\n nResStr = STR_UNDO;\n nId = GetUndoIds( &aStr );\n break;\n case REDO:\n nResStr = STR_REDO;\n nId = GetRedoIds( &aStr );\n break;\n }\n\n if( UNDO_END < nId )\n {\n aStr.Insert( String(ResId( nResStr, SFX_APP()->GetSfxResManager() )), 0 );\n if( UNDO_DRAWUNDO != nId )\n aStr += SW_RESSTR( UNDO_BASE + nId );\n }\n return aStr;\n}\n\nUSHORT SwWrtShell::GetDoStrings( DoType eDoType, SfxStringListItem& rStrs ) const\n{\n SwUndoIds aIds;\n switch( eDoType )\n {\n case UNDO:\n GetUndoIds( 0, &aIds );\n break;\n case REDO:\n GetRedoIds( 0, &aIds );\n break;\n }\n\n String sList;\n for( USHORT n = 0, nEnd = aIds.Count(); n < nEnd; ++n )\n {\n const SwUndoIdAndName& rIdNm = *aIds[ n ];\n if( UNDO_DRAWUNDO != rIdNm.GetUndoId() )\n sList += String( ResId( UNDO_BASE + rIdNm.GetUndoId(), pSwResMgr ));\n else if( rIdNm.GetUndoStr() )\n sList += *rIdNm.GetUndoStr();\n else\n {\n ASSERT( !this, \"no Undo\/Redo Test set\" );\n }\n sList += '\\n';\n }\n rStrs.SetString( sList );\n return aIds.Count();\n}\n\n\nString SwWrtShell::GetRepeatString() const\n{\n String aStr;\n USHORT nId = GetRepeatIds( &aStr );\n if( UNDO_END < nId )\n {\n aStr.Insert( ResId( STR_REPEAT, SFX_APP()->GetSfxResManager()), 0 );\n if( UNDO_DRAWUNDO != nId )\n aStr += SW_RESSTR( UNDO_BASE + nId );\n }\n return aStr;\n}\n\n\/*************************************************************************\n\n $Log: not supported by cvs2svn $\n Revision 1.3 2001\/09\/11 14:57:42 jp\n Task #91678#: 'selection clipbord' implemented\n\n Revision 1.2 2001\/04\/09 07:28:55 tl\n Undo\/Redo controller modifications\n\n Revision 1.1.1.1 2000\/09\/18 17:14:53 hr\n initial import\n\n Revision 1.53 2000\/09\/18 16:06:27 willem.vandorp\n OpenOffice header added.\n\n Revision 1.52 2000\/07\/27 21:01:41 jp\n Bug #76923#: Do - clamp the enterstdmode and Undo\/Redo\/Repeat call\n\n Revision 1.51 2000\/03\/03 15:17:06 os\n StarView remainders removed\n\n Revision 1.50 1998\/04\/15 14:35:34 OS\n STR_UNDO\/REDO\/REPEAT aus dem Sfx\n\n\n Rev 1.49 15 Apr 1998 16:35:34 OS\n STR_UNDO\/REDO\/REPEAT aus dem Sfx\n\n Rev 1.48 24 Nov 1997 14:35:02 MA\n includes\n\n Rev 1.47 03 Nov 1997 14:02:56 MA\n precomp entfernt\n\n Rev 1.46 22 Jan 1997 11:55:56 MA\n opt: bSelection entfernt\n\n Rev 1.45 11 Nov 1996 10:18:48 MA\n ResMgr\n\n Rev 1.44 31 Oct 1996 18:32:30 JP\n Bug #32918#: nach Undo der View sagen, das sich was getan hat\n\n Rev 1.43 29 Aug 1996 09:25:56 OS\n includes\n\n Rev 1.42 24 Nov 1995 16:59:06 OM\n PCH->PRECOMPILED\n\n Rev 1.41 19 Sep 1995 19:11:52 JP\n Bug 19431: Repeat funkt. wieder\n\n Rev 1.40 12 Sep 1995 17:59:32 JP\n Bug19137: vor Undo den Cursor in den StandardMode setzen\n\n Rev 1.39 28 Aug 1995 15:59:40 MA\n Renovierung: IDL, Shells, Textshell-Doktrin aufgegeben\n\n Rev 1.38 22 Aug 1995 17:30:04 JP\n GetUndo-\/-Redo-\/-RepeatIds: optional mit String-Ptr - DrawUndo-Objecte erzeuge die Strings selbst\n\n Rev 1.37 15 Aug 1995 19:52:20 JP\n Nach Undo\/Redo kann der Cursor in OLE oder GRF stehen, selektieren dann den Frame\n\n Rev 1.36 27 Apr 1995 13:14:16 AMA\n Fix (JP): ResId-Ueberpruef. bei Undo\n\n Rev 1.35 23 Feb 1995 17:51:58 MA\n Rudimentaer Undo\/Redo fuer Zeichenobjekte.\n\n Rev 1.34 08 Feb 1995 23:36:12 ER\n undo.hxx -> swundo.hxx wegen solar undo.hxx\n\n Rev 1.33 08 Feb 1995 19:01:30 JP\n UI-UndoIds ins undo.hxx verschoben\n\n*************************************************************************\/\n\n\n<|endoftext|>"} {"text":"add a TODO to exchange<|endoftext|>"} {"text":"#ifndef SDR_H_\n#define SDR_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace sdr\n{\n\ntypedef std::size_t position_t;\ntypedef std::size_t width_t;\n\n\/\/ this holds all of the traits for a single concept\n\/\/ ie - if width is 1024, this could hold up to 1024 values between 0 and 1024\nstruct concept\n{\n std::vector data;\n\n \/\/ for vector of positions we assume the data has already been dealt with\n concept(const std::vector & input) : data(input)\n {}\n\n \/\/ otherwise we assume that is hasn't, thus we only add non zero fields\n template \n concept(const T & input) : data()\n {\n for(std::size_t i=0; i < input.size(); ++i) {\n if(input[i]) {\n data.push_back(i);\n }\n }\n }\n};\n\n\ntemplate \nstruct node\n{\n \/\/ store the positions of all set bits from 0 -> width\n std::unordered_set positions;\n\n node(const concept & concept) : positions(concept.data.begin(), concept.data.end())\n {}\n\n void fill(const concept & concept)\n {\n std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));\n }\n\n void clear()\n {\n positions.clear();\n }\n\n void print() const\n {\n const std::size_t sroot = std::sqrt(Width);\n\n for(std::size_t y=0; y < sroot; ++y) {\n for(std::size_t x=0; x < sroot; ++x) {\n std::cout << (positions.count((y * sroot) + x) ? '1' : '0');\n }\n\n std::cout << std::endl;\n }\n }\n};\n\ntemplate \nstruct bank\n{\n \/\/ all inputs we have ever received, we store here compressed into storage\n std::vector> storage;\n\n \/\/ this holds our sets of vectors for easy comparison of different objects in storage\n std::array, Width> bitmap;\n\n bank() : storage(), bitmap()\n {}\n\n void print(const position_t pos) const\n {\n storage[pos].print();\n }\n\n position_t insert(const concept & concept)\n {\n storage.push_back(node(concept));\n\n const position_t last_pos = storage.size() - 1;\n\n for(position_t pos : concept.data) {\n bitmap[pos].insert(last_pos);\n }\n\n return last_pos;\n }\n\n void update(const position_t pos, const concept & concept)\n {\n node & node = storage[pos];\n\n for(position_t i : node.positions) {\n bitmap[i].erase(pos);\n }\n\n node.clear();\n\n node.fill(concept);\n\n for(position_t p : node.positions) {\n bitmap[p].insert(pos);\n }\n }\n\n \/\/ find amount of matching bits between two vectors\n std::size_t similarity(const position_t a, const position_t b) const\n {\n std::size_t result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b);\n }\n\n return result;\n }\n\n \/\/ find amount of matching bits between two vectors\n double weighted_similarity(const position_t a, const position_t b, const std::array & weights) const\n {\n double result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b) * weights[pos];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n std::size_t union_similarity(const position_t pos, const std::vector & positions) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n std::size_t result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n double weighted_union_similarity(const position_t pos, const std::vector & positions, const std::array & weights) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n double result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp] * weights[cmp];\n }\n\n return result;\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> closest(const position_t pos, const std::size_t amount) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(idx.begin(), idx.end(), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n ++v[bpos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i(v[m])));\n }\n\n return ret;\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> weighted_closest(const position_t pos, const std::size_t amount, const std::array & weights) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(idx.begin(), idx.end(), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n v[bpos] += weights[spos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0.0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i matching(const concept & concept) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n for(const std::size_t m : concept.data) {\n if(bitmap[m].count(pos) == 0) {\n goto skip;\n }\n }\n\n matching.insert(pos);\n skip:;\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n\n \/\/ has to match amount in data\n std::vector matching(const concept & concept, const std::size_t amount) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n std::size_t amount_matching = 0;\n\n for(const std::size_t m : concept.data) {\n amount_matching += bitmap[m].count(pos);\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n\n \/\/ has to match amount in data\n std::vector weighted_matching(const std::vector & data, const double amount, const std::array & weights) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : data) {\n for(const std::size_t pos : bitmap[item]) {\n double amount_matching = 0;\n\n for(const std::size_t m : data) {\n amount_matching += bitmap[m].count(pos) * weights[m];\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n};\n\n} \/\/namespace sdr\n\n#endif\nmore docs#ifndef SDR_H_\n#define SDR_H_\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace sdr\n{\n\n\ntypedef std::size_t position_t;\ntypedef std::size_t width_t;\n\n\n\n\/\/ this holds all of the traits for a single concept\n\/\/ ie - if width is 1024, this could hold up to 1024 values between 0 and 1024\nstruct concept\n{\n std::vector data;\n\n \/\/ for vector of positions we assume the data has already been dealt with\n concept(const std::vector & input) : data(input)\n {}\n\n \/\/ otherwise we assume that is hasn't, thus we only add non zero fields\n template concept(const T & input) : data()\n {\n for(std::size_t i=0; i < input.size(); ++i) {\n if(input[i]) {\n data.push_back(i);\n }\n }\n }\n};\n\n\n\/\/ represents a concept in storage\n\/\/ designed to be able to be quickly queried and modified\ntemplate struct node\n{\n \/\/ store the positions of all set bits from 0 -> width\n std::unordered_set positions;\n\n node(const concept & concept) : positions(concept.data.begin(), concept.data.end())\n {}\n\n void fill(const concept & concept)\n {\n std::copy(concept.data.begin(), concept.data.end(), std::inserter(positions, positions.begin()));\n }\n\n void clear()\n {\n positions.clear();\n }\n\n void print() const\n {\n const std::size_t sroot = std::sqrt(Width);\n\n for(std::size_t y=0; y < sroot; ++y) {\n for(std::size_t x=0; x < sroot; ++x) {\n std::cout << (positions.count((y * sroot) + x) ? '1' : '0');\n }\n\n std::cout << std::endl;\n }\n }\n};\n\n\n\/\/ this is the memory bank for the sdr memory unit\ntemplate struct bank\n{\n \/\/ all inputs we have ever received, we store here compressed into storage\n std::vector> storage;\n\n \/\/ this holds our sets of vectors for easy comparison of different objects in storage\n std::array, Width> bitmap;\n\n bank() : storage(), bitmap()\n {}\n\n void print(const position_t pos) const\n {\n storage[pos].print();\n }\n\n position_t insert(const concept & concept)\n {\n storage.push_back(node(concept));\n\n const position_t last_pos = storage.size() - 1;\n\n for(position_t pos : concept.data) {\n bitmap[pos].insert(last_pos);\n }\n\n return last_pos;\n }\n\n void update(const position_t pos, const concept & concept)\n {\n node & node = storage[pos];\n\n for(position_t i : node.positions) {\n bitmap[i].erase(pos);\n }\n\n node.clear();\n\n node.fill(concept);\n\n for(position_t p : node.positions) {\n bitmap[p].insert(pos);\n }\n }\n\n \/\/ find amount of matching bits between two vectors\n std::size_t similarity(const position_t a, const position_t b) const\n {\n std::size_t result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b);\n }\n\n return result;\n }\n\n \/\/ find amount of matching bits between two vectors\n double weighted_similarity(const position_t a, const position_t b, const std::array & weights) const\n {\n double result = 0;\n\n for(position_t pos : storage[a].positions) {\n result += bitmap[pos].count(b) * weights[pos];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n std::size_t union_similarity(const position_t pos, const std::vector & positions) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n std::size_t result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp];\n }\n\n return result;\n }\n\n \/\/ find similarity of one object compared to the OR'd result of a list of objects\n double weighted_union_similarity(const position_t pos, const std::vector & positions, const std::array & weights) const\n {\n std::bitset punions;\n\n for(const position_t ppos : positions) {\n for(const position_t spos : storage[ppos].positions) {\n punions.set(spos);\n }\n }\n\n double result = 0;\n\n for(const position_t cmp : storage[pos].positions) {\n result += punions[cmp] * weights[cmp];\n }\n\n return result;\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> closest(const position_t pos, const std::size_t amount) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(idx.begin(), idx.end(), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n ++v[bpos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i(v[m])));\n }\n\n return ret;\n }\n\n \/\/ find most similar to object at pos\n \/\/ first refers to position\n \/\/ second refers to matching number of bits\n std::vector> weighted_closest(const position_t pos, const std::size_t amount, const std::array & weights) const\n {\n std::vector idx(storage.size());\n std::vector v(storage.size());\n\n std::iota(idx.begin(), idx.end(), 0);\n\n \/\/ count matching bits for each\n for(const position_t spos : storage[pos].positions) {\n for(const position_t bpos : bitmap[spos]) {\n v[bpos] += weights[spos];\n }\n }\n\n \/\/ we dont care about our self similarity\n v[pos] = 0.0;\n\n \/\/ if there are less than amount in storage, just return amount that exist\n const auto partial_amount = ((amount >= idx.size()) ? idx.size() : amount);\n\n std::partial_sort(idx.begin(), idx.begin() + partial_amount, idx.end(), [&](\n const position_t a,\n const position_t b\n ) {\n return v[a] > v[b];\n });\n\n \/\/ create std::pair for result\n std::vector> ret;\n ret.reserve(partial_amount);\n\n for(std::size_t i=0; i matching(const concept & concept) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n for(const std::size_t m : concept.data) {\n if(bitmap[m].count(pos) == 0) {\n goto skip;\n }\n }\n\n matching.insert(pos);\n skip:;\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n\n \/\/ has to match amount in data\n std::vector matching(const concept & concept, const std::size_t amount) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : concept.data) {\n for(const std::size_t pos : bitmap[item]) {\n std::size_t amount_matching = 0;\n\n for(const std::size_t m : concept.data) {\n amount_matching += bitmap[m].count(pos);\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n\n \/\/ has to match amount in data\n std::vector weighted_matching(const std::vector & data, const double amount, const std::array & weights) const\n {\n std::unordered_set matching;\n\n for(const std::size_t item : data) {\n for(const std::size_t pos : bitmap[item]) {\n double amount_matching = 0;\n\n for(const std::size_t m : data) {\n amount_matching += bitmap[m].count(pos) * weights[m];\n }\n\n if(amount_matching >= amount) {\n matching.insert(pos);\n }\n }\n }\n\n return std::vector(matching.begin(), matching.end());\n }\n};\n\n} \/\/namespace sdr\n\n#endif\n<|endoftext|>"} {"text":"\/*\n * =====================================================================================\n *\n * Filename: mpu9150_node.cpp\n *\n * Description: ROS package that launches a node and publishes\n *\t the Invensense MPU-9150 in the format Imu.msgs and MagneticField.msgs to the topics\n * \/imu\/data_raw and \/imu\/mag\n *\n * Version: 1.1\n * Created: 27\/07\/13 15:06:50\n * Revision: Morgan Dykshorn 2015\n *\n * Author: Víctor Mayoral Vilches \n *\n * =====================================================================================\n *\/\n#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n\/\/include IMU message, geometry message quaternion, geometry message vector3, and magnetic field\n#include \"sensor_msgs\/Imu.h\"\n#include \"geometry_msgs\/Quaternion.h\"\n#include \"geometry_msgs\/Vector3.h\"\n#include \"sensor_msgs\/MagneticField.h\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Needed when mixing C and C++ code\/libraries\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n #include \"mpu9150.h\"\n #include \"linux_glue.h\"\n #include \"local_defaults.h\"\n\n#ifdef __cplusplus\n }\n#endif\n\n\/\/calibration function\nint set_cal(int mag, char *cal_file);\n\/\/\nvoid register_sig_handler();\nvoid sigint_handler(int sig);\n\nint done;\n\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"mpu9150_node\");\n ros::NodeHandle n;\n \/\/creates publisher of IMU message\n ros::Publisher pub = n.advertise(\"imu\/data_raw\", 1000);\n \/\/creates publisher of Magnetic FIeld message\n ros::Publisher pubM = n.advertise(\"imu\/mag\", 1000);\n ros::Rate loop_rate(10);\n\n \/* Init the sensor the values are hardcoded at the local_defaults.h file *\/\n int opt, len;\n\tint i2c_bus = DEFAULT_I2C_BUS;\n\tint sample_rate = DEFAULT_SAMPLE_RATE_HZ;\n\tint yaw_mix_factor = DEFAULT_YAW_MIX_FACTOR;\n\tint verbose = 0;\n\tchar *mag_cal_file = NULL;\n\tchar *accel_cal_file = NULL;\n\t\/\/creates object of mpudata_t\n\tmpudata_t mpu;\n\n\n \/\/ Initialize the MPU-9150\n\tregister_sig_handler();\n\tmpu9150_set_debug(verbose);\n\tif (mpu9150_init(i2c_bus, sample_rate, yaw_mix_factor))\n\t\texit(1);\n\tset_cal(0, accel_cal_file);\n\tset_cal(1, mag_cal_file);\n\tif (accel_cal_file)\n\t\tfree(accel_cal_file);\n\tif (mag_cal_file)\n\t\tfree(mag_cal_file);\n\n\tif (sample_rate == 0)\n\t\treturn -1;\n\n \/**\n * A count of how many messages we have sent. This is used to create\n * a unique string for each message.\n *\/\n int count = 0;\n while (ros::ok())\n {\n \t\/\/creates objects of each message type\n \t\/\/IMU Message\n sensor_msgs::Imu msgIMU;\n std_msgs::String header;\n geometry_msgs::Quaternion orientation;\n geometry_msgs::Vector3 angular_velocity;\n geometry_msgs::Vector3 linear_acceleration;\n \/\/magnetometer message\n sensor_msgs::MagneticField msgMAG;\n geometry_msgs::Vector3 magnetic_field;\n\n\/\/modified to output in the format of IMU message\n\tif (mpu9150_read(&mpu) == 0) {\n\t\t\/\/IMU Message\n\t\t\/\/sets up header for IMU message\n\t\tmsgIMU.header.seq = count;\n\t\tmsgIMU.header.stamp.sec = ros::Time::now().toSec();\n\t\tmsgIMU.header.frame_id = \"\/base_link\";\n\t\t\/\/adds data to the sensor message\n\t\t\/\/orientation\n\t\tmsgIMU.orientation.x = mpu.fusedQuat[QUAT_X];\n\t\tmsgIMU.orientation.y = mpu.fusedQuat[QUAT_Y];\n\t\tmsgIMU.orientation.z = mpu.fusedQuat[QUAT_Z];\n\t\tmsgIMU.orientation.w = mpu.fusedQuat[QUAT_W];\n\t\t\/\/msgIMU.orientation_covariance[0] = \n\t\t\/\/angular velocity\n\t\tmsgIMU.angular_velocity.x = mpu.fusedEuler[VEC3_X] * RAD_TO_DEGREE;\n\t\tmsgIMU.angular_velocity.y = mpu.fusedEuler[VEC3_Y] * RAD_TO_DEGREE;\n\t\tmsgIMU.angular_velocity.z = mpu.fusedEuler[VEC3_Z] * RAD_TO_DEGREE;\n\t\t\/\/msgIMU.angular_velocity_covariance[] = \n\t\t\/\/linear acceleration\n\t\tmsgIMU.linear_acceleration.x = mpu.calibratedAccel[VEC3_X];\n\t\tmsgIMU.linear_acceleration.y = mpu.calibratedAccel[VEC3_Y];\n\t\tmsgIMU.linear_acceleration.z = mpu.calibratedAccel[VEC3_Z];\n\t\t\/\/msgIMU.linear_acceleration_covariance[] = \n\n\t\t\/\/Magnetometer Message\n\t\t\/\/sets up header\n\t\tmsgMAG.header.seq = count;\n\t\tmsgMAG.header.stamp.sec = ros::Time::now().toSec();\n\t\tmsgMAG.header.frame_id = \"\/base_link\";\n\t\t\/\/adds data to magnetic field message\n\t\tmsgMAG.magnetic_field.x = mpu.calibratedMag[VEC3_X];\n\t\tmsgMAG.magnetic_field.y = mpu.calibratedMag[VEC3_Y];\n\t\tmsgMAG.magnetic_field.z = mpu.calibratedMag[VEC3_Z];\n\t\t\/\/fills the list with zeros as per message spec when no covariance is known\n\t\t\/\/msgMAG.magnetic_field_covariance[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};\n\t}\n\n\t\/\/publish both messages\n pub.publish(msgIMU);\n pubM.publish(msgMAG);\n ros::spinOnce();\n loop_rate.sleep();\n ++count;\n }\n mpu9150_exit();\n return 0;\n}\n\n\nint set_cal(int mag, char *cal_file)\n{\n\tint i;\n\tFILE *f;\n\tchar buff[32];\n\tlong val[6];\n\tcaldata_t cal;\n\n\tif (cal_file) {\n\t\tf = fopen(cal_file, \"r\");\n\t\t\n\t\tif (!f) {\n\t\t\tperror(\"open()\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\telse {\n\t\tif (mag) {\n\t\t\tf = fopen(\".\/magcal.txt\", \"r\");\n\t\t\n\t\t\tif (!f) {\n\t\t\t\tprintf(\"Default magcal.txt not found\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tf = fopen(\".\/accelcal.txt\", \"r\");\n\t\t\n\t\t\tif (!f) {\n\t\t\t\tprintf(\"Default accelcal.txt not found\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\t\t\n\t}\n\n\tmemset(buff, 0, sizeof(buff));\n\t\n\tfor (i = 0; i < 6; i++) {\n\t\tif (!fgets(buff, 20, f)) {\n\t\t\tprintf(\"Not enough lines in calibration file\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tval[i] = atoi(buff);\n\n\t\tif (val[i] == 0) {\n\t\t\tprintf(\"Invalid cal value: %s\\n\", buff);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfclose(f);\n\n\tif (i != 6) \n\t\treturn -1;\n\n\tcal.offset[0] = (short)((val[0] + val[1]) \/ 2);\n\tcal.offset[1] = (short)((val[2] + val[3]) \/ 2);\n\tcal.offset[2] = (short)((val[4] + val[5]) \/ 2);\n\n\tcal.range[0] = (short)(val[1] - cal.offset[0]);\n\tcal.range[1] = (short)(val[3] - cal.offset[1]);\n\tcal.range[2] = (short)(val[5] - cal.offset[2]);\n\t\n\tif (mag) \n\t\tmpu9150_set_mag_cal(&cal);\n\telse \n\t\tmpu9150_set_accel_cal(&cal);\n\n\treturn 0;\n}\n\nvoid register_sig_handler()\n{\n\tstruct sigaction sia;\n\n\tbzero(&sia, sizeof sia);\n\tsia.sa_handler = sigint_handler;\n\n\tif (sigaction(SIGINT, &sia, NULL) < 0) {\n\t\tperror(\"sigaction(SIGINT)\");\n\t\texit(1);\n\t} \n}\n\nvoid sigint_handler(int sig)\n{\n\tdone = 1;\n}added loop control\/*\n * =====================================================================================\n *\n * Filename: mpu9150_node.cpp\n *\n * Description: ROS package that launches a node and publishes\n *\t the Invensense MPU-9150 in the format Imu.msgs and MagneticField.msgs to the topics\n * \/imu\/data_raw and \/imu\/mag\n *\n * Version: 1.1\n * Created: 27\/07\/13 15:06:50\n * Revision: Morgan Dykshorn 2015\n *\n * Author: Víctor Mayoral Vilches \n *\n * =====================================================================================\n *\/\n#include \"ros\/ros.h\"\n#include \"std_msgs\/String.h\"\n\/\/include IMU message, geometry message quaternion, geometry message vector3, and magnetic field\n#include \"sensor_msgs\/Imu.h\"\n#include \"geometry_msgs\/Quaternion.h\"\n#include \"geometry_msgs\/Vector3.h\"\n#include \"sensor_msgs\/MagneticField.h\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ Needed when mixing C and C++ code\/libraries\n#ifdef __cplusplus\n extern \"C\" {\n#endif\n #include \"mpu9150.h\"\n #include \"linux_glue.h\"\n #include \"local_defaults.h\"\n\n#ifdef __cplusplus\n }\n#endif\n\n\/\/calibration function\nint set_cal(int mag, char *cal_file);\n\/\/\nvoid register_sig_handler();\nvoid sigint_handler(int sig);\n\nint done;\n\n\nint main(int argc, char **argv)\n{\n ros::init(argc, argv, \"mpu9150_node\");\n ros::NodeHandle n;\n \/\/creates publisher of IMU message\n ros::Publisher pub = n.advertise(\"imu\/data_raw\", 1000);\n \/\/creates publisher of Magnetic FIeld message\n ros::Publisher pubM = n.advertise(\"imu\/mag\", 1000);\n ros::Rate loop_rate(10);\n\n \/* Init the sensor the values are hardcoded at the local_defaults.h file *\/\n int opt, len;\n\tint i2c_bus = DEFAULT_I2C_BUS;\n\tint sample_rate = DEFAULT_SAMPLE_RATE_HZ;\n\tint yaw_mix_factor = DEFAULT_YAW_MIX_FACTOR;\n\tint verbose = 0;\n\tchar *mag_cal_file = NULL;\n\tchar *accel_cal_file = NULL;\n\t\/\/creates object of mpudata_t\n\tmpudata_t mpu;\n\n\n \/\/ Initialize the MPU-9150\n\tregister_sig_handler();\n\tmpu9150_set_debug(verbose);\n\tif (mpu9150_init(i2c_bus, sample_rate, yaw_mix_factor))\n\t\texit(1);\n\tset_cal(0, accel_cal_file);\n\tset_cal(1, mag_cal_file);\n\tif (accel_cal_file)\n\t\tfree(accel_cal_file);\n\tif (mag_cal_file)\n\t\tfree(mag_cal_file);\n\n\tif (sample_rate == 0)\n\t\treturn -1;\n\n \/\/ ROS loop config\n\tloop_delay = (1000 \/ sample_rate) - 2;\n\tprintf(\"\\nEntering MPU read loop (ctrl-c to exit)\\n\\n\");\n\tlinux_delay_ms(loop_delay);\n\n \/**\n * A count of how many messages we have sent. This is used to create\n * a unique string for each message.\n *\/\n int count = 0;\n while (ros::ok())\n {\n \t\/\/creates objects of each message type\n \t\/\/IMU Message\n sensor_msgs::Imu msgIMU;\n std_msgs::String header;\n geometry_msgs::Quaternion orientation;\n geometry_msgs::Vector3 angular_velocity;\n geometry_msgs::Vector3 linear_acceleration;\n \/\/magnetometer message\n sensor_msgs::MagneticField msgMAG;\n geometry_msgs::Vector3 magnetic_field;\n\n\/\/modified to output in the format of IMU message\n\tif (mpu9150_read(&mpu) == 0) {\n\t\t\/\/IMU Message\n\t\t\/\/sets up header for IMU message\n\t\tmsgIMU.header.seq = count;\n\t\tmsgIMU.header.stamp.sec = ros::Time::now().toSec();\n\t\tmsgIMU.header.frame_id = \"\/base_link\";\n\t\t\/\/adds data to the sensor message\n\t\t\/\/orientation\n\t\tmsgIMU.orientation.x = mpu.fusedQuat[QUAT_X];\n\t\tmsgIMU.orientation.y = mpu.fusedQuat[QUAT_Y];\n\t\tmsgIMU.orientation.z = mpu.fusedQuat[QUAT_Z];\n\t\tmsgIMU.orientation.w = mpu.fusedQuat[QUAT_W];\n\t\t\/\/msgIMU.orientation_covariance[0] = \n\t\t\/\/angular velocity\n\t\tmsgIMU.angular_velocity.x = mpu.fusedEuler[VEC3_X] * RAD_TO_DEGREE;\n\t\tmsgIMU.angular_velocity.y = mpu.fusedEuler[VEC3_Y] * RAD_TO_DEGREE;\n\t\tmsgIMU.angular_velocity.z = mpu.fusedEuler[VEC3_Z] * RAD_TO_DEGREE;\n\t\t\/\/msgIMU.angular_velocity_covariance[] = \n\t\t\/\/linear acceleration\n\t\tmsgIMU.linear_acceleration.x = mpu.calibratedAccel[VEC3_X];\n\t\tmsgIMU.linear_acceleration.y = mpu.calibratedAccel[VEC3_Y];\n\t\tmsgIMU.linear_acceleration.z = mpu.calibratedAccel[VEC3_Z];\n\t\t\/\/msgIMU.linear_acceleration_covariance[] = \n\n\t\t\/\/Magnetometer Message\n\t\t\/\/sets up header\n\t\tmsgMAG.header.seq = count;\n\t\tmsgMAG.header.stamp.sec = ros::Time::now().toSec();\n\t\tmsgMAG.header.frame_id = \"\/base_link\";\n\t\t\/\/adds data to magnetic field message\n\t\tmsgMAG.magnetic_field.x = mpu.calibratedMag[VEC3_X];\n\t\tmsgMAG.magnetic_field.y = mpu.calibratedMag[VEC3_Y];\n\t\tmsgMAG.magnetic_field.z = mpu.calibratedMag[VEC3_Z];\n\t\t\/\/fills the list with zeros as per message spec when no covariance is known\n\t\t\/\/msgMAG.magnetic_field_covariance[9] = {0, 0, 0, 0, 0, 0, 0, 0, 0};\n\t}\n\n\t\/\/publish both messages\n pub.publish(msgIMU);\n pubM.publish(msgMAG);\n ros::spinOnce();\n loop_rate.sleep();\n ++count;\n }\n mpu9150_exit();\n return 0;\n}\n\n\nint set_cal(int mag, char *cal_file)\n{\n\tint i;\n\tFILE *f;\n\tchar buff[32];\n\tlong val[6];\n\tcaldata_t cal;\n\n\tif (cal_file) {\n\t\tf = fopen(cal_file, \"r\");\n\t\t\n\t\tif (!f) {\n\t\t\tperror(\"open()\");\n\t\t\treturn -1;\n\t\t}\n\t}\n\telse {\n\t\tif (mag) {\n\t\t\tf = fopen(\".\/magcal.txt\", \"r\");\n\t\t\n\t\t\tif (!f) {\n\t\t\t\tprintf(\"Default magcal.txt not found\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\n\t\telse {\n\t\t\tf = fopen(\".\/accelcal.txt\", \"r\");\n\t\t\n\t\t\tif (!f) {\n\t\t\t\tprintf(\"Default accelcal.txt not found\\n\");\n\t\t\t\treturn 0;\n\t\t\t}\n\t\t}\t\t\n\t}\n\n\tmemset(buff, 0, sizeof(buff));\n\t\n\tfor (i = 0; i < 6; i++) {\n\t\tif (!fgets(buff, 20, f)) {\n\t\t\tprintf(\"Not enough lines in calibration file\\n\");\n\t\t\tbreak;\n\t\t}\n\n\t\tval[i] = atoi(buff);\n\n\t\tif (val[i] == 0) {\n\t\t\tprintf(\"Invalid cal value: %s\\n\", buff);\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tfclose(f);\n\n\tif (i != 6) \n\t\treturn -1;\n\n\tcal.offset[0] = (short)((val[0] + val[1]) \/ 2);\n\tcal.offset[1] = (short)((val[2] + val[3]) \/ 2);\n\tcal.offset[2] = (short)((val[4] + val[5]) \/ 2);\n\n\tcal.range[0] = (short)(val[1] - cal.offset[0]);\n\tcal.range[1] = (short)(val[3] - cal.offset[1]);\n\tcal.range[2] = (short)(val[5] - cal.offset[2]);\n\t\n\tif (mag) \n\t\tmpu9150_set_mag_cal(&cal);\n\telse \n\t\tmpu9150_set_accel_cal(&cal);\n\n\treturn 0;\n}\n\nvoid register_sig_handler()\n{\n\tstruct sigaction sia;\n\n\tbzero(&sia, sizeof sia);\n\tsia.sa_handler = sigint_handler;\n\n\tif (sigaction(SIGINT, &sia, NULL) < 0) {\n\t\tperror(\"sigaction(SIGINT)\");\n\t\texit(1);\n\t} \n}\n\nvoid sigint_handler(int sig)\n{\n\tdone = 1;\n}<|endoftext|>"} {"text":"\/*\n Persons Model Contact Item\n Represents person's contact item in the model\n Copyright (C) 2012 Martin Klapetek \n Copyright (C) 2012 Aleix Pol Gonzalez \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"persons-model-contact-item.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass PersonsModelContactItemPrivate {\npublic:\n QHash data;\n};\n\nPersonsModelContactItem::PersonsModelContactItem(const QUrl& uri, const QString& displayName)\n : d_ptr(new PersonsModelContactItemPrivate)\n{\n setData(uri, PersonsModel::UriRole);\n setText(displayName);\n \n refreshIcon();\n}\n\nPersonsModelContactItem::~PersonsModelContactItem()\n{\n delete d_ptr;\n}\n\nQMap initializeTypeIcons()\n{\n QMap ret;\n ret.insert(PersonsModel::Email, QIcon::fromTheme(QLatin1String(\"mail-mark-unread\")));\n ret.insert(PersonsModel::IM, QIcon::fromTheme(QLatin1String(\"im-user\")));\n ret.insert(PersonsModel::Phone, QIcon::fromTheme(QLatin1String(\"phone\")));\n ret.insert(PersonsModel::MobilePhone, QIcon::fromTheme(QLatin1String(\"phone\")));\n ret.insert(PersonsModel::Postal, QIcon::fromTheme(QLatin1String(\"mail-message\")));\n return ret;\n}\n\nstatic QMap s_contactTypeMap = initializeTypeIcons();\n\nvoid PersonsModelContactItem::refreshIcon()\n{\n PersonsModel::ContactType type = (PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt();\n setIcon(s_contactTypeMap[type]);\n}\n\nvoid PersonsModelContactItem::addData(const QUrl &key, const QVariant &value)\n{\n if(value.isNull())\n return;\n \n if(Nepomuk::Vocabulary::NCO::imNickname() == key) {\n setText(value.toString());\n } else if (Nepomuk::Vocabulary::NCO::imID() == key) {\n setType(PersonsModel::IM);\n } else if (Nepomuk::Vocabulary::NCO::hasEmailAddress() == key) {\n setType(PersonsModel::Email);\n }else if (Nepomuk::Vocabulary::NCO::emailAddress() == key) {\n setText(value.toString());\n }\n\n Q_D(PersonsModelContactItem);\n\/\/ kDebug() << \"Inserting\" << value << \"(\" << key << \")\";\n d->data.insert(key, value);\n emitDataChanged();\n}\n\nQVariant PersonsModelContactItem::dataValue(const QUrl &key)\n{\n Q_D(PersonsModelContactItem);\n return d->data.value(key);\n}\n\nQUrl PersonsModelContactItem::uri() const\n{\n return data(PersonsModel::UriRole).toUrl();\n}\n\nvoid PersonsModelContactItem::setType (PersonsModel::ContactType type)\n{\n setData(type, PersonsModel::ContactTypeRole);\n refreshIcon();\n}\n\nQVariant PersonsModelContactItem::data(int role) const\n{\n Q_D(const PersonsModelContactItem);\n switch(role) {\n case PersonsModel::NickRole: return d->data.value(Nepomuk::Vocabulary::NCO::imNickname());\n case PersonsModel::PhoneRole: return d->data.value(Nepomuk::Vocabulary::NCO::phoneNumber());\n case PersonsModel::EmailRole: return d->data.value(Nepomuk::Vocabulary::NCO::emailAddress());\n case PersonsModel::IMRole: return d->data.value(Nepomuk::Vocabulary::NCO::imID());\n case PersonsModel::PhotoRole: {\n QHash::const_iterator it = d->data.constFind(Nepomuk::Vocabulary::NCO::photo());\n if(it==d->data.constEnd()) {\n const QString query = QString::fromLatin1(\"select ?url where { %1 nco:photo ?phRes. ?phRes nie:url ?url . }\")\n .arg( Soprano::Node::resourceToN3(uri()) );\n Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();\n Soprano::QueryResultIterator qit = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );\n \n QUrl url;\n if( qit.next() ) {\n url = qit[\"url\"].uri();\n }\n it = d_ptr->data.insert(Nepomuk::Vocabulary::NCO::photo(), url);\n }\n return it!=d->data.constEnd() ? it.value() : QVariant();\n }\n }\n return QStandardItem::data(role);\n}\nImplement the ContactIdRole for contacts\/*\n Persons Model Contact Item\n Represents person's contact item in the model\n Copyright (C) 2012 Martin Klapetek \n Copyright (C) 2012 Aleix Pol Gonzalez \n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public\n License as published by the Free Software Foundation; either\n version 2.1 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n\n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free Software\n Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n\n#include \"persons-model-contact-item.h\"\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nclass PersonsModelContactItemPrivate {\npublic:\n QHash data;\n};\n\nPersonsModelContactItem::PersonsModelContactItem(const QUrl& uri, const QString& displayName)\n : d_ptr(new PersonsModelContactItemPrivate)\n{\n setData(uri, PersonsModel::UriRole);\n setText(displayName);\n \n refreshIcon();\n}\n\nPersonsModelContactItem::~PersonsModelContactItem()\n{\n delete d_ptr;\n}\n\nQMap initializeTypeIcons()\n{\n QMap ret;\n ret.insert(PersonsModel::Email, QIcon::fromTheme(QLatin1String(\"mail-mark-unread\")));\n ret.insert(PersonsModel::IM, QIcon::fromTheme(QLatin1String(\"im-user\")));\n ret.insert(PersonsModel::Phone, QIcon::fromTheme(QLatin1String(\"phone\")));\n ret.insert(PersonsModel::MobilePhone, QIcon::fromTheme(QLatin1String(\"phone\")));\n ret.insert(PersonsModel::Postal, QIcon::fromTheme(QLatin1String(\"mail-message\")));\n return ret;\n}\n\nstatic QMap s_contactTypeMap = initializeTypeIcons();\n\nvoid PersonsModelContactItem::refreshIcon()\n{\n PersonsModel::ContactType type = (PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt();\n setIcon(s_contactTypeMap[type]);\n}\n\nvoid PersonsModelContactItem::addData(const QUrl &key, const QVariant &value)\n{\n if(value.isNull())\n return;\n \n if(Nepomuk::Vocabulary::NCO::imNickname() == key) {\n setText(value.toString());\n } else if (Nepomuk::Vocabulary::NCO::imID() == key) {\n setType(PersonsModel::IM);\n } else if (Nepomuk::Vocabulary::NCO::hasEmailAddress() == key) {\n setType(PersonsModel::Email);\n }else if (Nepomuk::Vocabulary::NCO::emailAddress() == key) {\n setText(value.toString());\n }\n\n Q_D(PersonsModelContactItem);\n\/\/ kDebug() << \"Inserting\" << value << \"(\" << key << \")\";\n d->data.insert(key, value);\n emitDataChanged();\n}\n\nQVariant PersonsModelContactItem::dataValue(const QUrl &key)\n{\n Q_D(PersonsModelContactItem);\n return d->data.value(key);\n}\n\nQUrl PersonsModelContactItem::uri() const\n{\n return data(PersonsModel::UriRole).toUrl();\n}\n\nvoid PersonsModelContactItem::setType (PersonsModel::ContactType type)\n{\n setData(type, PersonsModel::ContactTypeRole);\n refreshIcon();\n}\n\nQVariant PersonsModelContactItem::data(int role) const\n{\n Q_D(const PersonsModelContactItem);\n switch(role) {\n case PersonsModel::NickRole: return d->data.value(Nepomuk::Vocabulary::NCO::imNickname());\n case PersonsModel::PhoneRole: return d->data.value(Nepomuk::Vocabulary::NCO::phoneNumber());\n case PersonsModel::EmailRole: return d->data.value(Nepomuk::Vocabulary::NCO::emailAddress());\n case PersonsModel::IMRole: return d->data.value(Nepomuk::Vocabulary::NCO::imID());\n case PersonsModel::PhotoRole: {\n QHash::const_iterator it = d->data.constFind(Nepomuk::Vocabulary::NCO::photo());\n if(it==d->data.constEnd()) {\n const QString query = QString::fromLatin1(\"select ?url where { %1 nco:photo ?phRes. ?phRes nie:url ?url . }\")\n .arg( Soprano::Node::resourceToN3(uri()) );\n Soprano::Model* model = Nepomuk::ResourceManager::instance()->mainModel();\n Soprano::QueryResultIterator qit = model->executeQuery( query, Soprano::Query::QueryLanguageSparql );\n \n QUrl url;\n if( qit.next() ) {\n url = qit[\"url\"].uri();\n }\n it = d_ptr->data.insert(Nepomuk::Vocabulary::NCO::photo(), url);\n }\n return it!=d->data.constEnd() ? it.value() : QVariant();\n }\n case PersonsModel::ContactIdRole: {\n int role = -1;\n switch((PersonsModel::ContactType) data(PersonsModel::ContactTypeRole).toInt()) {\n case PersonsModel::IM: role = PersonsModel::IMRole; break;\n case PersonsModel::Phone: role = PersonsModel::PhoneRole; break;\n case PersonsModel::Email: role = PersonsModel::EmailRole; break;\n case PersonsModel::MobilePhone: role = PersonsModel::PhoneRole; break;\n case PersonsModel::Postal: role = -1; break;\n }\n if(role>=0)\n return data(role);\n } break;\n }\n return QStandardItem::data(role);\n}\n<|endoftext|>"} {"text":"\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/multiphysics_sys.h\"\n\n\/\/ GRINS\n#include \"grins\/assembly_context.h\"\n\n\/\/ libMesh\n#include \"libmesh\/composite_function.h\"\n#include \"libmesh\/getpot.h\"\n\nnamespace GRINS\n{\n\n MultiphysicsSystem::MultiphysicsSystem( libMesh::EquationSystems& es,\n\t\t\t\t\t const std::string& name,\n\t\t\t\t\t const unsigned int number )\n : FEMSystem(es, name, number),\n _use_numerical_jacobians_only(false)\n {\n return;\n }\n\n MultiphysicsSystem::~MultiphysicsSystem()\n {\n return;\n }\n\n void MultiphysicsSystem::attach_physics_list( PhysicsList physics_list )\n {\n _physics_list = physics_list;\n return;\n }\n\n void MultiphysicsSystem::read_input_options( const GetPot& input )\n {\n \/\/ Read options for MultiphysicsSystem first\n this->verify_analytic_jacobians = input(\"linear-nonlinear-solver\/verify_analytic_jacobians\", 0.0 );\n this->print_solution_norms = input(\"screen-options\/print_solution_norms\", false );\n this->print_solutions = input(\"screen-options\/print_solutions\", false );\n this->print_residual_norms = input(\"screen-options\/print_residual_norms\", false );\n\n \/\/ backwards compatibility with old config files.\n \/*! \\todo Remove old print_residual nomenclature *\/\n this->print_residuals = input(\"screen-options\/print_residual\", false );\n if (this->print_residuals)\n libmesh_deprecated();\n\n this->print_residuals = input(\"screen-options\/print_residuals\", this->print_residuals );\n this->print_jacobian_norms = input(\"screen-options\/print_jacobian_norms\", false );\n this->print_jacobians = input(\"screen-options\/print_jacobians\", false );\n this->print_element_solutions = input(\"screen-options\/print_element_solutions\", false );\n this->print_element_residuals = input(\"screen-options\/print_element_residuals\", false );\n this->print_element_jacobians = input(\"screen-options\/print_element_jacobians\", false );\n\n _use_numerical_jacobians_only = input(\"linear-nonlinear-solver\/use_numerical_jacobians_only\", false );\n\n numerical_jacobian_h =\n input(\"linear-nonlinear-solver\/numerical_jacobian_h\",\n numerical_jacobian_h);\n }\n\n void MultiphysicsSystem::init_data()\n {\n \/\/ Need this to be true because of our overloading of the\n \/\/ mass_residual function.\n \/\/ This is data in FEMSystem. MUST be set before FEMSystem::init_data.\n use_fixed_solution = true;\n\n \/\/ Initalize all the variables. We pass this pointer for the system.\n \/* NOTE: We CANNOT fuse this loop with the others. This loop\n MUST complete first. *\/\n \/*! \\todo Figure out how to tell compilers not to fuse this loop when\n they want to be aggressive. *\/\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->init_variables( this );\n }\n\n \/\/ Now set time_evolving variables\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->set_time_evolving_vars( this );\n }\n\n \/\/ Set whether the problem we're solving is steady or not\n \/\/ Since the variable is static, just call one Physics class\n {\n (_physics_list.begin()->second)->set_is_steady((this->time_solver)->is_steady());\n }\n\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t\/\/ Initialize builtin BC's for each physics\n\t(physics_iter->second)->init_bcs( this );\n }\n\n \/\/ Next, call parent init_data function to intialize everything.\n libMesh::FEMSystem::init_data();\n\n \/\/ After solution has been initialized we can project initial\n \/\/ conditions to it\n libMesh::CompositeFunction ic_function;\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t\/\/ Initialize builtin IC's for each physics\n\t(physics_iter->second)->init_ics( this, ic_function );\n }\n\n if (ic_function.n_subfunctions())\n {\n this->project_solution(&ic_function);\n }\n\n return;\n }\n\n libMesh::AutoPtr MultiphysicsSystem::build_context()\n {\n AssemblyContext* context = new AssemblyContext(*this);\n\n libMesh::AutoPtr ap(context);\n\n libMesh::DifferentiablePhysics* phys = libMesh::FEMSystem::get_physics();\n\n libmesh_assert(phys);\n\n \/\/ If we are solving a moving mesh problem, tell that to the Context\n context->set_mesh_system(phys->get_mesh_system());\n context->set_mesh_x_var(phys->get_mesh_x_var());\n context->set_mesh_y_var(phys->get_mesh_y_var());\n context->set_mesh_z_var(phys->get_mesh_z_var());\n\n ap->set_deltat_pointer( &deltat );\n\n \/\/ If we are solving the adjoint problem, tell that to the Context\n ap->is_adjoint() = this->get_time_solver().is_adjoint();\n\n return ap;\n }\n\n void MultiphysicsSystem::register_postprocessing_vars( const GetPot& input,\n PostProcessedQuantities& postprocessing )\n {\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n (physics_iter->second)->register_postprocessing_vars( input, postprocessing );\n }\n\n return;\n }\n\n void MultiphysicsSystem::init_context( libMesh::DiffContext& context )\n {\n AssemblyContext& c = libMesh::libmesh_cast_ref(context);\n\n \/\/Loop over each physics to initialize relevant variable structures for assembling system\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->init_context( c );\n }\n\n return;\n }\n\n\n bool MultiphysicsSystem::_general_residual( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context,\n ResFuncType resfunc,\n CacheFuncType cachefunc)\n {\n AssemblyContext& c = libMesh::libmesh_cast_ref(context);\n \n bool compute_jacobian = true;\n if( !request_jacobian || _use_numerical_jacobians_only ) compute_jacobian = false;\n\n CachedValues cache;\n\n \/\/ Now compute cache for this element\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n \/\/ boost::shared_ptr gets confused by operator->*\n\t((*(physics_iter->second)).*cachefunc)( c, cache );\n }\n\n \/\/ Loop over each physics and compute their contributions\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n if(c.has_elem())\n {\n if( (physics_iter->second)->enabled_on_elem( &c.get_elem() ) )\n {\n ((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );\n }\n }\n else\n {\n ((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );\n }\n }\n\n \/\/ TODO: Need to think about the implications of this because there might be some\n \/\/ TODO: jacobian terms we don't want to compute for efficiency reasons\n return compute_jacobian;\n }\n\n bool MultiphysicsSystem::element_time_derivative( bool request_jacobian,\n\t\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::element_time_derivative,\n &GRINS::Physics::compute_element_time_derivative_cache);\n }\n\n bool MultiphysicsSystem::side_time_derivative( bool request_jacobian,\n\t\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::side_time_derivative,\n &GRINS::Physics::compute_side_time_derivative_cache);\n }\n\n bool MultiphysicsSystem::nonlocal_time_derivative( bool request_jacobian,\n\t\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::nonlocal_time_derivative,\n &GRINS::Physics::compute_nonlocal_time_derivative_cache);\n }\n\n bool MultiphysicsSystem::element_constraint( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::element_constraint,\n &GRINS::Physics::compute_element_constraint_cache);\n }\n\n bool MultiphysicsSystem::side_constraint( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::side_constraint,\n &GRINS::Physics::compute_side_constraint_cache);\n }\n\n bool MultiphysicsSystem::nonlocal_constraint( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::nonlocal_constraint,\n &GRINS::Physics::compute_nonlocal_constraint_cache);\n }\n\n bool MultiphysicsSystem::mass_residual( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::mass_residual,\n &GRINS::Physics::compute_mass_residual_cache);\n }\n\n bool MultiphysicsSystem::nonlocal_mass_residual( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::nonlocal_mass_residual,\n &GRINS::Physics::compute_nonlocal_mass_residual_cache);\n }\n\n std::tr1::shared_ptr MultiphysicsSystem::get_physics( const std::string physics_name )\n {\n if( _physics_list.find( physics_name ) == _physics_list.end() )\n {\n\tstd::cerr << \"Error: Could not find physics \" << physics_name << std::endl;\n\tlibmesh_error();\n }\n\n return _physics_list[physics_name];\n }\n\n bool MultiphysicsSystem::has_physics( const std::string physics_name ) const\n {\n bool has_physics = false;\n\n if( _physics_list.find(physics_name) != _physics_list.end() )\n has_physics = true;\n\n return has_physics;\n }\n\n void MultiphysicsSystem::compute_postprocessed_quantity( unsigned int quantity_index,\n const AssemblyContext& context,\n const libMesh::Point& point,\n libMesh::Real& value )\n {\n for( PhysicsListIter physics_iter = _physics_list.begin();\n physics_iter != _physics_list.end();\n physics_iter++ )\n {\n \/\/ Only compute if physics is active on current subdomain or globally\n if( (physics_iter->second)->enabled_on_elem( &context.get_elem() ) )\n {\n (physics_iter->second)->compute_postprocessed_quantity( quantity_index, context, point, value );\n }\n }\n return;\n }\n\n#ifdef GRINS_USE_GRVY_TIMERS\n void MultiphysicsSystem::attach_grvy_timer( GRVY::GRVY_Timer_Class* grvy_timer )\n {\n _timer = grvy_timer;\n\n \/\/ Attach timers to each physics\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->attach_grvy_timer( grvy_timer );\n }\n\n return;\n }\n#endif\n\n\n} \/\/ namespace GRINS\nHave MultiphysicsSystem call Physics::auxiliary_init\/\/-----------------------------------------------------------------------bl-\n\/\/--------------------------------------------------------------------------\n\/\/\n\/\/ GRINS - General Reacting Incompressible Navier-Stokes\n\/\/\n\/\/ Copyright (C) 2014-2015 Paul T. Bauman, Roy H. Stogner\n\/\/ Copyright (C) 2010-2013 The PECOS Development Team\n\/\/\n\/\/ This library is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the Version 2.1 GNU Lesser General\n\/\/ Public License as published by the Free Software Foundation.\n\/\/\n\/\/ This library is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ Lesser General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Lesser General Public\n\/\/ License along with this library; if not, write to the Free Software\n\/\/ Foundation, Inc. 51 Franklin Street, Fifth Floor,\n\/\/ Boston, MA 02110-1301 USA\n\/\/\n\/\/-----------------------------------------------------------------------el-\n\n\n\/\/ This class\n#include \"grins\/multiphysics_sys.h\"\n\n\/\/ GRINS\n#include \"grins\/assembly_context.h\"\n\n\/\/ libMesh\n#include \"libmesh\/composite_function.h\"\n#include \"libmesh\/getpot.h\"\n\nnamespace GRINS\n{\n\n MultiphysicsSystem::MultiphysicsSystem( libMesh::EquationSystems& es,\n\t\t\t\t\t const std::string& name,\n\t\t\t\t\t const unsigned int number )\n : FEMSystem(es, name, number),\n _use_numerical_jacobians_only(false)\n {\n return;\n }\n\n MultiphysicsSystem::~MultiphysicsSystem()\n {\n return;\n }\n\n void MultiphysicsSystem::attach_physics_list( PhysicsList physics_list )\n {\n _physics_list = physics_list;\n return;\n }\n\n void MultiphysicsSystem::read_input_options( const GetPot& input )\n {\n \/\/ Read options for MultiphysicsSystem first\n this->verify_analytic_jacobians = input(\"linear-nonlinear-solver\/verify_analytic_jacobians\", 0.0 );\n this->print_solution_norms = input(\"screen-options\/print_solution_norms\", false );\n this->print_solutions = input(\"screen-options\/print_solutions\", false );\n this->print_residual_norms = input(\"screen-options\/print_residual_norms\", false );\n\n \/\/ backwards compatibility with old config files.\n \/*! \\todo Remove old print_residual nomenclature *\/\n this->print_residuals = input(\"screen-options\/print_residual\", false );\n if (this->print_residuals)\n libmesh_deprecated();\n\n this->print_residuals = input(\"screen-options\/print_residuals\", this->print_residuals );\n this->print_jacobian_norms = input(\"screen-options\/print_jacobian_norms\", false );\n this->print_jacobians = input(\"screen-options\/print_jacobians\", false );\n this->print_element_solutions = input(\"screen-options\/print_element_solutions\", false );\n this->print_element_residuals = input(\"screen-options\/print_element_residuals\", false );\n this->print_element_jacobians = input(\"screen-options\/print_element_jacobians\", false );\n\n _use_numerical_jacobians_only = input(\"linear-nonlinear-solver\/use_numerical_jacobians_only\", false );\n\n numerical_jacobian_h =\n input(\"linear-nonlinear-solver\/numerical_jacobian_h\",\n numerical_jacobian_h);\n }\n\n void MultiphysicsSystem::init_data()\n {\n \/\/ Need this to be true because of our overloading of the\n \/\/ mass_residual function.\n \/\/ This is data in FEMSystem. MUST be set before FEMSystem::init_data.\n use_fixed_solution = true;\n\n \/\/ Initalize all the variables. We pass this pointer for the system.\n \/* NOTE: We CANNOT fuse this loop with the others. This loop\n MUST complete first. *\/\n \/*! \\todo Figure out how to tell compilers not to fuse this loop when\n they want to be aggressive. *\/\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->init_variables( this );\n }\n\n \/\/ Now set time_evolving variables\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->set_time_evolving_vars( this );\n }\n\n \/\/ Set whether the problem we're solving is steady or not\n \/\/ Since the variable is static, just call one Physics class\n {\n (_physics_list.begin()->second)->set_is_steady((this->time_solver)->is_steady());\n }\n\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t\/\/ Initialize builtin BC's for each physics\n\t(physics_iter->second)->init_bcs( this );\n }\n\n \/\/ Next, call parent init_data function to intialize everything.\n libMesh::FEMSystem::init_data();\n\n \/\/ After solution has been initialized we can project initial\n \/\/ conditions to it\n libMesh::CompositeFunction ic_function;\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t\/\/ Initialize builtin IC's for each physics\n\t(physics_iter->second)->init_ics( this, ic_function );\n }\n\n if (ic_function.n_subfunctions())\n {\n this->project_solution(&ic_function);\n }\n\n \/\/ Now do any auxillary initialization required by each Physics\n for( PhysicsListIter physics_iter = _physics_list.begin();\n physics_iter != _physics_list.end();\n physics_iter++ )\n {\n (physics_iter->second)->auxiliary_init( *this );\n }\n\n return;\n }\n\n libMesh::AutoPtr MultiphysicsSystem::build_context()\n {\n AssemblyContext* context = new AssemblyContext(*this);\n\n libMesh::AutoPtr ap(context);\n\n libMesh::DifferentiablePhysics* phys = libMesh::FEMSystem::get_physics();\n\n libmesh_assert(phys);\n\n \/\/ If we are solving a moving mesh problem, tell that to the Context\n context->set_mesh_system(phys->get_mesh_system());\n context->set_mesh_x_var(phys->get_mesh_x_var());\n context->set_mesh_y_var(phys->get_mesh_y_var());\n context->set_mesh_z_var(phys->get_mesh_z_var());\n\n ap->set_deltat_pointer( &deltat );\n\n \/\/ If we are solving the adjoint problem, tell that to the Context\n ap->is_adjoint() = this->get_time_solver().is_adjoint();\n\n return ap;\n }\n\n void MultiphysicsSystem::register_postprocessing_vars( const GetPot& input,\n PostProcessedQuantities& postprocessing )\n {\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n (physics_iter->second)->register_postprocessing_vars( input, postprocessing );\n }\n\n return;\n }\n\n void MultiphysicsSystem::init_context( libMesh::DiffContext& context )\n {\n AssemblyContext& c = libMesh::libmesh_cast_ref(context);\n\n \/\/Loop over each physics to initialize relevant variable structures for assembling system\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->init_context( c );\n }\n\n return;\n }\n\n\n bool MultiphysicsSystem::_general_residual( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context,\n ResFuncType resfunc,\n CacheFuncType cachefunc)\n {\n AssemblyContext& c = libMesh::libmesh_cast_ref(context);\n \n bool compute_jacobian = true;\n if( !request_jacobian || _use_numerical_jacobians_only ) compute_jacobian = false;\n\n CachedValues cache;\n\n \/\/ Now compute cache for this element\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n \/\/ boost::shared_ptr gets confused by operator->*\n\t((*(physics_iter->second)).*cachefunc)( c, cache );\n }\n\n \/\/ Loop over each physics and compute their contributions\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n if(c.has_elem())\n {\n if( (physics_iter->second)->enabled_on_elem( &c.get_elem() ) )\n {\n ((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );\n }\n }\n else\n {\n ((*(physics_iter->second)).*resfunc)( compute_jacobian, c, cache );\n }\n }\n\n \/\/ TODO: Need to think about the implications of this because there might be some\n \/\/ TODO: jacobian terms we don't want to compute for efficiency reasons\n return compute_jacobian;\n }\n\n bool MultiphysicsSystem::element_time_derivative( bool request_jacobian,\n\t\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::element_time_derivative,\n &GRINS::Physics::compute_element_time_derivative_cache);\n }\n\n bool MultiphysicsSystem::side_time_derivative( bool request_jacobian,\n\t\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::side_time_derivative,\n &GRINS::Physics::compute_side_time_derivative_cache);\n }\n\n bool MultiphysicsSystem::nonlocal_time_derivative( bool request_jacobian,\n\t\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::nonlocal_time_derivative,\n &GRINS::Physics::compute_nonlocal_time_derivative_cache);\n }\n\n bool MultiphysicsSystem::element_constraint( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::element_constraint,\n &GRINS::Physics::compute_element_constraint_cache);\n }\n\n bool MultiphysicsSystem::side_constraint( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::side_constraint,\n &GRINS::Physics::compute_side_constraint_cache);\n }\n\n bool MultiphysicsSystem::nonlocal_constraint( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::nonlocal_constraint,\n &GRINS::Physics::compute_nonlocal_constraint_cache);\n }\n\n bool MultiphysicsSystem::mass_residual( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::mass_residual,\n &GRINS::Physics::compute_mass_residual_cache);\n }\n\n bool MultiphysicsSystem::nonlocal_mass_residual( bool request_jacobian,\n\t\t\t\t\t libMesh::DiffContext& context )\n {\n return this->_general_residual\n (request_jacobian,\n context,\n &GRINS::Physics::nonlocal_mass_residual,\n &GRINS::Physics::compute_nonlocal_mass_residual_cache);\n }\n\n std::tr1::shared_ptr MultiphysicsSystem::get_physics( const std::string physics_name )\n {\n if( _physics_list.find( physics_name ) == _physics_list.end() )\n {\n\tstd::cerr << \"Error: Could not find physics \" << physics_name << std::endl;\n\tlibmesh_error();\n }\n\n return _physics_list[physics_name];\n }\n\n bool MultiphysicsSystem::has_physics( const std::string physics_name ) const\n {\n bool has_physics = false;\n\n if( _physics_list.find(physics_name) != _physics_list.end() )\n has_physics = true;\n\n return has_physics;\n }\n\n void MultiphysicsSystem::compute_postprocessed_quantity( unsigned int quantity_index,\n const AssemblyContext& context,\n const libMesh::Point& point,\n libMesh::Real& value )\n {\n for( PhysicsListIter physics_iter = _physics_list.begin();\n physics_iter != _physics_list.end();\n physics_iter++ )\n {\n \/\/ Only compute if physics is active on current subdomain or globally\n if( (physics_iter->second)->enabled_on_elem( &context.get_elem() ) )\n {\n (physics_iter->second)->compute_postprocessed_quantity( quantity_index, context, point, value );\n }\n }\n return;\n }\n\n#ifdef GRINS_USE_GRVY_TIMERS\n void MultiphysicsSystem::attach_grvy_timer( GRVY::GRVY_Timer_Class* grvy_timer )\n {\n _timer = grvy_timer;\n\n \/\/ Attach timers to each physics\n for( PhysicsListIter physics_iter = _physics_list.begin();\n\t physics_iter != _physics_list.end();\n\t physics_iter++ )\n {\n\t(physics_iter->second)->attach_grvy_timer( grvy_timer );\n }\n\n return;\n }\n#endif\n\n\n} \/\/ namespace GRINS\n<|endoftext|>"} {"text":"\/**\n ** \\file object\/object.cc\n ** \\brief Implementation of object::Object.\n *\/\n\n#include \n\n#include \n#include \n\n#include \"libport\/containers.hh\"\n\n#include \"object\/object.hh\"\n#include \"object\/atom.hh\"\n#include \"object\/urbi-exception.hh\"\n\nnamespace object\n{\n \/*-------.\n | kind. |\n `-------*\/\n\n const char*\n Object::string_of (Object::kind_type k)\n {\n switch (k)\n {\n#define CASE(What, Name) case kind_ ## What: return #Name; break;\n\tAPPLY_ON_ALL_PRIMITIVES(CASE);\n#undef CASE\n }\n pabort(\"unreachable\");\n }\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n Object::locate_type\n Object::slot_locate (const key_type& k, Object::objects_type& os) const\n {\n \/\/\/ Look in local slots.\n slots_type::const_iterator it = slots_.find (k);\n if (libport::mhas(slots_, k))\n return locate_type(true, rObject());\n\n \/\/\/ Break recursive loops.\n if (libport::mhas(os, this))\n return locate_type(false, rObject());\n os.insert (this);\n\n \/\/\/ Look in proto slots (depth first search).\n locate_type res;\n BOOST_FOREACH(rObject p, protos_)\n if ((res = p->slot_locate(k, os)).first)\n\treturn res.second?res:locate_type(true, p);\n return locate_type(false, rObject());\n }\n\n rObject slot_locate(const rObject& ref, const Object::key_type& k)\n {\n Object::objects_type os;\n Object::locate_type l = ref->slot_locate(k, os);\n if (l.first)\n return l.second? l.second:ref;\n else\n return rObject();\n }\n\n Object*\n Object::slot_locate(const key_type& k) const\n {\n objects_type os;\n Object::locate_type l = slot_locate(k, os);\n if (l.first)\n return const_cast(l.second?l.second.get():this);\n else\n return 0;\n }\n\n Object&\n Object::safe_slot_locate(const key_type& k) const\n {\n Object* r = slot_locate(k);\n if (!r)\n boost::throw_exception (LookupError(k));\n return *r;\n }\n\n const rObject&\n Object::slot_get (const key_type& k) const\n {\n Object& cont = safe_slot_locate(k);\n return cont.own_slot_get(k);\n }\n\n rObject&\n Object::slot_get (const key_type& k)\n {\n return const_cast(const_cast(this)->slot_get(k));\n }\n\n\n Object&\n Object::slot_set (const Object::key_type& k, rObject o)\n {\n if (libport::mhas(slots_, k))\n boost::throw_exception (RedefinitionError(k));\n slots_[k] = o;\n return *this;\n }\n\n\n Object&\n Object::slot_update (const Object::key_type& k, rObject o)\n {\n Object& l = safe_slot_locate(k);\n\n if (locals_ && l.locals_) \/\/ Local scope writes local var: no copyonwrite.\n l.own_slot_get(k) = o;\n else if (locals_ && !l.locals_)\n {\n \/\/ Local->class: copyonwrite to \"self\".\n rObject self = slot_get(SYMBOL(self));\n assert(self);\n if (self.get() == this)\n\tslots_[k] = o;\n else\n\tself->slot_update(k, o);\n }\n else \/\/ Class->class: copy on write.\n slots_[k] = o;\n\n return *this;\n }\n\n \/*-----------.\n | Printing. |\n `-----------*\/\n\n std::ostream&\n Object::special_slots_dump (std::ostream& o) const\n {\n return o;\n }\n\n bool\n Object::operator< (const Object& rhs) const\n {\n return this < &rhs;\n }\n\n std::ostream&\n Object::id_dump (std::ostream& o) const\n {\n try\n {\n \/\/ Should be an rString.\n o << slot_get(SYMBOL(type)).cast()->value_get ();\n }\n catch (UrbiException&)\n {}\n return o << '_' << this;\n }\n\n\n std::ostream&\n Object::dump (std::ostream& o) const\n {\n id_dump (o);\n \/\/\/ Use xalloc\/iword to store our current depth within the stream object.\n static const long idx = o.xalloc();\n static const long depth_max = 3;\n long& current_depth = o.iword(idx);\n \/\/\/ Stop recursion at depth_max.\n if (current_depth > depth_max)\n return o << \" <...>\";\n ++current_depth;\n o << \" {\" << libport::incendl;\n if (protos_.begin () != protos_.end ())\n {\n\to << \"protos = \";\n\tfor (protos_type::const_iterator i = protos_.begin ();\n\t i != protos_.end (); ++i)\n\t {\n\t if (i != protos_.begin())\n\t o << \", \";\n\t (*i)->id_dump (o);\n\t }\n\to << libport::iendl;\n }\n special_slots_dump (o);\n BOOST_FOREACH (slot_type s, slots_)\n o << s << libport::iendl;\n o << libport::decindent << '}';\n \/\/We can not reuse current_depth variable above according to spec.\n o.iword(idx)--;\n return o;\n }\n\n std::ostream&\n Object::print(std::ostream& out) const\n {\n \/\/ Temporary hack, detect void and print nothing\n if (this == void_class.get())\n return out;\n \/\/ FIXME: Decide what should be printed, but at least print something\n return out << \"\";\n }\n\n} \/\/ namespace object\nSimplify useless recursion\/**\n ** \\file object\/object.cc\n ** \\brief Implementation of object::Object.\n *\/\n\n#include \n\n#include \n#include \n\n#include \"libport\/containers.hh\"\n\n#include \"object\/object.hh\"\n#include \"object\/atom.hh\"\n#include \"object\/urbi-exception.hh\"\n\nnamespace object\n{\n \/*-------.\n | kind. |\n `-------*\/\n\n const char*\n Object::string_of (Object::kind_type k)\n {\n switch (k)\n {\n#define CASE(What, Name) case kind_ ## What: return #Name; break;\n\tAPPLY_ON_ALL_PRIMITIVES(CASE);\n#undef CASE\n }\n pabort(\"unreachable\");\n }\n\n \/*--------.\n | Slots. |\n `--------*\/\n\n Object::locate_type\n Object::slot_locate (const key_type& k, Object::objects_type& os) const\n {\n \/\/\/ Look in local slots.\n slots_type::const_iterator it = slots_.find (k);\n if (libport::mhas(slots_, k))\n return locate_type(true, rObject());\n\n \/\/\/ Break recursive loops.\n if (libport::mhas(os, this))\n return locate_type(false, rObject());\n os.insert (this);\n\n \/\/\/ Look in proto slots (depth first search).\n locate_type res;\n BOOST_FOREACH(rObject p, protos_)\n if ((res = p->slot_locate(k, os)).first)\n\treturn res.second?res:locate_type(true, p);\n return locate_type(false, rObject());\n }\n\n rObject slot_locate(const rObject& ref, const Object::key_type& k)\n {\n Object::objects_type os;\n Object::locate_type l = ref->slot_locate(k, os);\n if (l.first)\n return l.second? l.second:ref;\n else\n return rObject();\n }\n\n Object*\n Object::slot_locate(const key_type& k) const\n {\n objects_type os;\n Object::locate_type l = slot_locate(k, os);\n if (l.first)\n return const_cast(l.second?l.second.get():this);\n else\n return 0;\n }\n\n Object&\n Object::safe_slot_locate(const key_type& k) const\n {\n Object* r = slot_locate(k);\n if (!r)\n boost::throw_exception (LookupError(k));\n return *r;\n }\n\n const rObject&\n Object::slot_get (const key_type& k) const\n {\n Object& cont = safe_slot_locate(k);\n return cont.own_slot_get(k);\n }\n\n rObject&\n Object::slot_get (const key_type& k)\n {\n return const_cast(const_cast(this)->slot_get(k));\n }\n\n\n Object&\n Object::slot_set (const Object::key_type& k, rObject o)\n {\n if (libport::mhas(slots_, k))\n boost::throw_exception (RedefinitionError(k));\n slots_[k] = o;\n return *this;\n }\n\n\n Object&\n Object::slot_update (const Object::key_type& k, rObject o)\n {\n Object& l = safe_slot_locate(k);\n\n if (locals_ && l.locals_) \/\/ Local scope writes local var: no copyonwrite.\n l.own_slot_get(k) = o;\n else if (locals_ && !l.locals_)\n {\n \/\/ Local->class: copyonwrite to \"self\".\n rObject self = slot_get(SYMBOL(self));\n assert(self);\n self.get ()->slots_[k] = o;\n }\n else \/\/ Class->class: copy on write.\n slots_[k] = o;\n\n return *this;\n }\n\n \/*-----------.\n | Printing. |\n `-----------*\/\n\n std::ostream&\n Object::special_slots_dump (std::ostream& o) const\n {\n return o;\n }\n\n bool\n Object::operator< (const Object& rhs) const\n {\n return this < &rhs;\n }\n\n std::ostream&\n Object::id_dump (std::ostream& o) const\n {\n try\n {\n \/\/ Should be an rString.\n o << slot_get(SYMBOL(type)).cast()->value_get ();\n }\n catch (UrbiException&)\n {}\n return o << '_' << this;\n }\n\n\n std::ostream&\n Object::dump (std::ostream& o) const\n {\n id_dump (o);\n \/\/\/ Use xalloc\/iword to store our current depth within the stream object.\n static const long idx = o.xalloc();\n static const long depth_max = 3;\n long& current_depth = o.iword(idx);\n \/\/\/ Stop recursion at depth_max.\n if (current_depth > depth_max)\n return o << \" <...>\";\n ++current_depth;\n o << \" {\" << libport::incendl;\n if (protos_.begin () != protos_.end ())\n {\n\to << \"protos = \";\n\tfor (protos_type::const_iterator i = protos_.begin ();\n\t i != protos_.end (); ++i)\n\t {\n\t if (i != protos_.begin())\n\t o << \", \";\n\t (*i)->id_dump (o);\n\t }\n\to << libport::iendl;\n }\n special_slots_dump (o);\n BOOST_FOREACH (slot_type s, slots_)\n o << s << libport::iendl;\n o << libport::decindent << '}';\n \/\/We can not reuse current_depth variable above according to spec.\n o.iword(idx)--;\n return o;\n }\n\n std::ostream&\n Object::print(std::ostream& out) const\n {\n \/\/ Temporary hack, detect void and print nothing\n if (this == void_class.get())\n return out;\n \/\/ FIXME: Decide what should be printed, but at least print something\n return out << \"\";\n }\n\n} \/\/ namespace object\n<|endoftext|>"} {"text":"\/\/ Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.\n\/\/\n\/\/ This file is part of the hpp-corbaserver.\n\/\/\n\/\/ This software is provided \"as is\" without warranty of any kind,\n\/\/ either expressed or implied, including but not limited to the\n\/\/ implied warranties of fitness for a particular purpose.\n\/\/\n\/\/ See the COPYING file for more information.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"obstacle.impl.hh\"\n#include \"tools.hh\"\n\n#include \"hpp\/corbaserver\/server.hh\"\n\nnamespace hpp\n{\n namespace corbaServer\n {\n namespace impl\n {\n Obstacle::Obstacle (corbaServer::Server* server)\n\t: server_ (server),\n\t problemSolver_ (server->problemSolver ())\n {}\n\n void Obstacle::loadObstacleModel (const char* package,\n\t\t\t\t\tconst char* filename,\n\t\t\t\t\tconst char* prefix)\n\tthrow (hpp::Error)\n {\n\ttry {\n\t model::DevicePtr_t device (model::Device::create\n\t\t\t\t (std::string (filename)));\n\t hpp::model::urdf::loadUrdfModel (device,\n\t\t\t\t\t \"anchor\",\n\t\t\t\t\t std::string (package),\n\t\t\t\t\t std::string (filename));\n\t \/\/ Detach objects from joints\n\t for (ObjectIterator itObj = device->objectIterator\n\t\t (hpp::model::COLLISION); !itObj.isEnd (); ++itObj) {\n\t CollisionObjectPtr_t obj = model::CollisionObject::create\n\t ((*itObj)->fcl ()->collisionGeometry(), (*itObj)->getTransform (),\n\t std::string (prefix) + (*itObj)->name ());\n\t problemSolver_->addObstacle (obj, true, true);\n\t hppDout (info, \"Adding obstacle \" << obj->name ());\n\t }\n\t} catch (const std::exception& exc) {\n\t throw hpp::Error (exc.what ());\n\t}\n }\n\n void Obstacle::removeObstacleFromJoint\n (const char* objectName, const char* jointName, Boolean collision,\n Boolean distance) throw (hpp::Error)\n {\n\tusing model::JointPtr_t;\n\tusing model::ObjectVector_t;\n\tusing model::COLLISION;\n\tusing model::DISTANCE;\n\tstd::string objName (objectName);\n\tstd::string jName (jointName);\n\n\ttry {\n\t JointPtr_t joint = problemSolver_->robot ()->getJointByName (jName);\n\t BodyPtr_t body = joint->linkedBody ();\n\t if (!body) {\n\t throw std::runtime_error\n\t (std::string (\"Joint \" + jName + std::string (\" has no body.\")));\n\t }\n\t if (collision) {\n\t bool found = false;\n\t for (ObjectVector_t::const_iterator itObj =\n\t\t body->outerObjects (COLLISION).begin ();\n\t\t itObj != body->outerObjects (COLLISION).end () &&\n\t\t !found; ++itObj) {\n\t if ((*itObj)->name () == objName) {\n\t\tfound = true;\n\t\tbody->removeOuterObject (*itObj, true, false);\n\t }\n\t }\n\t if (!found) {\n\t throw std::runtime_error\n\t\t(std::string (\"Joint \") + jName +\n\t\t std::string (\" has no outer object called \") + objName);\n\t }\n\t }\n\t if (distance) {\n\t bool found = false;\n\t for (ObjectVector_t::const_iterator itObj =\n\t\t body->outerObjects (DISTANCE).begin ();\n\t\t itObj != body->outerObjects (DISTANCE).end () &&\n\t\t !found; ++itObj) {\n\t if ((*itObj)->name () == objName) {\n\t\tfound = true;\n\t\tbody->removeOuterObject (*itObj, false, true);\n\t }\n\t }\n\t if (!found) {\n\t throw std::runtime_error\n\t\t(std::string (\"Joint \") + jName +\n\t\t std::string (\" has no outer object called \") + objName);\n\t }\n\t }\n\t} catch (const std::exception& exc) {\n\t throw hpp::Error (exc.what ());\n\t}\n }\n\n void\n Obstacle::addObstacle(const char* objectName, Boolean collision,\n\t\t\t Boolean distance)\n\tthrow (hpp::Error)\n {\n\tstd::string objName (objectName);\n\tCollisionGeometryPtr_t geometry;\n\t\/\/ Check that polyhedron exists.\n\tVertexMap_t::const_iterator itVertex = vertexMap_.find(objName);\n\tif (itVertex != vertexMap_.end ()) {\n\t PolyhedronPtr_t polyhedron = PolyhedronPtr_t (new Polyhedron_t);\n\t int res = polyhedron->beginModel ();\n\t if (res != fcl::BVH_OK) {\n\t std::ostringstream oss (\"fcl BVHReturnCode = \");\n\t oss << res;\n\t throw hpp::Error (oss.str ().c_str ());\n\t }\n\n\t polyhedron->addSubModel (itVertex->second, triangleMap_ [objName]);\n\t polyhedron->endModel ();\n\t geometry = polyhedron;\n\t} else {\n\t ShapeMap_t::iterator itShape = shapeMap_.find (objName);\n\t if (itShape != shapeMap_.end ()) {\n\t geometry = itShape->second;\n\t }\n\t}\n\tif (!geometry) {\n\t std::ostringstream oss (\"Object \");\n\t oss << objName << \" does not exist.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\n\tTransform3f pos; pos.setIdentity ();\n\tCollisionObjectPtr_t collisionObject\n\t (CollisionObject_t::create (geometry, pos, objName));\n\tproblemSolver_->addObstacle (collisionObject, collision, distance);\n }\n\n CollisionObjectPtr_t Obstacle::getObstacleByName (const char* name)\n {\n\tconst ObjectVector_t& collisionObstacles\n\t (problemSolver_->collisionObstacles ());\n\tfor (ObjectVector_t::const_iterator it = collisionObstacles.begin ();\n\t it != collisionObstacles.end (); it++) {\n\t CollisionObjectPtr_t object = *it;\n\t if (object->name () == name) {\n\t hppDout (info, \"found \\\"\"\n\t\t << object->name () << \"\\\" in the obstacle list.\");\n\t return object;\n\t }\n\t}\n\tconst ObjectVector_t& distanceObstacles\n\t (problemSolver_->distanceObstacles ());\n\tfor (ObjectVector_t::const_iterator it = distanceObstacles.begin ();\n\t it != distanceObstacles.end (); it++) {\n\t CollisionObjectPtr_t object = *it;\n\t if (object->name () == name) {\n\t hppDout (info, \"found \\\"\"\n\t\t << object->name () << \"\\\" in the obstacle list.\");\n\t return object;\n\t }\n\t}\n\treturn CollisionObjectPtr_t ();\n }\n\n void Obstacle::moveObstacle\n (const char* objectName, const CORBA::Double* cfg)\n\tthrow(hpp::Error)\n {\n\tCollisionObjectPtr_t object = getObstacleByName (objectName);\n\tif (object) {\n\t Transform3f mat;\n\t hppTransformToTransform3f (cfg, mat);\n\t object->move (mat);\n\t return;\n\t}\n\tstd::ostringstream oss (\"Object \");\n\toss << objectName << \" not found\";\n\tthrow hpp::Error (oss.str ().c_str ());\n }\n\n void Obstacle::getObstaclePosition (const char* objectName,\n\t\t\t\t\t Double* cfg)\n\t throw (hpp::Error)\n {\n\tCollisionObjectPtr_t object = getObstacleByName (objectName);\n\tif (object) {\n\t Transform3f transform = object->getTransform ();\n\t Transform3fTohppTransform (transform, cfg);\n\t return;\n\t}\n\tstd::ostringstream oss (\"Object \");\n\toss << objectName << \" not found\";\n\tthrow hpp::Error (oss.str ().c_str ());\n }\n\n void Obstacle::createPolyhedron\n (const char* polyhedronName) throw (hpp::Error)\n {\n\t\/\/ Check that polyhedron does not already exist.\n\tif (vertexMap_.find(polyhedronName) != vertexMap_.end ()) {\n\t std::ostringstream oss (\"polyhedron \");\n\t oss << polyhedronName << \" already exists.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\tvertexMap_ [polyhedronName] = std::vector ();\n\ttriangleMap_ [polyhedronName] = std::vector ();\n }\n\n void Obstacle::createBox\n (const char* boxName, Double x, Double y, Double z)\n\tthrow (hpp::Error)\n {\n\tstd::string shapeName(boxName);\n\t\/\/ Check that object does not already exist.\n\tif (vertexMap_.find(shapeName) != vertexMap_.end () ||\n\t shapeMap_.find (shapeName) != shapeMap_.end ()) {\n\t std::ostringstream oss (\"object \");\n\t oss << shapeName << \" already exists.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\tBasicShapePtr_t box (new fcl::Box ( x, y, z));\n\tshapeMap_[shapeName] = box;\n }\n\n Short Obstacle::addPoint\n (const char* polyhedronName, Double x, Double y, Double z)\n\tthrow (hpp::Error)\n {\n\t\/\/ Check that polyhedron exists.\n\tVertexMap_t::iterator itVertex = vertexMap_.find (polyhedronName);\n\tif (itVertex == vertexMap_.end ()) {\n\t std::ostringstream oss (\"polyhedron \");\n\t oss << polyhedronName << \" does not exist.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\titVertex->second.push_back (fcl::Vec3f (x, y, z));\n\treturn static_cast (vertexMap_.size ());\n }\n\n Short\n Obstacle::addTriangle\n (const char* polyhedronName, ULong pt1, ULong pt2, ULong pt3)\n\tthrow (hpp::Error)\n {\n\t\/\/ Check that polyhedron exists.\n\tTriangleMap_t::iterator itTriangle = triangleMap_.find (polyhedronName);\n\tif (itTriangle == triangleMap_.end ()) {\n\t std::ostringstream oss (\"polyhedron \");\n\t oss << polyhedronName << \" does not exist.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\n\titTriangle->second.push_back (fcl::Triangle (pt1, pt2, pt3));\n\treturn static_cast (triangleMap_.size ());\n }\n } \/\/ end of namespace implementation.\n } \/\/ end of namespace corbaServer.\n} \/\/ end of namespace hpp.\nUpdate method removeObstacleFromJoint.\/\/ Copyright (C) 2009, 2010 by Florent Lamiraux, Thomas Moulard, JRL.\n\/\/\n\/\/ This file is part of the hpp-corbaserver.\n\/\/\n\/\/ This software is provided \"as is\" without warranty of any kind,\n\/\/ either expressed or implied, including but not limited to the\n\/\/ implied warranties of fitness for a particular purpose.\n\/\/\n\/\/ See the COPYING file for more information.\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"obstacle.impl.hh\"\n#include \"tools.hh\"\n\n#include \"hpp\/corbaserver\/server.hh\"\n\nnamespace hpp\n{\n namespace corbaServer\n {\n namespace impl\n {\n Obstacle::Obstacle (corbaServer::Server* server)\n\t: server_ (server),\n\t problemSolver_ (server->problemSolver ())\n {}\n\n void Obstacle::loadObstacleModel (const char* package,\n\t\t\t\t\tconst char* filename,\n\t\t\t\t\tconst char* prefix)\n\tthrow (hpp::Error)\n {\n\ttry {\n\t model::DevicePtr_t device (model::Device::create\n\t\t\t\t (std::string (filename)));\n\t hpp::model::urdf::loadUrdfModel (device,\n\t\t\t\t\t \"anchor\",\n\t\t\t\t\t std::string (package),\n\t\t\t\t\t std::string (filename));\n\t \/\/ Detach objects from joints\n\t for (ObjectIterator itObj = device->objectIterator\n\t\t (hpp::model::COLLISION); !itObj.isEnd (); ++itObj) {\n\t CollisionObjectPtr_t obj = model::CollisionObject::create\n\t ((*itObj)->fcl ()->collisionGeometry(), (*itObj)->getTransform (),\n\t std::string (prefix) + (*itObj)->name ());\n\t problemSolver_->addObstacle (obj, true, true);\n\t hppDout (info, \"Adding obstacle \" << obj->name ());\n\t }\n\t} catch (const std::exception& exc) {\n\t throw hpp::Error (exc.what ());\n\t}\n }\n\n void Obstacle::removeObstacleFromJoint\n (const char* objectName, const char* jointName, Boolean collision,\n Boolean distance) throw (hpp::Error)\n {\n\tusing model::JointPtr_t;\n\tusing model::ObjectVector_t;\n\tusing model::COLLISION;\n\tusing model::DISTANCE;\n\tstd::string objName (objectName);\n\tstd::string jName (jointName);\n\n\ttry {\n\t if (collision) {\n\t problemSolver_->removeObstacleFromJoint (objectName, jointName);\n\t }\n\t if (distance) {\n\t throw std::runtime_error (\"Not implemented.\");\n\t }\n\t} catch (const std::exception& exc) {\n\t throw hpp::Error (exc.what ());\n\t}\n }\n\n void\n Obstacle::addObstacle(const char* objectName, Boolean collision,\n\t\t\t Boolean distance)\n\tthrow (hpp::Error)\n {\n\tstd::string objName (objectName);\n\tCollisionGeometryPtr_t geometry;\n\t\/\/ Check that polyhedron exists.\n\tVertexMap_t::const_iterator itVertex = vertexMap_.find(objName);\n\tif (itVertex != vertexMap_.end ()) {\n\t PolyhedronPtr_t polyhedron = PolyhedronPtr_t (new Polyhedron_t);\n\t int res = polyhedron->beginModel ();\n\t if (res != fcl::BVH_OK) {\n\t std::ostringstream oss (\"fcl BVHReturnCode = \");\n\t oss << res;\n\t throw hpp::Error (oss.str ().c_str ());\n\t }\n\n\t polyhedron->addSubModel (itVertex->second, triangleMap_ [objName]);\n\t polyhedron->endModel ();\n\t geometry = polyhedron;\n\t} else {\n\t ShapeMap_t::iterator itShape = shapeMap_.find (objName);\n\t if (itShape != shapeMap_.end ()) {\n\t geometry = itShape->second;\n\t }\n\t}\n\tif (!geometry) {\n\t std::ostringstream oss (\"Object \");\n\t oss << objName << \" does not exist.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\n\tTransform3f pos; pos.setIdentity ();\n\tCollisionObjectPtr_t collisionObject\n\t (CollisionObject_t::create (geometry, pos, objName));\n\tproblemSolver_->addObstacle (collisionObject, collision, distance);\n }\n\n CollisionObjectPtr_t Obstacle::getObstacleByName (const char* name)\n {\n\tconst ObjectVector_t& collisionObstacles\n\t (problemSolver_->collisionObstacles ());\n\tfor (ObjectVector_t::const_iterator it = collisionObstacles.begin ();\n\t it != collisionObstacles.end (); it++) {\n\t CollisionObjectPtr_t object = *it;\n\t if (object->name () == name) {\n\t hppDout (info, \"found \\\"\"\n\t\t << object->name () << \"\\\" in the obstacle list.\");\n\t return object;\n\t }\n\t}\n\tconst ObjectVector_t& distanceObstacles\n\t (problemSolver_->distanceObstacles ());\n\tfor (ObjectVector_t::const_iterator it = distanceObstacles.begin ();\n\t it != distanceObstacles.end (); it++) {\n\t CollisionObjectPtr_t object = *it;\n\t if (object->name () == name) {\n\t hppDout (info, \"found \\\"\"\n\t\t << object->name () << \"\\\" in the obstacle list.\");\n\t return object;\n\t }\n\t}\n\treturn CollisionObjectPtr_t ();\n }\n\n void Obstacle::moveObstacle\n (const char* objectName, const CORBA::Double* cfg)\n\tthrow(hpp::Error)\n {\n\tCollisionObjectPtr_t object = getObstacleByName (objectName);\n\tif (object) {\n\t Transform3f mat;\n\t hppTransformToTransform3f (cfg, mat);\n\t object->move (mat);\n\t return;\n\t}\n\tstd::ostringstream oss (\"Object \");\n\toss << objectName << \" not found\";\n\tthrow hpp::Error (oss.str ().c_str ());\n }\n\n void Obstacle::getObstaclePosition (const char* objectName,\n\t\t\t\t\t Double* cfg)\n\t throw (hpp::Error)\n {\n\tCollisionObjectPtr_t object = getObstacleByName (objectName);\n\tif (object) {\n\t Transform3f transform = object->getTransform ();\n\t Transform3fTohppTransform (transform, cfg);\n\t return;\n\t}\n\tstd::ostringstream oss (\"Object \");\n\toss << objectName << \" not found\";\n\tthrow hpp::Error (oss.str ().c_str ());\n }\n\n void Obstacle::createPolyhedron\n (const char* polyhedronName) throw (hpp::Error)\n {\n\t\/\/ Check that polyhedron does not already exist.\n\tif (vertexMap_.find(polyhedronName) != vertexMap_.end ()) {\n\t std::ostringstream oss (\"polyhedron \");\n\t oss << polyhedronName << \" already exists.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\tvertexMap_ [polyhedronName] = std::vector ();\n\ttriangleMap_ [polyhedronName] = std::vector ();\n }\n\n void Obstacle::createBox\n (const char* boxName, Double x, Double y, Double z)\n\tthrow (hpp::Error)\n {\n\tstd::string shapeName(boxName);\n\t\/\/ Check that object does not already exist.\n\tif (vertexMap_.find(shapeName) != vertexMap_.end () ||\n\t shapeMap_.find (shapeName) != shapeMap_.end ()) {\n\t std::ostringstream oss (\"object \");\n\t oss << shapeName << \" already exists.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\tBasicShapePtr_t box (new fcl::Box ( x, y, z));\n\tshapeMap_[shapeName] = box;\n }\n\n Short Obstacle::addPoint\n (const char* polyhedronName, Double x, Double y, Double z)\n\tthrow (hpp::Error)\n {\n\t\/\/ Check that polyhedron exists.\n\tVertexMap_t::iterator itVertex = vertexMap_.find (polyhedronName);\n\tif (itVertex == vertexMap_.end ()) {\n\t std::ostringstream oss (\"polyhedron \");\n\t oss << polyhedronName << \" does not exist.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\titVertex->second.push_back (fcl::Vec3f (x, y, z));\n\treturn static_cast (vertexMap_.size ());\n }\n\n Short\n Obstacle::addTriangle\n (const char* polyhedronName, ULong pt1, ULong pt2, ULong pt3)\n\tthrow (hpp::Error)\n {\n\t\/\/ Check that polyhedron exists.\n\tTriangleMap_t::iterator itTriangle = triangleMap_.find (polyhedronName);\n\tif (itTriangle == triangleMap_.end ()) {\n\t std::ostringstream oss (\"polyhedron \");\n\t oss << polyhedronName << \" does not exist.\";\n\t throw hpp::Error (oss.str ().c_str ());\n\t}\n\n\titTriangle->second.push_back (fcl::Triangle (pt1, pt2, pt3));\n\treturn static_cast (triangleMap_.size ());\n }\n } \/\/ end of namespace implementation.\n } \/\/ end of namespace corbaServer.\n} \/\/ end of namespace hpp.\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2004-2008 See the AUTHORS file for details.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 as published\n * by the Free Software Foundation.\n *\/\n\n#include \"User.h\"\n#include \"znc.h\"\n\n\/\/ Forward Declaration\nclass CShellMod;\n\nclass CShellSock : public CExecSock {\npublic:\n\tCShellSock(CShellMod* pShellMod, CClient* pClient, const CString& sExec) : CExecSock( sExec ) {\n\t\tEnableReadLine();\n\t\tm_pParent = pShellMod;\n\t\tm_pClient = pClient;\n\t}\n\t\/\/ These next two function's bodies are at the bottom of the file since they reference CShellMod\n\tvirtual void ReadLine(const CString& sData);\n\tvirtual void Disconnected();\n\n\tCShellMod*\tm_pParent;\n\nprivate:\n\tCClient*\tm_pClient;\n};\n\nclass CShellMod : public CModule {\npublic:\n\tMODCONSTRUCTOR(CShellMod) {\n\t\tm_sPath = CZNC::Get().GetHomePath();\n\t}\n\n\tvirtual ~CShellMod() {\n\t\tvector vSocks = m_pManager->FindSocksByName(\"SHELL\");\n\n\t\tfor (unsigned int a = 0; a < vSocks.size(); a++) {\n\t\t\tm_pManager->DelSockByAddr(vSocks[a]);\n\t\t}\n\t}\n\n\tvirtual bool OnLoad(const CString& sArgs, CString& sMessage)\n\t{\n#ifndef MOD_SHELL_ALLOW_EVERYONE\n\t\tif (!m_pUser->IsAdmin()) {\n\t\t\tsMessage = \"You must be admin to use the shell module\";\n\t\t\treturn false;\n\t\t}\n#endif\n\n\t\treturn true;\n\t}\n\n\tvirtual void OnModCommand(const CString& sCommand) {\n\t\tif ((strcasecmp(sCommand.c_str(), \"cd\") == 0) || (strncasecmp(sCommand.c_str(), \"cd \", 3) == 0)) {\n\t\t\tCString sPath = CUtils::ChangeDir(m_sPath, ((sCommand.length() == 2) ? CString(CZNC::Get().GetHomePath()) : CString(sCommand.substr(3))), CZNC::Get().GetHomePath());\n\t\t\tCFile Dir(sPath);\n\n\t\t\tif (Dir.IsDir()) {\n\t\t\t\tm_sPath = sPath;\n\t\t\t} else if (Dir.Exists()) {\n\t\t\t\tPutShell(\"cd: not a directory [\" + sPath + \"]\");\n\t\t\t} else {\n\t\t\t\tPutShell(\"cd: no such directory [\" + sPath + \"]\");\n\t\t\t}\n\n\t\t\tPutShell(\"znc$\");\n\t\t} else if (strcasecmp(sCommand.Token(0).c_str(), \"SEND\") == 0) {\n\t\t\tCString sToNick = sCommand.Token(1);\n\t\t\tCString sFile = sCommand.Token(2);\n\n\t\t\tif ((sToNick.empty()) || (sFile.empty())) {\n\t\t\t\tPutShell(\"usage: Send \");\n\t\t\t} else {\n\t\t\t\tsFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());\n\n\t\t\t\tif (!CFile::Exists(sFile)) {\n\t\t\t\t\tPutShell(\"get: no such file [\" + sFile + \"]\");\n\t\t\t\t} else if (!CFile::IsReg(sFile)) {\n\t\t\t\t\tPutShell(\"get: not a file [\" + sFile + \"]\");\n\t\t\t\t} else {\n\t\t\t\t\tm_pUser->SendFile(sToNick, sFile, GetModName());\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (strcasecmp(sCommand.Token(0).c_str(), \"GET\") == 0) {\n\t\t\tCString sFile = sCommand.Token(1);\n\n\t\t\tif (sFile.empty()) {\n\t\t\t\tPutShell(\"usage: Get \");\n\t\t\t} else {\n\t\t\t\tsFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());\n\n\t\t\t\tif (!CFile::Exists(sFile)) {\n\t\t\t\t\tPutShell(\"get: no such file [\" + sFile + \"]\");\n\t\t\t\t} else if (!CFile::IsReg(sFile)) {\n\t\t\t\t\tPutShell(\"get: not a file [\" + sFile + \"]\");\n\t\t\t\t} else {\n\t\t\t\t\tm_pUser->SendFile(m_pUser->GetCurNick(), sFile, GetModName());\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tRunCommand(sCommand);\n\t\t}\n\t}\n\n\tvirtual EModRet OnStatusCommand(const CString& sCommand) {\n\t\tif (strcasecmp(sCommand.c_str(), \"SHELL\") == 0) {\n\t\t\tPutShell(\"-- ZNC Shell Service --\");\n\t\t\treturn HALT;\n\t\t}\n\n\t\treturn CONTINUE;\n\t}\n\n\tvirtual EModRet OnDCCUserSend(const CNick& RemoteNick, unsigned long uLongIP, unsigned short uPort, const CString& sFile, unsigned long uFileSize) {\n\t\tif (strcasecmp(RemoteNick.GetNick().c_str(), CString(GetModNick()).c_str()) == 0) {\n\t\t\tCString sLocalFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());\n\n\t\t\tm_pUser->GetFile(m_pUser->GetCurNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize, GetModName());\n\n\t\t\treturn HALT;\n\t\t}\n\n\t\treturn CONTINUE;\n\t}\n\n\tvoid PutShell(const CString& sLine) {\n\t\tCString sPath = m_sPath;\n\n\t\tCString::size_type a = sPath.find(' ');\n\t\twhile (a != CString::npos) {\n\t\t\tsPath.replace(a, 1, \"_\");\n\t\t\ta = sPath.find(' ');\n\t\t}\n\n\t\tPutModule(sLine, m_pUser->GetCurNick(), sPath);\n\t}\n\n\tvoid RunCommand(const CString& sCommand) {\n\t\tm_pManager->AddSock((Csock*) new CShellSock(this, m_pClient, \"cd \" + m_sPath + \" && \" + sCommand), \"SHELL\");\n\t}\nprivate:\n\tCString\tm_sPath;\n};\n\nvoid CShellSock::ReadLine(const CString& sData) {\n\tCString sLine = sData;\n\n\twhile (sLine.length() && (sLine[sLine.length() -1] == '\\r' || sLine[sLine.length() -1] == '\\n')) {\n\t\tsLine = sLine.substr(0, sLine.length() -1);\n\t}\n\n\tCString::size_type a = sLine.find('\\t');\n\twhile (a != CString::npos) {\n\t\tsLine.replace(a, 1, \" \");\n\t\ta = sLine.find('\\t');\n\t}\n\n\tm_pParent->SetClient(m_pClient);\n\tm_pParent->PutShell(sLine);\n\tm_pParent->SetClient(NULL);\n}\n\nvoid CShellSock::Disconnected() {\n\tm_pParent->SetClient(m_pClient);\n\tm_pParent->PutShell(\"znc$\");\n\tm_pParent->SetClient(NULL);\n}\n\nMODULEDEFS(CShellMod, \"Gives shell access\")\n\nShell module: Also read incomplete lines (no trailing newline) and display them\/*\n * Copyright (C) 2004-2008 See the AUTHORS file for details.\n *\n * This program is free software; you can redistribute it and\/or modify it\n * under the terms of the GNU General Public License version 2 as published\n * by the Free Software Foundation.\n *\/\n\n#include \"User.h\"\n#include \"znc.h\"\n\n\/\/ Forward Declaration\nclass CShellMod;\n\nclass CShellSock : public CExecSock {\npublic:\n\tCShellSock(CShellMod* pShellMod, CClient* pClient, const CString& sExec) : CExecSock( sExec ) {\n\t\tEnableReadLine();\n\t\tm_pParent = pShellMod;\n\t\tm_pClient = pClient;\n\t}\n\t\/\/ These next two function's bodies are at the bottom of the file since they reference CShellMod\n\tvirtual void ReadLine(const CString& sData);\n\tvirtual void Disconnected();\n\n\tCShellMod*\tm_pParent;\n\nprivate:\n\tCClient*\tm_pClient;\n};\n\nclass CShellMod : public CModule {\npublic:\n\tMODCONSTRUCTOR(CShellMod) {\n\t\tm_sPath = CZNC::Get().GetHomePath();\n\t}\n\n\tvirtual ~CShellMod() {\n\t\tvector vSocks = m_pManager->FindSocksByName(\"SHELL\");\n\n\t\tfor (unsigned int a = 0; a < vSocks.size(); a++) {\n\t\t\tm_pManager->DelSockByAddr(vSocks[a]);\n\t\t}\n\t}\n\n\tvirtual bool OnLoad(const CString& sArgs, CString& sMessage)\n\t{\n#ifndef MOD_SHELL_ALLOW_EVERYONE\n\t\tif (!m_pUser->IsAdmin()) {\n\t\t\tsMessage = \"You must be admin to use the shell module\";\n\t\t\treturn false;\n\t\t}\n#endif\n\n\t\treturn true;\n\t}\n\n\tvirtual void OnModCommand(const CString& sCommand) {\n\t\tif ((strcasecmp(sCommand.c_str(), \"cd\") == 0) || (strncasecmp(sCommand.c_str(), \"cd \", 3) == 0)) {\n\t\t\tCString sPath = CUtils::ChangeDir(m_sPath, ((sCommand.length() == 2) ? CString(CZNC::Get().GetHomePath()) : CString(sCommand.substr(3))), CZNC::Get().GetHomePath());\n\t\t\tCFile Dir(sPath);\n\n\t\t\tif (Dir.IsDir()) {\n\t\t\t\tm_sPath = sPath;\n\t\t\t} else if (Dir.Exists()) {\n\t\t\t\tPutShell(\"cd: not a directory [\" + sPath + \"]\");\n\t\t\t} else {\n\t\t\t\tPutShell(\"cd: no such directory [\" + sPath + \"]\");\n\t\t\t}\n\n\t\t\tPutShell(\"znc$\");\n\t\t} else if (strcasecmp(sCommand.Token(0).c_str(), \"SEND\") == 0) {\n\t\t\tCString sToNick = sCommand.Token(1);\n\t\t\tCString sFile = sCommand.Token(2);\n\n\t\t\tif ((sToNick.empty()) || (sFile.empty())) {\n\t\t\t\tPutShell(\"usage: Send \");\n\t\t\t} else {\n\t\t\t\tsFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());\n\n\t\t\t\tif (!CFile::Exists(sFile)) {\n\t\t\t\t\tPutShell(\"get: no such file [\" + sFile + \"]\");\n\t\t\t\t} else if (!CFile::IsReg(sFile)) {\n\t\t\t\t\tPutShell(\"get: not a file [\" + sFile + \"]\");\n\t\t\t\t} else {\n\t\t\t\t\tm_pUser->SendFile(sToNick, sFile, GetModName());\n\t\t\t\t}\n\t\t\t}\n\t\t} else if (strcasecmp(sCommand.Token(0).c_str(), \"GET\") == 0) {\n\t\t\tCString sFile = sCommand.Token(1);\n\n\t\t\tif (sFile.empty()) {\n\t\t\t\tPutShell(\"usage: Get \");\n\t\t\t} else {\n\t\t\t\tsFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());\n\n\t\t\t\tif (!CFile::Exists(sFile)) {\n\t\t\t\t\tPutShell(\"get: no such file [\" + sFile + \"]\");\n\t\t\t\t} else if (!CFile::IsReg(sFile)) {\n\t\t\t\t\tPutShell(\"get: not a file [\" + sFile + \"]\");\n\t\t\t\t} else {\n\t\t\t\t\tm_pUser->SendFile(m_pUser->GetCurNick(), sFile, GetModName());\n\t\t\t\t}\n\t\t\t}\n\t\t} else {\n\t\t\tRunCommand(sCommand);\n\t\t}\n\t}\n\n\tvirtual EModRet OnStatusCommand(const CString& sCommand) {\n\t\tif (strcasecmp(sCommand.c_str(), \"SHELL\") == 0) {\n\t\t\tPutShell(\"-- ZNC Shell Service --\");\n\t\t\treturn HALT;\n\t\t}\n\n\t\treturn CONTINUE;\n\t}\n\n\tvirtual EModRet OnDCCUserSend(const CNick& RemoteNick, unsigned long uLongIP, unsigned short uPort, const CString& sFile, unsigned long uFileSize) {\n\t\tif (strcasecmp(RemoteNick.GetNick().c_str(), CString(GetModNick()).c_str()) == 0) {\n\t\t\tCString sLocalFile = CUtils::ChangeDir(m_sPath, sFile, CZNC::Get().GetHomePath());\n\n\t\t\tm_pUser->GetFile(m_pUser->GetCurNick(), CUtils::GetIP(uLongIP), uPort, sLocalFile, uFileSize, GetModName());\n\n\t\t\treturn HALT;\n\t\t}\n\n\t\treturn CONTINUE;\n\t}\n\n\tvoid PutShell(const CString& sLine) {\n\t\tCString sPath = m_sPath;\n\n\t\tCString::size_type a = sPath.find(' ');\n\t\twhile (a != CString::npos) {\n\t\t\tsPath.replace(a, 1, \"_\");\n\t\t\ta = sPath.find(' ');\n\t\t}\n\n\t\tPutModule(sLine, m_pUser->GetCurNick(), sPath);\n\t}\n\n\tvoid RunCommand(const CString& sCommand) {\n\t\tm_pManager->AddSock((Csock*) new CShellSock(this, m_pClient, \"cd \" + m_sPath + \" && \" + sCommand), \"SHELL\");\n\t}\nprivate:\n\tCString\tm_sPath;\n};\n\nvoid CShellSock::ReadLine(const CString& sData) {\n\tCString sLine = sData;\n\n\twhile (sLine.length() && (sLine[sLine.length() -1] == '\\r' || sLine[sLine.length() -1] == '\\n')) {\n\t\tsLine = sLine.substr(0, sLine.length() -1);\n\t}\n\n\tCString::size_type a = sLine.find('\\t');\n\twhile (a != CString::npos) {\n\t\tsLine.replace(a, 1, \" \");\n\t\ta = sLine.find('\\t');\n\t}\n\n\tm_pParent->SetClient(m_pClient);\n\tm_pParent->PutShell(sLine);\n\tm_pParent->SetClient(NULL);\n}\n\nvoid CShellSock::Disconnected() {\n\t\/\/ If there is some incomplete line in the buffer, read it\n\t\/\/ (e.g. echo echo -n \"hi\" triggered this)\n\tCString &sBuffer = GetInternalBuffer();\n\tif (!sBuffer.empty())\n\t\tReadLine(sBuffer);\n\n\tm_pParent->SetClient(m_pClient);\n\tm_pParent->PutShell(\"znc$\");\n\tm_pParent->SetClient(NULL);\n}\n\nMODULEDEFS(CShellMod, \"Gives shell access\")\n\n<|endoftext|>"} {"text":"#include \n#include \n\nconst double FIRST_BRACKET_LENGTH = 18200;\nconst double SECOND_BRACKET_LENGTH = 18799;\nconst double THIRD_BRACKET_LENGTH = 42999;\nconst double FOURTH_BRACKET_LENGTH = 100000; \n\nconst double P_FIRST_BRACKET = 1;\nconst double P_SECOND_BRACKET = 0.81;\nconst double P_THIRD_BRACKET = 0.675;\nconst double P_FOURTH_BRACKET = 0.63;\nconst double P_LAST_BRACKET = 0.55;\n\n\ndouble tax_money_in_year(double income){\n\tdouble money_to_tax = income;\n\tdouble taxed_money = 0;\n\t\n\t\/\/ Between $0 - $18201\n\tif(money_to_tax >= 0){\n\t\t\/\/If under the first bracket, no tax is taken. \n\t\tif(money_to_tax < FIRST_BRACKET_LENGTH){\n\t\t\treturn money_to_tax;\n\t\t}\n\t\ttaxed_money += FIRST_BRACKET_LENGTH * P_FIRST_BRACKET;\n\t\tmoney_to_tax -= FIRST_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Between $18,201 - $37,000\n\tif(money_to_tax >= 0){\n\t\t\n\t\tif(money_to_tax < SECOND_BRACKET_LENGTH){\n\t\t\treturn taxed_money + (money_to_tax * P_SECOND_BRACKET);\n\t\t}\n\n\t\ttaxed_money += SECOND_BRACKET_LENGTH * P_SECOND_BRACKET;\n\t\tmoney_to_tax -= SECOND_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Between $37,001 - $80,000\n\tif(money_to_tax >= 0){\n\n\t\tif(money_to_tax < THIRD_BRACKET_LENGTH){\n\t\t\treturn taxed_money + (money_to_tax * P_THIRD_BRACKET);\n\t\t}\n\n\t\ttaxed_money += THIRD_BRACKET_LENGTH * P_THIRD_BRACKET;\n\t\tmoney_to_tax -= THIRD_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Between $80,001 - $180,000\n\tif(money_to_tax >= 0){\n\n\t\tif(money_to_tax < FOURTH_BRACKET_LENGTH){\n\t\t\treturn taxed_money + (money_to_tax * P_FOURTH_BRACKET);\n\t\t}\n\n\t\ttaxed_money += FOURTH_BRACKET_LENGTH * P_FOURTH_BRACKET;\n\t\tmoney_to_tax -= FOURTH_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Greater than $180,000\n\tif(money_to_tax >= 0){\n\t\ttaxed_money += money_to_tax * P_LAST_BRACKET;\n\t\tmoney_to_tax = 0;\n\t}\n\n\treturn taxed_money;\n}\n\nint main(int argc, char* argv[]){\n\n\tif(argc != 4){\n\t\tstd::cerr << \"Usage: (input) (output)\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tconst double user_input_wage = atof(argv[2]);\n\tdouble taxed_money_years;\n\n\t\/\/Convers it to yearly for storage\n\tswitch(*argv[1]){\n\t\tcase 'y': taxed_money_years = tax_money_in_year(user_input_wage); break;\n\t\tcase 'm': taxed_money_years = tax_money_in_year(user_input_wage * 12); break;\n\t\tcase 'w': taxed_money_years = tax_money_in_year(user_input_wage * 52); break;\n\t}\n\n\t\/\/Simply divides it back out.\n\tswitch(*argv[3]){\n\t\tcase 'y': std::cout << \"Yearly earnings after tax is $\" << taxed_money_years \/ 1.0 << std::endl; break;\n\t\tcase 'm': std::cout << \"Monthly earnings after tax is $\" << taxed_money_years \/ 12.0 << std::endl; break;\n\t\tcase 'w': std::cout << \"Weekly earnings after tax is $\" << taxed_money_years \/ 52.0 << std::endl; break;\n\t}\n\n\n\tswitch(*argv[3]){\n\t\tcase 'y': std::cout << \"You lose $\" << (user_input_wage\t) - (taxed_money_years \/ 1.0) << \" per year to the tax man\" << std::endl; break;\n\t\tcase 'm': std::cout << \"You lose $\" << (user_input_wage ) - (taxed_money_years \/ 12.0) << \" per month to the tax man\" << std::endl; break;\n\t\tcase 'w': std::cout << \"You lose $\" << (user_input_wage ) - (taxed_money_years \/ 52.0) << \" per week to the tax man\" << std::endl; break;\n\t}\n\n\tstd::cout << \"Done by Dale Salter(Note the estimates only work if the input and output are the same)\" << std::endl;\n\n\treturn 0;\n}CHANGE FOR VCS#include \n#include \n\nconst double FIRST_BRACKET_LENGTH = 18200;\nconst double SECOND_BRACKET_LENGTH = 18799;\nconst double THIRD_BRACKET_LENGTH = 42999;\nconst double FOURTH_BRACKET_LENGTH = 100000; \n\nconst double P_FIRST_BRACKET = 1;\nconst double P_SECOND_BRACKET = 0.81;\nconst double P_THIRD_BRACKET = 0.675;\nconst double P_FOURTH_BRACKET = 0.63;\nconst double P_LAST_BRACKET = 0.55;\n\n\ndouble tax_money_in_year(double income){\n\tdouble money_to_tax = income;\n\tdouble taxed_money = 0;\n\t\n\t\/\/ Between $0 - $18201\n\tif(money_to_tax >= 0){\n\t\t\/\/If under the first bracket, no tax is taken. \n\t\tif(money_to_tax < FIRST_BRACKET_LENGTH){\n\t\t\treturn money_to_tax;\n\t\t}\n\t\ttaxed_money += FIRST_BRACKET_LENGTH * P_FIRST_BRACKET;\n\t\tmoney_to_tax -= FIRST_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Between $18,201 - $37,000\n\tif(money_to_tax >= 0){\n\t\t\n\t\tif(money_to_tax < SECOND_BRACKET_LENGTH){\n\t\t\treturn taxed_money + (money_to_tax * P_SECOND_BRACKET);\n\t\t}\n\n\t\ttaxed_money += SECOND_BRACKET_LENGTH * P_SECOND_BRACKET;\n\t\tmoney_to_tax -= SECOND_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Between $37,001 - $80,000\n\tif(money_to_tax >= 0){\n\n\t\tif(money_to_tax < THIRD_BRACKET_LENGTH){\n\t\t\treturn taxed_money + (money_to_tax * P_THIRD_BRACKET);\n\t\t}\n\n\t\ttaxed_money += THIRD_BRACKET_LENGTH * P_THIRD_BRACKET;\n\t\tmoney_to_tax -= THIRD_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Between $80,001 - $180,000\n\tif(money_to_tax >= 0){\n\n\t\tif(money_to_tax < FOURTH_BRACKET_LENGTH){\n\t\t\treturn taxed_money + (money_to_tax * P_FOURTH_BRACKET);\n\t\t}\n\n\t\ttaxed_money += FOURTH_BRACKET_LENGTH * P_FOURTH_BRACKET;\n\t\tmoney_to_tax -= FOURTH_BRACKET_LENGTH;\n\t}\n\n\t\/\/ Greater than $180,000\n\tif(money_to_tax >= 0){\n\t\ttaxed_money += money_to_tax * P_LAST_BRACKET;\n\t\tmoney_to_tax = 0;\n\t}\n\n\treturn taxed_money;\n}\n\nint main(int argc, char* argv[]){\n\n\tif(argc != 4){\n\t\tstd::cerr << \"Usage: (input) (output)\" << std::endl;\n\t\treturn 1;\n\t}\n\n\tconst double user_input_wage = atof(argv[2]);\n\tdouble taxed_money_years;\n\n\t\/\/Convers it to yearly for storage\n\tswitch(*argv[1]){\n\t\tcase 'y': taxed_money_years = tax_money_in_year(user_input_wage); break;\n\t\tcase 'm': taxed_money_years = tax_money_in_year(user_input_wage * 12); break;\n\t\tcase 'w': taxed_money_years = tax_money_in_year(user_input_wage * 52); break;\n\t}\n\n\t\/\/Simply divides it back out.\n\tswitch(*argv[3]){\n\t\tcase 'y': std::cout << \"Yearly earnings after tax is $\" << taxed_money_years \/ 1.0 << std::endl; break;\n\t\tcase 'm': std::cout << \"Monthly earnings after tax is $\" << taxed_money_years \/ 12.0 << std::endl; break;\n\t\tcase 'w': std::cout << \"Weekly earnings after tax is $\" << taxed_money_years \/ 52.0 << std::endl; break;\n\t}\n\n\n\tswitch(*argv[3]){\n\t\tcase 'y': std::cout << \"You lose $\" << (user_input_wage\t) - (taxed_money_years \/ 1.0) << \" per year to the tax man\" << std::endl; break;\n\t\tcase 'm': std::cout << \"You lose $\" << (user_input_wage ) - (taxed_money_years \/ 12.0) << \" per month to the tax man\" << std::endl; break;\n\t\tcase 'w': std::cout << \"You lose $\" << (user_input_wage ) - (taxed_money_years \/ 52.0) << \" per week to the tax man\" << std::endl; break;\n\t}\n\n\tstd::cout << \"Done by Dale Salter(the input and output y\/m\/w have to be the same)\" << std::endl;\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include \n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n--allow-empty_message\/******************************************************************************\n * Copyright (c) 2014 Jamis Hoo \n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: test.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Dec. 29, 2014\n * Time: 11:10:09\n * Description: \n *****************************************************************************\/\n#include \n\nint main() {\n std::cout << \"Hello world!\" << std::endl;\n\n}\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n<|endoftext|>"} {"text":"planning: do not check traffic light color while creeping on right turn<|endoftext|>"} {"text":"\n#include \n#include \n\n#include \n\n#ifdef __APPLE__\n#include \n#endif \/\/\n\n#include \n#include \n#include \n\nnamespace lemon { namespace os {\n typedef std::wstring_convert, wchar_t> convert;\n\n host_t hostname()\n {\n\n #ifdef WIN32\n\t\treturn host_t::Windows;\n #elif defined(__linux)\n #ifdef __android\n return host_t::Android;\n #else\n return host_t::Linux;\n #endif\n #elif defined(__sun)\n return host_t::Solaris;\n #elif defined(__hppa)\n return host_t::HPUX;\n #elif defined(_AIX)\n return host_t::AIX;\n #elif defined(__APPLE__)\n #if TARGET_OS_SIMULATOR == 1\n return host_t::iOS_Simulator;\n #elif TARGET_OS_IPHONE == 1\n return host_t::iOS;\n #elif TARGET_OS_MAC == 1\n return host_t::OSX;\n #else\n return host_t::OSX_Unknown;\n #endif\n #endif \/\/WIN32\n }\n\n\tarch_t arch()\n\t{\n#if defined(__alpha__) || defined(_M_ALPHA) || defined(__alpha)\n\t\treturn arch_t::Alpha;\n#elif defined(__amd64__) || defined(__amd64) || defined(_M_X64)\n\t\treturn arch_t::AMD64;\n#elif defined(__arm__) || defined(_ARM) || defined(_M_ARM) || defined(_M_ARMT) || defined(__arm)\n\t\treturn arch_t::ARM;\n#elif defined(__aarch64__) || defined(__arm64__)\n\t\treturn arch_t::ARM64;\n#elif defined(__hppa__) || defined(__HPPA__)\n\t\treturn arch_t::HP_PA;\n#elif defined(__i386__) || defined(__i386) || defined(__i386) || defined(_M_IX86) || defined(_X86_)\n\t\treturn arch_t::X86;\n#elif defined(__mips__) || defined(__mips)\n\t\treturn arch_t::MIPS;\n#elif defined(__powerpc) || defined(_M_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_PPC)\n\t\treturn arch_t::PowerPC;\n#elif defined(__sparc__)\n\t\treturn arch_t::SPARC;\n#endif\n\t}\n\n\n\n #ifdef WIN32\n std::tuple getenv(const std::string &name)\n {\n auto namew = convert().from_bytes(name);\n\n DWORD length = ::GetEnvironmentVariableW(namew.c_str(), NULL, 0);\n\n if(length == 0)\n {\n return std::make_tuple(std::string(), false);\n }\n\n std::vector buff(length);\n\n ::GetEnvironmentVariableW(namew.c_str(), &buff[0], (DWORD)buff.size());\n\n return std::make_tuple(convert().to_bytes(&buff[0]), true);\n }\n\n\tvoid setenv(const std::string &name, const std::string &val,std::error_code &ec)\n\t{\n\t\tauto namew = convert().from_bytes(name);\n\n\t\tauto valnew = convert().from_bytes(val);\n\n\t\tif (!::SetEnvironmentVariableW(namew.c_str(), valnew.c_str()))\n\t\t{\n\t\t\tec = std::error_code(GetLastError(),std::system_category());\n\t\t}\n\t}\n\n #else\n\n std::tuple getenv(const std::string &name)\n {\n const char *val = ::getenv(name.c_str());\n\n if(val)\n {\n return std::make_tuple(std::string(val),true);\n }\n\n return std::make_tuple(std::string(), false);\n }\n\n\tvoid setenv(const std::string &name, const std::string &val, std::error_code &ec)\n\t{\n\t\tif (-1 == setenv(name.c_str(), val.c_str(), 1))\n\t\t{\n\t\t\tec = std::make_error_code(errno, std::system_category());\n\t\t}\n\t}\n\n #endif \/\/WIN32\n\n\n std::string execute_suffix()\n {\n #ifdef WIN32\n return \".exe\";\n #else\n return \"\";\n #endif\n }\n\n#ifndef WIN32\n std::string tmpdir(std::error_code & )\n {\n auto val = getenv(\"TMPDIR\");\n\n if(std::get<1>(val))\n {\n return std::get<0>(val);\n }\n#ifdef __android\n return \"\/data\/local\/tmp\";\n#endif\n\n return \"\/tmp\";\n }\n#else\n\n\n\tstd::string tmpdir(std::error_code & err)\n\t{\n\t\twchar_t buff[MAX_PATH + 1];\n\n\t\tauto length = ::GetTempPathW(MAX_PATH, buff);\n\n\t\tif(length == 0)\n\t\t{\n\t\t\terr = std::error_code(GetLastError(),std::system_category());\n\n\t\t\treturn \"\";\n\t\t}\n\n\t\treturn convert().to_bytes(std::wstring(buff, buff + length));\n\t}\n#endif\n\n\n std::tuple lookup(const std::string & cmd)\n {\n\n\t\tif(fs::exists(cmd))\n\t\t{\n\t\t\treturn std::make_tuple(fs::absolute(cmd).string(), true);\n\t\t}\n\n auto path = os::getenv(\"PATH\");\n\n if(!std::get<1>(path))\n {\n return std::make_tuple(std::string(),false);\n }\n\n #ifdef WIN32\n const std::string delimiter = \";\";\n const std::string extend = \".exe\";\n #else\n const std::string delimiter = \":\";\n const std::string extend = \"\";\n #endif \/\/WIN32\n\n auto paths = strings::split(std::get<0>(path), delimiter);\n\n #ifdef WIN32\n DWORD length = ::GetSystemDirectoryW(0, 0);\n\n std::vector buff(length);\n\n ::GetSystemDirectoryW(&buff[0], (UINT)buff.size());\n\n paths.push_back(convert().to_bytes(&buff[0]));\n #else\n #endif\n\n for(auto p : paths)\n {\n auto fullPath = fs::filepath(p) \/ (cmd + extend);\n\n if(fs::exists(fullPath))\n {\n return std::make_tuple(fullPath.string(), true);\n }\n }\n\n return std::make_tuple(std::string(), false);\n }\n}}fix some bugs\n#include \n#include \n\n#include \n\n#ifdef __APPLE__\n#include \n#endif \/\/\n\n#include \n#include \n#include \n\nnamespace lemon { namespace os {\n typedef std::wstring_convert, wchar_t> convert;\n\n host_t hostname()\n {\n\n #ifdef WIN32\n\t\treturn host_t::Windows;\n #elif defined(__linux)\n #ifdef __android\n return host_t::Android;\n #else\n return host_t::Linux;\n #endif\n #elif defined(__sun)\n return host_t::Solaris;\n #elif defined(__hppa)\n return host_t::HPUX;\n #elif defined(_AIX)\n return host_t::AIX;\n #elif defined(__APPLE__)\n #if TARGET_OS_SIMULATOR == 1\n return host_t::iOS_Simulator;\n #elif TARGET_OS_IPHONE == 1\n return host_t::iOS;\n #elif TARGET_OS_MAC == 1\n return host_t::OSX;\n #else\n return host_t::OSX_Unknown;\n #endif\n #endif \/\/WIN32\n }\n\n\tarch_t arch()\n\t{\n#if defined(__alpha__) || defined(_M_ALPHA) || defined(__alpha)\n\t\treturn arch_t::Alpha;\n#elif defined(__amd64__) || defined(__amd64) || defined(_M_X64)\n\t\treturn arch_t::AMD64;\n#elif defined(__arm__) || defined(_ARM) || defined(_M_ARM) || defined(_M_ARMT) || defined(__arm)\n\t\treturn arch_t::ARM;\n#elif defined(__aarch64__) || defined(__arm64__)\n\t\treturn arch_t::ARM64;\n#elif defined(__hppa__) || defined(__HPPA__)\n\t\treturn arch_t::HP_PA;\n#elif defined(__i386__) || defined(__i386) || defined(__i386) || defined(_M_IX86) || defined(_X86_)\n\t\treturn arch_t::X86;\n#elif defined(__mips__) || defined(__mips)\n\t\treturn arch_t::MIPS;\n#elif defined(__powerpc) || defined(_M_PPC) || defined(_ARCH_PPC64) || defined(_ARCH_PPC)\n\t\treturn arch_t::PowerPC;\n#elif defined(__sparc__)\n\t\treturn arch_t::SPARC;\n#endif\n\t}\n\n\n\n #ifdef WIN32\n std::tuple getenv(const std::string &name)\n {\n auto namew = convert().from_bytes(name);\n\n DWORD length = ::GetEnvironmentVariableW(namew.c_str(), NULL, 0);\n\n if(length == 0)\n {\n return std::make_tuple(std::string(), false);\n }\n\n std::vector buff(length);\n\n ::GetEnvironmentVariableW(namew.c_str(), &buff[0], (DWORD)buff.size());\n\n return std::make_tuple(convert().to_bytes(&buff[0]), true);\n }\n\n\tvoid setenv(const std::string &name, const std::string &val,std::error_code &ec)\n\t{\n\t\tauto namew = convert().from_bytes(name);\n\n\t\tauto valnew = convert().from_bytes(val);\n\n\t\tif (!::SetEnvironmentVariableW(namew.c_str(), valnew.c_str()))\n\t\t{\n\t\t\tec = std::error_code(GetLastError(),std::system_category());\n\t\t}\n\t}\n\n #else\n\n std::tuple getenv(const std::string &name)\n {\n const char *val = ::getenv(name.c_str());\n\n if(val)\n {\n return std::make_tuple(std::string(val),true);\n }\n\n return std::make_tuple(std::string(), false);\n }\n\n\tvoid setenv(const std::string &name, const std::string &val, std::error_code &ec)\n\t{\n\t\tif (-1 == setenv(name.c_str(), val.c_str(), 1))\n\t\t{\n\t\t\tec = std::make_error_code(errno, std::system_category());\n\t\t}\n\t}\n\n #endif \/\/WIN32\n\n\n std::string execute_suffix()\n {\n #ifdef WIN32\n return \".exe\";\n #else\n return \"\";\n #endif\n }\n\n#ifndef WIN32\n std::string tmpdir(std::error_code & )\n {\n auto val = getenv(\"TMPDIR\");\n\n if(std::get<1>(val))\n {\n return std::get<0>(val);\n }\n#ifdef __android\n return \"\/data\/local\/tmp\";\n#endif\n\n return \"\/tmp\";\n }\n#else\n\n\n\tstd::string tmpdir(std::error_code & err)\n\t{\n\t\twchar_t buff[MAX_PATH + 1];\n\n\t\tauto length = ::GetTempPathW(MAX_PATH, buff);\n\n\t\tif(length == 0)\n\t\t{\n\t\t\terr = std::error_code(GetLastError(),std::system_category());\n\n\t\t\treturn \"\";\n\t\t}\n\n\t\treturn convert().to_bytes(std::wstring(buff, buff + length));\n\t}\n#endif\n\n\n std::tuple lookup(const std::string & cmd)\n {\n\n\t\tif(fs::exists(cmd))\n\t\t{\n\t\t\treturn std::make_tuple(fs::absolute(cmd).string(), true);\n\t\t}\n\n auto path = os::getenv(\"PATH\");\n\n if(!std::get<1>(path))\n {\n return std::make_tuple(std::string(),false);\n }\n\n #ifdef WIN32\n const std::string delimiter = \";\";\n\t\tconst std::vector extends = { \".exe\",\".cmd\",\".bat\",\".com\" };\n #else\n const std::string delimiter = \":\";\n\t\tconst std::vector extends = { \"\" };\n #endif \/\/WIN32\n\n auto paths = strings::split(std::get<0>(path), delimiter);\n\n #ifdef WIN32\n DWORD length = ::GetSystemDirectoryW(0, 0);\n\n std::vector buff(length);\n\n ::GetSystemDirectoryW(&buff[0], (UINT)buff.size());\n\n paths.push_back(convert().to_bytes(&buff[0]));\n #else\n #endif\n\n for(auto p : paths)\n {\n\t\t\tfor (auto extend : extends)\n\t\t\t{\n\t\t\t\tauto fullPath = fs::filepath(p) \/ (cmd + extend);\n\n\t\t\t\tif (fs::exists(fullPath))\n\t\t\t\t{\n\t\t\t\t\treturn std::make_tuple(fullPath.string(), true);\n\t\t\t\t}\n\t\t\t}\n \n }\n\n return std::make_tuple(std::string(), false);\n }\n}}<|endoftext|>"} {"text":"\/\/===-- Writer.cpp - Library for writing LLVM bytecode files --------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This library implements the functionality defined in llvm\/Bytecode\/Writer.h\n\/\/\n\/\/ Note that this file uses an unusual technique of outputting all the bytecode\n\/\/ to a deque of unsigned char, then copies the deque to an ostream. The\n\/\/ reason for this is that we must do \"seeking\" in the stream to do back-\n\/\/ patching, and some very important ostreams that we want to support (like\n\/\/ pipes) do not support seeking. :( :( :(\n\/\/\n\/\/ The choice of the deque data structure is influenced by the extremely fast\n\/\/ \"append\" speed, plus the free \"seek\"\/replace in the middle of the stream. I\n\/\/ didn't use a vector because the stream could end up very large and copying\n\/\/ the whole thing to reallocate would be kinda silly.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"WriterInternals.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"Support\/STLExtras.h\"\n#include \"Support\/Statistic.h\"\n#include \n#include \nusing namespace llvm;\n\nstatic RegisterPass X(\"emitbytecode\", \"Bytecode Writer\");\n\nstatic Statistic<> \nBytesWritten(\"bytecodewriter\", \"Number of bytecode bytes written\");\n\nBytecodeWriter::BytecodeWriter(std::deque &o, const Module *M) \n : Out(o), Table(M, true) {\n\n \/\/ Emit the signature...\n static const unsigned char *Sig = (const unsigned char*)\"llvm\";\n output_data(Sig, Sig+4, Out);\n\n \/\/ Emit the top level CLASS block.\n BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);\n\n bool isBigEndian = M->getEndianness() == Module::BigEndian;\n bool hasLongPointers = M->getPointerSize() == Module::Pointer64;\n bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;\n bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;\n\n \/\/ Output the version identifier... we are currently on bytecode version #2,\n \/\/ which corresponds to LLVM v1.3.\n unsigned Version = (2 << 4) | isBigEndian | (hasLongPointers << 1) |\n (hasNoEndianness << 2) | (hasNoPointerSize << 3);\n output_vbr(Version, Out);\n align32(Out);\n\n {\n BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);\n \n \/\/ Write the type plane for types first because earlier planes (e.g. for a\n \/\/ primitive type like float) may have constants constructed using types\n \/\/ coming later (e.g., via getelementptr from a pointer type). The type\n \/\/ plane is needed before types can be fwd or bkwd referenced.\n const std::vector &Plane = Table.getPlane(Type::TypeTyID);\n assert(!Plane.empty() && \"No types at all?\");\n unsigned ValNo = Type::FirstDerivedTyID; \/\/ Start at the derived types...\n outputConstantsInPlane(Plane, ValNo); \/\/ Write out the types\n }\n\n \/\/ The ModuleInfoBlock follows directly after the type information\n outputModuleInfoBlock(M);\n\n \/\/ Output module level constants, used for global variable initializers\n outputConstants(false);\n\n \/\/ Do the whole module now! Process each function at a time...\n for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)\n outputFunction(I);\n\n \/\/ If needed, output the symbol table for the module...\n outputSymbolTable(M->getSymbolTable());\n}\n\n\/\/ Helper function for outputConstants().\n\/\/ Writes out all the constants in the plane Plane starting at entry StartNo.\n\/\/ \nvoid BytecodeWriter::outputConstantsInPlane(const std::vector\n &Plane, unsigned StartNo) {\n unsigned ValNo = StartNo;\n \n \/\/ Scan through and ignore function arguments, global values, and constant\n \/\/ strings.\n for (; ValNo < Plane.size() &&\n (isa(Plane[ValNo]) || isa(Plane[ValNo]) ||\n (isa(Plane[ValNo]) &&\n cast(Plane[ValNo])->isString())); ValNo++)\n \/*empty*\/;\n\n unsigned NC = ValNo; \/\/ Number of constants\n for (; NC < Plane.size() && \n (isa(Plane[NC]) || isa(Plane[NC])); NC++)\n \/*empty*\/;\n NC -= ValNo; \/\/ Convert from index into count\n if (NC == 0) return; \/\/ Skip empty type planes...\n\n \/\/ FIXME: Most slabs only have 1 or 2 entries! We should encode this much\n \/\/ more compactly.\n\n \/\/ Output type header: [num entries][type id number]\n \/\/\n output_vbr(NC, Out);\n\n \/\/ Output the Type ID Number...\n int Slot = Table.getSlot(Plane.front()->getType());\n assert (Slot != -1 && \"Type in constant pool but not in function!!\");\n output_vbr((unsigned)Slot, Out);\n\n \/\/cerr << \"Emitting \" << NC << \" constants of type '\" \n \/\/\t << Plane.front()->getType()->getName() << \"' = Slot #\" << Slot << \"\\n\";\n\n for (unsigned i = ValNo; i < ValNo+NC; ++i) {\n const Value *V = Plane[i];\n if (const Constant *CPV = dyn_cast(V)) {\n \/\/cerr << \"Serializing value: <\" << V->getType() << \">: \" << V << \":\" \n \/\/ << Out.size() << \"\\n\";\n outputConstant(CPV);\n } else {\n outputType(cast(V));\n }\n }\n}\n\nstatic inline bool hasNullValue(unsigned TyID) {\n return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&\n TyID != Type::VoidTyID;\n}\n\nvoid BytecodeWriter::outputConstants(bool isFunction) {\n BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out,\n true \/* Elide block if empty *\/);\n\n unsigned NumPlanes = Table.getNumPlanes();\n\n \/\/ Output the type plane before any constants!\n if (isFunction && NumPlanes > Type::TypeTyID) {\n const std::vector &Plane = Table.getPlane(Type::TypeTyID);\n if (!Plane.empty()) { \/\/ Skip empty type planes...\n unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);\n outputConstantsInPlane(Plane, ValNo);\n }\n }\n \n \/\/ Output module-level string constants before any other constants.x\n if (!isFunction)\n outputConstantStrings();\n\n for (unsigned pno = 0; pno != NumPlanes; pno++)\n if (pno != Type::TypeTyID) { \/\/ Type plane handled above.\n const std::vector &Plane = Table.getPlane(pno);\n if (!Plane.empty()) { \/\/ Skip empty type planes...\n unsigned ValNo = 0;\n if (isFunction) \/\/ Don't re-emit module constants\n ValNo += Table.getModuleLevel(pno);\n \n if (hasNullValue(pno)) {\n \/\/ Skip zero initializer\n if (ValNo == 0)\n ValNo = 1;\n }\n \n \/\/ Write out constants in the plane\n outputConstantsInPlane(Plane, ValNo);\n }\n }\n}\n\nstatic unsigned getEncodedLinkage(const GlobalValue *GV) {\n switch (GV->getLinkage()) {\n default: assert(0 && \"Invalid linkage!\");\n case GlobalValue::ExternalLinkage: return 0;\n case GlobalValue::WeakLinkage: return 1;\n case GlobalValue::AppendingLinkage: return 2;\n case GlobalValue::InternalLinkage: return 3;\n case GlobalValue::LinkOnceLinkage: return 4;\n }\n}\n\nvoid BytecodeWriter::outputModuleInfoBlock(const Module *M) {\n BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);\n \n \/\/ Output the types for the global variables in the module...\n for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {\n int Slot = Table.getSlot(I->getType());\n assert(Slot != -1 && \"Module global vars is broken!\");\n\n \/\/ Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,\n \/\/ bit5+ = Slot # for type\n unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |\n (I->hasInitializer() << 1) | I->isConstant();\n output_vbr(oSlot, Out);\n\n \/\/ If we have an initializer, output it now.\n if (I->hasInitializer()) {\n Slot = Table.getSlot((Value*)I->getInitializer());\n assert(Slot != -1 && \"No slot for global var initializer!\");\n output_vbr((unsigned)Slot, Out);\n }\n }\n output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);\n\n \/\/ Output the types of the functions in this module...\n for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {\n int Slot = Table.getSlot(I->getType());\n assert(Slot != -1 && \"Module const pool is broken!\");\n assert(Slot >= Type::FirstDerivedTyID && \"Derived type not in range!\");\n output_vbr((unsigned)Slot, Out);\n }\n output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);\n}\n\nvoid BytecodeWriter::outputInstructions(const Function *F) {\n BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);\n for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)\n outputInstruction(*I);\n}\n\nvoid BytecodeWriter::outputFunction(const Function *F) {\n BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);\n output_vbr(getEncodedLinkage(F), Out);\n\n \/\/ If this is an external function, there is nothing else to emit!\n if (F->isExternal()) return;\n\n \/\/ Get slot information about the function...\n Table.incorporateFunction(F);\n\n if (Table.getCompactionTable().empty()) {\n \/\/ Output information about the constants in the function if the compaction\n \/\/ table is not being used.\n outputConstants(true);\n } else {\n \/\/ Otherwise, emit the compaction table.\n outputCompactionTable();\n }\n \n \/\/ Output all of the instructions in the body of the function\n outputInstructions(F);\n \n \/\/ If needed, output the symbol table for the function...\n outputSymbolTable(F->getSymbolTable());\n \n Table.purgeFunction();\n}\n\nvoid BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,\n const std::vector &Plane,\n unsigned StartNo) {\n unsigned End = Table.getModuleLevel(PlaneNo);\n if (Plane.empty() || StartNo == End || End == 0) return; \/\/ Nothing to emit\n assert(StartNo < End && \"Cannot emit negative range!\");\n assert(StartNo < Plane.size() && End <= Plane.size());\n\n \/\/ Do not emit the null initializer!\n if (PlaneNo != Type::TypeTyID) ++StartNo;\n\n \/\/ Figure out which encoding to use. By far the most common case we have is\n \/\/ to emit 0-2 entries in a compaction table plane.\n switch (End-StartNo) {\n case 0: \/\/ Avoid emitting two vbr's if possible.\n case 1:\n case 2:\n output_vbr((PlaneNo << 2) | End-StartNo, Out);\n break;\n default:\n \/\/ Output the number of things.\n output_vbr((unsigned(End-StartNo) << 2) | 3, Out);\n output_vbr(PlaneNo, Out); \/\/ Emit the type plane this is\n break;\n }\n\n for (unsigned i = StartNo; i != End; ++i)\n output_vbr(Table.getGlobalSlot(Plane[i]), Out);\n}\n\nvoid BytecodeWriter::outputCompactionTable() {\n BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true\/*ElideIfEmpty*\/);\n const std::vector > &CT =Table.getCompactionTable();\n \n \/\/ First thing is first, emit the type compaction table if there is one.\n if (CT.size() > Type::TypeTyID)\n outputCompactionTablePlane(Type::TypeTyID, CT[Type::TypeTyID],\n Type::FirstDerivedTyID);\n\n for (unsigned i = 0, e = CT.size(); i != e; ++i)\n if (i != Type::TypeTyID)\n outputCompactionTablePlane(i, CT[i], 0);\n}\n\nvoid BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {\n \/\/ Do not output the Bytecode block for an empty symbol table, it just wastes\n \/\/ space!\n if (MST.begin() == MST.end()) return;\n\n BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out,\n true\/* ElideIfEmpty*\/);\n\n for (SymbolTable::const_iterator TI = MST.begin(); TI != MST.end(); ++TI) {\n SymbolTable::type_const_iterator I = MST.type_begin(TI->first);\n SymbolTable::type_const_iterator End = MST.type_end(TI->first);\n int Slot;\n \n if (I == End) continue; \/\/ Don't mess with an absent type...\n\n \/\/ Symtab block header: [num entries][type id number]\n output_vbr(MST.type_size(TI->first), Out);\n\n Slot = Table.getSlot(TI->first);\n assert(Slot != -1 && \"Type in symtab, but not in table!\");\n output_vbr((unsigned)Slot, Out);\n\n for (; I != End; ++I) {\n \/\/ Symtab entry: [def slot #][name]\n const Value *V = I->second;\n\n Slot = Table.getSlot(I->second);\n assert(Slot != -1 && \"Value in symtab but has no slot number!!\");\n output_vbr((unsigned)Slot, Out);\n output(I->first, Out, false); \/\/ Don't force alignment...\n }\n }\n}\n\nvoid llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {\n assert(C && \"You can't write a null module!!\");\n\n std::deque Buffer;\n\n \/\/ This object populates buffer for us...\n BytecodeWriter BCW(Buffer, C);\n\n \/\/ Keep track of how much we've written...\n BytesWritten += Buffer.size();\n\n \/\/ Okay, write the deque out to the ostream now... the deque is not\n \/\/ sequential in memory, however, so write out as much as possible in big\n \/\/ chunks, until we're done.\n \/\/\n std::deque::const_iterator I = Buffer.begin(),E = Buffer.end();\n while (I != E) { \/\/ Loop until it's all written\n \/\/ Scan to see how big this chunk is...\n const unsigned char *ChunkPtr = &*I;\n const unsigned char *LastPtr = ChunkPtr;\n while (I != E) {\n const unsigned char *ThisPtr = &*++I;\n if (LastPtr+1 != ThisPtr) { \/\/ Advanced by more than a byte of memory?\n ++LastPtr;\n break;\n }\n LastPtr = ThisPtr;\n }\n \n \/\/ Write out the chunk...\n Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);\n }\n\n Out.flush();\n}\nChanged to use SymbolTable's new iteration interfaces.\/\/===-- Writer.cpp - Library for writing LLVM bytecode files --------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This library implements the functionality defined in llvm\/Bytecode\/Writer.h\n\/\/\n\/\/ Note that this file uses an unusual technique of outputting all the bytecode\n\/\/ to a deque of unsigned char, then copies the deque to an ostream. The\n\/\/ reason for this is that we must do \"seeking\" in the stream to do back-\n\/\/ patching, and some very important ostreams that we want to support (like\n\/\/ pipes) do not support seeking. :( :( :(\n\/\/\n\/\/ The choice of the deque data structure is influenced by the extremely fast\n\/\/ \"append\" speed, plus the free \"seek\"\/replace in the middle of the stream. I\n\/\/ didn't use a vector because the stream could end up very large and copying\n\/\/ the whole thing to reallocate would be kinda silly.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"WriterInternals.h\"\n#include \"llvm\/Bytecode\/WriteBytecodePass.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Module.h\"\n#include \"llvm\/SymbolTable.h\"\n#include \"Support\/STLExtras.h\"\n#include \"Support\/Statistic.h\"\n#include \n#include \nusing namespace llvm;\n\nstatic RegisterPass X(\"emitbytecode\", \"Bytecode Writer\");\n\nstatic Statistic<> \nBytesWritten(\"bytecodewriter\", \"Number of bytecode bytes written\");\n\nBytecodeWriter::BytecodeWriter(std::deque &o, const Module *M) \n : Out(o), Table(M, true) {\n\n \/\/ Emit the signature...\n static const unsigned char *Sig = (const unsigned char*)\"llvm\";\n output_data(Sig, Sig+4, Out);\n\n \/\/ Emit the top level CLASS block.\n BytecodeBlock ModuleBlock(BytecodeFormat::Module, Out);\n\n bool isBigEndian = M->getEndianness() == Module::BigEndian;\n bool hasLongPointers = M->getPointerSize() == Module::Pointer64;\n bool hasNoEndianness = M->getEndianness() == Module::AnyEndianness;\n bool hasNoPointerSize = M->getPointerSize() == Module::AnyPointerSize;\n\n \/\/ Output the version identifier... we are currently on bytecode version #2,\n \/\/ which corresponds to LLVM v1.3.\n unsigned Version = (2 << 4) | isBigEndian | (hasLongPointers << 1) |\n (hasNoEndianness << 2) | (hasNoPointerSize << 3);\n output_vbr(Version, Out);\n align32(Out);\n\n {\n BytecodeBlock CPool(BytecodeFormat::GlobalTypePlane, Out);\n \n \/\/ Write the type plane for types first because earlier planes (e.g. for a\n \/\/ primitive type like float) may have constants constructed using types\n \/\/ coming later (e.g., via getelementptr from a pointer type). The type\n \/\/ plane is needed before types can be fwd or bkwd referenced.\n const std::vector &Plane = Table.getPlane(Type::TypeTyID);\n assert(!Plane.empty() && \"No types at all?\");\n unsigned ValNo = Type::FirstDerivedTyID; \/\/ Start at the derived types...\n outputConstantsInPlane(Plane, ValNo); \/\/ Write out the types\n }\n\n \/\/ The ModuleInfoBlock follows directly after the type information\n outputModuleInfoBlock(M);\n\n \/\/ Output module level constants, used for global variable initializers\n outputConstants(false);\n\n \/\/ Do the whole module now! Process each function at a time...\n for (Module::const_iterator I = M->begin(), E = M->end(); I != E; ++I)\n outputFunction(I);\n\n \/\/ If needed, output the symbol table for the module...\n outputSymbolTable(M->getSymbolTable());\n}\n\n\/\/ Helper function for outputConstants().\n\/\/ Writes out all the constants in the plane Plane starting at entry StartNo.\n\/\/ \nvoid BytecodeWriter::outputConstantsInPlane(const std::vector\n &Plane, unsigned StartNo) {\n unsigned ValNo = StartNo;\n \n \/\/ Scan through and ignore function arguments, global values, and constant\n \/\/ strings.\n for (; ValNo < Plane.size() &&\n (isa(Plane[ValNo]) || isa(Plane[ValNo]) ||\n (isa(Plane[ValNo]) &&\n cast(Plane[ValNo])->isString())); ValNo++)\n \/*empty*\/;\n\n unsigned NC = ValNo; \/\/ Number of constants\n for (; NC < Plane.size() && \n (isa(Plane[NC]) || isa(Plane[NC])); NC++)\n \/*empty*\/;\n NC -= ValNo; \/\/ Convert from index into count\n if (NC == 0) return; \/\/ Skip empty type planes...\n\n \/\/ FIXME: Most slabs only have 1 or 2 entries! We should encode this much\n \/\/ more compactly.\n\n \/\/ Output type header: [num entries][type id number]\n \/\/\n output_vbr(NC, Out);\n\n \/\/ Output the Type ID Number...\n int Slot = Table.getSlot(Plane.front()->getType());\n assert (Slot != -1 && \"Type in constant pool but not in function!!\");\n output_vbr((unsigned)Slot, Out);\n\n \/\/cerr << \"Emitting \" << NC << \" constants of type '\" \n \/\/\t << Plane.front()->getType()->getName() << \"' = Slot #\" << Slot << \"\\n\";\n\n for (unsigned i = ValNo; i < ValNo+NC; ++i) {\n const Value *V = Plane[i];\n if (const Constant *CPV = dyn_cast(V)) {\n \/\/cerr << \"Serializing value: <\" << V->getType() << \">: \" << V << \":\" \n \/\/ << Out.size() << \"\\n\";\n outputConstant(CPV);\n } else {\n outputType(cast(V));\n }\n }\n}\n\nstatic inline bool hasNullValue(unsigned TyID) {\n return TyID != Type::LabelTyID && TyID != Type::TypeTyID &&\n TyID != Type::VoidTyID;\n}\n\nvoid BytecodeWriter::outputConstants(bool isFunction) {\n BytecodeBlock CPool(BytecodeFormat::ConstantPool, Out,\n true \/* Elide block if empty *\/);\n\n unsigned NumPlanes = Table.getNumPlanes();\n\n \/\/ Output the type plane before any constants!\n if (isFunction && NumPlanes > Type::TypeTyID) {\n const std::vector &Plane = Table.getPlane(Type::TypeTyID);\n if (!Plane.empty()) { \/\/ Skip empty type planes...\n unsigned ValNo = Table.getModuleLevel(Type::TypeTyID);\n outputConstantsInPlane(Plane, ValNo);\n }\n }\n \n \/\/ Output module-level string constants before any other constants.x\n if (!isFunction)\n outputConstantStrings();\n\n for (unsigned pno = 0; pno != NumPlanes; pno++)\n if (pno != Type::TypeTyID) { \/\/ Type plane handled above.\n const std::vector &Plane = Table.getPlane(pno);\n if (!Plane.empty()) { \/\/ Skip empty type planes...\n unsigned ValNo = 0;\n if (isFunction) \/\/ Don't re-emit module constants\n ValNo += Table.getModuleLevel(pno);\n \n if (hasNullValue(pno)) {\n \/\/ Skip zero initializer\n if (ValNo == 0)\n ValNo = 1;\n }\n \n \/\/ Write out constants in the plane\n outputConstantsInPlane(Plane, ValNo);\n }\n }\n}\n\nstatic unsigned getEncodedLinkage(const GlobalValue *GV) {\n switch (GV->getLinkage()) {\n default: assert(0 && \"Invalid linkage!\");\n case GlobalValue::ExternalLinkage: return 0;\n case GlobalValue::WeakLinkage: return 1;\n case GlobalValue::AppendingLinkage: return 2;\n case GlobalValue::InternalLinkage: return 3;\n case GlobalValue::LinkOnceLinkage: return 4;\n }\n}\n\nvoid BytecodeWriter::outputModuleInfoBlock(const Module *M) {\n BytecodeBlock ModuleInfoBlock(BytecodeFormat::ModuleGlobalInfo, Out);\n \n \/\/ Output the types for the global variables in the module...\n for (Module::const_giterator I = M->gbegin(), End = M->gend(); I != End;++I) {\n int Slot = Table.getSlot(I->getType());\n assert(Slot != -1 && \"Module global vars is broken!\");\n\n \/\/ Fields: bit0 = isConstant, bit1 = hasInitializer, bit2-4=Linkage,\n \/\/ bit5+ = Slot # for type\n unsigned oSlot = ((unsigned)Slot << 5) | (getEncodedLinkage(I) << 2) |\n (I->hasInitializer() << 1) | I->isConstant();\n output_vbr(oSlot, Out);\n\n \/\/ If we have an initializer, output it now.\n if (I->hasInitializer()) {\n Slot = Table.getSlot((Value*)I->getInitializer());\n assert(Slot != -1 && \"No slot for global var initializer!\");\n output_vbr((unsigned)Slot, Out);\n }\n }\n output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);\n\n \/\/ Output the types of the functions in this module...\n for (Module::const_iterator I = M->begin(), End = M->end(); I != End; ++I) {\n int Slot = Table.getSlot(I->getType());\n assert(Slot != -1 && \"Module const pool is broken!\");\n assert(Slot >= Type::FirstDerivedTyID && \"Derived type not in range!\");\n output_vbr((unsigned)Slot, Out);\n }\n output_vbr((unsigned)Table.getSlot(Type::VoidTy), Out);\n}\n\nvoid BytecodeWriter::outputInstructions(const Function *F) {\n BytecodeBlock ILBlock(BytecodeFormat::InstructionList, Out);\n for (Function::const_iterator BB = F->begin(), E = F->end(); BB != E; ++BB)\n for (BasicBlock::const_iterator I = BB->begin(), E = BB->end(); I!=E; ++I)\n outputInstruction(*I);\n}\n\nvoid BytecodeWriter::outputFunction(const Function *F) {\n BytecodeBlock FunctionBlock(BytecodeFormat::Function, Out);\n output_vbr(getEncodedLinkage(F), Out);\n\n \/\/ If this is an external function, there is nothing else to emit!\n if (F->isExternal()) return;\n\n \/\/ Get slot information about the function...\n Table.incorporateFunction(F);\n\n if (Table.getCompactionTable().empty()) {\n \/\/ Output information about the constants in the function if the compaction\n \/\/ table is not being used.\n outputConstants(true);\n } else {\n \/\/ Otherwise, emit the compaction table.\n outputCompactionTable();\n }\n \n \/\/ Output all of the instructions in the body of the function\n outputInstructions(F);\n \n \/\/ If needed, output the symbol table for the function...\n outputSymbolTable(F->getSymbolTable());\n \n Table.purgeFunction();\n}\n\nvoid BytecodeWriter::outputCompactionTablePlane(unsigned PlaneNo,\n const std::vector &Plane,\n unsigned StartNo) {\n unsigned End = Table.getModuleLevel(PlaneNo);\n if (Plane.empty() || StartNo == End || End == 0) return; \/\/ Nothing to emit\n assert(StartNo < End && \"Cannot emit negative range!\");\n assert(StartNo < Plane.size() && End <= Plane.size());\n\n \/\/ Do not emit the null initializer!\n if (PlaneNo != Type::TypeTyID) ++StartNo;\n\n \/\/ Figure out which encoding to use. By far the most common case we have is\n \/\/ to emit 0-2 entries in a compaction table plane.\n switch (End-StartNo) {\n case 0: \/\/ Avoid emitting two vbr's if possible.\n case 1:\n case 2:\n output_vbr((PlaneNo << 2) | End-StartNo, Out);\n break;\n default:\n \/\/ Output the number of things.\n output_vbr((unsigned(End-StartNo) << 2) | 3, Out);\n output_vbr(PlaneNo, Out); \/\/ Emit the type plane this is\n break;\n }\n\n for (unsigned i = StartNo; i != End; ++i)\n output_vbr(Table.getGlobalSlot(Plane[i]), Out);\n}\n\nvoid BytecodeWriter::outputCompactionTable() {\n BytecodeBlock CTB(BytecodeFormat::CompactionTable, Out, true\/*ElideIfEmpty*\/);\n const std::vector > &CT =Table.getCompactionTable();\n \n \/\/ First thing is first, emit the type compaction table if there is one.\n if (CT.size() > Type::TypeTyID)\n outputCompactionTablePlane(Type::TypeTyID, CT[Type::TypeTyID],\n Type::FirstDerivedTyID);\n\n for (unsigned i = 0, e = CT.size(); i != e; ++i)\n if (i != Type::TypeTyID)\n outputCompactionTablePlane(i, CT[i], 0);\n}\n\nvoid BytecodeWriter::outputSymbolTable(const SymbolTable &MST) {\n \/\/ Do not output the Bytecode block for an empty symbol table, it just wastes\n \/\/ space!\n if (MST.plane_begin() == MST.plane_end()) return;\n\n BytecodeBlock SymTabBlock(BytecodeFormat::SymbolTable, Out,\n true\/* ElideIfEmpty*\/);\n\n \/\/Symtab block header: [num entries][type id number]\n output_vbr(MST.num_types(), Out);\n output_vbr((unsigned)Table.getSlot(Type::TypeTy), Out);\n for (SymbolTable::type_const_iterator TI = MST.type_begin(),\n TE = MST.type_end(); TI != TE; ++TI ) {\n \/\/Symtab entry:[def slot #][name]\n output_vbr((unsigned)Table.getSlot(TI->second), Out);\n output(TI->first, Out, \/*align=*\/false); \n }\n\n \/\/ Now do each of the type planes in order.\n for (SymbolTable::plane_const_iterator PI = MST.plane_begin(), \n PE = MST.plane_end(); PI != PE; ++PI) {\n SymbolTable::value_const_iterator I = MST.value_begin(PI->first);\n SymbolTable::value_const_iterator End = MST.value_end(PI->first);\n int Slot;\n \n if (I == End) continue; \/\/ Don't mess with an absent type...\n\n \/\/ Symtab block header: [num entries][type id number]\n output_vbr(MST.type_size(PI->first), Out);\n\n Slot = Table.getSlot(PI->first);\n assert(Slot != -1 && \"Type in symtab, but not in table!\");\n output_vbr((unsigned)Slot, Out);\n\n for (; I != End; ++I) {\n \/\/ Symtab entry: [def slot #][name]\n const Value *V = I->second;\n\n Slot = Table.getSlot(I->second);\n assert(Slot != -1 && \"Value in symtab but has no slot number!!\");\n output_vbr((unsigned)Slot, Out);\n output(I->first, Out, false); \/\/ Don't force alignment...\n }\n }\n}\n\nvoid llvm::WriteBytecodeToFile(const Module *C, std::ostream &Out) {\n assert(C && \"You can't write a null module!!\");\n\n std::deque Buffer;\n\n \/\/ This object populates buffer for us...\n BytecodeWriter BCW(Buffer, C);\n\n \/\/ Keep track of how much we've written...\n BytesWritten += Buffer.size();\n\n \/\/ Okay, write the deque out to the ostream now... the deque is not\n \/\/ sequential in memory, however, so write out as much as possible in big\n \/\/ chunks, until we're done.\n \/\/\n std::deque::const_iterator I = Buffer.begin(),E = Buffer.end();\n while (I != E) { \/\/ Loop until it's all written\n \/\/ Scan to see how big this chunk is...\n const unsigned char *ChunkPtr = &*I;\n const unsigned char *LastPtr = ChunkPtr;\n while (I != E) {\n const unsigned char *ThisPtr = &*++I;\n if (LastPtr+1 != ThisPtr) { \/\/ Advanced by more than a byte of memory?\n ++LastPtr;\n break;\n }\n LastPtr = ThisPtr;\n }\n \n \/\/ Write out the chunk...\n Out.write((char*)ChunkPtr, LastPtr-ChunkPtr);\n }\n\n Out.flush();\n}\n<|endoftext|>"} {"text":"better error message<|endoftext|>"} {"text":"Don't trim whitespace while parsing xml<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ LieroX Game Script Compiler\r\n\/\/\r\n\/\/ Copyright Auxiliary Software 2002\r\n\/\/\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\/\/ OpenLieroX\r\n\/\/ code under LGPL\r\n\r\n\r\n\/\/ Main compiler\r\n\/\/ Created 7\/2\/02\r\n\/\/ Jason Boettcher\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"CVec.h\"\r\n#include \"CGameScript.h\"\r\n#include \"ConfigHandler.h\"\r\n#include \"SmartPointer.h\"\r\n#include \"CrashHandler.h\"\r\n\r\n\r\n\r\n\r\n\r\n\/\/ Prototypes\r\nint\t\tCheckArgs(int argc, char *argv[]);\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Main entry point\r\nint main(int argc, char *argv[])\r\n{\r\n\tnotes << \"Liero Xtreme Game Script Compiler\" << endl;\r\n\tnotes << \"(c) ..-2002 Auxiliary Software \" << endl;\r\n\tnotes << \" 2002-.. OpenLieroX team\" << endl;\r\n\tnotes << \"Version: \" << GetGameVersion().asString() << endl;\r\n\tnotes << \"GameScript Version: \" << GS_VERSION << endl << endl << endl;\r\n\r\n\r\n\tif( !CheckArgs(argc, argv) ) {\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tCGameScript\t*Game = new CGameScript;\r\n\tif(Game == NULL) {\r\n\t\terrors << \"GameCompiler: Out of memory while creating gamescript\" << endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t\/\/ Compile\r\n\tbool comp = Game->Compile(argv[1]);\r\n\r\n\t\/\/ Only save if the compile went ok\r\n\tif(comp) {\r\n\t\tprintf(\"\\nSaving...\\n\");\r\n\t\tGame->Save(argv[2]);\r\n\t}\r\n\r\n\tif(comp)\r\n\t\tprintf(\"\\nInfo:\\nWeapons: %d\\nProjectiles: %d\\n\",Game->GetNumWeapons(),Game->getProjectileCount());\r\n\r\n\tif(Game) {\r\n\t\tdelete Game;\r\n\t\tGame = NULL;\r\n\t}\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Check the arguments\r\nint CheckArgs(int argc, char *argv[])\r\n{\r\n\tchar *d = strrchr(argv[0],'\\\\');\r\n\tif(!d)\r\n\t\td = argv[0];\r\n\telse\r\n\t\td++;\r\n\r\n\tif(argc != 3) {\r\n\t\tprintf(\"Usage:\\n\");\r\n\t\tprintf(\"%s [Mod dir] [filename]\\n\",d);\r\n\t\tprintf(\"\\nExample:\\n\");\r\n\t\tprintf(\"%s Base script.lgs\\n\\n\",d);\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\/\/ some dummies\/stubs are following to be able to compile with OLX sources\r\n\r\nFILE* OpenGameFile(const std::string& file, const char* mod) {\r\n\t\/\/ stub\r\n\treturn fopen(file.c_str(), mod);\r\n}\r\n\r\nbool GetExactFileName(const std::string& fn, std::string& exactfn) {\r\n\t\/\/ sub\r\n\texactfn = fn;\r\n\treturn true;\r\n}\r\n\r\nstruct SoundSample;\r\ntemplate <> void SmartPointer_ObjectDeinit ( SoundSample * obj )\r\n{\r\n\terrors << \"SmartPointer_ObjectDeinit SoundSample: stub\" << endl;\r\n}\r\n\r\ntemplate <> void SmartPointer_ObjectDeinit ( SDL_Surface * obj )\r\n{\r\n\terrors << \"SmartPointer_ObjectDeinit SDL_Surface: stub\" << endl;\r\n}\r\n\r\nSmartPointer LoadSample(const std::string& _filename, int maxplaying) {\r\n\t\/\/ stub\r\n\treturn NULL;\r\n}\r\n\r\nSmartPointer LoadGameImage(const std::string& _filename, bool withalpha) {\r\n\t\/\/ stub\r\n\treturn NULL;\r\n}\r\n\r\nvoid SetColorKey(SDL_Surface * dst) {} \/\/ stub\r\n\r\nbool bDedicated = true;\r\n\r\nvoid SetError(const std::string& text) { errors << \"SetError: \" << text << endl; }\r\n\r\nstruct GameOptions;\r\nGameOptions *tLXOptions = NULL;\r\n\r\nbool Con_IsInited() { return false; }\r\n\r\nCrashHandler* CrashHandler::get() {\treturn NULL; }\r\n\r\nvoid Con_AddText(int colour, const std::string& text, bool alsoToLogger) {}\r\n\r\nSDL_PixelFormat defaultFallbackFormat =\r\n{\r\n NULL, \/\/SDL_Palette *palette;\r\n 32, \/\/Uint8 BitsPerPixel;\r\n 4, \/\/Uint8 BytesPerPixel;\r\n 0, 0, 0, 0, \/\/Uint8 Rloss, Gloss, Bloss, Aloss;\r\n 24, 16, 8, 0, \/\/Uint8 Rshift, Gshift, Bshift, Ashift;\r\n 0xff000000, 0xff0000, 0xff00, 0xff, \/\/Uint32 Rmask, Gmask, Bmask, Amask;\r\n 0, \/\/Uint32 colorkey;\r\n 255 \/\/Uint8 alpha;\r\n};\r\n\r\nSDL_PixelFormat* mainPixelFormat = &defaultFallbackFormat;\r\nbetter output\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/\r\n\/\/ LieroX Game Script Compiler\r\n\/\/\r\n\/\/ Copyright Auxiliary Software 2002\r\n\/\/\r\n\/\/\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\r\n\/\/ OpenLieroX\r\n\/\/ code under LGPL\r\n\r\n\r\n\/\/ Main compiler\r\n\/\/ Created 7\/2\/02\r\n\/\/ Jason Boettcher\r\n\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"CVec.h\"\r\n#include \"CGameScript.h\"\r\n#include \"ConfigHandler.h\"\r\n#include \"SmartPointer.h\"\r\n#include \"CrashHandler.h\"\r\n\r\n\r\n\r\n\r\n\r\n\/\/ Prototypes\r\nint\t\tCheckArgs(int argc, char *argv[]);\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Main entry point\r\nint main(int argc, char *argv[])\r\n{\r\n\tnotes << \"Liero Xtreme Game Script Compiler\" << endl;\r\n\tnotes << \"(c) ..-2002 Auxiliary Software \" << endl;\r\n\tnotes << \" 2002-.. OpenLieroX team\" << endl;\r\n\tnotes << \"Version: \" << GetGameVersion().asString() << endl;\r\n\tnotes << \"GameScript Version: \" << GS_VERSION << endl << endl << endl;\r\n\r\n\r\n\tif( !CheckArgs(argc, argv) ) {\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tCGameScript\t*Game = new CGameScript;\r\n\tif(Game == NULL) {\r\n\t\terrors << \"GameCompiler: Out of memory while creating gamescript\" << endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\t\/\/ Compile\r\n\tbool comp = Game->Compile(argv[1]);\r\n\r\n\t\/\/ Only save if the compile went ok\r\n\tif(comp) {\r\n\t\tnotes << endl << \"Saving...\" << endl;\r\n\t\tGame->Save(argv[2]);\r\n\t}\r\n\r\n\tif(comp)\r\n\t\tnotes << endl <<\r\n\t\t\t\t\"Info:\" << endl <<\r\n\t\t\t\t\"Weapons: \" << Game->GetNumWeapons() << endl <<\r\n\t\t\t\t\"Projectiles: \" << Game->getProjectileCount() << endl;\r\n\r\n\tif(Game) {\r\n\t\tdelete Game;\r\n\t\tGame = NULL;\r\n\t}\r\n\t\r\n\treturn 0;\r\n}\r\n\r\n\r\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\r\n\/\/ Check the arguments\r\nint CheckArgs(int argc, char *argv[])\r\n{\r\n\tchar *d = strrchr(argv[0],'\\\\');\r\n\tif(!d)\r\n\t\td = argv[0];\r\n\telse\r\n\t\td++;\r\n\r\n\tif(argc != 3) {\r\n\t\tnotes << \"Usage:\" << endl;\r\n\t\tnotes << d << \" [Mod dir] [filename]\" << endl;\r\n\t\tnotes << endl << \"Example:\" << endl;\r\n\t\tnotes << d << \" Base script.lgs\" << endl << endl;\r\n\t\treturn false;\r\n\t}\r\n\r\n\treturn true;\r\n}\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\/\/ some dummies\/stubs are following to be able to compile with OLX sources\r\n\r\nFILE* OpenGameFile(const std::string& file, const char* mod) {\r\n\t\/\/ stub\r\n\treturn fopen(file.c_str(), mod);\r\n}\r\n\r\nbool GetExactFileName(const std::string& fn, std::string& exactfn) {\r\n\t\/\/ sub\r\n\texactfn = fn;\r\n\treturn true;\r\n}\r\n\r\nstruct SoundSample;\r\ntemplate <> void SmartPointer_ObjectDeinit ( SoundSample * obj )\r\n{\r\n\terrors << \"SmartPointer_ObjectDeinit SoundSample: stub\" << endl;\r\n}\r\n\r\ntemplate <> void SmartPointer_ObjectDeinit ( SDL_Surface * obj )\r\n{\r\n\terrors << \"SmartPointer_ObjectDeinit SDL_Surface: stub\" << endl;\r\n}\r\n\r\nSmartPointer LoadSample(const std::string& _filename, int maxplaying) {\r\n\t\/\/ stub\r\n\treturn NULL;\r\n}\r\n\r\nSmartPointer LoadGameImage(const std::string& _filename, bool withalpha) {\r\n\t\/\/ stub\r\n\treturn NULL;\r\n}\r\n\r\nvoid SetColorKey(SDL_Surface * dst) {} \/\/ stub\r\n\r\nbool bDedicated = true;\r\n\r\nvoid SetError(const std::string& text) { errors << \"SetError: \" << text << endl; }\r\n\r\nstruct GameOptions;\r\nGameOptions *tLXOptions = NULL;\r\n\r\nbool Con_IsInited() { return false; }\r\n\r\nCrashHandler* CrashHandler::get() {\treturn NULL; }\r\n\r\nvoid Con_AddText(int colour, const std::string& text, bool alsoToLogger) {}\r\n\r\nSDL_PixelFormat defaultFallbackFormat =\r\n{\r\n NULL, \/\/SDL_Palette *palette;\r\n 32, \/\/Uint8 BitsPerPixel;\r\n 4, \/\/Uint8 BytesPerPixel;\r\n 0, 0, 0, 0, \/\/Uint8 Rloss, Gloss, Bloss, Aloss;\r\n 24, 16, 8, 0, \/\/Uint8 Rshift, Gshift, Bshift, Ashift;\r\n 0xff000000, 0xff0000, 0xff00, 0xff, \/\/Uint32 Rmask, Gmask, Bmask, Amask;\r\n 0, \/\/Uint32 colorkey;\r\n 255 \/\/Uint8 alpha;\r\n};\r\n\r\nSDL_PixelFormat* mainPixelFormat = &defaultFallbackFormat;\r\n<|endoftext|>"} {"text":"mention the -directory option if no fonts are found<|endoftext|>"} {"text":"\/\/===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass eliminates machine instruction PHI nodes by inserting copy\n\/\/ instructions. This destroys SSA information, but is the desired input for\n\/\/ some register allocators.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/LiveVariables.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \nusing namespace llvm;\n\nnamespace {\n struct PNE : public MachineFunctionPass {\n bool runOnMachineFunction(MachineFunction &Fn) {\n bool Changed = false;\n\n \/\/ Eliminate PHI instructions by inserting copies into predecessor blocks.\n for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)\n Changed |= EliminatePHINodes(Fn, *I);\n\n return Changed;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addPreserved();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n private:\n \/\/\/ EliminatePHINodes - Eliminate phi nodes by inserting copy instructions\n \/\/\/ in predecessor basic blocks.\n \/\/\/\n bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);\n void LowerAtomicPHINode(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator AfterPHIsIt,\n DenseMap &VUC,\n unsigned BBIsSuccOfPreds);\n };\n\n RegisterPass X(\"phi-node-elimination\",\n \"Eliminate PHI nodes for register allocation\");\n}\n\n\nconst PassInfo *llvm::PHIEliminationID = X.getPassInfo();\n\n\/\/\/ EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in\n\/\/\/ predecessor basic blocks.\n\/\/\/\nbool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {\n if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)\n return false; \/\/ Quick exit for basic blocks without PHIs.\n\n \/\/ VRegPHIUseCount - Keep track of the number of times each virtual register\n \/\/ is used by PHI nodes in successors of this block.\n DenseMap VRegPHIUseCount;\n VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());\n\n unsigned BBIsSuccOfPreds = 0; \/\/ Number of times MBB is a succ of preds\n for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),\n E = MBB.pred_end(); PI != E; ++PI)\n for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),\n E = (*PI)->succ_end(); SI != E; ++SI) {\n BBIsSuccOfPreds += *SI == &MBB;\n for (MachineBasicBlock::iterator BBI = (*SI)->begin(); BBI !=(*SI)->end() &&\n BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)\n for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)\n VRegPHIUseCount[BBI->getOperand(i).getReg()]++;\n }\n\n \/\/ Get an iterator to the first instruction after the last PHI node (this may\n \/\/ also be the end of the basic block).\n MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();\n while (AfterPHIsIt != MBB.end() &&\n AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)\n ++AfterPHIsIt; \/\/ Skip over all of the PHI nodes...\n\n while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {\n LowerAtomicPHINode(MBB, AfterPHIsIt, VRegPHIUseCount, BBIsSuccOfPreds);\n }\n return true;\n}\n\n\/\/\/ LowerAtomicPHINode - Lower the PHI node at the top of the specified block,\n\/\/\/ under the assuption that it needs to be lowered in a way that supports\n\/\/\/ atomic execution of PHIs. This lowering method is always correct all of the\n\/\/\/ time.\nvoid PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator AfterPHIsIt,\n DenseMap &VRegPHIUseCount,\n unsigned BBIsSuccOfPreds) {\n \/\/ Unlink the PHI node from the basic block, but don't delete the PHI yet.\n MachineInstr *MPhi = MBB.remove(MBB.begin());\n\n unsigned DestReg = MPhi->getOperand(0).getReg();\n\n \/\/ Create a new register for the incoming PHI arguments\/\n MachineFunction &MF = *MBB.getParent();\n const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);\n unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);\n\n \/\/ Insert a register to register copy in the top of the current block (but\n \/\/ after any remaining phi nodes) which copies the new incoming register\n \/\/ into the phi node destination.\n \/\/\n const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();\n RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);\n\n \/\/ Update live variable information if there is any...\n LiveVariables *LV = getAnalysisToUpdate();\n if (LV) {\n MachineInstr *PHICopy = prior(AfterPHIsIt);\n\n \/\/ Add information to LiveVariables to know that the incoming value is\n \/\/ killed. Note that because the value is defined in several places (once\n \/\/ each for each incoming block), the \"def\" block and instruction fields\n \/\/ for the VarInfo is not filled in.\n \/\/\n LV->addVirtualRegisterKilled(IncomingReg, PHICopy);\n\n \/\/ Since we are going to be deleting the PHI node, if it is the last use\n \/\/ of any registers, or if the value itself is dead, we need to move this\n \/\/ information over to the new copy we just inserted.\n \/\/\n LV->removeVirtualRegistersKilled(MPhi);\n\n std::pair\n RKs = LV->dead_range(MPhi);\n if (RKs.first != RKs.second) {\n for (LiveVariables::killed_iterator I = RKs.first; I != RKs.second; ++I)\n LV->addVirtualRegisterDead(*I, PHICopy);\n LV->removeVirtualRegistersDead(MPhi);\n }\n }\n\n \/\/ Adjust the VRegPHIUseCount map to account for the removal of this PHI\n \/\/ node.\n for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)\n VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= BBIsSuccOfPreds;\n\n \/\/ Now loop over all of the incoming arguments, changing them to copy into\n \/\/ the IncomingReg register in the corresponding predecessor basic block.\n \/\/\n for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {\n MachineOperand &opVal = MPhi->getOperand(i-1);\n\n \/\/ Get the MachineBasicBlock equivalent of the BasicBlock that is the\n \/\/ source path the PHI.\n MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();\n\n MachineBasicBlock::iterator I = opBlock.getFirstTerminator();\n\n \/\/ Check to make sure we haven't already emitted the copy for this block.\n \/\/ This can happen because PHI nodes may have multiple entries for the\n \/\/ same basic block. It doesn't matter which entry we use though, because\n \/\/ all incoming values are guaranteed to be the same for a particular bb.\n \/\/\n \/\/ If we emitted a copy for this basic block already, it will be right\n \/\/ where we want to insert one now. Just check for a definition of the\n \/\/ register we are interested in!\n \/\/\n bool HaveNotEmitted = true;\n\n if (I != opBlock.begin()) {\n MachineBasicBlock::iterator PrevInst = prior(I);\n for (unsigned i = 0, e = PrevInst->getNumOperands(); i != e; ++i) {\n MachineOperand &MO = PrevInst->getOperand(i);\n if (MO.isRegister() && MO.getReg() == IncomingReg)\n if (MO.isDef()) {\n HaveNotEmitted = false;\n break;\n }\n }\n }\n\n if (HaveNotEmitted) { \/\/ If the copy has not already been emitted, do it.\n assert(MRegisterInfo::isVirtualRegister(opVal.getReg()) &&\n \"Machine PHI Operands must all be virtual registers!\");\n unsigned SrcReg = opVal.getReg();\n RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);\n\n \/\/ Now update live variable information if we have it.\n if (LV) {\n \/\/ We want to be able to insert a kill of the register if this PHI\n \/\/ (aka, the copy we just inserted) is the last use of the source\n \/\/ value. Live variable analysis conservatively handles this by\n \/\/ saying that the value is live until the end of the block the PHI\n \/\/ entry lives in. If the value really is dead at the PHI copy, there\n \/\/ will be no successor blocks which have the value live-in.\n \/\/\n \/\/ Check to see if the copy is the last use, and if so, update the\n \/\/ live variables information so that it knows the copy source\n \/\/ instruction kills the incoming value.\n \/\/\n LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);\n\n \/\/ Loop over all of the successors of the basic block, checking to see\n \/\/ if the value is either live in the block, or if it is killed in the\n \/\/ block. Also check to see if this register is in use by another PHI\n \/\/ node which has not yet been eliminated. If so, it will be killed\n \/\/ at an appropriate point later.\n \/\/\n bool ValueIsLive = false;\n for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),\n E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {\n MachineBasicBlock *SuccMBB = *SI;\n\n \/\/ Is it alive in this successor?\n unsigned SuccIdx = SuccMBB->getNumber();\n if (SuccIdx < InRegVI.AliveBlocks.size() &&\n InRegVI.AliveBlocks[SuccIdx]) {\n ValueIsLive = true;\n break;\n }\n\n \/\/ Is it killed in this successor?\n for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)\n if (InRegVI.Kills[i]->getParent() == SuccMBB) {\n ValueIsLive = true;\n break;\n }\n\n \/\/ Is it used by any PHI instructions in this block?\n if (!ValueIsLive)\n ValueIsLive = VRegPHIUseCount[SrcReg] != 0;\n }\n\n \/\/ Okay, if we now know that the value is not live out of the block,\n \/\/ we can add a kill marker to the copy we inserted saying that it\n \/\/ kills the incoming value!\n \/\/\n if (!ValueIsLive) {\n MachineBasicBlock::iterator Prev = prior(I);\n LV->addVirtualRegisterKilled(SrcReg, Prev);\n\n \/\/ This vreg no longer lives all of the way through opBlock.\n unsigned opBlockNum = opBlock.getNumber();\n if (opBlockNum < InRegVI.AliveBlocks.size())\n InRegVI.AliveBlocks[opBlockNum] = false;\n }\n }\n }\n }\n \n \/\/ Really delete the PHI instruction now!\n delete MPhi;\n}\nclean up this code a bit, no functionality change\/\/===-- PhiElimination.cpp - Eliminate PHI nodes by inserting copies ------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This pass eliminates machine instruction PHI nodes by inserting copy\n\/\/ instructions. This destroys SSA information, but is the desired input for\n\/\/ some register allocators.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/CodeGen\/LiveVariables.h\"\n#include \"llvm\/CodeGen\/Passes.h\"\n#include \"llvm\/CodeGen\/MachineFunctionPass.h\"\n#include \"llvm\/CodeGen\/MachineInstr.h\"\n#include \"llvm\/CodeGen\/SSARegMap.h\"\n#include \"llvm\/Target\/TargetInstrInfo.h\"\n#include \"llvm\/Target\/TargetMachine.h\"\n#include \"llvm\/ADT\/DenseMap.h\"\n#include \"llvm\/ADT\/STLExtras.h\"\n#include \"llvm\/ADT\/Statistic.h\"\n#include \n#include \nusing namespace llvm;\n\nnamespace {\n Statistic<> NumAtomic(\"phielim\", \"Number of atomic phis lowered\");\n Statistic<> NumSimple(\"phielim\", \"Number of simple phis lowered\");\n \n struct PNE : public MachineFunctionPass {\n bool runOnMachineFunction(MachineFunction &Fn) {\n bool Changed = false;\n\n \/\/ Eliminate PHI instructions by inserting copies into predecessor blocks.\n for (MachineFunction::iterator I = Fn.begin(), E = Fn.end(); I != E; ++I)\n Changed |= EliminatePHINodes(Fn, *I);\n\n return Changed;\n }\n\n virtual void getAnalysisUsage(AnalysisUsage &AU) const {\n AU.addPreserved();\n MachineFunctionPass::getAnalysisUsage(AU);\n }\n\n private:\n \/\/\/ EliminatePHINodes - Eliminate phi nodes by inserting copy instructions\n \/\/\/ in predecessor basic blocks.\n \/\/\/\n bool EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB);\n void LowerAtomicPHINode(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator AfterPHIsIt,\n DenseMap &VUC);\n };\n\n RegisterPass X(\"phi-node-elimination\",\n \"Eliminate PHI nodes for register allocation\");\n}\n\n\nconst PassInfo *llvm::PHIEliminationID = X.getPassInfo();\n\n\/\/\/ EliminatePHINodes - Eliminate phi nodes by inserting copy instructions in\n\/\/\/ predecessor basic blocks.\n\/\/\/\nbool PNE::EliminatePHINodes(MachineFunction &MF, MachineBasicBlock &MBB) {\n if (MBB.empty() || MBB.front().getOpcode() != TargetInstrInfo::PHI)\n return false; \/\/ Quick exit for basic blocks without PHIs.\n\n \/\/ VRegPHIUseCount - Keep track of the number of times each virtual register\n \/\/ is used by PHI nodes in successors of this block.\n DenseMap VRegPHIUseCount;\n VRegPHIUseCount.grow(MF.getSSARegMap()->getLastVirtReg());\n\n for (MachineBasicBlock::pred_iterator PI = MBB.pred_begin(),\n E = MBB.pred_end(); PI != E; ++PI)\n for (MachineBasicBlock::succ_iterator SI = (*PI)->succ_begin(),\n E = (*PI)->succ_end(); SI != E; ++SI)\n for (MachineBasicBlock::iterator BBI = (*SI)->begin(), E = (*SI)->end();\n BBI != E && BBI->getOpcode() == TargetInstrInfo::PHI; ++BBI)\n for (unsigned i = 1, e = BBI->getNumOperands(); i != e; i += 2)\n VRegPHIUseCount[BBI->getOperand(i).getReg()]++;\n \n \/\/ Get an iterator to the first instruction after the last PHI node (this may\n \/\/ also be the end of the basic block).\n MachineBasicBlock::iterator AfterPHIsIt = MBB.begin();\n while (AfterPHIsIt != MBB.end() &&\n AfterPHIsIt->getOpcode() == TargetInstrInfo::PHI)\n ++AfterPHIsIt; \/\/ Skip over all of the PHI nodes...\n\n while (MBB.front().getOpcode() == TargetInstrInfo::PHI) {\n LowerAtomicPHINode(MBB, AfterPHIsIt, VRegPHIUseCount);\n }\n return true;\n}\n\n\/\/\/ LowerAtomicPHINode - Lower the PHI node at the top of the specified block,\n\/\/\/ under the assuption that it needs to be lowered in a way that supports\n\/\/\/ atomic execution of PHIs. This lowering method is always correct all of the\n\/\/\/ time.\nvoid PNE::LowerAtomicPHINode(MachineBasicBlock &MBB,\n MachineBasicBlock::iterator AfterPHIsIt,\n DenseMap &VRegPHIUseCount) {\n \/\/ Unlink the PHI node from the basic block, but don't delete the PHI yet.\n MachineInstr *MPhi = MBB.remove(MBB.begin());\n\n unsigned DestReg = MPhi->getOperand(0).getReg();\n\n \/\/ Create a new register for the incoming PHI arguments\/\n MachineFunction &MF = *MBB.getParent();\n const TargetRegisterClass *RC = MF.getSSARegMap()->getRegClass(DestReg);\n unsigned IncomingReg = MF.getSSARegMap()->createVirtualRegister(RC);\n\n \/\/ Insert a register to register copy in the top of the current block (but\n \/\/ after any remaining phi nodes) which copies the new incoming register\n \/\/ into the phi node destination.\n \/\/\n const MRegisterInfo *RegInfo = MF.getTarget().getRegisterInfo();\n RegInfo->copyRegToReg(MBB, AfterPHIsIt, DestReg, IncomingReg, RC);\n\n \/\/ Update live variable information if there is any...\n LiveVariables *LV = getAnalysisToUpdate();\n if (LV) {\n MachineInstr *PHICopy = prior(AfterPHIsIt);\n\n \/\/ Add information to LiveVariables to know that the incoming value is\n \/\/ killed. Note that because the value is defined in several places (once\n \/\/ each for each incoming block), the \"def\" block and instruction fields\n \/\/ for the VarInfo is not filled in.\n \/\/\n LV->addVirtualRegisterKilled(IncomingReg, PHICopy);\n\n \/\/ Since we are going to be deleting the PHI node, if it is the last use\n \/\/ of any registers, or if the value itself is dead, we need to move this\n \/\/ information over to the new copy we just inserted.\n \/\/\n LV->removeVirtualRegistersKilled(MPhi);\n\n \/\/ If the result is dead, update LV.\n if (LV->RegisterDefIsDead(MPhi, DestReg)) {\n LV->addVirtualRegisterDead(DestReg, PHICopy);\n LV->removeVirtualRegistersDead(MPhi);\n }\n }\n\n \/\/ Adjust the VRegPHIUseCount map to account for the removal of this PHI\n \/\/ node.\n unsigned NumPreds = (MPhi->getNumOperands()-1)\/2;\n for (unsigned i = 1; i != MPhi->getNumOperands(); i += 2)\n VRegPHIUseCount[MPhi->getOperand(i).getReg()] -= NumPreds;\n\n \/\/ Now loop over all of the incoming arguments, changing them to copy into\n \/\/ the IncomingReg register in the corresponding predecessor basic block.\n \/\/\n std::set MBBsInsertedInto;\n for (int i = MPhi->getNumOperands() - 1; i >= 2; i-=2) {\n unsigned SrcReg = MPhi->getOperand(i-1).getReg();\n assert(MRegisterInfo::isVirtualRegister(SrcReg) &&\n \"Machine PHI Operands must all be virtual registers!\");\n\n \/\/ Get the MachineBasicBlock equivalent of the BasicBlock that is the\n \/\/ source path the PHI.\n MachineBasicBlock &opBlock = *MPhi->getOperand(i).getMachineBasicBlock();\n\n \/\/ Check to make sure we haven't already emitted the copy for this block.\n \/\/ This can happen because PHI nodes may have multiple entries for the\n \/\/ same basic block.\n if (!MBBsInsertedInto.insert(&opBlock).second)\n continue; \/\/ If the copy has already been emitted, we're done.\n \n \/\/ Get an iterator pointing to the first terminator in the block (or end()).\n \/\/ This is the point where we can insert a copy if we'd like to.\n MachineBasicBlock::iterator I = opBlock.getFirstTerminator();\n \n \/\/ Insert the copy.\n RegInfo->copyRegToReg(opBlock, I, IncomingReg, SrcReg, RC);\n\n \/\/ Now update live variable information if we have it. Otherwise we're done\n if (!LV) continue;\n \n \/\/ We want to be able to insert a kill of the register if this PHI\n \/\/ (aka, the copy we just inserted) is the last use of the source\n \/\/ value. Live variable analysis conservatively handles this by\n \/\/ saying that the value is live until the end of the block the PHI\n \/\/ entry lives in. If the value really is dead at the PHI copy, there\n \/\/ will be no successor blocks which have the value live-in.\n \/\/\n \/\/ Check to see if the copy is the last use, and if so, update the\n \/\/ live variables information so that it knows the copy source\n \/\/ instruction kills the incoming value.\n \/\/\n LiveVariables::VarInfo &InRegVI = LV->getVarInfo(SrcReg);\n\n \/\/ Loop over all of the successors of the basic block, checking to see\n \/\/ if the value is either live in the block, or if it is killed in the\n \/\/ block. Also check to see if this register is in use by another PHI\n \/\/ node which has not yet been eliminated. If so, it will be killed\n \/\/ at an appropriate point later.\n \/\/\n\n \/\/ Is it used by any PHI instructions in this block?\n bool ValueIsLive = VRegPHIUseCount[SrcReg] != 0;\n\n std::vector OpSuccBlocks;\n \n \/\/ Otherwise, scan successors, including the BB the PHI node lives in.\n for (MachineBasicBlock::succ_iterator SI = opBlock.succ_begin(),\n E = opBlock.succ_end(); SI != E && !ValueIsLive; ++SI) {\n MachineBasicBlock *SuccMBB = *SI;\n\n \/\/ Is it alive in this successor?\n unsigned SuccIdx = SuccMBB->getNumber();\n if (SuccIdx < InRegVI.AliveBlocks.size() &&\n InRegVI.AliveBlocks[SuccIdx]) {\n ValueIsLive = true;\n break;\n }\n\n OpSuccBlocks.push_back(SuccMBB);\n }\n\n \/\/ Check to see if this value is live because there is a use in a successor\n \/\/ that kills it.\n if (!ValueIsLive) {\n switch (OpSuccBlocks.size()) {\n case 1: {\n MachineBasicBlock *MBB = OpSuccBlocks[0];\n for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)\n if (InRegVI.Kills[i]->getParent() == MBB) {\n ValueIsLive = true;\n break;\n }\n break;\n }\n case 2: {\n MachineBasicBlock *MBB1 = OpSuccBlocks[0], *MBB2 = OpSuccBlocks[1];\n for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)\n if (InRegVI.Kills[i]->getParent() == MBB1 || \n InRegVI.Kills[i]->getParent() == MBB2) {\n ValueIsLive = true;\n break;\n }\n break; \n }\n default:\n std::sort(OpSuccBlocks.begin(), OpSuccBlocks.end());\n for (unsigned i = 0, e = InRegVI.Kills.size(); i != e; ++i)\n if (std::binary_search(OpSuccBlocks.begin(), OpSuccBlocks.end(),\n InRegVI.Kills[i]->getParent())) {\n ValueIsLive = true;\n break;\n }\n }\n } \n\n \/\/ Okay, if we now know that the value is not live out of the block,\n \/\/ we can add a kill marker to the copy we inserted saying that it\n \/\/ kills the incoming value!\n \/\/\n if (!ValueIsLive) {\n MachineBasicBlock::iterator Prev = prior(I);\n LV->addVirtualRegisterKilled(SrcReg, Prev);\n\n \/\/ This vreg no longer lives all of the way through opBlock.\n unsigned opBlockNum = opBlock.getNumber();\n if (opBlockNum < InRegVI.AliveBlocks.size())\n InRegVI.AliveBlocks[opBlockNum] = false;\n }\n }\n \n \/\/ Really delete the PHI instruction now!\n delete MPhi;\n ++NumAtomic;\n}\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"itkExceptionObject.h\"\n\n#include \"otbTerraSarCalibrationImageFilter.h\"\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"itkExtractImageFilter.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n\nint otbTerraSarCalibrationImageComplexFilterTest(int argc, char * argv[])\n{\n const char * inputFileName = argv[1];\n const char * outputFileName = argv[2];\n const bool useFastCalibration = atoi(argv[3]);\n const bool resultsInDbs = atoi(argv[4]);\n\n typedef std::complex ComplexType;\n typedef otb::Image ImageType;\n typedef otb::ImageFileReader ReaderType;\n typedef otb::ImageFileWriter WriterType;\n typedef otb::TerraSarCalibrationImageFilter FilterType;\n typedef itk::ExtractImageFilter ExtractorType;\n\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n FilterType::Pointer filter = FilterType::New();\n ExtractorType::Pointer extractor = ExtractorType::New();\n\n reader->SetFileName(inputFileName);\n writer->SetFileName(outputFileName);\n\n reader->UpdateOutputInformation();\n\n filter->SetInput(reader->GetOutput());\n filter->SetUseFastCalibration(useFastCalibration);\n filter->SetResultsInDecibels(resultsInDbs);\n\n if (argc == 9)\n {\n ImageType::RegionType region;\n ImageType::IndexType id;\n id[0] = atoi(argv[5]);\n id[1] = atoi(argv[6]);\n ImageType::SizeType size;\n size[0] = atoi(argv[7]);\n size[1] = atoi(argv[8]);\n region.SetIndex(id);\n region.SetSize(size);\n extractor->SetExtractionRegion(region);\n extractor->SetInput(filter->GetOutput());\n writer->SetInput(extractor->GetOutput());\n }\n else\n {\n writer->SetInput(filter->GetOutput());\n }\n\n writer->Update();\n\n return EXIT_SUCCESS;\n}\nCoorect test TorontoDb : write vectorimage\/*=========================================================================\n\n Program: ORFEO Toolbox\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\n Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.\n See OTBCopyright.txt for details.\n\n\n This software is distributed WITHOUT ANY WARRANTY; without even\n the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\n PURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n#include \"itkExceptionObject.h\"\n\n#include \"otbTerraSarCalibrationImageFilter.h\"\n#include \"otbImage.h\"\n#include \"otbVectorImage.h\"\n#include \"otbVectorImage.h\"\n#include \"itkExtractImageFilter.h\"\n#include \"otbImageFileReader.h\"\n#include \"otbImageFileWriter.h\"\n#include \"itkComplexToRealImageFilter.h\"\n#include \"itkComplexToImaginaryImageFilter.h\"\n#include \"otbImageList.h\"\n#include \"otbImageListToVectorImageFilter.h\"\n\n\nint otbTerraSarCalibrationImageComplexFilterTest(int argc, char * argv[])\n{\n const char * inputFileName = argv[1];\n const char * outputFileName = argv[2];\n const bool useFastCalibration = atoi(argv[3]);\n const bool resultsInDbs = atoi(argv[4]);\n\n typedef std::complex ComplexType;\n typedef otb::Image ImageCplxType;\n typedef otb::Image ImageScalarType; \n typedef otb::VectorImage OutputImageType;\n typedef otb::ImageList ImageListType;\n\n typedef otb::ImageFileReader ReaderType;\n typedef otb::ImageFileWriter WriterType;\n typedef otb::TerraSarCalibrationImageFilter FilterType;\n typedef itk::ExtractImageFilter ExtractorType;\n\n typedef itk::ComplexToRealImageFilter RealExtractorType;\n typedef itk::ComplexToImaginaryImageFilter ImaginaryExtractorType;\n typedef otb::ImageListToVectorImageFilter ListToVectorImageFilterType;\n\n ReaderType::Pointer reader = ReaderType::New();\n WriterType::Pointer writer = WriterType::New();\n FilterType::Pointer filter = FilterType::New();\n ExtractorType::Pointer extractor = ExtractorType::New();\n\n reader->SetFileName(inputFileName);\n writer->SetFileName(outputFileName);\n\n reader->UpdateOutputInformation();\n\n filter->SetInput(reader->GetOutput());\n filter->SetUseFastCalibration(useFastCalibration);\n filter->SetResultsInDecibels(resultsInDbs);\n\n \/\/ The rest of the code is here to translate the image complexe into\n \/\/ a VectorImage of int which each channel is the real and imagynary part\n RealExtractorType::Pointer realExt = RealExtractorType::New();\n ImaginaryExtractorType::Pointer imgExt = ImaginaryExtractorType::New();\n\n if (argc == 9)\n {\n ImageCplxType::RegionType region;\n ImageCplxType::IndexType id;\n id[0] = atoi(argv[5]);\n id[1] = atoi(argv[6]);\n ImageCplxType::SizeType size;\n size[0] = atoi(argv[7]);\n size[1] = atoi(argv[8]);\n region.SetIndex(id);\n region.SetSize(size);\n extractor->SetExtractionRegion(region);\n extractor->SetInput(filter->GetOutput());\n\n realExt->SetInput(extractor->GetOutput());\n imgExt->SetInput(extractor->GetOutput());\n }\n else\n {\n realExt->SetInput(filter->GetOutput());\n imgExt->SetInput(filter->GetOutput());\n }\n \n \n ImageListType::Pointer imList = ImageListType::New();\n imList->PushBack(realExt->GetOutput());\n imList->PushBack(imgExt->GetOutput());\n ListToVectorImageFilterType::Pointer listCaster = ListToVectorImageFilterType::New();\n listCaster->SetInput(imList);\n \n writer->SetInput(listCaster->GetOutput());\n writer->Update();\n\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/\/===--- REPLCodeCompletion.cpp - Code completion for REPL ----------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This module provides completions to the immediate mode environment.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/IDE\/REPLCodeCompletion.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/SourceManager.h\"\n#include \"swift\/Parse\/DelayedParsingCallbacks.h\"\n#include \"swift\/Parse\/Parser.h\"\n#include \"swift\/IDE\/CodeCompletion.h\"\n#include \"swift\/Subsystems.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \n\nusing namespace swift;\nusing namespace ide;\n\nstd::string toInsertableString(CodeCompletionResult *Result) {\n std::string Str;\n for (auto C : Result->getCompletionString()->getChunks()) {\n switch (C.getKind()) {\n case CodeCompletionString::Chunk::ChunkKind::Text:\n case CodeCompletionString::Chunk::ChunkKind::LeftParen:\n case CodeCompletionString::Chunk::ChunkKind::RightParen:\n case CodeCompletionString::Chunk::ChunkKind::LeftBracket:\n case CodeCompletionString::Chunk::ChunkKind::RightBracket:\n case CodeCompletionString::Chunk::ChunkKind::LeftAngle:\n case CodeCompletionString::Chunk::ChunkKind::RightAngle:\n case CodeCompletionString::Chunk::ChunkKind::Dot:\n case CodeCompletionString::Chunk::ChunkKind::Comma:\n case CodeCompletionString::Chunk::ChunkKind::ExclamationMark:\n case CodeCompletionString::Chunk::ChunkKind::QuestionMark:\n case CodeCompletionString::Chunk::ChunkKind::Ampersand:\n case CodeCompletionString::Chunk::ChunkKind::DynamicLookupMethodCallTail:\n Str += C.getText();\n break;\n\n case CodeCompletionString::Chunk::ChunkKind::CallParameterName:\n case CodeCompletionString::Chunk::ChunkKind::CallParameterColon:\n case CodeCompletionString::Chunk::ChunkKind::CallParameterType:\n case CodeCompletionString::Chunk::ChunkKind::OptionalBegin:\n case CodeCompletionString::Chunk::ChunkKind::CallParameterBegin:\n case CodeCompletionString::Chunk::ChunkKind::GenericParameterBegin:\n case CodeCompletionString::Chunk::ChunkKind::GenericParameterName:\n case CodeCompletionString::Chunk::ChunkKind::TypeAnnotation:\n return Str;\n }\n }\n return Str;\n}\n\nnamespace swift {\nclass REPLCodeCompletionConsumer : public CodeCompletionConsumer {\n REPLCompletions &Completions;\n\npublic:\n REPLCodeCompletionConsumer(REPLCompletions &Completions)\n : Completions(Completions) {}\n\n void handleResults(MutableArrayRef Results) override {\n CodeCompletionContext::sortCompletionResults(Results);\n for (auto Result : Results) {\n std::string InsertableString = toInsertableString(Result);\n if (StringRef(InsertableString).startswith(Completions.Prefix)) {\n llvm::SmallString<128> PrintedResult;\n {\n llvm::raw_svector_ostream OS(PrintedResult);\n Result->print(OS);\n }\n Completions.CompletionStrings.push_back(\n Completions.CompletionContext.copyString(PrintedResult));\n\n InsertableString = InsertableString.substr(Completions.Prefix.size());\n\n Completions.CookedResults.push_back(\n { Completions.CompletionContext.copyString(InsertableString),\n Result->getNumBytesToErase() });\n }\n }\n }\n};\n} \/\/ namespace swift\n\nREPLCompletions::REPLCompletions()\n : State(CompletionState::Invalid), CompletionContext(CompletionCache) {\n \/\/ Create a CodeCompletionConsumer.\n Consumer.reset(new REPLCodeCompletionConsumer(*this));\n\n \/\/ Cerate a factory for code completion callbacks that will feed the\n \/\/ Consumer.\n CompletionCallbacksFactory.reset(\n ide::makeCodeCompletionCallbacksFactory(CompletionContext,\n *Consumer.get()));\n}\n\nstatic void\ndoCodeCompletion(SourceFile &SF, StringRef EnteredCode, unsigned *BufferID,\n CodeCompletionCallbacksFactory *CompletionCallbacksFactory) {\n \/\/ Temporarily disable printing the diagnostics.\n ASTContext &Ctx = SF.getASTContext();\n auto DiagnosticConsumers = Ctx.Diags.takeConsumers();\n\n std::string AugmentedCode = EnteredCode.str();\n AugmentedCode += '\\0';\n *BufferID = Ctx.SourceMgr.addMemBufferCopy(AugmentedCode, \"\");\n\n const unsigned CodeCompletionOffset = AugmentedCode.size() - 1;\n\n Ctx.SourceMgr.setCodeCompletionPoint(*BufferID, CodeCompletionOffset);\n\n \/\/ Parse, typecheck and temporarily insert the incomplete code into the AST.\n const unsigned OriginalDeclCount = SF.Decls.size();\n\n unsigned CurElem = OriginalDeclCount;\n PersistentParserState PersistentState;\n std::unique_ptr DelayedCB(\n new CodeCompleteDelayedCallbacks(Ctx.SourceMgr.getCodeCompletionLoc()));\n bool Done;\n do {\n parseIntoSourceFile(SF, *BufferID, &Done, nullptr, &PersistentState,\n DelayedCB.get());\n performTypeChecking(SF, PersistentState.getTopLevelContext(), CurElem);\n CurElem = SF.Decls.size();\n } while (!Done);\n\n performDelayedParsing(&SF, PersistentState, CompletionCallbacksFactory);\n\n \/\/ Now we are done with code completion. Remove the declarations we\n \/\/ temporarily inserted.\n SF.Decls.resize(OriginalDeclCount);\n\n \/\/ Add the diagnostic consumers back.\n for (auto DC : DiagnosticConsumers)\n Ctx.Diags.addConsumer(*DC);\n\n Ctx.Diags.resetHadAnyError();\n}\n\nvoid REPLCompletions::populate(SourceFile &SF, StringRef EnteredCode) {\n Prefix = \"\";\n Root.reset();\n CurrentCompletionIdx = ~size_t(0);\n\n CompletionStrings.clear();\n CookedResults.clear();\n\n assert(SF.Kind == SourceFileKind::REPL && \"Can't append to a non-REPL file\");\n\n unsigned BufferID;\n doCodeCompletion(SF, EnteredCode, &BufferID,\n CompletionCallbacksFactory.get());\n\n ASTContext &Ctx = SF.getASTContext();\n std::vector Tokens = tokenize(Ctx.LangOpts, Ctx.SourceMgr, BufferID);\n\n if (!Tokens.empty() && Tokens.back().is(tok::code_complete))\n Tokens.pop_back();\n\n if (!Tokens.empty()) {\n Token &LastToken = Tokens.back();\n if (LastToken.is(tok::identifier) || LastToken.isKeyword()) {\n Prefix = LastToken.getText();\n\n unsigned Offset = Ctx.SourceMgr.getLocOffsetInBuffer(LastToken.getLoc(),\n BufferID);\n\n doCodeCompletion(SF, EnteredCode.substr(0, Offset),\n &BufferID, CompletionCallbacksFactory.get());\n }\n }\n\n if (CookedResults.empty())\n State = CompletionState::Empty;\n else if (CookedResults.size() == 1)\n State = CompletionState::Unique;\n else\n State = CompletionState::CompletedRoot;\n}\n\nStringRef REPLCompletions::getRoot() const {\n if (Root)\n return Root.getValue();\n\n if (CookedResults.empty()) {\n Root = std::string();\n return Root.getValue();\n }\n\n std::string RootStr = CookedResults[0].InsertableString;\n for (auto R : CookedResults) {\n if (R.NumBytesToErase != 0) {\n RootStr.resize(0);\n break;\n }\n auto MismatchPlace = std::mismatch(RootStr.begin(), RootStr.end(),\n R.InsertableString.begin());\n RootStr.resize(MismatchPlace.first - RootStr.begin());\n }\n Root = RootStr;\n return Root.getValue();\n}\n\nREPLCompletions::CookedResult REPLCompletions::getPreviousStem() const {\n if (CurrentCompletionIdx == ~size_t(0) || CookedResults.empty())\n return {};\n\n const auto &Result = CookedResults[CurrentCompletionIdx];\n return { Result.InsertableString.substr(getRoot().size()),\n Result.NumBytesToErase };\n}\n\nREPLCompletions::CookedResult REPLCompletions::getNextStem() {\n if (CookedResults.empty())\n return {};\n\n CurrentCompletionIdx++;\n if (CurrentCompletionIdx >= CookedResults.size())\n CurrentCompletionIdx = 0;\n\n const auto &Result = CookedResults[CurrentCompletionIdx];\n return { Result.InsertableString.substr(getRoot().size()),\n Result.NumBytesToErase };\n}\n\nvoid REPLCompletions::reset() { State = CompletionState::Invalid; }\n\nREPL code completion: handle PreferredCursorPosition chunk\/\/===--- REPLCodeCompletion.cpp - Code completion for REPL ----------------===\/\/\n\/\/\n\/\/ This source file is part of the Swift.org open source project\n\/\/\n\/\/ Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors\n\/\/ Licensed under Apache License v2.0 with Runtime Library Exception\n\/\/\n\/\/ See http:\/\/swift.org\/LICENSE.txt for license information\n\/\/ See http:\/\/swift.org\/CONTRIBUTORS.txt for the list of Swift project authors\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This module provides completions to the immediate mode environment.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"swift\/IDE\/REPLCodeCompletion.h\"\n#include \"swift\/AST\/ASTContext.h\"\n#include \"swift\/AST\/Module.h\"\n#include \"swift\/Basic\/LLVM.h\"\n#include \"swift\/Basic\/SourceManager.h\"\n#include \"swift\/Parse\/DelayedParsingCallbacks.h\"\n#include \"swift\/Parse\/Parser.h\"\n#include \"swift\/IDE\/CodeCompletion.h\"\n#include \"swift\/Subsystems.h\"\n#include \"llvm\/Support\/raw_ostream.h\"\n#include \"llvm\/Support\/MemoryBuffer.h\"\n#include \n\nusing namespace swift;\nusing namespace ide;\n\nstd::string toInsertableString(CodeCompletionResult *Result) {\n std::string Str;\n for (auto C : Result->getCompletionString()->getChunks()) {\n switch (C.getKind()) {\n case CodeCompletionString::Chunk::ChunkKind::Text:\n case CodeCompletionString::Chunk::ChunkKind::LeftParen:\n case CodeCompletionString::Chunk::ChunkKind::RightParen:\n case CodeCompletionString::Chunk::ChunkKind::LeftBracket:\n case CodeCompletionString::Chunk::ChunkKind::RightBracket:\n case CodeCompletionString::Chunk::ChunkKind::LeftAngle:\n case CodeCompletionString::Chunk::ChunkKind::RightAngle:\n case CodeCompletionString::Chunk::ChunkKind::Dot:\n case CodeCompletionString::Chunk::ChunkKind::Comma:\n case CodeCompletionString::Chunk::ChunkKind::ExclamationMark:\n case CodeCompletionString::Chunk::ChunkKind::QuestionMark:\n case CodeCompletionString::Chunk::ChunkKind::Ampersand:\n case CodeCompletionString::Chunk::ChunkKind::DynamicLookupMethodCallTail:\n Str += C.getText();\n break;\n\n case CodeCompletionString::Chunk::ChunkKind::CallParameterName:\n case CodeCompletionString::Chunk::ChunkKind::CallParameterColon:\n case CodeCompletionString::Chunk::ChunkKind::CallParameterType:\n case CodeCompletionString::Chunk::ChunkKind::OptionalBegin:\n case CodeCompletionString::Chunk::ChunkKind::CallParameterBegin:\n case CodeCompletionString::Chunk::ChunkKind::GenericParameterBegin:\n case CodeCompletionString::Chunk::ChunkKind::GenericParameterName:\n case CodeCompletionString::Chunk::ChunkKind::TypeAnnotation:\n case CodeCompletionString::Chunk::ChunkKind::PreferredCursorPosition:\n return Str;\n }\n }\n return Str;\n}\n\nnamespace swift {\nclass REPLCodeCompletionConsumer : public CodeCompletionConsumer {\n REPLCompletions &Completions;\n\npublic:\n REPLCodeCompletionConsumer(REPLCompletions &Completions)\n : Completions(Completions) {}\n\n void handleResults(MutableArrayRef Results) override {\n CodeCompletionContext::sortCompletionResults(Results);\n for (auto Result : Results) {\n std::string InsertableString = toInsertableString(Result);\n if (StringRef(InsertableString).startswith(Completions.Prefix)) {\n llvm::SmallString<128> PrintedResult;\n {\n llvm::raw_svector_ostream OS(PrintedResult);\n Result->print(OS);\n }\n Completions.CompletionStrings.push_back(\n Completions.CompletionContext.copyString(PrintedResult));\n\n InsertableString = InsertableString.substr(Completions.Prefix.size());\n\n Completions.CookedResults.push_back(\n { Completions.CompletionContext.copyString(InsertableString),\n Result->getNumBytesToErase() });\n }\n }\n }\n};\n} \/\/ namespace swift\n\nREPLCompletions::REPLCompletions()\n : State(CompletionState::Invalid), CompletionContext(CompletionCache) {\n \/\/ Create a CodeCompletionConsumer.\n Consumer.reset(new REPLCodeCompletionConsumer(*this));\n\n \/\/ Cerate a factory for code completion callbacks that will feed the\n \/\/ Consumer.\n CompletionCallbacksFactory.reset(\n ide::makeCodeCompletionCallbacksFactory(CompletionContext,\n *Consumer.get()));\n}\n\nstatic void\ndoCodeCompletion(SourceFile &SF, StringRef EnteredCode, unsigned *BufferID,\n CodeCompletionCallbacksFactory *CompletionCallbacksFactory) {\n \/\/ Temporarily disable printing the diagnostics.\n ASTContext &Ctx = SF.getASTContext();\n auto DiagnosticConsumers = Ctx.Diags.takeConsumers();\n\n std::string AugmentedCode = EnteredCode.str();\n AugmentedCode += '\\0';\n *BufferID = Ctx.SourceMgr.addMemBufferCopy(AugmentedCode, \"\");\n\n const unsigned CodeCompletionOffset = AugmentedCode.size() - 1;\n\n Ctx.SourceMgr.setCodeCompletionPoint(*BufferID, CodeCompletionOffset);\n\n \/\/ Parse, typecheck and temporarily insert the incomplete code into the AST.\n const unsigned OriginalDeclCount = SF.Decls.size();\n\n unsigned CurElem = OriginalDeclCount;\n PersistentParserState PersistentState;\n std::unique_ptr DelayedCB(\n new CodeCompleteDelayedCallbacks(Ctx.SourceMgr.getCodeCompletionLoc()));\n bool Done;\n do {\n parseIntoSourceFile(SF, *BufferID, &Done, nullptr, &PersistentState,\n DelayedCB.get());\n performTypeChecking(SF, PersistentState.getTopLevelContext(), CurElem);\n CurElem = SF.Decls.size();\n } while (!Done);\n\n performDelayedParsing(&SF, PersistentState, CompletionCallbacksFactory);\n\n \/\/ Now we are done with code completion. Remove the declarations we\n \/\/ temporarily inserted.\n SF.Decls.resize(OriginalDeclCount);\n\n \/\/ Add the diagnostic consumers back.\n for (auto DC : DiagnosticConsumers)\n Ctx.Diags.addConsumer(*DC);\n\n Ctx.Diags.resetHadAnyError();\n}\n\nvoid REPLCompletions::populate(SourceFile &SF, StringRef EnteredCode) {\n Prefix = \"\";\n Root.reset();\n CurrentCompletionIdx = ~size_t(0);\n\n CompletionStrings.clear();\n CookedResults.clear();\n\n assert(SF.Kind == SourceFileKind::REPL && \"Can't append to a non-REPL file\");\n\n unsigned BufferID;\n doCodeCompletion(SF, EnteredCode, &BufferID,\n CompletionCallbacksFactory.get());\n\n ASTContext &Ctx = SF.getASTContext();\n std::vector Tokens = tokenize(Ctx.LangOpts, Ctx.SourceMgr, BufferID);\n\n if (!Tokens.empty() && Tokens.back().is(tok::code_complete))\n Tokens.pop_back();\n\n if (!Tokens.empty()) {\n Token &LastToken = Tokens.back();\n if (LastToken.is(tok::identifier) || LastToken.isKeyword()) {\n Prefix = LastToken.getText();\n\n unsigned Offset = Ctx.SourceMgr.getLocOffsetInBuffer(LastToken.getLoc(),\n BufferID);\n\n doCodeCompletion(SF, EnteredCode.substr(0, Offset),\n &BufferID, CompletionCallbacksFactory.get());\n }\n }\n\n if (CookedResults.empty())\n State = CompletionState::Empty;\n else if (CookedResults.size() == 1)\n State = CompletionState::Unique;\n else\n State = CompletionState::CompletedRoot;\n}\n\nStringRef REPLCompletions::getRoot() const {\n if (Root)\n return Root.getValue();\n\n if (CookedResults.empty()) {\n Root = std::string();\n return Root.getValue();\n }\n\n std::string RootStr = CookedResults[0].InsertableString;\n for (auto R : CookedResults) {\n if (R.NumBytesToErase != 0) {\n RootStr.resize(0);\n break;\n }\n auto MismatchPlace = std::mismatch(RootStr.begin(), RootStr.end(),\n R.InsertableString.begin());\n RootStr.resize(MismatchPlace.first - RootStr.begin());\n }\n Root = RootStr;\n return Root.getValue();\n}\n\nREPLCompletions::CookedResult REPLCompletions::getPreviousStem() const {\n if (CurrentCompletionIdx == ~size_t(0) || CookedResults.empty())\n return {};\n\n const auto &Result = CookedResults[CurrentCompletionIdx];\n return { Result.InsertableString.substr(getRoot().size()),\n Result.NumBytesToErase };\n}\n\nREPLCompletions::CookedResult REPLCompletions::getNextStem() {\n if (CookedResults.empty())\n return {};\n\n CurrentCompletionIdx++;\n if (CurrentCompletionIdx >= CookedResults.size())\n CurrentCompletionIdx = 0;\n\n const auto &Result = CookedResults[CurrentCompletionIdx];\n return { Result.InsertableString.substr(getRoot().size()),\n Result.NumBytesToErase };\n}\n\nvoid REPLCompletions::reset() { State = CompletionState::Invalid; }\n\n<|endoftext|>"} {"text":"\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * File: example.cpp.main.1.cpp\n *\n * Purpose: Implementation file for the example.cpp.main.1 library.\n *\n * Created: 5th January 2011\n * Updated: 9th February 2021\n *\n * Status: Wizard-generated\n *\n * License: (Licensed under the Synesis Software Open License)\n *\n * Copyright (c) 2011-2021, Synesis Software Pty Ltd.\n * All rights reserved.\n *\n * www: http:\/\/www.synesis.com.au\/software\n *\n * \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * feature control\n *\/\n\n\/\/ This is defined for illustrative purposes. You are advised to *not*\n\/\/ define this in production code. See Quality Matters, #5: \"Exceptions: \n\/\/ The Worst Form of Error Handling, Apart From All The Others\" for details\n\/\/ (http:\/\/quality-matters-to.us\/).\n#define PANTHEIOS_EXTRAS_MAIN_USE_CATCHALL\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * includes\n *\/\n\n\/* Pantheios Extras header files *\/\n#include \n\n\/* Pantheios header files *\/\n#include \n\n\/* STLSoft header files *\/\n#include \n\n\/* Standard C header files *\/\n#include \n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * globals\n *\/\n\nPANTHEIOS_EXTERN_C PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING(\"example.cpp.main.1\");\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifndef USE_wmain\n\nint main0(int argc, char** argv)\n{\n \/* do the \"main\" business of main() here, without worrying about\n * initialising Pantheios libraries\n *\/\n\n \/* in this case, we simply throw a given type of exception, as\n * requested by the user\n *\/\n\n if (argc == 2)\n {\n if (0 == strcmp(argv[1], \"memory\"))\n {\n throw std::bad_alloc();\n }\n else\n if (0 == strcmp(argv[1], \"root\"))\n {\n throw std::runtime_error(\"oops!\");\n }\n else\n {\n throw 1.0;\n }\n }\n\n printf(\n \"USAGE: %s {memory|root|other}\\n\"\n , argv[0]\n );\n\n return EXIT_SUCCESS;\n}\n\nint main(int argc, char** argv)\n{\n return pantheios::extras::main::invoke(argc, argv, main0);\n}\n\n#else \/\/ ? USE_wmain\n\nint main0(int argc, wchar_t** argv)\n{\n \/* do the \"main\" business of main() here, without worrying about\n * initialising Pantheios libraries\n *\/\n\n \/* in this case, we simply throw a given type of exception, as\n * requested by the user\n *\/\n\n if (argc == 2)\n {\n if (0 == wcscmp(argv[1], L\"memory\"))\n {\n throw std::bad_alloc();\n }\n else\n if (0 == wcscmp(argv[1], L\"root\"))\n {\n throw std::runtime_error(\"oops!\");\n }\n else\n {\n throw 1.0;\n }\n }\n\n printf(\n \"USAGE: %s {memory|root|other}\\n\"\n , argv[0]\n );\n\n return EXIT_SUCCESS;\n}\n\nint wmain(int argc, wchar_t** argv)\n{\n return pantheios::extras::main::invoke(argc, argv, main0);\n}\n\n#endif \/\/ !USE_wmain\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end of file \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n~ wide-string implementation\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * File: example.cpp.main.1.cpp\n *\n * Purpose: Implementation file for the example.cpp.main.1 library.\n *\n * Created: 5th January 2011\n * Updated: 9th February 2021\n *\n * Status: Wizard-generated\n *\n * License: (Licensed under the Synesis Software Open License)\n *\n * Copyright (c) 2011-2021, Synesis Software Pty Ltd.\n * All rights reserved.\n *\n * www: http:\/\/www.synesis.com.au\/software\n *\n * \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * feature control\n *\/\n\n\/\/ This is defined for illustrative purposes. You are advised to *not*\n\/\/ define this in production code. See Quality Matters, #5: \"Exceptions: \n\/\/ The Worst Form of Error Handling, Apart From All The Others\" for details\n\/\/ (http:\/\/quality-matters-to.us\/).\n#define PANTHEIOS_EXTRAS_MAIN_USE_CATCHALL\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * includes\n *\/\n\n\/* Pantheios Extras header files *\/\n#include \n\n\/* Pantheios header files *\/\n#include \n\n\/* STLSoft header files *\/\n#include \n\n\/* Standard C header files *\/\n#include \n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n * globals\n *\/\n\nPANTHEIOS_EXTERN_C PAN_CHAR_T const PANTHEIOS_FE_PROCESS_IDENTITY[] = PANTHEIOS_LITERAL_STRING(\"example.cpp.main.1\");\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n#ifndef USE_wmain\n\nint main0(int argc, char** argv)\n{\n \/* do the \"main\" business of main() here, without worrying about\n * initialising Pantheios libraries\n *\/\n\n \/* in this case, we simply throw a given type of exception, as\n * requested by the user\n *\/\n\n if (argc == 2)\n {\n if (0 == strcmp(argv[1], \"memory\"))\n {\n throw std::bad_alloc();\n }\n else\n if (0 == strcmp(argv[1], \"root\"))\n {\n throw std::runtime_error(\"oops!\");\n }\n else\n {\n throw 1.0;\n }\n }\n\n printf(\n \"USAGE: %s {memory|root|other}\\n\"\n , argv[0]\n );\n\n return EXIT_SUCCESS;\n}\n\nint main(int argc, char** argv)\n{\n return pantheios::extras::main::invoke(argc, argv, main0);\n}\n\n#else \/\/ ? USE_wmain\n\nint main0(int argc, wchar_t** argv)\n{\n \/* do the \"main\" business of main() here, without worrying about\n * initialising Pantheios libraries\n *\/\n\n \/* in this case, we simply throw a given type of exception, as\n * requested by the user\n *\/\n\n if (argc == 2)\n {\n if (0 == wcscmp(argv[1], L\"memory\"))\n {\n throw std::bad_alloc();\n }\n else\n if (0 == wcscmp(argv[1], L\"root\"))\n {\n throw std::runtime_error(\"oops!\");\n }\n else\n {\n throw 1.0;\n }\n }\n\n wprintf(\n L\"USAGE: %s {memory|root|other}\\n\"\n , argv[0]\n );\n\n return EXIT_SUCCESS;\n}\n\nint wmain(int argc, wchar_t** argv)\n{\n return pantheios::extras::main::invoke(argc, argv, main0);\n}\n\n#endif \/\/ !USE_wmain\n\n\/* \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ end of file \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ *\/\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentservertests.h\"\n\n#include \"optionsmodel.h\"\n#include \"paymentrequestdata.h\"\n\n#include \"amount.h\"\n#include \"random.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include \n#include \n\n#include \n#include \n\nX509 *parse_b64der_cert(const char* cert_data)\n{\n std::vector data = DecodeBase64(cert_data);\n assert(data.size() > 0);\n const unsigned char* dptr = &data[0];\n X509 *cert = d2i_X509(NULL, &dptr, data.size());\n assert(cert);\n return cert;\n}\n\n\/\/\n\/\/ Test payment request handling\n\/\/\n\nstatic SendCoinsRecipient handleRequest(PaymentServer* server, std::vector& data)\n{\n RecipientCatcher sigCatcher;\n QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Write data to a temp file:\n QTemporaryFile f;\n f.open();\n f.write((const char*)&data[0], data.size());\n f.close();\n\n \/\/ Create a QObject, install event filter from PaymentServer\n \/\/ and send a file open event to the object\n QObject object;\n object.installEventFilter(server);\n QFileOpenEvent event(f.fileName());\n \/\/ If sending the event fails, this will cause sigCatcher to be empty,\n \/\/ which will lead to a test failure anyway.\n QCoreApplication::sendEvent(&object, &event);\n\n QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Return results from sigCatcher\n return sigCatcher.recipient;\n}\n\nvoid PaymentServerTests::paymentServerTests()\n{\n SelectParams(CBaseChainParams::MAIN);\n OptionsModel optionsModel;\n PaymentServer* server = new PaymentServer(NULL, false);\n X509_STORE* caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));\n PaymentServer::LoadRootCAs(caStore);\n server->setOptionsModel(&optionsModel);\n server->uiReady();\n\n std::vector data;\n SendCoinsRecipient r;\n QString merchant;\n\n \/\/ Now feed PaymentRequests to server, and observe signals it produces\n\n \/\/ Dogecoin: Disable certificate tests as we don't touch this code, and building test\n \/\/ data would take significant effort. Also pending discussion on spec\n \/\/ This payment request validates directly against the\n \/\/ caCert1 certificate authority:\n \/* data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant.org\"));\n\n \/\/ Signed, but expired, merchant cert in the request:\n data = DecodeBase64(paymentrequest2_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ 10-long certificate chain, all intermediates valid:\n data = DecodeBase64(paymentrequest3_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant8.org\"));\n\n \/\/ Long certificate chain, with an expired certificate in the middle:\n data = DecodeBase64(paymentrequest4_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Validly signed, but by a CA not in our root CA list:\n data = DecodeBase64(paymentrequest5_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Try again with no root CA's, verifiedMerchant should be empty:\n caStore = X509_STORE_new();\n PaymentServer::LoadRootCAs(caStore);\n data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Load second root certificate\n caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));\n PaymentServer::LoadRootCAs(caStore); *\/\n\n QByteArray byteArray;\n\n \/\/ For the tests below we just need the payment request data from\n \/\/ paymentrequestdata.h parsed + stored in r.paymentRequest.\n \/\/\n \/\/ These tests require us to bypass the following normal client execution flow\n \/\/ shown below to be able to explicitly just trigger a certain condition!\n \/\/\n \/\/ handleRequest()\n \/\/ -> PaymentServer::eventFilter()\n \/\/ -> PaymentServer::handleURIOrFile()\n \/\/ -> PaymentServer::readPaymentRequestFromFile()\n \/\/ -> PaymentServer::processPaymentRequest()\n\n \/\/ Contains a testnet paytoaddress, so payment request network doesn't match client network:\n data = DecodeBase64(paymentrequest1_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized, because network \"main\" is default, even for\n \/\/ uninizialized payment requests and that will fail our test here.\n QVERIFY(r.paymentRequest.IsInitialized());\n QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);\n\n \/\/ Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):\n data = DecodeBase64(paymentrequest2_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 1 < GetTime() == false (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):\n \/\/ 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)\n \/\/ -1 is 1969-12-31 23:59:59 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest3_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);\n\n \/\/ Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):\n \/\/ 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)\n \/\/ 0 is 1970-01-01 00:00:00 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest4_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares -9223372036854775808 < GetTime() == true (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Test BIP70 DoS protection:\n unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];\n GetRandBytes(randData, sizeof(randData));\n \/\/ Write data to a temp file:\n QTemporaryFile tempFile;\n tempFile.open();\n tempFile.write((const char*)randData, sizeof(randData));\n tempFile.close();\n \/\/ compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false\n QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);\n\n \/\/ Payment request with amount overflow (amount is set to 21000001 BTC):\n data = DecodeBase64(paymentrequest5_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ Extract address and amount from the request\n QList > sendingTos = r.paymentRequest.getPayTo();\n Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {\n CTxDestination dest;\n if (ExtractDestination(sendingTo.first, dest))\n QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);\n }\n\n delete server;\n}\n\nvoid RecipientCatcher::getRecipient(SendCoinsRecipient r)\n{\n recipient = r;\n}\nqt-tests: Disable payment server test that moves 21M+1 coins.\/\/ Copyright (c) 2009-2015 The Bitcoin Core developers\n\/\/ Distributed under the MIT software license, see the accompanying\n\/\/ file COPYING or http:\/\/www.opensource.org\/licenses\/mit-license.php.\n\n#include \"paymentservertests.h\"\n\n#include \"optionsmodel.h\"\n#include \"paymentrequestdata.h\"\n\n#include \"amount.h\"\n#include \"random.h\"\n#include \"script\/script.h\"\n#include \"script\/standard.h\"\n#include \"util.h\"\n#include \"utilstrencodings.h\"\n\n#include \n#include \n\n#include \n#include \n\nX509 *parse_b64der_cert(const char* cert_data)\n{\n std::vector data = DecodeBase64(cert_data);\n assert(data.size() > 0);\n const unsigned char* dptr = &data[0];\n X509 *cert = d2i_X509(NULL, &dptr, data.size());\n assert(cert);\n return cert;\n}\n\n\/\/\n\/\/ Test payment request handling\n\/\/\n\nstatic SendCoinsRecipient handleRequest(PaymentServer* server, std::vector& data)\n{\n RecipientCatcher sigCatcher;\n QObject::connect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Write data to a temp file:\n QTemporaryFile f;\n f.open();\n f.write((const char*)&data[0], data.size());\n f.close();\n\n \/\/ Create a QObject, install event filter from PaymentServer\n \/\/ and send a file open event to the object\n QObject object;\n object.installEventFilter(server);\n QFileOpenEvent event(f.fileName());\n \/\/ If sending the event fails, this will cause sigCatcher to be empty,\n \/\/ which will lead to a test failure anyway.\n QCoreApplication::sendEvent(&object, &event);\n\n QObject::disconnect(server, SIGNAL(receivedPaymentRequest(SendCoinsRecipient)),\n &sigCatcher, SLOT(getRecipient(SendCoinsRecipient)));\n\n \/\/ Return results from sigCatcher\n return sigCatcher.recipient;\n}\n\nvoid PaymentServerTests::paymentServerTests()\n{\n SelectParams(CBaseChainParams::MAIN);\n OptionsModel optionsModel;\n PaymentServer* server = new PaymentServer(NULL, false);\n X509_STORE* caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert1_BASE64));\n PaymentServer::LoadRootCAs(caStore);\n server->setOptionsModel(&optionsModel);\n server->uiReady();\n\n std::vector data;\n SendCoinsRecipient r;\n QString merchant;\n\n \/\/ Now feed PaymentRequests to server, and observe signals it produces\n\n \/\/ Dogecoin: Disable certificate tests as we don't touch this code, and building test\n \/\/ data would take significant effort. Also pending discussion on spec\n \/\/ This payment request validates directly against the\n \/\/ caCert1 certificate authority:\n \/* data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant.org\"));\n\n \/\/ Signed, but expired, merchant cert in the request:\n data = DecodeBase64(paymentrequest2_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ 10-long certificate chain, all intermediates valid:\n data = DecodeBase64(paymentrequest3_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"testmerchant8.org\"));\n\n \/\/ Long certificate chain, with an expired certificate in the middle:\n data = DecodeBase64(paymentrequest4_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Validly signed, but by a CA not in our root CA list:\n data = DecodeBase64(paymentrequest5_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Try again with no root CA's, verifiedMerchant should be empty:\n caStore = X509_STORE_new();\n PaymentServer::LoadRootCAs(caStore);\n data = DecodeBase64(paymentrequest1_cert1_BASE64);\n r = handleRequest(server, data);\n r.paymentRequest.getMerchant(caStore, merchant);\n QCOMPARE(merchant, QString(\"\"));\n\n \/\/ Load second root certificate\n caStore = X509_STORE_new();\n X509_STORE_add_cert(caStore, parse_b64der_cert(caCert2_BASE64));\n PaymentServer::LoadRootCAs(caStore); *\/\n\n QByteArray byteArray;\n\n \/\/ For the tests below we just need the payment request data from\n \/\/ paymentrequestdata.h parsed + stored in r.paymentRequest.\n \/\/\n \/\/ These tests require us to bypass the following normal client execution flow\n \/\/ shown below to be able to explicitly just trigger a certain condition!\n \/\/\n \/\/ handleRequest()\n \/\/ -> PaymentServer::eventFilter()\n \/\/ -> PaymentServer::handleURIOrFile()\n \/\/ -> PaymentServer::readPaymentRequestFromFile()\n \/\/ -> PaymentServer::processPaymentRequest()\n\n \/\/ Contains a testnet paytoaddress, so payment request network doesn't match client network:\n data = DecodeBase64(paymentrequest1_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized, because network \"main\" is default, even for\n \/\/ uninizialized payment requests and that will fail our test here.\n QVERIFY(r.paymentRequest.IsInitialized());\n QCOMPARE(PaymentServer::verifyNetwork(r.paymentRequest.getDetails()), false);\n\n \/\/ Expired payment request (expires is set to 1 = 1970-01-01 00:00:01):\n data = DecodeBase64(paymentrequest2_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 1 < GetTime() == false (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Unexpired payment request (expires is set to 0x7FFFFFFFFFFFFFFF = max. int64_t):\n \/\/ 9223372036854775807 (uint64), 9223372036854775807 (int64_t) and -1 (int32_t)\n \/\/ -1 is 1969-12-31 23:59:59 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest3_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares 9223372036854775807 < GetTime() == false (treated as unexpired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), false);\n\n \/\/ Unexpired payment request (expires is set to 0x8000000000000000 > max. int64_t, allowed uint64):\n \/\/ 9223372036854775808 (uint64), -9223372036854775808 (int64_t) and 0 (int32_t)\n \/\/ 0 is 1970-01-01 00:00:00 (for a 32 bit time values)\n data = DecodeBase64(paymentrequest4_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ compares -9223372036854775808 < GetTime() == true (treated as expired payment request)\n QCOMPARE(PaymentServer::verifyExpired(r.paymentRequest.getDetails()), true);\n\n \/\/ Test BIP70 DoS protection:\n unsigned char randData[BIP70_MAX_PAYMENTREQUEST_SIZE + 1];\n GetRandBytes(randData, sizeof(randData));\n \/\/ Write data to a temp file:\n QTemporaryFile tempFile;\n tempFile.open();\n tempFile.write((const char*)randData, sizeof(randData));\n tempFile.close();\n \/\/ compares 50001 <= BIP70_MAX_PAYMENTREQUEST_SIZE == false\n QCOMPARE(PaymentServer::verifySize(tempFile.size()), false);\n\n \/\/ Payment request with amount overflow (amount is set to 21000001 BTC):\n \/* PL: This doesn't work for Dogecoin (as there is no actual maximum coins)\n * I'm disabling this test for now.\n data = DecodeBase64(paymentrequest5_cert2_BASE64);\n byteArray = QByteArray((const char*)&data[0], data.size());\n r.paymentRequest.parse(byteArray);\n \/\/ Ensure the request is initialized\n QVERIFY(r.paymentRequest.IsInitialized());\n \/\/ Extract address and amount from the request\n QList > sendingTos = r.paymentRequest.getPayTo();\n Q_FOREACH (const PAIRTYPE(CScript, CAmount)& sendingTo, sendingTos) {\n CTxDestination dest;\n if (ExtractDestination(sendingTo.first, dest))\n QCOMPARE(PaymentServer::verifyAmount(sendingTo.second), false);\n }\n *\/\n\n delete server;\n}\n\nvoid RecipientCatcher::getRecipient(SendCoinsRecipient r)\n{\n recipient = r;\n}\n<|endoftext|>"} {"text":"\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"caf\/atom.hpp\"\n#include \"caf\/string_view.hpp\"\n#include \"caf\/timestamp.hpp\"\n\n\/\/ -- hard-coded default values for various CAF options ------------------------\n\nnamespace caf {\nnamespace defaults {\n\nnamespace stream {\n\nextern const timespan desired_batch_complexity;\nextern const timespan max_batch_delay;\nextern const timespan credit_round_interval;\n\n} \/\/ namespace streaming\n\nnamespace scheduler {\n\nextern const atom_value policy;\nextern string_view profiling_output_file;\nextern const size_t max_threads;\nextern const size_t max_throughput;\nextern const timespan profiling_resolution;\n\n} \/\/ namespace scheduler\n\nnamespace work_stealing {\n\nextern const size_t aggressive_poll_attempts;\nextern const size_t aggressive_steal_interval;\nextern const size_t moderate_poll_attempts;\nextern const size_t moderate_steal_interval;\nextern const timespan moderate_sleep_duration;\nextern const size_t relaxed_steal_interval;\nextern const timespan relaxed_sleep_duration;\n\n} \/\/ namespace work_stealing\n\nnamespace logger {\n\nextern string_view component_filter;\nextern const atom_value console;\nextern string_view console_format;\nextern const atom_value console_verbosity;\nextern string_view file_format;\nextern string_view file_name;\nextern const atom_value file_verbosity;\n\n} \/\/ namespace logger\n\nnamespace middleman {\n\nextern std::vector app_identifiers;\nextern const atom_value network_backend;\nextern const size_t max_consecutive_reads;\nextern const size_t heartbeat_interval;\nextern const size_t cached_udp_buffers;\nextern const size_t max_pending_msgs;\nextern const size_t workers;\n\n} \/\/ namespace middleman\n\n} \/\/ namespace defaults\n} \/\/ namespace caf\nMark hardcoded defaults as explicitly visible\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#pragma once\n\n#include \n#include \n#include \n#include \n\n#include \"caf\/config.hpp\"\n#include \"caf\/atom.hpp\"\n#include \"caf\/string_view.hpp\"\n#include \"caf\/timestamp.hpp\"\n\n\/\/ -- hard-coded default values for various CAF options ------------------------\n\nnamespace caf {\nnamespace defaults {\n\nnamespace stream {\n\nextern CAF_API const timespan desired_batch_complexity;\nextern CAF_API const timespan max_batch_delay;\nextern CAF_API const timespan credit_round_interval;\n\n} \/\/ namespace streaming\n\nnamespace scheduler {\n\nextern CAF_API const atom_value policy;\nextern CAF_API string_view profiling_output_file;\nextern CAF_API const size_t max_threads;\nextern CAF_API const size_t max_throughput;\nextern CAF_API const timespan profiling_resolution;\n\n} \/\/ namespace scheduler\n\nnamespace work_stealing {\n\nextern CAF_API const size_t aggressive_poll_attempts;\nextern CAF_API const size_t aggressive_steal_interval;\nextern CAF_API const size_t moderate_poll_attempts;\nextern CAF_API const size_t moderate_steal_interval;\nextern CAF_API const timespan moderate_sleep_duration;\nextern CAF_API const size_t relaxed_steal_interval;\nextern CAF_API const timespan relaxed_sleep_duration;\n\n} \/\/ namespace work_stealing\n\nnamespace logger {\n\nextern CAF_API string_view component_filter;\nextern CAF_API const atom_value console;\nextern CAF_API string_view console_format;\nextern CAF_API const atom_value console_verbosity;\nextern CAF_API string_view file_format;\nextern CAF_API string_view file_name;\nextern CAF_API const atom_value file_verbosity;\n\n} \/\/ namespace logger\n\nnamespace middleman {\n\nextern CAF_API std::vector app_identifiers;\nextern CAF_API const atom_value network_backend;\nextern CAF_API const size_t max_consecutive_reads;\nextern CAF_API const size_t heartbeat_interval;\nextern CAF_API const size_t cached_udp_buffers;\nextern CAF_API const size_t max_pending_msgs;\nextern CAF_API const size_t workers;\n\n} \/\/ namespace middleman\n\n} \/\/ namespace defaults\n} \/\/ namespace caf\n<|endoftext|>"} {"text":"\/* \n * cf. M. Hjorth-Jensen, Computational Physics, University of Oslo (2015) \n * http:\/\/www.mn.uio.no\/fysikk\/english\/people\/aca\/mhjensen\/ \n * Ernest Yeung (I typed it up and made modifications)\n * ernestyalumni@gmail.com\n * MIT License\n * cf. Chapter 3 Numerical differentiation and interpolation\n * 3.1 Numerical Differentiation\n * 3.1.1.1 Initializations and main program\n *\/\n\/*\n** Program to compute the second derivative of exp(x).\n** Three calling functions are included\n** in this version. In one function we read in the data from screen, \n** the next function computes the second derivative\n** while the last function prints out data to screen.\n*\/\nusing namespace std;\n#include \n\nvoid initialize(double *, double *, int *);\nvoid second_derivative(int, double, double, double *, double *);\nvoid output(double *, double *, double, int);\n\nint main()\n{\n \/\/ declarations of variables\n int number_of_steps;\n double x, initial_step;\n double *h_step, *computed_derivative;\n \/\/ read in input data from screen\n initialize(&initial_step, &x, &number_of_steps);\n \/\/ allocate space in memory for the one-dimensional arrays\n \/\/ h_step and computed_derivative\n h_step = new double[number_of_steps];\n computed_derivative = new double[number_of_steps];\n \/\/ compute the second derivative of exp(x)\n second_derivative(number_of_steps, x, initial_step, h_step, computed_derivative);\n \/\/ Then we print the results to file\n output(h_step, computed_derivative, x, number_of_steps);\n \/\/ free memory\n delete [] h_step;\n delete [] computed_derivative;\n return 0;\n} \/\/ end main program\n\t\t\t\t\t\t \nprogram1.cpp compiles and works\/* \n * cf. M. Hjorth-Jensen, Computational Physics, University of Oslo (2015) \n * http:\/\/www.mn.uio.no\/fysikk\/english\/people\/aca\/mhjensen\/ \n * Ernest Yeung (I typed it up and made modifications)\n * ernestyalumni@gmail.com\n * MIT License\n * cf. Chapter 3 Numerical differentiation and interpolation\n * 3.1 Numerical Differentiation\n * 3.1.1.1 Initializations and main program\n *\/\n\/*\n** Program to compute the second derivative of exp(x).\n** Three calling functions are included\n** in this version. In one function we read in the data from screen, \n** the next function computes the second derivative\n** while the last function prints out data to screen.\n*\/\n\/* \n** Big note - at least to me, program1.cpp in pp. 51 of Hjorth-Jensen's notes\n** code appears incomplete, and wouldn't compile (I don't think). I looked here:\n** https:\/\/github.com\/CompPhysics\/ComputationalPhysicsMSU\/blob\/master\/doc\/Programs\/LecturePrograms\/programs\/Classes\/cpp\/program1.cpp\n** and the entire code for program1.cpp appears there\n*\/\n\nusing namespace std;\n\/\/ #include I don't think this is correct of Hjorth-Jensen since printf,scanf are used\n#include \n#include \n\nvoid initialize(double *, double *, int *);\nvoid second_derivative(int, double, double, double *, double *);\nvoid output(double *, double *, double, int);\n\nint main()\n{\n \/\/ declarations of variables\n\n int number_of_steps;\n double x, initial_step;\n double *h_step, *computed_derivative;\n\n \/\/ read in input data from screen\n\n initialize(&initial_step, &x, &number_of_steps);\n\n \/\/ allocate space in memory for the one-dimensional arrays\n \/\/ h_step and computed_derivative\n\n h_step = new double[number_of_steps];\n computed_derivative = new double[number_of_steps];\n\n \/\/ compute the second derivative of exp(x)\n\n second_derivative(number_of_steps, x, initial_step, h_step, computed_derivative);\n\n \/\/ Then we print the results to file\n\n output(h_step, computed_derivative, x, number_of_steps);\n \/\/ free memory\n delete [] h_step;\n delete [] computed_derivative;\n return 0;\n} \/\/ end main program\n\n\/\/ Read in from screen the air temp, the number of steps\n\/\/ final time and the initial temperature *\/\n\nvoid initialize(double *initial_step, double *x, int *number_of_steps)\n{\n printf(\"Read in from screen initial step, x, and number of steps\\n\");\n scanf(\"%lf %lf %d\", initial_step, x, number_of_steps);\n return;\n} \/\/ end of function initialize\n\n\/\/ This function computes the second derivative\n\nvoid second_derivative( int number_of_steps, double x, double initial_step,\n\t\t\tdouble *h_step, double *computed_derivative)\n{\n int counter;\n double h;\n\n \/\/ calculate the step size\n \/\/ initialize the derivative, y and x (in minutes)\n \/\/ and iteration counter\n\n h = initial_step;\n\n \/\/ start computing for different step sizes\n for (counter=0; counter < number_of_steps; counter++ )\n {\n\n \/\/ setup arrays with derivatives and step sizes\n\n h_step[counter] = h;\n computed_derivative[counter] =\n\t(exp(x+h)-2.*exp(x) + exp(x-h))\/(h*h);\n h = h*0.5;\n } \/\/ end of do loop\n\n return;\n \n} \/\/ end of function second derivative\n\n\n\/\/ function to write out the final results\nvoid output(double *h_step, double *computed_derivative, double x,\n\t int number_of_steps)\n{\n int i;\n FILE *output_file;\n output_file = fopen(\"out.dat\", \"w\");\n for (i=0; i < number_of_steps; i++)\n {\n fprintf(output_file, \"%12.5E %12.5E \\n\",\n\t log10(h_step[i]),log10(fabs(computed_derivative[i]-exp(x))\/exp(x)));\n }\n fclose(output_file);\n\n} \/\/ end of function output\n\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2008 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the examples of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"mainwindow.h\"\n#include \"stationdialog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nMainWindow::MainWindow()\n : QWidget(0, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)\n{\n QAction *quitAction = new QAction(tr(\"E&xit\"), this);\n quitAction->setShortcut(tr(\"Ctrl+Q\"));\n connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\n\n QAction *configAction = new QAction(tr(\"&Select station...\"), this);\n configAction->setShortcut(tr(\"Ctrl+C\"));\n connect(configAction, SIGNAL(triggered()), this, SLOT(configure()));\n\n addAction(configAction);\n addAction(quitAction);\n\n setContextMenuPolicy(Qt::ActionsContextMenu);\n\n setWindowTitle(tr(\"Traffic Info Oslo\"));\n\n QTimer *timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeInformation()));\n timer->start(1000*60);\n\n const QSettings settings(\"Qt Software\", \"trafficinfo\");\n m_station = StationInformation(settings.value(\"stationId\", \"03012130\").toString(),\n settings.value(\"stationName\", \"Nydalen [T-bane] (OSL)\").toString());\n m_lines = settings.value(\"lines\", QStringList()).toStringList();\n\n updateTimeInformation();\n}\n\nMainWindow::~MainWindow()\n{\n QSettings settings(\"Qt Software\", \"trafficinfo\");\n settings.setValue(\"stationId\", m_station.id());\n settings.setValue(\"stationName\", m_station.name());\n settings.setValue(\"lines\", m_lines);\n}\n\nQSize MainWindow::sizeHint() const\n{\n return QSize(300, 200);\n}\n\nvoid MainWindow::mouseMoveEvent(QMouseEvent *event)\n{\n if (event->buttons() & Qt::LeftButton) {\n move(event->globalPos() - m_dragPosition);\n event->accept();\n }\n}\n\nvoid MainWindow::mousePressEvent(QMouseEvent *event)\n{\n if (event->button() == Qt::LeftButton) {\n m_dragPosition = event->globalPos() - frameGeometry().topLeft();\n event->accept();\n }\n}\n\nvoid MainWindow::paintEvent(QPaintEvent*)\n{\n QLinearGradient gradient(QPoint(width()\/2, 0), QPoint(width()\/2, height()));\n const QColor qtGreen(102, 176, 54);\n gradient.setColorAt(0, qtGreen.dark());\n gradient.setColorAt(0.5, qtGreen);\n gradient.setColorAt(1, qtGreen.dark());\n\n QPainter p(this);\n p.fillRect(0, 0, width(), height(), gradient);\n\n QFont headerFont(\"Sans Serif\", 12, QFont::Bold);\n QFont normalFont(\"Sans Serif\", 9, QFont::Normal);\n\n \/\/ draw it twice for shadow effect\n p.setFont(headerFont);\n QRect headerRect(1, 1, width(), 25);\n p.setPen(Qt::black);\n p.drawText(headerRect, Qt::AlignCenter, m_station.name());\n\n headerRect.moveTopLeft(QPoint(0, 0));\n p.setPen(Qt::white);\n p.drawText(headerRect, Qt::AlignCenter, m_station.name());\n\n p.setFont(normalFont);\n int pos = 40;\n for (int i = 0; i < m_times.count() && i < 9; ++i) {\n p.setPen(Qt::black);\n p.drawText(51, pos + 1, m_times.at(i).time());\n p.drawText(101, pos + 1, m_times.at(i).direction());\n\n p.setPen(Qt::white);\n p.drawText(50, pos, m_times.at(i).time());\n p.drawText(100, pos, m_times.at(i).direction());\n\n pos += 18;\n }\n}\n\nvoid MainWindow::resizeEvent(QResizeEvent*)\n{\n QBitmap maskBitmap(width(), height());\n maskBitmap.clear();\n\n QPainter p(&maskBitmap);\n p.setBrush(Qt::black);\n p.drawRoundRect(0, 0, width(), height(), 20, 30);\n p.end();\n\n setMask(maskBitmap);\n}\n\nvoid MainWindow::updateTimeInformation()\n{\n TimeQuery query;\n m_times = query.query(m_station.id(), m_lines, QDateTime::currentDateTime());\n\n update();\n}\n\nvoid MainWindow::configure()\n{\n StationDialog dlg(m_station.name(), m_lines, this);\n if (dlg.exec()) {\n m_station = dlg.selectedStation();\n m_lines = dlg.lineNumbers();\n updateTimeInformation();\n }\n}\nMake the traffic info example not hit the server every minute.\/****************************************************************************\n**\n** Copyright (C) 2008 Nokia Corporation and\/or its subsidiary(-ies).\n** Contact: Qt Software Information (qt-info@nokia.com)\n**\n** This file is part of the examples of the Qt Toolkit.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the either Technology Preview License Agreement or the\n** Beta Release License Agreement.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain\n** additional rights. These rights are described in the Nokia Qt LGPL\n** Exception version 1.0, included in the file LGPL_EXCEPTION.txt in this\n** package.\n**\n** GNU General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU\n** General Public License version 3.0 as published by the Free Software\n** Foundation and appearing in the file LICENSE.GPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU General Public License version 3.0 requirements will be\n** met: http:\/\/www.gnu.org\/copyleft\/gpl.html.\n**\n** If you are unsure which license is appropriate for your use, please\n** contact the sales department at qt-sales@nokia.com.\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"mainwindow.h\"\n#include \"stationdialog.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nMainWindow::MainWindow()\n : QWidget(0, Qt::FramelessWindowHint | Qt::WindowStaysOnTopHint)\n{\n QAction *quitAction = new QAction(tr(\"E&xit\"), this);\n quitAction->setShortcut(tr(\"Ctrl+Q\"));\n connect(quitAction, SIGNAL(triggered()), qApp, SLOT(quit()));\n\n QAction *configAction = new QAction(tr(\"&Select station...\"), this);\n configAction->setShortcut(tr(\"Ctrl+C\"));\n connect(configAction, SIGNAL(triggered()), this, SLOT(configure()));\n\n addAction(configAction);\n addAction(quitAction);\n\n setContextMenuPolicy(Qt::ActionsContextMenu);\n\n setWindowTitle(tr(\"Traffic Info Oslo\"));\n\n QTimer *timer = new QTimer(this);\n connect(timer, SIGNAL(timeout()), this, SLOT(updateTimeInformation()));\n timer->start(1000*60*5);\n\n const QSettings settings(\"Qt Software\", \"trafficinfo\");\n m_station = StationInformation(settings.value(\"stationId\", \"03012130\").toString(),\n settings.value(\"stationName\", \"Nydalen [T-bane] (OSL)\").toString());\n m_lines = settings.value(\"lines\", QStringList()).toStringList();\n\n updateTimeInformation();\n}\n\nMainWindow::~MainWindow()\n{\n QSettings settings(\"Qt Software\", \"trafficinfo\");\n settings.setValue(\"stationId\", m_station.id());\n settings.setValue(\"stationName\", m_station.name());\n settings.setValue(\"lines\", m_lines);\n}\n\nQSize MainWindow::sizeHint() const\n{\n return QSize(300, 200);\n}\n\nvoid MainWindow::mouseMoveEvent(QMouseEvent *event)\n{\n if (event->buttons() & Qt::LeftButton) {\n move(event->globalPos() - m_dragPosition);\n event->accept();\n }\n}\n\nvoid MainWindow::mousePressEvent(QMouseEvent *event)\n{\n if (event->button() == Qt::LeftButton) {\n m_dragPosition = event->globalPos() - frameGeometry().topLeft();\n event->accept();\n }\n}\n\nvoid MainWindow::paintEvent(QPaintEvent*)\n{\n QLinearGradient gradient(QPoint(width()\/2, 0), QPoint(width()\/2, height()));\n const QColor qtGreen(102, 176, 54);\n gradient.setColorAt(0, qtGreen.dark());\n gradient.setColorAt(0.5, qtGreen);\n gradient.setColorAt(1, qtGreen.dark());\n\n QPainter p(this);\n p.fillRect(0, 0, width(), height(), gradient);\n\n QFont headerFont(\"Sans Serif\", 12, QFont::Bold);\n QFont normalFont(\"Sans Serif\", 9, QFont::Normal);\n\n \/\/ draw it twice for shadow effect\n p.setFont(headerFont);\n QRect headerRect(1, 1, width(), 25);\n p.setPen(Qt::black);\n p.drawText(headerRect, Qt::AlignCenter, m_station.name());\n\n headerRect.moveTopLeft(QPoint(0, 0));\n p.setPen(Qt::white);\n p.drawText(headerRect, Qt::AlignCenter, m_station.name());\n\n p.setFont(normalFont);\n int pos = 40;\n for (int i = 0; i < m_times.count() && i < 9; ++i) {\n p.setPen(Qt::black);\n p.drawText(51, pos + 1, m_times.at(i).time());\n p.drawText(101, pos + 1, m_times.at(i).direction());\n\n p.setPen(Qt::white);\n p.drawText(50, pos, m_times.at(i).time());\n p.drawText(100, pos, m_times.at(i).direction());\n\n pos += 18;\n }\n}\n\nvoid MainWindow::resizeEvent(QResizeEvent*)\n{\n QBitmap maskBitmap(width(), height());\n maskBitmap.clear();\n\n QPainter p(&maskBitmap);\n p.setBrush(Qt::black);\n p.drawRoundRect(0, 0, width(), height(), 20, 30);\n p.end();\n\n setMask(maskBitmap);\n}\n\nvoid MainWindow::updateTimeInformation()\n{\n TimeQuery query;\n m_times = query.query(m_station.id(), m_lines, QDateTime::currentDateTime());\n\n update();\n}\n\nvoid MainWindow::configure()\n{\n StationDialog dlg(m_station.name(), m_lines, this);\n if (dlg.exec()) {\n m_station = dlg.selectedStation();\n m_lines = dlg.lineNumbers();\n updateTimeInformation();\n }\n}\n<|endoftext|>"} {"text":"\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file EthereumHost.cpp\n * @author Gav Wood \n * @date 2014\n *\/\n\n#include \"EthereumHost.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"BlockChain.h\"\n#include \"TransactionQueue.h\"\n#include \"BlockQueue.h\"\n#include \"EthereumPeer.h\"\n#include \"DownloadMan.h\"\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nusing namespace p2p;\n\nEthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId):\n\tHostCapability(),\n\tWorker\t\t(\"ethsync\"),\n\tm_chain\t\t(_ch),\n\tm_tq\t\t(_tq),\n\tm_bq\t\t(_bq),\n\tm_networkId\t(_networkId)\n{\n\tm_latestBlockSent = _ch.currentHash();\n}\n\nEthereumHost::~EthereumHost()\n{\n\tfor (auto i: peerSessions())\n\t\ti.first->cap().get()->abortSync();\n}\n\nbool EthereumHost::ensureInitialised()\n{\n\tif (!m_latestBlockSent)\n\t{\n\t\t\/\/ First time - just initialise.\n\t\tm_latestBlockSent = m_chain.currentHash();\n\t\tclog(NetNote) << \"Initialising: latest=\" << m_latestBlockSent.abridged();\n\n\t\tfor (auto const& i: m_tq.transactions())\n\t\t\tm_transactionsSent.insert(i.first);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid EthereumHost::noteNeedsSyncing(EthereumPeer* _who)\n{\n\t\/\/ if already downloading hash-chain, ignore.\n\tif (isSyncing())\n\t{\n\t\tclog(NetAllDetail) << \"Sync in progress: Just set to help out.\";\n\t\tif (m_syncer->m_asking == Asking::Blocks)\n\t\t\t_who->transition(Asking::Blocks);\n\t}\n\telse\n\t\t\/\/ otherwise check to see if we should be downloading...\n\t\t_who->attemptSync();\n}\n\nvoid EthereumHost::changeSyncer(EthereumPeer* _syncer)\n{\n\tif (_syncer)\n\t\tclog(NetAllDetail) << \"Changing syncer to\" << _syncer->session()->socketId();\n\telse\n\t\tclog(NetAllDetail) << \"Clearing syncer.\";\n\n\tm_syncer = _syncer;\n\tif (isSyncing())\n\t{\n\t\tif (_syncer->m_asking == Asking::Blocks)\n\t\t\tfor (auto j: peerSessions())\n\t\t\t{\n\t\t\t\tauto e = j.first->cap().get();\n\t\t\t\tif (e != _syncer && e->m_asking == Asking::Nothing)\n\t\t\t\t\te->transition(Asking::Blocks);\n\t\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ start grabbing next hash chain if there is one.\n\t\tfor (auto j: peerSessions())\n\t\t{\n\t\t\tj.first->cap()->attemptSync();\n\t\t\tif (isSyncing())\n\t\t\t\treturn;\n\t\t}\n\t\tclog(NetNote) << \"No more peers to sync with.\";\n\t}\n}\n\nvoid EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency)\n{\n\tif (m_man.isComplete())\n\t{\n\t\t\/\/ Done our chain-get.\n\t\tclog(NetNote) << \"Chain download complete.\";\n\t\t\/\/ 1\/100th for each useful block hash.\n\t\t_who->addRating(m_man.chain().size() \/ 100);\n\t\tm_man.reset();\n\t}\n\telse if (_who->isSyncing())\n\t{\n\t\tif (_clemency)\n\t\t\tclog(NetNote) << \"Chain download failed. Aborted while incomplete.\";\n\t\telse\n\t\t{\n\t\t\t\/\/ Done our chain-get.\n\t\t\tclog(NetWarn) << \"Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished.\";\n\t\t\tclog(NetWarn) << m_man.remaining();\n\t\t\tclog(NetWarn) << \"WOULD BAN.\";\n\/\/\t\t\tm_banned.insert(_who->session()->id());\t\t\t\/\/ We know who you are!\n\/\/\t\t\t_who->disable(\"Peer sent hashes but was unable to provide the blocks.\");\n\t\t}\n\t\tm_man.reset();\n\t}\n}\n\nvoid EthereumHost::reset()\n{\n\tif (m_syncer)\n\t\tm_syncer->abortSync();\n\n\tm_man.resetToChain(h256s());\n\n\tm_latestBlockSent = h256();\n\tm_transactionsSent.clear();\n}\n\nvoid EthereumHost::doWork()\n{\n\tbool netChange = ensureInitialised();\n\tauto h = m_chain.currentHash();\n\t\/\/ If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks\n\tif (!isSyncing() && m_chain.isKnown(m_latestBlockSent))\n\t{\n\t\tif (m_newTransactions)\n\t\t{\n\t\t\tm_newTransactions = false;\n\t\t\tmaintainTransactions();\n\t\t}\n\t\tif (m_newBlocks)\n\t\t{\n\t\t\tm_newBlocks = false;\n\t\t\tmaintainBlocks(h);\n\t\t}\n\t}\n\n\tfor (auto p: peerSessions())\n\t\tif (shared_ptr const& ep = p.first->cap())\n\t\t\tep->tick();\n\n\/\/\treturn netChange;\n\t\/\/ TODO: Figure out what to do with netChange.\n\t(void)netChange;\n}\n\nvoid EthereumHost::maintainTransactions()\n{\n\t\/\/ Send any new transactions.\n\tmap, h256s> peerTransactions;\n\tauto ts = m_tq.transactions();\n\tfor (auto const& i: ts)\n\t{\n\t\tbool unsent = !m_transactionsSent.count(i.first);\n\t\tfor (auto const& p: randomSelection(25, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); }))\n\t\t\tpeerTransactions[p].push_back(i.first);\n\t}\n\tfor (auto const& t: ts)\n\t\tm_transactionsSent.insert(t.first);\n\tfor (auto p: peerSessions())\n\t\tif (auto ep = p.first->cap())\n\t\t{\n\t\t\tbytes b;\n\t\t\tunsigned n = 0;\n\t\t\tfor (auto const& h: peerTransactions[ep])\n\t\t\t{\n\t\t\t\tep->m_knownTransactions.insert(h);\n\t\t\t\tb += ts[h].rlp();\n\t\t\t\t++n;\n\t\t\t}\n\n\t\t\tep->clearKnownTransactions();\n\n\t\t\tif (n || ep->m_requireTransactions)\n\t\t\t{\n\t\t\t\tRLPStream ts;\n\t\t\t\tep->prep(ts, TransactionsPacket, n).appendRaw(b, n);\n\t\t\t\tep->sealAndSend(ts);\n\t\t\t}\n\t\t\tep->m_requireTransactions = false;\n\t\t}\n}\n\nstd::vector> EthereumHost::randomSelection(unsigned _percent, std::function const& _allow)\n{\n\tstd::vector> candidates;\n\tcandidates.reserve(peerSessions().size());\n\tfor (auto const& j: peerSessions())\n\t{\n\t\tauto pp = j.first->cap();\n\t\tif (_allow(pp.get()))\n\t\t\tcandidates.push_back(pp);\n\t}\n\n\tstd::vector> ret;\n\tfor (unsigned i = (peerSessions().size() * _percent + 99) \/ 100; i-- && candidates.size();)\n\t{\n\t\tunsigned n = rand() % candidates.size();\n\t\tret.push_back(std::move(candidates[n]));\n\t\tcandidates.erase(candidates.begin() + n);\n\t}\n\treturn ret;\n}\n\nvoid EthereumHost::maintainBlocks(h256 _currentHash)\n{\n\t\/\/ Send any new blocks.\n\tauto detailsFrom = m_chain.details(m_latestBlockSent);\n\tauto detailsTo = m_chain.details(_currentHash);\n\tif (detailsFrom.totalDifficulty < detailsTo.totalDifficulty)\n\t{\n\t\tif (diff(detailsFrom.number, detailsTo.number) < 20)\n\t\t{\n\t\t\t\/\/ don't be sending more than 20 \"new\" blocks. if there are any more we were probably waaaay behind.\n\t\t\tclog(NetMessageSummary) << \"Sending a new block (current is\" << _currentHash << \", was\" << m_latestBlockSent << \")\";\n\n\t\t\th256s blocks = get<0>(m_chain.treeRoute(m_latestBlockSent, _currentHash, false, false, true));\n\n\t\t\tfor (auto const& p: randomSelection(25, [&](EthereumPeer* p){return !p->m_knownBlocks.count(_currentHash); }))\n\t\t\t\tfor (auto const& b: blocks)\n\t\t\t\t\tif (!p->m_knownBlocks.count(b))\n\t\t\t\t\t{\n\t\t\t\t\t\tRLPStream ts;\n\t\t\t\t\t\tp->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(b), 1).append(m_chain.details(b).totalDifficulty);\n\n\t\t\t\t\t\tGuard l(p->x_knownBlocks);\n\t\t\t\t\t\tp->sealAndSend(ts);\n\t\t\t\t\t\tp->m_knownBlocks.clear();\n\t\t\t\t\t}\n\t\t}\n\t\tm_latestBlockSent = _currentHash;\n\t}\n}\nBroadcast everything to everyone.\/*\n\tThis file is part of cpp-ethereum.\n\n\tcpp-ethereum is free software: you can redistribute it and\/or modify\n\tit under the terms of the GNU General Public License as published by\n\tthe Free Software Foundation, either version 3 of the License, or\n\t(at your option) any later version.\n\n\tcpp-ethereum is distributed in the hope that it will be useful,\n\tbut WITHOUT ANY WARRANTY; without even the implied warranty of\n\tMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\tGNU General Public License for more details.\n\n\tYou should have received a copy of the GNU General Public License\n\talong with cpp-ethereum. If not, see .\n*\/\n\/** @file EthereumHost.cpp\n * @author Gav Wood \n * @date 2014\n *\/\n\n#include \"EthereumHost.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"BlockChain.h\"\n#include \"TransactionQueue.h\"\n#include \"BlockQueue.h\"\n#include \"EthereumPeer.h\"\n#include \"DownloadMan.h\"\nusing namespace std;\nusing namespace dev;\nusing namespace dev::eth;\nusing namespace p2p;\n\nEthereumHost::EthereumHost(BlockChain const& _ch, TransactionQueue& _tq, BlockQueue& _bq, u256 _networkId):\n\tHostCapability(),\n\tWorker\t\t(\"ethsync\"),\n\tm_chain\t\t(_ch),\n\tm_tq\t\t(_tq),\n\tm_bq\t\t(_bq),\n\tm_networkId\t(_networkId)\n{\n\tm_latestBlockSent = _ch.currentHash();\n}\n\nEthereumHost::~EthereumHost()\n{\n\tfor (auto i: peerSessions())\n\t\ti.first->cap().get()->abortSync();\n}\n\nbool EthereumHost::ensureInitialised()\n{\n\tif (!m_latestBlockSent)\n\t{\n\t\t\/\/ First time - just initialise.\n\t\tm_latestBlockSent = m_chain.currentHash();\n\t\tclog(NetNote) << \"Initialising: latest=\" << m_latestBlockSent.abridged();\n\n\t\tfor (auto const& i: m_tq.transactions())\n\t\t\tm_transactionsSent.insert(i.first);\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nvoid EthereumHost::noteNeedsSyncing(EthereumPeer* _who)\n{\n\t\/\/ if already downloading hash-chain, ignore.\n\tif (isSyncing())\n\t{\n\t\tclog(NetAllDetail) << \"Sync in progress: Just set to help out.\";\n\t\tif (m_syncer->m_asking == Asking::Blocks)\n\t\t\t_who->transition(Asking::Blocks);\n\t}\n\telse\n\t\t\/\/ otherwise check to see if we should be downloading...\n\t\t_who->attemptSync();\n}\n\nvoid EthereumHost::changeSyncer(EthereumPeer* _syncer)\n{\n\tif (_syncer)\n\t\tclog(NetAllDetail) << \"Changing syncer to\" << _syncer->session()->socketId();\n\telse\n\t\tclog(NetAllDetail) << \"Clearing syncer.\";\n\n\tm_syncer = _syncer;\n\tif (isSyncing())\n\t{\n\t\tif (_syncer->m_asking == Asking::Blocks)\n\t\t\tfor (auto j: peerSessions())\n\t\t\t{\n\t\t\t\tauto e = j.first->cap().get();\n\t\t\t\tif (e != _syncer && e->m_asking == Asking::Nothing)\n\t\t\t\t\te->transition(Asking::Blocks);\n\t\t\t}\n\t}\n\telse\n\t{\n\t\t\/\/ start grabbing next hash chain if there is one.\n\t\tfor (auto j: peerSessions())\n\t\t{\n\t\t\tj.first->cap()->attemptSync();\n\t\t\tif (isSyncing())\n\t\t\t\treturn;\n\t\t}\n\t\tclog(NetNote) << \"No more peers to sync with.\";\n\t}\n}\n\nvoid EthereumHost::noteDoneBlocks(EthereumPeer* _who, bool _clemency)\n{\n\tif (m_man.isComplete())\n\t{\n\t\t\/\/ Done our chain-get.\n\t\tclog(NetNote) << \"Chain download complete.\";\n\t\t\/\/ 1\/100th for each useful block hash.\n\t\t_who->addRating(m_man.chain().size() \/ 100);\n\t\tm_man.reset();\n\t}\n\telse if (_who->isSyncing())\n\t{\n\t\tif (_clemency)\n\t\t\tclog(NetNote) << \"Chain download failed. Aborted while incomplete.\";\n\t\telse\n\t\t{\n\t\t\t\/\/ Done our chain-get.\n\t\t\tclog(NetWarn) << \"Chain download failed. Peer with blocks didn't have them all. This peer is bad and should be punished.\";\n\t\t\tclog(NetWarn) << m_man.remaining();\n\t\t\tclog(NetWarn) << \"WOULD BAN.\";\n\/\/\t\t\tm_banned.insert(_who->session()->id());\t\t\t\/\/ We know who you are!\n\/\/\t\t\t_who->disable(\"Peer sent hashes but was unable to provide the blocks.\");\n\t\t}\n\t\tm_man.reset();\n\t}\n}\n\nvoid EthereumHost::reset()\n{\n\tif (m_syncer)\n\t\tm_syncer->abortSync();\n\n\tm_man.resetToChain(h256s());\n\n\tm_latestBlockSent = h256();\n\tm_transactionsSent.clear();\n}\n\nvoid EthereumHost::doWork()\n{\n\tbool netChange = ensureInitialised();\n\tauto h = m_chain.currentHash();\n\t\/\/ If we've finished our initial sync (including getting all the blocks into the chain so as to reduce invalid transactions), start trading transactions & blocks\n\tif (!isSyncing() && m_chain.isKnown(m_latestBlockSent))\n\t{\n\t\tif (m_newTransactions)\n\t\t{\n\t\t\tm_newTransactions = false;\n\t\t\tmaintainTransactions();\n\t\t}\n\t\tif (m_newBlocks)\n\t\t{\n\t\t\tm_newBlocks = false;\n\t\t\tmaintainBlocks(h);\n\t\t}\n\t}\n\n\tfor (auto p: peerSessions())\n\t\tif (shared_ptr const& ep = p.first->cap())\n\t\t\tep->tick();\n\n\/\/\treturn netChange;\n\t\/\/ TODO: Figure out what to do with netChange.\n\t(void)netChange;\n}\n\nvoid EthereumHost::maintainTransactions()\n{\n\t\/\/ Send any new transactions.\n\tmap, h256s> peerTransactions;\n\tauto ts = m_tq.transactions();\n\tfor (auto const& i: ts)\n\t{\n\t\tbool unsent = !m_transactionsSent.count(i.first);\n\t\tfor (auto const& p: randomSelection(100, [&](EthereumPeer* p) { return p->m_requireTransactions || (unsent && !p->m_knownTransactions.count(i.first)); }))\n\t\t\tpeerTransactions[p].push_back(i.first);\n\t}\n\tfor (auto const& t: ts)\n\t\tm_transactionsSent.insert(t.first);\n\tfor (auto p: peerSessions())\n\t\tif (auto ep = p.first->cap())\n\t\t{\n\t\t\tbytes b;\n\t\t\tunsigned n = 0;\n\t\t\tfor (auto const& h: peerTransactions[ep])\n\t\t\t{\n\t\t\t\tep->m_knownTransactions.insert(h);\n\t\t\t\tb += ts[h].rlp();\n\t\t\t\t++n;\n\t\t\t}\n\n\t\t\tep->clearKnownTransactions();\n\n\t\t\tif (n || ep->m_requireTransactions)\n\t\t\t{\n\t\t\t\tRLPStream ts;\n\t\t\t\tep->prep(ts, TransactionsPacket, n).appendRaw(b, n);\n\t\t\t\tep->sealAndSend(ts);\n\t\t\t}\n\t\t\tep->m_requireTransactions = false;\n\t\t}\n}\n\nstd::vector> EthereumHost::randomSelection(unsigned _percent, std::function const& _allow)\n{\n\tstd::vector> candidates;\n\tcandidates.reserve(peerSessions().size());\n\tfor (auto const& j: peerSessions())\n\t{\n\t\tauto pp = j.first->cap();\n\t\tif (_allow(pp.get()))\n\t\t\tcandidates.push_back(pp);\n\t}\n\n\tstd::vector> ret;\n\tfor (unsigned i = (peerSessions().size() * _percent + 99) \/ 100; i-- && candidates.size();)\n\t{\n\t\tunsigned n = rand() % candidates.size();\n\t\tret.push_back(std::move(candidates[n]));\n\t\tcandidates.erase(candidates.begin() + n);\n\t}\n\treturn ret;\n}\n\nvoid EthereumHost::maintainBlocks(h256 _currentHash)\n{\n\t\/\/ Send any new blocks.\n\tauto detailsFrom = m_chain.details(m_latestBlockSent);\n\tauto detailsTo = m_chain.details(_currentHash);\n\tif (detailsFrom.totalDifficulty < detailsTo.totalDifficulty)\n\t{\n\t\tif (diff(detailsFrom.number, detailsTo.number) < 20)\n\t\t{\n\t\t\t\/\/ don't be sending more than 20 \"new\" blocks. if there are any more we were probably waaaay behind.\n\t\t\tclog(NetMessageSummary) << \"Sending a new block (current is\" << _currentHash << \", was\" << m_latestBlockSent << \")\";\n\n\t\t\th256s blocks = get<0>(m_chain.treeRoute(m_latestBlockSent, _currentHash, false, false, true));\n\n\t\t\tfor (auto const& p: randomSelection(100, [&](EthereumPeer* p){return !p->m_knownBlocks.count(_currentHash); }))\n\t\t\t\tfor (auto const& b: blocks)\n\t\t\t\t\tif (!p->m_knownBlocks.count(b))\n\t\t\t\t\t{\n\t\t\t\t\t\tRLPStream ts;\n\t\t\t\t\t\tp->prep(ts, NewBlockPacket, 2).appendRaw(m_chain.block(b), 1).append(m_chain.details(b).totalDifficulty);\n\n\t\t\t\t\t\tGuard l(p->x_knownBlocks);\n\t\t\t\t\t\tp->sealAndSend(ts);\n\t\t\t\t\t\tp->m_knownBlocks.clear();\n\t\t\t\t\t}\n\t\t}\n\t\tm_latestBlockSent = _currentHash;\n\t}\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Milian Wolff \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n\/**\n * @file heaptrack_interpret.cpp\n *\n * @brief Interpret raw heaptrack data and add Dwarf based debug information.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"libbacktrace\/backtrace.h\"\n#include \"libbacktrace\/internal.h\"\n#include \"linereader.h\"\n\nusing namespace std;\n\nnamespace {\n\nstring demangle(const char* function)\n{\n if (!function) {\n return {};\n } else if (function[0] != '_' || function[1] != 'Z') {\n return {function};\n }\n\n string ret;\n int status = 0;\n char* demangled = abi::__cxa_demangle(function, 0, 0, &status);\n if (demangled) {\n ret = demangled;\n free(demangled);\n }\n return ret;\n}\n\nstruct AddressInformation\n{\n string function;\n string file;\n int line = 0;\n};\n\nstruct Module\n{\n Module(uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState, size_t moduleIndex)\n : addressStart(addressStart)\n , addressEnd(addressEnd)\n , moduleIndex(moduleIndex)\n , backtraceState(backtraceState)\n {\n }\n\n AddressInformation resolveAddress(uintptr_t address) const\n {\n AddressInformation info;\n if (!backtraceState) {\n return info;\n }\n\n backtrace_pcinfo(backtraceState, address,\n [] (void *data, uintptr_t \/*addr*\/, const char *file, int line, const char *function) -> int {\n auto info = reinterpret_cast(data);\n info->function = demangle(function);\n info->file = file ? file : \"\";\n info->line = line;\n return 0;\n }, [] (void *\/*data*\/, const char *\/*msg*\/, int \/*errnum*\/) {}, &info);\n\n if (info.function.empty()) {\n backtrace_syminfo(backtraceState, address,\n [] (void *data, uintptr_t \/*pc*\/, const char *symname, uintptr_t \/*symval*\/, uintptr_t \/*symsize*\/) {\n if (symname) {\n reinterpret_cast(data)->function = demangle(symname);\n }\n }, [] (void *\/*data*\/, const char *msg, int errnum) {\n cerr << \"Module backtrace error (code \" << errnum << \"): \" << msg << endl;\n }, &info);\n }\n\n return info;\n }\n\n bool operator<(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, moduleIndex)\n < make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);\n }\n\n bool operator!=(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, moduleIndex)\n != make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);\n }\n\n uintptr_t addressStart;\n uintptr_t addressEnd;\n size_t moduleIndex;\n backtrace_state* backtraceState;\n};\n\nstruct Allocation\n{\n \/\/ backtrace entry point\n size_t ipIndex;\n \/\/ number of allocations\n size_t allocations;\n \/\/ amount of bytes leaked\n size_t leaked;\n};\n\n\/**\n * Information for a single call to an allocation function\n *\/\nstruct AllocationInfo\n{\n size_t ipIndex;\n size_t size;\n};\n\nstruct ResolvedIP\n{\n size_t moduleIndex = 0;\n size_t fileIndex = 0;\n size_t functionIndex = 0;\n int line = 0;\n};\n\nstruct AccumulatedTraceData\n{\n AccumulatedTraceData()\n {\n m_modules.reserve(256);\n m_backtraceStates.reserve(64);\n m_internedData.reserve(4096);\n m_encounteredIps.reserve(32768);\n }\n\n ~AccumulatedTraceData()\n {\n fprintf(stdout, \"# strings: %lu\\n# ips: %lu\\n\",\n m_internedData.size(), m_encounteredIps.size());\n }\n\n ResolvedIP resolve(const uintptr_t ip)\n {\n if (m_modulesDirty) {\n \/\/ sort by addresses, required for binary search below\n sort(m_modules.begin(), m_modules.end());\n\n for (size_t i = 0; i < m_modules.size(); ++i) {\n const auto& m1 = m_modules[i];\n for (size_t j = i + 1; j < m_modules.size(); ++j) {\n if (i == j) {\n continue;\n }\n const auto& m2 = m_modules[j];\n if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||\n (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))\n {\n cerr << \"OVERLAPPING MODULES: \" << hex\n << m1.moduleIndex << \" (\" << m1.addressStart << \" to \" << m1.addressEnd << \") and \"\n << m1.moduleIndex << \" (\" << m2.addressStart << \" to \" << m2.addressEnd << \")\\n\"\n << dec;\n } else if (m2.addressStart >= m1.addressEnd) {\n break;\n }\n }\n }\n\n m_modulesDirty = false;\n }\n\n ResolvedIP data;\n \/\/ find module for this instruction pointer\n auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,\n [] (const Module& module, const uintptr_t ip) -> bool {\n return module.addressEnd < ip;\n });\n if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {\n data.moduleIndex = module->moduleIndex;\n const auto info = module->resolveAddress(ip);\n data.fileIndex = intern(info.file);\n data.functionIndex = intern(info.function);\n data.line = info.line;\n }\n return data;\n }\n\n size_t intern(const string& str)\n {\n if (str.empty()) {\n return 0;\n }\n\n auto it = m_internedData.find(str);\n if (it != m_internedData.end()) {\n return it->second;\n }\n const size_t id = m_internedData.size() + 1;\n m_internedData.insert(it, make_pair(str, id));\n fprintf(stdout, \"s %s\\n\", str.c_str());\n return id;\n }\n\n void addModule(backtrace_state* backtraceState, const size_t moduleIndex,\n const uintptr_t addressStart, const uintptr_t addressEnd)\n {\n m_modules.emplace_back(addressStart, addressEnd, backtraceState, moduleIndex);\n m_modulesDirty = true;\n }\n\n void clearModules()\n {\n \/\/ TODO: optimize this, reuse modules that are still valid\n m_modules.clear();\n m_modulesDirty = true;\n }\n\n size_t addIp(const uintptr_t instructionPointer)\n {\n if (!instructionPointer) {\n return 0;\n }\n\n auto it = m_encounteredIps.find(instructionPointer);\n if (it != m_encounteredIps.end()) {\n return it->second;\n }\n\n const size_t ipId = m_encounteredIps.size() + 1;\n m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));\n\n const auto ip = resolve(instructionPointer);\n fprintf(stdout, \"i %lx %lx\", instructionPointer, ip.moduleIndex);\n if (ip.functionIndex || ip.fileIndex) {\n fprintf(stdout, \" %lx\", ip.functionIndex);\n if (ip.fileIndex) {\n fprintf(stdout, \" %lx %x\", ip.fileIndex, ip.line);\n }\n }\n fputc('\\n', stdout);\n return ipId;\n }\n\n \/**\n * Prevent the same file from being initialized multiple times.\n * This drastically cuts the memory consumption down\n *\/\n backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)\n {\n if (boost::algorithm::starts_with(fileName, \"linux-vdso.so\")) {\n \/\/ prevent warning, since this will always fail\n return nullptr;\n }\n\n auto it = m_backtraceStates.find(fileName);\n if (it != m_backtraceStates.end()) {\n return it->second;\n }\n\n struct CallbackData {\n const string* fileName;\n };\n CallbackData data = {&fileName};\n\n auto errorHandler = [] (void *rawData, const char *msg, int errnum) {\n auto data = reinterpret_cast(rawData);\n cerr << \"Failed to create backtrace state for module \" << *data->fileName << \": \"\n << msg << \" \/ \" << strerror(errnum) << \" (error code \" << errnum << \")\" << endl;\n };\n\n auto state = backtrace_create_state(fileName.c_str(), \/* we are single threaded, so: not thread safe *\/ false,\n errorHandler, &data);\n\n if (state) {\n const int descriptor = backtrace_open(fileName.c_str(), errorHandler, &data, nullptr);\n if (descriptor >= 1) {\n int foundSym = 0;\n int foundDwarf = 0;\n auto ret = elf_add(state, descriptor, addressStart, errorHandler, &data,\n &state->fileline_fn, &foundSym, &foundDwarf, isExe);\n if (ret && foundSym) {\n state->syminfo_fn = &elf_syminfo;\n }\n }\n }\n\n m_backtraceStates.insert(it, make_pair(fileName, state));\n\n return state;\n }\n\nprivate:\n vector m_modules;\n unordered_map m_backtraceStates;\n bool m_modulesDirty = false;\n\n unordered_map m_internedData;\n unordered_map m_encounteredIps;\n};\n\n}\n\nint main(int \/*argc*\/, char** \/*argv*\/)\n{\n \/\/ optimize: we only have a single thread\n ios_base::sync_with_stdio(false);\n\n AccumulatedTraceData data;\n\n LineReader reader;\n\n string exe;\n\n __fsetlocking(stdout, FSETLOCKING_BYCALLER);\n __fsetlocking(stdin, FSETLOCKING_BYCALLER);\n\n while (reader.getLine(cin)) {\n if (reader.mode() == 'x') {\n reader >> exe;\n } else if (reader.mode() == 'm') {\n string fileName;\n reader >> fileName;\n if (fileName == \"-\") {\n data.clearModules();\n } else {\n const bool isExe = (fileName == \"x\");\n if (isExe) {\n fileName = exe;\n }\n const auto moduleIndex = data.intern(fileName);\n uintptr_t addressStart = 0;\n if (!(reader >> addressStart)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n auto state = data.findBacktraceState(fileName, addressStart, isExe);\n uintptr_t vAddr = 0;\n uintptr_t memSize = 0;\n while ((reader >> vAddr) && (reader >> memSize)) {\n data.addModule(state, moduleIndex,\n addressStart + vAddr,\n addressStart + vAddr + memSize);\n }\n }\n } else if (reader.mode() == 't') {\n uintptr_t instructionPointer = 0;\n size_t parentIndex = 0;\n if (!(reader >> instructionPointer) || !(reader >> parentIndex)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n \/\/ ensure ip is encountered\n const auto ipId = data.addIp(instructionPointer);\n \/\/ trace point, map current output index to parent index\n fprintf(stdout, \"t %lx %lx\\n\", ipId, parentIndex);\n } else {\n fputs(reader.line().c_str(), stdout);\n fputc('\\n', stdout);\n }\n }\n\n return 0;\n}\nGroup disabling of stdio locking code.\/*\n * Copyright 2014 Milian Wolff \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU Library General Public License as\n * published by the Free Software Foundation; either version 2 of the\n * License, or (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public\n * License along with this program; if not, write to the\n * Free Software Foundation, Inc.,\n * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n *\/\n\n\/**\n * @file heaptrack_interpret.cpp\n *\n * @brief Interpret raw heaptrack data and add Dwarf based debug information.\n *\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n\n#include \"libbacktrace\/backtrace.h\"\n#include \"libbacktrace\/internal.h\"\n#include \"linereader.h\"\n\nusing namespace std;\n\nnamespace {\n\nstring demangle(const char* function)\n{\n if (!function) {\n return {};\n } else if (function[0] != '_' || function[1] != 'Z') {\n return {function};\n }\n\n string ret;\n int status = 0;\n char* demangled = abi::__cxa_demangle(function, 0, 0, &status);\n if (demangled) {\n ret = demangled;\n free(demangled);\n }\n return ret;\n}\n\nstruct AddressInformation\n{\n string function;\n string file;\n int line = 0;\n};\n\nstruct Module\n{\n Module(uintptr_t addressStart, uintptr_t addressEnd, backtrace_state* backtraceState, size_t moduleIndex)\n : addressStart(addressStart)\n , addressEnd(addressEnd)\n , moduleIndex(moduleIndex)\n , backtraceState(backtraceState)\n {\n }\n\n AddressInformation resolveAddress(uintptr_t address) const\n {\n AddressInformation info;\n if (!backtraceState) {\n return info;\n }\n\n backtrace_pcinfo(backtraceState, address,\n [] (void *data, uintptr_t \/*addr*\/, const char *file, int line, const char *function) -> int {\n auto info = reinterpret_cast(data);\n info->function = demangle(function);\n info->file = file ? file : \"\";\n info->line = line;\n return 0;\n }, [] (void *\/*data*\/, const char *\/*msg*\/, int \/*errnum*\/) {}, &info);\n\n if (info.function.empty()) {\n backtrace_syminfo(backtraceState, address,\n [] (void *data, uintptr_t \/*pc*\/, const char *symname, uintptr_t \/*symval*\/, uintptr_t \/*symsize*\/) {\n if (symname) {\n reinterpret_cast(data)->function = demangle(symname);\n }\n }, [] (void *\/*data*\/, const char *msg, int errnum) {\n cerr << \"Module backtrace error (code \" << errnum << \"): \" << msg << endl;\n }, &info);\n }\n\n return info;\n }\n\n bool operator<(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, moduleIndex)\n < make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);\n }\n\n bool operator!=(const Module& module) const\n {\n return make_tuple(addressStart, addressEnd, moduleIndex)\n != make_tuple(module.addressStart, module.addressEnd, module.moduleIndex);\n }\n\n uintptr_t addressStart;\n uintptr_t addressEnd;\n size_t moduleIndex;\n backtrace_state* backtraceState;\n};\n\nstruct Allocation\n{\n \/\/ backtrace entry point\n size_t ipIndex;\n \/\/ number of allocations\n size_t allocations;\n \/\/ amount of bytes leaked\n size_t leaked;\n};\n\n\/**\n * Information for a single call to an allocation function\n *\/\nstruct AllocationInfo\n{\n size_t ipIndex;\n size_t size;\n};\n\nstruct ResolvedIP\n{\n size_t moduleIndex = 0;\n size_t fileIndex = 0;\n size_t functionIndex = 0;\n int line = 0;\n};\n\nstruct AccumulatedTraceData\n{\n AccumulatedTraceData()\n {\n m_modules.reserve(256);\n m_backtraceStates.reserve(64);\n m_internedData.reserve(4096);\n m_encounteredIps.reserve(32768);\n }\n\n ~AccumulatedTraceData()\n {\n fprintf(stdout, \"# strings: %lu\\n# ips: %lu\\n\",\n m_internedData.size(), m_encounteredIps.size());\n }\n\n ResolvedIP resolve(const uintptr_t ip)\n {\n if (m_modulesDirty) {\n \/\/ sort by addresses, required for binary search below\n sort(m_modules.begin(), m_modules.end());\n\n for (size_t i = 0; i < m_modules.size(); ++i) {\n const auto& m1 = m_modules[i];\n for (size_t j = i + 1; j < m_modules.size(); ++j) {\n if (i == j) {\n continue;\n }\n const auto& m2 = m_modules[j];\n if ((m1.addressStart <= m2.addressStart && m1.addressEnd > m2.addressStart) ||\n (m1.addressStart < m2.addressEnd && m1.addressEnd >= m2.addressEnd))\n {\n cerr << \"OVERLAPPING MODULES: \" << hex\n << m1.moduleIndex << \" (\" << m1.addressStart << \" to \" << m1.addressEnd << \") and \"\n << m1.moduleIndex << \" (\" << m2.addressStart << \" to \" << m2.addressEnd << \")\\n\"\n << dec;\n } else if (m2.addressStart >= m1.addressEnd) {\n break;\n }\n }\n }\n\n m_modulesDirty = false;\n }\n\n ResolvedIP data;\n \/\/ find module for this instruction pointer\n auto module = lower_bound(m_modules.begin(), m_modules.end(), ip,\n [] (const Module& module, const uintptr_t ip) -> bool {\n return module.addressEnd < ip;\n });\n if (module != m_modules.end() && module->addressStart <= ip && module->addressEnd >= ip) {\n data.moduleIndex = module->moduleIndex;\n const auto info = module->resolveAddress(ip);\n data.fileIndex = intern(info.file);\n data.functionIndex = intern(info.function);\n data.line = info.line;\n }\n return data;\n }\n\n size_t intern(const string& str)\n {\n if (str.empty()) {\n return 0;\n }\n\n auto it = m_internedData.find(str);\n if (it != m_internedData.end()) {\n return it->second;\n }\n const size_t id = m_internedData.size() + 1;\n m_internedData.insert(it, make_pair(str, id));\n fprintf(stdout, \"s %s\\n\", str.c_str());\n return id;\n }\n\n void addModule(backtrace_state* backtraceState, const size_t moduleIndex,\n const uintptr_t addressStart, const uintptr_t addressEnd)\n {\n m_modules.emplace_back(addressStart, addressEnd, backtraceState, moduleIndex);\n m_modulesDirty = true;\n }\n\n void clearModules()\n {\n \/\/ TODO: optimize this, reuse modules that are still valid\n m_modules.clear();\n m_modulesDirty = true;\n }\n\n size_t addIp(const uintptr_t instructionPointer)\n {\n if (!instructionPointer) {\n return 0;\n }\n\n auto it = m_encounteredIps.find(instructionPointer);\n if (it != m_encounteredIps.end()) {\n return it->second;\n }\n\n const size_t ipId = m_encounteredIps.size() + 1;\n m_encounteredIps.insert(it, make_pair(instructionPointer, ipId));\n\n const auto ip = resolve(instructionPointer);\n fprintf(stdout, \"i %lx %lx\", instructionPointer, ip.moduleIndex);\n if (ip.functionIndex || ip.fileIndex) {\n fprintf(stdout, \" %lx\", ip.functionIndex);\n if (ip.fileIndex) {\n fprintf(stdout, \" %lx %x\", ip.fileIndex, ip.line);\n }\n }\n fputc('\\n', stdout);\n return ipId;\n }\n\n \/**\n * Prevent the same file from being initialized multiple times.\n * This drastically cuts the memory consumption down\n *\/\n backtrace_state* findBacktraceState(const string& fileName, uintptr_t addressStart, bool isExe)\n {\n if (boost::algorithm::starts_with(fileName, \"linux-vdso.so\")) {\n \/\/ prevent warning, since this will always fail\n return nullptr;\n }\n\n auto it = m_backtraceStates.find(fileName);\n if (it != m_backtraceStates.end()) {\n return it->second;\n }\n\n struct CallbackData {\n const string* fileName;\n };\n CallbackData data = {&fileName};\n\n auto errorHandler = [] (void *rawData, const char *msg, int errnum) {\n auto data = reinterpret_cast(rawData);\n cerr << \"Failed to create backtrace state for module \" << *data->fileName << \": \"\n << msg << \" \/ \" << strerror(errnum) << \" (error code \" << errnum << \")\" << endl;\n };\n\n auto state = backtrace_create_state(fileName.c_str(), \/* we are single threaded, so: not thread safe *\/ false,\n errorHandler, &data);\n\n if (state) {\n const int descriptor = backtrace_open(fileName.c_str(), errorHandler, &data, nullptr);\n if (descriptor >= 1) {\n int foundSym = 0;\n int foundDwarf = 0;\n auto ret = elf_add(state, descriptor, addressStart, errorHandler, &data,\n &state->fileline_fn, &foundSym, &foundDwarf, isExe);\n if (ret && foundSym) {\n state->syminfo_fn = &elf_syminfo;\n }\n }\n }\n\n m_backtraceStates.insert(it, make_pair(fileName, state));\n\n return state;\n }\n\nprivate:\n vector m_modules;\n unordered_map m_backtraceStates;\n bool m_modulesDirty = false;\n\n unordered_map m_internedData;\n unordered_map m_encounteredIps;\n};\n\n}\n\nint main(int \/*argc*\/, char** \/*argv*\/)\n{\n \/\/ optimize: we only have a single thread\n ios_base::sync_with_stdio(false);\n __fsetlocking(stdout, FSETLOCKING_BYCALLER);\n __fsetlocking(stdin, FSETLOCKING_BYCALLER);\n\n AccumulatedTraceData data;\n\n LineReader reader;\n\n string exe;\n\n while (reader.getLine(cin)) {\n if (reader.mode() == 'x') {\n reader >> exe;\n } else if (reader.mode() == 'm') {\n string fileName;\n reader >> fileName;\n if (fileName == \"-\") {\n data.clearModules();\n } else {\n const bool isExe = (fileName == \"x\");\n if (isExe) {\n fileName = exe;\n }\n const auto moduleIndex = data.intern(fileName);\n uintptr_t addressStart = 0;\n if (!(reader >> addressStart)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n auto state = data.findBacktraceState(fileName, addressStart, isExe);\n uintptr_t vAddr = 0;\n uintptr_t memSize = 0;\n while ((reader >> vAddr) && (reader >> memSize)) {\n data.addModule(state, moduleIndex,\n addressStart + vAddr,\n addressStart + vAddr + memSize);\n }\n }\n } else if (reader.mode() == 't') {\n uintptr_t instructionPointer = 0;\n size_t parentIndex = 0;\n if (!(reader >> instructionPointer) || !(reader >> parentIndex)) {\n cerr << \"failed to parse line: \" << reader.line() << endl;\n return 1;\n }\n \/\/ ensure ip is encountered\n const auto ipId = data.addIp(instructionPointer);\n \/\/ trace point, map current output index to parent index\n fprintf(stdout, \"t %lx %lx\\n\", ipId, parentIndex);\n } else {\n fputs(reader.line().c_str(), stdout);\n fputc('\\n', stdout);\n }\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \n#include \n#include \n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\n\n\nvoid test_mapping_1()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number_2\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number_to_keep\", CT_SCALAR, ST_NONE, PT_INT32, 0)\n\t);\n\n\t\/* finalizing the map is needed before accessing it *\/\n\tmap->finalize_map();\n\n\tmap->print_map();\n\tSG_SPRINT(\"\\n\");\n\n\n\t\/* get some elements from map, one\/two ARE in map, three and four are NOT *\/\n\tDynArray dummies;\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\t\tPT_INT32, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 0));\n\tdummies.append_element(new SGParamInfo(\"number_2\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\n\tfor (index_t i=0; ito_string();\n\t\tSG_SPRINT(\"searching for: %s\\n\", s);\n\t\tSG_FREE(s);\n\n\t\tconst SGParamInfo* result=map->get(current);\n\t\tif (result)\n\t\t{\n\t\t\ts=result->to_string();\n\t\t\tSG_SPRINT(\"found: %s\\n\\n\", s);\n\t\t\tSG_FREE(s);\n\t\t}\n\t\telse\n\t\t\tSG_SPRINT(\"nothing found\\n\\n\");\n\n\t\tdelete current;\n\t}\n\n\tdelete map;\n}\n\nvoid print_value(const SGParamInfo* key, ParameterMap* map)\n{\n\tconst SGParamInfo* current=map->get(key);\n\tkey->print_param_info();\n\tSG_SPRINT(\"value: \");\n\n\tif (current)\n\t\tcurrent->print_param_info();\n\telse\n\t\tSG_SPRINT(\"no element\\n\");\n\n\tSG_SPRINT(\"\\n\");\n}\n\nvoid test_mapping_2()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"eins\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"zwei\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"3\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"drei\", cto, sto, pto, 3));\n\tmap->put(new SGParamInfo(\"4\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"vier\", cto, sto, pto, 3));\n\n\tSG_SPRINT(\"before finalization:\\n\");\n\tmap->print_map();\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"\\n\\nafter finalization:\\n\");\n\tmap->print_map();\n\n\tconst SGParamInfo* key;\n\n\tSG_SPRINT(\"\\n\\ntesting map\\n\");\n\tkey=new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 1);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cto, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sto, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pto, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"5\", cfrom, sfrom, pfrom, 4);\n\tprint_value(key, map);\n\tdelete key;\n\n\tdelete map;\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\ttest_mapping_1();\n\ttest_mapping_2();\n\n\texit_shogun();\n\n\treturn 0;\n}\n\nadapted for new mutli-value per key parameter map and added testcase\/*\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 3 of the License, or\n * (at your option) any later version.\n *\n * Written (W) 2011 Heiko Strathmann\n * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society\n *\/\n\n#include \n#include \n#include \n\nusing namespace shogun;\n\nvoid print_message(FILE* target, const char* str)\n{\n\tfprintf(target, \"%s\", str);\n}\n\n\n\nvoid test_mapping_1()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number\", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)\n\t);\n\n\tmap->put(\n\t\t\tnew SGParamInfo(\"number_2\", CT_SCALAR, ST_NONE, PT_INT32, 1),\n\t\t\tnew SGParamInfo(\"number_to_keep\", CT_SCALAR, ST_NONE, PT_INT32, 0)\n\t);\n\n\t\/* finalizing the map is needed before accessing it *\/\n\tSG_SPRINT(\"\\n\\before finalization:\\n\");\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"\\n\\nafter finalization:\\n\");\n\tmap->print_map();\n\tSG_SPRINT(\"\\n\");\n\n\n\t\/* get some elements from map, one\/two ARE in map, three and four are NOT *\/\n\tDynArray dummies;\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\t\tPT_INT32, 2));\n\tdummies.append_element(new SGParamInfo(\"number\", CT_SCALAR, ST_NONE,\n\t\t\tPT_FLOAT64, 0));\n\tdummies.append_element(new SGParamInfo(\"number_2\", CT_SCALAR, ST_NONE,\n\t\t\tPT_INT32, 1));\n\n\tfor (index_t i=0; ito_string();\n\t\tSG_SPRINT(\"searching for: %s\\n\", s);\n\t\tSG_FREE(s);\n\n\t\tDynArray* result=map->get(current, 0);\n\t\tif (result)\n\t\t{\n\t\t\tfor (index_t i=0; iget_num_elements(); ++i)\n\t\t\t{\n\t\t\t\ts=result->get_element(i)->to_string();\n\t\t\t\tSG_SPRINT(\"found: %s\\n\\n\", s);\n\t\t\t\tSG_FREE(s);\n\t\t\t}\n\t\t}\n\t\telse\n\t\t\tSG_SPRINT(\"nothing found\\n\\n\");\n\n\t\tdelete current;\n\t}\n\n\tdelete map;\n}\n\nvoid print_value(const SGParamInfo* key, ParameterMap* map)\n{\n\tDynArray* current=map->get(key, 0);\n\tkey->print_param_info();\n\tSG_SPRINT(\"value: \");\n\n\tif (current)\n\t{\n\t\tfor (index_t i=0; iget_num_elements(); ++i)\n\t\t\tcurrent->get_element(i)->print_param_info(\"\\t\");\n\t}\n\telse\n\t\tSG_SPRINT(\"no elements\\n\");\n\n\tSG_SPRINT(\"\\n\");\n}\n\nvoid test_mapping_2()\n{\n\tParameterMap* map=new ParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"eins\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"zwei\", cto, sto, pto, 1));\n\tmap->put(new SGParamInfo(\"3\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"drei\", cto, sto, pto, 3));\n\tmap->put(new SGParamInfo(\"4\", cfrom, sfrom, pfrom, 4),\n\t\t\tnew SGParamInfo(\"vier\", cto, sto, pto, 3));\n\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"\\n\\nafter finalization:\\n\");\n\tmap->print_map();\n\n\tconst SGParamInfo* key;\n\n\tSG_SPRINT(\"\\n\\ntesting map\\n\");\n\tkey=new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 1);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cto, sfrom, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sto, pfrom, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"2\", cfrom, sfrom, pto, 2);\n\tprint_value(key, map);\n\tdelete key;\n\n\tkey=new SGParamInfo(\"5\", cfrom, sfrom, pfrom, 4);\n\tprint_value(key, map);\n\tdelete key;\n\n\tdelete map;\n}\n\nvoid test_mapping_0()\n{\n\t\/* test multiple values per key *\/\n\tParameterMap* map=new ParameterMap();\n\n\tEContainerType cfrom=CT_SCALAR;\n\tEContainerType cto=CT_MATRIX;\n\n\tEStructType sfrom=ST_NONE;\n\tEStructType sto=ST_STRING;\n\n\tEPrimitiveType pfrom=PT_BOOL;\n\tEPrimitiveType pto=PT_SGOBJECT;\n\n\t\/* 3 equal keys *\/\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"eins a\", cto, sto, pto, 1));\n\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"eins b\", cto, sto, pto, 1));\n\n\tmap->put(new SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"eins c\", cto, sto, pto, 1));\n\n\t\/* 2 equal keys *\/\n\tmap->put(new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"zwei a\", cto, sto, pto, 1));\n\n\tmap->put(new SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2),\n\t\t\tnew SGParamInfo(\"zwei b\", cto, sto, pto, 1));\n\n\tmap->finalize_map();\n\n\tSG_SPRINT(\"printing finalized map\\n\");\n\tmap->print_map();\n\n\t\/* assert that all is there *\/\n\tDynArray* result;\n\tbool found;\n\n\t\/* key 0 *\/\n\tresult=map->get(SGParamInfo(\"1\", cfrom, sfrom, pfrom, 2));\n\tASSERT(result);\n\n\t\/* first value element *\/\n\tfound=false;\n\tfor (index_t i=0; iget_num_elements(); ++i)\n\t{\n\t\tif (*result->get_element(i) == SGParamInfo(\"eins a\", cto, sto, pto, 1))\n\t\t\tfound=true;\n\t}\n\tASSERT(found);\n\n\t\/* second value element *\/\n\tfound=false;\n\tfor (index_t i=0; iget_num_elements(); ++i)\n\t{\n\t\tif (*result->get_element(i) == SGParamInfo(\"eins b\", cto, sto, pto, 1))\n\t\t\tfound=true;\n\t}\n\tASSERT(found);\n\n\t\/* third value element *\/\n\tfound=false;\n\tfor (index_t i=0; iget_num_elements(); ++i)\n\t{\n\t\tif (*result->get_element(i) == SGParamInfo(\"eins c\", cto, sto, pto, 1))\n\t\t\tfound=true;\n\t}\n\tASSERT(found);\n\n\t\/* key 1 *\/\n\tresult=map->get(SGParamInfo(\"2\", cfrom, sfrom, pfrom, 2));\n\tASSERT(result);\n\n\t\/* first value element *\/\n\tfound=false;\n\tfor (index_t i=0; iget_num_elements(); ++i)\n\t{\n\t\tif (*result->get_element(i) == SGParamInfo(\"zwei a\", cto, sto, pto, 1))\n\t\t\tfound=true;\n\t}\n\tASSERT(found);\n\n\t\/* second value element *\/\n\tfound=false;\n\tfor (index_t i=0; iget_num_elements(); ++i)\n\t{\n\t\tif (*result->get_element(i) == SGParamInfo(\"zwei b\", cto, sto, pto, 1))\n\t\t\tfound=true;\n\t}\n\tASSERT(found);\n\n\tdelete map;\n}\n\nint main(int argc, char **argv)\n{\n\tinit_shogun(&print_message, &print_message, &print_message);\n\n\ttest_mapping_0();\n\ttest_mapping_1();\n\ttest_mapping_2();\n\n\texit_shogun();\n\n\treturn 0;\n}\n\n<|endoftext|>"} {"text":"\/\/===-- Local.cpp - Functions to perform local transformations ------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This family of functions perform various local transformations to the\n\/\/ program.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local constant propagation...\n\/\/\n\n\/\/\/ doConstantPropagation - If an instruction references constants, try to fold\n\/\/\/ them together...\n\/\/\/\nbool llvm::doConstantPropagation(BasicBlock::iterator &II) {\n if (Constant *C = ConstantFoldInstruction(II)) {\n \/\/ Replaces all of the uses of a variable with uses of the constant.\n II->replaceAllUsesWith(C);\n \n \/\/ Remove the instruction from the basic block...\n II = II->getParent()->getInstList().erase(II);\n return true;\n }\n\n return false;\n}\n\n\/\/\/ ConstantFoldInstruction - Attempt to constant fold the specified\n\/\/\/ instruction. If successful, the constant result is returned, if not, null\n\/\/\/ is returned. Note that this function can only fail when attempting to fold\n\/\/\/ instructions like loads and stores, which have no constant expression form.\n\/\/\/\nConstant *llvm::ConstantFoldInstruction(Instruction *I) {\n if (PHINode *PN = dyn_cast(I)) {\n if (PN->getNumIncomingValues() == 0)\n return Constant::getNullValue(PN->getType());\n \n Constant *Result = dyn_cast(PN->getIncomingValue(0));\n if (Result == 0) return 0;\n\n \/\/ Handle PHI nodes specially here...\n for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)\n if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)\n return 0; \/\/ Not all the same incoming constants...\n \n \/\/ If we reach here, all incoming values are the same constant.\n return Result;\n } else if (CallInst *CI = dyn_cast(I)) {\n if (Function *F = CI->getCalledFunction())\n if (canConstantFoldCallTo(F)) {\n std::vector Args;\n for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)\n if (Constant *Op = dyn_cast(CI->getOperand(i)))\n Args.push_back(Op);\n else\n return 0;\n return ConstantFoldCall(F, Args);\n }\n return 0;\n }\n\n Constant *Op0 = 0, *Op1 = 0;\n switch (I->getNumOperands()) {\n default:\n case 2:\n Op1 = dyn_cast(I->getOperand(1));\n if (Op1 == 0) return 0; \/\/ Not a constant?, can't fold\n case 1:\n Op0 = dyn_cast(I->getOperand(0));\n if (Op0 == 0) return 0; \/\/ Not a constant?, can't fold\n break;\n case 0: return 0;\n }\n\n if (isa(I) || isa(I))\n return ConstantExpr::get(I->getOpcode(), Op0, Op1); \n\n switch (I->getOpcode()) {\n default: return 0;\n case Instruction::Cast:\n return ConstantExpr::getCast(Op0, I->getType());\n case Instruction::Select:\n if (Constant *Op2 = dyn_cast(I->getOperand(2)))\n return ConstantExpr::getSelect(Op0, Op1, Op2);\n return 0;\n case Instruction::GetElementPtr:\n std::vector IdxList;\n IdxList.reserve(I->getNumOperands()-1);\n if (Op1) IdxList.push_back(Op1);\n for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)\n if (Constant *C = dyn_cast(I->getOperand(i)))\n IdxList.push_back(C);\n else\n return 0; \/\/ Non-constant operand\n return ConstantExpr::getGetElementPtr(Op0, IdxList);\n }\n}\n\n\/\/ ConstantFoldTerminator - If a terminator instruction is predicated on a\n\/\/ constant value, convert it into an unconditional branch to the constant\n\/\/ destination.\n\/\/\nbool llvm::ConstantFoldTerminator(BasicBlock *BB) {\n TerminatorInst *T = BB->getTerminator();\n \n \/\/ Branch - See if we are conditional jumping on constant\n if (BranchInst *BI = dyn_cast(T)) {\n if (BI->isUnconditional()) return false; \/\/ Can't optimize uncond branch\n BasicBlock *Dest1 = cast(BI->getOperand(0));\n BasicBlock *Dest2 = cast(BI->getOperand(1));\n\n if (ConstantBool *Cond = dyn_cast(BI->getCondition())) {\n \/\/ Are we branching on constant?\n \/\/ YES. Change to unconditional branch...\n BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;\n BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;\n\n \/\/cerr << \"Function: \" << T->getParent()->getParent() \n \/\/ << \"\\nRemoving branch from \" << T->getParent() \n \/\/ << \"\\n\\nTo: \" << OldDest << endl;\n\n \/\/ Let the basic block know that we are letting go of it. Based on this,\n \/\/ it will adjust it's PHI nodes.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n OldDest->removePredecessor(BI->getParent());\n\n \/\/ Set the unconditional destination, and change the insn to be an\n \/\/ unconditional branch.\n BI->setUnconditionalDest(Destination);\n return true;\n } else if (Dest2 == Dest1) { \/\/ Conditional branch to same location?\n \/\/ This branch matches something like this: \n \/\/ br bool %cond, label %Dest, label %Dest\n \/\/ and changes it into: br label %Dest\n\n \/\/ Let the basic block know that we are letting go of one copy of it.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n Dest1->removePredecessor(BI->getParent());\n\n \/\/ Change a conditional branch to unconditional.\n BI->setUnconditionalDest(Dest1);\n return true;\n }\n } else if (SwitchInst *SI = dyn_cast(T)) {\n \/\/ If we are switching on a constant, we can convert the switch into a\n \/\/ single branch instruction!\n ConstantInt *CI = dyn_cast(SI->getCondition());\n BasicBlock *TheOnlyDest = SI->getSuccessor(0); \/\/ The default dest\n BasicBlock *DefaultDest = TheOnlyDest;\n assert(TheOnlyDest == SI->getDefaultDest() &&\n \"Default destination is not successor #0?\");\n\n \/\/ Figure out which case it goes to...\n for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n if (SI->getSuccessorValue(i) == CI) {\n TheOnlyDest = SI->getSuccessor(i);\n break;\n }\n\n \/\/ Check to see if this branch is going to the same place as the default\n \/\/ dest. If so, eliminate it as an explicit compare.\n if (SI->getSuccessor(i) == DefaultDest) {\n \/\/ Remove this entry...\n DefaultDest->removePredecessor(SI->getParent());\n SI->removeCase(i);\n --i; --e; \/\/ Don't skip an entry...\n continue;\n }\n\n \/\/ Otherwise, check to see if the switch only branches to one destination.\n \/\/ We do this by reseting \"TheOnlyDest\" to null when we find two non-equal\n \/\/ destinations.\n if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;\n }\n\n if (CI && !TheOnlyDest) {\n \/\/ Branching on a constant, but not any of the cases, go to the default\n \/\/ successor.\n TheOnlyDest = SI->getDefaultDest();\n }\n\n \/\/ If we found a single destination that we can fold the switch into, do so\n \/\/ now.\n if (TheOnlyDest) {\n \/\/ Insert the new branch..\n new BranchInst(TheOnlyDest, SI);\n BasicBlock *BB = SI->getParent();\n\n \/\/ Remove entries from PHI nodes which we no longer branch to...\n for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n BasicBlock *Succ = SI->getSuccessor(i);\n if (Succ == TheOnlyDest)\n TheOnlyDest = 0; \/\/ Don't modify the first branch to TheOnlyDest\n else\n Succ->removePredecessor(BB);\n }\n\n \/\/ Delete the old switch...\n BB->getInstList().erase(SI);\n return true;\n } else if (SI->getNumSuccessors() == 2) {\n \/\/ Otherwise, we can fold this switch into a conditional branch\n \/\/ instruction if it has only one non-default destination.\n Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),\n SI->getSuccessorValue(1), \"cond\", SI);\n \/\/ Insert the new branch...\n new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);\n\n \/\/ Delete the old switch...\n SI->getParent()->getInstList().erase(SI);\n return true;\n }\n }\n return false;\n}\n\n\/\/\/ canConstantFoldCallTo - Return true if its even possible to fold a call to\n\/\/\/ the specified function.\nbool llvm::canConstantFoldCallTo(Function *F) {\n const std::string &Name = F->getName();\n\n switch (F->getIntrinsicID()) {\n case Intrinsic::isnan: return true;\n default: break;\n }\n\n return Name == \"sin\" || Name == \"cos\" || Name == \"tan\" || Name == \"sqrt\" ||\n Name == \"log\" || Name == \"log10\" || Name == \"exp\" || Name == \"pow\" ||\n Name == \"acos\" || Name == \"asin\" || Name == \"atan\" || Name == \"fmod\";\n}\n\nstatic Constant *ConstantFoldFP(double (*NativeFP)(double), double V,\n const Type *Ty) {\n errno = 0;\n V = NativeFP(V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n return 0;\n}\n\n\/\/\/ ConstantFoldCall - Attempt to constant fold a call to the specified function\n\/\/\/ with the specified arguments, returning null if unsuccessful.\nConstant *llvm::ConstantFoldCall(Function *F,\n const std::vector &Operands) {\n const std::string &Name = F->getName();\n const Type *Ty = F->getReturnType();\n\n if (Operands.size() == 1) {\n if (ConstantFP *Op = dyn_cast(Operands[0])) {\n double V = Op->getValue();\n if (Name == \"llvm.isnan\")\n return ConstantBool::get(isnan(V));\n else if (Name == \"sin\")\n return ConstantFP::get(Ty, sin(V));\n else if (Name == \"cos\")\n return ConstantFP::get(Ty, cos(V));\n else if (Name == \"tan\")\n return ConstantFP::get(Ty, tan(V));\n else if (Name == \"sqrt\" && V >= 0)\n return ConstantFP::get(Ty, sqrt(V));\n else if (Name == \"exp\")\n return ConstantFP::get(Ty, exp(V));\n else if (Name == \"log\" && V > 0)\n return ConstantFP::get(Ty, log(V));\n else if (Name == \"log10\")\n return ConstantFoldFP(log10, V, Ty);\n else if (Name == \"acos\")\n return ConstantFoldFP(acos, V, Ty);\n else if (Name == \"asin\")\n return ConstantFoldFP(asin, V, Ty);\n else if (Name == \"atan\")\n return ConstantFP::get(Ty, atan(V));\n }\n } else if (Operands.size() == 2) {\n if (ConstantFP *Op1 = dyn_cast(Operands[0]))\n if (ConstantFP *Op2 = dyn_cast(Operands[1])) {\n double Op1V = Op1->getValue(), Op2V = Op2->getValue();\n\n if (Name == \"pow\") {\n errno = 0;\n double V = pow(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n } else if (Name == \"fmod\") {\n errno = 0;\n double V = fmod(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n }\n }\n }\n return 0;\n}\n\n\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local dead code elimination...\n\/\/\n\nbool llvm::isInstructionTriviallyDead(Instruction *I) {\n return I->use_empty() && !I->mayWriteToMemory() && !isa(I);\n}\n\n\/\/ dceInstruction - Inspect the instruction at *BBI and figure out if it's\n\/\/ [trivially] dead. If so, remove the instruction and update the iterator\n\/\/ to point to the instruction that immediately succeeded the original\n\/\/ instruction.\n\/\/\nbool llvm::dceInstruction(BasicBlock::iterator &BBI) {\n \/\/ Look for un\"used\" definitions...\n if (isInstructionTriviallyDead(BBI)) {\n BBI = BBI->getParent()->getInstList().erase(BBI); \/\/ Bye bye\n return true;\n }\n return false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PHI Instruction Simplification\n\/\/\n\n\/\/\/ hasConstantValue - If the specified PHI node always merges together the same\n\/\/\/ value, return the value, otherwise return null.\n\/\/\/\nValue *llvm::hasConstantValue(PHINode *PN) {\n \/\/ If the PHI node only has one incoming value, eliminate the PHI node...\n if (PN->getNumIncomingValues() == 1)\n return PN->getIncomingValue(0);\n\n \/\/ Otherwise if all of the incoming values are the same for the PHI, replace\n \/\/ the PHI node with the incoming value.\n \/\/\n Value *InVal = 0;\n for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)\n if (PN->getIncomingValue(i) != PN) \/\/ Not the PHI node itself...\n if (InVal && PN->getIncomingValue(i) != InVal)\n return 0; \/\/ Not the same, bail out.\n else\n InVal = PN->getIncomingValue(i);\n\n \/\/ The only case that could cause InVal to be null is if we have a PHI node\n \/\/ that only has entries for itself. In this case, there is no entry into the\n \/\/ loop, so kill the PHI.\n \/\/\n if (InVal == 0) InVal = Constant::getNullValue(PN->getType());\n\n \/\/ All of the incoming values are the same, return the value now.\n return InVal;\n}\nAdd constant folding capabilities to the isunordered intrinsic.\/\/===-- Local.cpp - Functions to perform local transformations ------------===\/\/\n\/\/ \n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/ \n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This family of functions perform various local transformations to the\n\/\/ program.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local constant propagation...\n\/\/\n\n\/\/\/ doConstantPropagation - If an instruction references constants, try to fold\n\/\/\/ them together...\n\/\/\/\nbool llvm::doConstantPropagation(BasicBlock::iterator &II) {\n if (Constant *C = ConstantFoldInstruction(II)) {\n \/\/ Replaces all of the uses of a variable with uses of the constant.\n II->replaceAllUsesWith(C);\n \n \/\/ Remove the instruction from the basic block...\n II = II->getParent()->getInstList().erase(II);\n return true;\n }\n\n return false;\n}\n\n\/\/\/ ConstantFoldInstruction - Attempt to constant fold the specified\n\/\/\/ instruction. If successful, the constant result is returned, if not, null\n\/\/\/ is returned. Note that this function can only fail when attempting to fold\n\/\/\/ instructions like loads and stores, which have no constant expression form.\n\/\/\/\nConstant *llvm::ConstantFoldInstruction(Instruction *I) {\n if (PHINode *PN = dyn_cast(I)) {\n if (PN->getNumIncomingValues() == 0)\n return Constant::getNullValue(PN->getType());\n \n Constant *Result = dyn_cast(PN->getIncomingValue(0));\n if (Result == 0) return 0;\n\n \/\/ Handle PHI nodes specially here...\n for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)\n if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)\n return 0; \/\/ Not all the same incoming constants...\n \n \/\/ If we reach here, all incoming values are the same constant.\n return Result;\n } else if (CallInst *CI = dyn_cast(I)) {\n if (Function *F = CI->getCalledFunction())\n if (canConstantFoldCallTo(F)) {\n std::vector Args;\n for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)\n if (Constant *Op = dyn_cast(CI->getOperand(i)))\n Args.push_back(Op);\n else\n return 0;\n return ConstantFoldCall(F, Args);\n }\n return 0;\n }\n\n Constant *Op0 = 0, *Op1 = 0;\n switch (I->getNumOperands()) {\n default:\n case 2:\n Op1 = dyn_cast(I->getOperand(1));\n if (Op1 == 0) return 0; \/\/ Not a constant?, can't fold\n case 1:\n Op0 = dyn_cast(I->getOperand(0));\n if (Op0 == 0) return 0; \/\/ Not a constant?, can't fold\n break;\n case 0: return 0;\n }\n\n if (isa(I) || isa(I))\n return ConstantExpr::get(I->getOpcode(), Op0, Op1); \n\n switch (I->getOpcode()) {\n default: return 0;\n case Instruction::Cast:\n return ConstantExpr::getCast(Op0, I->getType());\n case Instruction::Select:\n if (Constant *Op2 = dyn_cast(I->getOperand(2)))\n return ConstantExpr::getSelect(Op0, Op1, Op2);\n return 0;\n case Instruction::GetElementPtr:\n std::vector IdxList;\n IdxList.reserve(I->getNumOperands()-1);\n if (Op1) IdxList.push_back(Op1);\n for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)\n if (Constant *C = dyn_cast(I->getOperand(i)))\n IdxList.push_back(C);\n else\n return 0; \/\/ Non-constant operand\n return ConstantExpr::getGetElementPtr(Op0, IdxList);\n }\n}\n\n\/\/ ConstantFoldTerminator - If a terminator instruction is predicated on a\n\/\/ constant value, convert it into an unconditional branch to the constant\n\/\/ destination.\n\/\/\nbool llvm::ConstantFoldTerminator(BasicBlock *BB) {\n TerminatorInst *T = BB->getTerminator();\n \n \/\/ Branch - See if we are conditional jumping on constant\n if (BranchInst *BI = dyn_cast(T)) {\n if (BI->isUnconditional()) return false; \/\/ Can't optimize uncond branch\n BasicBlock *Dest1 = cast(BI->getOperand(0));\n BasicBlock *Dest2 = cast(BI->getOperand(1));\n\n if (ConstantBool *Cond = dyn_cast(BI->getCondition())) {\n \/\/ Are we branching on constant?\n \/\/ YES. Change to unconditional branch...\n BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;\n BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;\n\n \/\/cerr << \"Function: \" << T->getParent()->getParent() \n \/\/ << \"\\nRemoving branch from \" << T->getParent() \n \/\/ << \"\\n\\nTo: \" << OldDest << endl;\n\n \/\/ Let the basic block know that we are letting go of it. Based on this,\n \/\/ it will adjust it's PHI nodes.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n OldDest->removePredecessor(BI->getParent());\n\n \/\/ Set the unconditional destination, and change the insn to be an\n \/\/ unconditional branch.\n BI->setUnconditionalDest(Destination);\n return true;\n } else if (Dest2 == Dest1) { \/\/ Conditional branch to same location?\n \/\/ This branch matches something like this: \n \/\/ br bool %cond, label %Dest, label %Dest\n \/\/ and changes it into: br label %Dest\n\n \/\/ Let the basic block know that we are letting go of one copy of it.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n Dest1->removePredecessor(BI->getParent());\n\n \/\/ Change a conditional branch to unconditional.\n BI->setUnconditionalDest(Dest1);\n return true;\n }\n } else if (SwitchInst *SI = dyn_cast(T)) {\n \/\/ If we are switching on a constant, we can convert the switch into a\n \/\/ single branch instruction!\n ConstantInt *CI = dyn_cast(SI->getCondition());\n BasicBlock *TheOnlyDest = SI->getSuccessor(0); \/\/ The default dest\n BasicBlock *DefaultDest = TheOnlyDest;\n assert(TheOnlyDest == SI->getDefaultDest() &&\n \"Default destination is not successor #0?\");\n\n \/\/ Figure out which case it goes to...\n for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n if (SI->getSuccessorValue(i) == CI) {\n TheOnlyDest = SI->getSuccessor(i);\n break;\n }\n\n \/\/ Check to see if this branch is going to the same place as the default\n \/\/ dest. If so, eliminate it as an explicit compare.\n if (SI->getSuccessor(i) == DefaultDest) {\n \/\/ Remove this entry...\n DefaultDest->removePredecessor(SI->getParent());\n SI->removeCase(i);\n --i; --e; \/\/ Don't skip an entry...\n continue;\n }\n\n \/\/ Otherwise, check to see if the switch only branches to one destination.\n \/\/ We do this by reseting \"TheOnlyDest\" to null when we find two non-equal\n \/\/ destinations.\n if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;\n }\n\n if (CI && !TheOnlyDest) {\n \/\/ Branching on a constant, but not any of the cases, go to the default\n \/\/ successor.\n TheOnlyDest = SI->getDefaultDest();\n }\n\n \/\/ If we found a single destination that we can fold the switch into, do so\n \/\/ now.\n if (TheOnlyDest) {\n \/\/ Insert the new branch..\n new BranchInst(TheOnlyDest, SI);\n BasicBlock *BB = SI->getParent();\n\n \/\/ Remove entries from PHI nodes which we no longer branch to...\n for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n BasicBlock *Succ = SI->getSuccessor(i);\n if (Succ == TheOnlyDest)\n TheOnlyDest = 0; \/\/ Don't modify the first branch to TheOnlyDest\n else\n Succ->removePredecessor(BB);\n }\n\n \/\/ Delete the old switch...\n BB->getInstList().erase(SI);\n return true;\n } else if (SI->getNumSuccessors() == 2) {\n \/\/ Otherwise, we can fold this switch into a conditional branch\n \/\/ instruction if it has only one non-default destination.\n Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),\n SI->getSuccessorValue(1), \"cond\", SI);\n \/\/ Insert the new branch...\n new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);\n\n \/\/ Delete the old switch...\n SI->getParent()->getInstList().erase(SI);\n return true;\n }\n }\n return false;\n}\n\n\/\/\/ canConstantFoldCallTo - Return true if its even possible to fold a call to\n\/\/\/ the specified function.\nbool llvm::canConstantFoldCallTo(Function *F) {\n const std::string &Name = F->getName();\n\n switch (F->getIntrinsicID()) {\n case Intrinsic::isnan: return true;\n case Intrinsic::isunordered: return true;\n default: break;\n }\n\n return Name == \"sin\" || Name == \"cos\" || Name == \"tan\" || Name == \"sqrt\" ||\n Name == \"log\" || Name == \"log10\" || Name == \"exp\" || Name == \"pow\" ||\n Name == \"acos\" || Name == \"asin\" || Name == \"atan\" || Name == \"fmod\";\n}\n\nstatic Constant *ConstantFoldFP(double (*NativeFP)(double), double V,\n const Type *Ty) {\n errno = 0;\n V = NativeFP(V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n return 0;\n}\n\n\/\/\/ ConstantFoldCall - Attempt to constant fold a call to the specified function\n\/\/\/ with the specified arguments, returning null if unsuccessful.\nConstant *llvm::ConstantFoldCall(Function *F,\n const std::vector &Operands) {\n const std::string &Name = F->getName();\n const Type *Ty = F->getReturnType();\n\n if (Operands.size() == 1) {\n if (ConstantFP *Op = dyn_cast(Operands[0])) {\n double V = Op->getValue();\n if (Name == \"llvm.isnan\")\n return ConstantBool::get(isnan(V));\n else if (Name == \"sin\")\n return ConstantFP::get(Ty, sin(V));\n else if (Name == \"cos\")\n return ConstantFP::get(Ty, cos(V));\n else if (Name == \"tan\")\n return ConstantFP::get(Ty, tan(V));\n else if (Name == \"sqrt\" && V >= 0)\n return ConstantFP::get(Ty, sqrt(V));\n else if (Name == \"exp\")\n return ConstantFP::get(Ty, exp(V));\n else if (Name == \"log\" && V > 0)\n return ConstantFP::get(Ty, log(V));\n else if (Name == \"log10\")\n return ConstantFoldFP(log10, V, Ty);\n else if (Name == \"acos\")\n return ConstantFoldFP(acos, V, Ty);\n else if (Name == \"asin\")\n return ConstantFoldFP(asin, V, Ty);\n else if (Name == \"atan\")\n return ConstantFP::get(Ty, atan(V));\n }\n } else if (Operands.size() == 2) {\n if (ConstantFP *Op1 = dyn_cast(Operands[0]))\n if (ConstantFP *Op2 = dyn_cast(Operands[1])) {\n double Op1V = Op1->getValue(), Op2V = Op2->getValue();\n\n if (Name == \"llvm.isunordered\")\n return ConstantBool::get(isnan(Op1V) | isnan(Op2V));\n else if (Name == \"pow\") {\n errno = 0;\n double V = pow(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n } else if (Name == \"fmod\") {\n errno = 0;\n double V = fmod(Op1V, Op2V);\n if (errno == 0)\n return ConstantFP::get(Ty, V);\n }\n }\n }\n return 0;\n}\n\n\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local dead code elimination...\n\/\/\n\nbool llvm::isInstructionTriviallyDead(Instruction *I) {\n return I->use_empty() && !I->mayWriteToMemory() && !isa(I);\n}\n\n\/\/ dceInstruction - Inspect the instruction at *BBI and figure out if it's\n\/\/ [trivially] dead. If so, remove the instruction and update the iterator\n\/\/ to point to the instruction that immediately succeeded the original\n\/\/ instruction.\n\/\/\nbool llvm::dceInstruction(BasicBlock::iterator &BBI) {\n \/\/ Look for un\"used\" definitions...\n if (isInstructionTriviallyDead(BBI)) {\n BBI = BBI->getParent()->getInstList().erase(BBI); \/\/ Bye bye\n return true;\n }\n return false;\n}\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ PHI Instruction Simplification\n\/\/\n\n\/\/\/ hasConstantValue - If the specified PHI node always merges together the same\n\/\/\/ value, return the value, otherwise return null.\n\/\/\/\nValue *llvm::hasConstantValue(PHINode *PN) {\n \/\/ If the PHI node only has one incoming value, eliminate the PHI node...\n if (PN->getNumIncomingValues() == 1)\n return PN->getIncomingValue(0);\n\n \/\/ Otherwise if all of the incoming values are the same for the PHI, replace\n \/\/ the PHI node with the incoming value.\n \/\/\n Value *InVal = 0;\n for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)\n if (PN->getIncomingValue(i) != PN) \/\/ Not the PHI node itself...\n if (InVal && PN->getIncomingValue(i) != InVal)\n return 0; \/\/ Not the same, bail out.\n else\n InVal = PN->getIncomingValue(i);\n\n \/\/ The only case that could cause InVal to be null is if we have a PHI node\n \/\/ that only has entries for itself. In this case, there is no entry into the\n \/\/ loop, so kill the PHI.\n \/\/\n if (InVal == 0) InVal = Constant::getNullValue(PN->getType());\n\n \/\/ All of the incoming values are the same, return the value now.\n return InVal;\n}\n<|endoftext|>"} {"text":"\/\/===-- Local.cpp - Functions to perform local transformations ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This family of functions perform various local transformations to the\n\/\/ program.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Analysis\/ConstantFolding.h\"\n#include \"llvm\/Support\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local constant propagation...\n\/\/\n\n\/\/\/ doConstantPropagation - If an instruction references constants, try to fold\n\/\/\/ them together...\n\/\/\/\nbool llvm::doConstantPropagation(BasicBlock::iterator &II) {\n if (Constant *C = ConstantFoldInstruction(II)) {\n \/\/ Replaces all of the uses of a variable with uses of the constant.\n II->replaceAllUsesWith(C);\n\n \/\/ Remove the instruction from the basic block...\n II = II->getParent()->getInstList().erase(II);\n return true;\n }\n\n return false;\n}\n\n\/\/\/ ConstantFoldInstruction - Attempt to constant fold the specified\n\/\/\/ instruction. If successful, the constant result is returned, if not, null\n\/\/\/ is returned. Note that this function can only fail when attempting to fold\n\/\/\/ instructions like loads and stores, which have no constant expression form.\n\/\/\/\nConstant *llvm::ConstantFoldInstruction(Instruction *I) {\n if (PHINode *PN = dyn_cast(I)) {\n if (PN->getNumIncomingValues() == 0)\n return Constant::getNullValue(PN->getType());\n\n Constant *Result = dyn_cast(PN->getIncomingValue(0));\n if (Result == 0) return 0;\n\n \/\/ Handle PHI nodes specially here...\n for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)\n if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)\n return 0; \/\/ Not all the same incoming constants...\n\n \/\/ If we reach here, all incoming values are the same constant.\n return Result;\n } else if (CallInst *CI = dyn_cast(I)) {\n if (Function *F = CI->getCalledFunction())\n if (canConstantFoldCallTo(F)) {\n std::vector Args;\n for (unsigned i = 1, e = CI->getNumOperands(); i != e; ++i)\n if (Constant *Op = dyn_cast(CI->getOperand(i)))\n Args.push_back(Op);\n else\n return 0;\n return ConstantFoldCall(F, Args);\n }\n return 0;\n }\n\n Constant *Op0 = 0, *Op1 = 0;\n switch (I->getNumOperands()) {\n default:\n case 2:\n Op1 = dyn_cast(I->getOperand(1));\n if (Op1 == 0) return 0; \/\/ Not a constant?, can't fold\n case 1:\n Op0 = dyn_cast(I->getOperand(0));\n if (Op0 == 0) return 0; \/\/ Not a constant?, can't fold\n break;\n case 0: return 0;\n }\n\n if (isa(I) || isa(I))\n return ConstantExpr::get(I->getOpcode(), Op0, Op1);\n\n switch (I->getOpcode()) {\n default: return 0;\n case Instruction::Cast:\n return ConstantExpr::getCast(Op0, I->getType());\n case Instruction::Select:\n if (Constant *Op2 = dyn_cast(I->getOperand(2)))\n return ConstantExpr::getSelect(Op0, Op1, Op2);\n return 0;\n case Instruction::ExtractElement:\n return ConstantExpr::getExtractElement(Op0, Op1);\n case Instruction::InsertElement:\n if (Constant *Op2 = dyn_cast(I->getOperand(2)))\n return ConstantExpr::getInsertElement(Op0, Op1, Op2);\n return 0;\n case Instruction::ShuffleVector:\n if (Constant *Op2 = dyn_cast(I->getOperand(2)))\n return ConstantExpr::getShuffleVector(Op0, Op1, Op2);\n return 0;\n case Instruction::GetElementPtr:\n std::vector IdxList;\n IdxList.reserve(I->getNumOperands()-1);\n if (Op1) IdxList.push_back(Op1);\n for (unsigned i = 2, e = I->getNumOperands(); i != e; ++i)\n if (Constant *C = dyn_cast(I->getOperand(i)))\n IdxList.push_back(C);\n else\n return 0; \/\/ Non-constant operand\n return ConstantExpr::getGetElementPtr(Op0, IdxList);\n }\n}\n\n\/\/ ConstantFoldTerminator - If a terminator instruction is predicated on a\n\/\/ constant value, convert it into an unconditional branch to the constant\n\/\/ destination.\n\/\/\nbool llvm::ConstantFoldTerminator(BasicBlock *BB) {\n TerminatorInst *T = BB->getTerminator();\n\n \/\/ Branch - See if we are conditional jumping on constant\n if (BranchInst *BI = dyn_cast(T)) {\n if (BI->isUnconditional()) return false; \/\/ Can't optimize uncond branch\n BasicBlock *Dest1 = cast(BI->getOperand(0));\n BasicBlock *Dest2 = cast(BI->getOperand(1));\n\n if (ConstantBool *Cond = dyn_cast(BI->getCondition())) {\n \/\/ Are we branching on constant?\n \/\/ YES. Change to unconditional branch...\n BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;\n BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;\n\n \/\/cerr << \"Function: \" << T->getParent()->getParent()\n \/\/ << \"\\nRemoving branch from \" << T->getParent()\n \/\/ << \"\\n\\nTo: \" << OldDest << endl;\n\n \/\/ Let the basic block know that we are letting go of it. Based on this,\n \/\/ it will adjust it's PHI nodes.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n OldDest->removePredecessor(BI->getParent());\n\n \/\/ Set the unconditional destination, and change the insn to be an\n \/\/ unconditional branch.\n BI->setUnconditionalDest(Destination);\n return true;\n } else if (Dest2 == Dest1) { \/\/ Conditional branch to same location?\n \/\/ This branch matches something like this:\n \/\/ br bool %cond, label %Dest, label %Dest\n \/\/ and changes it into: br label %Dest\n\n \/\/ Let the basic block know that we are letting go of one copy of it.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n Dest1->removePredecessor(BI->getParent());\n\n \/\/ Change a conditional branch to unconditional.\n BI->setUnconditionalDest(Dest1);\n return true;\n }\n } else if (SwitchInst *SI = dyn_cast(T)) {\n \/\/ If we are switching on a constant, we can convert the switch into a\n \/\/ single branch instruction!\n ConstantInt *CI = dyn_cast(SI->getCondition());\n BasicBlock *TheOnlyDest = SI->getSuccessor(0); \/\/ The default dest\n BasicBlock *DefaultDest = TheOnlyDest;\n assert(TheOnlyDest == SI->getDefaultDest() &&\n \"Default destination is not successor #0?\");\n\n \/\/ Figure out which case it goes to...\n for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n if (SI->getSuccessorValue(i) == CI) {\n TheOnlyDest = SI->getSuccessor(i);\n break;\n }\n\n \/\/ Check to see if this branch is going to the same place as the default\n \/\/ dest. If so, eliminate it as an explicit compare.\n if (SI->getSuccessor(i) == DefaultDest) {\n \/\/ Remove this entry...\n DefaultDest->removePredecessor(SI->getParent());\n SI->removeCase(i);\n --i; --e; \/\/ Don't skip an entry...\n continue;\n }\n\n \/\/ Otherwise, check to see if the switch only branches to one destination.\n \/\/ We do this by reseting \"TheOnlyDest\" to null when we find two non-equal\n \/\/ destinations.\n if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;\n }\n\n if (CI && !TheOnlyDest) {\n \/\/ Branching on a constant, but not any of the cases, go to the default\n \/\/ successor.\n TheOnlyDest = SI->getDefaultDest();\n }\n\n \/\/ If we found a single destination that we can fold the switch into, do so\n \/\/ now.\n if (TheOnlyDest) {\n \/\/ Insert the new branch..\n new BranchInst(TheOnlyDest, SI);\n BasicBlock *BB = SI->getParent();\n\n \/\/ Remove entries from PHI nodes which we no longer branch to...\n for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n BasicBlock *Succ = SI->getSuccessor(i);\n if (Succ == TheOnlyDest)\n TheOnlyDest = 0; \/\/ Don't modify the first branch to TheOnlyDest\n else\n Succ->removePredecessor(BB);\n }\n\n \/\/ Delete the old switch...\n BB->getInstList().erase(SI);\n return true;\n } else if (SI->getNumSuccessors() == 2) {\n \/\/ Otherwise, we can fold this switch into a conditional branch\n \/\/ instruction if it has only one non-default destination.\n Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),\n SI->getSuccessorValue(1), \"cond\", SI);\n \/\/ Insert the new branch...\n new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);\n\n \/\/ Delete the old switch...\n SI->getParent()->getInstList().erase(SI);\n return true;\n }\n }\n return false;\n}\n\n\/\/\/ ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a\n\/\/\/ getelementptr constantexpr, return the constant value being addressed by the\n\/\/\/ constant expression, or null if something is funny and we can't decide.\nConstant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, \n ConstantExpr *CE) {\n if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))\n return 0; \/\/ Do not allow stepping over the value!\n \n \/\/ Loop over all of the operands, tracking down which value we are\n \/\/ addressing...\n gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);\n for (++I; I != E; ++I)\n if (const StructType *STy = dyn_cast(*I)) {\n ConstantUInt *CU = cast(I.getOperand());\n assert(CU->getValue() < STy->getNumElements() &&\n \"Struct index out of range!\");\n unsigned El = (unsigned)CU->getValue();\n if (ConstantStruct *CS = dyn_cast(C)) {\n C = CS->getOperand(El);\n } else if (isa(C)) {\n C = Constant::getNullValue(STy->getElementType(El));\n } else if (isa(C)) {\n C = UndefValue::get(STy->getElementType(El));\n } else {\n return 0;\n }\n } else if (ConstantInt *CI = dyn_cast(I.getOperand())) {\n if (const ArrayType *ATy = dyn_cast(*I)) {\n if ((uint64_t)CI->getRawValue() >= ATy->getNumElements())\n return 0;\n if (ConstantArray *CA = dyn_cast(C))\n C = CA->getOperand((unsigned)CI->getRawValue());\n else if (isa(C))\n C = Constant::getNullValue(ATy->getElementType());\n else if (isa(C))\n C = UndefValue::get(ATy->getElementType());\n else\n return 0;\n } else if (const PackedType *PTy = dyn_cast(*I)) {\n if ((uint64_t)CI->getRawValue() >= PTy->getNumElements())\n return 0;\n if (ConstantPacked *CP = dyn_cast(C))\n C = CP->getOperand((unsigned)CI->getRawValue());\n else if (isa(C))\n C = Constant::getNullValue(PTy->getElementType());\n else if (isa(C))\n C = UndefValue::get(PTy->getElementType());\n else\n return 0;\n } else {\n return 0;\n }\n } else {\n return 0;\n }\n return C;\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local dead code elimination...\n\/\/\n\nbool llvm::isInstructionTriviallyDead(Instruction *I) {\n if (!I->use_empty() || isa(I)) return false;\n\n if (!I->mayWriteToMemory()) return true;\n\n if (CallInst *CI = dyn_cast(I))\n if (Function *F = CI->getCalledFunction()) {\n unsigned IntrinsicID = F->getIntrinsicID();\n#define GET_SIDE_EFFECT_INFO\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_SIDE_EFFECT_INFO\n }\n return false;\n}\n\n\/\/ dceInstruction - Inspect the instruction at *BBI and figure out if it's\n\/\/ [trivially] dead. If so, remove the instruction and update the iterator\n\/\/ to point to the instruction that immediately succeeded the original\n\/\/ instruction.\n\/\/\nbool llvm::dceInstruction(BasicBlock::iterator &BBI) {\n \/\/ Look for un\"used\" definitions...\n if (isInstructionTriviallyDead(BBI)) {\n BBI = BBI->getParent()->getInstList().erase(BBI); \/\/ Bye bye\n return true;\n }\n return false;\n}\nRefactor some code to expose an interface to constant fold and instruction given it's opcode, typeand operands.\/\/===-- Local.cpp - Functions to perform local transformations ------------===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file was developed by the LLVM research group and is distributed under\n\/\/ the University of Illinois Open Source License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This family of functions perform various local transformations to the\n\/\/ program.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Transforms\/Utils\/Local.h\"\n#include \"llvm\/Constants.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/Intrinsics.h\"\n#include \"llvm\/Analysis\/ConstantFolding.h\"\n#include \"llvm\/Support\/GetElementPtrTypeIterator.h\"\n#include \"llvm\/Support\/MathExtras.h\"\n#include \n#include \nusing namespace llvm;\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local constant propagation...\n\/\/\n\n\/\/\/ doConstantPropagation - If an instruction references constants, try to fold\n\/\/\/ them together...\n\/\/\/\nbool llvm::doConstantPropagation(BasicBlock::iterator &II) {\n if (Constant *C = ConstantFoldInstruction(II)) {\n \/\/ Replaces all of the uses of a variable with uses of the constant.\n II->replaceAllUsesWith(C);\n\n \/\/ Remove the instruction from the basic block...\n II = II->getParent()->getInstList().erase(II);\n return true;\n }\n\n return false;\n}\n\n\/\/\/ ConstantFoldInstruction - Attempt to constant fold the specified\n\/\/\/ instruction. If successful, the constant result is returned, if not, null\n\/\/\/ is returned. Note that this function can only fail when attempting to fold\n\/\/\/ instructions like loads and stores, which have no constant expression form.\n\/\/\/\nConstant *llvm::ConstantFoldInstruction(Instruction *I) {\n if (PHINode *PN = dyn_cast(I)) {\n if (PN->getNumIncomingValues() == 0)\n return Constant::getNullValue(PN->getType());\n\n Constant *Result = dyn_cast(PN->getIncomingValue(0));\n if (Result == 0) return 0;\n\n \/\/ Handle PHI nodes specially here...\n for (unsigned i = 1, e = PN->getNumIncomingValues(); i != e; ++i)\n if (PN->getIncomingValue(i) != Result && PN->getIncomingValue(i) != PN)\n return 0; \/\/ Not all the same incoming constants...\n\n \/\/ If we reach here, all incoming values are the same constant.\n return Result;\n }\n\n Constant *Op0 = 0, *Op1 = 0;\n switch (I->getNumOperands()) {\n default:\n case 2:\n Op1 = dyn_cast(I->getOperand(1));\n if (Op1 == 0) return 0; \/\/ Not a constant?, can't fold\n case 1:\n Op0 = dyn_cast(I->getOperand(0));\n if (Op0 == 0) return 0; \/\/ Not a constant?, can't fold\n break;\n case 0: return 0;\n }\n\n if (isa(I) || isa(I)) {\n if (Constant *Op0 = dyn_cast(I->getOperand(0)))\n if (Constant *Op1 = dyn_cast(I->getOperand(1)))\n return ConstantExpr::get(I->getOpcode(), Op0, Op1);\n return 0; \/\/ Operands not constants.\n }\n\n \/\/ Scan the operand list, checking to see if the are all constants, if so,\n \/\/ hand off to ConstantFoldInstOperands.\n std::vector Ops;\n for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)\n if (Constant *Op = dyn_cast(I->getOperand(i)))\n Ops.push_back(Op);\n else\n return 0; \/\/ All operands not constant!\n\n return ConstantFoldInstOperands(I->getOpcode(), I->getType(), Ops);\n}\n\n\/\/\/ ConstantFoldInstOperands - Attempt to constant fold an instruction with the\n\/\/\/ specified opcode and operands. If successful, the constant result is\n\/\/\/ returned, if not, null is returned. Note that this function can fail when\n\/\/\/ attempting to fold instructions like loads and stores, which have no\n\/\/\/ constant expression form.\n\/\/\/\nConstant *llvm::ConstantFoldInstOperands(unsigned Opc, const Type *DestTy,\n const std::vector &Ops) {\n if (Opc >= Instruction::BinaryOpsBegin && Opc < Instruction::BinaryOpsEnd)\n return ConstantExpr::get(Opc, Ops[0], Ops[1]);\n \n switch (Opc) {\n default: return 0;\n case Instruction::Call:\n if (Function *F = dyn_cast(Ops[0])) {\n if (canConstantFoldCallTo(F)) {\n std::vector Args(Ops.begin()+1, Ops.end());\n return ConstantFoldCall(F, Args);\n }\n }\n return 0;\n case Instruction::Shl:\n case Instruction::Shr:\n return ConstantExpr::get(Opc, Ops[0], Ops[1]);\n case Instruction::Cast:\n return ConstantExpr::getCast(Ops[0], DestTy);\n case Instruction::Select:\n return ConstantExpr::getSelect(Ops[0], Ops[1], Ops[2]);\n case Instruction::ExtractElement:\n return ConstantExpr::getExtractElement(Ops[0], Ops[1]);\n case Instruction::InsertElement:\n return ConstantExpr::getInsertElement(Ops[0], Ops[1], Ops[2]);\n case Instruction::ShuffleVector:\n return ConstantExpr::getShuffleVector(Ops[0], Ops[1], Ops[2]);\n case Instruction::GetElementPtr:\n return ConstantExpr::getGetElementPtr(Ops[0],\n std::vector(Ops.begin()+1, \n Ops.end()));\n }\n}\n\n\/\/ ConstantFoldTerminator - If a terminator instruction is predicated on a\n\/\/ constant value, convert it into an unconditional branch to the constant\n\/\/ destination.\n\/\/\nbool llvm::ConstantFoldTerminator(BasicBlock *BB) {\n TerminatorInst *T = BB->getTerminator();\n\n \/\/ Branch - See if we are conditional jumping on constant\n if (BranchInst *BI = dyn_cast(T)) {\n if (BI->isUnconditional()) return false; \/\/ Can't optimize uncond branch\n BasicBlock *Dest1 = cast(BI->getOperand(0));\n BasicBlock *Dest2 = cast(BI->getOperand(1));\n\n if (ConstantBool *Cond = dyn_cast(BI->getCondition())) {\n \/\/ Are we branching on constant?\n \/\/ YES. Change to unconditional branch...\n BasicBlock *Destination = Cond->getValue() ? Dest1 : Dest2;\n BasicBlock *OldDest = Cond->getValue() ? Dest2 : Dest1;\n\n \/\/cerr << \"Function: \" << T->getParent()->getParent()\n \/\/ << \"\\nRemoving branch from \" << T->getParent()\n \/\/ << \"\\n\\nTo: \" << OldDest << endl;\n\n \/\/ Let the basic block know that we are letting go of it. Based on this,\n \/\/ it will adjust it's PHI nodes.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n OldDest->removePredecessor(BI->getParent());\n\n \/\/ Set the unconditional destination, and change the insn to be an\n \/\/ unconditional branch.\n BI->setUnconditionalDest(Destination);\n return true;\n } else if (Dest2 == Dest1) { \/\/ Conditional branch to same location?\n \/\/ This branch matches something like this:\n \/\/ br bool %cond, label %Dest, label %Dest\n \/\/ and changes it into: br label %Dest\n\n \/\/ Let the basic block know that we are letting go of one copy of it.\n assert(BI->getParent() && \"Terminator not inserted in block!\");\n Dest1->removePredecessor(BI->getParent());\n\n \/\/ Change a conditional branch to unconditional.\n BI->setUnconditionalDest(Dest1);\n return true;\n }\n } else if (SwitchInst *SI = dyn_cast(T)) {\n \/\/ If we are switching on a constant, we can convert the switch into a\n \/\/ single branch instruction!\n ConstantInt *CI = dyn_cast(SI->getCondition());\n BasicBlock *TheOnlyDest = SI->getSuccessor(0); \/\/ The default dest\n BasicBlock *DefaultDest = TheOnlyDest;\n assert(TheOnlyDest == SI->getDefaultDest() &&\n \"Default destination is not successor #0?\");\n\n \/\/ Figure out which case it goes to...\n for (unsigned i = 1, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n if (SI->getSuccessorValue(i) == CI) {\n TheOnlyDest = SI->getSuccessor(i);\n break;\n }\n\n \/\/ Check to see if this branch is going to the same place as the default\n \/\/ dest. If so, eliminate it as an explicit compare.\n if (SI->getSuccessor(i) == DefaultDest) {\n \/\/ Remove this entry...\n DefaultDest->removePredecessor(SI->getParent());\n SI->removeCase(i);\n --i; --e; \/\/ Don't skip an entry...\n continue;\n }\n\n \/\/ Otherwise, check to see if the switch only branches to one destination.\n \/\/ We do this by reseting \"TheOnlyDest\" to null when we find two non-equal\n \/\/ destinations.\n if (SI->getSuccessor(i) != TheOnlyDest) TheOnlyDest = 0;\n }\n\n if (CI && !TheOnlyDest) {\n \/\/ Branching on a constant, but not any of the cases, go to the default\n \/\/ successor.\n TheOnlyDest = SI->getDefaultDest();\n }\n\n \/\/ If we found a single destination that we can fold the switch into, do so\n \/\/ now.\n if (TheOnlyDest) {\n \/\/ Insert the new branch..\n new BranchInst(TheOnlyDest, SI);\n BasicBlock *BB = SI->getParent();\n\n \/\/ Remove entries from PHI nodes which we no longer branch to...\n for (unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {\n \/\/ Found case matching a constant operand?\n BasicBlock *Succ = SI->getSuccessor(i);\n if (Succ == TheOnlyDest)\n TheOnlyDest = 0; \/\/ Don't modify the first branch to TheOnlyDest\n else\n Succ->removePredecessor(BB);\n }\n\n \/\/ Delete the old switch...\n BB->getInstList().erase(SI);\n return true;\n } else if (SI->getNumSuccessors() == 2) {\n \/\/ Otherwise, we can fold this switch into a conditional branch\n \/\/ instruction if it has only one non-default destination.\n Value *Cond = new SetCondInst(Instruction::SetEQ, SI->getCondition(),\n SI->getSuccessorValue(1), \"cond\", SI);\n \/\/ Insert the new branch...\n new BranchInst(SI->getSuccessor(1), SI->getSuccessor(0), Cond, SI);\n\n \/\/ Delete the old switch...\n SI->getParent()->getInstList().erase(SI);\n return true;\n }\n }\n return false;\n}\n\n\/\/\/ ConstantFoldLoadThroughGEPConstantExpr - Given a constant and a\n\/\/\/ getelementptr constantexpr, return the constant value being addressed by the\n\/\/\/ constant expression, or null if something is funny and we can't decide.\nConstant *llvm::ConstantFoldLoadThroughGEPConstantExpr(Constant *C, \n ConstantExpr *CE) {\n if (CE->getOperand(1) != Constant::getNullValue(CE->getOperand(1)->getType()))\n return 0; \/\/ Do not allow stepping over the value!\n \n \/\/ Loop over all of the operands, tracking down which value we are\n \/\/ addressing...\n gep_type_iterator I = gep_type_begin(CE), E = gep_type_end(CE);\n for (++I; I != E; ++I)\n if (const StructType *STy = dyn_cast(*I)) {\n ConstantUInt *CU = cast(I.getOperand());\n assert(CU->getValue() < STy->getNumElements() &&\n \"Struct index out of range!\");\n unsigned El = (unsigned)CU->getValue();\n if (ConstantStruct *CS = dyn_cast(C)) {\n C = CS->getOperand(El);\n } else if (isa(C)) {\n C = Constant::getNullValue(STy->getElementType(El));\n } else if (isa(C)) {\n C = UndefValue::get(STy->getElementType(El));\n } else {\n return 0;\n }\n } else if (ConstantInt *CI = dyn_cast(I.getOperand())) {\n if (const ArrayType *ATy = dyn_cast(*I)) {\n if ((uint64_t)CI->getRawValue() >= ATy->getNumElements())\n return 0;\n if (ConstantArray *CA = dyn_cast(C))\n C = CA->getOperand((unsigned)CI->getRawValue());\n else if (isa(C))\n C = Constant::getNullValue(ATy->getElementType());\n else if (isa(C))\n C = UndefValue::get(ATy->getElementType());\n else\n return 0;\n } else if (const PackedType *PTy = dyn_cast(*I)) {\n if ((uint64_t)CI->getRawValue() >= PTy->getNumElements())\n return 0;\n if (ConstantPacked *CP = dyn_cast(C))\n C = CP->getOperand((unsigned)CI->getRawValue());\n else if (isa(C))\n C = Constant::getNullValue(PTy->getElementType());\n else if (isa(C))\n C = UndefValue::get(PTy->getElementType());\n else\n return 0;\n } else {\n return 0;\n }\n } else {\n return 0;\n }\n return C;\n}\n\n\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/ Local dead code elimination...\n\/\/\n\nbool llvm::isInstructionTriviallyDead(Instruction *I) {\n if (!I->use_empty() || isa(I)) return false;\n\n if (!I->mayWriteToMemory()) return true;\n\n if (CallInst *CI = dyn_cast(I))\n if (Function *F = CI->getCalledFunction()) {\n unsigned IntrinsicID = F->getIntrinsicID();\n#define GET_SIDE_EFFECT_INFO\n#include \"llvm\/Intrinsics.gen\"\n#undef GET_SIDE_EFFECT_INFO\n }\n return false;\n}\n\n\/\/ dceInstruction - Inspect the instruction at *BBI and figure out if it's\n\/\/ [trivially] dead. If so, remove the instruction and update the iterator\n\/\/ to point to the instruction that immediately succeeded the original\n\/\/ instruction.\n\/\/\nbool llvm::dceInstruction(BasicBlock::iterator &BBI) {\n \/\/ Look for un\"used\" definitions...\n if (isInstructionTriviallyDead(BBI)) {\n BBI = BBI->getParent()->getInstList().erase(BBI); \/\/ Bye bye\n return true;\n }\n return false;\n}\n<|endoftext|>"} {"text":"\/*\n * face-cleaner.cpp\n *\n * Created on: Nov 15, 2014\n * Author: Michael Williams\n *\/\n\n#include \"facerecogntion\/face-cleaner.h\"\n#include \n#include \n\nusing namespace cv;\nusing namespace std;\n\nnamespace facerecogntion{\n\nMat clean_face(Mat face){\n\tCascadeClassifier filter;\n\tfilter.load( FACE_FILTER );\n\tvector faces;\n\tMat gray_face;\n\tcvtColor( face, gray_face, CV_BGR2GRAY );\n\tgray_face.convertTo(gray_face, CV_8UC1);\n\tequalizeHist( gray_face, gray_face );\n\tfilter.detectMultiScale( gray_face, faces, 1.1, 2, 0, Size(100, 100) );\n\tRect roi;\n\tvector::iterator it;\n\tfor(it=faces.begin(); it != faces.end(); it++){\n\t\tif(it->area() > roi.area()){\n\t\t\troi = (*it);\n\t\t}\n\t}\n\tMat tmp;\n\tcvtColor(gray_face(roi), tmp, CV_BGR2GRAY);\n\treturn tmp;\n\n}\n\n}\nMore cleaning to the images\/*\n * face-cleaner.cpp\n *\n * Created on: Nov 15, 2014\n * Author: Michael Williams\n *\/\n\n#include \"facerecogntion\/face-cleaner.h\"\n#include \n#include \n\nusing namespace cv;\nusing namespace std;\n\nnamespace facerecogntion{\n\nMat clean_face(Mat face){\n\tCascadeClassifier filter;\n\tfilter.load( FACE_FILTER );\n\tvector faces;\n\tMat gray_face;\n\tcvtColor( face, gray_face, CV_BGR2GRAY );\n\tgray_face.convertTo(gray_face, CV_8UC1);\n\tequalizeHist( gray_face, gray_face );\n\tfilter.detectMultiScale( gray_face, faces, 1.1, 2, 0, Size(100, 100) );\n\tRect roi;\n\tvector::iterator it;\n\tfor(it=faces.begin(); it != faces.end(); it++){\n\t\tif(it->area() > roi.area()){\n\t\t\troi = (*it);\n\t\t}\n\t}\n\tMat tmp;\n\tgray_face(roi).convertTo(tmp, CV_8UC1);\n\tequalizeHist( tmp, tmp );\n\treturn tmp;\n\n}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: lockfile.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2003-03-25 13:51:15 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): lars.oppermann@sun.com\n *\n *\n ************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"desktopresid.hxx\"\n#include \"lockfile.hxx\"\n#include \"desktop.hrc\"\n\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::utl;\n\n\nnamespace desktop {\n\n \/\/ initialize static members...\n \/\/ lock suffix\n const OUString Lockfile::m_aSuffix = OUString::createFromAscii( \"\/.lock\" );\n \/\/ values for datafile\n const ByteString Lockfile::m_aGroup( \"Lockdata\" );\n const ByteString Lockfile::m_aUserkey( \"User\" );\n const ByteString Lockfile::m_aHostkey( \"Host\" );\n const ByteString Lockfile::m_aStampkey( \"Stamp\" );\n const ByteString Lockfile::m_aTimekey( \"Time\" );\n\n Lockfile::Lockfile(void)\n :m_bRemove(sal_False)\n ,m_bIsLocked(sal_False)\n {\n \/\/ build the file-url to use for the lock\n OUString aUserPath;\n Bootstrap::locateUserInstallation( aUserPath );\n m_aLockname = aUserPath + m_aSuffix;\n\n \/\/ generate ID\n const int nIdBytes = 16;\n char tmpId[nIdBytes*2+1];\n time_t t;\n srand( (unsigned)(t = time( NULL )) );\n int tmpByte = 0;\n for (int i = 0; iINTEGRATION: CWS fwk01 (1.2.2.5.16); FILE MERGED 2003\/04\/01 14:03:31 lo 1.2.2.5.16.1: #i12907# allow startup without splashscreen component being loaded\/*************************************************************************\n *\n * $RCSfile: lockfile.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: hr $ $Date: 2003-04-04 17:22:51 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): lars.oppermann@sun.com\n *\n *\n ************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"desktopresid.hxx\"\n#include \"lockfile.hxx\"\n#include \"desktop.hrc\"\n\nusing namespace ::osl;\nusing namespace ::rtl;\nusing namespace ::utl;\n\n\nnamespace desktop {\n\n \/\/ initialize static members...\n \/\/ lock suffix\n const OUString Lockfile::m_aSuffix = OUString::createFromAscii( \"\/.lock\" );\n \/\/ values for datafile\n const ByteString Lockfile::m_aGroup( \"Lockdata\" );\n const ByteString Lockfile::m_aUserkey( \"User\" );\n const ByteString Lockfile::m_aHostkey( \"Host\" );\n const ByteString Lockfile::m_aStampkey( \"Stamp\" );\n const ByteString Lockfile::m_aTimekey( \"Time\" );\n\n Lockfile::Lockfile(void)\n :m_bRemove(sal_False)\n ,m_bIsLocked(sal_False)\n {\n \/\/ build the file-url to use for the lock\n OUString aUserPath;\n Bootstrap::locateUserInstallation( aUserPath );\n m_aLockname = aUserPath + m_aSuffix;\n\n \/\/ generate ID\n const int nIdBytes = 16;\n char tmpId[nIdBytes*2+1];\n time_t t;\n srand( (unsigned)(t = time( NULL )) );\n int tmpByte = 0;\n for (int i = 0; i"} {"text":"\/*\n Copyright(c) 2004 John J.Bolton\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,\n merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"ZHash.h\"\n\n#include \"Chess\/Board.h\"\n#include \"Chess\/Piece.h\"\n#include \"Chess\/Position.h\"\n\n#include \"Misc\/Random.h\"\n\n#include \n\nZHash::ZValueTable const ZHash::zValueTable_;\n\nnamespace\n{\n uint64_t generateRandomZ(RandomMT & rng)\n {\n \/\/ Z is 63 bits and RandomMT is 32 bits so we have to concatenate two numbers together to make a Z value.\n return ((uint64_t(rng()) << 32) | rng()) & 0x7fffffffffffffff;\n }\n} \/\/ anonymous namespace\n\nZHash::ZHash(Z z \/* = EMPTY *\/)\n : value_(z)\n{\n}\n\nZHash::ZHash(Board const & board,\n Color whoseTurn,\n unsigned castleStatus \/* = 0*\/,\n Color ePColor \/* = INVALID*\/,\n int ePColumn \/* = -1*\/,\n bool fiftyMoveRule \/* = false *\/)\n{\n value_ = 0;\n\n for (int i = 0; i < Board::SIZE; ++i)\n {\n for (int j = 0; j < Board::SIZE; ++j)\n {\n Piece const * const piece = board.pieceAt(i, j);\n if (piece)\n add(piece, Position(i, j));\n }\n }\n\n if (whoseTurn != Color::WHITE)\n turn();\n\n if (castleStatus != 0)\n castle(castleStatus);\n\n if ((ePColor != Color::INVALID) && (ePColumn >= 0))\n enPassant(ePColor, ePColumn);\n\n if (fiftyMoveRule)\n fifty();\n}\n\nZHash ZHash::add(Piece const * piece, Position const & position)\n{\n value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);\n return *this;\n}\n\nZHash ZHash::remove(Piece const * piece, Position const & position)\n{\n value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);\n return *this;\n}\n\nZHash ZHash::move(Piece const * piece, Position const & from, Position const & to)\n{\n remove(piece, from);\n return add(piece, to);\n}\n\nZHash ZHash::turn()\n{\n value_ ^= zValueTable_.turnValue();\n return *this;\n}\n\nZHash ZHash::castle(unsigned mask)\n{\n assert(NUMBER_OF_CASTLE_BITS == 8);\n assert(CASTLE_AVAILABILITY_MASK == 0xf0);\n for (int i = 0; i < 4; ++i)\n {\n if (mask & (0x10 << i))\n value_ ^= zValueTable_.castleValue(i);\n }\n return *this;\n}\n\nZHash ZHash::enPassant(Color color, int column)\n{\n value_ ^= zValueTable_.enPassantValue((int)color, column);\n return *this;\n}\n\nZHash ZHash::fifty()\n{\n value_ ^= zValueTable_.fiftyValue();\n return *this;\n}\n\nbool ZHash::isUndefined() const\n{\n \/\/ The value is undefined if the high order bit is set\n return static_cast(value_) < 0;\n}\n\nZHash::ZValueTable::ZValueTable()\n{\n RandomMT rng(0);\n\n \/\/ Generate piece values\n\n for (int i = 0; i < NUMBER_OF_COLORS; ++i)\n {\n for (int j = 0; j < Board::SIZE; ++j)\n {\n for (int k = 0; k < Board::SIZE; ++k)\n {\n for (int m = 0; m < NUMBER_OF_PIECE_TYPES; ++m)\n {\n pieceValues_[i][j][k][m] = generateRandomZ(rng);\n }\n }\n }\n }\n\n \/\/ Generate castle values\n\n for (auto & v : castleValues_)\n {\n v = generateRandomZ(rng);\n }\n\n \/\/ Generate en passant values\n\n for (int i = 0; i < NUMBER_OF_COLORS; ++i)\n {\n for (int j = 0; j < Board::SIZE; ++j)\n {\n enPassantValues_[i][j] = generateRandomZ(rng);\n }\n }\n\n \/\/ Generate fifty-move rule value\n\n fiftyValue_ = generateRandomZ(rng);\n\n \/\/ Generate turn value\n\n turnValue_ = generateRandomZ(rng);\n}\n\nZHash::Z ZHash::ZValueTable::pieceValue(int color, int type, int row, int column) const\n{\n return pieceValues_[color][row][column][type];\n}\n\nZHash::Z ZHash::ZValueTable::castleValue(int castle) const\n{\n return castleValues_[castle];\n}\n\nZHash::Z ZHash::ZValueTable::enPassantValue(int color, int column) const\n{\n return enPassantValues_[color][column];\n}\n\nZHash::Z ZHash::ZValueTable::fiftyValue() const\n{\n return fiftyValue_;\n}\n\nZHash::Z ZHash::ZValueTable::turnValue() const\n{\n return turnValue_;\n}\n\nbool operator ==(ZHash const & x, ZHash const & y)\n{\n return x.value_ == y.value_;\n}\nSwitched to std::random\/*\n Copyright(c) 2004 John J.Bolton\n\n Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files\n (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify,\n merge, publish, distribute, sublicense, and\/or sell copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES\n OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE\n LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *\/\n\n#include \"ZHash.h\"\n\n#include \"Chess\/Board.h\"\n#include \"Chess\/Piece.h\"\n#include \"Chess\/Position.h\"\n\n#include \n#include \n\nZHash::ZValueTable const ZHash::zValueTable_;\n\nZHash::ZHash(Z z \/* = EMPTY *\/)\n : value_(z)\n{\n}\n\nZHash::ZHash(Board const & board,\n Color whoseTurn,\n unsigned castleStatus \/* = 0*\/,\n Color ePColor \/* = INVALID*\/,\n int ePColumn \/* = -1*\/,\n bool fiftyMoveRule \/* = false *\/)\n{\n value_ = 0;\n\n for (int i = 0; i < Board::SIZE; ++i)\n {\n for (int j = 0; j < Board::SIZE; ++j)\n {\n Piece const * const piece = board.pieceAt(i, j);\n if (piece)\n add(piece, Position(i, j));\n }\n }\n\n if (whoseTurn != Color::WHITE)\n turn();\n\n if (castleStatus != 0)\n castle(castleStatus);\n\n if ((ePColor != Color::INVALID) && (ePColumn >= 0))\n enPassant(ePColor, ePColumn);\n\n if (fiftyMoveRule)\n fifty();\n}\n\nZHash ZHash::add(Piece const * piece, Position const & position)\n{\n value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);\n return *this;\n}\n\nZHash ZHash::remove(Piece const * piece, Position const & position)\n{\n value_ ^= zValueTable_.pieceValue((int)piece->color(), (int)piece->type(), position.row, position.column);\n return *this;\n}\n\nZHash ZHash::move(Piece const * piece, Position const & from, Position const & to)\n{\n remove(piece, from);\n return add(piece, to);\n}\n\nZHash ZHash::turn()\n{\n value_ ^= zValueTable_.turnValue();\n return *this;\n}\n\nZHash ZHash::castle(unsigned mask)\n{\n assert(NUMBER_OF_CASTLE_BITS == 8);\n assert(CASTLE_AVAILABILITY_MASK == 0xf0);\n for (int i = 0; i < 4; ++i)\n {\n if (mask & (0x10 << i))\n value_ ^= zValueTable_.castleValue(i);\n }\n return *this;\n}\n\nZHash ZHash::enPassant(Color color, int column)\n{\n value_ ^= zValueTable_.enPassantValue((int)color, column);\n return *this;\n}\n\nZHash ZHash::fifty()\n{\n value_ ^= zValueTable_.fiftyValue();\n return *this;\n}\n\nbool ZHash::isUndefined() const\n{\n \/\/ The value is undefined if the high order bit is set\n return static_cast(value_) < 0;\n}\n\nZHash::ZValueTable::ZValueTable()\n{\n std::mt19937_64 rng;\n static_assert(sizeof(std::mt19937_64::result_type) == 8);\n\n \/\/ Generate piece values\n\n for (int i = 0; i < NUMBER_OF_COLORS; ++i)\n {\n for (int j = 0; j < Board::SIZE; ++j)\n {\n for (int k = 0; k < Board::SIZE; ++k)\n {\n for (int m = 0; m < NUMBER_OF_PIECE_TYPES; ++m)\n {\n pieceValues_[i][j][k][m] = rng();\n }\n }\n }\n }\n\n \/\/ Generate castle values\n\n for (auto & v : castleValues_)\n {\n v = rng();\n }\n\n \/\/ Generate en passant values\n\n for (int i = 0; i < NUMBER_OF_COLORS; ++i)\n {\n for (int j = 0; j < Board::SIZE; ++j)\n {\n enPassantValues_[i][j] = rng();\n }\n }\n\n \/\/ Generate fifty-move rule value\n\n fiftyValue_ = rng();\n\n \/\/ Generate turn value\n\n turnValue_ = rng();\n}\n\nZHash::Z ZHash::ZValueTable::pieceValue(int color, int type, int row, int column) const\n{\n return pieceValues_[color][row][column][type];\n}\n\nZHash::Z ZHash::ZValueTable::castleValue(int castle) const\n{\n return castleValues_[castle];\n}\n\nZHash::Z ZHash::ZValueTable::enPassantValue(int color, int column) const\n{\n return enPassantValues_[color][column];\n}\n\nZHash::Z ZHash::ZValueTable::fiftyValue() const\n{\n return fiftyValue_;\n}\n\nZHash::Z ZHash::ZValueTable::turnValue() const\n{\n return turnValue_;\n}\n\nbool operator ==(ZHash const & x, ZHash const & y)\n{\n return x.value_ == y.value_;\n}\n<|endoftext|>"} {"text":"\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/cc\/saved_model\/loader.h\"\n\n#include \n\n#include \"tensorflow\/cc\/saved_model\/constants.h\"\n#include \"tensorflow\/cc\/saved_model\/reader.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/monitoring\/counter.h\"\n#include \"tensorflow\/core\/lib\/monitoring\/sampler.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/protobuf_internal.h\"\n#include \"tensorflow\/core\/protobuf\/saved_model.pb.h\"\n#include \"tensorflow\/core\/protobuf\/saver.pb.h\"\n#include \"tensorflow\/core\/public\/session.h\"\n#include \"tensorflow\/core\/public\/session_options.h\"\n#include \"tensorflow\/core\/util\/tensor_bundle\/naming.h\"\n\nnamespace tensorflow {\nnamespace {\n\nauto* load_attempt_count = monitoring::Counter<2>::New(\n \"\/tensorflow\/cc\/saved_model\/load_attempt_count\",\n \"The number of times a SavedModel was successfully loaded.\", \"model_path\",\n \"status\");\nauto* load_latency = monitoring::Counter<1>::New(\n \"\/tensorflow\/cc\/saved_model\/load_latency\",\n \"Latency in microseconds for SavedModels that were successfully loaded.\",\n \"model_path\");\nauto* load_latency_by_stage = monitoring::Sampler<2>::New(\n {\n \"\/tensorflow\/cc\/saved_model\/load_latency_by_stage\", \/\/ metric name\n \"Distribution of wall time spent (in microseconds) in each stage \"\n \"(restore graph from disk, run init graph op, etc) when loading the \"\n \"model\",\n \"model_path\",\n \"stage\",\n },\n \/\/ Scale of 10, power of 1.5 with bucket count 36 (~20 minutes).\n monitoring::Buckets::Exponential(10, 1.5, 36));\n\nconstexpr char kLoadAttemptFail[] = \"fail\";\nconstexpr char kLoadAttemptSuccess[] = \"success\";\n\nuint64 GetLatencyMicroseconds(const uint64 start_microseconds) {\n const uint64 end_microseconds = Env::Default()->NowMicros();\n \/\/ Avoid clock skew.\n if (end_microseconds < start_microseconds) return 0;\n return end_microseconds - start_microseconds;\n}\n\nStatus LoadMetaGraphIntoSession(const MetaGraphDef& meta_graph_def,\n const SessionOptions& session_options,\n std::unique_ptr* session) {\n Session* session_p = nullptr;\n TF_RETURN_IF_ERROR(NewSession(session_options, &session_p));\n session->reset(session_p);\n return (*session)->Create(meta_graph_def.graph_def());\n}\n\nTensor CreateStringTensor(const string& value) {\n Tensor tensor(DT_STRING, TensorShape({}));\n tensor.scalar()() = value;\n return tensor;\n}\n\nvoid AddAssetsTensorsToInputs(const StringPiece export_dir,\n const std::vector& asset_file_defs,\n std::vector>* inputs) {\n if (asset_file_defs.empty()) {\n return;\n }\n for (auto& asset_file_def : asset_file_defs) {\n Tensor assets_file_path_tensor = CreateStringTensor(io::JoinPath(\n export_dir, kSavedModelAssetsDirectory, asset_file_def.filename()));\n inputs->push_back(\n {asset_file_def.tensor_info().name(), assets_file_path_tensor});\n }\n}\n\n\/\/ Like Session::Run(), but uses the Make\/Run\/ReleaseCallable() API to avoid\n\/\/ leaving behind non-GC'ed state.\n\/\/\n\/\/ Detailed motivation behind this approach, from ashankar@:\n\/\/\n\/\/ Each call to Session::Run() that identifies a new subgraph (based on feeds\n\/\/ and fetches) creates some datastructures that live as long as the session\n\/\/ (the partitioned graph, associated executors etc.).\n\/\/\n\/\/ A pathological case of this would be if say the initialization op\n\/\/ (main_op\/legacy_init_op) involves the use of a large constant. Then we\n\/\/ allocate memory for that large constant that will just stick around till the\n\/\/ session dies. With this Callable mechanism, that memory will be released\n\/\/ right after ReleaseCallable returns.\n\/\/\n\/\/ However, the resource manager state remains.\nStatus RunOnce(const RunOptions& run_options,\n const std::vector>& inputs,\n const std::vector& output_tensor_names,\n const std::vector& target_node_names,\n std::vector* outputs, RunMetadata* run_metadata,\n Session* session) {\n CallableOptions callable_options;\n std::vector feed_tensors;\n *callable_options.mutable_run_options() = run_options;\n for (const auto& input : inputs) {\n const string& name = input.first;\n const Tensor& tensor = input.second;\n callable_options.add_feed(name);\n feed_tensors.push_back(tensor);\n }\n for (const string& output_tensor_name : output_tensor_names) {\n callable_options.add_fetch(output_tensor_name);\n }\n for (const string& target_node_name : target_node_names) {\n callable_options.add_target(target_node_name);\n }\n\n Session::CallableHandle callable_handle;\n TF_RETURN_IF_ERROR(session->MakeCallable(callable_options, &callable_handle));\n const Status run_status = session->RunCallable(callable_handle, feed_tensors,\n outputs, run_metadata);\n \/\/ Be sure to call ReleaseCallable() regardless of the outcome of\n \/\/ RunCallable().\n session->ReleaseCallable(callable_handle).IgnoreError();\n return run_status;\n}\n\n\/\/ RunInitOp will return OK if the initialization op was run successfully.\n\/\/ An empty init_op_name indicates that there are no init ops to run.\nStatus RunInitOp(const RunOptions& run_options, const string& export_dir,\n const MetaGraphDef& meta_graph_def,\n const std::vector& asset_file_defs,\n Session* session, const string& init_op_name) {\n if (!init_op_name.empty()) {\n LOG(INFO) << \"Running initialization op on SavedModel bundle.\";\n std::vector> inputs;\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n RunMetadata run_metadata;\n return RunOnce(run_options, inputs, {}, {init_op_name},\n nullptr \/* outputs *\/, &run_metadata, session);\n }\n return Status::OK();\n}\n\n\/\/ A SavedModel may store the name of the initialization op to run in the\n\/\/ in the SignatureDef (v2) or a collection (v1). If an init_op collection\n\/\/ exists, then the collection must contain exactly one op.\nStatus GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n string* init_op_name) {\n const auto& sig_def_map = meta_graph_def.signature_def();\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n *init_op_name = init_op_sig_it->second.outputs()\n .find(kSavedModelInitOpSignatureKey)\n ->second.name();\n return Status::OK();\n }\n\n const auto& collection_def_map = meta_graph_def.collection_def();\n string init_op_collection_key;\n if (collection_def_map.find(kSavedModelMainOpKey) !=\n collection_def_map.end()) {\n init_op_collection_key = kSavedModelMainOpKey;\n } else {\n init_op_collection_key = kSavedModelLegacyInitOpKey;\n }\n\n const auto init_op_it = collection_def_map.find(init_op_collection_key);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(\n strings::StrCat(\"Expected exactly one main op in : \", export_dir));\n }\n *init_op_name = init_op_it->second.node_list().value(0);\n }\n return Status::OK();\n}\n\nStatus RunRestore(const RunOptions& run_options, const string& export_dir,\n const StringPiece restore_op_name,\n const StringPiece variable_filename_const_op_name,\n const std::vector& asset_file_defs,\n Session* session) {\n LOG(INFO) << \"Restoring SavedModel bundle.\";\n \/\/ Find path to variables to be restored in export directory.\n const string variables_directory =\n io::JoinPath(export_dir, kSavedModelVariablesDirectory);\n \/\/ Check for saver checkpoints in v2 format. Models exported in the checkpoint\n \/\/ v2 format will have a variables.index file. The corresponding\n \/\/ variables are stored in the variables.data-?????-of-????? files.\n const string variables_index_path = io::JoinPath(\n variables_directory, MetaFilename(kSavedModelVariablesFilename));\n if (!Env::Default()->FileExists(variables_index_path).ok()) {\n LOG(INFO) << \"The specified SavedModel has no variables; no checkpoints \"\n \"were restored. File does not exist: \"\n << variables_index_path;\n return Status::OK();\n }\n const string variables_path =\n io::JoinPath(variables_directory, kSavedModelVariablesFilename);\n\n \/\/ Add variables to the graph.\n Tensor variables_path_tensor(DT_STRING, TensorShape({}));\n variables_path_tensor.scalar()() = variables_path;\n\n std::vector> inputs = {\n {string(variable_filename_const_op_name), variables_path_tensor}};\n\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n\n RunMetadata run_metadata;\n return RunOnce(run_options, inputs, {}, {string(restore_op_name)},\n nullptr \/* outputs *\/, &run_metadata, session);\n}\n\nStatus GetAssetFileDefs(const MetaGraphDef& meta_graph_def,\n std::vector* asset_file_defs) {\n \/\/ With SavedModel v2, we write asset file def into metagraph instead of\n \/\/ collection, so read from metagraph first.\n if (meta_graph_def.asset_file_def_size() > 0) {\n for (const auto& asset : meta_graph_def.asset_file_def()) {\n asset_file_defs->push_back(asset);\n }\n return Status::OK();\n }\n \/\/ Fall back to read from collection to be backward compatible with v1.\n const auto& collection_def_map = meta_graph_def.collection_def();\n const auto assets_it = collection_def_map.find(kSavedModelAssetsKey);\n if (assets_it == collection_def_map.end()) {\n return Status::OK();\n }\n const auto& any_assets = assets_it->second.any_list().value();\n for (const auto& any_asset : any_assets) {\n AssetFileDef asset_file_def;\n TF_RETURN_IF_ERROR(\n ParseAny(any_asset, &asset_file_def, \"tensorflow.AssetFileDef\"));\n asset_file_defs->push_back(asset_file_def);\n }\n return Status::OK();\n}\n\nStatus LoadSavedModelInternal(const SessionOptions& session_options,\n const RunOptions& run_options,\n const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n const uint64 read_start_microseconds = Env::Default()->NowMicros();\n TF_RETURN_IF_ERROR(ReadMetaGraphDefFromSavedModel(export_dir, tags,\n &bundle->meta_graph_def));\n\n TF_RETURN_IF_ERROR(LoadMetaGraphIntoSession(\n bundle->meta_graph_def, session_options, &bundle->session));\n\n std::vector asset_file_defs;\n TF_RETURN_IF_ERROR(\n GetAssetFileDefs(bundle->meta_graph_def, &asset_file_defs));\n TF_RETURN_IF_ERROR(\n RunRestore(run_options, export_dir,\n bundle->meta_graph_def.saver_def().restore_op_name(),\n bundle->meta_graph_def.saver_def().filename_tensor_name(),\n asset_file_defs, bundle->session.get()));\n \/\/ Record walltime spent in restoring graph from disk, but postpone metric\n \/\/ increments until graph init finishes.\n const uint64 restore_graph_walltime =\n GetLatencyMicroseconds(read_start_microseconds);\n\n const uint64 graph_init_start_microseconds = Env::Default()->NowMicros();\n string init_op_name;\n TF_RETURN_IF_ERROR(\n GetInitOp(export_dir, bundle->meta_graph_def, &init_op_name));\n TF_RETURN_IF_ERROR(RunInitOp(run_options, export_dir, bundle->meta_graph_def,\n asset_file_defs, bundle->session.get(),\n init_op_name));\n load_latency_by_stage->GetCell(export_dir, \"restore_graph\")\n ->Add(restore_graph_walltime);\n \/\/ Record wall time spent in init op.\n load_latency_by_stage->GetCell(export_dir, \"init_graph\")\n ->Add(GetLatencyMicroseconds(graph_init_start_microseconds));\n return Status::OK();\n}\n\n} \/\/ namespace\n\nStatus LoadSavedModel(const SessionOptions& session_options,\n const RunOptions& run_options, const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n \/\/ TODO(robson): Add tests for the counters.\n const uint64 start_microseconds = Env::Default()->NowMicros();\n const Status status = LoadSavedModelInternal(session_options, run_options,\n export_dir, tags, bundle);\n auto log_and_count = [&](const string& status_str) {\n LOG(INFO) << \"SavedModel load for tags { \" << str_util::Join(tags, \" \")\n << \" }; Status: \" << status_str << \". Took \"\n << GetLatencyMicroseconds(start_microseconds) << \" microseconds.\";\n load_attempt_count->GetCell(export_dir, status_str)->IncrementBy(1);\n };\n if (status.ok()) {\n log_and_count(kLoadAttemptSuccess);\n } else {\n log_and_count(kLoadAttemptFail);\n }\n load_latency->GetCell(export_dir)\n ->IncrementBy(GetLatencyMicroseconds(start_microseconds));\n return status;\n}\n\nbool MaybeSavedModelDirectory(const string& export_dir) {\n const string saved_model_pb_path =\n io::JoinPath(export_dir, kSavedModelFilenamePb);\n const string saved_model_pbtxt_path =\n io::JoinPath(export_dir, kSavedModelFilenamePbTxt);\n return Env::Default()->FileExists(saved_model_pb_path).ok() ||\n Env::Default()->FileExists(saved_model_pbtxt_path).ok();\n}\n\n} \/\/ namespace tensorflow\nUse Sampler to record warm up latency distribution (by status).\/* Copyright 2016 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/cc\/saved_model\/loader.h\"\n\n#include \n\n#include \"tensorflow\/cc\/saved_model\/constants.h\"\n#include \"tensorflow\/cc\/saved_model\/reader.h\"\n#include \"tensorflow\/core\/lib\/io\/path.h\"\n#include \"tensorflow\/core\/lib\/monitoring\/counter.h\"\n#include \"tensorflow\/core\/lib\/monitoring\/sampler.h\"\n#include \"tensorflow\/core\/lib\/strings\/str_util.h\"\n#include \"tensorflow\/core\/lib\/strings\/strcat.h\"\n#include \"tensorflow\/core\/platform\/env.h\"\n#include \"tensorflow\/core\/platform\/protobuf_internal.h\"\n#include \"tensorflow\/core\/protobuf\/saved_model.pb.h\"\n#include \"tensorflow\/core\/protobuf\/saver.pb.h\"\n#include \"tensorflow\/core\/public\/session.h\"\n#include \"tensorflow\/core\/public\/session_options.h\"\n#include \"tensorflow\/core\/util\/tensor_bundle\/naming.h\"\n\nnamespace tensorflow {\nnamespace {\n\nauto* load_attempt_count = monitoring::Counter<2>::New(\n \"\/tensorflow\/cc\/saved_model\/load_attempt_count\",\n \"The number of times a SavedModel was successfully loaded.\", \"model_path\",\n \"status\");\nauto* load_latency = monitoring::Counter<1>::New(\n \"\/tensorflow\/cc\/saved_model\/load_latency\",\n \"Latency in microseconds for SavedModels that were successfully loaded.\",\n \"model_path\");\nauto* load_latency_by_stage = monitoring::Sampler<2>::New(\n {\n \"\/tensorflow\/cc\/saved_model\/load_latency_by_stage\", \/\/ metric name\n \"Distribution of wall time spent (in microseconds) in each stage \"\n \"(restore graph from disk, run init graph op, etc) when loading the \"\n \"model\",\n \"model_path\",\n \"stage\",\n },\n \/\/ Scale of 10, power of 1.8 with bucket count 33 (~20 minutes).\n monitoring::Buckets::Exponential(10, 1.8, 33));\n\nconstexpr char kLoadAttemptFail[] = \"fail\";\nconstexpr char kLoadAttemptSuccess[] = \"success\";\n\nuint64 GetLatencyMicroseconds(const uint64 start_microseconds) {\n const uint64 end_microseconds = Env::Default()->NowMicros();\n \/\/ Avoid clock skew.\n if (end_microseconds < start_microseconds) return 0;\n return end_microseconds - start_microseconds;\n}\n\nStatus LoadMetaGraphIntoSession(const MetaGraphDef& meta_graph_def,\n const SessionOptions& session_options,\n std::unique_ptr* session) {\n Session* session_p = nullptr;\n TF_RETURN_IF_ERROR(NewSession(session_options, &session_p));\n session->reset(session_p);\n return (*session)->Create(meta_graph_def.graph_def());\n}\n\nTensor CreateStringTensor(const string& value) {\n Tensor tensor(DT_STRING, TensorShape({}));\n tensor.scalar()() = value;\n return tensor;\n}\n\nvoid AddAssetsTensorsToInputs(const StringPiece export_dir,\n const std::vector& asset_file_defs,\n std::vector>* inputs) {\n if (asset_file_defs.empty()) {\n return;\n }\n for (auto& asset_file_def : asset_file_defs) {\n Tensor assets_file_path_tensor = CreateStringTensor(io::JoinPath(\n export_dir, kSavedModelAssetsDirectory, asset_file_def.filename()));\n inputs->push_back(\n {asset_file_def.tensor_info().name(), assets_file_path_tensor});\n }\n}\n\n\/\/ Like Session::Run(), but uses the Make\/Run\/ReleaseCallable() API to avoid\n\/\/ leaving behind non-GC'ed state.\n\/\/\n\/\/ Detailed motivation behind this approach, from ashankar@:\n\/\/\n\/\/ Each call to Session::Run() that identifies a new subgraph (based on feeds\n\/\/ and fetches) creates some datastructures that live as long as the session\n\/\/ (the partitioned graph, associated executors etc.).\n\/\/\n\/\/ A pathological case of this would be if say the initialization op\n\/\/ (main_op\/legacy_init_op) involves the use of a large constant. Then we\n\/\/ allocate memory for that large constant that will just stick around till the\n\/\/ session dies. With this Callable mechanism, that memory will be released\n\/\/ right after ReleaseCallable returns.\n\/\/\n\/\/ However, the resource manager state remains.\nStatus RunOnce(const RunOptions& run_options,\n const std::vector>& inputs,\n const std::vector& output_tensor_names,\n const std::vector& target_node_names,\n std::vector* outputs, RunMetadata* run_metadata,\n Session* session) {\n CallableOptions callable_options;\n std::vector feed_tensors;\n *callable_options.mutable_run_options() = run_options;\n for (const auto& input : inputs) {\n const string& name = input.first;\n const Tensor& tensor = input.second;\n callable_options.add_feed(name);\n feed_tensors.push_back(tensor);\n }\n for (const string& output_tensor_name : output_tensor_names) {\n callable_options.add_fetch(output_tensor_name);\n }\n for (const string& target_node_name : target_node_names) {\n callable_options.add_target(target_node_name);\n }\n\n Session::CallableHandle callable_handle;\n TF_RETURN_IF_ERROR(session->MakeCallable(callable_options, &callable_handle));\n const Status run_status = session->RunCallable(callable_handle, feed_tensors,\n outputs, run_metadata);\n \/\/ Be sure to call ReleaseCallable() regardless of the outcome of\n \/\/ RunCallable().\n session->ReleaseCallable(callable_handle).IgnoreError();\n return run_status;\n}\n\n\/\/ RunInitOp will return OK if the initialization op was run successfully.\n\/\/ An empty init_op_name indicates that there are no init ops to run.\nStatus RunInitOp(const RunOptions& run_options, const string& export_dir,\n const MetaGraphDef& meta_graph_def,\n const std::vector& asset_file_defs,\n Session* session, const string& init_op_name) {\n if (!init_op_name.empty()) {\n LOG(INFO) << \"Running initialization op on SavedModel bundle.\";\n std::vector> inputs;\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n RunMetadata run_metadata;\n return RunOnce(run_options, inputs, {}, {init_op_name},\n nullptr \/* outputs *\/, &run_metadata, session);\n }\n return Status::OK();\n}\n\n\/\/ A SavedModel may store the name of the initialization op to run in the\n\/\/ in the SignatureDef (v2) or a collection (v1). If an init_op collection\n\/\/ exists, then the collection must contain exactly one op.\nStatus GetInitOp(const string& export_dir, const MetaGraphDef& meta_graph_def,\n string* init_op_name) {\n const auto& sig_def_map = meta_graph_def.signature_def();\n const auto& init_op_sig_it =\n meta_graph_def.signature_def().find(kSavedModelInitOpSignatureKey);\n if (init_op_sig_it != sig_def_map.end()) {\n *init_op_name = init_op_sig_it->second.outputs()\n .find(kSavedModelInitOpSignatureKey)\n ->second.name();\n return Status::OK();\n }\n\n const auto& collection_def_map = meta_graph_def.collection_def();\n string init_op_collection_key;\n if (collection_def_map.find(kSavedModelMainOpKey) !=\n collection_def_map.end()) {\n init_op_collection_key = kSavedModelMainOpKey;\n } else {\n init_op_collection_key = kSavedModelLegacyInitOpKey;\n }\n\n const auto init_op_it = collection_def_map.find(init_op_collection_key);\n if (init_op_it != collection_def_map.end()) {\n if (init_op_it->second.node_list().value_size() != 1) {\n return errors::FailedPrecondition(\n strings::StrCat(\"Expected exactly one main op in : \", export_dir));\n }\n *init_op_name = init_op_it->second.node_list().value(0);\n }\n return Status::OK();\n}\n\nStatus RunRestore(const RunOptions& run_options, const string& export_dir,\n const StringPiece restore_op_name,\n const StringPiece variable_filename_const_op_name,\n const std::vector& asset_file_defs,\n Session* session) {\n LOG(INFO) << \"Restoring SavedModel bundle.\";\n \/\/ Find path to variables to be restored in export directory.\n const string variables_directory =\n io::JoinPath(export_dir, kSavedModelVariablesDirectory);\n \/\/ Check for saver checkpoints in v2 format. Models exported in the checkpoint\n \/\/ v2 format will have a variables.index file. The corresponding\n \/\/ variables are stored in the variables.data-?????-of-????? files.\n const string variables_index_path = io::JoinPath(\n variables_directory, MetaFilename(kSavedModelVariablesFilename));\n if (!Env::Default()->FileExists(variables_index_path).ok()) {\n LOG(INFO) << \"The specified SavedModel has no variables; no checkpoints \"\n \"were restored. File does not exist: \"\n << variables_index_path;\n return Status::OK();\n }\n const string variables_path =\n io::JoinPath(variables_directory, kSavedModelVariablesFilename);\n\n \/\/ Add variables to the graph.\n Tensor variables_path_tensor(DT_STRING, TensorShape({}));\n variables_path_tensor.scalar()() = variables_path;\n\n std::vector> inputs = {\n {string(variable_filename_const_op_name), variables_path_tensor}};\n\n AddAssetsTensorsToInputs(export_dir, asset_file_defs, &inputs);\n\n RunMetadata run_metadata;\n return RunOnce(run_options, inputs, {}, {string(restore_op_name)},\n nullptr \/* outputs *\/, &run_metadata, session);\n}\n\nStatus GetAssetFileDefs(const MetaGraphDef& meta_graph_def,\n std::vector* asset_file_defs) {\n \/\/ With SavedModel v2, we write asset file def into metagraph instead of\n \/\/ collection, so read from metagraph first.\n if (meta_graph_def.asset_file_def_size() > 0) {\n for (const auto& asset : meta_graph_def.asset_file_def()) {\n asset_file_defs->push_back(asset);\n }\n return Status::OK();\n }\n \/\/ Fall back to read from collection to be backward compatible with v1.\n const auto& collection_def_map = meta_graph_def.collection_def();\n const auto assets_it = collection_def_map.find(kSavedModelAssetsKey);\n if (assets_it == collection_def_map.end()) {\n return Status::OK();\n }\n const auto& any_assets = assets_it->second.any_list().value();\n for (const auto& any_asset : any_assets) {\n AssetFileDef asset_file_def;\n TF_RETURN_IF_ERROR(\n ParseAny(any_asset, &asset_file_def, \"tensorflow.AssetFileDef\"));\n asset_file_defs->push_back(asset_file_def);\n }\n return Status::OK();\n}\n\nStatus LoadSavedModelInternal(const SessionOptions& session_options,\n const RunOptions& run_options,\n const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n const uint64 read_start_microseconds = Env::Default()->NowMicros();\n TF_RETURN_IF_ERROR(ReadMetaGraphDefFromSavedModel(export_dir, tags,\n &bundle->meta_graph_def));\n\n TF_RETURN_IF_ERROR(LoadMetaGraphIntoSession(\n bundle->meta_graph_def, session_options, &bundle->session));\n\n std::vector asset_file_defs;\n TF_RETURN_IF_ERROR(\n GetAssetFileDefs(bundle->meta_graph_def, &asset_file_defs));\n TF_RETURN_IF_ERROR(\n RunRestore(run_options, export_dir,\n bundle->meta_graph_def.saver_def().restore_op_name(),\n bundle->meta_graph_def.saver_def().filename_tensor_name(),\n asset_file_defs, bundle->session.get()));\n \/\/ Record walltime spent in restoring graph from disk, but postpone metric\n \/\/ increments until graph init finishes.\n const uint64 restore_graph_walltime =\n GetLatencyMicroseconds(read_start_microseconds);\n\n const uint64 graph_init_start_microseconds = Env::Default()->NowMicros();\n string init_op_name;\n TF_RETURN_IF_ERROR(\n GetInitOp(export_dir, bundle->meta_graph_def, &init_op_name));\n TF_RETURN_IF_ERROR(RunInitOp(run_options, export_dir, bundle->meta_graph_def,\n asset_file_defs, bundle->session.get(),\n init_op_name));\n load_latency_by_stage->GetCell(export_dir, \"restore_graph\")\n ->Add(restore_graph_walltime);\n \/\/ Record wall time spent in init op.\n load_latency_by_stage->GetCell(export_dir, \"init_graph\")\n ->Add(GetLatencyMicroseconds(graph_init_start_microseconds));\n return Status::OK();\n}\n\n} \/\/ namespace\n\nStatus LoadSavedModel(const SessionOptions& session_options,\n const RunOptions& run_options, const string& export_dir,\n const std::unordered_set& tags,\n SavedModelBundle* const bundle) {\n \/\/ TODO(robson): Add tests for the counters.\n const uint64 start_microseconds = Env::Default()->NowMicros();\n const Status status = LoadSavedModelInternal(session_options, run_options,\n export_dir, tags, bundle);\n auto log_and_count = [&](const string& status_str) {\n LOG(INFO) << \"SavedModel load for tags { \" << str_util::Join(tags, \" \")\n << \" }; Status: \" << status_str << \". Took \"\n << GetLatencyMicroseconds(start_microseconds) << \" microseconds.\";\n load_attempt_count->GetCell(export_dir, status_str)->IncrementBy(1);\n };\n if (status.ok()) {\n log_and_count(kLoadAttemptSuccess);\n } else {\n log_and_count(kLoadAttemptFail);\n }\n load_latency->GetCell(export_dir)\n ->IncrementBy(GetLatencyMicroseconds(start_microseconds));\n return status;\n}\n\nbool MaybeSavedModelDirectory(const string& export_dir) {\n const string saved_model_pb_path =\n io::JoinPath(export_dir, kSavedModelFilenamePb);\n const string saved_model_pbtxt_path =\n io::JoinPath(export_dir, kSavedModelFilenamePbTxt);\n return Env::Default()->FileExists(saved_model_pb_path).ok() ||\n Env::Default()->FileExists(saved_model_pbtxt_path).ok();\n}\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/common_shape_fns.h\"\n#include \"tensorflow\/core\/framework\/numeric_op.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/shape_inference.h\"\n\nnamespace tensorflow {\n\nusing shape_inference::DimensionHandle;\nusing shape_inference::InferenceContext;\nusing shape_inference::ShapeHandle;\n\nREGISTER_OP(\"FFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 1);\n })\n .Doc(R\"doc(\nCompute the 1-dimensional discrete Fourier Transform over the inner-most\ndimension of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its 1D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IFFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 1);\n })\n .Doc(R\"doc(\nCompute the inverse 1-dimensional discrete Fourier Transform over the inner-most\ndimension of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its inverse 1D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"FFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 2);\n })\n .Doc(R\"doc(\nCompute the 2-dimensional discrete Fourier Transform over the inner-most\n2 dimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IFFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 2);\n })\n .Doc(R\"doc(\nCompute the inverse 2-dimensional discrete Fourier Transform over the inner-most\n2 dimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their inverse 2D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"FFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 3);\n })\n .Doc(R\"doc(\nCompute the 3-dimensional discrete Fourier Transform over the inner-most 3\ndimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their 3D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IFFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 3);\n })\n .Doc(R\"doc(\nCompute the inverse 3-dimensional discrete Fourier Transform over the inner-most\n3 dimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their inverse 3D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\nStatus RFFTShape(InferenceContext* c, const bool forward, const int rank) {\n ShapeHandle out;\n TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), rank, &out));\n\n \/\/ Check that fft_length has shape [rank].\n ShapeHandle unused_shape;\n DimensionHandle unused_dim;\n ShapeHandle fft_length_input = c->input(1);\n TF_RETURN_IF_ERROR(c->WithRank(fft_length_input, 1, &unused_shape));\n TF_RETURN_IF_ERROR(\n c->WithValue(c->Dim(fft_length_input, 0), rank, &unused_dim));\n const Tensor* fft_length_tensor = c->input_tensor(1);\n\n \/\/ If fft_length is unknown at graph creation time, we can't predict the\n \/\/ output size.\n if (fft_length_tensor == nullptr) {\n \/\/ We can't know the dimension of any of the rank inner dimensions of the\n \/\/ output without knowing fft_length.\n for (int i = 0; i < rank; ++i) {\n TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->UnknownDim(), &out));\n }\n } else {\n auto fft_length_as_vec = fft_length_tensor->vec();\n for (int i = 0; i < rank; ++i) {\n \/\/ For RFFT, replace the last dimension with fft_length\/2 + 1.\n auto dim = forward && i == rank - 1 && fft_length_as_vec(i) != 0\n ? fft_length_as_vec(i) \/ 2 + 1\n : fft_length_as_vec(i);\n TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->MakeDim(dim), &out));\n }\n }\n\n c->set_output(0, out);\n return Status::OK();\n}\n\nREGISTER_OP(\"RFFT\")\n .Input(\"input: float\")\n .Input(\"fft_length: int32\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 1); })\n .Doc(R\"doc(\nCompute the 1-dimensional discrete Fourier Transform of a real-valued signal\nover the inner-most dimension of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the\n`fft_length \/ 2 + 1` unique components of the FFT: the zero-frequency term,\nfollowed by the `fft_length \/ 2` positive-frequency terms.\n\ninput: A float32 tensor.\nfft_length: An int32 tensor of shape [1]. The FFT length.\noutput: A complex64 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length \/ 2 + 1` unique\n frequency components of its 1D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IRFFT\")\n .Input(\"input: complex64\")\n .Input(\"fft_length: int32\")\n .Output(\"output: float\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 1); })\n .Doc(R\"doc(\nCompute the inverse 1-dimensional discrete Fourier Transform of a real-valued\nsignal over the inner-most dimension of `input`.\n\nThe inner-most dimension of `input` is assumed to be the result of `RFFT`: the\n`fft_length \/ 2 + 1` unique components of the DFT of a real-valued signal. If\n`fft_length` is not provided, it is computed from the size of the inner-most\ndimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to\ncompute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\ninput: A complex64 tensor.\nfft_length: An int32 tensor of shape [1]. The FFT length.\noutput: A float32 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length` samples of its inverse\n 1D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"RFFT2D\")\n .Input(\"input: float\")\n .Input(\"fft_length: int32\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 2); })\n .Doc(R\"doc(\nCompute the 2-dimensional discrete Fourier Transform of a real-valued signal\nover the inner-most 2 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the\n`fft_length \/ 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length \/ 2`\npositive-frequency terms.\n\ninput: A float32 tensor.\nfft_length: An int32 tensor of shape [2]. The FFT length for each dimension.\noutput: A complex64 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier Transform. The\n inner-most dimension contains `fft_length \/ 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IRFFT2D\")\n .Input(\"input: complex64\")\n .Input(\"fft_length: int32\")\n .Output(\"output: float\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 2); })\n .Doc(R\"doc(\nCompute the inverse 2-dimensional discrete Fourier Transform of a real-valued\nsignal over the inner-most 2 dimensions of `input`.\n\nThe inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`:\nThe inner-most dimension contains the `fft_length \/ 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 2 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\ninput: A complex64 tensor.\nfft_length: An int32 tensor of shape [2]. The FFT length for each dimension.\noutput: A float32 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 2D Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"RFFT3D\")\n .Input(\"input: float\")\n .Input(\"fft_length: int32\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 3); })\n .Doc(R\"doc(\nCompute the 3-dimensional discrete Fourier Transform of a real-valued signal\nover the inner-most 3 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the\n`fft_length \/ 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length \/ 2`\npositive-frequency terms.\n\ninput: A float32 tensor.\nfft_length: An int32 tensor of shape [3]. The FFT length for each dimension.\noutput: A complex64 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the their 3D Fourier Transform. The\n inner-most dimension contains `fft_length \/ 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IRFFT3D\")\n .Input(\"input: complex64\")\n .Input(\"fft_length: int32\")\n .Output(\"output: float\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 3); })\n .Doc(R\"doc(\nCompute the inverse 3-dimensional discrete Fourier Transform of a real-valued\nsignal over the inner-most 3 dimensions of `input`.\n\nThe inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`:\nThe inner-most dimension contains the `fft_length \/ 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 3 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\ninput: A complex64 tensor.\nfft_length: An int32 tensor of shape [3]. The FFT length for each dimension.\noutput: A float32 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 3D real Fourier Transform.\n\n@compatibility(numpy)\nEquivalent to np.irfftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\n\/\/ Deprecated ops:\nREGISTER_OP(\"BatchFFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use FFT\");\nREGISTER_OP(\"BatchIFFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use IFFT\");\nREGISTER_OP(\"BatchFFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use FFT2D\");\nREGISTER_OP(\"BatchIFFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use IFFT2D\");\nREGISTER_OP(\"BatchFFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use FFT3D\");\nREGISTER_OP(\"BatchIFFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use IFFT3D\");\n\n} \/\/ namespace tensorflow\nRemove extra blank lines from auto-generated Python documentation. Change: 152046128\/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \"tensorflow\/core\/framework\/common_shape_fns.h\"\n#include \"tensorflow\/core\/framework\/numeric_op.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/shape_inference.h\"\n\nnamespace tensorflow {\n\nusing shape_inference::DimensionHandle;\nusing shape_inference::InferenceContext;\nusing shape_inference::ShapeHandle;\n\nREGISTER_OP(\"FFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 1);\n })\n .Doc(R\"doc(\nFast Fourier transform.\n\nComputes the 1-dimensional discrete Fourier transform over the inner-most\ndimension of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IFFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 1);\n })\n .Doc(R\"doc(\nInverse fast Fourier transform.\n\nComputes the inverse 1-dimensional discrete Fourier transform over the\ninner-most dimension of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most\n dimension of `input` is replaced with its inverse 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"FFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 2);\n })\n .Doc(R\"doc(\n2D fast Fourier transform.\n\nComputes the 2-dimensional discrete Fourier transform over the inner-most\n2 dimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IFFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 2);\n })\n .Doc(R\"doc(\nInverse 2D fast Fourier transform.\n\nComputes the inverse 2-dimensional discrete Fourier transform over the\ninner-most 2 dimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 2\n dimensions of `input` are replaced with their inverse 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"FFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 3);\n })\n .Doc(R\"doc(\n3D fast Fourier transform.\n\nComputes the 3-dimensional discrete Fourier transform over the inner-most 3\ndimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their 3D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.fftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IFFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) {\n return shape_inference::UnchangedShapeWithRankAtLeast(c, 3);\n })\n .Doc(R\"doc(\nInverse 3D fast Fourier transform.\n\nComputes the inverse 3-dimensional discrete Fourier transform over the\ninner-most 3 dimensions of `input`.\n\ninput: A complex64 tensor.\noutput: A complex64 tensor of the same shape as `input`. The inner-most 3\n dimensions of `input` are replaced with their inverse 3D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.ifftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\nStatus RFFTShape(InferenceContext* c, const bool forward, const int rank) {\n ShapeHandle out;\n TF_RETURN_IF_ERROR(c->WithRankAtLeast(c->input(0), rank, &out));\n\n \/\/ Check that fft_length has shape [rank].\n ShapeHandle unused_shape;\n DimensionHandle unused_dim;\n ShapeHandle fft_length_input = c->input(1);\n TF_RETURN_IF_ERROR(c->WithRank(fft_length_input, 1, &unused_shape));\n TF_RETURN_IF_ERROR(\n c->WithValue(c->Dim(fft_length_input, 0), rank, &unused_dim));\n const Tensor* fft_length_tensor = c->input_tensor(1);\n\n \/\/ If fft_length is unknown at graph creation time, we can't predict the\n \/\/ output size.\n if (fft_length_tensor == nullptr) {\n \/\/ We can't know the dimension of any of the rank inner dimensions of the\n \/\/ output without knowing fft_length.\n for (int i = 0; i < rank; ++i) {\n TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->UnknownDim(), &out));\n }\n } else {\n auto fft_length_as_vec = fft_length_tensor->vec();\n for (int i = 0; i < rank; ++i) {\n \/\/ For RFFT, replace the last dimension with fft_length\/2 + 1.\n auto dim = forward && i == rank - 1 && fft_length_as_vec(i) != 0\n ? fft_length_as_vec(i) \/ 2 + 1\n : fft_length_as_vec(i);\n TF_RETURN_IF_ERROR(c->ReplaceDim(out, -rank + i, c->MakeDim(dim), &out));\n }\n }\n\n c->set_output(0, out);\n return Status::OK();\n}\n\nREGISTER_OP(\"RFFT\")\n .Input(\"input: float\")\n .Input(\"fft_length: int32\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 1); })\n .Doc(R\"doc(\nReal-valued fast Fourier transform.\n\nComputes the 1-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most dimension of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT` only returns the\n`fft_length \/ 2 + 1` unique components of the FFT: the zero-frequency term,\nfollowed by the `fft_length \/ 2` positive-frequency terms.\n\ninput: A float32 tensor.\nfft_length: An int32 tensor of shape [1]. The FFT length.\noutput: A complex64 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length \/ 2 + 1` unique\n frequency components of its 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IRFFT\")\n .Input(\"input: complex64\")\n .Input(\"fft_length: int32\")\n .Output(\"output: float\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 1); })\n .Doc(R\"doc(\nInverse real-valued fast Fourier transform.\n\nComputes the inverse 1-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most dimension of `input`.\n\nThe inner-most dimension of `input` is assumed to be the result of `RFFT`: the\n`fft_length \/ 2 + 1` unique components of the DFT of a real-valued signal. If\n`fft_length` is not provided, it is computed from the size of the inner-most\ndimension of `input` (`fft_length = 2 * (inner - 1)`). If the FFT length used to\ncompute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\ninput: A complex64 tensor.\nfft_length: An int32 tensor of shape [1]. The FFT length.\noutput: A float32 tensor of the same rank as `input`. The inner-most\n dimension of `input` is replaced with the `fft_length` samples of its inverse\n 1D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"RFFT2D\")\n .Input(\"input: float\")\n .Input(\"fft_length: int32\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 2); })\n .Doc(R\"doc(\n2D real-valued fast Fourier transform.\n\nComputes the 2-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most 2 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT2D` only returns the\n`fft_length \/ 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length \/ 2`\npositive-frequency terms.\n\ninput: A float32 tensor.\nfft_length: An int32 tensor of shape [2]. The FFT length for each dimension.\noutput: A complex64 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with their 2D Fourier transform. The\n inner-most dimension contains `fft_length \/ 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IRFFT2D\")\n .Input(\"input: complex64\")\n .Input(\"fft_length: int32\")\n .Output(\"output: float\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 2); })\n .Doc(R\"doc(\nInverse 2D real-valued fast Fourier transform.\n\nComputes the inverse 2-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most 2 dimensions of `input`.\n\nThe inner-most 2 dimensions of `input` are assumed to be the result of `RFFT2D`:\nThe inner-most dimension contains the `fft_length \/ 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 2 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\ninput: A complex64 tensor.\nfft_length: An int32 tensor of shape [2]. The FFT length for each dimension.\noutput: A float32 tensor of the same rank as `input`. The inner-most 2\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 2D Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.fft.irfft2\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"RFFT3D\")\n .Input(\"input: float\")\n .Input(\"fft_length: int32\")\n .Output(\"output: complex64\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, true, 3); })\n .Doc(R\"doc(\n3D real-valued fast Fourier transform.\n\nComputes the 3-dimensional discrete Fourier transform of a real-valued signal\nover the inner-most 3 dimensions of `input`.\n\nSince the DFT of a real signal is Hermitian-symmetric, `RFFT3D` only returns the\n`fft_length \/ 2 + 1` unique components of the FFT for the inner-most dimension\nof `output`: the zero-frequency term, followed by the `fft_length \/ 2`\npositive-frequency terms.\n\ninput: A float32 tensor.\nfft_length: An int32 tensor of shape [3]. The FFT length for each dimension.\noutput: A complex64 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the their 3D Fourier transform. The\n inner-most dimension contains `fft_length \/ 2 + 1` unique frequency\n components.\n\n@compatibility(numpy)\nEquivalent to np.fft.rfftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\nREGISTER_OP(\"IRFFT3D\")\n .Input(\"input: complex64\")\n .Input(\"fft_length: int32\")\n .Output(\"output: float\")\n .SetShapeFn([](InferenceContext* c) { return RFFTShape(c, false, 3); })\n .Doc(R\"doc(\nInverse 3D real-valued fast Fourier transform.\n\nComputes the inverse 3-dimensional discrete Fourier transform of a real-valued\nsignal over the inner-most 3 dimensions of `input`.\n\nThe inner-most 3 dimensions of `input` are assumed to be the result of `RFFT3D`:\nThe inner-most dimension contains the `fft_length \/ 2 + 1` unique components of\nthe DFT of a real-valued signal. If `fft_length` is not provided, it is computed\nfrom the size of the inner-most 3 dimensions of `input`. If the FFT length used\nto compute `input` is odd, it should be provided since it cannot be inferred\nproperly.\n\ninput: A complex64 tensor.\nfft_length: An int32 tensor of shape [3]. The FFT length for each dimension.\noutput: A float32 tensor of the same rank as `input`. The inner-most 3\n dimensions of `input` are replaced with the `fft_length` samples of their\n inverse 3D real Fourier transform.\n\n@compatibility(numpy)\nEquivalent to np.irfftn with 3 dimensions.\n@end_compatibility\n)doc\");\n\n\/\/ Deprecated ops:\nREGISTER_OP(\"BatchFFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use FFT\");\nREGISTER_OP(\"BatchIFFT\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use IFFT\");\nREGISTER_OP(\"BatchFFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use FFT2D\");\nREGISTER_OP(\"BatchIFFT2D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use IFFT2D\");\nREGISTER_OP(\"BatchFFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use FFT3D\");\nREGISTER_OP(\"BatchIFFT3D\")\n .Input(\"input: complex64\")\n .Output(\"output: complex64\")\n .Deprecated(15, \"Use IFFT3D\");\n\n} \/\/ namespace tensorflow\n<|endoftext|>"} {"text":"\/\/ SUBS-04.WeirdCombinations.cpp\n\/\/ https:\/\/judge.softuni.bg\/Contests\/37\/CSharp-Basics-Exam-7-November-2014\n#include \n#include \n#include \nusing namespace std;\n\nconst int numSysBase = 5 ;\n\nint main ()\n{ \/\/ numeral system based solution. The author uses nested loops.\n\tstring s ;\n\tint n,\n\t\tqtyDigits ;\n\tstack digits ;\n\tchar result [numSysBase] ;\n\tcin >>s >>n;\n\t\n\tdo\t\n\t{\t\/\/ moves to stack a last digit\n\t\tdigits.push(n%numSysBase) ;\n\t\tn = n\/numSysBase ; \/\/ remove last digit\n\t} while (n != 0) ;\n\t\n\tqtyDigits = digits.size() ; \n\tif (qtyDigits > numSysBase)\n\t{\n\t\tcout <<\"No\" ;\n\t\treturn 0 ;\n\t} ;\n\t\n\tfor (int k=0; kminor\/\/ SUBS-04.WeirdCombinations.cpp\n\/\/ https:\/\/judge.softuni.bg\/Contests\/37\/CSharp-Basics-Exam-7-November-2014\n#include \n\/\/ https:\/\/bg.wikipedia.org\/wiki\/%D0%A1%D1%82%D0%B5%D0%BA_(%D1%81%D1%82%D1%80%D1%83%D0%BA%D1%82%D1%83%D1%80%D0%B0_%D0%BE%D1%82_%D0%B4%D0%B0%D0%BD%D0%BD%D0%B8)\n\/\/ https:\/\/www.youtube.com\/watch?v=5UjENioK8tw\n#include \n#include \/\/ Koala Press - SIMVOLNI NIZOVE - p 123.\nusing namespace std;\n\nconst int numSysBase = 5 ;\n\nint main ()\n{ \/\/ numeral system based solution. The author uses nested loops.\n\tstring s ;\n\tint n,\n\t\tqtyDigits ;\n\tstack digits ;\n\tchar result [numSysBase] ;\n\tcin >>s >>n;\n\t\n\tdo\t\n\t{\t\/\/ moves to stack a last digit\n\t\tdigits.push(n%numSysBase) ;\n\t\tn = n\/numSysBase ; \/\/ remove last digit\n\t} while (n != 0) ;\n\t\n\tqtyDigits = digits.size() ; \n\tif (qtyDigits > numSysBase)\n\t{\n\t\tcout <<\"No\" ;\n\t\treturn 0 ;\n\t} ;\n\t\n\tfor (int k=0; k"} {"text":"#include \"s3.h\"\nusing namespace himan;\n\n#ifdef HAVE_S3\n#include \"debug.h\"\n#include \"timer.h\"\n#include \"util.h\"\n#include \n#include \n#include \n#include \/\/ memcpy\n\nnamespace\n{\nstatic std::once_flag oflag;\n\nconst char* access_key = 0;\nconst char* secret_key = 0;\nconst char* security_token = 0;\nS3Protocol protocol = S3ProtocolHTTP;\n\nthread_local S3Status statusG = S3StatusOK;\n\nvoid CheckS3Error(S3Status errarg, const char* file, const int line);\n\n#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)\n\nvoid HandleS3Error(himan::logger& logr, const std::string& host, const std::string& object, const std::string& op)\n{\n\tlogr.Error(fmt::format(\"{} operation to\/from host={} object=s3:\/\/{} failed\", op, host, object));\n\n\tswitch (statusG)\n\t{\n\t\tcase S3StatusInternalError:\n\t\t\tlogr.Error(fmt::format(\"{}: is there a proxy blocking the connection?\", S3_get_status_name(statusG)));\n\t\t\tthrow himan::kFileDataNotFound;\n\t\tcase S3StatusFailedToConnect:\n\t\t\tlogr.Error(fmt::format(\"{}: is proxy required but not set?\", S3_get_status_name(statusG)));\n\t\t\tthrow himan::kFileDataNotFound;\n\t\tcase S3StatusErrorInvalidAccessKeyId:\n\t\t\tlogr.Error(fmt::format(\n\t\t\t \"{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?\",\n\t\t\t S3_get_status_name(statusG)));\n\t\t\tthrow himan::kFileDataNotFound;\n\t\tdefault:\n\t\t\tlogr.Error(S3_get_status_name(statusG));\n\t\t\tthrow himan::kFileDataNotFound;\n\t}\n}\n\nstd::vector GetBucketAndFileName(const std::string& fullFileName)\n{\n\tstd::vector ret;\n\n\tauto fileName = fullFileName;\n\n\t\/\/ strip protocol from string if it's there\n\tconst auto pos = fullFileName.find(\"s3:\/\/\");\n\n\tif (pos != std::string::npos)\n\t{\n\t\tfileName = fileName.erase(pos, 5);\n\t}\n\n\t\/\/ erase forward slash if exists (s3 buckets can't start with \/)\n\tif (fileName[0] == '\/')\n\t{\n\t\tfileName = fileName.erase(0, 1);\n\t}\n\n\tauto tokens = util::Split(fileName, \"\/\");\n\n\tret.push_back(tokens[0]);\n\ttokens.erase(std::begin(tokens), std::begin(tokens) + 1);\n\n\tstd::string key;\n\tfor (const auto& piece : tokens)\n\t{\n\t\tif (!key.empty())\n\t\t{\n\t\t\tkey += \"\/\";\n\t\t}\n\t\tkey += piece;\n\t}\n\n\tret.push_back(key);\n\treturn ret;\n}\n\ninline void CheckS3Error(S3Status errarg, const char* file, const int line)\n{\n\tif (errarg)\n\t{\n\t\tstd::cerr << \"Error at \" << file << \"(\" << line << \"): \" << S3_get_status_name(errarg) << std::endl;\n\t\thiman::Abort();\n\t}\n}\n\nS3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)\n{\n\treturn S3StatusOK;\n}\n\nstatic void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)\n{\n\tstatusG = status;\n\treturn;\n}\n\nthread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};\n\nstatic S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)\n{\n\thiman::buffer* ret = static_cast(callbackData);\n\n\tret->data = static_cast(realloc(ret->data, ret->length + bufferSize));\n\tmemcpy(ret->data + ret->length, buffer, bufferSize);\n\tret->length += bufferSize;\n\n\treturn S3StatusOK;\n}\n\nvoid Initialize()\n{\n\tcall_once(oflag, [&]() {\n\t\taccess_key = getenv(\"S3_ACCESS_KEY_ID\");\n\t\tsecret_key = getenv(\"S3_SECRET_ACCESS_KEY\");\n\t\tsecurity_token = getenv(\"S3_SESSION_TOKEN\");\n\n\t\tlogger logr(\"s3\");\n\n\t\tif (!access_key)\n\t\t{\n\t\t\tlogr.Info(\"Environment variable S3_ACCESS_KEY_ID not defined\");\n\t\t}\n\n\t\tif (!secret_key)\n\t\t{\n\t\t\tlogr.Info(\"Environment variable S3_SECRET_ACCESS_KEY not defined\");\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tconst auto envproto = himan::util::GetEnv(\"S3_PROTOCOL\");\n\t\t\tif (envproto == \"https\")\n\t\t\t{\n\t\t\t\tprotocol = S3ProtocolHTTPS;\n\t\t\t}\n\t\t\telse if (envproto == \"http\")\n\t\t\t{\n\t\t\t\tprotocol = S3ProtocolHTTP;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogr.Warning(fmt::format(\"Unrecognized value found from env variable S3_PROTOCOL: '{}'\", envproto));\n\t\t\t}\n\t\t}\n\t\tcatch (const std::invalid_argument& e)\n\t\t{\n\t\t}\n\n\t\tS3_CHECK(S3_initialize(\"s3\", S3_INIT_ALL, NULL));\n\t});\n}\n\nstd::string ReadAWSRegionFromHostname(const std::string& hostname)\n{\n\tif (hostname.find(\"amazonaws.com\") != std::string::npos)\n\t{\n\t\t\/\/ extract region name from host name, assuming aws hostname like\n\t\t\/\/ s3.us-east-1.amazonaws.com\n\n\t\tauto tokens = util::Split(hostname, \".\");\n\n\t\tlogger logr(\"s3\");\n\n\t\tif (tokens.size() != 4)\n\t\t{\n\t\t\tlogr.Fatal(\"Hostname does not follow pattern s3..amazonaws.com\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogr.Trace(fmt::format(\"s3 authentication hostname: {}\", tokens[1]));\n\t\t\treturn tokens[1];\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nstruct write_data\n{\n\thiman::buffer buffer;\n\tsize_t write_ptr;\n};\n\nstatic int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)\n{\n\twrite_data* data = static_cast(callbackData);\n\tint bytesWritten = 0;\n\n\tif (data->buffer.length)\n\t{\n\t\tbytesWritten =\n\t\t static_cast((static_cast(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);\n\t\tmemcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);\n\t\tdata->write_ptr += bytesWritten;\n\t\tdata->buffer.length -= bytesWritten;\n\t}\n\n\treturn bytesWritten;\n}\n\n} \/\/ namespace\n\nbuffer s3::ReadFile(const file_information& fileInformation)\n{\n\tInitialize();\n\tlogger logr(\"s3\");\n\n\tS3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};\n\n\tconst auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);\n\tconst auto bucket = bucketAndFileName[0];\n\tconst auto key = bucketAndFileName[1];\n\n\tbuffer ret;\n\n#ifdef S3_DEFAULT_REGION\n\n\tstd::string region = ReadAWSRegionFromHostname(fileInformation.file_server);\n\n\t\/\/ clang-format off\n\n S3BucketContext bucketContext =\n {\n fileInformation.file_server.c_str(),\n bucket.c_str(),\n protocol,\n S3UriStylePath,\n access_key,\n secret_key,\n security_token,\n region.c_str()\n };\n#else\n\n\t\/\/ clang-format off\n\n\tS3BucketContext bucketContext = \n\t{\n\t\tfileInformation.file_server.c_str(),\n\t\tbucket.c_str(),\n\t\tprotocol,\n\t\tS3UriStylePath,\n\t\taccess_key,\n\t\tsecret_key,\n\t\tsecurity_token\n\t};\n\n\t\/\/ clang-format on\n#endif\n\n\tint count = 0;\n\tdo\n\t{\n\t\tif (count > 0)\n\t\t{\n\t\t\tsleep(2 * count);\n\t\t}\n\t\tconst unsigned long offset = fileInformation.offset.get();\n\t\tconst unsigned long length = fileInformation.length.get();\n\n#ifdef S3_DEFAULT_REGION\n\t\tS3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);\n#else\n\t\tS3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);\n#endif\n\t\tcount++;\n\t} while (S3_status_is_retryable(statusG) && count < 3);\n\n\tswitch (statusG)\n\t{\n\t\tcase S3StatusOK:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tHandleS3Error(logr, fileInformation.file_server, fmt::format(\"{}\/{}\", bucket, key), \"Read\");\n\t\t\tbreak;\n\t}\n\n\tif (ret.length == 0)\n\t{\n\t\tthrow himan::kFileDataNotFound;\n\t}\n\n\treturn ret;\n}\n\nvoid s3::WriteObject(const std::string& objectName, const buffer& buff)\n{\n\tInitialize();\n\n\tconst auto bucketAndFileName = GetBucketAndFileName(objectName);\n\tconst auto bucket = bucketAndFileName[0];\n\tconst auto key = bucketAndFileName[1];\n\n\tconst char* host = getenv(\"S3_HOSTNAME\");\n\n\tlogger logr(\"s3\");\n\n\tif (!host)\n\t{\n\t\tlogr.Fatal(\"Environment variable S3_HOSTNAME not defined\");\n\t\thiman::Abort();\n\t}\n\n#ifdef S3_DEFAULT_REGION\n\n\tstd::string region = ReadAWSRegionFromHostname(std::string(host));\n\n\t\/\/ clang-format off\n\n S3BucketContext bucketContext =\n {\n host,\n bucket.c_str(),\n protocol,\n S3UriStylePath,\n access_key,\n secret_key,\n security_token,\n region.c_str()\n };\n#else\n\n\t\/\/ clang-format off\n\n\tS3BucketContext bucketContext =\n\t{\n\t\thost,\n\t\tbucket.c_str(),\n\t\tprotocol,\n\t\tS3UriStylePath,\n\t\taccess_key,\n\t\tsecret_key,\n\t\tsecurity_token\n\t};\n#endif\n\n\t\/\/ clang-format on\n\n\tS3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};\n\n\twrite_data data;\n\tdata.buffer.data = buff.data;\n\tdata.buffer.length = buff.length;\n\tdata.write_ptr = 0;\n\n\ttimer t(true);\n\n\tint count = 0;\n\tdo\n\t{\n\t\tif (count > 0)\n\t\t{\n\t\t\tsleep(2 * count);\n\t\t}\n\n#ifdef S3_DEFAULT_REGION\n\t\tS3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);\n#else\n\t\tS3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);\n#endif\n\n\t\tcount++;\n\t} while (S3_status_is_retryable(statusG) && count < 3);\n\n\t\/\/ remove pointer to original buff so that double free doesn't occur\n\tdata.buffer.data = 0;\n\n\tswitch (statusG)\n\t{\n\t\tcase S3StatusOK:\n\t\t{\n\t\t\tt.Stop();\n\t\t\tconst double time = static_cast(t.GetTime());\n\t\t\tconst double size = util::round(static_cast(buff.length) \/ 1024. \/ 1024., 1);\n\t\t\tlogr.Info(fmt::format(\"Wrote {} MB in {} ms ({:.1f} MBps) to file s3:\/\/{}\/{}\", size, time, size \/ time,\n\t\t\t bucket, key));\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tHandleS3Error(logr, host, fmt::format(\"{}\/{}\", bucket, key), \"Write\");\n\t\t\tbreak;\n\t}\n}\n\n#else\nbuffer s3::ReadFile(const file_information& fileInformation)\n{\n\tthrow std::runtime_error(\"S3 support not compiled\");\n}\nvoid s3::WriteObject(const std::string& objectName, const buffer& buff)\n{\n\tthrow std::runtime_error(\"S3 support not compiled\");\n}\n#endif\nCorrect calculation of transmission speed#include \"s3.h\"\nusing namespace himan;\n\n#ifdef HAVE_S3\n#include \"debug.h\"\n#include \"timer.h\"\n#include \"util.h\"\n#include \n#include \n#include \n#include \/\/ memcpy\n\nnamespace\n{\nstatic std::once_flag oflag;\n\nconst char* access_key = 0;\nconst char* secret_key = 0;\nconst char* security_token = 0;\nS3Protocol protocol = S3ProtocolHTTP;\n\nthread_local S3Status statusG = S3StatusOK;\n\nvoid CheckS3Error(S3Status errarg, const char* file, const int line);\n\n#define S3_CHECK(errarg) CheckS3Error(errarg, __FILE__, __LINE__)\n\nvoid HandleS3Error(himan::logger& logr, const std::string& host, const std::string& object, const std::string& op)\n{\n\tlogr.Error(fmt::format(\"{} operation to\/from host={} object=s3:\/\/{} failed\", op, host, object));\n\n\tswitch (statusG)\n\t{\n\t\tcase S3StatusInternalError:\n\t\t\tlogr.Error(fmt::format(\"{}: is there a proxy blocking the connection?\", S3_get_status_name(statusG)));\n\t\t\tthrow himan::kFileDataNotFound;\n\t\tcase S3StatusFailedToConnect:\n\t\t\tlogr.Error(fmt::format(\"{}: is proxy required but not set?\", S3_get_status_name(statusG)));\n\t\t\tthrow himan::kFileDataNotFound;\n\t\tcase S3StatusErrorInvalidAccessKeyId:\n\t\t\tlogr.Error(fmt::format(\n\t\t\t \"{}: are Temporary Security Credentials used without security token (env: S3_SESSION_TOKEN)?\",\n\t\t\t S3_get_status_name(statusG)));\n\t\t\tthrow himan::kFileDataNotFound;\n\t\tdefault:\n\t\t\tlogr.Error(S3_get_status_name(statusG));\n\t\t\tthrow himan::kFileDataNotFound;\n\t}\n}\n\nstd::vector GetBucketAndFileName(const std::string& fullFileName)\n{\n\tstd::vector ret;\n\n\tauto fileName = fullFileName;\n\n\t\/\/ strip protocol from string if it's there\n\tconst auto pos = fullFileName.find(\"s3:\/\/\");\n\n\tif (pos != std::string::npos)\n\t{\n\t\tfileName = fileName.erase(pos, 5);\n\t}\n\n\t\/\/ erase forward slash if exists (s3 buckets can't start with \/)\n\tif (fileName[0] == '\/')\n\t{\n\t\tfileName = fileName.erase(0, 1);\n\t}\n\n\tauto tokens = util::Split(fileName, \"\/\");\n\n\tret.push_back(tokens[0]);\n\ttokens.erase(std::begin(tokens), std::begin(tokens) + 1);\n\n\tstd::string key;\n\tfor (const auto& piece : tokens)\n\t{\n\t\tif (!key.empty())\n\t\t{\n\t\t\tkey += \"\/\";\n\t\t}\n\t\tkey += piece;\n\t}\n\n\tret.push_back(key);\n\treturn ret;\n}\n\ninline void CheckS3Error(S3Status errarg, const char* file, const int line)\n{\n\tif (errarg)\n\t{\n\t\tstd::cerr << \"Error at \" << file << \"(\" << line << \"): \" << S3_get_status_name(errarg) << std::endl;\n\t\thiman::Abort();\n\t}\n}\n\nS3Status responsePropertiesCallback(const S3ResponseProperties* properties, void* callbackData)\n{\n\treturn S3StatusOK;\n}\n\nstatic void responseCompleteCallback(S3Status status, const S3ErrorDetails* error, void* callbackData)\n{\n\tstatusG = status;\n\treturn;\n}\n\nthread_local S3ResponseHandler responseHandler = {&responsePropertiesCallback, &responseCompleteCallback};\n\nstatic S3Status getObjectDataCallback(int bufferSize, const char* buffer, void* callbackData)\n{\n\thiman::buffer* ret = static_cast(callbackData);\n\n\tret->data = static_cast(realloc(ret->data, ret->length + bufferSize));\n\tmemcpy(ret->data + ret->length, buffer, bufferSize);\n\tret->length += bufferSize;\n\n\treturn S3StatusOK;\n}\n\nvoid Initialize()\n{\n\tcall_once(oflag, [&]() {\n\t\taccess_key = getenv(\"S3_ACCESS_KEY_ID\");\n\t\tsecret_key = getenv(\"S3_SECRET_ACCESS_KEY\");\n\t\tsecurity_token = getenv(\"S3_SESSION_TOKEN\");\n\n\t\tlogger logr(\"s3\");\n\n\t\tif (!access_key)\n\t\t{\n\t\t\tlogr.Info(\"Environment variable S3_ACCESS_KEY_ID not defined\");\n\t\t}\n\n\t\tif (!secret_key)\n\t\t{\n\t\t\tlogr.Info(\"Environment variable S3_SECRET_ACCESS_KEY not defined\");\n\t\t}\n\n\t\ttry\n\t\t{\n\t\t\tconst auto envproto = himan::util::GetEnv(\"S3_PROTOCOL\");\n\t\t\tif (envproto == \"https\")\n\t\t\t{\n\t\t\t\tprotocol = S3ProtocolHTTPS;\n\t\t\t}\n\t\t\telse if (envproto == \"http\")\n\t\t\t{\n\t\t\t\tprotocol = S3ProtocolHTTP;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tlogr.Warning(fmt::format(\"Unrecognized value found from env variable S3_PROTOCOL: '{}'\", envproto));\n\t\t\t}\n\t\t}\n\t\tcatch (const std::invalid_argument& e)\n\t\t{\n\t\t}\n\n\t\tS3_CHECK(S3_initialize(\"s3\", S3_INIT_ALL, NULL));\n\t});\n}\n\nstd::string ReadAWSRegionFromHostname(const std::string& hostname)\n{\n\tif (hostname.find(\"amazonaws.com\") != std::string::npos)\n\t{\n\t\t\/\/ extract region name from host name, assuming aws hostname like\n\t\t\/\/ s3.us-east-1.amazonaws.com\n\n\t\tauto tokens = util::Split(hostname, \".\");\n\n\t\tlogger logr(\"s3\");\n\n\t\tif (tokens.size() != 4)\n\t\t{\n\t\t\tlogr.Fatal(\"Hostname does not follow pattern s3..amazonaws.com\");\n\t\t}\n\t\telse\n\t\t{\n\t\t\tlogr.Trace(fmt::format(\"s3 authentication hostname: {}\", tokens[1]));\n\t\t\treturn tokens[1];\n\t\t}\n\t}\n\n\treturn \"\";\n}\n\nstruct write_data\n{\n\thiman::buffer buffer;\n\tsize_t write_ptr;\n};\n\nstatic int putObjectDataCallback(int bufferSize, char* buffer, void* callbackData)\n{\n\twrite_data* data = static_cast(callbackData);\n\tint bytesWritten = 0;\n\n\tif (data->buffer.length)\n\t{\n\t\tbytesWritten =\n\t\t static_cast((static_cast(data->buffer.length) > bufferSize) ? bufferSize : data->buffer.length);\n\t\tmemcpy(buffer, data->buffer.data + data->write_ptr, bytesWritten);\n\t\tdata->write_ptr += bytesWritten;\n\t\tdata->buffer.length -= bytesWritten;\n\t}\n\n\treturn bytesWritten;\n}\n\n} \/\/ namespace\n\nbuffer s3::ReadFile(const file_information& fileInformation)\n{\n\tInitialize();\n\tlogger logr(\"s3\");\n\n\tS3GetObjectHandler getObjectHandler = {responseHandler, &getObjectDataCallback};\n\n\tconst auto bucketAndFileName = GetBucketAndFileName(fileInformation.file_location);\n\tconst auto bucket = bucketAndFileName[0];\n\tconst auto key = bucketAndFileName[1];\n\n\tbuffer ret;\n\n#ifdef S3_DEFAULT_REGION\n\n\tstd::string region = ReadAWSRegionFromHostname(fileInformation.file_server);\n\n\t\/\/ clang-format off\n\n S3BucketContext bucketContext =\n {\n fileInformation.file_server.c_str(),\n bucket.c_str(),\n protocol,\n S3UriStylePath,\n access_key,\n secret_key,\n security_token,\n region.c_str()\n };\n#else\n\n\t\/\/ clang-format off\n\n\tS3BucketContext bucketContext = \n\t{\n\t\tfileInformation.file_server.c_str(),\n\t\tbucket.c_str(),\n\t\tprotocol,\n\t\tS3UriStylePath,\n\t\taccess_key,\n\t\tsecret_key,\n\t\tsecurity_token\n\t};\n\n\t\/\/ clang-format on\n#endif\n\n\tint count = 0;\n\tdo\n\t{\n\t\tif (count > 0)\n\t\t{\n\t\t\tsleep(2 * count);\n\t\t}\n\t\tconst unsigned long offset = fileInformation.offset.get();\n\t\tconst unsigned long length = fileInformation.length.get();\n\n#ifdef S3_DEFAULT_REGION\n\t\tS3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, 0, &getObjectHandler, &ret);\n#else\n\t\tS3_get_object(&bucketContext, key.c_str(), NULL, offset, length, NULL, &getObjectHandler, &ret);\n#endif\n\t\tcount++;\n\t} while (S3_status_is_retryable(statusG) && count < 3);\n\n\tswitch (statusG)\n\t{\n\t\tcase S3StatusOK:\n\t\t\tbreak;\n\t\tdefault:\n\t\t\tHandleS3Error(logr, fileInformation.file_server, fmt::format(\"{}\/{}\", bucket, key), \"Read\");\n\t\t\tbreak;\n\t}\n\n\tif (ret.length == 0)\n\t{\n\t\tthrow himan::kFileDataNotFound;\n\t}\n\n\treturn ret;\n}\n\nvoid s3::WriteObject(const std::string& objectName, const buffer& buff)\n{\n\tInitialize();\n\n\tconst auto bucketAndFileName = GetBucketAndFileName(objectName);\n\tconst auto bucket = bucketAndFileName[0];\n\tconst auto key = bucketAndFileName[1];\n\n\tconst char* host = getenv(\"S3_HOSTNAME\");\n\n\tlogger logr(\"s3\");\n\n\tif (!host)\n\t{\n\t\tlogr.Fatal(\"Environment variable S3_HOSTNAME not defined\");\n\t\thiman::Abort();\n\t}\n\n#ifdef S3_DEFAULT_REGION\n\n\tstd::string region = ReadAWSRegionFromHostname(std::string(host));\n\n\t\/\/ clang-format off\n\n S3BucketContext bucketContext =\n {\n host,\n bucket.c_str(),\n protocol,\n S3UriStylePath,\n access_key,\n secret_key,\n security_token,\n region.c_str()\n };\n#else\n\n\t\/\/ clang-format off\n\n\tS3BucketContext bucketContext =\n\t{\n\t\thost,\n\t\tbucket.c_str(),\n\t\tprotocol,\n\t\tS3UriStylePath,\n\t\taccess_key,\n\t\tsecret_key,\n\t\tsecurity_token\n\t};\n#endif\n\n\t\/\/ clang-format on\n\n\tS3PutObjectHandler putObjectHandler = {responseHandler, &putObjectDataCallback};\n\n\twrite_data data;\n\tdata.buffer.data = buff.data;\n\tdata.buffer.length = buff.length;\n\tdata.write_ptr = 0;\n\n\ttimer t(true);\n\n\tint count = 0;\n\tdo\n\t{\n\t\tif (count > 0)\n\t\t{\n\t\t\tsleep(2 * count);\n\t\t}\n\n#ifdef S3_DEFAULT_REGION\n\t\tS3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, 0, &putObjectHandler, &data);\n#else\n\t\tS3_put_object(&bucketContext, key.c_str(), buff.length, NULL, NULL, &putObjectHandler, &data);\n#endif\n\n\t\tcount++;\n\t} while (S3_status_is_retryable(statusG) && count < 3);\n\n\t\/\/ remove pointer to original buff so that double free doesn't occur\n\tdata.buffer.data = 0;\n\n\tswitch (statusG)\n\t{\n\t\tcase S3StatusOK:\n\t\t{\n\t\t\tt.Stop();\n\t\t\tconst double time = static_cast(t.GetTime());\n\t\t\tconst double size = util::round(static_cast(buff.length) \/ 1024. \/ 1024., 1);\n\t\t\tlogr.Info(fmt::format(\"Wrote {} MB in {} ms ({:.1f} MBps) to file s3:\/\/{}\/{}\", size, time,\n\t\t\t size \/ (time * 0.001), bucket, key));\n\t\t}\n\t\tbreak;\n\t\tdefault:\n\t\t\tHandleS3Error(logr, host, fmt::format(\"{}\/{}\", bucket, key), \"Write\");\n\t\t\tbreak;\n\t}\n}\n\n#else\nbuffer s3::ReadFile(const file_information& fileInformation)\n{\n\tthrow std::runtime_error(\"S3 support not compiled\");\n}\nvoid s3::WriteObject(const std::string& objectName, const buffer& buff)\n{\n\tthrow std::runtime_error(\"S3 support not compiled\");\n}\n#endif\n<|endoftext|>"} {"text":"\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_tdataframe\n\/\/\/ \\notebook -draw\n\/\/\/ This tutorial shows how VecOps can be used to slim down the programming\n\/\/\/ model typically adopted in HEP for analysis.\n\/\/\/ In this case we have a dataset containing the kinematic properties of\n\/\/\/ particles stored in individual arrays.\n\/\/\/ We want to plot the transverse momentum of these particles if the energy is\n\/\/\/ greater than 100.\n\/\/\/\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\date March 2018\n\/\/\/ \\author Danilo Piparo, Andre Vieira Silva\n\nR__LOAD_LIBRARY(libVecOps);\n\nauto filename = gROOT->GetTutorialDir() + \"\/dataframe\/tdf017_vecOpsHEP.root\";\nauto treename = \"myDataset\";\nusing doubles = ROOT::Experimental::VecOps::TVec;\nusing TDF = ROOT::Experimental::TDataFrame;\n\nvoid WithTTreeReader()\n{\n TFile f(filename);\n TTreeReader tr(treename, &f);\n TTreeReaderArray px(tr, \"px\");\n TTreeReaderArray py(tr, \"py\");\n TTreeReaderArray E(tr, \"E\");\n\n TH1F h(\"pt\", \"pt\", 16, 0, 4);\n\n while (tr.Next()) {\n for (auto i=0U;i < px.GetSize(); ++i) {\n if (E[i] > 100) h.Fill(sqrt(px[i]*px[i] + py[i]*py[i]));\n }\n }\n h.DrawCopy();\n}\n\nvoid WithTDataFrame()\n{\n TDF f(treename, filename.Data());\n auto CalcPt = [](doubles &px, doubles &py, doubles &E) {\n doubles v;\n for (auto i=0U;i < px.size(); ++i) {\n if (E[i] > 100) {\n v.emplace_back(sqrt(px[i]*px[i] + py[i]*py[i]));\n }\n }\n return v;\n };\n f.Define(\"pt\", CalcPt, {\"px\", \"py\", \"E\"})\n .Histo1D({\"pt\", \"pt\", 16, 0, 4}, \"pt\")->DrawCopy();\n}\n\nvoid WithTDataFrameVecOps()\n{\n TDF f(treename, filename.Data());\n auto CalcPt = [](doubles &px, doubles &py, doubles &E) {\n auto pt = sqrt(px*px + py*py);\n return pt[E>100];\n };\n f.Define(\"good_pt\", CalcPt, {\"px\", \"py\", \"E\"})\n .Histo1D({\"pt\", \"pt\", 16, 0, 4}, \"good_pt\")->DrawCopy();\n}\n\nvoid WithTDataFrameVecOpsJit()\n{\n TDF f(treename, filename.Data());\n f.Define(\"good_pt\", \"sqrt(px*px + py*py)[E>100]\")\n .Histo1D({\"pt\", \"pt\", 16, 0, 4}, \"good_pt\")->DrawCopy();\n}\n\nvoid tdf017_vecOpsHEP()\n{\n \/\/ We plot four times the same quantity, the key is to look into the implementation\n \/\/ of the functions above\n auto c = new TCanvas();\n c->Divide(2,2);\n c->cd(1);\n WithTTreeReader();\n c->cd(2);\n WithTDataFrame();\n c->cd(3);\n WithTDataFrameVecOps();\n c->cd(4);\n WithTDataFrameVecOpsJit();\n}\n[VecOps] Remove workaround for loading manually the library\/\/\/ \\file\n\/\/\/ \\ingroup tutorial_tdataframe\n\/\/\/ \\notebook -draw\n\/\/\/ This tutorial shows how VecOps can be used to slim down the programming\n\/\/\/ model typically adopted in HEP for analysis.\n\/\/\/ In this case we have a dataset containing the kinematic properties of\n\/\/\/ particles stored in individual arrays.\n\/\/\/ We want to plot the transverse momentum of these particles if the energy is\n\/\/\/ greater than 100.\n\/\/\/\n\/\/\/ \\macro_code\n\/\/\/\n\/\/\/ \\date March 2018\n\/\/\/ \\author Danilo Piparo, Andre Vieira Silva\n\nauto filename = gROOT->GetTutorialDir() + \"\/dataframe\/tdf017_vecOpsHEP.root\";\nauto treename = \"myDataset\";\nusing doubles = ROOT::Experimental::VecOps::TVec;\nusing TDF = ROOT::Experimental::TDataFrame;\n\nvoid WithTTreeReader()\n{\n TFile f(filename);\n TTreeReader tr(treename, &f);\n TTreeReaderArray px(tr, \"px\");\n TTreeReaderArray py(tr, \"py\");\n TTreeReaderArray E(tr, \"E\");\n\n TH1F h(\"pt\", \"pt\", 16, 0, 4);\n\n while (tr.Next()) {\n for (auto i=0U;i < px.GetSize(); ++i) {\n if (E[i] > 100) h.Fill(sqrt(px[i]*px[i] + py[i]*py[i]));\n }\n }\n h.DrawCopy();\n}\n\nvoid WithTDataFrame()\n{\n TDF f(treename, filename.Data());\n auto CalcPt = [](doubles &px, doubles &py, doubles &E) {\n doubles v;\n for (auto i=0U;i < px.size(); ++i) {\n if (E[i] > 100) {\n v.emplace_back(sqrt(px[i]*px[i] + py[i]*py[i]));\n }\n }\n return v;\n };\n f.Define(\"pt\", CalcPt, {\"px\", \"py\", \"E\"})\n .Histo1D({\"pt\", \"pt\", 16, 0, 4}, \"pt\")->DrawCopy();\n}\n\nvoid WithTDataFrameVecOps()\n{\n TDF f(treename, filename.Data());\n auto CalcPt = [](doubles &px, doubles &py, doubles &E) {\n auto pt = sqrt(px*px + py*py);\n return pt[E>100];\n };\n f.Define(\"good_pt\", CalcPt, {\"px\", \"py\", \"E\"})\n .Histo1D({\"pt\", \"pt\", 16, 0, 4}, \"good_pt\")->DrawCopy();\n}\n\nvoid WithTDataFrameVecOpsJit()\n{\n TDF f(treename, filename.Data());\n f.Define(\"good_pt\", \"sqrt(px*px + py*py)[E>100]\")\n .Histo1D({\"pt\", \"pt\", 16, 0, 4}, \"good_pt\")->DrawCopy();\n}\n\nvoid tdf017_vecOpsHEP()\n{\n \/\/ We plot four times the same quantity, the key is to look into the implementation\n \/\/ of the functions above\n auto c = new TCanvas();\n c->Divide(2,2);\n c->cd(1);\n WithTTreeReader();\n c->cd(2);\n WithTDataFrame();\n c->cd(3);\n WithTDataFrameVecOps();\n c->cd(4);\n WithTDataFrameVecOpsJit();\n}\n<|endoftext|>"} {"text":"void MdApi::OnDisconnected(int reason)\n{\n\tTask task = Task();\n\ttask.task_name = ONDISCONNECTED;\n\ttask.task_extra = reason;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnError(XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONERROR;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBMARKETDATA;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBMARKETDATA;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnDepthMarketData(XTPMD *market_data, int bid1_qty int bid1_count, int max_bid1_count, int ask1_qty int ask1_count, int max_ask1_count)\n{\n\tTask task = Task();\n\ttask.task_name = ONDEPTHMARKETDATA;\n\tif (market_data)\n\t{\n\t\tXTPMD *task_data = new XTPMD();\n\t\t*task_data = *market_data;\n\t\ttask.task_data = task_data;\n\t}\n\ttask.task_extra = bid1_qty;\n\ttask.task_extra = bid1_count;\n\ttask.task_extra = max_bid1_count;\n\ttask.task_extra = ask1_qty;\n\ttask.task_extra = ask1_count;\n\ttask.task_extra = max_ask1_count;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBORDERBOOK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBORDERBOOK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnOrderBook(XTPOB *order_book)\n{\n\tTask task = Task();\n\ttask.task_name = ONORDERBOOK;\n\tif (order_book)\n\t{\n\t\tXTPOB *task_data = new XTPOB();\n\t\t*task_data = *order_book;\n\t\ttask.task_data = task_data;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBTICKBYTICK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBTICKBYTICK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnTickByTick(XTPTBT *tbt_data)\n{\n\tTask task = Task();\n\ttask.task_name = ONTICKBYTICK;\n\tif (tbt_data)\n\t{\n\t\tXTPTBT *task_data = new XTPTBT();\n\t\t*task_data = *tbt_data;\n\t\ttask.task_data = task_data;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllMarketData(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllMarketData(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOrderBook(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOrderBook(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllTickByTick(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllTickByTick(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnQueryAllTickers(XTPQSI* ticker_info, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONQUERYALLTICKERS;\n\tif (ticker_info)\n\t{\n\t\tXTPQSI *task_data = new XTPQSI();\n\t\t*task_data = *ticker_info;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnQueryTickersPriceInfo(XTPTPI* ticker_info, XTPRI *error_info, bool is_last)\n{\n\tTask task = Task();\n\ttask.task_name = ONQUERYTICKERSPRICEINFO;\n\tif (ticker_info)\n\t{\n\t\tXTPTPI *task_data = new XTPTPI();\n\t\t*task_data = *ticker_info;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOptionMarketData(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLOPTIONMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOptionMarketData(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLOPTIONMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOptionOrderBook(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLOPTIONORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOptionOrderBook(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLOPTIONORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOptionTickByTick(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLOPTIONTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOptionTickByTick(int exchange_id, XTPRI *error_info)\n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLOPTIONTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nUpdate xtp_md_source_task.cppvoid MdApi::OnDisconnected(int reason) \n{\n\tTask task = Task();\n\ttask.task_name = ONDISCONNECTED;\n\ttask.task_extra = reason;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnError(XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONERROR;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBMARKETDATA;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubMarketData(XTPST *ticker, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBMARKETDATA;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnDepthMarketData(XTPMD *market_data, int64_t bid1_qty[], int32_t bid1_count, int32_t max_bid1_count, int64_t ask1_qty[], int32_t ask1_count, int32_t max_ask1_count) \n{\n\tTask task = Task();\n\ttask.task_name = ONDEPTHMARKETDATA;\n\tif (market_data)\n\t{\n\t\tXTPMD *task_data = new XTPMD();\n\t\t*task_data = *market_data;\n\t\ttask.task_data = task_data;\n\t}\n\ttask.task_extra = bid1_qty;\n\ttask.task_extra = bid1_count;\n\ttask.task_extra = max_bid1_count;\n\ttask.task_extra = ask1_qty;\n\ttask.task_extra = ask1_count;\n\ttask.task_extra = max_ask1_count;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBORDERBOOK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubOrderBook(XTPST *ticker, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBORDERBOOK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnOrderBook(XTPOB *order_book) \n{\n\tTask task = Task();\n\ttask.task_name = ONORDERBOOK;\n\tif (order_book)\n\t{\n\t\tXTPOB *task_data = new XTPOB();\n\t\t*task_data = *order_book;\n\t\ttask.task_data = task_data;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBTICKBYTICK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubTickByTick(XTPST *ticker, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBTICKBYTICK;\n\tif (ticker)\n\t{\n\t\tXTPST *task_data = new XTPST();\n\t\t*task_data = *ticker;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnTickByTick(XTPTBT *tbt_data) \n{\n\tTask task = Task();\n\ttask.task_name = ONTICKBYTICK;\n\tif (tbt_data)\n\t{\n\t\tXTPTBT *task_data = new XTPTBT();\n\t\t*task_data = *tbt_data;\n\t\ttask.task_data = task_data;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnQueryAllTickers(XTPQSI* ticker_info, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONQUERYALLTICKERS;\n\tif (ticker_info)\n\t{\n\t\tXTPQSI *task_data = new XTPQSI();\n\t\t*task_data = *ticker_info;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnQueryTickersPriceInfo(XTPTPI* ticker_info, XTPRI *error_info, bool is_last) \n{\n\tTask task = Task();\n\ttask.task_name = ONQUERYTICKERSPRICEINFO;\n\tif (ticker_info)\n\t{\n\t\tXTPTPI *task_data = new XTPTPI();\n\t\t*task_data = *ticker_info;\n\t\ttask.task_data = task_data;\n\t}\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\ttask.task_last = is_last;\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOptionMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLOPTIONMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOptionMarketData(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLOPTIONMARKETDATA;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOptionOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLOPTIONORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOptionOrderBook(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLOPTIONORDERBOOK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnSubscribeAllOptionTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONSUBSCRIBEALLOPTIONTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\nvoid MdApi::OnUnSubscribeAllOptionTickByTick(XTP_EXCHANGE_TYPE exchange_id, XTPRI *error_info) \n{\n\tTask task = Task();\n\ttask.task_name = ONUNSUBSCRIBEALLOPTIONTICKBYTICK;\n\ttask.task_extra = (int) exchange_id;\n\tif (error_info)\n\t{\n\t\tXTPRI *task_error = new XTPRI();\n\t\t*task_error = *error_info;\n\t\ttask.task_error = task_error;\n\t}\n\tthis->task_queue.push(task);\n};\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: getfilenamewrapper.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: obo $ $Date: 2006-10-12 10:53:22 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_fpicker.hxx\"\n\n\/\/------------------------------------------------------------------------\n\/\/ includes\n\/\/------------------------------------------------------------------------\n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#ifndef _GETFILENAMEWRAPPER_HXX_\n#include \"getfilenamewrapper.hxx\"\n#endif\n\n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#include \n#include \n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\nnamespace \/* private *\/\n{\n\n \/\/-----------------------------------------------\n \/\/\n \/\/-----------------------------------------------\n\n struct GetFileNameParam\n {\n GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) :\n m_bOpen(bOpen),\n m_lpofn(lpofn),\n m_bRet(false),\n m_ExtErr(0)\n {}\n\n bool m_bOpen;\n LPOPENFILENAME m_lpofn;\n bool m_bRet;\n int m_ExtErr;\n };\n\n \/\/-----------------------------------------------\n \/\/\n \/\/-----------------------------------------------\n\n unsigned __stdcall ThreadProc(void* pParam)\n {\n GetFileNameParam* lpgfnp =\n reinterpret_cast(pParam);\n\n HRESULT hr = OleInitialize( NULL );\n\n if (lpgfnp->m_bOpen)\n lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn);\n else\n lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn);\n\n lpgfnp->m_ExtErr = CommDlgExtendedError();\n\n if ( SUCCEEDED( hr ) )\n OleUninitialize();\n\n return 0;\n }\n\n \/\/-----------------------------------------------\n \/\/ exceutes GetOpenFileName\/GetSaveFileName in\n \/\/ a separat thread\n \/\/-----------------------------------------------\n\n bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, \/*out*\/ int& ExtErr)\n {\n GetFileNameParam gfnp(bOpen,lpofn);\n unsigned id;\n\n HANDLE hThread = reinterpret_cast(\n _beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id));\n\n OSL_POSTCOND(hThread, \"could not create STA thread\");\n\n WaitForSingleObject(hThread, INFINITE);\n CloseHandle(hThread);\n\n ExtErr = gfnp.m_ExtErr;\n\n return gfnp.m_bRet;\n }\n\n \/\/-----------------------------------------------\n \/\/ This function returns true if the calling\n \/\/ thread belongs to a Multithreaded Appartment\n \/\/ (MTA)\n \/\/-----------------------------------------------\n\n bool IsMTA()\n {\n HRESULT hr = CoInitialize(NULL);\n\n if (RPC_E_CHANGED_MODE == hr)\n return true;\n\n if(SUCCEEDED(hr))\n CoUninitialize();\n\n return false;\n }\n\n} \/\/ namespace private\n\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nCGetFileNameWrapper::CGetFileNameWrapper() :\n m_ExtendedDialogError(0)\n{\n}\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nbool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn)\n{\n OSL_PRECOND(lpofn,\"invalid parameter\");\n\n bool bRet = false;\n\n if (IsMTA())\n {\n bRet = ThreadExecGetFileName(\n lpofn, true, m_ExtendedDialogError);\n }\n else\n {\n HRESULT hr = OleInitialize( NULL );\n\n bRet = GetOpenFileName(lpofn);\n m_ExtendedDialogError = CommDlgExtendedError();\n\n if ( SUCCEEDED( hr ) )\n OleUninitialize();\n }\n\n return bRet;\n}\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nbool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn)\n{\n OSL_PRECOND(lpofn,\"invalid parameter\");\n\n bool bRet = false;\n\n if (IsMTA())\n {\n bRet = ThreadExecGetFileName(\n lpofn, false, m_ExtendedDialogError);\n }\n else\n {\n bRet = GetSaveFileName(lpofn);\n m_ExtendedDialogError = CommDlgExtendedError();\n }\n\n return bRet;\n}\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nint CGetFileNameWrapper::commDlgExtendedError( )\n{\n return m_ExtendedDialogError;\n}\n\nINTEGRATION: CWS fwk56 (1.8.22); FILE MERGED 2006\/11\/28 09:26:47 mav 1.8.22.2: #i21747# fix long path handling 2006\/11\/15 14:42:49 mav 1.8.22.1: #i21747# preserv the current directory value\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: getfilenamewrapper.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: ihi $ $Date: 2006-12-19 13:54:09 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_fpicker.hxx\"\n\n\/\/------------------------------------------------------------------------\n\/\/ includes\n\/\/------------------------------------------------------------------------\n\n#include \n\n#ifndef _OSL_DIAGNOSE_H_\n#include \n#endif\n\n#ifndef _GETFILENAMEWRAPPER_HXX_\n#include \"getfilenamewrapper.hxx\"\n#endif\n\n#if defined _MSC_VER\n#pragma warning(push, 1)\n#endif\n#include \n#include \n#if defined _MSC_VER\n#pragma warning(pop)\n#endif\n\nnamespace \/* private *\/\n{\n\n \/\/-----------------------------------------------\n \/\/ This class prevents changing of the working\n \/\/ directory.\n \/\/-----------------------------------------------\n class CurDirGuard\n {\n BOOL m_bValid;\n wchar_t* m_pBuffer;\n DWORD m_nBufLen;\n\n public:\n CurDirGuard()\n : m_bValid( FALSE )\n , m_pBuffer( NULL )\n , m_nBufLen( 0 )\n {\n m_nBufLen = GetCurrentDirectoryW( 0, NULL );\n if ( m_nBufLen )\n {\n m_pBuffer = new wchar_t[m_nBufLen];\n m_bValid = ( GetCurrentDirectoryW( m_nBufLen, m_pBuffer ) == ( m_nBufLen - 1 ) );\n }\n }\n\n ~CurDirGuard()\n {\n BOOL bDirSet = FALSE;\n\n if ( m_pBuffer )\n {\n if ( m_bValid )\n {\n if ( m_nBufLen - 1 > MAX_PATH )\n {\n if ( (LONG32)GetVersion() < 0 )\n {\n \/\/ this is Win 98\/ME branch, such a long path can not be set\n \/\/ use the system path as fallback later\n }\n else\n {\n DWORD nNewLen = m_nBufLen + 8;\n wchar_t* pNewBuffer = new wchar_t[nNewLen];\n if ( m_nBufLen > 3 && m_pBuffer[0] == (wchar_t)'\\\\' && m_pBuffer[1] == (wchar_t)'\\\\' )\n {\n if ( m_pBuffer[2] == (wchar_t)'?' )\n _snwprintf( pNewBuffer, nNewLen, L\"%s\", m_pBuffer );\n else\n _snwprintf( pNewBuffer, nNewLen, L\"\\\\\\\\?\\\\UNC\\\\%s\", m_pBuffer+2 );\n }\n else\n _snwprintf( pNewBuffer, nNewLen, L\"\\\\\\\\?\\\\%s\", m_pBuffer );\n bDirSet = SetCurrentDirectoryW( pNewBuffer );\n\n delete [] pNewBuffer;\n }\n }\n else\n bDirSet = SetCurrentDirectoryW( m_pBuffer );\n }\n\n delete [] m_pBuffer;\n m_pBuffer = NULL;\n }\n\n if ( !bDirSet )\n {\n \/\/ the fallback solution\n wchar_t pPath[MAX_PATH+1];\n if ( GetWindowsDirectoryW( pPath, MAX_PATH+1 ) <= MAX_PATH )\n {\n SetCurrentDirectoryW( pPath );\n }\n else\n {\n \/\/ the system path is also too long?!!\n }\n }\n }\n };\n\n \/\/-----------------------------------------------\n \/\/\n \/\/-----------------------------------------------\n\n struct GetFileNameParam\n {\n GetFileNameParam(bool bOpen, LPOPENFILENAME lpofn) :\n m_bOpen(bOpen),\n m_lpofn(lpofn),\n m_bRet(false),\n m_ExtErr(0)\n {}\n\n bool m_bOpen;\n LPOPENFILENAME m_lpofn;\n bool m_bRet;\n int m_ExtErr;\n };\n\n \/\/-----------------------------------------------\n \/\/\n \/\/-----------------------------------------------\n\n unsigned __stdcall ThreadProc(void* pParam)\n {\n CurDirGuard aGuard;\n\n GetFileNameParam* lpgfnp =\n reinterpret_cast(pParam);\n\n HRESULT hr = OleInitialize( NULL );\n\n if (lpgfnp->m_bOpen)\n lpgfnp->m_bRet = GetOpenFileName(lpgfnp->m_lpofn);\n else\n lpgfnp->m_bRet = GetSaveFileName(lpgfnp->m_lpofn);\n\n lpgfnp->m_ExtErr = CommDlgExtendedError();\n\n if ( SUCCEEDED( hr ) )\n OleUninitialize();\n\n return 0;\n }\n\n \/\/-----------------------------------------------\n \/\/ exceutes GetOpenFileName\/GetSaveFileName in\n \/\/ a separat thread\n \/\/-----------------------------------------------\n\n bool ThreadExecGetFileName(LPOPENFILENAME lpofn, bool bOpen, \/*out*\/ int& ExtErr)\n {\n GetFileNameParam gfnp(bOpen,lpofn);\n unsigned id;\n\n HANDLE hThread = reinterpret_cast(\n _beginthreadex(0, 0, ThreadProc, &gfnp, 0, &id));\n\n OSL_POSTCOND(hThread, \"could not create STA thread\");\n\n WaitForSingleObject(hThread, INFINITE);\n CloseHandle(hThread);\n\n ExtErr = gfnp.m_ExtErr;\n\n return gfnp.m_bRet;\n }\n\n \/\/-----------------------------------------------\n \/\/ This function returns true if the calling\n \/\/ thread belongs to a Multithreaded Appartment\n \/\/ (MTA)\n \/\/-----------------------------------------------\n\n bool IsMTA()\n {\n HRESULT hr = CoInitialize(NULL);\n\n if (RPC_E_CHANGED_MODE == hr)\n return true;\n\n if(SUCCEEDED(hr))\n CoUninitialize();\n\n return false;\n }\n\n} \/\/ namespace private\n\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nCGetFileNameWrapper::CGetFileNameWrapper() :\n m_ExtendedDialogError(0)\n{\n}\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nbool CGetFileNameWrapper::getOpenFileName(LPOPENFILENAME lpofn)\n{\n OSL_PRECOND(lpofn,\"invalid parameter\");\n\n bool bRet = false;\n\n if (IsMTA())\n {\n bRet = ThreadExecGetFileName(\n lpofn, true, m_ExtendedDialogError);\n }\n else\n {\n CurDirGuard aGuard;\n\n HRESULT hr = OleInitialize( NULL );\n\n bRet = GetOpenFileName(lpofn);\n m_ExtendedDialogError = CommDlgExtendedError();\n\n if ( SUCCEEDED( hr ) )\n OleUninitialize();\n }\n\n return bRet;\n}\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nbool CGetFileNameWrapper::getSaveFileName(LPOPENFILENAME lpofn)\n{\n OSL_PRECOND(lpofn,\"invalid parameter\");\n\n bool bRet = false;\n\n if (IsMTA())\n {\n bRet = ThreadExecGetFileName(\n lpofn, false, m_ExtendedDialogError);\n }\n else\n {\n CurDirGuard aGuard;\n\n bRet = GetSaveFileName(lpofn);\n m_ExtendedDialogError = CommDlgExtendedError();\n }\n\n return bRet;\n}\n\n\/\/-----------------------------------------------\n\/\/\n\/\/-----------------------------------------------\n\nint CGetFileNameWrapper::commDlgExtendedError( )\n{\n return m_ExtendedDialogError;\n}\n\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cybertron\/transport\/qos\/qos_profile_conf.h\"\n\nnamespace apollo {\nnamespace cybertron {\nnamespace transport {\n\nQosProfileConf::QosProfileConf() {}\n\nQosProfileConf::~QosProfileConf() {}\n\nQosProfile QosProfileConf::CreateQosProfile(\n const QosHistoryPolicy& history, size_t depth, size_t mps,\n const QosReliabilityPolicy& reliability,\n const QosDurabilityPolicy& durability) {\n QosProfile qos_profile;\n qos_profile.set_history(history);\n qos_profile.set_depth(depth);\n qos_profile.set_mps(mps);\n qos_profile.set_reliability(reliability);\n qos_profile.set_durability(durability);\n\n return qos_profile;\n}\n\nconst size_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0;\nconst size_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0;\n\nconst QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 2000, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_BEST_EFFORT,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT =\n CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10,\n QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile(\n QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT,\n QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\n} \/\/ namespace transport\n} \/\/ namespace cybertron\n} \/\/ namespace apollo\nframework: change default history depth to 1\/******************************************************************************\n * Copyright 2018 The Apollo Authors. All Rights Reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *****************************************************************************\/\n\n#include \"cybertron\/transport\/qos\/qos_profile_conf.h\"\n\nnamespace apollo {\nnamespace cybertron {\nnamespace transport {\n\nQosProfileConf::QosProfileConf() {}\n\nQosProfileConf::~QosProfileConf() {}\n\nQosProfile QosProfileConf::CreateQosProfile(\n const QosHistoryPolicy& history, size_t depth, size_t mps,\n const QosReliabilityPolicy& reliability,\n const QosDurabilityPolicy& durability) {\n QosProfile qos_profile;\n qos_profile.set_history(history);\n qos_profile.set_depth(depth);\n qos_profile.set_mps(mps);\n qos_profile.set_reliability(reliability);\n qos_profile.set_durability(durability);\n\n return qos_profile;\n}\n\nconst size_t QosProfileConf::QOS_HISTORY_DEPTH_SYSTEM_DEFAULT = 0;\nconst size_t QosProfileConf::QOS_MPS_SYSTEM_DEFAULT = 0;\n\nconst QosProfile QosProfileConf::QOS_PROFILE_DEFAULT = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 1, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_SENSOR_DATA = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 5, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_BEST_EFFORT,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_PARAMETERS = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_SERVICES_DEFAULT =\n CreateQosProfile(QosHistoryPolicy::HISTORY_KEEP_LAST, 10,\n QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_PARAM_EVENT = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_LAST, 1000, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_VOLATILE);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_SYSTEM_DEFAULT = CreateQosProfile(\n QosHistoryPolicy::HISTORY_SYSTEM_DEFAULT, QOS_HISTORY_DEPTH_SYSTEM_DEFAULT,\n QOS_MPS_SYSTEM_DEFAULT, QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_TF_STATIC = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\nconst QosProfile QosProfileConf::QOS_PROFILE_TOPO_CHANGE = CreateQosProfile(\n QosHistoryPolicy::HISTORY_KEEP_ALL, 10, QOS_MPS_SYSTEM_DEFAULT,\n QosReliabilityPolicy::RELIABILITY_RELIABLE,\n QosDurabilityPolicy::DURABILITY_TRANSIENT_LOCAL);\n\n} \/\/ namespace transport\n} \/\/ namespace cybertron\n} \/\/ namespace apollo\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"kernel.h\"\n#include \"ilwisdata.h\"\n#include \"ilwiscontext.h\"\n#include \"errorobject.h\"\n#include \"issuelogger.h\"\n\nusing namespace Ilwis;\n\nstd::map IssueLogger::_silentThreads;\n\nIssueObject::IssueObject()\n{\n}\n\nIlwis::IssueObject::IssueObject(const QString &message, int it, quint64 id)\n{\n _message = message;\n _itype = it;\n _itime = QDateTime::currentDateTime();\n _id = id;\n}\n\nQString Ilwis::IssueObject::message() const\n{\n return _message;\n}\n\nQDateTime Ilwis::IssueObject::time() const\n{\n return _itime;\n}\n\nint Ilwis::IssueObject::type() const\n{\n return _itype;\n}\n\nQString Ilwis::IssueObject::logMessage(Ilwis::IssueObject::LogMessageFormat) const{\n return QString(\"%1: (%2) %3\").arg(type2String(), _itime.toString(), _message);\n}\n\nint IssueObject::codeLine() const {\n return _line;\n}\n\nQString IssueObject::codeFunc() const {\n return _func;\n}\n\nQString IssueObject::codeFile() const {\n return _file;\n}\n\nvoid IssueObject::addCodeInfo(int line, const QString &func, const QString &file)\n{\n _line = line;\n _func = func;\n _file = file;\n}\n\nvoid IssueObject::stream(std::ofstream& stream, LogMessageFormat frmt) {\n stream << std::setw(4) << _id << \" ; \" << std::setw(9) << type2String().toStdString() << \" ; \" << std::setw(27)<<_itime.toString().toStdString() << \" ; \" << _message.toStdString() << std::endl;\n if ( frmt == lmCODE) {\n stream << std::setw(4) << _id << \" ; \" << _line << \" : \" << _func.toStdString() << \" ; \" << _file.toStdString() << std::endl;\n }\n}\n\n\n\nquint64 IssueObject::id() const\n{\n return _id;\n}\n\nQString IssueObject::type2String() const{\n switch(_itype) {\n case itCritical:\n return \"Critical\";\n case itError:\n return \"Error\";\n case itWarning:\n return \"Warning\";\n case itMessage:\n return \"Message\";\n case itDebug:\n return \"Debug\";\n }\n return \"Text\";\n}\n\n\/\/---------------------------------------------------------------------------\nIssueLogger::IssueLogger(QObject *parent) : QObject(parent), _repeatCount(0)\n{\n QString apploc= context()->ilwisFolder().absoluteFilePath();\n apploc += \"\/log\";\n QDir dir(apploc);\n if ( !dir.exists())\n dir.mkdir(apploc);\n QString rlogFilePath = apploc + \"\/logfile.txt\";\n QString clogFilePath = apploc + \"\/logfile_ext.txt\";\n _logFileRegular.open(rlogFilePath.toLatin1());\n _logFileCode.open(clogFilePath.toLatin1());\n}\n\nIssueLogger::~IssueLogger()\n{\n if (_logFileCode.is_open())\n _logFileCode.close();\n if ( _logFileRegular.is_open())\n _logFileRegular.close();\n}\n\nquint64 IssueLogger::log(const QString &message, int it)\n{\n ++_repeatCount;\n std::thread::id id = std::this_thread::get_id();\n if ( _silentThreads.find(id)!= _silentThreads.end() && it != IssueObject::itCritical)\n return i64UNDEF;\n\n\n if ( _lastmessage == message && _repeatCount == 10) {\n return _issueId;\n } else {\n if ( _repeatCount > 10 && _lastmessage != message ){\n _issues.enqueue(IssueObject(QString(\"Message repeated %1 times\").arg(_repeatCount), it, _issueId));\n throw ErrorObject(\"Error message cascade\");\n }\n _repeatCount = 0;\n }\n\n _issues.enqueue(IssueObject(message, it, _issueId));\n if ( _lastmessage == message)\n return _issueId;\n IssueObject& obj = _issues.back();\n if ( _logFileRegular.is_open()) {\n obj.stream(_logFileRegular, IssueObject::lmREGULAR);\n }\n emit ilwiserrormessage(obj.logMessage());\n\n _lastmessage = message;\n return _issueId++;\n}\n\nquint64 IssueLogger::log(const QString& objectName, const QString &message, int it)\n{\n QString newmessage = objectName + \":\" + message;\n return log(newmessage, it);\n}\n\nvoid IssueLogger::addCodeInfo(quint64 issueid, int line, const QString &func, const QString &file)\n{\n for(auto iter=_issues.begin(); iter != _issues.end(); ++iter) {\n IssueObject& issue = *iter;\n if ( issue.id() == issueid) {\n issue.addCodeInfo(line, func, file);\n if ( _logFileCode.is_open()) {\n issue.stream(_logFileCode, IssueObject::lmCODE);\n }\n break;\n }\n }\n}\n\nbool IssueLogger::silent() const\n{\n std::thread::id id = std::this_thread::get_id();\n auto iter = _silentThreads.find(id);\n if ( iter != _silentThreads.end())\n return iter->second;\n return false;\n}\n\nvoid IssueLogger::silent(bool yesno)\n{\n std::thread::id id = std::this_thread::get_id();\n if ( yesno == false){\n auto iter = _silentThreads.find(id) ;\n if (iter != _silentThreads.end())\n _silentThreads.erase(iter);\n }else\n _silentThreads[id] = true;\n}\n\nquint64 IssueLogger::logSql(const QSqlError &err)\n{\n return log(err.text(), IssueObject::itError);\n}\n\nIssueObject::IssueType IssueLogger::maxIssueLevel() const\n{\n int type = IssueObject::itNone;\n foreach(IssueObject issue, _issues) {\n type |= issue.type();\n }\n if ( type & IssueObject::itCritical)\n return IssueObject::itCritical;\n if ( type & IssueObject::itError)\n return IssueObject::itError;\n if ( type & IssueObject::itWarning)\n return IssueObject::itWarning;\n if ( type & IssueObject::itMessage)\n return IssueObject::itMessage;\n return IssueObject::itNone;\n}\n\nvoid IssueLogger::copy(IssueLogger &other)\n{\n foreach(IssueObject issue, _issues) {\n other._issues.enqueue(issue);\n }\n}\n\nQString IssueLogger::popfirst(int tp) {\n if ( tp != IssueObject::itAll){\n for(auto iter= --_issues.end(); iter != _issues.begin(); --iter ){\n if (hasType((*iter).type(), tp)){\n QString mes = (*iter).message();\n _issues.erase(iter);\n return mes;\n }\n }\n }\n if ( _issues.size() > 0)\n return _issues.dequeue().message();\n return \"?\";\n}\n\nQString IssueLogger::poplast(int tp) {\n if ( tp != IssueObject::itAll){\n for(auto iter= _issues.begin(); iter != _issues.end(); ++iter ){\n if (hasType((*iter).type(), tp)){\n QString mes = (*iter).message();\n _issues.erase(iter);\n return mes;\n }\n }\n }\n if ( _issues.size() >0 )\n return _issues.takeLast().message();\n return \"?\";\n}\n\nvoid IssueLogger::clear() {\n _issues.clear();\n}\n\n\n\nadded comment about the error cascade mechanism#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"kernel.h\"\n#include \"ilwisdata.h\"\n#include \"ilwiscontext.h\"\n#include \"errorobject.h\"\n#include \"issuelogger.h\"\n\nusing namespace Ilwis;\n\nstd::map IssueLogger::_silentThreads;\n\nIssueObject::IssueObject()\n{\n}\n\nIlwis::IssueObject::IssueObject(const QString &message, int it, quint64 id)\n{\n _message = message;\n _itype = it;\n _itime = QDateTime::currentDateTime();\n _id = id;\n}\n\nQString Ilwis::IssueObject::message() const\n{\n return _message;\n}\n\nQDateTime Ilwis::IssueObject::time() const\n{\n return _itime;\n}\n\nint Ilwis::IssueObject::type() const\n{\n return _itype;\n}\n\nQString Ilwis::IssueObject::logMessage(Ilwis::IssueObject::LogMessageFormat) const{\n return QString(\"%1: (%2) %3\").arg(type2String(), _itime.toString(), _message);\n}\n\nint IssueObject::codeLine() const {\n return _line;\n}\n\nQString IssueObject::codeFunc() const {\n return _func;\n}\n\nQString IssueObject::codeFile() const {\n return _file;\n}\n\nvoid IssueObject::addCodeInfo(int line, const QString &func, const QString &file)\n{\n _line = line;\n _func = func;\n _file = file;\n}\n\nvoid IssueObject::stream(std::ofstream& stream, LogMessageFormat frmt) {\n stream << std::setw(4) << _id << \" ; \" << std::setw(9) << type2String().toStdString() << \" ; \" << std::setw(27)<<_itime.toString().toStdString() << \" ; \" << _message.toStdString() << std::endl;\n if ( frmt == lmCODE) {\n stream << std::setw(4) << _id << \" ; \" << _line << \" : \" << _func.toStdString() << \" ; \" << _file.toStdString() << std::endl;\n }\n}\n\n\n\nquint64 IssueObject::id() const\n{\n return _id;\n}\n\nQString IssueObject::type2String() const{\n switch(_itype) {\n case itCritical:\n return \"Critical\";\n case itError:\n return \"Error\";\n case itWarning:\n return \"Warning\";\n case itMessage:\n return \"Message\";\n case itDebug:\n return \"Debug\";\n }\n return \"Text\";\n}\n\n\/\/---------------------------------------------------------------------------\nIssueLogger::IssueLogger(QObject *parent) : QObject(parent), _repeatCount(0)\n{\n QString apploc= context()->ilwisFolder().absoluteFilePath();\n apploc += \"\/log\";\n QDir dir(apploc);\n if ( !dir.exists())\n dir.mkdir(apploc);\n QString rlogFilePath = apploc + \"\/logfile.txt\";\n QString clogFilePath = apploc + \"\/logfile_ext.txt\";\n _logFileRegular.open(rlogFilePath.toLatin1());\n _logFileCode.open(clogFilePath.toLatin1());\n}\n\nIssueLogger::~IssueLogger()\n{\n if (_logFileCode.is_open())\n _logFileCode.close();\n if ( _logFileRegular.is_open())\n _logFileRegular.close();\n}\n\nquint64 IssueLogger::log(const QString &message, int it)\n{\n ++_repeatCount;\n std::thread::id id = std::this_thread::get_id();\n if ( _silentThreads.find(id)!= _silentThreads.end() && it != IssueObject::itCritical)\n return i64UNDEF;\n\n\n if ( _lastmessage == message && _repeatCount == 10) {\n return _issueId;\n } else {\n \/\/ Mechanism to prevent(some) 'stuck in a loop' kind of errors.\n \/\/ this should basically be solved at the place the loop is happening but oversights happen.\n \/\/ This is a last fallback to break the loop without the need to stop the process\n if ( _repeatCount > 10 && _lastmessage != message ){\n _issues.enqueue(IssueObject(QString(\"Message repeated %1 times\").arg(_repeatCount), it, _issueId));\n throw ErrorObject(QString(\"Error message cascade : %1\").arg(message));\n }\n _repeatCount = 0;\n }\n\n _issues.enqueue(IssueObject(message, it, _issueId));\n if ( _lastmessage == message)\n return _issueId;\n IssueObject& obj = _issues.back();\n if ( _logFileRegular.is_open()) {\n obj.stream(_logFileRegular, IssueObject::lmREGULAR);\n }\n emit ilwiserrormessage(obj.logMessage());\n\n _lastmessage = message;\n return _issueId++;\n}\n\nquint64 IssueLogger::log(const QString& objectName, const QString &message, int it)\n{\n QString newmessage = objectName + \":\" + message;\n return log(newmessage, it);\n}\n\nvoid IssueLogger::addCodeInfo(quint64 issueid, int line, const QString &func, const QString &file)\n{\n for(auto iter=_issues.begin(); iter != _issues.end(); ++iter) {\n IssueObject& issue = *iter;\n if ( issue.id() == issueid) {\n issue.addCodeInfo(line, func, file);\n if ( _logFileCode.is_open()) {\n issue.stream(_logFileCode, IssueObject::lmCODE);\n }\n break;\n }\n }\n}\n\nbool IssueLogger::silent() const\n{\n std::thread::id id = std::this_thread::get_id();\n auto iter = _silentThreads.find(id);\n if ( iter != _silentThreads.end())\n return iter->second;\n return false;\n}\n\nvoid IssueLogger::silent(bool yesno)\n{\n std::thread::id id = std::this_thread::get_id();\n if ( yesno == false){\n auto iter = _silentThreads.find(id) ;\n if (iter != _silentThreads.end())\n _silentThreads.erase(iter);\n }else\n _silentThreads[id] = true;\n}\n\nquint64 IssueLogger::logSql(const QSqlError &err)\n{\n return log(err.text(), IssueObject::itError);\n}\n\nIssueObject::IssueType IssueLogger::maxIssueLevel() const\n{\n int type = IssueObject::itNone;\n foreach(IssueObject issue, _issues) {\n type |= issue.type();\n }\n if ( type & IssueObject::itCritical)\n return IssueObject::itCritical;\n if ( type & IssueObject::itError)\n return IssueObject::itError;\n if ( type & IssueObject::itWarning)\n return IssueObject::itWarning;\n if ( type & IssueObject::itMessage)\n return IssueObject::itMessage;\n return IssueObject::itNone;\n}\n\nvoid IssueLogger::copy(IssueLogger &other)\n{\n foreach(IssueObject issue, _issues) {\n other._issues.enqueue(issue);\n }\n}\n\nQString IssueLogger::popfirst(int tp) {\n if ( tp != IssueObject::itAll){\n for(auto iter= --_issues.end(); iter != _issues.begin(); --iter ){\n if (hasType((*iter).type(), tp)){\n QString mes = (*iter).message();\n _issues.erase(iter);\n return mes;\n }\n }\n }\n if ( _issues.size() > 0)\n return _issues.dequeue().message();\n return \"?\";\n}\n\nQString IssueLogger::poplast(int tp) {\n if ( tp != IssueObject::itAll){\n for(auto iter= _issues.begin(); iter != _issues.end(); ++iter ){\n if (hasType((*iter).type(), tp)){\n QString mes = (*iter).message();\n _issues.erase(iter);\n return mes;\n }\n }\n }\n if ( _issues.size() >0 )\n return _issues.takeLast().message();\n return \"?\";\n}\n\nvoid IssueLogger::clear() {\n _issues.clear();\n}\n\n\n\n<|endoftext|>"} {"text":"#ifndef MCMC_TRAITS\n#define MCMC_TRAITS\n#define MCMC_HEADER\n#include \n#include \nnamespace mcmc_utilities\n{\n \/**\n Get the size of an array object\n \\param x the array object\n \\return the size of the array object\n *\/\n template \n inline size_t get_size(const T& x)\n {\n return x.size();\n }\n \n \/**\n \\brief Trait class, in which the types of elements in an array are defined\n \\tparam the type of the array object\n *\/\n template \n class element_type_trait\n {\n public:\n \/**\n Default definition of element_type\n *\/\n typedef typename T::value_type element_type;\n };\n\n \n \/**\n \\brief The return type trait of some certain data types.\n *\/\n template \n class return_type_trait\n {\n public:\n typedef T value_type;\n typedef T& reference_type;\n typedef const T& const_reference_type;\n };\n \n\n \/**\n Help function to get the i-th element from an array\n \\tparam T the type of the array object\n \\param x the array object\n \\param i the order of the element\n \\return the fetched element value, const reference\n *\/\n template \n inline typename \n return_type_trait::element_type>::\n const_reference_type get_element(const T& x,size_t i)\n {\n return x[i];\n }\n\n \n \/**\n set ths i-th element by a given value\n \\tparam T the type of the array object\n \\tparam Tx the type of the element\n \\param x the array object\n \\param i the order of the element\n \\param v the value of the element to be set\n *\/\n template\n inline void set_element(T& x,size_t i,\n\t\t\t const TX& v)\n {\n x[i]=v;\n }\n\n template \n inline void push_back(T& x,const TX& v)\n {\n x.push_back(v);\n }\n\n template \n inline typename return_type_trait::element_type>::\n const_reference_type last_element(const T& x)\n {\n return x.back();\n }\n\n template \n inline typename return_type_trait::element_type>::\n reference_type last_element(T& x)\n {\n return x.back();\n }\n\n\n \/**\n resize an array object\n \\tparam T the type of the array\n \\param x the array object\n \\param s the new size\n *\/\n template \n inline void resize(T& x,size_t s)\n {\n x.resize(s);\n }\n\n template \n inline void reserve(T& x,size_t s)\n {\n x.reserve(s);\n }\n\n\n \/**\n Assignment operator of two array objects\n \\tparam Tl the type of left-hand array\n \\tparam Tr the type of right-hand array\n \\param lhs the left-hand array\n \\param rhs the right-hand array\n \\return the reference of the left-hand array\n *\/\n template \n inline Tl& mcmc_assign(Tl& lhs,const Tr& rhs)\n {\n return (lhs=rhs);\n }\n\n template \n constexpr T C_ONE()\n {\n return static_cast(1);\n }\n\n template \n constexpr T C_ZERO()\n {\n return static_cast(0);\n }\n\n template \n constexpr T C_N2T()\n {\n return static_cast(N);\n }\n \n template \n constexpr T C_NAN()\n {\n return static_cast(std::nan(\"\"));\n }\n}\n\n\n\n#endif\n\tmodified: core\/mcmc_traits.hpp#ifndef MCMC_TRAITS\n#define MCMC_TRAITS\n#define MCMC_HEADER\n#include \n#include \nnamespace mcmc_utilities\n{\n \/**\n Get the size of an array object\n \\param x the array object\n \\return the size of the array object\n *\/\n template \n inline size_t get_size(const T& x)\n {\n return x.size();\n }\n \n \/**\n \\brief Trait class, in which the types of elements in an array are defined\n \\tparam the type of the array object\n *\/\n template \n class element_type_trait\n {\n public:\n \/**\n Default definition of element_type\n *\/\n typedef typename T::value_type element_type;\n };\n\n \n \/**\n \\brief The return type trait of some certain data types.\n *\/\n template \n class return_type_trait\n {\n public:\n typedef T value_type;\n typedef T& reference_type;\n typedef const T& const_reference_type;\n };\n \n\n \/**\n Help function to get the i-th element from an array\n \\tparam T the type of the array object\n \\param x the array object\n \\param i the order of the element\n \\return the fetched element value, const reference\n *\/\n template \n inline typename \n return_type_trait::element_type>::\n const_reference_type get_element(const T& x,size_t i)\n {\n return x[i];\n }\n\n \n \/**\n set ths i-th element by a given value\n \\tparam T the type of the array object\n \\tparam Tx the type of the element\n \\param x the array object\n \\param i the order of the element\n \\param v the value of the element to be set\n *\/\n template\n inline void set_element(T& x,size_t i,\n\t\t\t const TX& v)\n {\n x[i]=v;\n }\n\n template \n inline void push_back(T& x,const TX& v)\n {\n x.push_back(v);\n }\n\n template \n inline typename return_type_trait::element_type>::\n const_reference_type last_element(const T& x)\n {\n return x.back();\n }\n\n template \n inline typename return_type_trait::element_type>::\n reference_type last_element(T& x)\n {\n return x.back();\n }\n\n\n \/**\n resize an array object\n \\tparam T the type of the array\n \\param x the array object\n \\param s the new size\n *\/\n template \n inline void resize(T& x,size_t s)\n {\n x.resize(s);\n }\n\n template \n inline void reserve(T& x,size_t s)\n {\n x.reserve(s);\n }\n\n\n \/**\n Assignment operator of two array objects\n \\tparam Tl the type of left-hand array\n \\tparam Tr the type of right-hand array\n \\param lhs the left-hand array\n \\param rhs the right-hand array\n \\return the reference of the left-hand array\n *\/\n template \n inline Tl& mcmc_assign(Tl& lhs,const Tr& rhs)\n {\n return (lhs=rhs);\n }\n\n template \n constexpr T C_ONE()\n {\n return static_cast(1);\n }\n\n template \n constexpr T C_ZERO()\n {\n return static_cast(0);\n }\n\n template \n constexpr T C_N2T()\n {\n return static_cast(N);\n }\n \n template \n constexpr T C_NAN()\n {\n \/\/return static_cast(std::nan(\"\"));\n return static_cast(NAN);\n }\n}\n\n\n\n#endif\n<|endoftext|>"} {"text":"\/*\n Copyright (C) 1998 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"cssys\/csshlib.h\"\n\n#include \n\ncsLibraryHandle csLoadLibrary (const char* szLibName)\n{\n return LoadLibrary (szLibName);\n}\n\nvoid* csGetLibrarySymbol(csLibraryHandle Handle, const char* Name)\n{\n void* ptr=GetProcAddress ((HMODULE)Handle, Name);\n if(!ptr) {\n char *Name2;\n Name2=new char[strlen(Name)+2];\n strcpy(Name2, \"_\");\n strcat(Name2, Name);\n ptr=GetProcAddress ((HMODULE)Handle, Name2);\n delete [] Name2;\n }\n return ptr;\n}\n\nbool csUnloadLibrary (csLibraryHandle Handle)\n{\n return FreeLibrary ((HMODULE)Handle)!=0;\n}\nNow includes sysdef.h in order to eliminate some warnings from windows.h under VC5.\/*\n Copyright (C) 1998 by Jorrit Tyberghein\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Library General Public\n License as published by the Free Software Foundation; either\n version 2 of the License, or (at your option) any later version.\n\n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Library General Public License for more details.\n\n You should have received a copy of the GNU Library General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.\n*\/\n\n#include \"sysdef.h\"\n#include \"cssys\/csshlib.h\"\n\n#include \n\ncsLibraryHandle csLoadLibrary (const char* szLibName)\n{\n return LoadLibrary (szLibName);\n}\n\nvoid* csGetLibrarySymbol(csLibraryHandle Handle, const char* Name)\n{\n void* ptr=GetProcAddress ((HMODULE)Handle, Name);\n if(!ptr) {\n char *Name2;\n Name2=new char[strlen(Name)+2];\n strcpy(Name2, \"_\");\n strcat(Name2, Name);\n ptr=GetProcAddress ((HMODULE)Handle, Name2);\n delete [] Name2;\n }\n return ptr;\n}\n\nbool csUnloadLibrary (csLibraryHandle Handle)\n{\n return FreeLibrary ((HMODULE)Handle)!=0;\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n\n#include \"TimingTag.hpp\"\n#include \"tatum_range.hpp\"\n\nnamespace tatum {\n\n\n\/**\n * The 'TimingTags' class represents a collection of timing tags (see the 'TimingTag' class)\n * that belong to a particular node in the timing graph.\n *\n * Any operations performed using this task generally consider *all* associated tags.\n * For example, preforming a max_arr() call will apply the max accross all tags with matching\n * clock domain. If no matching tag is found, the tag will be added to the set of tags.\n *\n * Implementation\n * ====================\n * Since each node in the timing graph typically has only a few tags (usually 1 or 2), we\n * perform linear searches to find match tags and tag ranges.\n *\n * Note that to allow efficient iteration of tag ranges (by type) we ensure that tags of the\n * same type are adjacent in the storage vector (i.e. the vector is sorted by type)\n *\/\nclass TimingTags {\n public:\n template\n class Iterator;\n private:\n \/\/In practice the vast majority of nodes have only two or one\n \/\/tags, so we reserve space for two to avoid costly memory\n \/\/allocations\n constexpr static size_t DEFAULT_TAGS_TO_RESERVE = 3;\n constexpr static size_t GROWTH_FACTOR = 2;\n\n public:\n\n typedef Iterator iterator;\n typedef Iterator const_iterator;\n\n typedef tatum::util::Range tag_range;\n\n public:\n\n \/\/Constructors\n TimingTags(size_t num_reserve=DEFAULT_TAGS_TO_RESERVE);\n TimingTags(const TimingTags&);\n TimingTags(TimingTags&&);\n TimingTags& operator=(TimingTags);\n ~TimingTags() = default;\n friend void swap(TimingTags& lhs, TimingTags& rhs);\n\n \/*\n * Getters\n *\/\n \/\/\/\\returns The number of timing tags in this set\n size_t size() const;\n bool empty() const { return size() == 0; }\n\n \/\/\/\\returns A range of all tags\n tag_range tags() const;\n\n \/\/\/\\returns A range of all tags matching type\n tag_range tags(const TagType type) const;\n\n\n \/*\n * Modifiers\n *\/\n \/\/\/Adds a TimingTag to the current set provided it has a valid clock domain\n \/\/\/\\param tag_pool The pool memory allocator used to allocate the tag\n \/\/\/\\param src_tag The source tag who is inserted. Note that the src_tag is copied when inserted (the original is unchanged)\n void add_tag(const TimingTag& src_tag);\n\n \/*\n * Operations\n *\/\n \/\/\/Updates the arrival time of this set of tags to be the maximum.\n \/\/\/\\param new_time The new arrival time to compare against\n \/\/\/\\param base_tag The associated metat-data for new_time\n \/\/\/\\remark Finds (or creates) the tag with the same clock domain as base_tag and update the arrival time if new_time is larger\n void max(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);\n\n \/\/\/Updates the required time of this set of tags to be the minimum.\n \/\/\/\\param new_time The new arrival time to compare against\n \/\/\/\\param base_tag The associated metat-data for new_time\n \/\/\/\\remark Finds (or creates) the tag with the same clock domain as base_tag and update the required time if new_time is smaller\n void min(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);\n\n \/\/\/Clears the tags in the current set\n void clear();\n\n public:\n\n \/\/Iterator definition\n template\n class Iterator : public std::iterator {\n friend TimingTags;\n public:\n using value_type = typename std::iterator::value_type;\n using difference_type = typename std::iterator::difference_type;\n using pointer = typename std::iterator::pointer;\n using reference = typename std::iterator::reference;\n using iterator_category = typename std::iterator::iterator_category;\n public:\n Iterator(): p_(nullptr) {}\n Iterator(pointer p): p_(p) {}\n Iterator(const Iterator& other): p_(other.p_) {}\n Iterator& operator=(const Iterator& other) { p_ = other.p_; return *this; }\n\n friend bool operator==(Iterator a, Iterator b) { return a.p_ == b.p_; }\n friend bool operator!=(Iterator a, Iterator b) { return a.p_ != b.p_; }\n\n reference operator*() { return *p_; }\n pointer operator->() { return p_; }\n reference operator[](size_t n) { return *(p_ + n); }\n\n Iterator& operator++() { ++p_; return *this; }\n Iterator operator++(int) { Iterator old = *this; ++p_; return old; }\n Iterator& operator--() { --p_; return *this; }\n Iterator operator--(int) { Iterator old = *this; --p_; return old; }\n Iterator& operator+=(size_t n) { p_ += n; return *this; }\n Iterator& operator-=(size_t n) { p_ -= n; return *this; }\n friend Iterator operator+(Iterator lhs, size_t rhs) { return lhs += rhs; }\n friend Iterator operator-(Iterator lhs, size_t rhs) { return lhs += rhs; }\n\n friend difference_type operator-(const Iterator lhs, const Iterator rhs) { return lhs.p_ - rhs.p_; }\n\n friend bool operator<(Iterator lhs, Iterator rhs) { return lhs.p_ < rhs.p_; }\n friend bool operator>(Iterator lhs, Iterator rhs) { return lhs.p_ > rhs.p_; }\n friend bool operator<=(Iterator lhs, Iterator rhs) { return lhs.p_ <= rhs.p_; }\n friend bool operator>=(Iterator lhs, Iterator rhs) { return lhs.p_ >= rhs.p_; }\n friend void swap(Iterator lhs, Iterator rhs) { std::swap(lhs.p_, rhs.p_); }\n private:\n T* p_ = nullptr;\n };\n\n private:\n\n \/\/\/\\returns An iterator to the first tag in the current set\n iterator begin();\n const_iterator begin() const;\n iterator begin(TagType type);\n const_iterator begin(TagType type) const;\n\n \/\/\/\\returns An iterator 'one-past-the-end' of the current set\n iterator end();\n const_iterator end() const;\n iterator end(TagType type);\n const_iterator end(TagType type) const;\n\n size_t capacity() const;\n\n std::pair find_matching_tag(const TimingTag& tag, bool arr_must_be_valid);\n\n \/\/\/Finds a TimingTag in the current set that has clock domain id matching domain_id\n \/\/\/\\returns An iterator to the tag if found, or end(tag.type()) if not found\n std::pair find_matching_tag(const TimingTag& tag);\n\n \/\/Find a TimingTag matching the specified DATA_REQUIRED tag provided there is a valid associated\n \/\/DATA_ARRIVAL tag\n std::pair find_matching_tag_with_valid_arrival(const TimingTag& tag);\n\n\n iterator insert(iterator iter, const TimingTag& tag);\n void grow_insert(size_t index, const TimingTag& tag);\n\n void increment_size(TagType type);\n\n\n private:\n \/\/We don't expect many tags in a node so unsigned short's\/unsigned char's\n \/\/should be more than sufficient. This also allows the class\n \/\/to be packed down to 16 bytes (8 for counters, 8 for pointer)\n \/\/\n \/\/In its current configuration we can store at most:\n \/\/ 65536 total tags (size_ and capacity_)\n \/\/ 256 clock launch tags (num_clock_launch_tags_)\n \/\/ 256 clock capture tags (num_clock_capture_tags_)\n \/\/ 256 data arrival tags (num_data_arrival_tags_)\n \/\/ (65536 - 3*256) data required tags (size_ - num_*)\n unsigned short size_ = 0;\n unsigned short capacity_ = 0;\n unsigned char num_clock_launch_tags_ = 0;\n unsigned char num_clock_capture_tags_ = 0;\n unsigned char num_data_arrival_tags_ = 0;\n std::unique_ptr tags_;\n\n};\n\n} \/\/namepsace\n\n\/\/Implementation\n#include \"TimingTags.inl\"\nFix iterator subtraction#pragma once\n#include \n#include \n\n#include \"TimingTag.hpp\"\n#include \"tatum_range.hpp\"\n\nnamespace tatum {\n\n\n\/**\n * The 'TimingTags' class represents a collection of timing tags (see the 'TimingTag' class)\n * that belong to a particular node in the timing graph.\n *\n * Any operations performed using this task generally consider *all* associated tags.\n * For example, preforming a max_arr() call will apply the max accross all tags with matching\n * clock domain. If no matching tag is found, the tag will be added to the set of tags.\n *\n * Implementation\n * ====================\n * Since each node in the timing graph typically has only a few tags (usually 1 or 2), we\n * perform linear searches to find match tags and tag ranges.\n *\n * Note that to allow efficient iteration of tag ranges (by type) we ensure that tags of the\n * same type are adjacent in the storage vector (i.e. the vector is sorted by type)\n *\/\nclass TimingTags {\n public:\n template\n class Iterator;\n private:\n \/\/In practice the vast majority of nodes have only a handful of tags,\n \/\/so we reserve space for some to avoid costly memory allocations\n constexpr static size_t DEFAULT_TAGS_TO_RESERVE = 3;\n constexpr static size_t GROWTH_FACTOR = 2;\n\n public:\n\n typedef Iterator iterator;\n typedef Iterator const_iterator;\n\n typedef tatum::util::Range tag_range;\n\n public:\n\n \/\/Constructors\n TimingTags(size_t num_reserve=DEFAULT_TAGS_TO_RESERVE);\n TimingTags(const TimingTags&);\n TimingTags(TimingTags&&);\n TimingTags& operator=(TimingTags);\n ~TimingTags() = default;\n friend void swap(TimingTags& lhs, TimingTags& rhs);\n\n \/*\n * Getters\n *\/\n \/\/\/\\returns The number of timing tags in this set\n size_t size() const;\n bool empty() const { return size() == 0; }\n\n \/\/\/\\returns A range of all tags\n tag_range tags() const;\n\n \/\/\/\\returns A range of all tags matching type\n tag_range tags(const TagType type) const;\n\n\n \/*\n * Modifiers\n *\/\n \/\/\/Adds a TimingTag to the current set provided it has a valid clock domain\n \/\/\/\\param tag_pool The pool memory allocator used to allocate the tag\n \/\/\/\\param src_tag The source tag who is inserted. Note that the src_tag is copied when inserted (the original is unchanged)\n void add_tag(const TimingTag& src_tag);\n\n \/*\n * Operations\n *\/\n \/\/\/Updates the arrival time of this set of tags to be the maximum.\n \/\/\/\\param new_time The new arrival time to compare against\n \/\/\/\\param base_tag The associated metat-data for new_time\n \/\/\/\\remark Finds (or creates) the tag with the same clock domain as base_tag and update the arrival time if new_time is larger\n void max(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);\n\n \/\/\/Updates the required time of this set of tags to be the minimum.\n \/\/\/\\param new_time The new arrival time to compare against\n \/\/\/\\param base_tag The associated metat-data for new_time\n \/\/\/\\remark Finds (or creates) the tag with the same clock domain as base_tag and update the required time if new_time is smaller\n void min(const Time& new_time, const TimingTag& base_tag, bool arr_must_be_valid=false);\n\n \/\/\/Clears the tags in the current set\n void clear();\n\n public:\n\n \/\/Iterator definition\n template\n class Iterator : public std::iterator {\n friend TimingTags;\n public:\n using value_type = typename std::iterator::value_type;\n using difference_type = typename std::iterator::difference_type;\n using pointer = typename std::iterator::pointer;\n using reference = typename std::iterator::reference;\n using iterator_category = typename std::iterator::iterator_category;\n public:\n Iterator(): p_(nullptr) {}\n Iterator(pointer p): p_(p) {}\n Iterator(const Iterator& other): p_(other.p_) {}\n Iterator& operator=(const Iterator& other) { p_ = other.p_; return *this; }\n\n friend bool operator==(Iterator a, Iterator b) { return a.p_ == b.p_; }\n friend bool operator!=(Iterator a, Iterator b) { return a.p_ != b.p_; }\n\n reference operator*() { return *p_; }\n pointer operator->() { return p_; }\n reference operator[](size_t n) { return *(p_ + n); }\n\n Iterator& operator++() { ++p_; return *this; }\n Iterator operator++(int) { Iterator old = *this; ++p_; return old; }\n Iterator& operator--() { --p_; return *this; }\n Iterator operator--(int) { Iterator old = *this; --p_; return old; }\n Iterator& operator+=(size_t n) { p_ += n; return *this; }\n Iterator& operator-=(size_t n) { p_ -= n; return *this; }\n friend Iterator operator+(Iterator lhs, size_t rhs) { return lhs += rhs; }\n friend Iterator operator-(Iterator lhs, size_t rhs) { return lhs -= rhs; }\n\n friend difference_type operator-(const Iterator lhs, const Iterator rhs) { return lhs.p_ - rhs.p_; }\n\n friend bool operator<(Iterator lhs, Iterator rhs) { return lhs.p_ < rhs.p_; }\n friend bool operator>(Iterator lhs, Iterator rhs) { return lhs.p_ > rhs.p_; }\n friend bool operator<=(Iterator lhs, Iterator rhs) { return lhs.p_ <= rhs.p_; }\n friend bool operator>=(Iterator lhs, Iterator rhs) { return lhs.p_ >= rhs.p_; }\n friend void swap(Iterator lhs, Iterator rhs) { std::swap(lhs.p_, rhs.p_); }\n private:\n T* p_ = nullptr;\n };\n\n private:\n\n \/\/\/\\returns An iterator to the first tag in the current set\n iterator begin();\n const_iterator begin() const;\n iterator begin(TagType type);\n const_iterator begin(TagType type) const;\n\n \/\/\/\\returns An iterator 'one-past-the-end' of the current set\n iterator end();\n const_iterator end() const;\n iterator end(TagType type);\n const_iterator end(TagType type) const;\n\n size_t capacity() const;\n\n std::pair find_matching_tag(const TimingTag& tag, bool arr_must_be_valid);\n\n \/\/\/Finds a TimingTag in the current set that has clock domain id matching domain_id\n \/\/\/\\returns An iterator to the tag if found, or end(tag.type()) if not found\n std::pair find_matching_tag(const TimingTag& tag);\n\n \/\/Find a TimingTag matching the specified DATA_REQUIRED tag provided there is a valid associated\n \/\/DATA_ARRIVAL tag\n std::pair find_matching_tag_with_valid_arrival(const TimingTag& tag);\n\n\n iterator insert(iterator iter, const TimingTag& tag);\n void grow_insert(size_t index, const TimingTag& tag);\n\n void increment_size(TagType type);\n\n\n private:\n \/\/We don't expect many tags in a node so unsigned short's\/unsigned char's\n \/\/should be more than sufficient. This also allows the class\n \/\/to be packed down to 16 bytes (8 for counters, 8 for pointer)\n \/\/\n \/\/In its current configuration we can store at most:\n \/\/ 65536 total tags (size_ and capacity_)\n \/\/ 256 clock launch tags (num_clock_launch_tags_)\n \/\/ 256 clock capture tags (num_clock_capture_tags_)\n \/\/ 256 data arrival tags (num_data_arrival_tags_)\n \/\/ (65536 - 3*256) data required tags (size_ - num_*)\n unsigned short size_ = 0;\n unsigned short capacity_ = 0;\n unsigned char num_clock_launch_tags_ = 0;\n unsigned char num_clock_capture_tags_ = 0;\n unsigned char num_data_arrival_tags_ = 0;\n std::unique_ptr tags_;\n\n};\n\n} \/\/namepsace\n\n\/\/Implementation\n#include \"TimingTags.inl\"\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 Maciej Gajewski\n\n#ifndef COROUTINES_MUTEX_HPP\n#define COROUTINES_MUTEX_HPP\n\n#include \"profiling\/profiling.hpp\"\n\n#include \n#include \n\nnamespace coroutines {\n\n\nclass spinlock\n{\npublic:\n\n spinlock() \n : _flag(ATOMIC_FLAG_INIT)\n { }\n\n spinlock(const char* name)\n : _flag(ATOMIC_FLAG_INIT)\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n CORO_PROF(\"spinlock\", this, \"created\", name);\n #else\n (void)name;\n #endif\n }\n\n void lock()\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n \/\/ only report contested lock events\n if (try_lock())\n return;\n CORO_PROF(\"spinlock\", this, \"spinning begin\");\n #endif\n while(_flag.test_and_set(std::memory_order_acquire))\n ; \/\/ spin\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n CORO_PROF(\"spinlock\", this, \"spinning end\");\n #endif\n }\n\n bool try_lock()\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n if (!_flag.test_and_set(std::memory_order_acquire))\n {\n CORO_PROF(\"spinlock\", this, \"locked\");\n return true;\n }\n else\n return false;\n #else\n return !_flag.test_and_set(std::memory_order_acquire);\n #endif\n }\n\n void unlock()\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n CORO_PROF(\"spinlock\", this, \"unlocked\");\n #endif\n _flag.clear(std::memory_order_release);\n }\n\n\nprivate:\n\n std::atomic_flag _flag;\n};\n\n\n\/\/typedef std::mutex mutex;\ntypedef spinlock mutex;\n\n}\n\n#endif\nrw_spinlock code added, now its time for testing\/\/ Copyright (c) 2013 Maciej Gajewski\n\n#ifndef COROUTINES_MUTEX_HPP\n#define COROUTINES_MUTEX_HPP\n\n#include \"profiling\/profiling.hpp\"\n\n#include \n#include \n#include \n\nnamespace coroutines {\n\n\nclass spinlock\n{\npublic:\n\n spinlock() \n : _flag(ATOMIC_FLAG_INIT)\n { }\n\n spinlock(const char* name)\n : _flag(ATOMIC_FLAG_INIT)\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n CORO_PROF(\"spinlock\", this, \"created\", name);\n #else\n (void)name;\n #endif\n }\n\n void lock()\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n \/\/ only report contested lock events\n if (try_lock())\n return;\n CORO_PROF(\"spinlock\", this, \"spinning begin\");\n #endif\n while(_flag.test_and_set(std::memory_order_acquire))\n ; \/\/ spin\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n CORO_PROF(\"spinlock\", this, \"spinning end\");\n #endif\n }\n\n bool try_lock()\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n if (!_flag.test_and_set(std::memory_order_acquire))\n {\n CORO_PROF(\"spinlock\", this, \"locked\");\n return true;\n }\n else\n return false;\n #else\n return !_flag.test_and_set(std::memory_order_acquire);\n #endif\n }\n\n void unlock()\n {\n #ifdef COROUTINES_SPINLOCKS_PROFILING\n CORO_PROF(\"spinlock\", this, \"unlocked\");\n #endif\n _flag.clear(std::memory_order_release);\n }\n\n\nprivate:\n\n std::atomic_flag _flag;\n};\n\n\n\/\/typedef std::mutex mutex;\ntypedef spinlock mutex;\n\n\/\/ based on folly's RWSpinLock\nclass rw_spinlock\n{\n enum : std::int32_t { READER = 4, UPGRADED = 2, WRITER = 1 };\n\npublic:\n rw_spinlock() : _bits(0) {}\n\n void lock()\n {\n while (!try_lock())\n ;\n }\n\n \/\/ Writer is responsible for clearing up both the UPGRADED and WRITER bits.\n void unlock()\n {\n static_assert(READER > WRITER + UPGRADED, \"wrong bits!\");\n _bits.fetch_and(~(WRITER | UPGRADED), std::memory_order_release);\n }\n\n \/\/ SharedLockable Concept\n void lock_shared()\n {\n while (try_lock_shared())\n ;\n }\n\n void unlock_shared()\n {\n _bits.fetch_add(-READER, std::memory_order_release);\n }\n\n \/\/ Downgrade the lock from writer status to reader status.\n void unlock_and_lock_shared()\n {\n _bits.fetch_add(READER, std::memory_order_acquire);\n unlock();\n }\n\n \/\/ UpgradeLockable Concept\n void lock_upgrade()\n {\n while (!try_lock_upgrade())\n ;\n }\n\n void unlock_upgrade()\n {\n _bits.fetch_add(-UPGRADED, std::memory_order_acq_rel);\n }\n\n \/\/ unlock upgrade and try to acquire write lock\n void unlock_upgrade_and_lock()\n {\n while (!try_unlock_upgrade_and_lock())\n ;\n }\n\n \/\/ unlock upgrade and read lock atomically\n void unlock_upgrade_and_lock_shared()\n {\n _bits.fetch_add(READER - UPGRADED, std::memory_order_acq_rel);\n }\n\n \/\/ write unlock and upgrade lock atomically\n void unlock_and_lock_upgrade()\n {\n \/\/ need to do it in two steps here -- as the UPGRADED bit might be OR-ed at\n \/\/ the same time when other threads are trying do try_lock_upgrade().\n _bits.fetch_or(UPGRADED, std::memory_order_acquire);\n _bits.fetch_add(-WRITER, std::memory_order_release);\n }\n\n\n \/\/ Attempt to acquire writer permission. Return false if we didn't get it.\n bool try_lock()\n {\n std::int32_t expect = 0;\n return _bits.compare_exchange_strong(expect, WRITER, std::memory_order_acq_rel);\n }\n\n \/\/ Try to get reader permission on the lock. This can fail if we\n \/\/ find out someone is a writer or upgrader.\n \/\/ Setting the UPGRADED bit would allow a writer-to-be to indicate\n \/\/ its intention to write and block any new readers while waiting\n \/\/ for existing readers to finish and release their read locks. This\n \/\/ helps avoid starving writers (promoted from upgraders).\n bool try_lock_shared()\n {\n \/\/ fetch_add is considerably (100%) faster than compare_exchange,\n \/\/ so here we are optimizing for the common (lock success) case.\n std::int32_t value = _bits.fetch_add(READER, std::memory_order_acquire);\n if (value & (WRITER|UPGRADED))\n {\n _bits.fetch_add(-READER, std::memory_order_release);\n return false;\n }\n return true;\n }\n\n \/\/ try to unlock upgrade and write lock atomically\n bool try_unlock_upgrade_and_lock()\n {\n std::int32_t expect = UPGRADED;\n return _bits.compare_exchange_strong(expect, WRITER, std::memory_order_acq_rel);\n }\n\n \/\/ try to acquire an upgradable lock.\n bool try_lock_upgrade()\n {\n std::int32_t value = _bits.fetch_or(UPGRADED, std::memory_order_acquire);\n\n \/\/ Note: when failed, we cannot flip the UPGRADED bit back,\n \/\/ as in this case there is either another upgrade lock or a write lock.\n \/\/ If it's a write lock, the bit will get cleared up when that lock's done\n \/\/ with unlock().\n return ((value & (UPGRADED | WRITER)) == 0);\n }\n\nprivate:\n\n std::atomic _bits;\n};\n\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/plugins\/ppapi\/ppb_nacl_private_impl.h\"\n\n#include \"base\/rand_util_c.h\"\n#include \"ppapi\/c\/private\/ppb_nacl_private.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nnamespace webkit {\nnamespace ppapi {\n\nnamespace {\n\nbool LaunchSelLdr(const char* alleged_url, int socket_count,\n void* imc_handles, void* nacl_process_handle,\n int* nacl_process_id) {\n#if !defined(DISABLE_NACL)\n return webkit_glue::LaunchSelLdr(alleged_url, socket_count, imc_handles,\n nacl_process_handle, nacl_process_id);\n#else\n return 0;\n#endif\n}\n\nint UrandomFD(void) {\n#if defined(OS_POSIX)\n return GetUrandomFD();\n#else\n return 0;\n#endif\n}\n\n} \/\/ namespace\n\nconst PPB_NaCl_Private ppb_nacl = {\n &LaunchSelLdr,\n &UrandomFD,\n};\n\n\/\/ static\nconst PPB_NaCl_Private* PPB_NaCl_Private_Impl::GetInterface() {\n return &ppb_nacl;\n}\n\n} \/\/ namespace ppapi\n} \/\/ namespace webkit\nBy zero, I mean false\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"webkit\/plugins\/ppapi\/ppb_nacl_private_impl.h\"\n\n#include \"base\/rand_util_c.h\"\n#include \"ppapi\/c\/private\/ppb_nacl_private.h\"\n#include \"webkit\/glue\/webkit_glue.h\"\n\nnamespace webkit {\nnamespace ppapi {\n\nnamespace {\n\nbool LaunchSelLdr(const char* alleged_url, int socket_count,\n void* imc_handles, void* nacl_process_handle,\n int* nacl_process_id) {\n#if !defined(DISABLE_NACL)\n return webkit_glue::LaunchSelLdr(alleged_url, socket_count, imc_handles,\n nacl_process_handle, nacl_process_id);\n#else\n return false;\n#endif\n}\n\nint UrandomFD(void) {\n#if defined(OS_POSIX)\n return GetUrandomFD();\n#else\n return 0;\n#endif\n}\n\n} \/\/ namespace\n\nconst PPB_NaCl_Private ppb_nacl = {\n &LaunchSelLdr,\n &UrandomFD,\n};\n\n\/\/ static\nconst PPB_NaCl_Private* PPB_NaCl_Private_Impl::GetInterface() {\n return &ppb_nacl;\n}\n\n} \/\/ namespace ppapi\n} \/\/ namespace webkit\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.\n *\/\n#define __STDC_FORMAT_MACROS\n#define __STDC_LIMIT_MACROS\n#define __STDC_CONSTANT_MACROS\n\n#include \"monarch\/ws\/WebServer.h\"\n\n#include \"monarch\/crypto\/AsymmetricKeyFactory.h\"\n#include \"monarch\/data\/json\/JsonWriter.h\"\n#include \"monarch\/logging\/Logging.h\"\n#include \"monarch\/net\/NullSocketDataPresenter.h\"\n#include \"monarch\/net\/SslSocketDataPresenter.h\"\n\nusing namespace std;\nusing namespace monarch::config;\nusing namespace monarch::crypto;\nusing namespace monarch::data::json;\nusing namespace monarch::http;\nusing namespace monarch::io;\nusing namespace monarch::net;\nusing namespace monarch::rt;\nusing namespace monarch::util;\nusing namespace monarch::ws;\n\nWebServer::WebServer() :\n mServer(NULL),\n mHostAddress(NULL),\n mSslContext(NULL),\n mSocketDataPresenterList(NULL),\n mServiceId(Server::sInvalidServiceId)\n{\n}\n\nWebServer::~WebServer()\n{\n}\n\nbool WebServer::initialize(Config& cfg)\n{\n bool rval = true;\n\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer initializing...\");\n\n \/\/ create default container if one is not set\n if(mContainer.isNull())\n {\n mContainer = new WebServiceContainer();\n }\n\n \/\/ get basic config\n \/\/ security: on\/off\/both\n bool secure;\n bool nonSecure;\n const char* security = cfg[\"security\"]->getString();\n if(strcasecmp(security, \"on\") == 0)\n {\n secure = true;\n nonSecure = false;\n }\n else if(strcasecmp(security, \"off\") == 0)\n {\n secure = false;\n nonSecure = true;\n }\n else\n {\n secure = nonSecure = true;\n }\n\n if(secure)\n {\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer enabling SSL...\");\n\n \/\/ FIXME: make configurable\n \/* Create SSL server context. \"TLS\" is most secure and recent SSL but we\n must use \"ALL\" to handle browsers that use SSL 3.0. *\/\n mSslContext = new SslContext(\"ALL\", false);\n\n \/\/ setup certificate file and private key\n File certFile(cfg[\"certificate\"]->getString());\n File pkeyFile(cfg[\"privateKey\"]->getString());\n\n MO_CAT_DEBUG(MO_WS_CAT,\n \"WebServer setting SSL certificate and private key...\");\n\n \/\/ set certificate and private key for SSL context\n rval =\n mSslContext->setCertificate(certFile) &&\n mSslContext->setPrivateKey(pkeyFile);\n if(rval)\n {\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer reading SSL certificate...\");\n\n \/\/ set default virtual host based on certificate common name\n ByteBuffer b(certFile->getLength());\n rval = certFile.readBytes(&b);\n if(rval)\n {\n MO_CAT_DEBUG(MO_WS_CAT,\n \"WebServer loading SSL certificate from PEM...\");\n\n AsymmetricKeyFactory afk;\n X509CertificateRef cert = afk.loadCertificateFromPem(\n b.data(), b.length());\n rval = !cert.isNull();\n if(rval)\n {\n DynamicObject subject = cert->getSubject();\n string commonName = cert->getField(subject, \"CN\");\n MO_CAT_DEBUG(MO_WS_CAT,\n \"Setting default virtual host to common name: %s\",\n commonName.c_str());\n mSslContext->setVirtualHost(commonName.c_str());\n }\n }\n }\n\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer SSL setup complete.\");\n }\n\n if(rval)\n {\n \/\/ setup host address\n const char* host = cfg[\"host\"]->getString();\n uint32_t port = cfg[\"port\"]->getUInt32();\n mHostAddress = new InternetAddress(host, port);\n\n \/\/ handle socket presentation layer\n mSocketDataPresenterList = new SocketDataPresenterList(true);\n if(secure)\n {\n SslSocketDataPresenter* ssdp =\n new SslSocketDataPresenter(&(*mSslContext));\n mSocketDataPresenterList->add(ssdp);\n }\n if(nonSecure)\n {\n NullSocketDataPresenter* nsdp = new NullSocketDataPresenter();\n mSocketDataPresenterList->add(nsdp);\n }\n\n \/\/ get the list of default domains\n DynamicObject domains(NULL);\n if(cfg->hasMember(\"domains\"))\n {\n domains = cfg[\"domains\"].clone();\n if(domains->length() == 0)\n {\n \/\/ add wildcard if no domains specified\n domains->append() = \"*\";\n }\n }\n else\n {\n \/\/ no specified default domains, so use \"*\"\n domains = DynamicObject();\n domains->append() = \"*\";\n }\n mContainer->setDefaultDomains(domains);\n\n MO_CAT_INFO(MO_WS_CAT, \"WebServer running web services on domains: %s\",\n JsonWriter::writeToString(domains, false, false).c_str());\n }\n\n if(rval)\n {\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer initialized.\");\n }\n\n return rval;\n}\n\nvoid WebServer::cleanup()\n{\n \/\/ reset container\n mContainer->clear();\n DynamicObject domains;\n domains->append() = \"*\";\n mContainer->setDefaultDomains(domains);\n\n \/\/ clean up\n mHostAddress.setNull();\n mSslContext.setNull();\n mSocketDataPresenterList.setNull();\n}\n\nbool WebServer::enable(Server* server, const char* name)\n{\n bool rval = true;\n\n \/\/ add http connection service\n mServiceId = server->addConnectionService(\n &(*mHostAddress), mContainer->getServicer(),\n &(*mSocketDataPresenterList), name);\n if(mServiceId == Server::sInvalidServiceId)\n {\n \/\/ could not add connection service\n rval = false;\n }\n else\n {\n mServer = server;\n MO_CAT_INFO(MO_WS_CAT, \"WebServer serving on %s\",\n mHostAddress->toString(false).c_str());\n }\n\n return rval;\n}\n\nvoid WebServer::disable()\n{\n \/\/ remove http connection service\n if(mServiceId != Server::sInvalidServiceId)\n {\n mServer->removePortService(mServiceId);\n mServiceId = Server::sInvalidServiceId;\n mServer = NULL;\n }\n}\n\nvoid WebServer::setContainer(WebServiceContainerRef& c)\n{\n mContainer = c;\n}\n\nWebServiceContainerRef& WebServer::getContainer()\n{\n return mContainer;\n}\n\nInternetAddressRef WebServer::getHostAddress()\n{\n return mHostAddress;\n}\n\nSslContextRef WebServer::getSslContext()\n{\n return mSslContext;\n}\nAdded WebServer name to log output.\/*\n * Copyright (c) 2010 Digital Bazaar, Inc. All rights reserved.\n *\/\n#define __STDC_FORMAT_MACROS\n#define __STDC_LIMIT_MACROS\n#define __STDC_CONSTANT_MACROS\n\n#include \"monarch\/ws\/WebServer.h\"\n\n#include \"monarch\/crypto\/AsymmetricKeyFactory.h\"\n#include \"monarch\/data\/json\/JsonWriter.h\"\n#include \"monarch\/logging\/Logging.h\"\n#include \"monarch\/net\/NullSocketDataPresenter.h\"\n#include \"monarch\/net\/SslSocketDataPresenter.h\"\n\nusing namespace std;\nusing namespace monarch::config;\nusing namespace monarch::crypto;\nusing namespace monarch::data::json;\nusing namespace monarch::http;\nusing namespace monarch::io;\nusing namespace monarch::net;\nusing namespace monarch::rt;\nusing namespace monarch::util;\nusing namespace monarch::ws;\n\nWebServer::WebServer() :\n mServer(NULL),\n mHostAddress(NULL),\n mSslContext(NULL),\n mSocketDataPresenterList(NULL),\n mServiceId(Server::sInvalidServiceId)\n{\n}\n\nWebServer::~WebServer()\n{\n}\n\nbool WebServer::initialize(Config& cfg)\n{\n bool rval = true;\n\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer initializing...\");\n\n \/\/ create default container if one is not set\n if(mContainer.isNull())\n {\n mContainer = new WebServiceContainer();\n }\n\n \/\/ get basic config\n \/\/ security: on\/off\/both\n bool secure;\n bool nonSecure;\n const char* security = cfg[\"security\"]->getString();\n if(strcasecmp(security, \"on\") == 0)\n {\n secure = true;\n nonSecure = false;\n }\n else if(strcasecmp(security, \"off\") == 0)\n {\n secure = false;\n nonSecure = true;\n }\n else\n {\n secure = nonSecure = true;\n }\n\n if(secure)\n {\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer enabling SSL...\");\n\n \/\/ FIXME: make configurable\n \/* Create SSL server context. \"TLS\" is most secure and recent SSL but we\n must use \"ALL\" to handle browsers that use SSL 3.0. *\/\n mSslContext = new SslContext(\"ALL\", false);\n\n \/\/ setup certificate file and private key\n File certFile(cfg[\"certificate\"]->getString());\n File pkeyFile(cfg[\"privateKey\"]->getString());\n\n MO_CAT_DEBUG(MO_WS_CAT,\n \"WebServer setting SSL certificate and private key...\");\n\n \/\/ set certificate and private key for SSL context\n rval =\n mSslContext->setCertificate(certFile) &&\n mSslContext->setPrivateKey(pkeyFile);\n if(rval)\n {\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer reading SSL certificate...\");\n\n \/\/ set default virtual host based on certificate common name\n ByteBuffer b(certFile->getLength());\n rval = certFile.readBytes(&b);\n if(rval)\n {\n MO_CAT_DEBUG(MO_WS_CAT,\n \"WebServer loading SSL certificate from PEM...\");\n\n AsymmetricKeyFactory afk;\n X509CertificateRef cert = afk.loadCertificateFromPem(\n b.data(), b.length());\n rval = !cert.isNull();\n if(rval)\n {\n DynamicObject subject = cert->getSubject();\n string commonName = cert->getField(subject, \"CN\");\n MO_CAT_DEBUG(MO_WS_CAT,\n \"Setting default virtual host to common name: %s\",\n commonName.c_str());\n mSslContext->setVirtualHost(commonName.c_str());\n }\n }\n }\n\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer SSL setup complete.\");\n }\n\n if(rval)\n {\n \/\/ setup host address\n const char* host = cfg[\"host\"]->getString();\n uint32_t port = cfg[\"port\"]->getUInt32();\n mHostAddress = new InternetAddress(host, port);\n\n \/\/ handle socket presentation layer\n mSocketDataPresenterList = new SocketDataPresenterList(true);\n if(secure)\n {\n SslSocketDataPresenter* ssdp =\n new SslSocketDataPresenter(&(*mSslContext));\n mSocketDataPresenterList->add(ssdp);\n }\n if(nonSecure)\n {\n NullSocketDataPresenter* nsdp = new NullSocketDataPresenter();\n mSocketDataPresenterList->add(nsdp);\n }\n\n \/\/ get the list of default domains\n DynamicObject domains(NULL);\n if(cfg->hasMember(\"domains\"))\n {\n domains = cfg[\"domains\"].clone();\n if(domains->length() == 0)\n {\n \/\/ add wildcard if no domains specified\n domains->append() = \"*\";\n }\n }\n else\n {\n \/\/ no specified default domains, so use \"*\"\n domains = DynamicObject();\n domains->append() = \"*\";\n }\n mContainer->setDefaultDomains(domains);\n\n MO_CAT_INFO(MO_WS_CAT, \"WebServer running web services on domains: %s\",\n JsonWriter::writeToString(domains, false, false).c_str());\n }\n\n if(rval)\n {\n MO_CAT_DEBUG(MO_WS_CAT, \"WebServer initialized.\");\n }\n\n return rval;\n}\n\nvoid WebServer::cleanup()\n{\n \/\/ reset container\n mContainer->clear();\n DynamicObject domains;\n domains->append() = \"*\";\n mContainer->setDefaultDomains(domains);\n\n \/\/ clean up\n mHostAddress.setNull();\n mSslContext.setNull();\n mSocketDataPresenterList.setNull();\n}\n\nbool WebServer::enable(Server* server, const char* name)\n{\n bool rval = true;\n\n \/\/ add http connection service\n mServiceId = server->addConnectionService(\n &(*mHostAddress), mContainer->getServicer(),\n &(*mSocketDataPresenterList), name);\n if(mServiceId == Server::sInvalidServiceId)\n {\n \/\/ could not add connection service\n rval = false;\n }\n else\n {\n mServer = server;\n MO_CAT_INFO(MO_WS_CAT, \"WebServer %s serving on %s\",\n name, mHostAddress->toString(false).c_str());\n }\n\n return rval;\n}\n\nvoid WebServer::disable()\n{\n \/\/ remove http connection service\n if(mServiceId != Server::sInvalidServiceId)\n {\n mServer->removePortService(mServiceId);\n mServiceId = Server::sInvalidServiceId;\n mServer = NULL;\n }\n}\n\nvoid WebServer::setContainer(WebServiceContainerRef& c)\n{\n mContainer = c;\n}\n\nWebServiceContainerRef& WebServer::getContainer()\n{\n return mContainer;\n}\n\nInternetAddressRef WebServer::getHostAddress()\n{\n return mHostAddress;\n}\n\nSslContextRef WebServer::getSslContext()\n{\n return mSslContext;\n}\n<|endoftext|>"} {"text":"#include \"Pixel.h\"\n\n#define PIXEL WalrusRPG::Graphics::Pixel\n\nPIXEL::Pixel(std::uint16_t color) : value(color)\n{\n}\n\nPIXEL::Pixel(Pixel &pix) : value((std::uint8_t) pix)\n{\n}\n\nPIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue)\n : b(blue >> 3), g(green >> 2), r(red >> 3)\n{\n}\n\nPIXEL::operator std::uint16_t() const\n{\n return value;\n}\n\nPIXEL &PIXEL::operator=(unsigned value)\n{\n this->value = value;\n return *this;\n}\n\n#define CONST_COLOR(color, r, g, b) \\\n const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b)\nCONST_COLOR(Black, 0, 0, 0);\nCONST_COLOR(White, 255, 255, 255);\nCONST_COLOR(Red, 255, 0, 0);\nCONST_COLOR(Green, 0, 255, 0);\nCONST_COLOR(Blue, 0, 0, 255);\n#undef CONST_COLOR\nFixed pixel copy constructor#include \"Pixel.h\"\n\n#define PIXEL WalrusRPG::Graphics::Pixel\n\nPIXEL::Pixel(std::uint16_t color) : value(color)\n{\n}\n\nPIXEL::Pixel(Pixel &pix) : value(pix.value)\n{\n}\n\nPIXEL::Pixel(std::uint8_t red, std::uint8_t green, std::uint8_t blue)\n : b(blue >> 3), g(green >> 2), r(red >> 3)\n{\n}\n\nPIXEL::operator std::uint16_t() const\n{\n return value;\n}\n\nPIXEL &PIXEL::operator=(unsigned value)\n{\n this->value = value;\n return *this;\n}\n\n#define CONST_COLOR(color, r, g, b) \\\n const WalrusRPG::Graphics::Pixel WalrusRPG::Graphics::color(r, g, b)\nCONST_COLOR(Black, 0, 0, 0);\nCONST_COLOR(White, 255, 255, 255);\nCONST_COLOR(Red, 255, 0, 0);\nCONST_COLOR(Green, 0, 255, 0);\nCONST_COLOR(Blue, 0, 0, 255);\n#undef CONST_COLOR\n<|endoftext|>"} {"text":"\/\/ Copyright 2022 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/internal\/curl_handle_factory.h\"\n#include \n\nnamespace google {\nnamespace cloud {\nnamespace rest_internal {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\nnamespace {\n\nclass PoolFixture : public ::benchmark::Fixture {\n public:\n PoolFixture() : pool_(128) {}\n\n CurlHandleFactory& pool() { return pool_; }\n\n private:\n PooledCurlHandleFactory pool_;\n};\n\nbool CreateAndCleanup(CurlHandleFactory& factory) {\n auto h = factory.CreateHandle();\n auto m = factory.CreateMultiHandle();\n auto const success = h && m;\n factory.CleanupMultiHandle(std::move(m), HandleDisposition::kKeep);\n factory.CleanupHandle(std::move(h), HandleDisposition::kKeep);\n return success;\n}\n\nBENCHMARK_DEFINE_F(PoolFixture, Burst)(benchmark::State& state) {\n for (auto _ : state) {\n if (!CreateAndCleanup(pool())) {\n state.SkipWithError(\"error creating handles\");\n break;\n }\n }\n}\nBENCHMARK_REGISTER_F(PoolFixture, Burst)->ThreadRange(1, 1 << 8)->UseRealTime();\n\nBENCHMARK_DEFINE_F(PoolFixture, Linear)(benchmark::State& state) {\n for (auto _ : state) {\n for (auto i = 0; i != state.range(0); ++i) {\n if (!CreateAndCleanup(pool())) {\n state.SkipWithError(\"error creating handles\");\n break;\n }\n }\n }\n state.SetComplexityN(state.range(0));\n}\nBENCHMARK_REGISTER_F(PoolFixture, Linear)\n ->RangeMultiplier(2)\n ->Ranges({{1, 1 << 10}})\n ->Complexity(benchmark::oN);\n\n} \/\/ namespace\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n} \/\/ namespace rest_internal\n} \/\/ namespace cloud\n} \/\/ namespace google\ndoc(rest): record baseline for HandleFactory benchmark (#9578)\/\/ Copyright 2022 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ https:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \"google\/cloud\/internal\/curl_handle_factory.h\"\n#include \n\nnamespace google {\nnamespace cloud {\nnamespace rest_internal {\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN\nnamespace {\n\nclass PoolFixture : public ::benchmark::Fixture {\n public:\n PoolFixture() : pool_(128) {}\n\n CurlHandleFactory& pool() { return pool_; }\n\n private:\n PooledCurlHandleFactory pool_;\n};\n\nbool CreateAndCleanup(CurlHandleFactory& factory) {\n auto h = factory.CreateHandle();\n auto m = factory.CreateMultiHandle();\n auto const success = h && m;\n factory.CleanupMultiHandle(std::move(m), HandleDisposition::kKeep);\n factory.CleanupHandle(std::move(h), HandleDisposition::kKeep);\n return success;\n}\n\n\/\/ clang-format off\n\/\/ Run on (96 X 2000 MHz CPU s)\n\/\/ CPU Caches:\n\/\/ L1 Data 32 KiB (x48)\n\/\/ L1 Instruction 32 KiB (x48)\n\/\/ L2 Unified 1024 KiB (x48)\n\/\/ L3 Unified 39424 KiB (x2)\n\/\/ Load Average: 15.12, 5.10, 1.98\n\/\/----------------------------------------------------------------------------------\n\/\/ Benchmark Time CPU Iterations\n\/\/----------------------------------------------------------------------------------\n\/\/ PoolFixture\/Burst\/real_time\/threads:1 611 ns 611 ns 1138757\n\/\/ PoolFixture\/Burst\/real_time\/threads:2 753 ns 1503 ns 931064\n\/\/ PoolFixture\/Burst\/real_time\/threads:4 912 ns 3460 ns 775028\n\/\/ PoolFixture\/Burst\/real_time\/threads:8 977 ns 6946 ns 719024\n\/\/ PoolFixture\/Burst\/real_time\/threads:16 1038 ns 14855 ns 645392\n\/\/ PoolFixture\/Burst\/real_time\/threads:32 1280 ns 38140 ns 570144\n\/\/ PoolFixture\/Burst\/real_time\/threads:64 1665 ns 101765 ns 510976\n\/\/ PoolFixture\/Burst\/real_time\/threads:128 1846 ns 172375 ns 388736\n\/\/ PoolFixture\/Burst\/real_time\/threads:256 1859 ns 180947 ns 377600\n\/\/ clang-format on\nBENCHMARK_DEFINE_F(PoolFixture, Burst)(benchmark::State& state) {\n for (auto _ : state) {\n if (!CreateAndCleanup(pool())) {\n state.SkipWithError(\"error creating handles\");\n break;\n }\n }\n}\nBENCHMARK_REGISTER_F(PoolFixture, Burst)->ThreadRange(1, 1 << 8)->UseRealTime();\n\n\/\/ clang-format off\n\/\/ Run on (96 X 2000 MHz CPU s)\n\/\/ CPU Caches:\n\/\/ L1 Data 32 KiB (x48)\n\/\/ L1 Instruction 32 KiB (x48)\n\/\/ L2 Unified 1024 KiB (x48)\n\/\/ L3 Unified 39424 KiB (x2)\n\/\/ Load Average: 10.79, 7.87, 3.39\n\/\/------------------------------------------------------------------\n\/\/ Benchmark Time CPU Iterations\n\/\/------------------------------------------------------------------\n\/\/ PoolFixture\/Linear\/1 628 ns 628 ns 1098609\n\/\/ PoolFixture\/Linear\/2 1255 ns 1255 ns 553833\n\/\/ PoolFixture\/Linear\/4 2491 ns 2490 ns 278630\n\/\/ PoolFixture\/Linear\/8 4967 ns 4967 ns 140583\n\/\/ PoolFixture\/Linear\/16 9935 ns 9935 ns 70534\n\/\/ PoolFixture\/Linear\/32 19896 ns 19892 ns 35236\n\/\/ PoolFixture\/Linear\/64 39706 ns 39700 ns 17636\n\/\/ PoolFixture\/Linear\/128 79433 ns 79428 ns 8816\n\/\/ PoolFixture\/Linear\/256 159164 ns 159102 ns 4392\n\/\/ PoolFixture\/Linear\/512 318709 ns 318687 ns 2202\n\/\/ PoolFixture\/Linear\/1024 638671 ns 638514 ns 1098\n\/\/ PoolFixture\/Linear_BigO 623.33 N 623.20 N\n\/\/ PoolFixture\/Linear_RMS 0 % 0 %\n\/\/ clang-format on\nBENCHMARK_DEFINE_F(PoolFixture, Linear)(benchmark::State& state) {\n for (auto _ : state) {\n for (auto i = 0; i != state.range(0); ++i) {\n if (!CreateAndCleanup(pool())) {\n state.SkipWithError(\"error creating handles\");\n break;\n }\n }\n }\n state.SetComplexityN(state.range(0));\n}\nBENCHMARK_REGISTER_F(PoolFixture, Linear)\n ->RangeMultiplier(2)\n ->Ranges({{1, 1 << 10}})\n ->Complexity(benchmark::oN);\n\n} \/\/ namespace\nGOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END\n} \/\/ namespace rest_internal\n} \/\/ namespace cloud\n} \/\/ namespace google\n<|endoftext|>"} {"text":"\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qHasFeature_OpenSSL\n#include \n#include \n#endif\n\n#include \"..\/..\/Containers\/Common.h\"\n#include \"..\/..\/Debug\/Assertions.h\"\n#include \"..\/..\/Execution\/Common.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"OpenSSLCryptoStream.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Cryptography;\nusing namespace Stroika::Foundation::Cryptography::Encoding;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::Streams;\n\nusing Memory::BLOB;\n\n\n\/\/ @todo examine\/test https:\/\/github.com\/saju\/misc\/blob\/master\/misc\/openssl_aes.c\n\n\n\n#if qHasFeature_OpenSSL && defined (_MSC_VER)\n\/\/ Use #pragma comment lib instead of explicit entry in the lib entry of the project file\n#pragma comment (lib, \"libeay32.lib\")\n#pragma comment (lib, \"ssleay32.lib\")\n#endif\n\n\n\n\n\/\/\/\/ VERY ROUGH DRAFT - NOT VERY CLOSE TO CORRECT FOR ALL ALGORITHSM\n\/\/\/\/ SEE http:\/\/www.openssl.org\/docs\/crypto\/EVP_EncryptInit.html\n\/\/\/ SEE https:\/\/wiki.openssl.org\/index.php\/EVP_Symmetric_Encryption_and_Decryption\n\/\/\/\/ for details on what todo\n\n\n#if qHasFeature_OpenSSL\nnamespace {\n struct InOutStrmCommon_ {\n InOutStrmCommon_ (const OpenSSLCryptoParams& cryptoParams, Direction d)\n : fCTX_ ()\n , fFinalCalled_ (false)\n {\n ::EVP_CIPHER_CTX_init (&fCTX_);\n cryptoParams.fInitializer (&fCTX_, d);\n }\n InOutStrmCommon_ (const InOutStrmCommon_&) = delete;\n InOutStrmCommon_& operator= (const InOutStrmCommon_&) = delete;\n ~InOutStrmCommon_ ()\n {\n Verify (::EVP_CIPHER_CTX_cleanup (&fCTX_) == 1);\n }\n static constexpr size_t _GetMinOutBufSize (size_t n)\n {\n return n + EVP_MAX_BLOCK_LENGTH;\n }\n \/\/ return nBytes in outBuf, throws on error\n size_t _runOnce (const Byte* data2ProcessStart, const Byte* data2ProcessEnd, Byte* outBufStart, Byte* outBufEnd)\n {\n Require (outBufStart <= outBufEnd and static_cast (outBufEnd - outBufStart) >= _GetMinOutBufSize (data2ProcessEnd - data2ProcessStart)); \/\/ always need out buf big enuf for inbuf\n int outLen = 0;\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherUpdate (&fCTX_, outBufStart, &outLen, data2ProcessStart, static_cast (data2ProcessEnd - data2ProcessStart)));\n Ensure (outLen >= 0);\n Ensure (outLen <= (outBufEnd - outBufStart));\n return size_t (outLen);\n }\n \/\/ return nBytes in outBuf, throws on error\n \/\/ Can call multiple times - it keeps track itself if finalized.\n size_t _cipherFinal (Byte* outBufStart, Byte* outBufEnd)\n {\n Require (outBufStart <= outBufEnd and static_cast (outBufEnd - outBufStart) >= _GetMinOutBufSize (0));\n if (fFinalCalled_) {\n return 0; \/\/ not an error - just zero more bytes\n }\n int outLen = 0;\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherFinal_ex (&fCTX_, outBufStart, &outLen));\n fFinalCalled_ = true;\n Ensure (outLen >= 0);\n Ensure (outLen <= (outBufEnd - outBufStart));\n return size_t (outLen);\n }\n EVP_CIPHER_CTX fCTX_;\n bool fFinalCalled_;\n };\n}\n#endif\n\n\n\n#if qHasFeature_OpenSSL\nclass OpenSSLInputStream::IRep_ : public InputStream::_IRep, private InOutStrmCommon_ {\nprivate:\n DEFINE_CONSTEXPR_CONSTANT(size_t, kInBufSize_, 10 * 1024);\n\npublic:\n IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const InputStream& realIn)\n : InputStream::_IRep ()\n , InOutStrmCommon_ (cryptoParams, d)\n , fCriticalSection_ ()\n , fOutBuf_ (_GetMinOutBufSize (kInBufSize_))\n , fOutBufStart_ (nullptr)\n , fOutBufEnd_ (nullptr)\n , fRealIn_ (realIn)\n {\n }\n virtual bool IsSeekable () const override\n {\n return false;\n }\n virtual SeekOffsetType GetReadOffset () const override\n {\n RequireNotReached ();\n return 0;\n }\n virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached ();\n return 0;\n }\n virtual size_t Read (SeekOffsetType* offset, Byte* intoStart, Byte* intoEnd) override\n {\n Require (offset == nullptr); \/\/ not seekable\n \/*\n * Keep track if unread bytes in fOutBuf_ - bounded by fOutBufStart_ and fOutBufEnd_.\n * If none to read there - pull from fRealIn_ src, and push those through the cipher.\n * and use that to re-populate fOutBuf_.\n *\/\n Require (intoStart < intoEnd);\n auto critSec { Execution::make_unique_lock (fCriticalSection_) };\n if (fOutBufStart_ == fOutBufEnd_) {\n Byte toDecryptBuf[kInBufSize_];\n size_t n2Decrypt = fRealIn_.Read (begin (toDecryptBuf), end (toDecryptBuf));\n if (n2Decrypt == 0) {\n size_t nBytesInOutBuf = _cipherFinal (fOutBuf_.begin (), fOutBuf_.end ());\n Assert (nBytesInOutBuf <= fOutBuf_.GetSize ());\n fOutBufStart_ = fOutBuf_.begin ();\n fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf;\n }\n else {\n fOutBuf_.GrowToSize (_GetMinOutBufSize (NEltsOf (toDecryptBuf)));\n size_t nBytesInOutBuf = _runOnce (begin (toDecryptBuf), begin (toDecryptBuf) + n2Decrypt, fOutBuf_.begin (), fOutBuf_.end ());\n Assert (nBytesInOutBuf <= fOutBuf_.GetSize ());\n fOutBufStart_ = fOutBuf_.begin ();\n fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf;\n }\n }\n if (fOutBufStart_ < fOutBufEnd_) {\n size_t n2Copy = min (fOutBufEnd_ - fOutBufStart_, intoEnd - intoStart);\n (void)::memcpy (intoStart, fOutBufStart_, n2Copy);\n fOutBufStart_ += n2Copy;\n return n2Copy;\n }\n return 0; \/\/ EOF\n }\n\nprivate:\n mutable mutex fCriticalSection_;\n Memory::SmallStackBuffer < Byte, kInBufSize_ + EVP_MAX_BLOCK_LENGTH > fOutBuf_;\n Byte* fOutBufStart_;\n Byte* fOutBufEnd_;\n InputStream fRealIn_;\n};\n#endif\n\n\n\n\n\n\n#if qHasFeature_OpenSSL\nclass OpenSSLOutputStream::IRep_ : public OutputStream::_IRep, private InOutStrmCommon_ {\npublic:\n IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const OutputStream& realOut)\n : OutputStream::_IRep ()\n , InOutStrmCommon_ (cryptoParams, d)\n , fCriticalSection_ ()\n , fRealOut_ (realOut)\n {\n }\n virtual ~IRep_ ()\n {\n \/\/ no need for critical section because at most one thread can be running DTOR at a time, and no other methods can be running\n try {\n Flush ();\n }\n catch (...) {\n \/\/ not great to do in DTOR, because we must drop exceptions on the floor!\n }\n }\n virtual bool IsSeekable () const override\n {\n return false;\n }\n virtual SeekOffsetType GetWriteOffset () const override\n {\n RequireNotReached ();\n return 0;\n }\n virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached ();\n return 0;\n }\n \/\/ pointer must refer to valid memory at least bufSize long, and cannot be nullptr. BufSize must always be >= 1.\n \/\/ Writes always succeed fully or throw.\n virtual void Write (const Byte* start, const Byte* end) override\n {\n Require (start < end); \/\/ for OutputStream - this funciton requires non-empty write\n Memory::SmallStackBuffer < Byte, 1000 + EVP_MAX_BLOCK_LENGTH > outBuf (_GetMinOutBufSize (end - start));\n auto critSec { Execution::make_unique_lock (fCriticalSection_) };\n size_t nBytesEncypted = _runOnce (start, end, outBuf.begin (), outBuf.end ());\n Assert (nBytesEncypted <= outBuf.GetSize ());\n fRealOut_.Write (outBuf.begin (), outBuf.begin () + nBytesEncypted);\n }\n\n virtual void Flush () override\n {\n Byte outBuf[EVP_MAX_BLOCK_LENGTH];\n size_t nBytesInOutBuf = _cipherFinal (begin (outBuf), end (outBuf));\n Assert (nBytesInOutBuf < sizeof (outBuf));\n fRealOut_.Write (begin (outBuf), begin (outBuf) + nBytesInOutBuf);\n }\n\nprivate:\n mutable recursive_mutex fCriticalSection_;\n OutputStream fRealOut_;\n};\n#endif\n\n\n\n\n\n\n\n\n\n#if qHasFeature_OpenSSL\n\/*\n ********************************************************************************\n ******************** Cryptography::OpenSSLInputStream **************************\n ********************************************************************************\n *\/\nnamespace {\n void ApplySettings2CTX_ (EVP_CIPHER_CTX* ctx, const EVP_CIPHER* cipher, Direction d, bool nopad, bool useArgumentKeyLength, const Memory::BLOB& key, const Memory::BLOB& initialIV)\n {\n RequireNotNull (ctx);\n RequireNotNull (cipher);\n bool enc = (d == Direction::eEncrypt);\n if (nopad) {\n Verify (::EVP_CIPHER_CTX_set_padding (ctx, 0) == 1);\n }\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, cipher, NULL, nullptr, nullptr, enc));\n size_t keyLen = EVP_CIPHER_CTX_key_length (ctx);\n size_t ivLen = EVP_CIPHER_CTX_iv_length (ctx);\n\n if (useArgumentKeyLength) {\n keyLen = key.length ();\n Verify (::EVP_CIPHER_CTX_set_key_length (ctx, static_cast (keyLen)) == 1);\n }\n\n Memory::SmallStackBuffer useKey { keyLen };\n Memory::SmallStackBuffer useIV { ivLen };\n\n memset (useKey.begin (), 0, keyLen);\n memset (useIV.begin (), 0, ivLen);\n\n memcpy (useKey.begin (), key.begin (), min(keyLen, key.size ()));\n memcpy (useIV.begin (), initialIV.begin (), min(ivLen, initialIV.size ()));\n\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, nullptr, NULL, useKey.begin (), useIV.begin (), enc));\n }\n}\n\nOpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, Memory::BLOB key, Memory::BLOB initialIV)\n : fInitializer ()\n{\n bool nopad = false;\n switch (alg) {\n case CipherAlgorithm::eRC2_CBC: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_cbc (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC2_ECB: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_ecb (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC2_CFB: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_cfb (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC2_OFB: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_ofb (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC4: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc4 (), d, nopad, true, key, initialIV);\n };\n }\n break;\n default: {\n fInitializer = [alg, nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, Convert2OpenSSL (alg), d, nopad, false, key, initialIV);\n };\n break;\n\n }\n }\n}\n\nOpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, const DerivedKey& derivedKey)\n : OpenSSLCryptoParams (alg, derivedKey.fKey, derivedKey.fIV)\n{\n}\n#endif\n\n\n\n\n\n#if qHasFeature_OpenSSL\n\/*\n ********************************************************************************\n ******************** Cryptography::OpenSSLInputStream **************************\n ********************************************************************************\n *\/\nOpenSSLInputStream::OpenSSLInputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const InputStream& realIn)\n : InputStream (make_shared (cryptoParams, direction, realIn))\n{\n}\n#endif\n\n\n\n\n\n#if qHasFeature_OpenSSL\n\/*\n ********************************************************************************\n ******************* Cryptography::OpenSSLOutputStream **************************\n ********************************************************************************\n *\/\nOpenSSLOutputStream::OpenSSLOutputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const OutputStream& realOut)\n : OutputStream (make_shared (cryptoParams, direction, realOut))\n{\n}\n#endif\nfixed https:\/\/stroika.atlassian.net\/browse\/STK-193 - issue with short encrpytions failing with block ciphers - was bug in pull code in streams\/*\n * Copyright(c) Sophist Solutions, Inc. 1990-2016. All rights reserved\n *\/\n#include \"..\/..\/StroikaPreComp.h\"\n\n#if qHasFeature_OpenSSL\n#include \n#include \n#endif\n\n#include \"..\/..\/Containers\/Common.h\"\n#include \"..\/..\/Debug\/Assertions.h\"\n#include \"..\/..\/Execution\/Common.h\"\n#include \"..\/..\/Memory\/SmallStackBuffer.h\"\n\n#include \"OpenSSLCryptoStream.h\"\n\n\nusing namespace Stroika::Foundation;\nusing namespace Stroika::Foundation::Containers;\nusing namespace Stroika::Foundation::Cryptography;\nusing namespace Stroika::Foundation::Cryptography::Encoding;\nusing namespace Stroika::Foundation::Memory;\nusing namespace Stroika::Foundation::Streams;\n\nusing Memory::BLOB;\n\n\n\/\/ @todo examine\/test https:\/\/github.com\/saju\/misc\/blob\/master\/misc\/openssl_aes.c\n\n\n\n#if qHasFeature_OpenSSL && defined (_MSC_VER)\n\/\/ Use #pragma comment lib instead of explicit entry in the lib entry of the project file\n#pragma comment (lib, \"libeay32.lib\")\n#pragma comment (lib, \"ssleay32.lib\")\n#endif\n\n\n\n\n\/\/\/\/ VERY ROUGH DRAFT - NOT VERY CLOSE TO CORRECT FOR ALL ALGORITHSM\n\/\/\/\/ SEE http:\/\/www.openssl.org\/docs\/crypto\/EVP_EncryptInit.html\n\/\/\/ SEE https:\/\/wiki.openssl.org\/index.php\/EVP_Symmetric_Encryption_and_Decryption\n\/\/\/\/ for details on what todo\n\n\n#if qHasFeature_OpenSSL\nnamespace {\n struct InOutStrmCommon_ {\n InOutStrmCommon_ (const OpenSSLCryptoParams& cryptoParams, Direction d)\n : fCTX_ ()\n , fFinalCalled_ (false)\n {\n ::EVP_CIPHER_CTX_init (&fCTX_);\n cryptoParams.fInitializer (&fCTX_, d);\n }\n InOutStrmCommon_ (const InOutStrmCommon_&) = delete;\n InOutStrmCommon_& operator= (const InOutStrmCommon_&) = delete;\n ~InOutStrmCommon_ ()\n {\n Verify (::EVP_CIPHER_CTX_cleanup (&fCTX_) == 1);\n }\n static constexpr size_t _GetMinOutBufSize (size_t n)\n {\n return n + EVP_MAX_BLOCK_LENGTH;\n }\n \/\/ return nBytes in outBuf, throws on error\n size_t _runOnce (const Byte* data2ProcessStart, const Byte* data2ProcessEnd, Byte* outBufStart, Byte* outBufEnd)\n {\n Require (outBufStart <= outBufEnd and static_cast (outBufEnd - outBufStart) >= _GetMinOutBufSize (data2ProcessEnd - data2ProcessStart)); \/\/ always need out buf big enuf for inbuf\n int outLen = 0;\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherUpdate (&fCTX_, outBufStart, &outLen, data2ProcessStart, static_cast (data2ProcessEnd - data2ProcessStart)));\n Ensure (outLen >= 0);\n Ensure (outLen <= (outBufEnd - outBufStart));\n return size_t (outLen);\n }\n \/\/ return nBytes in outBuf, throws on error\n \/\/ Can call multiple times - it keeps track itself if finalized.\n size_t _cipherFinal (Byte* outBufStart, Byte* outBufEnd)\n {\n Require (outBufStart <= outBufEnd and static_cast (outBufEnd - outBufStart) >= _GetMinOutBufSize (0));\n if (fFinalCalled_) {\n return 0; \/\/ not an error - just zero more bytes\n }\n int outLen = 0;\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherFinal_ex (&fCTX_, outBufStart, &outLen));\n fFinalCalled_ = true;\n Ensure (outLen >= 0);\n Ensure (outLen <= (outBufEnd - outBufStart));\n return size_t (outLen);\n }\n EVP_CIPHER_CTX fCTX_;\n bool fFinalCalled_;\n };\n}\n#endif\n\n\n\n#if qHasFeature_OpenSSL\nclass OpenSSLInputStream::IRep_ : public InputStream::_IRep, private InOutStrmCommon_ {\nprivate:\n DEFINE_CONSTEXPR_CONSTANT(size_t, kInBufSize_, 10 * 1024);\n\npublic:\n IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const InputStream& realIn)\n : InputStream::_IRep ()\n , InOutStrmCommon_ (cryptoParams, d)\n , fCriticalSection_ ()\n , fOutBuf_ (_GetMinOutBufSize (kInBufSize_))\n , fOutBufStart_ (nullptr)\n , fOutBufEnd_ (nullptr)\n , fRealIn_ (realIn)\n {\n }\n virtual bool IsSeekable () const override\n {\n return false;\n }\n virtual SeekOffsetType GetReadOffset () const override\n {\n RequireNotReached ();\n return 0;\n }\n virtual SeekOffsetType SeekRead (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached ();\n return 0;\n }\n virtual size_t Read (SeekOffsetType* offset, Byte* intoStart, Byte* intoEnd) override\n {\n Require (offset == nullptr); \/\/ not seekable\n \/*\n * Keep track if unread bytes in fOutBuf_ - bounded by fOutBufStart_ and fOutBufEnd_.\n * If none to read there - pull from fRealIn_ src, and push those through the cipher.\n * and use that to re-populate fOutBuf_.\n *\/\n Require (intoStart < intoEnd);\n auto critSec { Execution::make_unique_lock (fCriticalSection_) };\n if (fOutBufStart_ == fOutBufEnd_) {\n \/*\n * Then pull from 'real in' stream until we have reach EOF there, or until we have some bytes to output\n * on our own.\n *\/\n Byte toDecryptBuf[kInBufSize_];\nAgain:\n size_t n2Decrypt = fRealIn_.Read (begin (toDecryptBuf), end (toDecryptBuf));\n if (n2Decrypt == 0) {\n size_t nBytesInOutBuf = _cipherFinal (fOutBuf_.begin (), fOutBuf_.end ());\n Assert (nBytesInOutBuf <= fOutBuf_.GetSize ());\n fOutBufStart_ = fOutBuf_.begin ();\n fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf;\n }\n else {\n fOutBuf_.GrowToSize (_GetMinOutBufSize (NEltsOf (toDecryptBuf)));\n size_t nBytesInOutBuf = _runOnce (begin (toDecryptBuf), begin (toDecryptBuf) + n2Decrypt, fOutBuf_.begin (), fOutBuf_.end ());\n Assert (nBytesInOutBuf <= fOutBuf_.GetSize ());\n if (nBytesInOutBuf == 0) {\n \/\/ This can happen with block ciphers - we put stuff in, and get nothing out. But we cannot return EOF\n \/\/ yet, so try again...\n goto Again;\n }\n else {\n fOutBufStart_ = fOutBuf_.begin ();\n fOutBufEnd_ = fOutBufStart_ + nBytesInOutBuf;\n }\n }\n }\n if (fOutBufStart_ < fOutBufEnd_) {\n size_t n2Copy = min (fOutBufEnd_ - fOutBufStart_, intoEnd - intoStart);\n (void)::memcpy (intoStart, fOutBufStart_, n2Copy);\n fOutBufStart_ += n2Copy;\n return n2Copy;\n }\n return 0; \/\/ EOF\n }\n\nprivate:\n mutable mutex fCriticalSection_;\n Memory::SmallStackBuffer < Byte, kInBufSize_ + EVP_MAX_BLOCK_LENGTH > fOutBuf_;\n Byte* fOutBufStart_;\n Byte* fOutBufEnd_;\n InputStream fRealIn_;\n};\n#endif\n\n\n\n\n\n\n#if qHasFeature_OpenSSL\nclass OpenSSLOutputStream::IRep_ : public OutputStream::_IRep, private InOutStrmCommon_ {\npublic:\n IRep_ (const OpenSSLCryptoParams& cryptoParams, Direction d, const OutputStream& realOut)\n : OutputStream::_IRep ()\n , InOutStrmCommon_ (cryptoParams, d)\n , fCriticalSection_ ()\n , fRealOut_ (realOut)\n {\n }\n virtual ~IRep_ ()\n {\n \/\/ no need for critical section because at most one thread can be running DTOR at a time, and no other methods can be running\n try {\n Flush ();\n }\n catch (...) {\n \/\/ not great to do in DTOR, because we must drop exceptions on the floor!\n }\n }\n virtual bool IsSeekable () const override\n {\n return false;\n }\n virtual SeekOffsetType GetWriteOffset () const override\n {\n RequireNotReached ();\n return 0;\n }\n virtual SeekOffsetType SeekWrite (Whence whence, SignedSeekOffsetType offset) override\n {\n RequireNotReached ();\n return 0;\n }\n \/\/ pointer must refer to valid memory at least bufSize long, and cannot be nullptr. BufSize must always be >= 1.\n \/\/ Writes always succeed fully or throw.\n virtual void Write (const Byte* start, const Byte* end) override\n {\n Require (start < end); \/\/ for OutputStream - this funciton requires non-empty write\n Memory::SmallStackBuffer < Byte, 1000 + EVP_MAX_BLOCK_LENGTH > outBuf (_GetMinOutBufSize (end - start));\n auto critSec { Execution::make_unique_lock (fCriticalSection_) };\n size_t nBytesEncypted = _runOnce (start, end, outBuf.begin (), outBuf.end ());\n Assert (nBytesEncypted <= outBuf.GetSize ());\n fRealOut_.Write (outBuf.begin (), outBuf.begin () + nBytesEncypted);\n }\n\n virtual void Flush () override\n {\n Byte outBuf[EVP_MAX_BLOCK_LENGTH];\n size_t nBytesInOutBuf = _cipherFinal (begin (outBuf), end (outBuf));\n Assert (nBytesInOutBuf < sizeof (outBuf));\n fRealOut_.Write (begin (outBuf), begin (outBuf) + nBytesInOutBuf);\n }\n\nprivate:\n mutable recursive_mutex fCriticalSection_;\n OutputStream fRealOut_;\n};\n#endif\n\n\n\n\n\n\n\n\n\n#if qHasFeature_OpenSSL\n\/*\n ********************************************************************************\n ******************** Cryptography::OpenSSLInputStream **************************\n ********************************************************************************\n *\/\nnamespace {\n void ApplySettings2CTX_ (EVP_CIPHER_CTX* ctx, const EVP_CIPHER* cipher, Direction d, bool nopad, bool useArgumentKeyLength, const Memory::BLOB& key, const Memory::BLOB& initialIV)\n {\n RequireNotNull (ctx);\n RequireNotNull (cipher);\n bool enc = (d == Direction::eEncrypt);\n if (nopad) {\n Verify (::EVP_CIPHER_CTX_set_padding (ctx, 0) == 1);\n }\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, cipher, NULL, nullptr, nullptr, enc));\n size_t keyLen = EVP_CIPHER_CTX_key_length (ctx);\n size_t ivLen = EVP_CIPHER_CTX_iv_length (ctx);\n\n if (useArgumentKeyLength) {\n keyLen = key.length ();\n Verify (::EVP_CIPHER_CTX_set_key_length (ctx, static_cast (keyLen)) == 1);\n }\n\n Memory::SmallStackBuffer useKey { keyLen };\n Memory::SmallStackBuffer useIV { ivLen };\n\n memset (useKey.begin (), 0, keyLen);\n memset (useIV.begin (), 0, ivLen);\n\n memcpy (useKey.begin (), key.begin (), min(keyLen, key.size ()));\n memcpy (useIV.begin (), initialIV.begin (), min(ivLen, initialIV.size ()));\n\n Cryptography::OpenSSL::Exception::ThrowLastErrorIfFailed (::EVP_CipherInit_ex (ctx, nullptr, NULL, useKey.begin (), useIV.begin (), enc));\n }\n}\n\nOpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, Memory::BLOB key, Memory::BLOB initialIV)\n : fInitializer ()\n{\n bool nopad = false;\n switch (alg) {\n case CipherAlgorithm::eRC2_CBC: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_cbc (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC2_ECB: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_ecb (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC2_CFB: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_cfb (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC2_OFB: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc2_ofb (), d, nopad, true, key, initialIV);\n };\n }\n break;\n case CipherAlgorithm::eRC4: {\n fInitializer = [nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, ::EVP_rc4 (), d, nopad, true, key, initialIV);\n };\n }\n break;\n default: {\n fInitializer = [alg, nopad, key, initialIV] (EVP_CIPHER_CTX * ctx, Direction d) {\n ApplySettings2CTX_ (ctx, Convert2OpenSSL (alg), d, nopad, false, key, initialIV);\n };\n break;\n\n }\n }\n}\n\nOpenSSLCryptoParams::OpenSSLCryptoParams (CipherAlgorithm alg, const DerivedKey& derivedKey)\n : OpenSSLCryptoParams (alg, derivedKey.fKey, derivedKey.fIV)\n{\n}\n#endif\n\n\n\n\n\n#if qHasFeature_OpenSSL\n\/*\n ********************************************************************************\n ******************** Cryptography::OpenSSLInputStream **************************\n ********************************************************************************\n *\/\nOpenSSLInputStream::OpenSSLInputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const InputStream& realIn)\n : InputStream (make_shared (cryptoParams, direction, realIn))\n{\n}\n#endif\n\n\n\n\n\n#if qHasFeature_OpenSSL\n\/*\n ********************************************************************************\n ******************* Cryptography::OpenSSLOutputStream **************************\n ********************************************************************************\n *\/\nOpenSSLOutputStream::OpenSSLOutputStream (const OpenSSLCryptoParams& cryptoParams, Direction direction, const OutputStream& realOut)\n : OutputStream (make_shared (cryptoParams, direction, realOut))\n{\n}\n#endif\n<|endoftext|>"} {"text":"#include \"instantiationconstraint.h\"\n\n#include \n\nInstantiationConstraint::InstantiationConstraint(DeviserValidator *validator)\n : DeviserConstraint(validator)\n{\n\n}\n\nint InstantiationConstraint::analyzePackage(DeviserPackage *package)\n{\n int errors = 0;\n\n foreach (DeviserVersion* version, package->getVersions())\n {\n foreach(DeviserClass* pClass, version ->getElements())\n {\n foreach(DeviserConcrete* instantiation, pClass->getConcretes())\n {\n if (instantiation->getElement().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"The instantiation '\"\n << instantiation->getName()\n << \"' has no element defined, this is a required attribute.\");\n ++errors;\n }\n }\n }\n\n }\n\n return errors;\n}\n- issue #111045570: also validate that there is a name specified#include \"instantiationconstraint.h\"\n\n#include \n\nInstantiationConstraint::InstantiationConstraint(DeviserValidator *validator)\n : DeviserConstraint(validator)\n{\n\n}\n\nint InstantiationConstraint::analyzePackage(DeviserPackage *package)\n{\n int errors = 0;\n\n foreach (DeviserVersion* version, package->getVersions())\n {\n foreach(DeviserClass* pClass, version ->getElements())\n {\n foreach(DeviserConcrete* instantiation, pClass->getConcretes())\n {\n if (instantiation->getName().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"In class '\"\n << pClass->getName()\n << \"' an instantiation has no XML name, this is a required attribute.\");\n ++errors;\n }\n if (instantiation->getElement().isEmpty())\n {\n ADD_MESSAGE_WITH_SEVERITY(DEVISER_ERROR, \"The instantiation '\"\n << instantiation->getName()\n << \"' has no element defined, this is a required attribute.\");\n ++errors;\n }\n }\n }\n\n }\n\n return errors;\n}\n<|endoftext|>"} {"text":"#include \"precomp.h\"\n#include \"game_object_types.h\"\n#include \"game_object_manager.h\"\n#include \"game_object.h\"\n#include \"player.h\"\n#include \"..\/tile_chunk.h\"\n#include \"throwable_object.h\"\n#include \"..\/net\/message.h\"\n\nclan::Sprite Player::s_rw, \n\t\t\t Player::s_lw, \n\t\t\t Player::s_uw, \n\t\t\t Player::s_dw,\n\t\t\t Player::s_h;\n\nstatic clan::Font title;\n\nPlayer::Player(uint32_t guid): GameObject(type(),guid)\n{\n\tkeys=add_property(\"keys\",0);\n\tlife=add_property(\"life\",100);\n\tkills=add_property(\"kills\",0);\n\tkiller=add_property(\"killer\");\n\tname=add_property(\"name\",\"Sir. Waitfor Servereply\");\n\n\tclan::Contour contour;\n\tcontour.get_points().push_back(clan::Pointf(16,13));\n\tcontour.get_points().push_back(clan::Pointf(16,63));\n\tcontour.get_points().push_back(clan::Pointf(47,63));\n\tcontour.get_points().push_back(clan::Pointf(47,13));\n\n\tm_outline.get_contours().push_back(contour);\n\tm_outline.calculate_radius();\n\tm_outline.calculate_smallest_enclosing_discs();\n\t\n\tm_next_attack_time = 0;\n}\n\nPlayer::~Player()\n{\n\n}\n\nuint32_t Player::get_next_attack_time()\n{\n\treturn m_next_attack_time;\n}\n\nvoid Player::set_next_attack_time(uint32_t time)\n{\n\tm_next_attack_time = time;\n}\n\nclan::Colorf Player::get_hp_bar_color()\n{\n\tfloat r,g;\n\tr = 1.0f - (float)life\/100;\n\tg = (float)life\/100;\n\treturn clan::Colorf(r,g,0.0f,1.0f);\n}\n\nbool Player::preload(clan::Canvas & canvas, clan::ResourceManager & resources)\n{\n\ttitle = clan::Font(canvas,\"Arial\",12); \/\/\/DON'T CHANGE EVEN AGAIN\n\ts_rw = clan::Sprite::resource(canvas, \"champ_rw\", resources );\n\ts_lw = clan::Sprite::resource(canvas, \"champ_lw\", resources );\n\ts_uw = clan::Sprite::resource(canvas, \"champ_uw\", resources );\n\ts_dw = clan::Sprite::resource(canvas, \"champ_dw\", resources );\n\n\ts_h = clan::Sprite::resource(canvas, \"hp_bar\", resources );\n\n\treturn true;\n}\n\nvoid Player::free()\n{\n\ts_rw = clan::Sprite();\n\ts_lw = clan::Sprite();\n\ts_uw = clan::Sprite();\n\ts_dw = clan::Sprite();\n\n\ts_h = clan::Sprite();\n\n\ttitle = clan::Font();\n}\n\nvoid Player::load(clan::Canvas & canvas, clan::ResourceManager & resources)\n{\n\tm_rw = s_rw.clone();\n\tm_lw = s_lw.clone();\n\tm_uw = s_uw.clone();\n\tm_dw = s_dw.clone();\n\n\tm_h = s_h.clone();\n\n\tm_sprite=m_dw;\n\tclan::Console::write_line(\"is null: %1\",m_sprite.is_null());\n}\n\nvoid Player::update(const clan::GameTime & time)\n{\n\tif(!m_sprite.is_null())\n\t\tm_sprite.update(time.get_time_elapsed_ms());\n\t\/\/m_pos.data().x += 16.0f * (float)time.get_time_elapsed_ms()\/1000.0f;\n\n\tlast_pos = m_pos.get();\n\tif(keys&EUIKT_MOVE_LEFT && m_pos.get().x>-20.0f)\n\t{\n\t\tm_sprite=m_lw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.x-= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\tif(keys&EUIKT_MOVE_RIGHT && m_pos.get().x<980.0f)\n\t{\n\t\tm_sprite=m_rw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.x+= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\tif(keys&EUIKT_MOVE_UP && m_pos.get().y>0.0f)\n\t{\n\t\tm_sprite=m_uw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.y-= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\tif(keys&EUIKT_MOVE_DOWN && m_pos.get().y<660.0f)\n\t{\n\t\tm_sprite=m_dw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.y+= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\n\tm_outline.set_translation(m_pos.get().x,m_pos.get().y);\n}\n\nvoid Player::render(clan::Canvas & c, const clan::vec2 & offset)\n{\n#if defined GAME_CLIENT\n\tif(!m_sprite.is_null())\n\t{\n\t\tm_sprite.draw(c, m_pos.get().x+offset.x, m_pos.get().y+offset.y);\n\t\tc.fill_rect(m_pos.get().x+offset.x+10, m_pos.get().y+offset.y-1, m_pos.get().x+offset.x+10+(44*life\/100), m_pos.get().y+offset.y+8, get_hp_bar_color());\n\t\tm_h.draw(c,m_pos.get().x+offset.x, m_pos.get().y+offset.y-5);\n\t\tm_outline.draw(offset.x,offset.y,clan::Colorf(1,0,0,1),c);\n\n\t\ttitle.draw_text(c, m_pos.get().x+offset.x+6,m_pos.get().y+offset.y-8, name.get()+\": \"+clan::StringHelp::uint_to_text(kills.get()), get_hp_bar_color());\n\t}\n#endif\n}\n\nvoid Player::on_message(const Message & msg)\n{\n\tif(msg.get_type()==MSGC_INPUT)\n\t{\n\t\tconst MSGC_Input & input = static_cast(msg);\n\t\tkeys = input.keys;\n\t}\n}\n\nvoid Player::on_collide(GameObject * obj)\n{\n\tif(obj->is_alive() && obj->get_type()==EGOT_THROWABLE_OBJECT)\n\t{\n\t\tif(static_cast(obj)->get_owner_guid()==this->get_guid())\n\t\t\treturn;\n\n\t\tobj->set_is_alive(false);\n\n\t\tif(this->life>10)\n\t\t{\n\t\t\tthis->life = this->life - 10;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->killer=static_cast(obj)->get_owner_guid();\n\t\t\tthis->life=0;\n\t\t}\n\t}\n}\n\nvoid Player::on_tile_collide(const Tile & tile)\n{\n\tm_pos = last_pos;\n}\n\nclan::CollisionOutline & Player::get_outline()\n{\n\treturn m_outline;\n}Signed-off-by: serengeor #include \"precomp.h\"\n#include \"game_object_types.h\"\n#include \"game_object_manager.h\"\n#include \"game_object.h\"\n#include \"player.h\"\n#include \"..\/tile_chunk.h\"\n#include \"throwable_object.h\"\n#include \"..\/net\/message.h\"\n\nclan::Sprite Player::s_rw, \n\t\t\t Player::s_lw, \n\t\t\t Player::s_uw, \n\t\t\t Player::s_dw,\n\t\t\t Player::s_h;\n\nstatic clan::Font title;\n\nPlayer::Player(uint32_t guid): GameObject(type(),guid)\n{\n\tkeys=add_property(\"keys\",0);\n\tlife=add_property(\"life\",100);\n\tkills=add_property(\"kills\",0);\n\tkiller=add_property(\"killer\");\n\tname=add_property(\"name\",\"Sir. Waitfor Servereply\");\n\n\tclan::Contour contour;\n\tcontour.get_points().push_back(clan::Pointf(16,13));\n\tcontour.get_points().push_back(clan::Pointf(16,63));\n\tcontour.get_points().push_back(clan::Pointf(47,63));\n\tcontour.get_points().push_back(clan::Pointf(47,13));\n\n\tm_outline.get_contours().push_back(contour);\n\tm_outline.calculate_radius();\n\tm_outline.calculate_smallest_enclosing_discs();\n\t\n\tm_next_attack_time = 0;\n}\n\nPlayer::~Player()\n{\n\n}\n\nuint32_t Player::get_next_attack_time()\n{\n\treturn m_next_attack_time;\n}\n\nvoid Player::set_next_attack_time(uint32_t time)\n{\n\tm_next_attack_time = time;\n}\n\nclan::Colorf Player::get_hp_bar_color()\n{\n\tfloat r,g;\n\tr = 1.0f - (float)life\/100;\n\tg = (float)life\/100;\n\treturn clan::Colorf(r,g,0.0f,1.0f);\n}\n\nbool Player::preload(clan::Canvas & canvas, clan::ResourceManager & resources)\n{\n\ttitle = clan::Font(canvas,\"Arial\",12); \/\/\/DON'T CHANGE EVEN AGAIN\n\ts_rw = clan::Sprite::resource(canvas, \"champ_rw\", resources );\n\ts_lw = clan::Sprite::resource(canvas, \"champ_lw\", resources );\n\ts_uw = clan::Sprite::resource(canvas, \"champ_uw\", resources );\n\ts_dw = clan::Sprite::resource(canvas, \"champ_dw\", resources );\n\n\ts_h = clan::Sprite::resource(canvas, \"hp_bar\", resources );\n\n\treturn true;\n}\n\nvoid Player::free()\n{\n\ts_rw = clan::Sprite();\n\ts_lw = clan::Sprite();\n\ts_uw = clan::Sprite();\n\ts_dw = clan::Sprite();\n\n\ts_h = clan::Sprite();\n\n\ttitle = clan::Font();\n}\n\nvoid Player::load(clan::Canvas & canvas, clan::ResourceManager & resources)\n{\n\tm_rw = s_rw.clone();\n\tm_lw = s_lw.clone();\n\tm_uw = s_uw.clone();\n\tm_dw = s_dw.clone();\n\n\tm_h = s_h.clone();\n\n\tm_sprite=m_dw;\n}\n\nvoid Player::update(const clan::GameTime & time)\n{\n\tif(!m_sprite.is_null())\n\t\tm_sprite.update(time.get_time_elapsed_ms());\n\t\/\/m_pos.data().x += 16.0f * (float)time.get_time_elapsed_ms()\/1000.0f;\n\n\tlast_pos = m_pos.get();\n\tif(keys&EUIKT_MOVE_LEFT && m_pos.get().x>-20.0f)\n\t{\n\t\tm_sprite=m_lw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.x-= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\tif(keys&EUIKT_MOVE_RIGHT && m_pos.get().x<980.0f)\n\t{\n\t\tm_sprite=m_rw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.x+= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\tif(keys&EUIKT_MOVE_UP && m_pos.get().y>0.0f)\n\t{\n\t\tm_sprite=m_uw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.y-= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\tif(keys&EUIKT_MOVE_DOWN && m_pos.get().y<660.0f)\n\t{\n\t\tm_sprite=m_dw;\n\t\tclan::vec2f v=m_pos;\n\t\tv.y+= 32.0f * (float)time.get_time_elapsed_ms()\/900.0f;\n\t\tm_pos.set(v);\n\t}\n\n\tm_outline.set_translation(m_pos.get().x,m_pos.get().y);\n}\n\nvoid Player::render(clan::Canvas & c, const clan::vec2 & offset)\n{\n#if defined GAME_CLIENT\n\tif(!m_sprite.is_null())\n\t{\n\t\tm_sprite.draw(c, m_pos.get().x+offset.x, m_pos.get().y+offset.y);\n\t\tc.fill_rect(m_pos.get().x+offset.x+10, m_pos.get().y+offset.y-1, m_pos.get().x+offset.x+10+(44*life\/100), m_pos.get().y+offset.y+8, get_hp_bar_color());\n\t\tm_h.draw(c,m_pos.get().x+offset.x, m_pos.get().y+offset.y-5);\n\t\tm_outline.draw(offset.x,offset.y,clan::Colorf(1,0,0,1),c);\n\n\t\ttitle.draw_text(c, m_pos.get().x+offset.x+6,m_pos.get().y+offset.y-8, name.get()+\": \"+clan::StringHelp::uint_to_text(kills.get()), get_hp_bar_color());\n\t}\n#endif\n}\n\nvoid Player::on_message(const Message & msg)\n{\n\tif(msg.get_type()==MSGC_INPUT)\n\t{\n\t\tconst MSGC_Input & input = static_cast(msg);\n\t\tkeys = input.keys;\n\t}\n}\n\nvoid Player::on_collide(GameObject * obj)\n{\n\tif(obj->is_alive() && obj->get_type()==EGOT_THROWABLE_OBJECT)\n\t{\n\t\tif(static_cast(obj)->get_owner_guid()==this->get_guid())\n\t\t\treturn;\n\n\t\tobj->set_is_alive(false);\n\n\t\tif(this->life>10)\n\t\t{\n\t\t\tthis->life = this->life - 10;\n\t\t}\n\t\telse\n\t\t{\n\t\t\tthis->killer=static_cast(obj)->get_owner_guid();\n\t\t\tthis->life=0;\n\t\t}\n\t}\n}\n\nvoid Player::on_tile_collide(const Tile & tile)\n{\n\tm_pos = last_pos;\n}\n\nclan::CollisionOutline & Player::get_outline()\n{\n\treturn m_outline;\n}<|endoftext|>"} {"text":"\/\/ General tests that the header search paths detected by the driver and passed\n\/\/ to CC1 are sane.\n\/\/\n\/\/ Test a very broken version of multiarch that shipped in Ubuntu 11.04.\n\/\/ RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \\\n\/\/ RUN: -ccc-host-triple i386-unknown-linux \\\n\/\/ RUN: --sysroot=%S\/Inputs\/ubuntu_11.04_multiarch_tree \\\n\/\/ RUN: | FileCheck --check-prefix=CHECK-UBUNTU-11-04 %s\n\/\/ CHECK-UBUNTU-11-04: \"{{.*}}clang{{.*}}\" \"-cc1\"\n\/\/ CHECK-UBUNTU-11-04: \"-isysroot\" \"[[SYSROOT:[^\"]+]]\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/lib\/i386-linux-gnu\/gcc\/i686-linux-gnu\/4.5\/..\/..\/..\/..\/..\/include\/c++\/4.5\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/lib\/i386-linux-gnu\/gcc\/i686-linux-gnu\/4.5\/..\/..\/..\/..\/..\/include\/c++\/4.5\/i686-linux-gnu\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/lib\/i386-linux-gnu\/gcc\/i686-linux-gnu\/4.5\/..\/..\/..\/..\/..\/include\/c++\/4.5\/backward\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/local\/include\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"{{.*}}\/lib\/clang\/{{[0-9]\\.[0-9]}}\/include\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-externc-isystem\" \"[[SYSROOT]]\/include\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-externc-isystem\" \"[[SYSROOT]]\/usr\/include\"\nTry to fix an issue on some hosts where the 'lib' in the builtin include path is actually a multilib.\/\/ General tests that the header search paths detected by the driver and passed\n\/\/ to CC1 are sane.\n\/\/\n\/\/ Test a very broken version of multiarch that shipped in Ubuntu 11.04.\n\/\/ RUN: %clang -no-canonical-prefixes %s -### -fsyntax-only 2>&1 \\\n\/\/ RUN: -ccc-host-triple i386-unknown-linux \\\n\/\/ RUN: --sysroot=%S\/Inputs\/ubuntu_11.04_multiarch_tree \\\n\/\/ RUN: | FileCheck --check-prefix=CHECK-UBUNTU-11-04 %s\n\/\/ CHECK-UBUNTU-11-04: \"{{.*}}clang{{.*}}\" \"-cc1\"\n\/\/ CHECK-UBUNTU-11-04: \"-isysroot\" \"[[SYSROOT:[^\"]+]]\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/lib\/i386-linux-gnu\/gcc\/i686-linux-gnu\/4.5\/..\/..\/..\/..\/..\/include\/c++\/4.5\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/lib\/i386-linux-gnu\/gcc\/i686-linux-gnu\/4.5\/..\/..\/..\/..\/..\/include\/c++\/4.5\/i686-linux-gnu\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/lib\/i386-linux-gnu\/gcc\/i686-linux-gnu\/4.5\/..\/..\/..\/..\/..\/include\/c++\/4.5\/backward\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"[[SYSROOT]]\/usr\/local\/include\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-isystem\" \"{{.*}}\/lib{{(64|32)?}}\/clang\/{{[0-9]\\.[0-9]}}\/include\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-externc-isystem\" \"[[SYSROOT]]\/include\"\n\/\/ CHECK-UBUNTU-11-04: \"-internal-externc-isystem\" \"[[SYSROOT]]\/usr\/include\"\n<|endoftext|>"} {"text":"#include \".\/..\/..\/..\/Common\/verbose-output\/rule.hpp\"\r\n\r\n#include \r\n\r\nnamespace utils { namespace verbose_output {\r\n \/\/\/ @brief rule for events from integrals state changing\r\n \/\/\/ @detailed 1. let x be monotonous increasing integral under observation\r\n \/\/\/ 2. let we want to track x every time if it goes through 100\r\n \/\/\/ 3. so integrals_rule will raise event if we observe x + y, where y >= 100\r\n template\r\n class integrals_rule\r\n : public rule\r\n {\r\n BOOST_STATIC_ASSERT((boost::is_arithmetic::value));\r\n\r\n typedef integrals_rule this_class;\r\n typedef rule base_class;\r\n\r\n public:\r\n \/\/\/ @brief default constructor\r\n \/\/\/ @param state observable\r\n \/\/\/ @param stride stride we want to log observable through\r\n integrals_rule(T state, T stride)\r\n : m_state(state), m_stride(stride){ };\r\n\r\n \/\/\/ @brief inherited from rule interface\r\n \/\/\/ @see rule\r\n result_type operator()(args<0>::type);\r\n\r\n private:\r\n \/\/ logics: we could not adaptively change rule behavior.\r\n \/\/ Correctly, it should be done by changing rule\r\n \/\/ private setter and getter for observable state\r\n T state() const{ return m_state; }\r\n this_class& state(T val){ m_state = val; return *this; }\r\n\r\n \/\/ just getter for observations stride\r\n T stride() const{ return m_stride; }\r\n\r\n T m_state;\r\n T m_stride;\r\n };\r\n}}\r\n\r\n#define _tmpl_head_T_ template\r\n#define _cls_name_ integrals_rule\r\n\r\n#include \".\/..\/..\/..\/Common\/verbose-output\/rules\/details\/integrals_rule.inl\"\r\nnumerals_rule.hpp: add #def protection for multiple object translating during compilation#ifndef INC_NUMERALS_RULE_HPP_\r\n#define INC_NUMERALS_RULE_HPP_\r\n\r\n#include \".\/..\/..\/..\/Common\/verbose-output\/rule.hpp\"\r\n\r\n#include \r\n\r\nnamespace utils { namespace verbose_output {\r\n \/\/\/ @brief rule for events from integrals state changing\r\n \/\/\/ @detailed 1. let x be monotonous increasing integral under observation\r\n \/\/\/ 2. let we want to track x every time if it goes through 100\r\n \/\/\/ 3. so integrals_rule will raise event if we observe x + y, where y >= 100\r\n template\r\n class integrals_rule\r\n : public rule\r\n {\r\n BOOST_STATIC_ASSERT((boost::is_arithmetic::value));\r\n\r\n typedef integrals_rule this_class;\r\n typedef rule base_class;\r\n\r\n public:\r\n \/\/\/ @brief default constructor\r\n \/\/\/ @param state observable\r\n \/\/\/ @param stride stride we want to log observable through\r\n integrals_rule(T state, T stride)\r\n : m_state(state), m_stride(stride){ };\r\n\r\n \/\/\/ @brief inherited from rule interface\r\n \/\/\/ @see rule\r\n result_type operator()(args<0>::type);\r\n\r\n private:\r\n \/\/ logics: we could not adaptively change rule behavior.\r\n \/\/ Correctly, it should be done by changing rule\r\n \/\/ private setter and getter for observable state\r\n T state() const{ return m_state; }\r\n this_class& state(T val){ m_state = val; return *this; }\r\n\r\n \/\/ just getter for observations stride\r\n T stride() const{ return m_stride; }\r\n\r\n T m_state;\r\n T m_stride;\r\n };\r\n}}\r\n\r\n#define _tmpl_head_T_ template\r\n#define _cls_name_ integrals_rule\r\n\r\n#include \".\/..\/..\/..\/Common\/verbose-output\/rules\/details\/integrals_rule.inl\"\r\n\r\n#endif\r\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"solvers\/equality_assistant.h\"\n#include \"config.h\"\n\nusing namespace theorysolver;\n\n#define VERBOSE_ASSISTANT true\n\n#define EF satsolver::ExtendedFormula\n#define SPEF std::shared_ptr\n#define EA EqualityAtom\n#define SPEA std::shared_ptr\n\n\/\/ Return a formula that uses only atoms in the canonical “xi-xj<=n” form.\n\/\/ Note that it may use literal #0; for instance, xi >= n is converted to\n\/\/ x0 - xi <= -n, so we will have to make sure x0 is always equal to 0.\nSPEF canonize_atom(SPEA atom, std::vector &literal_to_EA, std::string literal) {\n unsigned long int id1;\n assert(atom);\n if(atom->left==atom->right) {\n switch (atom->op) {\n case EA::EQUAL: \/\/ t1 = t1 \n atom->canonical = SPEF(new EF(EF::TRUE));\n break;\n case EA::UNEQUAL: \/\/ t1 != t1 \n atom->canonical = SPEF(new EF(EF::FALSE));\n break; \n } \n }\n else {\n switch (atom->op) {\n case EA::EQUAL: \/\/ t1 = t2 --> t1 = t2\n atom->canonical = SPEF(new EF(EF::LITERAL, literal));\n break;\n case EA::UNEQUAL: \/\/ t2 != t2 --> ~(t1 = t2)\n id1 = EqualityAtom::add_EA(literal_to_EA, atom->left, EA::EQUAL, atom->right);\n atom->canonical = SPEF(new EF(EF::NOT,\n SPEF(new EF(EF::LITERAL, EqualityAtom::variable_name_from_atom_id(id1)))\n ));\n break;\n }\n }\n return atom->canonical;\n}\n\nSPEF EqualityAssistant::canonize_formula(SPEF formula, std::vector &literal_to_EA) {\n SPEA atom;\n switch (formula->get_type()) {\n case EF::XOR:\n case EF::OR:\n case EF::AND:\n case EF::IMPLIES:\n return std::make_shared(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA), EqualityAssistant::canonize_formula(formula->get_f2(), literal_to_EA));\n case EF::NOT:\n return std::make_shared(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA));\n case EF::LITERAL:\n atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal());\n if (!EqualityAtom::is_atom_variable(formula->get_literal()))\n return std::make_shared(formula->get_type(), formula->get_literal());\n atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal());\n return canonize_atom(atom, literal_to_EA, formula->get_literal());\n case EF::TRUE:\n case EF::FALSE:\n return std::make_shared(formula->get_type());\n }\n assert(false);\n}\n\n\nEqualityAssistant::EqualityAssistant(std::vector &literal_to_EA, std::shared_ptr> name_to_variable, std::shared_ptr formula) :\n formula(formula), literal_to_EA(literal_to_EA), name_to_variable(*name_to_variable), variable_to_name(), union_find(), unequal(), consistent_state(true), depth_back(-1), old_polarity(formula->get_nb_variables()+1, 0) {\n for (auto it : *name_to_variable)\n this->variable_to_name.insert(make_pair(it.second, it.first));\n}\n\nint EqualityAssistant::on_flip(unsigned int variable) {\n unsigned int atom_id;\n SPEA atom;\n int clause_id=-1;\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"flip variable: \" << variable;\n if (!EqualityAtom::is_atom_literal(this->variable_to_name, variable)) {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \", which is not an atom.\" << std::endl;\n return -1; \/\/ We care only about variables matching atoms.\n }\n assert(variable <= static_cast(this->formula->get_nb_variables()));\n atom_id = EqualityAtom::atom_id_from_literal(this->variable_to_name, variable);\n atom = EqualityAtom::SPEA_from_literal(this->literal_to_EA, this->variable_to_name, variable);\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \", whose atom is: \" << atom_id << \", and whose new state is: \";\n if (this->formula->get_aff()->is_true(variable)) {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"true\" << std::endl;\n assert(this->consistent_state);\n if (this->old_polarity[variable] == 1)\n return -1;\n clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::EQUAL, atom_id, variable);\n this->old_polarity[variable] = 1;\n }\n else if (this->formula->get_aff()->is_false(variable)) {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"false\" << std::endl;\n assert(this->consistent_state);\n if (this->old_polarity[variable] == -1)\n return -1;\n clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::UNEQUAL, atom_id, variable);\n this->old_polarity[variable] = -1;\n }\n else {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"unknown\" << std::endl;\n if (this->old_polarity[variable] == 0)\n return -1;\n if (this->old_polarity[variable] == 1) {\n this->union_find.unmerge();\n }\n else {\n assert(this->unequal.size());\n assert(this->unequal.back().first == atom_id);\n this->unequal.pop_back();\n }\n this->consistent_state = true;\n\n this->old_polarity[variable] = 0;\n }\n return clause_id;\n}\n\nint EqualityAssistant::insert_atom(unsigned int i, unsigned int j, bool equal, unsigned int atom_id, int lit_conf) {\n if (equal) {\n this->union_find.merge(atom_id, i, j);\n for (auto it : this->unequal) {\n if (this->union_find.find(it.second.first) == this->union_find.find(it.second.second)) {\n this->consistent_state = false;\n return this->learn_clause(it.first, i, j, lit_conf);\n }\n }\n }\n else {\n this->consistent_state = (this->union_find.find(i) != this->union_find.find(j));\n this->unequal.push_back(std::make_pair(atom_id, std::make_pair(i, j)));\n if (!this->consistent_state)\n return this->learn_clause(atom_id, i, j, lit_conf);\n }\n return -1;\n}\n\nint EqualityAssistant::literal_from_atom_id(int atom_id) const {\n if (atom_id > 0)\n return EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast(atom_id));\n else\n return -EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast(-atom_id));\n}\n\n#define invert_polarity(lit) this->formula->get_aff()->is_true(lit) ? -lit : lit\n\nint EqualityAssistant::learn_clause(int unequal_atomid, int i, int j, int lit_conf) {\n std::unordered_set clause;\n int max_depth=-1, max_depth_l=0 ;\n int lit;\n int tmp;\n lit_conf = invert_polarity(lit_conf) ;\n clause.insert(lit_conf);\n clause.insert(lit=invert_polarity(this->literal_from_atom_id(unequal_atomid)));\n if(lit!=lit_conf) {\n max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;\n max_depth_l = lit ;\n }\n for (auto it : this->union_find.get_path(i)) {\n lit = invert_polarity(this->literal_from_atom_id(it));\n clause.insert(lit);\n if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) {\n max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;\n max_depth_l = lit ;\n }\n } \n for (auto it : this->union_find.get_path(j)) {\n lit = invert_polarity(this->literal_from_atom_id(it));\n clause.insert(lit);\n if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) {\n max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;\n max_depth_l = lit ;\n }\n }\n assert(max_depth >= 0);\n this->depth_back = max_depth ;\n assert(clause.size()>=2) ;\n assert(this->formula->get_aff());\n tmp = static_cast(this->formula->add_clause(std::make_shared(this->formula->get_nb_variables(), clause, this->formula->get_aff())));\n std::cout << \"Learn : \" << this->formula->to_clauses_vector()[tmp]->to_string() << \" with \" << lit_conf << \" \" << max_depth_l << std::endl ;\n if(WITH_WL) this->formula->to_clauses_vector()[tmp]->init_WL_CL(lit_conf,max_depth_l) ;\n return tmp ;\n}\n\nbool EqualityAssistant::is_state_consistent() {\n return this->consistent_state;\n}\n\nbool EqualityAssistant::detect_isolated_literals() {\n return false;\n}\n\nunsigned int EqualityAssistant::get_depth_back() {\n return -1;\n}\nAdd EqualityAssistant::get_depth_back.#include \n#include \n#include \n#include \"solvers\/equality_assistant.h\"\n#include \"config.h\"\n\nusing namespace theorysolver;\n\n#define VERBOSE_ASSISTANT true\n\n#define EF satsolver::ExtendedFormula\n#define SPEF std::shared_ptr\n#define EA EqualityAtom\n#define SPEA std::shared_ptr\n\n\/\/ Return a formula that uses only atoms in the canonical “xi-xj<=n” form.\n\/\/ Note that it may use literal #0; for instance, xi >= n is converted to\n\/\/ x0 - xi <= -n, so we will have to make sure x0 is always equal to 0.\nSPEF canonize_atom(SPEA atom, std::vector &literal_to_EA, std::string literal) {\n unsigned long int id1;\n assert(atom);\n if(atom->left==atom->right) {\n switch (atom->op) {\n case EA::EQUAL: \/\/ t1 = t1 \n atom->canonical = SPEF(new EF(EF::TRUE));\n break;\n case EA::UNEQUAL: \/\/ t1 != t1 \n atom->canonical = SPEF(new EF(EF::FALSE));\n break; \n } \n }\n else {\n switch (atom->op) {\n case EA::EQUAL: \/\/ t1 = t2 --> t1 = t2\n atom->canonical = SPEF(new EF(EF::LITERAL, literal));\n break;\n case EA::UNEQUAL: \/\/ t2 != t2 --> ~(t1 = t2)\n id1 = EqualityAtom::add_EA(literal_to_EA, atom->left, EA::EQUAL, atom->right);\n atom->canonical = SPEF(new EF(EF::NOT,\n SPEF(new EF(EF::LITERAL, EqualityAtom::variable_name_from_atom_id(id1)))\n ));\n break;\n }\n }\n return atom->canonical;\n}\n\nSPEF EqualityAssistant::canonize_formula(SPEF formula, std::vector &literal_to_EA) {\n SPEA atom;\n switch (formula->get_type()) {\n case EF::XOR:\n case EF::OR:\n case EF::AND:\n case EF::IMPLIES:\n return std::make_shared(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA), EqualityAssistant::canonize_formula(formula->get_f2(), literal_to_EA));\n case EF::NOT:\n return std::make_shared(formula->get_type(), EqualityAssistant::canonize_formula(formula->get_f1(), literal_to_EA));\n case EF::LITERAL:\n atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal());\n if (!EqualityAtom::is_atom_variable(formula->get_literal()))\n return std::make_shared(formula->get_type(), formula->get_literal());\n atom = EqualityAtom::SPEA_from_variable(literal_to_EA, formula->get_literal());\n return canonize_atom(atom, literal_to_EA, formula->get_literal());\n case EF::TRUE:\n case EF::FALSE:\n return std::make_shared(formula->get_type());\n }\n assert(false);\n}\n\n\nEqualityAssistant::EqualityAssistant(std::vector &literal_to_EA, std::shared_ptr> name_to_variable, std::shared_ptr formula) :\n formula(formula), literal_to_EA(literal_to_EA), name_to_variable(*name_to_variable), variable_to_name(), union_find(), unequal(), consistent_state(true), depth_back(-1), old_polarity(formula->get_nb_variables()+1, 0) {\n for (auto it : *name_to_variable)\n this->variable_to_name.insert(make_pair(it.second, it.first));\n}\n\nint EqualityAssistant::on_flip(unsigned int variable) {\n unsigned int atom_id;\n SPEA atom;\n int clause_id=-1;\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"flip variable: \" << variable;\n if (!EqualityAtom::is_atom_literal(this->variable_to_name, variable)) {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \", which is not an atom.\" << std::endl;\n return -1; \/\/ We care only about variables matching atoms.\n }\n assert(variable <= static_cast(this->formula->get_nb_variables()));\n atom_id = EqualityAtom::atom_id_from_literal(this->variable_to_name, variable);\n atom = EqualityAtom::SPEA_from_literal(this->literal_to_EA, this->variable_to_name, variable);\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \", whose atom is: \" << atom_id << \", and whose new state is: \";\n if (this->formula->get_aff()->is_true(variable)) {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"true\" << std::endl;\n assert(this->consistent_state);\n if (this->old_polarity[variable] == 1)\n return -1;\n clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::EQUAL, atom_id, variable);\n this->old_polarity[variable] = 1;\n }\n else if (this->formula->get_aff()->is_false(variable)) {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"false\" << std::endl;\n assert(this->consistent_state);\n if (this->old_polarity[variable] == -1)\n return -1;\n clause_id = this->insert_atom(atom->left, atom->right, atom->op == EA::UNEQUAL, atom_id, variable);\n this->old_polarity[variable] = -1;\n }\n else {\n if (VERBOSE_ASSISTANT && VERBOSE)\n std::cout << \"unknown\" << std::endl;\n if (this->old_polarity[variable] == 0)\n return -1;\n if (this->old_polarity[variable] == 1) {\n this->union_find.unmerge();\n }\n else {\n assert(this->unequal.size());\n assert(this->unequal.back().first == atom_id);\n this->unequal.pop_back();\n }\n this->consistent_state = true;\n\n this->old_polarity[variable] = 0;\n }\n return clause_id;\n}\n\nint EqualityAssistant::insert_atom(unsigned int i, unsigned int j, bool equal, unsigned int atom_id, int lit_conf) {\n if (equal) {\n this->union_find.merge(atom_id, i, j);\n for (auto it : this->unequal) {\n if (this->union_find.find(it.second.first) == this->union_find.find(it.second.second)) {\n this->consistent_state = false;\n return this->learn_clause(it.first, i, j, lit_conf);\n }\n }\n }\n else {\n this->consistent_state = (this->union_find.find(i) != this->union_find.find(j));\n this->unequal.push_back(std::make_pair(atom_id, std::make_pair(i, j)));\n if (!this->consistent_state)\n return this->learn_clause(atom_id, i, j, lit_conf);\n }\n return -1;\n}\n\nint EqualityAssistant::literal_from_atom_id(int atom_id) const {\n if (atom_id > 0)\n return EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast(atom_id));\n else\n return -EqualityAtom::literal_from_atom_id(this->name_to_variable, static_cast(-atom_id));\n}\n\n#define invert_polarity(lit) this->formula->get_aff()->is_true(lit) ? -lit : lit\n\nint EqualityAssistant::learn_clause(int unequal_atomid, int i, int j, int lit_conf) {\n std::unordered_set clause;\n int max_depth=-1, max_depth_l=0 ;\n int lit;\n int tmp;\n lit_conf = invert_polarity(lit_conf) ;\n clause.insert(lit_conf);\n clause.insert(lit=invert_polarity(this->literal_from_atom_id(unequal_atomid)));\n if(lit!=lit_conf) {\n max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;\n max_depth_l = lit ;\n }\n for (auto it : this->union_find.get_path(i)) {\n lit = invert_polarity(this->literal_from_atom_id(it));\n clause.insert(lit);\n if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) {\n max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;\n max_depth_l = lit ;\n }\n } \n for (auto it : this->union_find.get_path(j)) {\n lit = invert_polarity(this->literal_from_atom_id(it));\n clause.insert(lit);\n if(lit!=lit_conf && this->formula->get_ded()->get_deduction_depth(lit) > max_depth) {\n max_depth = this->formula->get_ded()->get_deduction_depth(lit) ;\n max_depth_l = lit ;\n }\n }\n assert(max_depth >= 0);\n this->depth_back = max_depth ;\n assert(clause.size()>=2) ;\n assert(this->formula->get_aff());\n tmp = static_cast(this->formula->add_clause(std::make_shared(this->formula->get_nb_variables(), clause, this->formula->get_aff())));\n std::cout << \"Learn : \" << this->formula->to_clauses_vector()[tmp]->to_string() << \" with \" << lit_conf << \" \" << max_depth_l << std::endl ;\n if(WITH_WL) this->formula->to_clauses_vector()[tmp]->init_WL_CL(lit_conf,max_depth_l) ;\n return tmp ;\n}\n\nbool EqualityAssistant::is_state_consistent() {\n return this->consistent_state;\n}\n\nbool EqualityAssistant::detect_isolated_literals() {\n return false;\n}\n\nunsigned int EqualityAssistant::get_depth_back() {\n assert(this->depth_back>=0) ;\n unsigned int tmp = static_cast(this->depth_back) ; \/\/ cette fonction ne doit être appelée qu'une fois par clause apprise\n this->depth_back = -1 ;\n return tmp ;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2017 The WebRTC Project Authors. All rights reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"test\/gmock.h\"\n#include \"test\/gtest.h\"\n\n#include \"api\/video_codecs\/video_decoder.h\"\n#include \"call\/rtp_stream_receiver_controller.h\"\n#include \"media\/base\/fakevideorenderer.h\"\n#include \"modules\/pacing\/packet_router.h\"\n#include \"modules\/rtp_rtcp\/source\/rtp_packet_to_send.h\"\n#include \"modules\/utility\/include\/process_thread.h\"\n#include \"rtc_base\/criticalsection.h\"\n#include \"rtc_base\/event.h\"\n#include \"system_wrappers\/include\/clock.h\"\n#include \"test\/field_trial.h\"\n#include \"video\/call_stats.h\"\n#include \"video\/video_receive_stream.h\"\n\nnamespace webrtc {\nnamespace {\n\nusing testing::_;\nusing testing::Invoke;\n\nconstexpr int kDefaultTimeOutMs = 50;\n\nconst char kNewJitterBufferFieldTrialEnabled[] =\n \"WebRTC-NewVideoJitterBuffer\/Enabled\/\";\n\nclass MockTransport : public Transport {\n public:\n MOCK_METHOD3(SendRtp,\n bool(const uint8_t* packet,\n size_t length,\n const PacketOptions& options));\n MOCK_METHOD2(SendRtcp, bool(const uint8_t* packet, size_t length));\n};\n\nclass MockVideoDecoder : public VideoDecoder {\n public:\n MOCK_METHOD2(InitDecode,\n int32_t(const VideoCodec* config, int32_t number_of_cores));\n MOCK_METHOD4(Decode,\n int32_t(const EncodedImage& input,\n bool missing_frames,\n const CodecSpecificInfo* codec_specific_info,\n int64_t render_time_ms));\n MOCK_METHOD1(RegisterDecodeCompleteCallback,\n int32_t(DecodedImageCallback* callback));\n MOCK_METHOD0(Release, int32_t(void));\n const char* ImplementationName() const { return \"MockVideoDecoder\"; }\n};\n\n} \/\/ namespace\n\nclass VideoReceiveStreamTest : public testing::Test {\n public:\n VideoReceiveStreamTest()\n : process_thread_(ProcessThread::Create(\"TestThread\")),\n override_field_trials_(kNewJitterBufferFieldTrialEnabled),\n config_(&mock_transport_),\n call_stats_(Clock::GetRealTimeClock(), process_thread_.get()) {}\n\n void SetUp() {\n constexpr int kDefaultNumCpuCores = 2;\n config_.rtp.remote_ssrc = 1111;\n config_.rtp.local_ssrc = 2222;\n config_.renderer = &fake_renderer_;\n VideoReceiveStream::Decoder h264_decoder;\n h264_decoder.payload_type = 99;\n h264_decoder.payload_name = \"H264\";\n h264_decoder.codec_params.insert(\n {\"sprop-parameter-sets\", \"Z0IACpZTBYmI,aMljiA==\"});\n h264_decoder.decoder = &mock_h264_video_decoder_;\n config_.decoders.push_back(h264_decoder);\n VideoReceiveStream::Decoder null_decoder;\n null_decoder.payload_type = 98;\n null_decoder.payload_name = \"null\";\n null_decoder.decoder = &mock_null_video_decoder_;\n config_.decoders.push_back(null_decoder);\n\n video_receive_stream_.reset(new webrtc::internal::VideoReceiveStream(\n &rtp_stream_receiver_controller_, kDefaultNumCpuCores, &packet_router_,\n config_.Copy(), process_thread_.get(), &call_stats_));\n }\n\n protected:\n std::unique_ptr process_thread_;\n webrtc::test::ScopedFieldTrials override_field_trials_;\n VideoReceiveStream::Config config_;\n CallStats call_stats_;\n MockVideoDecoder mock_h264_video_decoder_;\n MockVideoDecoder mock_null_video_decoder_;\n cricket::FakeVideoRenderer fake_renderer_;\n MockTransport mock_transport_;\n PacketRouter packet_router_;\n RtpStreamReceiverController rtp_stream_receiver_controller_;\n std::unique_ptr video_receive_stream_;\n};\n\nTEST_F(VideoReceiveStreamTest, CreateFrameFromH264FmtpSpropAndIdr) {\n constexpr uint8_t idr_nalu[] = {0x05, 0xFF, 0xFF, 0xFF};\n RtpPacketToSend rtppacket(nullptr);\n uint8_t* payload = rtppacket.AllocatePayload(sizeof(idr_nalu));\n memcpy(payload, idr_nalu, sizeof(idr_nalu));\n rtppacket.SetMarker(true);\n rtppacket.SetSsrc(1111);\n rtppacket.SetPayloadType(99);\n rtppacket.SetSequenceNumber(1);\n rtppacket.SetTimestamp(0);\n rtc::Event init_decode_event_(false, false);\n EXPECT_CALL(mock_h264_video_decoder_, InitDecode(_, _))\n .WillOnce(Invoke([&init_decode_event_](const VideoCodec* config,\n int32_t number_of_cores) {\n init_decode_event_.Set();\n return 0;\n }));\n EXPECT_CALL(mock_h264_video_decoder_, RegisterDecodeCompleteCallback(_));\n video_receive_stream_->Start();\n EXPECT_CALL(mock_h264_video_decoder_, Decode(_, false, _, _));\n RtpPacketReceived parsed_packet;\n ASSERT_TRUE(parsed_packet.Parse(rtppacket.data(), rtppacket.size()));\n rtp_stream_receiver_controller_.OnRtpPacket(parsed_packet);\n EXPECT_CALL(mock_h264_video_decoder_, Release());\n \/\/ Make sure the decoder thread had a chance to run.\n init_decode_event_.Wait(kDefaultTimeOutMs);\n}\n\n} \/\/ namespace webrtc\nRemoved old and unused WebRTC-NewVideoJitterBuffer field trial from VideoReceiveStreamTest.\/*\n * Copyright 2017 The WebRTC Project Authors. All rights reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n\n#include \n\n#include \"test\/gmock.h\"\n#include \"test\/gtest.h\"\n\n#include \"api\/video_codecs\/video_decoder.h\"\n#include \"call\/rtp_stream_receiver_controller.h\"\n#include \"media\/base\/fakevideorenderer.h\"\n#include \"modules\/pacing\/packet_router.h\"\n#include \"modules\/rtp_rtcp\/source\/rtp_packet_to_send.h\"\n#include \"modules\/utility\/include\/process_thread.h\"\n#include \"rtc_base\/criticalsection.h\"\n#include \"rtc_base\/event.h\"\n#include \"system_wrappers\/include\/clock.h\"\n#include \"test\/field_trial.h\"\n#include \"video\/call_stats.h\"\n#include \"video\/video_receive_stream.h\"\n\nnamespace webrtc {\nnamespace {\n\nusing testing::_;\nusing testing::Invoke;\n\nconstexpr int kDefaultTimeOutMs = 50;\n\nclass MockTransport : public Transport {\n public:\n MOCK_METHOD3(SendRtp,\n bool(const uint8_t* packet,\n size_t length,\n const PacketOptions& options));\n MOCK_METHOD2(SendRtcp, bool(const uint8_t* packet, size_t length));\n};\n\nclass MockVideoDecoder : public VideoDecoder {\n public:\n MOCK_METHOD2(InitDecode,\n int32_t(const VideoCodec* config, int32_t number_of_cores));\n MOCK_METHOD4(Decode,\n int32_t(const EncodedImage& input,\n bool missing_frames,\n const CodecSpecificInfo* codec_specific_info,\n int64_t render_time_ms));\n MOCK_METHOD1(RegisterDecodeCompleteCallback,\n int32_t(DecodedImageCallback* callback));\n MOCK_METHOD0(Release, int32_t(void));\n const char* ImplementationName() const { return \"MockVideoDecoder\"; }\n};\n\n} \/\/ namespace\n\nclass VideoReceiveStreamTest : public testing::Test {\n public:\n VideoReceiveStreamTest()\n : process_thread_(ProcessThread::Create(\"TestThread\")),\n config_(&mock_transport_),\n call_stats_(Clock::GetRealTimeClock(), process_thread_.get()) {}\n\n void SetUp() {\n constexpr int kDefaultNumCpuCores = 2;\n config_.rtp.remote_ssrc = 1111;\n config_.rtp.local_ssrc = 2222;\n config_.renderer = &fake_renderer_;\n VideoReceiveStream::Decoder h264_decoder;\n h264_decoder.payload_type = 99;\n h264_decoder.payload_name = \"H264\";\n h264_decoder.codec_params.insert(\n {\"sprop-parameter-sets\", \"Z0IACpZTBYmI,aMljiA==\"});\n h264_decoder.decoder = &mock_h264_video_decoder_;\n config_.decoders.push_back(h264_decoder);\n VideoReceiveStream::Decoder null_decoder;\n null_decoder.payload_type = 98;\n null_decoder.payload_name = \"null\";\n null_decoder.decoder = &mock_null_video_decoder_;\n config_.decoders.push_back(null_decoder);\n\n video_receive_stream_.reset(new webrtc::internal::VideoReceiveStream(\n &rtp_stream_receiver_controller_, kDefaultNumCpuCores, &packet_router_,\n config_.Copy(), process_thread_.get(), &call_stats_));\n }\n\n protected:\n std::unique_ptr process_thread_;\n VideoReceiveStream::Config config_;\n CallStats call_stats_;\n MockVideoDecoder mock_h264_video_decoder_;\n MockVideoDecoder mock_null_video_decoder_;\n cricket::FakeVideoRenderer fake_renderer_;\n MockTransport mock_transport_;\n PacketRouter packet_router_;\n RtpStreamReceiverController rtp_stream_receiver_controller_;\n std::unique_ptr video_receive_stream_;\n};\n\nTEST_F(VideoReceiveStreamTest, CreateFrameFromH264FmtpSpropAndIdr) {\n constexpr uint8_t idr_nalu[] = {0x05, 0xFF, 0xFF, 0xFF};\n RtpPacketToSend rtppacket(nullptr);\n uint8_t* payload = rtppacket.AllocatePayload(sizeof(idr_nalu));\n memcpy(payload, idr_nalu, sizeof(idr_nalu));\n rtppacket.SetMarker(true);\n rtppacket.SetSsrc(1111);\n rtppacket.SetPayloadType(99);\n rtppacket.SetSequenceNumber(1);\n rtppacket.SetTimestamp(0);\n rtc::Event init_decode_event_(false, false);\n EXPECT_CALL(mock_h264_video_decoder_, InitDecode(_, _))\n .WillOnce(Invoke([&init_decode_event_](const VideoCodec* config,\n int32_t number_of_cores) {\n init_decode_event_.Set();\n return 0;\n }));\n EXPECT_CALL(mock_h264_video_decoder_, RegisterDecodeCompleteCallback(_));\n video_receive_stream_->Start();\n EXPECT_CALL(mock_h264_video_decoder_, Decode(_, false, _, _));\n RtpPacketReceived parsed_packet;\n ASSERT_TRUE(parsed_packet.Parse(rtppacket.data(), rtppacket.size()));\n rtp_stream_receiver_controller_.OnRtpPacket(parsed_packet);\n EXPECT_CALL(mock_h264_video_decoder_, Release());\n \/\/ Make sure the decoder thread had a chance to run.\n init_decode_event_.Wait(kDefaultTimeOutMs);\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/***********************************************************************************************************************\n* *\n* SPLASH build system v0.2 *\n* *\n* Copyright (c) 2016 Andrew D. Zonenberg *\n* All rights reserved. *\n* *\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *\n* following conditions are met: *\n* *\n* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *\n* following disclaimer. *\n* *\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *\n* following disclaimer in the documentation and\/or other materials provided with the distribution. *\n* *\n* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *\n* derived from this software without specific prior written permission. *\n* *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *\n* POSSIBILITY OF SUCH DAMAGE. *\n* *\n***********************************************************************************************************************\/\n\n#include \"splashcore.h\"\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nGNUCPPToolchain::GNUCPPToolchain(string basepath, string triplet)\n\t: CPPToolchain(basepath, TOOLCHAIN_GNU)\n\t, GNUToolchain(triplet)\n{\n\t\/\/Get the full compiler version\n\tm_stringVersion = string(\"GNU C++\") + ShellCommand(basepath + \" --version | head -n 1 | cut -d \\\")\\\" -f 2\");\n\n\t\/\/Parse it\n\tif(3 != sscanf(m_stringVersion.c_str(), \"GNU C++ %4d.%4d.%4d\",\n\t\t&m_majorVersion, &m_minorVersion, &m_patchVersion))\n\t{\n\t\t\/\/TODO: handle this better, don't abort :P\n\t\tLogFatal(\"bad G++ version\\n\");\n\t}\n\n\t\/\/Some compilers can target other arches if you feed them the right flags.\n\t\/\/Thanks to @GyrosGeier for this\n\tstring cmd =\n\t\tstring(\"\/bin\/bash -c \\\"\") +\n\t\tbasepath + \" -print-multi-lib | sed -e 's\/.*;\/\/' -e 's\/@\/ -\/g' | while read line; do \" +\n\t\tbasepath + \" \\\\$line -print-multiarch; done\" +\n\t\tstring(\"\\\"\");\n\tstring extra_arches = ShellCommand(cmd);\n\tvector triplets;\n\tParseLines(extra_arches, triplets);\n\tfor(auto t : triplets)\n\t\tm_triplets.emplace(t);\n\n\t\/\/If no arches found in the last step, fall back to the triplet in the file name\n\tif(m_triplets.empty())\n\t\tm_triplets.emplace(triplet);\n\n\t\/\/Look up where this toolchain gets its include files from\n\tfor(auto t : m_triplets)\n\t{\n\t\tvector paths;\n\t\tFindDefaultIncludePaths(paths, basepath, false, t);\n\t\tm_defaultIncludePaths[t] = paths;\n\t\tm_virtualSystemIncludePath[t] =\n\t\t\t\"__sysinclude__\/\" + str_replace(\" \", \"_\", m_stringVersion) + \"_\" + t;\n\t}\n\n\t\/\/Set suffixes for WINDOWS\n\tif(triplet.find(\"mingw\") != string::npos)\n\t{\n\t\tm_exeSuffix = \".exe\";\n\t\tm_shlibSuffix = \".dll\";\n\t\tm_stlibSuffix = \".lib\";\n\t\tm_objSuffix = \".obj\";\n\t\tm_shlibPrefix = \"\";\n\t}\n\n\t\/\/Set suffixes for POSIX\n\telse\n\t{\n\t\tm_exeSuffix = \"\";\n\t\tm_shlibSuffix = \".so\";\n\t\tm_stlibSuffix = \".a\";\n\t\tm_objSuffix = \".o\";\n\t\tm_shlibPrefix = \"lib\";\n\t}\n\n\t\/\/Generate the hash\n\t\/\/TODO: Anything else to add here?\n\tm_hash = sha256(m_stringVersion + triplet);\n}\n\nGNUCPPToolchain::~GNUCPPToolchain()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Toolchain properties\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Actual operations\n\nbool GNUCPPToolchain::ScanDependencies(\n\tstring arch,\n\tstring path,\n\tstring root,\n\tset flags,\n\tset& deps,\n\tmap& dephashes,\n\tstring& output,\n\tset& missingFiles)\n{\n\treturn GNUToolchain::ScanDependencies(\n\t\tm_basepath, arch, path, root, flags, m_defaultIncludePaths[arch], deps, dephashes, output, missingFiles);\n}\n\n\/**\n\t@brief Compile stuff\n *\/\nbool GNUCPPToolchain::Build(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& output)\n{\n\treturn GNUToolchain::Compile(m_basepath, triplet, sources, fname, flags, outputs, output);\n}\nBUGFIX: C++ compler should use C++ include paths\/***********************************************************************************************************************\n* *\n* SPLASH build system v0.2 *\n* *\n* Copyright (c) 2016 Andrew D. Zonenberg *\n* All rights reserved. *\n* *\n* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the *\n* following conditions are met: *\n* *\n* * Redistributions of source code must retain the above copyright notice, this list of conditions, and the *\n* following disclaimer. *\n* *\n* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the *\n* following disclaimer in the documentation and\/or other materials provided with the distribution. *\n* *\n* * Neither the name of the author nor the names of any contributors may be used to endorse or promote products *\n* derived from this software without specific prior written permission. *\n* *\n* THIS SOFTWARE IS PROVIDED BY THE AUTHORS \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED *\n* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *\n* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES *\n* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *\n* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *\n* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *\n* POSSIBILITY OF SUCH DAMAGE. *\n* *\n***********************************************************************************************************************\/\n\n#include \"splashcore.h\"\n\nusing namespace std;\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Construction \/ destruction\n\nGNUCPPToolchain::GNUCPPToolchain(string basepath, string triplet)\n\t: CPPToolchain(basepath, TOOLCHAIN_GNU)\n\t, GNUToolchain(triplet)\n{\n\t\/\/Get the full compiler version\n\tm_stringVersion = string(\"GNU C++\") + ShellCommand(basepath + \" --version | head -n 1 | cut -d \\\")\\\" -f 2\");\n\n\t\/\/Parse it\n\tif(3 != sscanf(m_stringVersion.c_str(), \"GNU C++ %4d.%4d.%4d\",\n\t\t&m_majorVersion, &m_minorVersion, &m_patchVersion))\n\t{\n\t\t\/\/TODO: handle this better, don't abort :P\n\t\tLogFatal(\"bad G++ version\\n\");\n\t}\n\n\t\/\/Some compilers can target other arches if you feed them the right flags.\n\t\/\/Thanks to @GyrosGeier for this\n\tstring cmd =\n\t\tstring(\"\/bin\/bash -c \\\"\") +\n\t\tbasepath + \" -print-multi-lib | sed -e 's\/.*;\/\/' -e 's\/@\/ -\/g' | while read line; do \" +\n\t\tbasepath + \" \\\\$line -print-multiarch; done\" +\n\t\tstring(\"\\\"\");\n\tstring extra_arches = ShellCommand(cmd);\n\tvector triplets;\n\tParseLines(extra_arches, triplets);\n\tfor(auto t : triplets)\n\t\tm_triplets.emplace(t);\n\n\t\/\/If no arches found in the last step, fall back to the triplet in the file name\n\tif(m_triplets.empty())\n\t\tm_triplets.emplace(triplet);\n\n\t\/\/Look up where this toolchain gets its include files from\n\tfor(auto t : m_triplets)\n\t{\n\t\tvector paths;\n\t\tFindDefaultIncludePaths(paths, basepath, true, t);\n\t\tm_defaultIncludePaths[t] = paths;\n\t\tm_virtualSystemIncludePath[t] =\n\t\t\t\"__sysinclude__\/\" + str_replace(\" \", \"_\", m_stringVersion) + \"_\" + t;\n\t}\n\n\t\/\/Set suffixes for WINDOWS\n\tif(triplet.find(\"mingw\") != string::npos)\n\t{\n\t\tm_exeSuffix = \".exe\";\n\t\tm_shlibSuffix = \".dll\";\n\t\tm_stlibSuffix = \".lib\";\n\t\tm_objSuffix = \".obj\";\n\t\tm_shlibPrefix = \"\";\n\t}\n\n\t\/\/Set suffixes for POSIX\n\telse\n\t{\n\t\tm_exeSuffix = \"\";\n\t\tm_shlibSuffix = \".so\";\n\t\tm_stlibSuffix = \".a\";\n\t\tm_objSuffix = \".o\";\n\t\tm_shlibPrefix = \"lib\";\n\t}\n\n\t\/\/Generate the hash\n\t\/\/TODO: Anything else to add here?\n\tm_hash = sha256(m_stringVersion + triplet);\n}\n\nGNUCPPToolchain::~GNUCPPToolchain()\n{\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Toolchain properties\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ Actual operations\n\nbool GNUCPPToolchain::ScanDependencies(\n\tstring arch,\n\tstring path,\n\tstring root,\n\tset flags,\n\tset& deps,\n\tmap& dephashes,\n\tstring& output,\n\tset& missingFiles)\n{\n\treturn GNUToolchain::ScanDependencies(\n\t\tm_basepath, arch, path, root, flags, m_defaultIncludePaths[arch], deps, dephashes, output, missingFiles);\n}\n\n\/**\n\t@brief Compile stuff\n *\/\nbool GNUCPPToolchain::Build(\n\tstring triplet,\n\tset sources,\n\tstring fname,\n\tset flags,\n\tmap& outputs,\n\tstring& output)\n{\n\treturn GNUToolchain::Compile(m_basepath, triplet, sources, fname, flags, outputs, output);\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_header_parser.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/source\/rtcp_utility.h\"\n#include \"webrtc\/system_wrappers\/interface\/event_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n#include \"webrtc\/video_engine\/test\/common\/fake_encoder.h\"\n#include \"webrtc\/video_engine\/test\/common\/frame_generator.h\"\n#include \"webrtc\/video_engine\/test\/common\/frame_generator_capturer.h\"\n#include \"webrtc\/video_engine\/test\/common\/null_transport.h\"\n#include \"webrtc\/video_engine\/new_include\/call.h\"\n#include \"webrtc\/video_engine\/new_include\/video_send_stream.h\"\n\nnamespace webrtc {\n\nclass SendTransportObserver : public test::NullTransport {\n public:\n explicit SendTransportObserver(unsigned long timeout_ms)\n : rtp_header_parser_(RtpHeaderParser::Create()),\n send_test_complete_(EventWrapper::Create()),\n timeout_ms_(timeout_ms) {}\n\n EventTypeWrapper Wait() { return send_test_complete_->Wait(timeout_ms_); }\n\n protected:\n scoped_ptr rtp_header_parser_;\n scoped_ptr send_test_complete_;\n\n private:\n unsigned long timeout_ms_;\n};\n\nclass VideoSendStreamTest : public ::testing::Test {\n public:\n VideoSendStreamTest() : fake_encoder_(Clock::GetRealTimeClock()) {}\n\n protected:\n static const uint32_t kSendSsrc;\n void RunSendTest(Call* call,\n const VideoSendStream::Config& config,\n SendTransportObserver* observer) {\n VideoSendStream* send_stream = call->CreateSendStream(config);\n scoped_ptr frame_generator_capturer(\n test::FrameGeneratorCapturer::Create(\n send_stream->Input(),\n test::FrameGenerator::Create(320, 240, Clock::GetRealTimeClock()),\n 30));\n send_stream->StartSend();\n frame_generator_capturer->Start();\n\n EXPECT_EQ(kEventSignaled, observer->Wait());\n\n frame_generator_capturer->Stop();\n send_stream->StopSend();\n call->DestroySendStream(send_stream);\n }\n\n VideoSendStream::Config GetSendTestConfig(Call* call) {\n VideoSendStream::Config config = call->GetDefaultSendConfig();\n config.encoder = &fake_encoder_;\n config.internal_source = false;\n test::FakeEncoder::SetCodecSettings(&config.codec, 1);\n return config;\n }\n\n test::FakeEncoder fake_encoder_;\n};\n\nconst uint32_t VideoSendStreamTest::kSendSsrc = 0xC0FFEE;\n\nTEST_F(VideoSendStreamTest, SendsSetSsrc) {\n class SendSsrcObserver : public SendTransportObserver {\n public:\n SendSsrcObserver() : SendTransportObserver(30 * 1000) {}\n\n virtual bool SendRTP(const uint8_t* packet, size_t length) OVERRIDE {\n RTPHeader header;\n EXPECT_TRUE(\n rtp_header_parser_->Parse(packet, static_cast(length), &header));\n\n if (header.ssrc == kSendSsrc)\n send_test_complete_->Set();\n\n return true;\n }\n } observer;\n\n Call::Config call_config(&observer);\n scoped_ptr call(Call::Create(call_config));\n\n VideoSendStream::Config send_config = GetSendTestConfig(call.get());\n send_config.rtp.ssrcs.push_back(kSendSsrc);\n\n RunSendTest(call.get(), send_config, &observer);\n}\n\nTEST_F(VideoSendStreamTest, SupportsCName) {\n static std::string kCName = \"PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo=\";\n class CNameObserver : public SendTransportObserver {\n public:\n CNameObserver() : SendTransportObserver(30 * 1000) {}\n\n virtual bool SendRTCP(const uint8_t* packet, size_t length) OVERRIDE {\n RTCPUtility::RTCPParserV2 parser(packet, length, true);\n EXPECT_TRUE(parser.IsValid());\n\n RTCPUtility::RTCPPacketTypes packet_type = parser.Begin();\n while (packet_type != RTCPUtility::kRtcpNotValidCode) {\n if (packet_type == RTCPUtility::kRtcpSdesChunkCode) {\n EXPECT_EQ(parser.Packet().CName.CName, kCName);\n send_test_complete_->Set();\n }\n\n packet_type = parser.Iterate();\n }\n\n return true;\n }\n } observer;\n\n Call::Config call_config(&observer);\n scoped_ptr call(Call::Create(call_config));\n\n VideoSendStream::Config send_config = GetSendTestConfig(call.get());\n send_config.rtp.ssrcs.push_back(kSendSsrc);\n send_config.rtp.c_name = kCName;\n\n RunSendTest(call.get(), send_config, &observer);\n}\n\n} \/\/ namespace webrtc\nTest that VideoSendStream responds to NACK.\/*\n * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.\n *\n * Use of this source code is governed by a BSD-style license\n * that can be found in the LICENSE file in the root of the source\n * tree. An additional intellectual property rights grant can be found\n * in the file PATENTS. All contributing project authors may\n * be found in the AUTHORS file in the root of the source tree.\n *\/\n#include \"testing\/gtest\/include\/gtest\/gtest.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/interface\/rtp_header_parser.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/source\/rtcp_sender.h\"\n#include \"webrtc\/modules\/rtp_rtcp\/source\/rtcp_utility.h\"\n#include \"webrtc\/system_wrappers\/interface\/event_wrapper.h\"\n#include \"webrtc\/system_wrappers\/interface\/scoped_ptr.h\"\n#include \"webrtc\/system_wrappers\/interface\/thread_wrapper.h\"\n#include \"webrtc\/video_engine\/test\/common\/fake_encoder.h\"\n#include \"webrtc\/video_engine\/test\/common\/frame_generator.h\"\n#include \"webrtc\/video_engine\/test\/common\/frame_generator_capturer.h\"\n#include \"webrtc\/video_engine\/test\/common\/null_transport.h\"\n#include \"webrtc\/video_engine\/new_include\/call.h\"\n#include \"webrtc\/video_engine\/new_include\/video_send_stream.h\"\n\nnamespace webrtc {\n\nclass SendTransportObserver : public test::NullTransport {\n public:\n explicit SendTransportObserver(unsigned long timeout_ms)\n : rtp_header_parser_(RtpHeaderParser::Create()),\n send_test_complete_(EventWrapper::Create()),\n timeout_ms_(timeout_ms) {}\n\n EventTypeWrapper Wait() { return send_test_complete_->Wait(timeout_ms_); }\n\n protected:\n scoped_ptr rtp_header_parser_;\n scoped_ptr send_test_complete_;\n\n private:\n unsigned long timeout_ms_;\n};\n\nclass VideoSendStreamTest : public ::testing::Test {\n public:\n VideoSendStreamTest() : fake_encoder_(Clock::GetRealTimeClock()) {}\n\n protected:\n static const uint32_t kSendSsrc;\n void RunSendTest(Call* call,\n const VideoSendStream::Config& config,\n SendTransportObserver* observer) {\n VideoSendStream* send_stream = call->CreateSendStream(config);\n scoped_ptr frame_generator_capturer(\n test::FrameGeneratorCapturer::Create(\n send_stream->Input(),\n test::FrameGenerator::Create(320, 240, Clock::GetRealTimeClock()),\n 30));\n send_stream->StartSend();\n frame_generator_capturer->Start();\n\n EXPECT_EQ(kEventSignaled, observer->Wait());\n\n frame_generator_capturer->Stop();\n send_stream->StopSend();\n call->DestroySendStream(send_stream);\n }\n\n VideoSendStream::Config GetSendTestConfig(Call* call) {\n VideoSendStream::Config config = call->GetDefaultSendConfig();\n config.encoder = &fake_encoder_;\n config.internal_source = false;\n config.rtp.ssrcs.push_back(kSendSsrc);\n test::FakeEncoder::SetCodecSettings(&config.codec, 1);\n return config;\n }\n\n test::FakeEncoder fake_encoder_;\n};\n\nconst uint32_t VideoSendStreamTest::kSendSsrc = 0xC0FFEE;\n\nTEST_F(VideoSendStreamTest, SendsSetSsrc) {\n class SendSsrcObserver : public SendTransportObserver {\n public:\n SendSsrcObserver() : SendTransportObserver(30 * 1000) {}\n\n virtual bool SendRTP(const uint8_t* packet, size_t length) OVERRIDE {\n RTPHeader header;\n EXPECT_TRUE(\n rtp_header_parser_->Parse(packet, static_cast(length), &header));\n\n if (header.ssrc == kSendSsrc)\n send_test_complete_->Set();\n\n return true;\n }\n } observer;\n\n Call::Config call_config(&observer);\n scoped_ptr call(Call::Create(call_config));\n\n VideoSendStream::Config send_config = GetSendTestConfig(call.get());\n\n RunSendTest(call.get(), send_config, &observer);\n}\n\nTEST_F(VideoSendStreamTest, SupportsCName) {\n static std::string kCName = \"PjQatC14dGfbVwGPUOA9IH7RlsFDbWl4AhXEiDsBizo=\";\n class CNameObserver : public SendTransportObserver {\n public:\n CNameObserver() : SendTransportObserver(30 * 1000) {}\n\n virtual bool SendRTCP(const uint8_t* packet, size_t length) OVERRIDE {\n RTCPUtility::RTCPParserV2 parser(packet, length, true);\n EXPECT_TRUE(parser.IsValid());\n\n RTCPUtility::RTCPPacketTypes packet_type = parser.Begin();\n while (packet_type != RTCPUtility::kRtcpNotValidCode) {\n if (packet_type == RTCPUtility::kRtcpSdesChunkCode) {\n EXPECT_EQ(parser.Packet().CName.CName, kCName);\n send_test_complete_->Set();\n }\n\n packet_type = parser.Iterate();\n }\n\n return true;\n }\n } observer;\n\n Call::Config call_config(&observer);\n scoped_ptr call(Call::Create(call_config));\n\n VideoSendStream::Config send_config = GetSendTestConfig(call.get());\n send_config.rtp.c_name = kCName;\n\n RunSendTest(call.get(), send_config, &observer);\n}\n\nTEST_F(VideoSendStreamTest, RespondsToNack) {\n class NackObserver : public SendTransportObserver, webrtc::Transport {\n public:\n NackObserver()\n : SendTransportObserver(30 * 1000),\n thread_(ThreadWrapper::CreateThread(NackProcess, this)),\n send_call_receiver_(NULL),\n send_count_(0),\n ssrc_(0),\n nacked_sequence_number_(0) {}\n\n ~NackObserver() {\n EXPECT_TRUE(thread_->Stop());\n }\n\n void SetReceiver(PacketReceiver* send_call_receiver) {\n send_call_receiver_ = send_call_receiver;\n }\n\n \/\/ Sending NACKs must be done from a different \"network\" thread to prevent\n \/\/ violating locking orders. With this no locks are held prior to inserting\n \/\/ packets back into the sender.\n static bool NackProcess(void* observer) {\n return static_cast(observer)->SendNack();\n }\n\n bool SendNack() {\n NullReceiveStatistics null_stats;\n RTCPSender rtcp_sender(0, false, Clock::GetRealTimeClock(), &null_stats);\n EXPECT_EQ(0, rtcp_sender.RegisterSendTransport(this));\n\n rtcp_sender.SetRTCPStatus(kRtcpNonCompound);\n rtcp_sender.SetRemoteSSRC(ssrc_);\n\n RTCPSender::FeedbackState feedback_state;\n EXPECT_EQ(0, rtcp_sender.SendRTCP(\n feedback_state, kRtcpNack, 1, &nacked_sequence_number_));\n return false;\n }\n\n virtual int SendPacket(int channel, const void* data, int len) OVERRIDE {\n ADD_FAILURE()\n << \"This should never be reached. Only a NACK should be sent.\";\n return -1;\n }\n\n virtual int SendRTCPPacket(int channel,\n const void* data,\n int len) OVERRIDE {\n EXPECT_TRUE(send_call_receiver_->DeliverPacket(\n static_cast(data), static_cast(len)));\n return len;\n }\n\n virtual bool SendRTP(const uint8_t* packet, size_t length) OVERRIDE {\n EXPECT_TRUE(send_call_receiver_ != NULL);\n RTPHeader header;\n EXPECT_TRUE(\n rtp_header_parser_->Parse(packet, static_cast(length), &header));\n\n \/\/ Nack second packet after receiving the third one.\n if (++send_count_ == 3) {\n ssrc_ = header.ssrc;\n nacked_sequence_number_ = header.sequenceNumber - 1;\n unsigned int id;\n EXPECT_TRUE(thread_->Start(id));\n }\n\n if (header.sequenceNumber == nacked_sequence_number_)\n send_test_complete_->Set();\n\n return true;\n }\n private:\n scoped_ptr thread_;\n PacketReceiver* send_call_receiver_;\n int send_count_;\n uint32_t ssrc_;\n uint16_t nacked_sequence_number_;\n } observer;\n\n Call::Config call_config(&observer);\n scoped_ptr call(Call::Create(call_config));\n observer.SetReceiver(call->Receiver());\n\n VideoSendStream::Config send_config = GetSendTestConfig(call.get());\n send_config.rtp.nack.rtp_history_ms = 1000;\n\n RunSendTest(call.get(), send_config, &observer);\n}\n\n} \/\/ namespace webrtc\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/button\/custom_button.h\"\n\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/animation\/throb_animation.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"ui\/gfx\/screen.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace views {\n\n\/\/ How long the hover animation takes if uninterrupted.\nstatic const int kHoverFadeDurationMs = 150;\n\n\/\/ static\nconst char CustomButton::kViewClassName[] = \"views\/CustomButton\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, public:\n\nCustomButton::~CustomButton() {\n}\n\nvoid CustomButton::SetState(ButtonState state) {\n if (state == state_)\n return;\n\n if (animate_on_state_change_ &&\n (!is_throbbing_ || !hover_animation_->is_animating())) {\n is_throbbing_ = false;\n if (state_ == BS_NORMAL && state == BS_HOT) {\n \/\/ Button is hovered from a normal state, start hover animation.\n hover_animation_->Show();\n } else if (state_ == BS_HOT && state == BS_NORMAL) {\n \/\/ Button is returning to a normal state from hover, start hover\n \/\/ fade animation.\n hover_animation_->Hide();\n } else {\n hover_animation_->Stop();\n }\n }\n\n state_ = state;\n StateChanged();\n SchedulePaint();\n}\n\nvoid CustomButton::StartThrobbing(int cycles_til_stop) {\n is_throbbing_ = true;\n hover_animation_->StartThrobbing(cycles_til_stop);\n}\n\nvoid CustomButton::StopThrobbing() {\n if (hover_animation_->is_animating()) {\n hover_animation_->Stop();\n SchedulePaint();\n }\n}\n\nvoid CustomButton::SetAnimationDuration(int duration) {\n hover_animation_->SetSlideDuration(duration);\n}\n\nbool CustomButton::IsMouseHovered() const {\n \/\/ If we haven't yet been placed in an onscreen view hierarchy, we can't be\n \/\/ hovered.\n if (!GetWidget())\n return false;\n\n gfx::Point cursor_pos(gfx::Screen::GetCursorScreenPoint());\n ConvertPointToView(NULL, this, &cursor_pos);\n return HitTest(cursor_pos);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides:\n\nvoid CustomButton::SetHotTracked(bool flag) {\n if (state_ != BS_DISABLED)\n SetState(flag ? BS_HOT : BS_NORMAL);\n\n if (flag && GetWidget()) {\n GetWidget()->NotifyAccessibilityEvent(\n this, ui::AccessibilityTypes::EVENT_FOCUS, true);\n }\n}\n\nbool CustomButton::IsHotTracked() const {\n return state_ == BS_HOT;\n}\n\nvoid CustomButton::OnEnabledChanged() {\n if (View::IsEnabled() ? (state_ != BS_DISABLED) : (state_ == BS_DISABLED))\n return;\n\n if (View::IsEnabled())\n SetState(IsMouseHovered() ? BS_HOT : BS_NORMAL);\n else\n SetState(BS_DISABLED);\n}\n\nbool CustomButton::IsEnabled() const {\n return state_ != BS_DISABLED;\n}\n\nstd::string CustomButton::GetClassName() const {\n return kViewClassName;\n}\n\nbool CustomButton::OnMousePressed(const MouseEvent& event) {\n if (state_ != BS_DISABLED) {\n if (ShouldEnterPushedState(event) && HitTest(event.location()))\n SetState(BS_PUSHED);\n if (request_focus_on_press_)\n RequestFocus();\n }\n return true;\n}\n\nbool CustomButton::OnMouseDragged(const MouseEvent& event) {\n if (state_ != BS_DISABLED) {\n if (HitTest(event.location()))\n SetState(ShouldEnterPushedState(event) ? BS_PUSHED : BS_HOT);\n else\n SetState(BS_NORMAL);\n }\n return true;\n}\n\nvoid CustomButton::OnMouseReleased(const MouseEvent& event) {\n if (state_ == BS_DISABLED)\n return;\n\n if (!HitTest(event.location())) {\n SetState(BS_NORMAL);\n return;\n }\n\n SetState(BS_HOT);\n if (IsTriggerableEvent(event)) {\n NotifyClick(event);\n \/\/ NOTE: We may be deleted at this point (by the listener's notification\n \/\/ handler).\n }\n}\n\nvoid CustomButton::OnMouseCaptureLost() {\n \/\/ Starting a drag results in a MouseCaptureLost, we need to ignore it.\n if (state_ != BS_DISABLED && !InDrag())\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::OnMouseEntered(const MouseEvent& event) {\n if (state_ != BS_DISABLED)\n SetState(BS_HOT);\n}\n\nvoid CustomButton::OnMouseExited(const MouseEvent& event) {\n \/\/ Starting a drag results in a MouseExited, we need to ignore it.\n if (state_ != BS_DISABLED && !InDrag())\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::OnMouseMoved(const MouseEvent& event) {\n if (state_ != BS_DISABLED)\n SetState(HitTest(event.location()) ? BS_HOT : BS_NORMAL);\n}\n\nbool CustomButton::OnKeyPressed(const KeyEvent& event) {\n if (state_ == BS_DISABLED)\n return false;\n\n \/\/ Space sets button state to pushed. Enter clicks the button. This matches\n \/\/ the Windows native behavior of buttons, where Space clicks the button on\n \/\/ KeyRelease and Enter clicks the button on KeyPressed.\n if (event.key_code() == ui::VKEY_SPACE) {\n SetState(BS_PUSHED);\n } else if (event.key_code() == ui::VKEY_RETURN) {\n SetState(BS_NORMAL);\n NotifyClick(event);\n } else {\n return false;\n }\n return true;\n}\n\nbool CustomButton::OnKeyReleased(const KeyEvent& event) {\n if ((state_ == BS_DISABLED) || (event.key_code() != ui::VKEY_SPACE))\n return false;\n\n SetState(BS_NORMAL);\n NotifyClick(event);\n return true;\n}\n\nbool CustomButton::AcceleratorPressed(const Accelerator& accelerator) {\n if (!View::IsEnabled())\n return false;\n\n SetState(BS_NORMAL);\n KeyEvent key_event(ui::ET_KEY_RELEASED, accelerator.key_code(),\n accelerator.modifiers());\n NotifyClick(key_event);\n return true;\n}\n\nvoid CustomButton::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) {\n if (!context_menu_controller())\n return;\n\n \/\/ We're about to show the context menu. Showing the context menu likely means\n \/\/ we won't get a mouse exited and reset state. Reset it now to be sure.\n if (state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n View::ShowContextMenu(p, is_mouse_gesture);\n}\n\nvoid CustomButton::OnDragDone() {\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::GetAccessibleState(ui::AccessibleViewState* state) {\n Button::GetAccessibleState(state);\n switch (state_) {\n case BS_HOT:\n state->state = ui::AccessibilityTypes::STATE_HOTTRACKED;\n break;\n case BS_PUSHED:\n state->state = ui::AccessibilityTypes::STATE_PRESSED;\n break;\n case BS_DISABLED:\n state->state = ui::AccessibilityTypes::STATE_UNAVAILABLE;\n break;\n case BS_NORMAL:\n case BS_COUNT:\n \/\/ No additional accessibility state set for this button state.\n break;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, ui::AnimationDelegate implementation:\n\nvoid CustomButton::AnimationProgressed(const ui::Animation* animation) {\n SchedulePaint();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, protected:\n\nCustomButton::CustomButton(ButtonListener* listener)\n : Button(listener),\n state_(BS_NORMAL),\n animate_on_state_change_(true),\n is_throbbing_(false),\n triggerable_event_flags_(ui::EF_LEFT_BUTTON_DOWN),\n request_focus_on_press_(true) {\n hover_animation_.reset(new ui::ThrobAnimation(this));\n hover_animation_->SetSlideDuration(kHoverFadeDurationMs);\n}\n\nvoid CustomButton::StateChanged() {\n}\n\nbool CustomButton::IsTriggerableEvent(const MouseEvent& event) {\n return (triggerable_event_flags_ & event.flags()) != 0;\n}\n\nbool CustomButton::ShouldEnterPushedState(const MouseEvent& event) {\n return IsTriggerableEvent(event);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides (protected):\n\nvoid CustomButton::ViewHierarchyChanged(bool is_add, View *parent,\n View *child) {\n if (!is_add && state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n}\n\nbool CustomButton::IsFocusable() const {\n return (state_ != BS_DISABLED) && View::IsFocusable();\n}\n\nvoid CustomButton::OnBlur() {\n if (IsHotTracked())\n SetState(BS_NORMAL);\n}\n\n} \/\/ namespace views\nFix painting issue with maximize button in aura.\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"views\/controls\/button\/custom_button.h\"\n\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/animation\/throb_animation.h\"\n#include \"ui\/base\/keycodes\/keyboard_codes.h\"\n#include \"ui\/gfx\/screen.h\"\n#include \"views\/widget\/widget.h\"\n\nnamespace views {\n\n\/\/ How long the hover animation takes if uninterrupted.\nstatic const int kHoverFadeDurationMs = 150;\n\n\/\/ static\nconst char CustomButton::kViewClassName[] = \"views\/CustomButton\";\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, public:\n\nCustomButton::~CustomButton() {\n}\n\nvoid CustomButton::SetState(ButtonState state) {\n if (state == state_)\n return;\n\n if (animate_on_state_change_ &&\n (!is_throbbing_ || !hover_animation_->is_animating())) {\n is_throbbing_ = false;\n if (state_ == BS_NORMAL && state == BS_HOT) {\n \/\/ Button is hovered from a normal state, start hover animation.\n hover_animation_->Show();\n } else if ((state_ == BS_HOT || state_ == BS_PUSHED)\n && state == BS_NORMAL) {\n \/\/ Button is returning to a normal state from hover, start hover\n \/\/ fade animation.\n hover_animation_->Hide();\n } else {\n hover_animation_->Stop();\n }\n }\n\n state_ = state;\n StateChanged();\n SchedulePaint();\n}\n\nvoid CustomButton::StartThrobbing(int cycles_til_stop) {\n is_throbbing_ = true;\n hover_animation_->StartThrobbing(cycles_til_stop);\n}\n\nvoid CustomButton::StopThrobbing() {\n if (hover_animation_->is_animating()) {\n hover_animation_->Stop();\n SchedulePaint();\n }\n}\n\nvoid CustomButton::SetAnimationDuration(int duration) {\n hover_animation_->SetSlideDuration(duration);\n}\n\nbool CustomButton::IsMouseHovered() const {\n \/\/ If we haven't yet been placed in an onscreen view hierarchy, we can't be\n \/\/ hovered.\n if (!GetWidget())\n return false;\n\n gfx::Point cursor_pos(gfx::Screen::GetCursorScreenPoint());\n ConvertPointToView(NULL, this, &cursor_pos);\n return HitTest(cursor_pos);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides:\n\nvoid CustomButton::SetHotTracked(bool flag) {\n if (state_ != BS_DISABLED)\n SetState(flag ? BS_HOT : BS_NORMAL);\n\n if (flag && GetWidget()) {\n GetWidget()->NotifyAccessibilityEvent(\n this, ui::AccessibilityTypes::EVENT_FOCUS, true);\n }\n}\n\nbool CustomButton::IsHotTracked() const {\n return state_ == BS_HOT;\n}\n\nvoid CustomButton::OnEnabledChanged() {\n if (View::IsEnabled() ? (state_ != BS_DISABLED) : (state_ == BS_DISABLED))\n return;\n\n if (View::IsEnabled())\n SetState(IsMouseHovered() ? BS_HOT : BS_NORMAL);\n else\n SetState(BS_DISABLED);\n}\n\nbool CustomButton::IsEnabled() const {\n return state_ != BS_DISABLED;\n}\n\nstd::string CustomButton::GetClassName() const {\n return kViewClassName;\n}\n\nbool CustomButton::OnMousePressed(const MouseEvent& event) {\n if (state_ != BS_DISABLED) {\n if (ShouldEnterPushedState(event) && HitTest(event.location()))\n SetState(BS_PUSHED);\n if (request_focus_on_press_)\n RequestFocus();\n }\n return true;\n}\n\nbool CustomButton::OnMouseDragged(const MouseEvent& event) {\n if (state_ != BS_DISABLED) {\n if (HitTest(event.location()))\n SetState(ShouldEnterPushedState(event) ? BS_PUSHED : BS_HOT);\n else\n SetState(BS_NORMAL);\n }\n return true;\n}\n\nvoid CustomButton::OnMouseReleased(const MouseEvent& event) {\n if (state_ == BS_DISABLED)\n return;\n\n if (!HitTest(event.location())) {\n SetState(BS_NORMAL);\n return;\n }\n\n SetState(BS_HOT);\n if (IsTriggerableEvent(event)) {\n NotifyClick(event);\n \/\/ NOTE: We may be deleted at this point (by the listener's notification\n \/\/ handler).\n }\n}\n\nvoid CustomButton::OnMouseCaptureLost() {\n \/\/ Starting a drag results in a MouseCaptureLost, we need to ignore it.\n if (state_ != BS_DISABLED && !InDrag())\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::OnMouseEntered(const MouseEvent& event) {\n if (state_ != BS_DISABLED)\n SetState(BS_HOT);\n}\n\nvoid CustomButton::OnMouseExited(const MouseEvent& event) {\n \/\/ Starting a drag results in a MouseExited, we need to ignore it.\n if (state_ != BS_DISABLED && !InDrag())\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::OnMouseMoved(const MouseEvent& event) {\n if (state_ != BS_DISABLED)\n SetState(HitTest(event.location()) ? BS_HOT : BS_NORMAL);\n}\n\nbool CustomButton::OnKeyPressed(const KeyEvent& event) {\n if (state_ == BS_DISABLED)\n return false;\n\n \/\/ Space sets button state to pushed. Enter clicks the button. This matches\n \/\/ the Windows native behavior of buttons, where Space clicks the button on\n \/\/ KeyRelease and Enter clicks the button on KeyPressed.\n if (event.key_code() == ui::VKEY_SPACE) {\n SetState(BS_PUSHED);\n } else if (event.key_code() == ui::VKEY_RETURN) {\n SetState(BS_NORMAL);\n NotifyClick(event);\n } else {\n return false;\n }\n return true;\n}\n\nbool CustomButton::OnKeyReleased(const KeyEvent& event) {\n if ((state_ == BS_DISABLED) || (event.key_code() != ui::VKEY_SPACE))\n return false;\n\n SetState(BS_NORMAL);\n NotifyClick(event);\n return true;\n}\n\nbool CustomButton::AcceleratorPressed(const Accelerator& accelerator) {\n if (!View::IsEnabled())\n return false;\n\n SetState(BS_NORMAL);\n KeyEvent key_event(ui::ET_KEY_RELEASED, accelerator.key_code(),\n accelerator.modifiers());\n NotifyClick(key_event);\n return true;\n}\n\nvoid CustomButton::ShowContextMenu(const gfx::Point& p, bool is_mouse_gesture) {\n if (!context_menu_controller())\n return;\n\n \/\/ We're about to show the context menu. Showing the context menu likely means\n \/\/ we won't get a mouse exited and reset state. Reset it now to be sure.\n if (state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n View::ShowContextMenu(p, is_mouse_gesture);\n}\n\nvoid CustomButton::OnDragDone() {\n SetState(BS_NORMAL);\n}\n\nvoid CustomButton::GetAccessibleState(ui::AccessibleViewState* state) {\n Button::GetAccessibleState(state);\n switch (state_) {\n case BS_HOT:\n state->state = ui::AccessibilityTypes::STATE_HOTTRACKED;\n break;\n case BS_PUSHED:\n state->state = ui::AccessibilityTypes::STATE_PRESSED;\n break;\n case BS_DISABLED:\n state->state = ui::AccessibilityTypes::STATE_UNAVAILABLE;\n break;\n case BS_NORMAL:\n case BS_COUNT:\n \/\/ No additional accessibility state set for this button state.\n break;\n }\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, ui::AnimationDelegate implementation:\n\nvoid CustomButton::AnimationProgressed(const ui::Animation* animation) {\n SchedulePaint();\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, protected:\n\nCustomButton::CustomButton(ButtonListener* listener)\n : Button(listener),\n state_(BS_NORMAL),\n animate_on_state_change_(true),\n is_throbbing_(false),\n triggerable_event_flags_(ui::EF_LEFT_BUTTON_DOWN),\n request_focus_on_press_(true) {\n hover_animation_.reset(new ui::ThrobAnimation(this));\n hover_animation_->SetSlideDuration(kHoverFadeDurationMs);\n}\n\nvoid CustomButton::StateChanged() {\n}\n\nbool CustomButton::IsTriggerableEvent(const MouseEvent& event) {\n return (triggerable_event_flags_ & event.flags()) != 0;\n}\n\nbool CustomButton::ShouldEnterPushedState(const MouseEvent& event) {\n return IsTriggerableEvent(event);\n}\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ CustomButton, View overrides (protected):\n\nvoid CustomButton::ViewHierarchyChanged(bool is_add, View *parent,\n View *child) {\n if (!is_add && state_ != BS_DISABLED)\n SetState(BS_NORMAL);\n}\n\nbool CustomButton::IsFocusable() const {\n return (state_ != BS_DISABLED) && View::IsFocusable();\n}\n\nvoid CustomButton::OnBlur() {\n if (IsHotTracked())\n SetState(BS_NORMAL);\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2016, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-core.\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core. If not, see .\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace hpp {\n namespace core {\n namespace steeringMethod {\n PathPtr_t ReedsShepp::impl_compute (ConfigurationIn_t q1,\n ConfigurationIn_t q2) const\n {\n ReedsSheppPathPtr_t path =\n ReedsSheppPath::create (device_.lock (), q1, q2,\n rho_ , xy_, rz_, constraints ());\n path->setWheelJoints (turningJoint_, wheels_);\n return path;\n }\n\n void ReedsShepp::computeRadius ()\n {\n rho_ = 1;\n if (wheels_.empty()) return;\n rho_ = 0;\n for (std::vector::const_iterator _wheels = wheels_.begin();\n _wheels != wheels_.end(); ++_wheels) {\n rho_ = std::max (rho_, computeAngle(*_wheels));\n }\n hppDout (info, \"rho_ = \" << rho_);\n }\n\n ReedsShepp::ReedsShepp (const ProblemPtr_t& problem) :\n SteeringMethod (problem), device_ (problem->robot ()),\n rho_ (1.), xy_ (0), rz_(2), weak_ ()\n {\n DevicePtr_t d (device_.lock());\n std::string sn = d->rootJoint()->jointModel().shortname();\n \/\/TODO shortname() == se3::JointModelPlanar::classname();\n if (sn == \"planar\") {\n turningJoint_ = d->rootJoint();\n } else if (sn == \"translation\" && d->rootJoint()->configSize() == 2) {\n std::string sn2 = d->getJointAtConfigRank(2)->jointModel().shortname();\n if (sn2 == \"revoluteunbounded\")\n turningJoint_ = d->getJointAtConfigRank(2);\n else\n throw std::runtime_error (\"root joint should be of type \"\n \"se3::JointModelPlanar or JointModelTranslation + JointModelRevolute\");\n } else {\n throw std::runtime_error (\"root joint should be of type \"\n \"se3::JointModelPlanar or JointModelTranslation + JointModelRevolute\");\n }\n\n guessWheels();\n computeRadius();\n }\n\n ReedsShepp::ReedsShepp (const ProblemPtr_t& problem,\n const value_type turningRadius,\n JointPtr_t xyJoint, JointPtr_t rzJoint,\n std::vector wheels) :\n SteeringMethod (problem), device_ (problem->robot ()),\n rho_ (turningRadius),\n turningJoint_ (rzJoint),\n xy_ (xyJoint->rankInConfiguration()),\n rz_ (rzJoint->rankInConfiguration()),\n wheels_ (wheels), weak_ ()\n {\n }\n\n \/\/\/ Copy constructor\n ReedsShepp::ReedsShepp (const ReedsShepp& other) :\n SteeringMethod (other), device_ (other.device_),\n rho_ (other.rho_)\n {\n }\n\n inline value_type ReedsShepp::computeAngle(const JointPtr_t wheel) const\n {\n \/\/ Compute wheel position in joint RZ\n const Transform3f zt (turningJoint_->currentTransformation ());\n const Transform3f wt (zt.actInv (wheel->currentTransformation ()));\n const vector3_t& wp (wt.translation ());\n\n \/\/ Assume the non turning wheels are on the plane z = 0 of \n \/\/ in joint rz.\n const value_type alpha = (wheel->upperBound(0) - wheel->lowerBound(0)) \/ 2;\n const value_type delta = std::abs(wp[1]);\n const value_type beta = std::abs(wp[2]);\n\n return delta + beta \/ std::tan(alpha);\n }\n\n inline void ReedsShepp::guessWheels()\n {\n wheels_.clear();\n for (std::size_t i = 0; i < turningJoint_->numberChildJoints(); ++i) {\n JointPtr_t j = turningJoint_->childJoint(i);\n if (j->configSize() != 1) continue;\n if (!j->isBounded(0)) continue;\n if (j->name().find(\"wheel\") == std::string::npos) continue;\n wheels_.push_back(j);\n }\n }\n } \/\/ namespace steeringMethod\n } \/\/ namespace core\n} \/\/ namespace hpp\nFix steeringMethod::ReedsShepp\/\/ Copyright (c) 2016, Joseph Mirabel\n\/\/ Authors: Joseph Mirabel (joseph.mirabel@laas.fr)\n\/\/\n\/\/ This file is part of hpp-core.\n\/\/ hpp-core is free software: you can redistribute it\n\/\/ and\/or modify it under the terms of the GNU Lesser General Public\n\/\/ License as published by the Free Software Foundation, either version\n\/\/ 3 of the License, or (at your option) any later version.\n\/\/\n\/\/ hpp-core is distributed in the hope that it will be\n\/\/ useful, but WITHOUT ANY WARRANTY; without even the implied warranty\n\/\/ of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n\/\/ General Lesser Public License for more details. You should have\n\/\/ received a copy of the GNU Lesser General Public License along with\n\/\/ hpp-core. If not, see .\n\n#include \n\n#include \n\n#include \n#include \n\n#include \n#include \n\nnamespace hpp {\n namespace core {\n namespace steeringMethod {\n PathPtr_t ReedsShepp::impl_compute (ConfigurationIn_t q1,\n ConfigurationIn_t q2) const\n {\n ReedsSheppPathPtr_t path =\n ReedsSheppPath::create (device_.lock (), q1, q2,\n rho_ , xy_, rz_, constraints ());\n path->setWheelJoints (turningJoint_, wheels_);\n return path;\n }\n\n void ReedsShepp::computeRadius ()\n {\n rho_ = 1;\n if (wheels_.empty()) return;\n rho_ = 0;\n for (std::vector::const_iterator _wheels = wheels_.begin();\n _wheels != wheels_.end(); ++_wheels) {\n rho_ = std::max (rho_, computeAngle(*_wheels));\n }\n hppDout (info, \"rho_ = \" << rho_);\n }\n\n ReedsShepp::ReedsShepp (const ProblemPtr_t& problem) :\n SteeringMethod (problem), device_ (problem->robot ()),\n rho_ (1.), xy_ (0), rz_(2), weak_ ()\n {\n DevicePtr_t d (device_.lock());\n std::string sn = d->rootJoint()->jointModel().shortname();\n if (sn == se3::JointModelPlanar::classname()) {\n turningJoint_ = d->rootJoint();\n \/\/ } else if (sn == se3::JointModelPlanar::classname() && d->rootJoint()->configSize() == 2) {\n \/\/ std::string sn2 = d->getJointAtConfigRank(2)->jointModel().shortname();\n \/\/ if (sn2 == \"revoluteunbounded\")\n \/\/ turningJoint_ = d->getJointAtConfigRank(2);\n \/\/ else\n \/\/ throw std::runtime_error (\"root joint should be of type \"\n \/\/ \"se3::JointModelPlanar or JointModelTranslation + JointModelRevolute\");\n } else {\n throw std::runtime_error (\"root joint should be of type \"\n \"se3::JointModelPlanar\" \/*\" or JointModelTranslation + JointModelRevolute\"*\/);\n }\n\n guessWheels();\n computeRadius();\n }\n\n ReedsShepp::ReedsShepp (const ProblemPtr_t& problem,\n const value_type turningRadius,\n JointPtr_t xyJoint, JointPtr_t rzJoint,\n std::vector wheels) :\n SteeringMethod (problem), device_ (problem->robot ()),\n rho_ (turningRadius),\n turningJoint_ (rzJoint),\n xy_ (xyJoint->rankInConfiguration()),\n rz_ (rzJoint->rankInConfiguration()),\n wheels_ (wheels), weak_ ()\n {\n }\n\n \/\/\/ Copy constructor\n ReedsShepp::ReedsShepp (const ReedsShepp& other) :\n SteeringMethod (other), device_ (other.device_),\n rho_ (other.rho_)\n {\n }\n\n inline value_type ReedsShepp::computeAngle(const JointPtr_t wheel) const\n {\n \/\/ Compute wheel position in joint RZ\n const Transform3f zt (turningJoint_->currentTransformation ());\n const Transform3f wt (zt.actInv (wheel->currentTransformation ()));\n const vector3_t& wp (wt.translation ());\n\n \/\/ Assume the non turning wheels are on the plane z = 0 of \n \/\/ in joint rz.\n const value_type alpha = (wheel->upperBound(0) - wheel->lowerBound(0)) \/ 2;\n const value_type delta = std::abs(wp[1]);\n const value_type beta = std::abs(wp[2]);\n\n return delta + beta \/ std::tan(alpha);\n }\n\n inline void ReedsShepp::guessWheels()\n {\n wheels_.clear();\n for (std::size_t i = 0; i < turningJoint_->numberChildJoints(); ++i) {\n JointPtr_t j = turningJoint_->childJoint(i);\n if (j->configSize() != 1) continue;\n if (!j->isBounded(0)) continue;\n if (j->name().find(\"wheel\") == std::string::npos) continue;\n wheels_.push_back(j);\n }\n }\n } \/\/ namespace steeringMethod\n } \/\/ namespace core\n} \/\/ namespace hpp\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Copyright (c) 2019, The Regents of the University of California\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stt\/SteinerTreeBuilder.h\"\n#include \"stt\/flute.h\"\n#include \"stt\/pdrev.h\"\n\n#include \n#include \n\n#include \"ord\/OpenRoad.hh\"\n#include \"opendb\/db.h\"\n\nnamespace stt{\n\nSteinerTreeBuilder::SteinerTreeBuilder() :\n alpha_(0.3),\n min_fanout_alpha_({0, -1}),\n min_hpwl_alpha_({0, -1}),\n logger_(nullptr),\n db_(nullptr)\n{\n}\n\nvoid SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger)\n{\n db_ = db;\n logger_ = logger;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n Tree tree = makeTree(x, y, drvr_index, alpha_);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net,\n std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n float net_alpha = alpha_;\n int min_fanout = min_fanout_alpha_.first;\n int min_hpwl = min_hpwl_alpha_.first;\n\n if (net_alpha_map_.find(net) != net_alpha_map_.end()) {\n net_alpha = net_alpha_map_[net];\n } else if (min_hpwl > 0) {\n if (computeHPWL(net) >= min_hpwl) {\n net_alpha = min_hpwl_alpha_.second;\n }\n } else if (min_fanout > 0) {\n if (net->getTermCount()-1 >= min_fanout) {\n net_alpha = min_fanout_alpha_.second;\n }\n }\n\n Tree tree = makeTree(x, y, drvr_index, net_alpha);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(const std::vector& x,\n const std::vector& y,\n const std::vector& s,\n int accuracy)\n{\n Tree tree = flt::flutes(x, y, s, accuracy);\n return tree;\n}\n\nvoid SteinerTreeBuilder::setAlpha(float alpha)\n{\n alpha_ = alpha;\n}\n\nfloat SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const\n{\n float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ?\n net_alpha_map_.at(net) : alpha_;\n return net_alpha;\n}\n\n\/\/ This checks whether the tree has the property that no two\n\/\/ non-adjacent edges have intersecting bounding boxes. If\n\/\/ they do it is a failure as embedding those egdes may cause\n\/\/ overlap between them.\nbool SteinerTreeBuilder::checkTree(const Tree& tree) const\n{\n \/\/ Such high fanout nets are going to get buffered so\n \/\/ we don't need to worry about them.\n if (tree.deg > 100) {\n return true;\n }\n\n std::vector rects;\n for (int i = 0; i < tree.branchCount(); ++i) {\n const Branch& branch = tree.branch[i];\n const int x1 = branch.x;\n const int y1 = branch.y;\n const Branch& neighbor = tree.branch[branch.n];\n const int x2 = neighbor.x;\n const int y2 = neighbor.y;\n rects.emplace_back(x1, y1, x2, y2);\n }\n for (auto i = 0; i < rects.size(); ++i) {\n for (auto j = i + 1; j < rects.size(); ++j) {\n const Branch& b1 = tree.branch[i];\n const Branch& b2 = tree.branch[j];\n const odb::Rect& r1 = rects[i];\n const odb::Rect& r2 = rects[j];\n if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) {\n debugPrint(logger_, utl::STT, \"check\", 1,\n \"check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}\",\n r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(),\n i, b1.n,\n r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(),\n j, b2.n, tree.deg);\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid SteinerTreeBuilder::setNetAlpha(const odb::dbNet* net, float alpha)\n{\n net_alpha_map_[net] = alpha;\n}\nvoid SteinerTreeBuilder::setMinFanoutAlpha(int min_fanout, float alpha)\n{\n min_fanout_alpha_ = {min_fanout, alpha};\n}\nvoid SteinerTreeBuilder::setMinHPWLAlpha(int min_hpwl, float alpha)\n{\n min_hpwl_alpha_ = {min_hpwl, alpha};\n}\n\nTree SteinerTreeBuilder::makeTree(std::vector& x,\n std::vector& y,\n int drvr_index,\n float alpha)\n{\n Tree tree;\n\n if (alpha > 0.0) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_);\n\n if (checkTree(tree)) {\n return tree;\n }\n\n \/\/ Try a smaller alpha if possible\n if (alpha > 0.1) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha - 0.1, logger_);\n if (checkTree(tree)) {\n return tree;\n }\n }\n\n \/\/ Give up and use flute\n return tree = flt::flute(x, y, flute_accuracy);\n } else {\n return flt::flute(x, y, flute_accuracy);\n }\n}\n\nint SteinerTreeBuilder::computeHPWL(odb::dbNet* net)\n{\n int min_x = std::numeric_limits::max();\n int min_y = std::numeric_limits::max();\n int max_x = std::numeric_limits::min();\n int max_y = std::numeric_limits::min();\n\n for (odb::dbITerm* iterm : net->getITerms()) {\n odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus();\n if (status != odb::dbPlacementStatus::NONE &&\n status != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n iterm->getAvgXY(&x, &y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 4, \"Net {} is connected to unplaced instance {}.\",\n net->getName(),\n iterm->getInst()->getName());\n }\n }\n\n for (odb::dbBTerm* bterm : net->getBTerms()) {\n if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE ||\n bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n bterm->getFirstPinLocation(x, y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 5, \"Net {} is connected to unplaced pin {}.\",\n net->getName(),\n bterm->getName());\n }\n }\n\n int hpwl = (max_x - min_x) + (max_y - min_y);\n\n return hpwl;\n}\n\nvoid Tree::printTree(utl::Logger* logger)\n{\n if (deg > 1) {\n for (int i = 0; i < deg; i++)\n logger->report(\" {:2d}: x={:4g} y={:4g} e={}\",\n i, (float)branch[i].x, (float)branch[i].y, branch[i].n);\n for (int i = deg; i < 2 * deg - 2; i++)\n logger->report(\"s{:2d}: x={:4g} y={:4g} e={}\",\n i, (float)branch[i].x, (float)branch[i].y, branch[i].n);\n logger->report(\"\");\n }\n}\n\n}\nstt: minor refactor\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Copyright (c) 2019, The Regents of the University of California\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stt\/SteinerTreeBuilder.h\"\n#include \"stt\/flute.h\"\n#include \"stt\/pdrev.h\"\n\n#include \n#include \n\n#include \"ord\/OpenRoad.hh\"\n#include \"opendb\/db.h\"\n\nnamespace stt{\n\nSteinerTreeBuilder::SteinerTreeBuilder() :\n alpha_(0.3),\n min_fanout_alpha_({0, -1}),\n min_hpwl_alpha_({0, -1}),\n logger_(nullptr),\n db_(nullptr)\n{\n}\n\nvoid SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger)\n{\n db_ = db;\n logger_ = logger;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n Tree tree = makeTree(x, y, drvr_index, alpha_);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net,\n std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n float net_alpha = alpha_;\n int min_fanout = min_fanout_alpha_.first;\n int min_hpwl = min_hpwl_alpha_.first;\n\n if (net_alpha_map_.find(net) != net_alpha_map_.end()) {\n net_alpha = net_alpha_map_[net];\n } else if (min_hpwl > 0) {\n if (computeHPWL(net) >= min_hpwl) {\n net_alpha = min_hpwl_alpha_.second;\n }\n } else if (min_fanout > 0) {\n if (net->getTermCount()-1 >= min_fanout) {\n net_alpha = min_fanout_alpha_.second;\n }\n }\n\n Tree tree = makeTree(x, y, drvr_index, net_alpha);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(const std::vector& x,\n const std::vector& y,\n const std::vector& s,\n int accuracy)\n{\n Tree tree = flt::flutes(x, y, s, accuracy);\n return tree;\n}\n\nvoid SteinerTreeBuilder::setAlpha(float alpha)\n{\n alpha_ = alpha;\n}\n\nfloat SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const\n{\n float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ?\n net_alpha_map_.at(net) : alpha_;\n return net_alpha;\n}\n\n\/\/ This checks whether the tree has the property that no two\n\/\/ non-adjacent edges have intersecting bounding boxes. If\n\/\/ they do it is a failure as embedding those egdes may cause\n\/\/ overlap between them.\nbool SteinerTreeBuilder::checkTree(const Tree& tree) const\n{\n \/\/ Such high fanout nets are going to get buffered so\n \/\/ we don't need to worry about them.\n if (tree.deg > 100) {\n return true;\n }\n\n std::vector rects;\n for (int i = 0; i < tree.branchCount(); ++i) {\n const Branch& branch = tree.branch[i];\n const int x1 = branch.x;\n const int y1 = branch.y;\n const Branch& neighbor = tree.branch[branch.n];\n const int x2 = neighbor.x;\n const int y2 = neighbor.y;\n rects.emplace_back(x1, y1, x2, y2);\n }\n for (auto i = 0; i < rects.size(); ++i) {\n for (auto j = i + 1; j < rects.size(); ++j) {\n const Branch& b1 = tree.branch[i];\n const Branch& b2 = tree.branch[j];\n const odb::Rect& r1 = rects[i];\n const odb::Rect& r2 = rects[j];\n if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) {\n debugPrint(logger_, utl::STT, \"check\", 1,\n \"check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}\",\n r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(),\n i, b1.n,\n r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(),\n j, b2.n, tree.deg);\n return false;\n }\n }\n }\n\n return true;\n}\n\nvoid SteinerTreeBuilder::setNetAlpha(const odb::dbNet* net, float alpha)\n{\n net_alpha_map_[net] = alpha;\n}\nvoid SteinerTreeBuilder::setMinFanoutAlpha(int min_fanout, float alpha)\n{\n min_fanout_alpha_ = {min_fanout, alpha};\n}\nvoid SteinerTreeBuilder::setMinHPWLAlpha(int min_hpwl, float alpha)\n{\n min_hpwl_alpha_ = {min_hpwl, alpha};\n}\n\nTree SteinerTreeBuilder::makeTree(std::vector& x,\n std::vector& y,\n int drvr_index,\n float alpha)\n{\n Tree tree;\n\n if (alpha > 0.0) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_);\n\n if (checkTree(tree)) {\n return tree;\n }\n\n \/\/ Try a smaller alpha if possible\n if (alpha > 0.1) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha - 0.1, logger_);\n if (checkTree(tree)) {\n return tree;\n }\n }\n\n \/\/ Give up and use flute\n } \n\n return flt::flute(x, y, flute_accuracy);\n}\n\nint SteinerTreeBuilder::computeHPWL(odb::dbNet* net)\n{\n int min_x = std::numeric_limits::max();\n int min_y = std::numeric_limits::max();\n int max_x = std::numeric_limits::min();\n int max_y = std::numeric_limits::min();\n\n for (odb::dbITerm* iterm : net->getITerms()) {\n odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus();\n if (status != odb::dbPlacementStatus::NONE &&\n status != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n iterm->getAvgXY(&x, &y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 4, \"Net {} is connected to unplaced instance {}.\",\n net->getName(),\n iterm->getInst()->getName());\n }\n }\n\n for (odb::dbBTerm* bterm : net->getBTerms()) {\n if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE ||\n bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n bterm->getFirstPinLocation(x, y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 5, \"Net {} is connected to unplaced pin {}.\",\n net->getName(),\n bterm->getName());\n }\n }\n\n int hpwl = (max_x - min_x) + (max_y - min_y);\n\n return hpwl;\n}\n\nvoid Tree::printTree(utl::Logger* logger)\n{\n if (deg > 1) {\n for (int i = 0; i < deg; i++)\n logger->report(\" {:2d}: x={:4g} y={:4g} e={}\",\n i, (float)branch[i].x, (float)branch[i].y, branch[i].n);\n for (int i = deg; i < 2 * deg - 2; i++)\n logger->report(\"s{:2d}: x={:4g} y={:4g} e={}\",\n i, (float)branch[i].x, (float)branch[i].y, branch[i].n);\n logger->report(\"\");\n }\n}\n\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Copyright (c) 2019, The Regents of the University of California\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stt\/SteinerTreeBuilder.h\"\n\n#include \n#include \n\n#include \"ord\/OpenRoad.hh\"\n#include \"opendb\/db.h\"\n\nnamespace stt{\n\nSteinerTreeBuilder::SteinerTreeBuilder() :\n alpha_(0.3),\n min_fanout_alpha_({0, -1}),\n min_hpwl_alpha_({0, -1}),\n logger_(nullptr),\n db_(nullptr)\n{\n}\n\nvoid SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger)\n{\n db_ = db;\n logger_ = logger;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n Tree tree = makeTree(x, y, drvr_index, alpha_);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net,\n std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n float net_alpha = alpha_;\n int min_fanout = min_fanout_alpha_.first;\n int min_hpwl = min_hpwl_alpha_.first;\n\n if (net_alpha_map_.find(net) != net_alpha_map_.end()) {\n net_alpha = net_alpha_map_[net];\n } else if (min_hpwl > 0) {\n if (computeHPWL(net) >= min_hpwl) {\n net_alpha = min_hpwl_alpha_.second;\n }\n } else if (min_fanout > 0) {\n if (net->getTermCount()-1 >= min_fanout) {\n net_alpha = min_fanout_alpha_.second;\n }\n }\n\n Tree tree = makeTree(x, y, drvr_index, net_alpha);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(const std::vector& x,\n const std::vector& y,\n const std::vector& s,\n int accuracy)\n{\n Tree tree = flt::flutes(x, y, s, accuracy);\n return tree;\n}\n\nfloat SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const\n{\n float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ?\n net_alpha_map_.at(net) : alpha_;\n return net_alpha;\n}\n\n\/\/ This checks whether the tree has the property that no two\n\/\/ non-adjacent edges have intersecting bounding boxes. If\n\/\/ they do it is a failure as embedding those egdes may cause\n\/\/ overlap between them.\nbool SteinerTreeBuilder::checkTree(const Tree& tree) const\n{\n \/\/ Such high fanout nets are going to get buffered so\n \/\/ we don't need to worry about them.\n if (tree.deg > 100) {\n return true;\n }\n\n std::vector rects;\n for (int i = 0; i < tree.branchCount(); ++i) {\n const Branch& branch = tree.branch[i];\n const int x1 = branch.x;\n const int y1 = branch.y;\n const Branch& neighbor = tree.branch[branch.n];\n const int x2 = neighbor.x;\n const int y2 = neighbor.y;\n rects.emplace_back(x1, y1, x2, y2);\n }\n for (auto i = 0; i < rects.size(); ++i) {\n for (auto j = i + 1; j < rects.size(); ++j) {\n const Branch& b1 = tree.branch[i];\n const Branch& b2 = tree.branch[j];\n const odb::Rect& r1 = rects[i];\n const odb::Rect& r2 = rects[j];\n if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) {\n debugPrint(logger_, utl::STT, \"check\", 1,\n \"check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}\",\n r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(),\n i, b1.n,\n r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(),\n j, b2.n, tree.deg);\n return false;\n }\n }\n }\n\n return true;\n}\n\nTree SteinerTreeBuilder::makeTree(std::vector& x,\n std::vector& y,\n int drvr_index,\n float alpha)\n{\n Tree tree;\n\n if (alpha > 0.0) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_);\n\n if (!checkTree(tree)) { \/\/ fallback\n tree = flt::flute(x, y, flute_accuracy);\n }\n } else {\n tree = flt::flute(x, y, flute_accuracy);\n }\n\n return tree;\n}\n\nint SteinerTreeBuilder::computeHPWL(odb::dbNet* net)\n{\n int min_x = std::numeric_limits::max();\n int min_y = std::numeric_limits::max();\n int max_x = std::numeric_limits::min();\n int max_y = std::numeric_limits::min();\n\n for (odb::dbITerm* iterm : net->getITerms()) {\n odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus();\n if (status != odb::dbPlacementStatus::NONE &&\n status != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n iterm->getAvgXY(&x, &y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 4, \"Net {} is connected to unplaced instance {}.\",\n net->getName(),\n iterm->getInst()->getName());\n }\n }\n\n for (odb::dbBTerm* bterm : net->getBTerms()) {\n if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE ||\n bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n bterm->getFirstPinLocation(x, y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 5, \"Net {} is connected to unplaced pin {}.\",\n net->getName(),\n bterm->getName());\n }\n }\n\n int hpwl = (max_x - min_x) + (max_y - min_y);\n\n return hpwl;\n}\n\n}\nstt: try adding alpha-0.1 fallback\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ BSD 3-Clause License\n\/\/\n\/\/ Copyright (c) 2019, The Regents of the University of California\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ * Redistributions of source code must retain the above copyright notice, this\n\/\/ list of conditions and the following disclaimer.\n\/\/\n\/\/ * Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ * Neither the name of the copyright holder nor the names of its\n\/\/ contributors may be used to endorse or promote products derived from\n\/\/ this software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n\/\/ POSSIBILITY OF SUCH DAMAGE.\n\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"stt\/SteinerTreeBuilder.h\"\n\n#include \n#include \n\n#include \"ord\/OpenRoad.hh\"\n#include \"opendb\/db.h\"\n\nnamespace stt{\n\nSteinerTreeBuilder::SteinerTreeBuilder() :\n alpha_(0.3),\n min_fanout_alpha_({0, -1}),\n min_hpwl_alpha_({0, -1}),\n logger_(nullptr),\n db_(nullptr)\n{\n}\n\nvoid SteinerTreeBuilder::init(odb::dbDatabase* db, Logger* logger)\n{\n db_ = db;\n logger_ = logger;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n Tree tree = makeTree(x, y, drvr_index, alpha_);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(odb::dbNet* net,\n std::vector& x,\n std::vector& y,\n int drvr_index)\n{\n float net_alpha = alpha_;\n int min_fanout = min_fanout_alpha_.first;\n int min_hpwl = min_hpwl_alpha_.first;\n\n if (net_alpha_map_.find(net) != net_alpha_map_.end()) {\n net_alpha = net_alpha_map_[net];\n } else if (min_hpwl > 0) {\n if (computeHPWL(net) >= min_hpwl) {\n net_alpha = min_hpwl_alpha_.second;\n }\n } else if (min_fanout > 0) {\n if (net->getTermCount()-1 >= min_fanout) {\n net_alpha = min_fanout_alpha_.second;\n }\n }\n\n Tree tree = makeTree(x, y, drvr_index, net_alpha);\n\n return tree;\n}\n\nTree SteinerTreeBuilder::makeSteinerTree(const std::vector& x,\n const std::vector& y,\n const std::vector& s,\n int accuracy)\n{\n Tree tree = flt::flutes(x, y, s, accuracy);\n return tree;\n}\n\nfloat SteinerTreeBuilder::getAlpha(const odb::dbNet* net) const\n{\n float net_alpha = net_alpha_map_.find(net) != net_alpha_map_.end() ?\n net_alpha_map_.at(net) : alpha_;\n return net_alpha;\n}\n\n\/\/ This checks whether the tree has the property that no two\n\/\/ non-adjacent edges have intersecting bounding boxes. If\n\/\/ they do it is a failure as embedding those egdes may cause\n\/\/ overlap between them.\nbool SteinerTreeBuilder::checkTree(const Tree& tree) const\n{\n \/\/ Such high fanout nets are going to get buffered so\n \/\/ we don't need to worry about them.\n if (tree.deg > 100) {\n return true;\n }\n\n std::vector rects;\n for (int i = 0; i < tree.branchCount(); ++i) {\n const Branch& branch = tree.branch[i];\n const int x1 = branch.x;\n const int y1 = branch.y;\n const Branch& neighbor = tree.branch[branch.n];\n const int x2 = neighbor.x;\n const int y2 = neighbor.y;\n rects.emplace_back(x1, y1, x2, y2);\n }\n for (auto i = 0; i < rects.size(); ++i) {\n for (auto j = i + 1; j < rects.size(); ++j) {\n const Branch& b1 = tree.branch[i];\n const Branch& b2 = tree.branch[j];\n const odb::Rect& r1 = rects[i];\n const odb::Rect& r2 = rects[j];\n if (r1.intersects(r2) && b1.n != j && b2.n != i && b1.n != b2.n) {\n debugPrint(logger_, utl::STT, \"check\", 1,\n \"check failed ({}, {}) ({}, {}) [{}, {}] vs ({}, {}) ({}, {}) [{}, {}] degree={}\",\n r1.xMin(), r1.yMin(), r1.xMax(), r1.yMax(),\n i, b1.n,\n r2.xMin(), r2.yMin(), r2.xMax(), r2.yMax(),\n j, b2.n, tree.deg);\n return false;\n }\n }\n }\n\n return true;\n}\n\nTree SteinerTreeBuilder::makeTree(std::vector& x,\n std::vector& y,\n int drvr_index,\n float alpha)\n{\n Tree tree;\n\n if (alpha > 0.0) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha, logger_);\n\n if (checkTree(tree)) {\n return tree;\n }\n\n \/\/ Try a smaller alpha if possible\n if (alpha > 0.1) {\n tree = pdr::primDijkstra(x, y, drvr_index, alpha - 0.1, logger_);\n if (checkTree(tree)) {\n return tree;\n }\n }\n\n \/\/ Give up and use flute\n return tree = flt::flute(x, y, flute_accuracy);\n } else {\n return flt::flute(x, y, flute_accuracy);\n }\n}\n\nint SteinerTreeBuilder::computeHPWL(odb::dbNet* net)\n{\n int min_x = std::numeric_limits::max();\n int min_y = std::numeric_limits::max();\n int max_x = std::numeric_limits::min();\n int max_y = std::numeric_limits::min();\n\n for (odb::dbITerm* iterm : net->getITerms()) {\n odb::dbPlacementStatus status = iterm->getInst()->getPlacementStatus();\n if (status != odb::dbPlacementStatus::NONE &&\n status != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n iterm->getAvgXY(&x, &y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 4, \"Net {} is connected to unplaced instance {}.\",\n net->getName(),\n iterm->getInst()->getName());\n }\n }\n\n for (odb::dbBTerm* bterm : net->getBTerms()) {\n if (bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::NONE ||\n bterm->getFirstPinPlacementStatus() != odb::dbPlacementStatus::UNPLACED) {\n int x, y;\n bterm->getFirstPinLocation(x, y);\n min_x = std::min(min_x, x);\n max_x = std::max(max_x, x);\n min_y = std::min(min_y, y);\n max_y = std::max(max_y, y);\n } else {\n logger_->error(utl::STT, 5, \"Net {} is connected to unplaced pin {}.\",\n net->getName(),\n bterm->getName());\n }\n }\n\n int hpwl = (max_x - min_x) + (max_y - min_y);\n\n return hpwl;\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ Check that the stack trace debugging API works and returns correct\n\/\/ malloc and free stacks.\n\/\/ RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\n#include \n#include \n#include \n\nchar *mem;\nvoid func1() {\n mem = (char *)malloc(10);\n}\n\nvoid func2() {\n free(mem);\n}\n\nint main() {\n func1();\n func2();\n\n void *trace[100];\n size_t num_frames = 100;\n int thread_id;\n num_frames = __asan_get_alloc_stack(mem, trace, num_frames, &thread_id);\n\n fprintf(stderr, \"alloc stack retval %s\\n\", (num_frames > 0 && num_frames < 10)\n ? \"ok\" : \"\");\n \/\/ CHECK: alloc stack retval ok\n fprintf(stderr, \"thread id = %d\\n\", thread_id);\n \/\/ CHECK: thread id = 0\n fprintf(stderr, \"0x%lx\\n\", trace[0]);\n \/\/ CHECK: [[ALLOC_FRAME_0:0x[0-9a-f]+]]\n fprintf(stderr, \"0x%lx\\n\", trace[1]);\n \/\/ CHECK: [[ALLOC_FRAME_1:0x[0-9a-f]+]]\n\n num_frames = 100;\n num_frames = __asan_get_free_stack(mem, trace, num_frames, &thread_id);\n\n fprintf(stderr, \"free stack retval %s\\n\", (num_frames > 0 && num_frames < 10)\n ? \"ok\" : \"\");\n \/\/ CHECK: free stack retval ok\n fprintf(stderr, \"thread id = %d\\n\", thread_id);\n \/\/ CHECK: thread id = 0\n fprintf(stderr, \"0x%lx\\n\", trace[0]);\n \/\/ CHECK: [[FREE_FRAME_0:0x[0-9a-f]+]]\n fprintf(stderr, \"0x%lx\\n\", trace[1]);\n \/\/ CHECK: [[FREE_FRAME_1:0x[0-9a-f]+]]\n\n mem[0] = 'A'; \/\/ BOOM\n\n \/\/ CHECK: ERROR: AddressSanitizer: heap-use-after-free\n \/\/ CHECK: WRITE of size 1 at 0x{{.*}}\n \/\/ CHECK: freed by thread T0 here:\n \/\/ CHECK: #0 [[FREE_FRAME_0]]\n \/\/ CHECK: #1 [[FREE_FRAME_1]]\n \/\/ CHECK: previously allocated by thread T0 here:\n \/\/ CHECK: #0 [[ALLOC_FRAME_0]]\n \/\/ CHECK: #1 [[ALLOC_FRAME_1]]\n\n return 0;\n}\n[ASan] debug_stacks.cc was passing on ARM by accident, disable this test there for now.\/\/ Check that the stack trace debugging API works and returns correct\n\/\/ malloc and free stacks.\n\/\/ RUN: %clangxx_asan -O0 %s -o %t && not %run %t 2>&1 | FileCheck %s\n\n\/\/ FIXME: Figure out why allocation\/free stack traces may be too short on ARM.\n\/\/ REQUIRES: stable-runtime\n\n#include \n#include \n#include \n\nchar *mem;\nvoid func1() {\n mem = (char *)malloc(10);\n}\n\nvoid func2() {\n free(mem);\n}\n\nint main() {\n func1();\n func2();\n\n void *trace[100];\n size_t num_frames = 100;\n int thread_id;\n num_frames = __asan_get_alloc_stack(mem, trace, num_frames, &thread_id);\n\n fprintf(stderr, \"alloc stack retval %s\\n\", (num_frames > 0 && num_frames < 10)\n ? \"ok\" : \"\");\n \/\/ CHECK: alloc stack retval ok\n fprintf(stderr, \"thread id = %d\\n\", thread_id);\n \/\/ CHECK: thread id = 0\n fprintf(stderr, \"0x%lx\\n\", trace[0]);\n \/\/ CHECK: [[ALLOC_FRAME_0:0x[0-9a-f]+]]\n fprintf(stderr, \"0x%lx\\n\", trace[1]);\n \/\/ CHECK: [[ALLOC_FRAME_1:0x[0-9a-f]+]]\n\n num_frames = 100;\n num_frames = __asan_get_free_stack(mem, trace, num_frames, &thread_id);\n\n fprintf(stderr, \"free stack retval %s\\n\", (num_frames > 0 && num_frames < 10)\n ? \"ok\" : \"\");\n \/\/ CHECK: free stack retval ok\n fprintf(stderr, \"thread id = %d\\n\", thread_id);\n \/\/ CHECK: thread id = 0\n fprintf(stderr, \"0x%lx\\n\", trace[0]);\n \/\/ CHECK: [[FREE_FRAME_0:0x[0-9a-f]+]]\n fprintf(stderr, \"0x%lx\\n\", trace[1]);\n \/\/ CHECK: [[FREE_FRAME_1:0x[0-9a-f]+]]\n\n mem[0] = 'A'; \/\/ BOOM\n\n \/\/ CHECK: ERROR: AddressSanitizer: heap-use-after-free\n \/\/ CHECK: WRITE of size 1 at 0x{{.*}}\n \/\/ CHECK: freed by thread T0 here:\n \/\/ CHECK: #0 [[FREE_FRAME_0]]\n \/\/ CHECK: #1 [[FREE_FRAME_1]]\n \/\/ CHECK: previously allocated by thread T0 here:\n \/\/ CHECK: #0 [[ALLOC_FRAME_0]]\n \/\/ CHECK: #1 [[ALLOC_FRAME_1]]\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/***************************************************\/\/**\n * @file FlameXUSBTransferHelper.cpp\n * @date February 2016\n * @author Ocean Optics, Inc.\n *\n * LICENSE:\n *\n * SeaBreeze Copyright (C) 2016, Ocean Optics Inc\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject\n * to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *******************************************************\/\n\n#include \"common\/globals.h\"\n#include \"vendors\/OceanOptics\/buses\/usb\/FlameXUSBTransferHelper.h\"\n#include \/* for memcpy() *\/\n\nusing namespace seabreeze;\nusing namespace std;\n\nconst int FlameXUSBTransferHelper::WORD_SIZE_BYTES = 4;\n\nFlameXUSBTransferHelper::FlameXUSBTransferHelper(USB *usb,\n const OOIUSBBidrectionalEndpointMap &map) : USBTransferHelper(usb) {\n this->sendEndpoint = map.getPrimaryOutEndpoint();\n this->receiveEndpoint = map.getPrimaryInEndpoint();\n}\n\nFlameXUSBTransferHelper::~FlameXUSBTransferHelper() {\n\n}\n\nint FlameXUSBTransferHelper::receive(vector &buffer,\n unsigned int length) {\n if(0 != (length % WORD_SIZE_BYTES)) {\n vector *inBuffer;\n int paddedLength;\n \n paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES));\n inBuffer = new vector(paddedLength);\n \n int result = USBTransferHelper::receive(*inBuffer, paddedLength);\n if(result != paddedLength) {\n string error(\"Failed to read padded message length: \");\n error += result;\n error += \" != \";\n error += paddedLength;\n throw BusTransferException(error);\n }\n memcpy(&buffer[0], &inBuffer[0], length);\n delete inBuffer;\n return length;\n } else {\n return USBTransferHelper::receive(buffer, length);\n }\n}\n\nint FlameXUSBTransferHelper::send(const std::vector &buffer,\n unsigned int length) const {\n \n if(0 != (length % WORD_SIZE_BYTES)) {\n \/* Pad up to a multiple of the word size *\/\n int paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES));\n vector *outBuffer = new vector(paddedLength);\n memcpy(&outBuffer[0], &buffer[0], length);\n int result = USBTransferHelper::send(*outBuffer, paddedLength);\n delete outBuffer;\n return result;\n } else {\n return USBTransferHelper::send(buffer, length);\n }\n}\n[libseabreeze] fix FlameXUSBTransferHelper warning\/***************************************************\/\/**\n * @file FlameXUSBTransferHelper.cpp\n * @date February 2016\n * @author Ocean Optics, Inc.\n *\n * LICENSE:\n *\n * SeaBreeze Copyright (C) 2016, Ocean Optics Inc\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * \"Software\"), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and\/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject\n * to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included\n * in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n *******************************************************\/\n\n#include \"common\/globals.h\"\n#include \"vendors\/OceanOptics\/buses\/usb\/FlameXUSBTransferHelper.h\"\n#include \/* for memcpy() *\/\n\nusing namespace seabreeze;\nusing namespace std;\n\nconst int FlameXUSBTransferHelper::WORD_SIZE_BYTES = 4;\n\nFlameXUSBTransferHelper::FlameXUSBTransferHelper(USB *usb,\n const OOIUSBBidrectionalEndpointMap &map) : USBTransferHelper(usb) {\n this->sendEndpoint = map.getPrimaryOutEndpoint();\n this->receiveEndpoint = map.getPrimaryInEndpoint();\n}\n\nFlameXUSBTransferHelper::~FlameXUSBTransferHelper() {\n\n}\n\nint FlameXUSBTransferHelper::receive(vector &buffer,\n unsigned int length) {\n if(0 != (length % WORD_SIZE_BYTES)) {\n vector *inBuffer;\n int paddedLength;\n \n paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES));\n inBuffer = new vector(paddedLength);\n \n int result = USBTransferHelper::receive(*inBuffer, paddedLength);\n if(result != paddedLength) {\n string error(\"Failed to read padded message length: \");\n error += result;\n error += \" != \";\n error += paddedLength;\n throw BusTransferException(error);\n }\n memcpy(&buffer[0], &inBuffer[0], length);\n delete inBuffer;\n return length;\n } else {\n return USBTransferHelper::receive(buffer, length);\n }\n}\n\nint FlameXUSBTransferHelper::send(const std::vector &buffer,\n unsigned int length) const {\n \n if(0 != (length % WORD_SIZE_BYTES)) {\n \/* Pad up to a multiple of the word size *\/\n int paddedLength = length + (WORD_SIZE_BYTES - (length % WORD_SIZE_BYTES));\n vector *outBuffer = new vector(paddedLength);\n memcpy((byte*) &outBuffer[0], (byte*) &buffer[0], length);\n int result = USBTransferHelper::send(*outBuffer, paddedLength);\n delete outBuffer;\n return result;\n } else {\n return USBTransferHelper::send(buffer, length);\n }\n}\n<|endoftext|>"} {"text":"\/*!\n * \\brief Tests the GUI geometry builder\n *\n * \\author ddubois \n * \\date 06-Nov-16.\n *\/\n\n#include \n#include \n\n#include \n#include \n\nTEST(gui_geometry_builder, add_vertex_test) {\n auto vertex_buffer = std::vector{};\n\n nova::model::add_vertex(vertex_buffer, 5, 5, 0.5, 0.5);\n\n EXPECT_EQ(vertex_buffer.size(), 5);\n\n EXPECT_EQ(vertex_buffer[0], 5);\n EXPECT_EQ(vertex_buffer[1], 5);\n EXPECT_EQ(vertex_buffer[2], 0);\n EXPECT_EQ(vertex_buffer[3], 0.5);\n EXPECT_EQ(vertex_buffer[4], 0.5);\n}\n\nTEST(gui_geometry_builder, add_vertices_from_button_test) {\n auto vertex_buffer = std::vector{};\n auto button = mc_gui_button{0, 0, 100, 100, \"Main Menu\", false};\n auto uvs = std::vector{0, 0, 0, 1, 1, 0, 1, 1};\n\n nova::model::add_vertices_from_button(vertex_buffer, button, uvs);\n\n EXPECT_EQ(vertex_buffer.size(), 20);\n\n \/\/ First vertex\n EXPECT_EQ(vertex_buffer[0], 0);\n EXPECT_EQ(vertex_buffer[1], 0);\n EXPECT_EQ(vertex_buffer[2], 0);\n EXPECT_EQ(vertex_buffer[3], 0);\n\n \/\/ Third vertex because I'm too lazy to check all of them\n EXPECT_EQ(vertex_buffer[10], 0);\n EXPECT_EQ(vertex_buffer[11], 100);\n EXPECT_EQ(vertex_buffer[13], 1);\n EXPECT_EQ(vertex_buffer[14], 0);\n}\n\nTEST(gui_geometry_builder, add_indices_with_offset_positive_test) {\n auto indices = std::vector{};\n auto start_pos = 3;\n\n nova::model::add_indices_with_offset(indices, (unsigned int) start_pos);\n\n EXPECT_EQ(indices[0], 3);\n EXPECT_EQ(indices[1], 4);\n EXPECT_EQ(indices[2], 5);\n EXPECT_EQ(indices[3], 5);\n EXPECT_EQ(indices[4], 4);\n EXPECT_EQ(indices[5], 6);\n}\n\nTEST(gui_geometry_builder, add_indices_with_offset_negative_offset_test) {\n auto indices = std::vector{};\n auto start_pos = -3;\n\n nova::model::add_indices_with_offset(indices, (unsigned int) start_pos);\n\n EXPECT_EQ(indices[0], 65533);\n EXPECT_EQ(indices[1], 65534);\n EXPECT_EQ(indices[2], 65535);\n EXPECT_EQ(indices[3], 65535);\n EXPECT_EQ(indices[4], 65534);\n EXPECT_EQ(indices[5], 0);\n}\n\nTEST(gui_geometry_builder, build_gui_geometry_no_buttons_test) {\n nova::view::nova_renderer::init_instance();\n mc_gui_screen gui = {};\n gui.num_buttons = 0;\n\n nova::model::mesh_definition gui_mesh = nova::model::build_gui_geometry(gui);\n}\nAll tests now pass\/*!\n * \\brief Tests the GUI geometry builder\n *\n * \\author ddubois \n * \\date 06-Nov-16.\n *\/\n\n#include \n#include \n\n#include \n#include \n\nTEST(gui_geometry_builder, add_vertex_test) {\n auto vertex_buffer = std::vector{};\n\n nova::model::add_vertex(vertex_buffer, 5, 5, 0.5, 0.5);\n\n EXPECT_EQ(vertex_buffer.size(), 5);\n\n EXPECT_EQ(vertex_buffer[0], 5);\n EXPECT_EQ(vertex_buffer[1], 5);\n EXPECT_EQ(vertex_buffer[2], 0);\n EXPECT_EQ(vertex_buffer[3], 0.5);\n EXPECT_EQ(vertex_buffer[4], 0.5);\n}\n\nTEST(gui_geometry_builder, add_vertices_from_button_test) {\n auto vertex_buffer = std::vector{};\n auto button = mc_gui_button{0, 0, 100, 100, \"Main Menu\", false};\n auto uvs = std::vector{0, 0, 0, 1, 1, 0, 1, 1};\n\n nova::model::add_vertices_from_button(vertex_buffer, button, uvs);\n\n EXPECT_EQ(vertex_buffer.size(), 20);\n\n \/\/ First vertex\n EXPECT_EQ(vertex_buffer[0], 0);\n EXPECT_EQ(vertex_buffer[1], 0);\n EXPECT_EQ(vertex_buffer[2], 0);\n EXPECT_EQ(vertex_buffer[3], 0);\n\n \/\/ Third vertex because I'm too lazy to check all of them\n EXPECT_EQ(vertex_buffer[10], 0);\n EXPECT_EQ(vertex_buffer[11], 100);\n EXPECT_EQ(vertex_buffer[13], 1);\n EXPECT_EQ(vertex_buffer[14], 0);\n}\n\nTEST(gui_geometry_builder, add_indices_with_offset_positive_test) {\n auto indices = std::vector{};\n auto start_pos = 3;\n\n nova::model::add_indices_with_offset(indices, (unsigned int) start_pos);\n\n EXPECT_EQ(indices[0], 3);\n EXPECT_EQ(indices[1], 4);\n EXPECT_EQ(indices[2], 5);\n EXPECT_EQ(indices[3], 5);\n EXPECT_EQ(indices[4], 4);\n EXPECT_EQ(indices[5], 6);\n}\n\nTEST(gui_geometry_builder, add_indices_with_offset_negative_offset_test) {\n auto indices = std::vector{};\n auto start_pos = -3;\n\n nova::model::add_indices_with_offset(indices, (unsigned int) start_pos);\n\n EXPECT_EQ(indices[0], 4294967293);\n EXPECT_EQ(indices[1], 4294967294);\n EXPECT_EQ(indices[2], 4294967295);\n EXPECT_EQ(indices[3], 4294967295);\n EXPECT_EQ(indices[4], 4294967294);\n EXPECT_EQ(indices[5], 0);\n}\n\nTEST(gui_geometry_builder, build_gui_geometry_no_buttons_test) {\n nova::view::nova_renderer::init_instance();\n mc_gui_screen gui = {};\n gui.num_buttons = 0;\n\n nova::model::mesh_definition gui_mesh = nova::model::build_gui_geometry(gui);\n}\n<|endoftext|>"} {"text":"\/\/ programming_challenges_13.cpp: santiaago\n\/\/ Description: Australian Voting - Programming challenges 110108\n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ntemplate\nvoid printVector(vector v);\nvoid printMap(map m);\n\nint main(){\n cout << \"Australian Voting\" << endl;\n unsigned int num_cases(0);\n cin >> num_cases;\n string line;\n getline (cin, line);\n while(num_cases > 0){\n unsigned int num_candidates(0);\n cin >> num_candidates;\n vector candidates(num_candidates);\n map > candidate_votes;\n\n string candidate;\n while( num_candidates > 0 && cin >> candidate ){\n candidates[candidates.size()-num_candidates] = candidate;\n num_candidates--;\n }\n printVector(candidates);\n \/\/printMap(candidate_votes);\n \/\/ read up to 1000 lines\n \n string vote;\n unsigned int num_votes(0);\n cin.ignore();\n while( num_votes < 1000){\n getline(cin, vote);\n if(vote.empty()) break;\n istringstream stm(vote);\n unsigned int index_candidate;\n vector current_vote;\n while( stm >> index_candidate){\n\tcurrent_vote.push_back(index_candidate);\n }\n for(int i = 0; i < current_vote.size(); i++){\n \t\/\/candidate_votes[candidates[current_vote[i] - 1]]++;\n\tcout << \"vote: \" << current_vote[i] << endl;\n\tcout << \"candidate: \" << candidates[current_vote[i]-1] << endl;\n\tcout << \"count: \" << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl;\n\tcandidate_votes[i + 1][candidates[current_vote[i]-1]]++;\/\/candidates[current_vote[i]][\n\tcout << \"count: \" << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl;\n }\n printVector(current_vote);\n num_votes++;\n }\n \/\/ printMap(candidate_votes);\n for(auto t : candidate_votes){\n cout << t.first << \" | \";\n for(auto t2 : t.second){\n\tcout << \"\\t\" << t2.first << \" : \" << t2.second << endl;\n } \n }\n cout << \"case done \" << endl;\n num_cases--;\n }\n cout << \"end\" << endl;\n}\n\ntemplate\nvoid printVector(vector v){\n for(T c : v){\n cout << c << \" | \";\n }\n cout << endl;\n}\n\nvoid printMap(map m){\n for(auto t : m){\n cout << t.first << \" : \" << t.second << endl;\n }\n}\nmain algorithm for the australian vote is ready.\/\/ programming_challenges_13.cpp: santiaago\n\/\/ Description: Australian Voting - Programming challenges 110108\n\n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace std;\n\ntemplate\nvoid printVector(vector v);\nvoid printMap(map m);\nstring getLowestCandidate(map candidates);\nstring getHighestCandidate(map m);\nbool areCandidatesTied(map candidates);\n\nint main(){\n cout << \"Australian Voting\" << endl;\n unsigned int num_cases(0);\n cin >> num_cases;\n string line;\n getline (cin, line);\n vector winners;\n while(num_cases > 0){\n unsigned int num_candidates(0);\n cin >> num_candidates;\n vector candidates(num_candidates);\n map > candidate_votes;\n\n string candidate;\n while( num_candidates > 0 && cin >> candidate ){\n candidates[candidates.size()-num_candidates] = candidate;\n num_candidates--;\n }\n printVector(candidates);\n \/\/ read up to 1000 lines \n string vote;\n unsigned int num_votes(0);\n cin.ignore();\n while( num_votes < 1000){\n getline(cin, vote);\n if(vote.empty()) break;\n istringstream stm(vote);\n unsigned int index_candidate;\n vector current_vote;\n while( stm >> index_candidate){\n\tcurrent_vote.push_back(index_candidate);\n }\n for(int i = 0; i < current_vote.size(); i++){\n \t\/\/candidate_votes[candidates[current_vote[i] - 1]]++;\n\tcout << \"vote: \" << current_vote[i] << endl;\n\tcout << \"candidate: \" << candidates[current_vote[i]-1] << endl;\n\tcout << \"count: \" << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl;\n\tcandidate_votes[i + 1][candidates[current_vote[i]-1]]++;\/\/candidates[current_vote[i]][\n\tcout << \"count: \" << candidate_votes[i + 1][candidates[current_vote[i]-1]] << endl;\n }\n printVector(current_vote);\n num_votes++;\n }\n for(auto t : candidate_votes){\n cout << t.first << \" | \";\n for(auto t2 : t.second){\n\tcout << \"\\t\" << t2.first << \" : \" << t2.second << endl;\n } \n }\n double mayority = num_votes\/double(2.0);\n bool has_winner(false);\n while(!has_winner){\n for(auto t : candidate_votes[1]){\n\tif(t.second > mayority){\n\t winners.push_back(t.first);\n\t has_winner = true;\n\t break;\n\t}\n }\n if(!has_winner){\n\tstring highest_candidate = getHighestCandidate(candidate_votes[1]);\n\tstring lowest_candidate = getLowestCandidate(candidate_votes[1]);\n\tunsigned int votes = candidate_votes[1][lowest_candidate];\n\tmap::iterator to_remove;\n\tto_remove = candidate_votes[1].find(lowest_candidate);\n\tcandidate_votes[1].erase(to_remove);\n\tcandidate_votes[1][highest_candidate] += votes;\n }\n if(areCandidatesTied(candidate_votes[1])){\n\tfor(auto c : candidate_votes[1]){\n\t winners.push_back(c.first);\n\t}\n\thas_winner = true;\n }\n }\n \n for(auto w : winners){\n cout << w << endl;\n }\n cout << \"case done \" << endl;\n num_cases--;\n }\n for(int i = 0; i < winners.size(); i++){\n cout << winners[i] << endl;\n }\n cout << \"end\" << endl;\n}\n\ntemplate\nvoid printVector(vector v){\n for(T c : v){\n cout << c << \" | \";\n }\n cout << endl;\n}\n\nvoid printMap(map m){\n for(auto t : m){\n cout << t.first << \" : \" << t.second << endl;\n }\n}\n\nbool areCandidatesTied(map candidates){\n unsigned int value(-1);\n for(auto c : candidates){\n if(value == -1){\n value = c.second;\n } else {\n if(value != c.second){\n\treturn false;\n }\n }\n }\n return true;\n}\n\nstring getLowestCandidate(map candidates){\n string lowest_candidate;\n unsigned int min(numeric_limits::max());\n for(auto c : candidates){\n if(c.second < min){\n min = c.second;\n lowest_candidate = c.first;\n }\n }\n return lowest_candidate;\n \n}\n\nstring getHighestCandidate(map candidates){\n string highest_candidate;\n unsigned int max(0);\n for(auto c : candidates){\n if(c.second > max){\n max = c.second;\n highest_candidate = c.first;\n }\n }\n return highest_candidate;\n}\n<|endoftext|>"} {"text":"#include \"request.h\"\n#include \n\nnamespace REST {\n\nconst size_t Request::BUFFER_SIZE = 4096;\n\nRequest::Request(int client, struct sockaddr_storage client_addr) : handle(client), addr(client_addr) {\n static Json::Reader json_reader;\n\n std::string line;\n bool is_header = true;\n char buffer[BUFFER_SIZE];\n\n \/\/ receive data from client\n recv(client, buffer, BUFFER_SIZE, 0);\n\n \/\/ parse each line\n std::istringstream request_stream(buffer);\n while (std::getline(request_stream, line)) {\n \/\/ if method is undefined, assumie its first line\n if (method == Method::UNDEFINED) {\n \/\/ so parse header\n parse_header(line);\n continue;\n }\n\n \/\/ next lines are headers, strip them\n line.erase(line.find_last_not_of(\" \\n\\r\\t\")+1);\n\n \/\/ if line is empty, then content should follow\n if (line.size() == 0) {\n is_header = false;\n break;\n }\n\n \/\/ extract name and value from header\n size_t colon;\n std::string name = line.substr(0, colon = line.find(\":\"));\n std::string value = line.substr(colon+1);\n value.erase(0, value.find_first_not_of(\" \\n\\r\\t\"));\n\n headers.insert(std::make_pair(name, value));\n }\n\n \/\/ if has content\n if (!is_header) {\n \/\/ assume proper content length\n size_t content_length = header(\"Content-Length\", 0);\n raw.reserve(content_length);\n\n if (content_length > 0) {\n \/\/ read whats left in header\n length = std::min(content_length, (size_t)(BUFFER_SIZE - request_stream.tellg()));\n raw = std::string(buffer, BUFFER_SIZE).substr(request_stream.tellg(), length);\n\n \/\/ receive some more\n while (length < content_length) {\n memset(buffer, 0, BUFFER_SIZE);\n size_t buffer_length = recv(client, buffer, BUFFER_SIZE, 0);\n raw += std::string(buffer, buffer_length);\n length += buffer_length;\n }\n }\n \/\/std::cout << \"content o \"<second == \"application\/x-www-form-urlencoded\") {\n parse_query_string(raw);\n } else\n if (ct->second == \"application\/json\" || ct->second == \"text\/json\") {\n data = std::make_shared();\n json_reader.parse(raw, *data.get(), false);\n }\n }\n }\n}\n\nvoid Request::parse_header(std::string line) {\n if (line.find(\"GET\") == 0) {\n method = Method::GET;\n } else\n if (line.find(\"HEAD\") == 0) {\n method = Method::HEAD;\n } else\n if (line.find(\"POST\") == 0) {\n method = Method::POST;\n } else\n if (line.find(\"PUT\") == 0) {\n method = Method::PUT;\n } else\n if (line.find(\"PATCH\") == 0) {\n method = Method::PATCH;\n } else\n if (line.find(\"DELETE\") == 0) {\n method = Method::DELETE;\n } else\n if (line.find(\"TRACE\") == 0) {\n method = Method::TRACE;\n } else\n if (line.find(\"CONNECT\") == 0) {\n method = Method::CONNECT;\n } else\n if (line.find(\"OPTIONS\") == 0) {\n method = Method::OPTIONS;\n }\n\n size_t path_start = line.find_first_of(\" \")+1;\n size_t path_end = line.rfind(\"HTTP\/1.\")-1;\n\n path = line.substr(path_start, path_end - path_start);\n\n size_t path_query = path.find(\"?\");\n\n if (path_query != std::string::npos) {\n std::string query = path.substr(path_query+1, path.size() - path_query);\n\n parse_query_string(query);\n\n path.erase(path_query, query.size()+1);\n }\n}\n\nvoid Request::parse_query_string(std::string query) {\n query.erase(query.find_last_not_of(\" \\n\\r\\t\")+1);\n std::istringstream query_stream(query);\n std::string pair;\n while (std::getline(query_stream, pair, '&')) {\n std::string name, value;\n size_t value_position = pair.find(\"=\");\n\n name = pair.substr(0, value_position);\n if (value_position != std::string::npos)\n value = pair.substr(value_position+1, pair.size() - value_position-1);\n\n parameters[Utils::uri_decode(name)] = Utils::uri_decode(value);\n }\n}\n\nRequest::~Request() {\n}\n\n\n}\nworking on copy#include \"request.h\"\n#include \n\nnamespace REST {\n\nconst size_t Request::BUFFER_SIZE = 4096;\n\nRequest::Request(int client, struct sockaddr_storage client_addr) : handle(client), addr(client_addr) {\n static Json::Reader json_reader;\n\n std::string line;\n bool is_header = true;\n char buffer[BUFFER_SIZE];\n\n \/\/ receive data from client\n recv(client, buffer, BUFFER_SIZE, 0);\n\n \/\/ parse each line\n std::istringstream request_stream(buffer);\n while (std::getline(request_stream, line)) {\n \/\/ if method is undefined, assumie its first line\n if (method == Method::UNDEFINED) {\n \/\/ so parse header\n parse_header(line);\n continue;\n }\n\n \/\/ next lines are headers, strip them\n line.erase(line.find_last_not_of(\" \\n\\r\\t\")+1);\n\n \/\/ if line is empty, then content should follow\n if (line.size() == 0) {\n is_header = false;\n break;\n }\n\n \/\/ extract name and value from header\n size_t colon;\n std::string name = line.substr(0, colon = line.find(\":\"));\n std::string value = line.substr(colon+1);\n value.erase(0, value.find_first_not_of(\" \\n\\r\\t\"));\n\n headers.insert(std::make_pair(name, value));\n }\n\n \/\/ if has content\n if (!is_header) {\n \/\/ assume proper content length\n size_t content_length = header(\"Content-Length\", 0);\n raw.reserve(content_length);\n\n if (content_length > 0) {\n \/\/ read whats left in header\n length = std::min(content_length, (size_t)(BUFFER_SIZE - request_stream.tellg()));\n raw = std::string(buffer, BUFFER_SIZE).substr(request_stream.tellg(), length);\n\n \/\/ receive some more\n while (length < content_length) {\n memset(buffer, 0, BUFFER_SIZE);\n size_t buffer_length = recv(client, buffer, BUFFER_SIZE, 0);\n raw += std::string(buffer, buffer_length);\n length += buffer_length;\n }\n }\n \/\/std::cout << \"content o \"<second == \"application\/x-www-form-urlencoded\") {\n parse_query_string(raw);\n } else\n if (ct->second == \"application\/json\" || ct->second == \"text\/json\") {\n data = std::make_shared();\n std::string raw_copy(raw);\n json_reader.parse(raw_copy, *data.get(), false);\n }\n }\n }\n}\n\nvoid Request::parse_header(std::string line) {\n if (line.find(\"GET\") == 0) {\n method = Method::GET;\n } else\n if (line.find(\"HEAD\") == 0) {\n method = Method::HEAD;\n } else\n if (line.find(\"POST\") == 0) {\n method = Method::POST;\n } else\n if (line.find(\"PUT\") == 0) {\n method = Method::PUT;\n } else\n if (line.find(\"PATCH\") == 0) {\n method = Method::PATCH;\n } else\n if (line.find(\"DELETE\") == 0) {\n method = Method::DELETE;\n } else\n if (line.find(\"TRACE\") == 0) {\n method = Method::TRACE;\n } else\n if (line.find(\"CONNECT\") == 0) {\n method = Method::CONNECT;\n } else\n if (line.find(\"OPTIONS\") == 0) {\n method = Method::OPTIONS;\n }\n\n size_t path_start = line.find_first_of(\" \")+1;\n size_t path_end = line.rfind(\"HTTP\/1.\")-1;\n\n path = line.substr(path_start, path_end - path_start);\n\n size_t path_query = path.find(\"?\");\n\n if (path_query != std::string::npos) {\n std::string query = path.substr(path_query+1, path.size() - path_query);\n\n parse_query_string(query);\n\n path.erase(path_query, query.size()+1);\n }\n}\n\nvoid Request::parse_query_string(std::string query) {\n query.erase(query.find_last_not_of(\" \\n\\r\\t\")+1);\n std::istringstream query_stream(query);\n std::string pair;\n while (std::getline(query_stream, pair, '&')) {\n std::string name, value;\n size_t value_position = pair.find(\"=\");\n\n name = pair.substr(0, value_position);\n if (value_position != std::string::npos)\n value = pair.substr(value_position+1, pair.size() - value_position-1);\n\n parameters[Utils::uri_decode(name)] = Utils::uri_decode(value);\n }\n}\n\nRequest::~Request() {\n}\n\n\n}\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\nusing namespace std;\n\n#include \"config.h\"\n\n#include \n#include \"common\/common_init.h\"\n\n#include \"common\/base64.h\"\n#include \"rgw_user.h\"\n#include \"rgw_access.h\"\n#include \"rgw_acl.h\"\n\n\n#define SECRET_KEY_LEN 40\n#define PUBLIC_ID_LEN 20\n\nvoid usage() \n{\n cerr << \"usage: rgw_admin <--user-gen | --user-modify | --read-policy | --list-buckets > [options...]\" << std::endl;\n cerr << \"options:\" << std::endl;\n cerr << \" --uid=\" << std::endl;\n cerr << \" --key=\" << std::endl;\n cerr << \" --email=\" << std::endl;\n cerr << \" --display-name=\" << std::endl;\n cerr << \" --bucket=\" << std::endl;\n cerr << \" --object=\" << std::endl;\n generic_usage();\n}\n\nint gen_rand_base64(char *dest, int size) \/* size should be the required string size + 1 *\/\n{\n unsigned char buf[size];\n char tmp_dest[size + 4]; \/* so that there's space for the extra '=' characters, and some *\/\n\n int ret = RAND_bytes(buf, sizeof(buf));\n if (!ret) {\n cerr << \"RAND_bytes failed, entropy problem?\" << std::endl;\n return -1;\n }\n\n ret = encode_base64((const char *)buf, ((size - 1) * 3 + 4 - 1) \/ 4, tmp_dest, sizeof(tmp_dest));\n if (ret < 0) {\n cerr << \"encode_base64 failed\" << std::endl;\n return -1;\n }\n memcpy(dest, tmp_dest, size);\n dest[size] = '\\0';\n\n return 0;\n}\n\nstatic const char alphanum_table[]=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nint gen_rand_alphanumeric(char *dest, int size) \/* size should be the required string size + 1 *\/\n{\n int ret = RAND_bytes((unsigned char *)dest, size);\n if (!ret) {\n cerr << \"RAND_bytes failed, entropy problem?\" << std::endl;\n return -1;\n }\n\n int i;\n for (i=0; iget_id(), owner_info) < 0) {\n cerr << \"owner info does not exist\" << std::endl;\n return -EINVAL;\n }\n ACLOwner& new_owner = dest.get_owner();\n new_owner.set_id(owner->get_id());\n new_owner.set_name(owner_info.display_name);\n\n RGWAccessControlList& src_acl = src.get_acl();\n RGWAccessControlList& acl = dest.get_acl();\n\n XMLObjIter iter = src_acl.find(\"Grant\");\n ACLGrant *src_grant = (ACLGrant *)iter.get_next();\n while (src_grant) {\n string id = src_grant->get_id();\n \n RGWUserInfo grant_user;\n if (rgw_get_user_info(id, grant_user) < 0) {\n cerr << \"grant user does not exist:\" << id << std::endl;\n } else {\n ACLGrant new_grant;\n ACLPermission& perm = src_grant->get_permission();\n new_grant.set_canon(id, grant_user.display_name, perm.get_permissions());\n cerr << \"new grant: \" << id << \":\" << grant_user.display_name << std::endl;\n acl.add_grant(&new_grant);\n }\n src_grant = (ACLGrant *)iter.get_next();\n }\n\n return 0; \n}\n#endif\n\nint main(int argc, char **argv) \n{\n DEFINE_CONF_VARS(usage);\n vector args;\n argv_to_vec(argc, (const char **)argv, args);\n env_to_vec(args);\n common_init(args, \"rgw\", true, true);\n\n const char *user_id = 0;\n const char *secret_key = 0;\n const char *user_email = 0;\n const char *display_name = 0;\n const char *bucket = 0;\n const char *object = 0;\n bool gen_user = false;\n bool mod_user = false;\n bool read_policy = false;\n bool list_buckets = false;\n int actions = 0 ;\n RGWUserInfo info;\n RGWAccess *store;\n\n if (g_conf.clock_tare) g_clock.tare();\n\n FOR_EACH_ARG(args) {\n if (CONF_ARG_EQ(\"user-gen\", 'g')) {\n gen_user = true;\n } else if (CONF_ARG_EQ(\"user-modify\", 'm')) {\n mod_user = true;\n } else if (CONF_ARG_EQ(\"read-policy\", 'p')) {\n read_policy = true;\n } else if (CONF_ARG_EQ(\"list-buckets\", 'l')) {\n list_buckets = true;\n } else if (CONF_ARG_EQ(\"uid\", 'i')) {\n CONF_SAFE_SET_ARG_VAL(&user_id, OPT_STR);\n } else if (CONF_ARG_EQ(\"key\", 'k')) {\n CONF_SAFE_SET_ARG_VAL(&secret_key, OPT_STR);\n } else if (CONF_ARG_EQ(\"email\", 'e')) {\n CONF_SAFE_SET_ARG_VAL(&user_email, OPT_STR);\n } else if (CONF_ARG_EQ(\"display-name\", 'n')) {\n CONF_SAFE_SET_ARG_VAL(&display_name, OPT_STR);\n } else if (CONF_ARG_EQ(\"bucket\", 'b')) {\n CONF_SAFE_SET_ARG_VAL(&bucket, OPT_STR);\n } else if (CONF_ARG_EQ(\"object\", 'o')) {\n CONF_SAFE_SET_ARG_VAL(&object, OPT_STR);\n } else {\n cerr << \"unrecognized arg \" << args[i] << std::endl;\n ARGS_USAGE();\n }\n }\n\n store = RGWAccess::init_storage_provider(\"rados\", argc, argv);\n if (!store) {\n cerr << \"couldn't init storage provider\" << std::endl;\n }\n\n\n if (mod_user) {\n actions++;\n\n if (!user_id) {\n cerr << \"user_id was not specified, aborting\" << std::endl;\n return 0;\n }\n\n string user_id_str = user_id;\n\n if (rgw_get_user_info(user_id_str, info) < 0) {\n cerr << \"error reading user info, aborting\" << std::endl;\n exit(1);\n }\n }\n\n if (gen_user) {\n actions++;\n char secret_key_buf[SECRET_KEY_LEN + 1];\n char public_id_buf[PUBLIC_ID_LEN + 1];\n int ret;\n\n if (!display_name) {\n cerr << \"display name was not specified, aborting\" << std::endl;\n return 0;\n }\n\n if (!secret_key) {\n ret = gen_rand_base64(secret_key_buf, sizeof(secret_key_buf));\n if (ret < 0) {\n cerr << \"aborting\" << std::endl;\n exit(1);\n }\n secret_key = secret_key_buf;\n }\n if (!user_id) {\n ret = gen_rand_alphanumeric(public_id_buf, sizeof(public_id_buf));\n if (ret < 0) {\n cerr << \"aborting\" << std::endl;\n exit(1);\n }\n user_id = public_id_buf;\n }\n }\n\n if (gen_user || mod_user) {\n if (user_id)\n info.user_id = user_id;\n if (secret_key)\n info.secret_key = secret_key;\n if (display_name)\n info.display_name = display_name;\n if (user_email)\n info.user_email = user_email;\n\n int err;\n if ((err = rgw_store_user_info(info)) < 0) {\n cerr << \"error storing user info\" << strerror(-err) << std::endl;\n } else {\n cout << \"User ID: \" << info.user_id << std::endl;\n cout << \"Secret Key: \" << info.secret_key << std::endl;\n cout << \"Display Name: \" << info.display_name << std::endl;\n }\n }\n\n if (read_policy) {\n actions++;\n bufferlist bl;\n if (!bucket)\n bucket = \"\";\n if (!object)\n object = \"\";\n string bucket_str(bucket);\n string object_str(object);\n int ret = store->get_attr(bucket_str, object_str,\n RGW_ATTR_ACL, bl);\n\n RGWAccessControlPolicy policy;\n if (ret >= 0) {\n bufferlist::iterator iter = bl.begin();\n policy.decode(iter);\n policy.to_xml(cout);\n cout << std::endl;\n }\n }\n\n if (list_buckets) {\n actions++;\n string id;\n RGWAccessHandle handle;\n\n if (user_id) {\n RGWUserBuckets buckets;\n if (rgw_get_user_buckets(user_id, buckets) < 0) {\n cout << \"could not get buckets for uid \" << user_id << std::endl;\n } else {\n cout << \"listing buckets for uid \" << user_id << std::endl;\n map& m = buckets.get_buckets();\n map::iterator iter;\n\n for (iter = m.begin(); iter != m.end(); ++iter) {\n RGWObjEnt obj = iter->second;\n cout << obj.name << std::endl;\n }\n }\n } else {\n if (store->list_buckets_init(id, &handle) < 0) {\n cout << \"list-buckets: no entries found\" << std::endl;\n } else {\n RGWObjEnt obj;\n cout << \"listing all buckets\" << std::endl;\n while (store->list_buckets_next(id, obj, &handle) >= 0) {\n cout << obj.name << std::endl;\n }\n }\n }\n }\n\n if (!actions)\n ARGS_USAGE();\n\n return 0;\n}\n\n\nrgw: set auid if specified at creation#include \n\n#include \n#include \n\nusing namespace std;\n\n#include \"config.h\"\n\n#include \n#include \"common\/common_init.h\"\n\n#include \"common\/base64.h\"\n#include \"rgw_user.h\"\n#include \"rgw_access.h\"\n#include \"rgw_acl.h\"\n\n\n#define SECRET_KEY_LEN 40\n#define PUBLIC_ID_LEN 20\n\nvoid usage() \n{\n cerr << \"usage: rgw_admin <--user-gen | --user-modify | --read-policy | --list-buckets > [options...]\" << std::endl;\n cerr << \"options:\" << std::endl;\n cerr << \" --uid= (S3 uid)\" << std::endl;\n cerr << \" --auth_uid= (librados uid)\" << std::endl;\n cerr << \" --key=\" << std::endl;\n cerr << \" --email=\" << std::endl;\n cerr << \" --display-name=\" << std::endl;\n cerr << \" --bucket=\" << std::endl;\n cerr << \" --object=\" << std::endl;\n generic_usage();\n}\n\nint gen_rand_base64(char *dest, int size) \/* size should be the required string size + 1 *\/\n{\n unsigned char buf[size];\n char tmp_dest[size + 4]; \/* so that there's space for the extra '=' characters, and some *\/\n\n int ret = RAND_bytes(buf, sizeof(buf));\n if (!ret) {\n cerr << \"RAND_bytes failed, entropy problem?\" << std::endl;\n return -1;\n }\n\n ret = encode_base64((const char *)buf, ((size - 1) * 3 + 4 - 1) \/ 4, tmp_dest, sizeof(tmp_dest));\n if (ret < 0) {\n cerr << \"encode_base64 failed\" << std::endl;\n return -1;\n }\n memcpy(dest, tmp_dest, size);\n dest[size] = '\\0';\n\n return 0;\n}\n\nstatic const char alphanum_table[]=\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\";\n\nint gen_rand_alphanumeric(char *dest, int size) \/* size should be the required string size + 1 *\/\n{\n int ret = RAND_bytes((unsigned char *)dest, size);\n if (!ret) {\n cerr << \"RAND_bytes failed, entropy problem?\" << std::endl;\n return -1;\n }\n\n int i;\n for (i=0; iget_id(), owner_info) < 0) {\n cerr << \"owner info does not exist\" << std::endl;\n return -EINVAL;\n }\n ACLOwner& new_owner = dest.get_owner();\n new_owner.set_id(owner->get_id());\n new_owner.set_name(owner_info.display_name);\n\n RGWAccessControlList& src_acl = src.get_acl();\n RGWAccessControlList& acl = dest.get_acl();\n\n XMLObjIter iter = src_acl.find(\"Grant\");\n ACLGrant *src_grant = (ACLGrant *)iter.get_next();\n while (src_grant) {\n string id = src_grant->get_id();\n \n RGWUserInfo grant_user;\n if (rgw_get_user_info(id, grant_user) < 0) {\n cerr << \"grant user does not exist:\" << id << std::endl;\n } else {\n ACLGrant new_grant;\n ACLPermission& perm = src_grant->get_permission();\n new_grant.set_canon(id, grant_user.display_name, perm.get_permissions());\n cerr << \"new grant: \" << id << \":\" << grant_user.display_name << std::endl;\n acl.add_grant(&new_grant);\n }\n src_grant = (ACLGrant *)iter.get_next();\n }\n\n return 0; \n}\n#endif\n\nint main(int argc, char **argv) \n{\n DEFINE_CONF_VARS(usage);\n vector args;\n argv_to_vec(argc, (const char **)argv, args);\n env_to_vec(args);\n common_init(args, \"rgw\", true, true);\n\n const char *user_id = 0;\n const char *secret_key = 0;\n const char *user_email = 0;\n const char *display_name = 0;\n const char *bucket = 0;\n const char *object = 0;\n bool gen_user = false;\n bool mod_user = false;\n bool read_policy = false;\n bool list_buckets = false;\n int actions = 0 ;\n __u64 auid = 0;\n RGWUserInfo info;\n RGWAccess *store;\n\n if (g_conf.clock_tare) g_clock.tare();\n\n FOR_EACH_ARG(args) {\n if (CONF_ARG_EQ(\"user-gen\", 'g')) {\n gen_user = true;\n } else if (CONF_ARG_EQ(\"user-modify\", 'm')) {\n mod_user = true;\n } else if (CONF_ARG_EQ(\"read-policy\", 'p')) {\n read_policy = true;\n } else if (CONF_ARG_EQ(\"list-buckets\", 'l')) {\n list_buckets = true;\n } else if (CONF_ARG_EQ(\"uid\", 'i')) {\n CONF_SAFE_SET_ARG_VAL(&user_id, OPT_STR);\n } else if (CONF_ARG_EQ(\"key\", 'k')) {\n CONF_SAFE_SET_ARG_VAL(&secret_key, OPT_STR);\n } else if (CONF_ARG_EQ(\"email\", 'e')) {\n CONF_SAFE_SET_ARG_VAL(&user_email, OPT_STR);\n } else if (CONF_ARG_EQ(\"display-name\", 'n')) {\n CONF_SAFE_SET_ARG_VAL(&display_name, OPT_STR);\n } else if (CONF_ARG_EQ(\"bucket\", 'b')) {\n CONF_SAFE_SET_ARG_VAL(&bucket, OPT_STR);\n } else if (CONF_ARG_EQ(\"object\", 'o')) {\n CONF_SAFE_SET_ARG_VAL(&object, OPT_STR);\n } else if (CONF_ARG_EQ(\"auth_uid\", 'a')) {\n CONF_SAFE_SET_ARG_VAL(&auid, OPT_LONGLONG);\n } else {\n cerr << \"unrecognized arg \" << args[i] << std::endl;\n ARGS_USAGE();\n }\n }\n\n store = RGWAccess::init_storage_provider(\"rados\", argc, argv);\n if (!store) {\n cerr << \"couldn't init storage provider\" << std::endl;\n }\n\n\n if (mod_user) {\n actions++;\n\n if (!user_id) {\n cerr << \"user_id was not specified, aborting\" << std::endl;\n return 0;\n }\n\n string user_id_str = user_id;\n\n if (rgw_get_user_info(user_id_str, info) < 0) {\n cerr << \"error reading user info, aborting\" << std::endl;\n exit(1);\n }\n }\n\n if (gen_user) {\n actions++;\n char secret_key_buf[SECRET_KEY_LEN + 1];\n char public_id_buf[PUBLIC_ID_LEN + 1];\n int ret;\n\n if (!display_name) {\n cerr << \"display name was not specified, aborting\" << std::endl;\n return 0;\n }\n\n if (!secret_key) {\n ret = gen_rand_base64(secret_key_buf, sizeof(secret_key_buf));\n if (ret < 0) {\n cerr << \"aborting\" << std::endl;\n exit(1);\n }\n secret_key = secret_key_buf;\n }\n if (!user_id) {\n ret = gen_rand_alphanumeric(public_id_buf, sizeof(public_id_buf));\n if (ret < 0) {\n cerr << \"aborting\" << std::endl;\n exit(1);\n }\n user_id = public_id_buf;\n }\n }\n\n if (gen_user || mod_user) {\n if (user_id)\n info.user_id = user_id;\n if (secret_key)\n info.secret_key = secret_key;\n if (display_name)\n info.display_name = display_name;\n if (user_email)\n info.user_email = user_email;\n if (auid)\n info.auid = auid;\n\n int err;\n if ((err = rgw_store_user_info(info)) < 0) {\n cerr << \"error storing user info\" << strerror(-err) << std::endl;\n } else {\n cout << \"User ID: \" << info.user_id << std::endl;\n cout << \"Secret Key: \" << info.secret_key << std::endl;\n cout << \"Display Name: \" << info.display_name << std::endl;\n }\n }\n\n if (read_policy) {\n actions++;\n bufferlist bl;\n if (!bucket)\n bucket = \"\";\n if (!object)\n object = \"\";\n string bucket_str(bucket);\n string object_str(object);\n int ret = store->get_attr(bucket_str, object_str,\n RGW_ATTR_ACL, bl);\n\n RGWAccessControlPolicy policy;\n if (ret >= 0) {\n bufferlist::iterator iter = bl.begin();\n policy.decode(iter);\n policy.to_xml(cout);\n cout << std::endl;\n }\n }\n\n if (list_buckets) {\n actions++;\n string id;\n RGWAccessHandle handle;\n\n if (user_id) {\n RGWUserBuckets buckets;\n if (rgw_get_user_buckets(user_id, buckets) < 0) {\n cout << \"could not get buckets for uid \" << user_id << std::endl;\n } else {\n cout << \"listing buckets for uid \" << user_id << std::endl;\n map& m = buckets.get_buckets();\n map::iterator iter;\n\n for (iter = m.begin(); iter != m.end(); ++iter) {\n RGWObjEnt obj = iter->second;\n cout << obj.name << std::endl;\n }\n }\n } else {\n if (store->list_buckets_init(id, &handle) < 0) {\n cout << \"list-buckets: no entries found\" << std::endl;\n } else {\n RGWObjEnt obj;\n cout << \"listing all buckets\" << std::endl;\n while (store->list_buckets_next(id, obj, &handle) >= 0) {\n cout << obj.name << std::endl;\n }\n }\n }\n }\n\n if (!actions)\n ARGS_USAGE();\n\n return 0;\n}\n\n\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2020 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \"mutation_reader.hh\"\n\nclass test_reader_lifecycle_policy\n : public reader_lifecycle_policy\n , public enable_shared_from_this {\npublic:\n class operations_gate {\n public:\n class operation {\n gate* _g = nullptr;\n\n private:\n void leave() {\n if (_g) {\n _g->leave();\n }\n }\n\n public:\n operation() = default;\n explicit operation(gate& g) : _g(&g) { _g->enter(); }\n operation(const operation&) = delete;\n operation(operation&& o) : _g(std::exchange(o._g, nullptr)) { }\n ~operation() { leave(); }\n operation& operator=(const operation&) = delete;\n operation& operator=(operation&& o) {\n leave();\n _g = std::exchange(o._g, nullptr);\n return *this;\n }\n };\n\n private:\n std::vector _gates;\n\n public:\n operations_gate()\n : _gates(smp::count) {\n }\n\n operation enter() {\n return operation(_gates[this_shard_id()]);\n }\n\n future<> close() {\n return parallel_for_each(boost::irange(smp::count), [this] (shard_id shard) {\n return smp::submit_to(shard, [this, shard] {\n return _gates[shard].close();\n });\n });\n }\n };\n\nprivate:\n using factory_function = std::function;\n\n struct reader_context {\n std::unique_ptr semaphore;\n operations_gate::operation op;\n std::optional permit;\n std::optional> wait_future;\n std::optional range;\n std::optional slice;\n\n reader_context() = default;\n reader_context(dht::partition_range range, query::partition_slice slice) : range(std::move(range)), slice(std::move(slice)) {\n }\n };\n\n factory_function _factory_function;\n operations_gate& _operation_gate;\n std::vector>> _contexts;\n std::vector> _destroy_futures;\n bool _evict_paused_readers = false;\n\npublic:\n explicit test_reader_lifecycle_policy(factory_function f, operations_gate& g, bool evict_paused_readers = false)\n : _factory_function(std::move(f))\n , _operation_gate(g)\n , _contexts(smp::count)\n , _evict_paused_readers(evict_paused_readers) {\n }\n virtual flat_mutation_reader create_reader(\n schema_ptr schema,\n const dht::partition_range& range,\n const query::partition_slice& slice,\n const io_priority_class& pc,\n tracing::trace_state_ptr trace_state,\n mutation_reader::forwarding fwd_mr) override {\n const auto shard = this_shard_id();\n if (_contexts[shard]) {\n _contexts[shard]->range.emplace(range);\n _contexts[shard]->slice.emplace(slice);\n } else {\n _contexts[shard] = make_foreign(std::make_unique(range, slice));\n }\n _contexts[shard]->op = _operation_gate.enter();\n return _factory_function(std::move(schema), *_contexts[shard]->range, *_contexts[shard]->slice, pc, std::move(trace_state), fwd_mr);\n }\n virtual void destroy_reader(shard_id shard, future reader) noexcept override {\n \/\/ Move to the background, waited via _operation_gate\n (void)reader.then([shard, this] (stopped_reader&& reader) {\n return smp::submit_to(shard, [handle = std::move(reader.handle), ctx = std::move(_contexts[shard])] () mutable {\n ctx->semaphore->unregister_inactive_read(std::move(*handle));\n ctx->semaphore->broken(std::make_exception_ptr(broken_semaphore{}));\n if (ctx->wait_future) {\n return ctx->wait_future->then_wrapped([ctx = std::move(ctx)] (future f) mutable {\n f.ignore_ready_future();\n ctx->permit.reset(); \/\/ make sure it's destroyed before the semaphore\n });\n }\n return make_ready_future<>();\n });\n }).finally([zis = shared_from_this()] {});\n }\n virtual reader_concurrency_semaphore& semaphore() override {\n const auto shard = this_shard_id();\n if (!_contexts[shard]) {\n _contexts[shard] = make_foreign(std::make_unique());\n } else if (_contexts[shard]->semaphore) {\n return *_contexts[shard]->semaphore;\n }\n if (_evict_paused_readers) {\n _contexts[shard]->semaphore = std::make_unique(0, std::numeric_limits::max(),\n format(\"reader_concurrency_semaphore @shard_id={}\", shard));\n _contexts[shard]->permit = _contexts[shard]->semaphore->make_permit();\n \/\/ Add a waiter, so that all registered inactive reads are\n \/\/ immediately evicted.\n \/\/ We don't care about the returned future.\n _contexts[shard]->wait_future = _contexts[shard]->permit->wait_admission(1, db::no_timeout);\n } else {\n _contexts[shard]->semaphore = std::make_unique(reader_concurrency_semaphore::no_limits{});\n }\n return *_contexts[shard]->semaphore;\n }\n};\n\ntest\/lib\/reader_lifecycle_policy: don't destroy reader context eagerly\/*\n * Copyright (C) 2020 ScyllaDB\n *\/\n\n\/*\n * This file is part of Scylla.\n *\n * Scylla is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Scylla is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with Scylla. If not, see .\n *\/\n\n#pragma once\n\n#include \"mutation_reader.hh\"\n\nclass test_reader_lifecycle_policy\n : public reader_lifecycle_policy\n , public enable_shared_from_this {\npublic:\n class operations_gate {\n public:\n class operation {\n gate* _g = nullptr;\n\n private:\n void leave() {\n if (_g) {\n _g->leave();\n }\n }\n\n public:\n operation() = default;\n explicit operation(gate& g) : _g(&g) { _g->enter(); }\n operation(const operation&) = delete;\n operation(operation&& o) : _g(std::exchange(o._g, nullptr)) { }\n ~operation() { leave(); }\n operation& operator=(const operation&) = delete;\n operation& operator=(operation&& o) {\n leave();\n _g = std::exchange(o._g, nullptr);\n return *this;\n }\n };\n\n private:\n std::vector _gates;\n\n public:\n operations_gate()\n : _gates(smp::count) {\n }\n\n operation enter() {\n return operation(_gates[this_shard_id()]);\n }\n\n future<> close() {\n return parallel_for_each(boost::irange(smp::count), [this] (shard_id shard) {\n return smp::submit_to(shard, [this, shard] {\n return _gates[shard].close();\n });\n });\n }\n };\n\nprivate:\n using factory_function = std::function;\n\n struct reader_context {\n std::unique_ptr semaphore;\n operations_gate::operation op;\n std::optional permit;\n std::optional> wait_future;\n std::optional range;\n std::optional slice;\n\n reader_context() = default;\n reader_context(dht::partition_range range, query::partition_slice slice) : range(std::move(range)), slice(std::move(slice)) {\n }\n };\n\n factory_function _factory_function;\n operations_gate& _operation_gate;\n std::vector>> _contexts;\n std::vector> _destroy_futures;\n bool _evict_paused_readers = false;\n\npublic:\n explicit test_reader_lifecycle_policy(factory_function f, operations_gate& g, bool evict_paused_readers = false)\n : _factory_function(std::move(f))\n , _operation_gate(g)\n , _contexts(smp::count)\n , _evict_paused_readers(evict_paused_readers) {\n }\n virtual flat_mutation_reader create_reader(\n schema_ptr schema,\n const dht::partition_range& range,\n const query::partition_slice& slice,\n const io_priority_class& pc,\n tracing::trace_state_ptr trace_state,\n mutation_reader::forwarding fwd_mr) override {\n const auto shard = this_shard_id();\n if (_contexts[shard]) {\n _contexts[shard]->range.emplace(range);\n _contexts[shard]->slice.emplace(slice);\n } else {\n _contexts[shard] = make_foreign(std::make_unique(range, slice));\n }\n _contexts[shard]->op = _operation_gate.enter();\n return _factory_function(std::move(schema), *_contexts[shard]->range, *_contexts[shard]->slice, pc, std::move(trace_state), fwd_mr);\n }\n virtual void destroy_reader(shard_id shard, future reader) noexcept override {\n \/\/ Move to the background, waited via _operation_gate\n (void)reader.then([shard, this] (stopped_reader&& reader) {\n return smp::submit_to(shard, [handle = std::move(reader.handle), ctx = &*_contexts[shard]] () mutable {\n ctx->semaphore->unregister_inactive_read(std::move(*handle));\n ctx->semaphore->broken(std::make_exception_ptr(broken_semaphore{}));\n if (ctx->wait_future) {\n return ctx->wait_future->then_wrapped([ctx = std::move(ctx)] (future f) mutable {\n f.ignore_ready_future();\n ctx->permit.reset(); \/\/ make sure it's destroyed before the semaphore\n });\n }\n return make_ready_future<>();\n });\n }).finally([zis = shared_from_this()] {});\n }\n virtual reader_concurrency_semaphore& semaphore() override {\n const auto shard = this_shard_id();\n if (!_contexts[shard]) {\n _contexts[shard] = make_foreign(std::make_unique());\n } else if (_contexts[shard]->semaphore) {\n return *_contexts[shard]->semaphore;\n }\n if (_evict_paused_readers) {\n _contexts[shard]->semaphore = std::make_unique(0, std::numeric_limits::max(),\n format(\"reader_concurrency_semaphore @shard_id={}\", shard));\n _contexts[shard]->permit = _contexts[shard]->semaphore->make_permit();\n \/\/ Add a waiter, so that all registered inactive reads are\n \/\/ immediately evicted.\n \/\/ We don't care about the returned future.\n _contexts[shard]->wait_future = _contexts[shard]->permit->wait_admission(1, db::no_timeout);\n } else {\n _contexts[shard]->semaphore = std::make_unique(reader_concurrency_semaphore::no_limits{});\n }\n return *_contexts[shard]->semaphore;\n }\n};\n\n<|endoftext|>"} {"text":"#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n\nusing namespace ydsh;\n\nstatic std::vector tokenize(const char *str) {\n std::vector tokens;\n std::string tokenBuf;\n\n for(unsigned int i = 0; str[i] != '\\0'; i++) {\n char ch = str[i];\n switch(ch) {\n case '(':\n case ')': {\n if(!tokenBuf.empty()) {\n tokens.push_back(std::move(tokenBuf));\n }\n\n tokenBuf += ch;\n tokens.push_back(std::move(tokenBuf));\n break;\n }\n case ' ':\n case '\\t': {\n if(!tokenBuf.empty()) {\n tokens.push_back(std::move(tokenBuf));\n }\n break;\n }\n default:\n tokenBuf += ch;\n break;\n }\n }\n if(!tokenBuf.empty()) {\n tokens.push_back(std::move(tokenBuf));\n }\n\n return tokens;\n}\n\nclass PrettyPrinter : public BaseVisitor {\nprivate:\n std::vector out;\n\npublic:\n PrettyPrinter() = default;\n ~PrettyPrinter() = default;\n\n std::vector operator()(RootNode &rootNode) {\n this->visitRootNode(rootNode);\n return std::move(this->out);\n }\n\n void append(const char *str) {\n this->out.push_back(str);\n }\n\n void append(const std::string &str) {\n this->out.push_back(str);\n }\n\n void open() {\n this->append(\"(\");\n }\n\n void close() {\n this->append(\")\");\n }\n\n void visitDefault(Node &) override {\n fatal(\"unsupported\\n\");\n }\n\n void visitNumberNode(NumberNode &node) override {\n this->append(std::to_string(node.getIntValue()));\n }\n\n void visitTypeOpNode(TypeOpNode &node) override {\n this->open();\n this->visit(*node.getExprNode());\n this->append(node.isCastOp() ? \"as\" : \"is\");\n this->append(dynamic_cast(node.getTargetTypeNode())->getTokenText()); \/\/FIXME:\n this->close();\n }\n\n void visitBinaryOpNode(BinaryOpNode &node) override {\n this->open();\n this->visit(*node.getLeftNode());\n this->append(TO_NAME(node.getOp()));\n this->visit(*node.getRightNode());\n this->close();\n }\n\n void visitIfNode(IfNode &node) override {\n this->open();\n this->visit(*node.getCondNode());\n this->append(\"?\");\n this->visit(*node.getThenNode());\n this->append(\":\");\n this->visit(*node.getElseNode());\n this->close();\n }\n\n void visitAssignNode(AssignNode &node) override {\n this->open();\n this->visit(*node.getLeftNode());\n this->append(\"=\");\n this->visit(*node.getRightNode());\n this->close();\n }\n\n void visitRootNode(RootNode &node) override {\n if(node.getNodes().size() != 1) {\n fatal(\"must be 1\\n\");\n }\n\n this->visit(*node.getNodes().front());\n }\n};\n\n\nclass PrecedenceTest : public ::testing::Test {\npublic:\n PrecedenceTest() = default;\n virtual ~PrecedenceTest() = default;\n\n virtual void SetUp() { }\n\n virtual void TearDown() { }\n\n virtual void equalsTokens(const std::vector &expected, const std::vector &actual) {\n SCOPED_TRACE(\"\");\n\n \/\/ check size\n unsigned int size = expected.size();\n ASSERT_EQ(size, actual.size());\n\n \/\/ check each\n for(unsigned int i = 0; i < size; i++) {\n ASSERT_EQ(expected[i], actual[i]);\n }\n }\n\n virtual void equals(const char *expected, const char *input) {\n SCOPED_TRACE(\"\");\n\n ASSERT_TRUE(expected != nullptr);\n ASSERT_TRUE(input != nullptr);\n\n \/\/ parse\n Lexer lexer(\"(string)\", input);\n Parser parser(lexer);\n auto rootNode = parser();\n ASSERT_FALSE(parser.hasError());\n\n std::vector actualTokens = PrettyPrinter()(*rootNode);\n std::vector expectedTokens = tokenize(expected);\n\n this->equalsTokens(expectedTokens, actualTokens);\n }\n};\n\nTEST_F(PrecedenceTest, base1) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"1\", \"1\"));\n}\n\nTEST_F(PrecedenceTest, base2) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\" 1 \", \"(1)\"));\n}\n\nTEST_F(PrecedenceTest, base3) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(1 + 2)\", \"1+2\"));\n}\n\nTEST_F(PrecedenceTest, case1) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 as Int) is Int)\", \"1 as Int is Int\"));\n}\n\nTEST_F(PrecedenceTest, case2) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 is Int) as Int)\", \"1 is Int as Int\"));\n}\n\nTEST_F(PrecedenceTest, case3) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(12 \/ (23 as Int))\", \"12 \/ 23 as Int\"));\n}\n\nTEST_F(PrecedenceTest, case4) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(((1 \/ 2) * 3) % 4)\", \"1 \/ 2 * 3 % 4\"));\n}\n\nTEST_F(PrecedenceTest, case5) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 + (2 * 3)) - 4)\", \"1 + 2 * 3 - 4\"));\n}\n\nTEST_F(PrecedenceTest, case6) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 and 2) or (3 xor (4 + 3)))\", \"1 and 2 or 3 xor 4 + 3\"));\n}\n\nTEST_F(PrecedenceTest, case7) {\n ASSERT_NO_FATAL_FAILURE(\n this->equals(\"((((((((1 < 2) > 3) == 4) >= 5) !~ 6) <= 7) != 8) =~ 9)\",\n \"1 < 2 > 3 == 4 >= 5 !~ 6 <= 7 != 8 =~ 9\"));\n}\n\nTEST_F(PrecedenceTest, case8) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(1 = (((2 == 3) && (4 + 5)) || 6))\", \"1 = 2 == 3 && 4 + 5 || 6\"));\n}\n\nTEST_F(PrecedenceTest, case9) {\n ASSERT_NO_FATAL_FAILURE(\n this->equals(\"((1 == 2) ? ((3 > 4) ? (5 + 6) : (7 xor 8)) : (9 && 10))\",\n \"1 == 2 ? 3 > 4 ? 5 + 6 : 7 xor 8 : 9 && 10\"));\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nupdate operator precedence test case, close #283#include \"gtest\/gtest.h\"\n\n#include \n#include \n#include \n\nusing namespace ydsh;\n\nstatic std::vector tokenize(const char *str) {\n std::vector tokens;\n std::string tokenBuf;\n\n for(unsigned int i = 0; str[i] != '\\0'; i++) {\n char ch = str[i];\n switch(ch) {\n case '(':\n case ')': {\n if(!tokenBuf.empty()) {\n tokens.push_back(std::move(tokenBuf));\n }\n\n tokenBuf += ch;\n tokens.push_back(std::move(tokenBuf));\n break;\n }\n case ' ':\n case '\\t': {\n if(!tokenBuf.empty()) {\n tokens.push_back(std::move(tokenBuf));\n }\n break;\n }\n default:\n tokenBuf += ch;\n break;\n }\n }\n if(!tokenBuf.empty()) {\n tokens.push_back(std::move(tokenBuf));\n }\n\n return tokens;\n}\n\nclass PrettyPrinter : public BaseVisitor {\nprivate:\n std::vector out;\n\npublic:\n PrettyPrinter() = default;\n ~PrettyPrinter() = default;\n\n std::vector operator()(RootNode &rootNode) {\n this->visitRootNode(rootNode);\n return std::move(this->out);\n }\n\n void append(const char *str) {\n this->out.push_back(str);\n }\n\n void append(const std::string &str) {\n this->out.push_back(str);\n }\n\n void open() {\n this->append(\"(\");\n }\n\n void close() {\n this->append(\")\");\n }\n\n void visitDefault(Node &) override {\n fatal(\"unsupported\\n\");\n }\n\n void visitNumberNode(NumberNode &node) override {\n this->append(std::to_string(node.getIntValue()));\n }\n\n void visitTypeOpNode(TypeOpNode &node) override {\n this->open();\n this->visit(*node.getExprNode());\n this->append(node.isCastOp() ? \"as\" : \"is\");\n this->append(dynamic_cast(node.getTargetTypeNode())->getTokenText()); \/\/FIXME:\n this->close();\n }\n\n void visitBinaryOpNode(BinaryOpNode &node) override {\n this->open();\n this->visit(*node.getLeftNode());\n this->append(TO_NAME(node.getOp()));\n this->visit(*node.getRightNode());\n this->close();\n }\n\n void visitIfNode(IfNode &node) override {\n this->open();\n this->visit(*node.getCondNode());\n this->append(\"?\");\n this->visit(*node.getThenNode());\n this->append(\":\");\n this->visit(*node.getElseNode());\n this->close();\n }\n\n void visitAssignNode(AssignNode &node) override {\n this->open();\n this->visit(*node.getLeftNode());\n this->append(\"=\");\n this->visit(*node.getRightNode());\n this->close();\n }\n\n void visitJumpNode(JumpNode &node) override {\n this->open();\n assert(node.getOpKind() == JumpNode::THROW);\n this->append(\"throw\");\n this->visit(*node.getExprNode());\n this->close();\n }\n\n void visitWithNode(WithNode &node) override {\n this->open();\n this->visit(*node.getExprNode());\n this->append(\"with\");\n this->visit(*node.getRedirNodes().back());\n this->close();\n }\n\n void visitRedirNode(RedirNode &node) override {\n this->append(TO_NAME(node.getRedirectOP()));\n this->visit(*node.getTargetNode());\n }\n\n void visitCmdArgNode(CmdArgNode &node) override {\n this->visit(*node.getSegmentNodes().back());\n }\n\n void visitStringNode(StringNode &node) override {\n this->append(node.getValue());\n }\n\n void visitPipelineNode(PipelineNode &node) override {\n this->open();\n for(unsigned int i = 0; i < node.getNodes().size(); i++) {\n if(i > 0) {\n this->append(\"|\");\n }\n this->visit(*node.getNodes()[i]);\n }\n this->close();\n }\n\n void visitRootNode(RootNode &node) override {\n if(node.getNodes().size() != 1) {\n fatal(\"must be 1\\n\");\n }\n\n this->visit(*node.getNodes().front());\n }\n};\n\n\nclass PrecedenceTest : public ::testing::Test {\npublic:\n PrecedenceTest() = default;\n virtual ~PrecedenceTest() = default;\n\n virtual void SetUp() { }\n\n virtual void TearDown() { }\n\n virtual void equalsTokens(const std::vector &expected, const std::vector &actual) {\n SCOPED_TRACE(\"\");\n\n \/\/ check size\n unsigned int size = expected.size();\n ASSERT_EQ(size, actual.size());\n\n \/\/ check each\n for(unsigned int i = 0; i < size; i++) {\n ASSERT_EQ(expected[i], actual[i]);\n }\n }\n\n virtual void equals(const char *expected, const char *input) {\n SCOPED_TRACE(\"\");\n\n ASSERT_TRUE(expected != nullptr);\n ASSERT_TRUE(input != nullptr);\n\n \/\/ parse\n Lexer lexer(\"(string)\", input);\n Parser parser(lexer);\n auto rootNode = parser();\n ASSERT_FALSE(parser.hasError());\n\n std::vector actualTokens = PrettyPrinter()(*rootNode);\n std::vector expectedTokens = tokenize(expected);\n\n this->equalsTokens(expectedTokens, actualTokens);\n }\n};\n\nTEST_F(PrecedenceTest, base1) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"1\", \"1\"));\n}\n\nTEST_F(PrecedenceTest, base2) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\" 1 \", \"(1)\"));\n}\n\nTEST_F(PrecedenceTest, base3) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(1 + 2)\", \"1+2\"));\n}\n\nTEST_F(PrecedenceTest, case1) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 as Int) is Int)\", \"1 as Int is Int\"));\n}\n\nTEST_F(PrecedenceTest, case2) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 is Int) as Int)\", \"1 is Int as Int\"));\n}\n\nTEST_F(PrecedenceTest, case3) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(12 \/ (23 as Int))\", \"12 \/ 23 as Int\"));\n}\n\nTEST_F(PrecedenceTest, case4) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(((1 \/ 2) * 3) % 4)\", \"1 \/ 2 * 3 % 4\"));\n}\n\nTEST_F(PrecedenceTest, case5) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 + (2 * 3)) - 4)\", \"1 + 2 * 3 - 4\"));\n}\n\nTEST_F(PrecedenceTest, case6) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"((1 and 2) or (3 xor (4 + 3)))\", \"1 and 2 or 3 xor 4 + 3\"));\n}\n\nTEST_F(PrecedenceTest, case7) {\n ASSERT_NO_FATAL_FAILURE(\n this->equals(\"((((((((1 < 2) > 3) == 4) >= 5) !~ 6) <= 7) != 8) =~ 9)\",\n \"1 < 2 > 3 == 4 >= 5 !~ 6 <= 7 != 8 =~ 9\"));\n}\n\nTEST_F(PrecedenceTest, case8) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(1 = (((2 == 3) && (4 + 5)) || 6))\", \"1 = 2 == 3 && 4 + 5 || 6\"));\n}\n\nTEST_F(PrecedenceTest, case9) {\n ASSERT_NO_FATAL_FAILURE(\n this->equals(\"((1 == 2) ? ((3 > 4) ? (5 + 6) : (7 xor 8)) : (9 && 10))\",\n \"1 == 2 ? 3 > 4 ? 5 + 6 : 7 xor 8 : 9 && 10\"));\n}\n\nTEST_F(PrecedenceTest, case10) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(55 < ((65 or 75) ?? 78))\", \"55 < 65 or 75 ?? 78\"));\n}\n\nTEST_F(PrecedenceTest, case11) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(((throw 45) + 45) && 54)\", \"throw 45 + 45 && 54\"));\n}\n\nTEST_F(PrecedenceTest, case12) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(34 || ((45 | (56 and 67)) && 78))\", \"34 || 45 | 56 and 67 && 78\"));\n}\n\nTEST_F(PrecedenceTest, case13) {\n ASSERT_NO_FATAL_FAILURE(this->equals(\"(45 | ((56 as Int) with 2> 67))\", \"45 | 56 as Int with 2> 67\"));\n}\n\nint main(int argc, char **argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \nnamespace tamer {\n\nvolatile sig_atomic_t driver::sig_any_active;\nint driver::sig_pipe[2] = { -1, -1 };\n\nnamespace {\n\nvolatile sig_atomic_t sig_active[NSIG];\nvolatile int sig_installing = -1;\nevent<> sig_handlers[NSIG];\n\nclass sigcancel_rendezvous : public rendezvous<> { public:\n\n sigcancel_rendezvous() {\n }\n\n inline void add(tamerpriv::simple_event *e) throw () {\n\t_nwaiting++;\n\te->initialize(this, sig_installing);\n }\n \n void complete(uintptr_t rid) {\n\tif ((int) rid != sig_installing) {\n\t struct sigaction sa;\n\t sa.sa_handler = SIG_DFL;\n\t sigemptyset(&sa.sa_mask);\n\t sa.sa_flags = SA_RESETHAND;\n\t sigaction(rid, &sa, 0);\n\t}\n\trendezvous<>::complete(rid);\n }\n \n};\n\nsigcancel_rendezvous sigcancelr;\n\n}\n\n\nextern \"C\" {\nstatic void tame_signal_handler(int signal) {\n int save_errno = errno;\n \n driver::sig_any_active = sig_active[signal] = 1;\n \n \/\/ ensure select wakes up\n write(driver::sig_pipe[1], \"\", 1);\n\n \/\/ block signal until we trigger the event, giving the unblocked\n \/\/ rendezvous a chance to maybe install a different handler\n sigset_t sigset;\n sigemptyset(&sigset);\n sigaddset(&sigset, signal);\n sigprocmask(SIG_BLOCK, &sigset, NULL);\n\n errno = save_errno;\n}\n}\n\n\nvoid driver::at_signal(int signal, const event<> &trigger)\n{\n assert(signal >= 0 && signal < NSIG);\n\n if (sig_pipe[0] < 0) {\n\tpipe(sig_pipe);\n\tfcntl(sig_pipe[0], F_SETFL, O_NONBLOCK);\n\tfcntl(sig_pipe[0], F_SETFD, FD_CLOEXEC);\n\tfcntl(sig_pipe[1], F_SETFD, FD_CLOEXEC);\n }\n\n if (!trigger)\t\t\/\/ special case forces creation of signal pipe\n\treturn;\n\n if (sig_handlers[signal])\n\tsig_handlers[signal] = distribute(sig_handlers[signal], trigger);\n else {\n\tsig_installing = signal;\n \n\tsig_handlers[signal] = trigger;\n\tsig_handlers[signal].at_trigger(make_event(sigcancelr));\n\t\n\tstruct sigaction sa;\n\tsa.sa_handler = tame_signal_handler;\n\tsigemptyset(&sa.sa_mask);\n\tsa.sa_flags = SA_RESETHAND;\n\tsigaction(signal, &sa, 0);\n\t\n\tsig_installing = -1;\n }\n}\n\n\nvoid driver::dispatch_signals()\n{\n sig_any_active = 0;\n sigset_t sigs_unblock;\n sigemptyset(&sigs_unblock);\n\n \/\/ kill crap data written to pipe\n char crap[64];\n while (read(sig_pipe[0], crap, 64) > 0)\n\t\/* do nothing *\/;\n\n \/\/ check signals\n for (int sig = 0; sig < NSIG; sig++)\n\tif (sig_active[sig]) {\n\t sig_active[sig] = 0;\n\t sig_handlers[sig].trigger();\n\t sigaddset(&sigs_unblock, sig);\n\t}\n\n \/\/ run closures activated by signals (plus maybe some others)\n while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked)\n\tr->run();\n\n \/\/ now that the signal responders have potentially reinstalled signal\n \/\/ handlers, unblock the signals\n sigprocmask(SIG_UNBLOCK, &sigs_unblock, 0);\n}\n\n}\na bit of signal nonsense, should test#include \n#include \n#include \n#include \n#include \nnamespace tamer {\n\nvolatile sig_atomic_t driver::sig_any_active;\nint driver::sig_pipe[2] = { -1, -1 };\n\nnamespace {\n\nvolatile sig_atomic_t sig_active[NSIG];\nvolatile int sig_installing = -1;\nevent<> sig_handlers[NSIG];\n\nclass sigcancel_rendezvous : public rendezvous<> { public:\n\n sigcancel_rendezvous() {\n }\n\n inline void add(tamerpriv::simple_event *e) throw () {\n\t_nwaiting++;\n\te->initialize(this, sig_installing);\n }\n \n void complete(uintptr_t rid) {\n\tif ((int) rid != sig_installing) {\n\t struct sigaction sa;\n\t sa.sa_handler = SIG_DFL;\n\t sigemptyset(&sa.sa_mask);\n\t sa.sa_flags = SA_RESETHAND;\n\t sigaction(rid, &sa, 0);\n\t}\n\trendezvous<>::complete(rid);\n }\n \n};\n\nsigcancel_rendezvous sigcancelr;\n\n}\n\n\nextern \"C\" {\nstatic void tame_signal_handler(int signal) {\n int save_errno = errno;\n \n driver::sig_any_active = sig_active[signal] = 1;\n \n \/\/ ensure select wakes up\n write(driver::sig_pipe[1], \"\", 1);\n\n \/\/ block signal until we trigger the event, giving the unblocked\n \/\/ rendezvous a chance to maybe install a different handler\n sigset_t sigset;\n sigemptyset(&sigset);\n sigaddset(&sigset, signal);\n sigprocmask(SIG_BLOCK, &sigset, NULL);\n\n errno = save_errno;\n}\n}\n\n\nvoid driver::at_signal(int signal, const event<> &trigger)\n{\n assert(signal >= 0 && signal < NSIG);\n\n if (sig_pipe[0] < 0) {\n\tpipe(sig_pipe);\n\tfcntl(sig_pipe[0], F_SETFL, O_NONBLOCK);\n\tfcntl(sig_pipe[0], F_SETFD, FD_CLOEXEC);\n\tfcntl(sig_pipe[1], F_SETFD, FD_CLOEXEC);\n }\n\n if (!trigger)\t\t\/\/ special case forces creation of signal pipe\n\treturn;\n\n if (sig_handlers[signal])\n\tsig_handlers[signal] = distribute(sig_handlers[signal], trigger);\n else {\n\tint old_sig_installing = sig_installing;\n\tsig_installing = signal;\n \n\tsig_handlers[signal] = trigger;\n\tsig_handlers[signal].at_trigger(make_event(sigcancelr));\n\t\n\tstruct sigaction sa;\n\tsa.sa_handler = tame_signal_handler;\n\tsigemptyset(&sa.sa_mask);\n\tsa.sa_flags = SA_RESETHAND;\n\tsigaction(signal, &sa, 0);\n\t\n\tsig_installing = old_sig_installing;\n }\n}\n\n\nvoid driver::dispatch_signals()\n{\n sig_any_active = 0;\n sigset_t sigs_unblock;\n sigemptyset(&sigs_unblock);\n\n \/\/ kill crap data written to pipe\n char crap[64];\n while (read(sig_pipe[0], crap, 64) > 0)\n\t\/* do nothing *\/;\n\n \/\/ check signals\n for (int sig = 0; sig < NSIG; sig++)\n\tif (sig_active[sig]) {\n\t sig_active[sig] = 0;\n\t sig_installing = sig;\n\t sig_handlers[sig].trigger();\n\t sig_installing = -1;\n\t sigaddset(&sigs_unblock, sig);\n\t}\n\n \/\/ run closures activated by signals (plus maybe some others)\n while (tamerpriv::abstract_rendezvous *r = tamerpriv::abstract_rendezvous::unblocked)\n\tr->run();\n\n \/\/ now that the signal responders have potentially reinstalled signal\n \/\/ handlers, unblock the signals\n sigprocmask(SIG_UNBLOCK, &sigs_unblock, 0);\n}\n\n}\n<|endoftext|>"} {"text":"#ifndef UTIL_HH\n#define UTIL_HH\n\n#include \n#include \n#include \n\n\/** Common utility functions. *\/\nnamespace util {\n\n \/** The square of the value. *\/\n template \n T sqr(T a)\n {\n return a * a;\n }\n\n \/** Median of the values in a vector. \n * \\note For odd number (2n + 1) of values, the n'th value is returned.\n *\/\n template \n T\n median(std::vector v)\n {\n std::sort(v.begin(), v.end());\n return v[v.size() \/ 2];\n }\n\n \/** Absolute value. *\/\n template \n T\n abs(const T &value)\n {\n if (value < 0)\n return -value;\n return value;\n }\n\n \/** Maximum of two values. *\/\n template \n T\n max(const T &a, const T &b)\n {\n if (a < b)\n return b;\n return a;\n }\n\n inline float\n log10add(float a, float b)\n {\n const float LOG10TOe = M_LN10;\n const float LOGeTO10 = 1.0 \/ M_LN10;\n\n a = a * LOG10TOe;\n b = b * LOG10TOe;\n\n float delta = a - b;\n if (delta > 64.0) {\n b += 64;\n delta = -delta;\n }\n return (b + log1pf(exp(delta))) * LOGeTO10;\n }\n\n inline float\n logadd(float a, float b)\n {\n float delta = a - b;\n if (delta > 64.0) {\n b += 64;\n delta = -delta;\n }\n return b + log1pf(exp(delta));\n }\n\n static const float tiny_for_log = (float)1e-16;\n inline double safe_log(double x)\n {\n if (x < tiny_for_log)\n return logf(tiny_for_log);\n else\n return logf(x);\n }\n\n};\n\n#endif \/* UTIL_HH *\/\nadded modulo#ifndef UTIL_HH\n#define UTIL_HH\n\n#include \n#include \n#include \n\n\/** Common utility functions. *\/\nnamespace util {\n\n \/** The square of the value. *\/\n template \n T sqr(T a)\n {\n return a * a;\n }\n\n \/** Median of the values in a vector. \n * \\note For odd number (2n + 1) of values, the n'th value is returned.\n *\/\n template \n T\n median(std::vector v)\n {\n std::sort(v.begin(), v.end());\n return v[v.size() \/ 2];\n }\n\n \/** Absolute value. *\/\n template \n T\n abs(const T &value)\n {\n if (value < 0)\n return -value;\n return value;\n }\n\n \/** Maximum of two values. *\/\n template \n T\n max(const T &a, const T &b)\n {\n if (a < b)\n return b;\n return a;\n }\n\n inline float\n log10add(float a, float b)\n {\n const float LOG10TOe = M_LN10;\n const float LOGeTO10 = 1.0 \/ M_LN10;\n\n a = a * LOG10TOe;\n b = b * LOG10TOe;\n\n float delta = a - b;\n if (delta > 64.0) {\n b += 64;\n delta = -delta;\n }\n return (b + log1pf(exp(delta))) * LOGeTO10;\n }\n\n inline float\n logadd(float a, float b)\n {\n float delta = a - b;\n if (delta > 64.0) {\n b += 64;\n delta = -delta;\n }\n return b + log1pf(exp(delta));\n }\n\n static const float tiny_for_log = (float)1e-16;\n inline double safe_log(double x)\n {\n if (x < tiny_for_log)\n return logf(tiny_for_log);\n else\n return logf(x);\n }\n\n \/** Compute modulo of two values so that negative arguments are\n * handled correctly. *\/\n int modulo(int a, int b) \n {\n int result = a % b;\n if (result < 0)\n result += b;\n return result;\n }\n\n};\n\n#endif \/* UTIL_HH *\/\n<|endoftext|>"} {"text":"\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\/\n\/\/ Copyright Holders: Felix Albrecht, Rene Milk\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#warning This header is deprecated, use '#include [la.container.dunedynamic] fixed deprecation warning\/\/ This file is part of the dune-stuff project:\n\/\/ https:\/\/users.dune-project.org\/projects\/dune-stuff\/\n\/\/ Copyright Holders: Felix Albrecht, Rene Milk\n\/\/ License: BSD 2-Clause License (http:\/\/opensource.org\/licenses\/BSD-2-Clause)\n\n#warning This header is deprecated, use '#include ' instead!\n#include \"common.hh\"\n<|endoftext|>"} {"text":"#define EXT_SINGULAR 2\n#define EXT_DEPTH_CHECK 3\n#define EXT_DEPTH_ONE_REPLY 2\n#define EXT_DEPTH_RECAP 2\n#define NULL_DEPTH_RATE 12\n#define NULL_DEPTH_REDUCE 14\n#define NULL_DEPTH_VRATE 510\n#define REDUCTION_RATE1 12\n#define REDUCTION_RATE2 12\n#define RAZOR_MARGIN1 230\n#define RAZOR_MARGIN2 700\n#define RAZOR_MARGIN3 820\n#define RAZOR_MARGIN4 660\n#define FUT_PRUN_MAX_DEPTH 24\n#define FUT_PRUN_MARGIN_RATE 40\n#define FUT_PRUN_MARGIN 70\n#define PROBCUT_MARGIN 200\n#define PROBCUT_REDUCTION 16\n#define ASP_MIN_DEPTH 0\n#define ASP_1ST_DELTA 70\n#define ASP_DELTA_RATE 20\n#define SINGULAR_DEPTH 36\n#define SINGULAR_MARGIN 20\nFix ASP_MIN_DEPTH parameter#define EXT_SINGULAR 2\n#define EXT_DEPTH_CHECK 3\n#define EXT_DEPTH_ONE_REPLY 2\n#define EXT_DEPTH_RECAP 2\n#define NULL_DEPTH_RATE 12\n#define NULL_DEPTH_REDUCE 14\n#define NULL_DEPTH_VRATE 510\n#define REDUCTION_RATE1 12\n#define REDUCTION_RATE2 12\n#define RAZOR_MARGIN1 230\n#define RAZOR_MARGIN2 700\n#define RAZOR_MARGIN3 820\n#define RAZOR_MARGIN4 660\n#define FUT_PRUN_MAX_DEPTH 24\n#define FUT_PRUN_MARGIN_RATE 40\n#define FUT_PRUN_MARGIN 70\n#define PROBCUT_MARGIN 200\n#define PROBCUT_REDUCTION 16\n#define ASP_MIN_DEPTH 2\n#define ASP_1ST_DELTA 70\n#define ASP_DELTA_RATE 20\n#define SINGULAR_DEPTH 36\n#define SINGULAR_MARGIN 20\n<|endoftext|>"} {"text":"\/\/ Copyright 2014-2015 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \"elang\/compiler\/testing\/analyzer_test.h\"\n\n#include \"base\/strings\/string_piece.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"elang\/compiler\/compilation_session.h\"\n#include \"elang\/compiler\/predefined_names.h\"\n#include \"elang\/compiler\/semantics\/editor.h\"\n#include \"elang\/compiler\/semantics\/factory.h\"\n#include \"elang\/compiler\/semantics\/nodes.h\"\n#include \"elang\/compiler\/source_code_range.h\"\n#include \"elang\/compiler\/token.h\"\n#include \"elang\/compiler\/token_type.h\"\n\nnamespace elang {\nnamespace compiler {\nnamespace sm {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ IrSemanticsTest\n\/\/\nclass IrSemanticsTest : public testing::AnalyzerTest {\n protected:\n IrSemanticsTest();\n ~IrSemanticsTest() override = default;\n\n Editor* editor() { return &editor_; }\n Factory* factory() { return editor()->factory(); }\n Type* system_int32();\n Type* system_int64();\n\n Value* NewLiteral(Type* type, const TokenData& data);\n Token* NewToken(const TokenData& data);\n Token* NewToken(base::StringPiece name);\n std::string ToString(Semantic* node);\n\n private:\n sm::Editor editor_;\n\n DISALLOW_COPY_AND_ASSIGN(IrSemanticsTest);\n};\n\nIrSemanticsTest::IrSemanticsTest() : editor_(session()) {\n}\n\nType* IrSemanticsTest::system_int32() {\n return session()->PredefinedTypeOf(PredefinedName::Int32);\n}\n\nType* IrSemanticsTest::system_int64() {\n return session()->PredefinedTypeOf(PredefinedName::Int64);\n}\n\nValue* IrSemanticsTest::NewLiteral(Type* type, const TokenData& data) {\n return factory()->NewLiteral(type, NewToken(data));\n}\n\nToken* IrSemanticsTest::NewToken(const TokenData& data) {\n return session()->NewToken(SourceCodeRange(), data);\n}\n\nToken* IrSemanticsTest::NewToken(base::StringPiece name) {\n return NewToken(\n TokenData(session()->NewAtomicString(base::UTF8ToUTF16(name))));\n}\n\nstd::string IrSemanticsTest::ToString(Semantic* semantic) {\n std::stringstream ostream;\n ostream << *semantic;\n return ostream.str();\n}\n\nTEST_F(IrSemanticsTest, ArrayType) {\n auto const type1 = factory()->NewArrayType(system_int32(), {10, 20});\n auto const type2 = factory()->NewArrayType(system_int32(), {10, 20});\n auto const type3 = factory()->NewArrayType(system_int32(), {10});\n EXPECT_EQ(type1, type2)\n << \"array type should be unique by element type and dimensions\";\n EXPECT_NE(type1, type3);\n EXPECT_EQ(2, type1->rank());\n EXPECT_EQ(\"System.Int32[10, 20]\", ToString(type1));\n EXPECT_EQ(\"System.Int32[10]\", ToString(type3));\n}\n\n\/\/ Element type of array type is omitting left most rank, e.g.\n\/\/ element_type_of(T[A]) = T\n\/\/ element_type_of(T[A][B}) = T[B]\n\/\/ element_type_of(T[A][B}[C]) = T[B][C]\nTEST_F(IrSemanticsTest, ArrayTypeArrayOfArray) {\n auto const type1 = factory()->NewArrayType(system_int32(), {10});\n auto const type2 = factory()->NewArrayType(type1, {20});\n auto const type3 = factory()->NewArrayType(type2, {30});\n EXPECT_EQ(\"System.Int32[10]\", ToString(type1));\n EXPECT_EQ(\"System.Int32[20][10]\", ToString(type2));\n EXPECT_EQ(\"System.Int32[30][20][10]\", ToString(type3));\n}\n\nTEST_F(IrSemanticsTest, ArrayTypeUnbound) {\n EXPECT_EQ(\"System.Int32[]\",\n ToString(factory()->NewArrayType(system_int32(), {-1})));\n EXPECT_EQ(\"System.Int32[,]\",\n ToString(factory()->NewArrayType(system_int32(), {-1, -1})));\n EXPECT_EQ(\"System.Int32[,,]\",\n ToString(factory()->NewArrayType(system_int32(), {-1, -1, -1})));\n}\n\nTEST_F(IrSemanticsTest, Enum) {\n auto const outer =\n factory()->NewNamespace(factory()->global_namespace(), NewToken(\"Foo\"));\n auto const enum_base = system_int64();\n auto const enum_type =\n factory()->NewEnum(outer, NewToken(\"Color\"), enum_base);\n factory()->NewEnumMember(enum_type, NewToken(\"Red\"), nullptr);\n factory()->NewEnumMember(enum_type, NewToken(\"Green\"), nullptr);\n factory()->NewEnumMember(\n enum_type, NewToken(\"Blue\"),\n NewLiteral(enum_base, TokenData(TokenType::Int32Literal, 42)));\n EXPECT_EQ(\"enum Foo.Color : System.Int64 {Red, Green, Blue = 42}\",\n ToString(enum_type));\n}\n\nTEST_F(IrSemanticsTest, Namespace) {\n auto const ns1 =\n factory()->NewNamespace(factory()->global_namespace(), NewToken(\"Foo\"));\n auto const ns2 = factory()->NewNamespace(ns1, NewToken(\"Bar\"));\n EXPECT_EQ(\"namespace Foo\", ToString(ns1));\n EXPECT_EQ(\"namespace Foo.Bar\", ToString(ns2));\n}\n\n} \/\/ namespace sm\n} \/\/ namespace compiler\n} \/\/ namespace elang\nelang\/compiler\/semantics: Tidy up \"node_test.cc\".\/\/ Copyright 2014-2015 Project Vogue. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \n#include \n\n#include \"elang\/compiler\/testing\/analyzer_test.h\"\n\n#include \"base\/strings\/string_piece.h\"\n#include \"base\/strings\/utf_string_conversions.h\"\n#include \"elang\/compiler\/compilation_session.h\"\n#include \"elang\/compiler\/predefined_names.h\"\n#include \"elang\/compiler\/semantics\/editor.h\"\n#include \"elang\/compiler\/semantics\/factory.h\"\n#include \"elang\/compiler\/semantics\/nodes.h\"\n#include \"elang\/compiler\/source_code_range.h\"\n#include \"elang\/compiler\/token.h\"\n#include \"elang\/compiler\/token_type.h\"\n\nnamespace elang {\nnamespace compiler {\nnamespace sm {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ SemanticTest\n\/\/\nclass SemanticTest : public testing::AnalyzerTest {\n protected:\n SemanticTest();\n ~SemanticTest() override = default;\n\n Editor* editor() { return &editor_; }\n Factory* factory() { return editor()->factory(); }\n Type* int32_type();\n Type* int64_type();\n\n Value* NewLiteral(Type* type, const TokenData& data);\n Token* NewToken(const TokenData& data);\n Token* NewToken(base::StringPiece name);\n std::string ToString(Semantic* node);\n\n private:\n sm::Editor editor_;\n\n DISALLOW_COPY_AND_ASSIGN(SemanticTest);\n};\n\nSemanticTest::SemanticTest() : editor_(session()) {\n}\n\nType* SemanticTest::int32_type() {\n return session()->PredefinedTypeOf(PredefinedName::Int32);\n}\n\nType* SemanticTest::int64_type() {\n return session()->PredefinedTypeOf(PredefinedName::Int64);\n}\n\nValue* SemanticTest::NewLiteral(Type* type, const TokenData& data) {\n return factory()->NewLiteral(type, NewToken(data));\n}\n\nToken* SemanticTest::NewToken(const TokenData& data) {\n return session()->NewToken(SourceCodeRange(), data);\n}\n\nToken* SemanticTest::NewToken(base::StringPiece name) {\n return NewToken(\n TokenData(session()->NewAtomicString(base::UTF8ToUTF16(name))));\n}\n\nstd::string SemanticTest::ToString(Semantic* semantic) {\n std::stringstream ostream;\n ostream << *semantic;\n return ostream.str();\n}\n\nTEST_F(SemanticTest, ArrayType) {\n auto const type1 = factory()->NewArrayType(int32_type(), {10, 20});\n auto const type2 = factory()->NewArrayType(int32_type(), {10, 20});\n auto const type3 = factory()->NewArrayType(int32_type(), {10});\n EXPECT_EQ(type1, type2)\n << \"array type should be unique by element type and dimensions\";\n EXPECT_NE(type1, type3);\n EXPECT_EQ(2, type1->rank());\n EXPECT_EQ(\"System.Int32[10, 20]\", ToString(type1));\n EXPECT_EQ(\"System.Int32[10]\", ToString(type3));\n}\n\n\/\/ Element type of array type is omitting left most rank, e.g.\n\/\/ element_type_of(T[A]) = T\n\/\/ element_type_of(T[A][B}) = T[B]\n\/\/ element_type_of(T[A][B}[C]) = T[B][C]\nTEST_F(SemanticTest, ArrayTypeArrayOfArray) {\n auto const type1 = factory()->NewArrayType(int32_type(), {10});\n auto const type2 = factory()->NewArrayType(type1, {20});\n auto const type3 = factory()->NewArrayType(type2, {30});\n EXPECT_EQ(\"System.Int32[10]\", ToString(type1));\n EXPECT_EQ(\"System.Int32[20][10]\", ToString(type2));\n EXPECT_EQ(\"System.Int32[30][20][10]\", ToString(type3));\n}\n\nTEST_F(SemanticTest, ArrayTypeUnbound) {\n EXPECT_EQ(\"System.Int32[]\",\n ToString(factory()->NewArrayType(int32_type(), {-1})));\n EXPECT_EQ(\"System.Int32[,]\",\n ToString(factory()->NewArrayType(int32_type(), {-1, -1})));\n EXPECT_EQ(\"System.Int32[,,]\",\n ToString(factory()->NewArrayType(int32_type(), {-1, -1, -1})));\n}\n\nTEST_F(SemanticTest, Enum) {\n auto const outer =\n factory()->NewNamespace(factory()->global_namespace(), NewToken(\"Foo\"));\n auto const enum_base = int64_type();\n auto const enum_type =\n factory()->NewEnum(outer, NewToken(\"Color\"), enum_base);\n factory()->NewEnumMember(enum_type, NewToken(\"Red\"), nullptr);\n factory()->NewEnumMember(enum_type, NewToken(\"Green\"), nullptr);\n factory()->NewEnumMember(\n enum_type, NewToken(\"Blue\"),\n NewLiteral(enum_base, TokenData(TokenType::Int32Literal, 42)));\n EXPECT_EQ(\"enum Foo.Color : System.Int64 {Red, Green, Blue = 42}\",\n ToString(enum_type));\n}\n\nTEST_F(SemanticTest, Namespace) {\n auto const ns1 =\n factory()->NewNamespace(factory()->global_namespace(), NewToken(\"Foo\"));\n auto const ns2 = factory()->NewNamespace(ns1, NewToken(\"Bar\"));\n EXPECT_EQ(\"namespace Foo\", ToString(ns1));\n EXPECT_EQ(\"namespace Foo.Bar\", ToString(ns2));\n}\n\n} \/\/ namespace sm\n} \/\/ namespace compiler\n} \/\/ namespace elang\n<|endoftext|>"} {"text":"#include \n\nint main()\n{\n std::cout << \"123\\n\";\n}\n\nAdd return 0;#include \n\nint main()\n{\n std::cout << \"123\\n\";\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"core\/svg.h\"\n\n#include \"core\/numeric.h\"\n#include \"core\/angle.h\"\n#include \"core\/random.h\"\n#include \"core\/range.h\"\n#include \"core\/palette.h\"\n#include \"core\/palette_tableu.h\"\n\nusing namespace euphoria::core;\nusing namespace euphoria::core::svg;\n\nPoly\nMakeStar(const vec2f& origo, float radius, const Rgbi& fill, const Angle& rotation)\n{\n auto alpha = Angle::OneTurn() \/ 10;\n\n auto p = Poly{};\n\n for(auto i = 11; i > 0; i--)\n {\n auto r = radius*(i % 2 + 1)\/2.0f;\n auto omega = rotation + alpha * static_cast(i);\n p.points.push_back({(r * Sin(omega)) + origo.x, (r * Cos(omega)) + origo.y});\n }\n\n p.Close(fill);\n\n return p;\n}\n\nint\nmain(int, char*[])\n{\n Random rand;\n\n auto pal = palette::Tableau_20();\n\n auto svg = Svg{};\n\n for(int i=0; i<30; i+=1)\n {\n const auto p = rand.PointOnUnitCircle_CenterFocused()*100.0f;\n const auto s = rand.Next(Range{5.0f, 30.0f});\n const auto c = pal.GetRandomColor(&rand);\n const auto r = Angle::FromPercentOf360(rand.NextFloat01());\n svg << MakeStar(p, s, c, r);\n }\n svg.AddAxis().Grid(10);\n svg.Write(\"stars.html\");\n}\n\nstarted using shufflebag instead of just random values#include \"core\/svg.h\"\n\n#include \"core\/numeric.h\"\n#include \"core\/angle.h\"\n#include \"core\/random.h\"\n#include \"core\/range.h\"\n#include \"core\/palette.h\"\n#include \"core\/palette_tableu.h\"\n#include \"core\/shufflebag.h\"\n\nusing namespace euphoria::core;\nusing namespace euphoria::core::svg;\n\nPoly\nMakeStar(const vec2f& origo, float radius, const Rgbi& fill, const Angle& rotation)\n{\n auto alpha = Angle::OneTurn() \/ 10;\n\n auto p = Poly{};\n\n for(auto i = 11; i > 0; i--)\n {\n auto r = radius*(i % 2 + 1)\/2.0f;\n auto omega = rotation + alpha * static_cast(i);\n p.points.push_back({(r * Sin(omega)) + origo.x, (r * Cos(omega)) + origo.y});\n }\n\n p.Close(fill);\n\n return p;\n}\n\nint\nmain(int, char*[])\n{\n Random rand;\n\n auto pal = CreateShuffleBag(palette::ColorBlind_10().colors, 2);\n\n auto svg = Svg{};\n\n for(int i=0; i<30; i+=1)\n {\n const auto p = rand.PointOnUnitCircle_CenterFocused()*100.0f;\n const auto s = rand.Next(Range{5.0f, 30.0f});\n const auto c = pal.Next(&rand);\n const auto r = Angle::FromPercentOf360(rand.NextFloat01());\n svg << MakeStar(p, s, c, r);\n }\n svg.AddAxis().Grid(10);\n svg.Write(\"stars.html\");\n}\n\n<|endoftext|>"} {"text":"#include \"rtp\/QualityManager.h\"\n#include \"WebRtcConnection.h\"\n\nnamespace erizo {\n\nDEFINE_LOGGER(QualityManager, \"rtp.QualityManager\");\n\nconstexpr duration QualityManager::kMinLayerSwitchInterval;\nconstexpr duration QualityManager::kActiveLayerInterval;\nconstexpr float QualityManager::kIncreaseLayerBitrateThreshold;\n\nQualityManager::QualityManager(std::shared_ptr the_clock)\n : initialized_{false}, enabled_{false}, padding_enabled_{false}, forced_layers_{false},\n slideshow_mode_active_{false}, spatial_layer_{0}, temporal_layer_{0}, max_active_spatial_layer_{0},\n max_active_temporal_layer_{0}, current_estimated_bitrate_{0}, last_quality_check_{the_clock->now()},\n last_activity_check_{the_clock->now()}, clock_{the_clock} {}\n\nvoid QualityManager::enable() {\n ELOG_DEBUG(\"message: Enabling QualityManager\");\n enabled_ = true;\n setPadding(true);\n}\n\nvoid QualityManager::disable() {\n ELOG_DEBUG(\"message: Disabling QualityManager\");\n enabled_ = false;\n setPadding(false);\n}\n\nvoid QualityManager::notifyQualityUpdate() {\n if (!enabled_) {\n return;\n }\n\n if (!initialized_) {\n auto pipeline = getContext()->getPipelineShared();\n if (!pipeline) {\n return;\n }\n stats_ = pipeline->getService();\n if (!stats_) {\n return;\n }\n if (!stats_->getNode()[\"total\"].hasChild(\"senderBitrateEstimation\")) {\n return;\n }\n initialized_ = true;\n }\n\n if (forced_layers_) {\n return;\n }\n time_point now = clock_->now();\n current_estimated_bitrate_ = stats_->getNode()[\"total\"][\"senderBitrateEstimation\"].value();\n uint64_t current_layer_instant_bitrate = getInstantLayerBitrate(spatial_layer_, temporal_layer_);\n bool estimated_is_under_layer_bitrate = current_estimated_bitrate_ < current_layer_instant_bitrate;\n\n if (now - last_activity_check_ > kActiveLayerInterval) {\n calculateMaxActiveLayer();\n last_activity_check_ = now;\n }\n\n bool layer_is_active = spatial_layer_ <= max_active_spatial_layer_;\n\n if (!layer_is_active || (estimated_is_under_layer_bitrate && !slideshow_mode_active_)) {\n ELOG_DEBUG(\"message: Forcing calculate new layer, \"\n \"estimated_is_under_layer_bitrate: %d, layer_is_active: %d\", estimated_is_under_layer_bitrate,\n layer_is_active);\n selectLayer(false);\n } else if (now - last_quality_check_ > kMinLayerSwitchInterval) {\n selectLayer(true);\n }\n}\n\nvoid QualityManager::selectLayer(bool try_higher_layers) {\n last_quality_check_ = clock_->now();\n int aux_temporal_layer = 0;\n int aux_spatial_layer = 0;\n int next_temporal_layer = 0;\n int next_spatial_layer = 0;\n float bitrate_margin = try_higher_layers ? kIncreaseLayerBitrateThreshold : 0;\n bool below_min_layer = true;\n ELOG_DEBUG(\"Calculate best layer with %lu, current layer %d\/%d\",\n current_estimated_bitrate_, spatial_layer_, temporal_layer_);\n for (auto &spatial_layer_node : stats_->getNode()[\"qualityLayers\"].getMap()) {\n for (auto &temporal_layer_node : stats_->getNode()[\"qualityLayers\"][spatial_layer_node.first.c_str()].getMap()) {\n ELOG_DEBUG(\"Bitrate for layer %d\/%d %lu\",\n aux_spatial_layer, aux_temporal_layer, temporal_layer_node.second->value());\n if (temporal_layer_node.second->value() != 0 &&\n (1. + bitrate_margin) * temporal_layer_node.second->value() < current_estimated_bitrate_) {\n next_temporal_layer = aux_temporal_layer;\n next_spatial_layer = aux_spatial_layer;\n below_min_layer = false;\n }\n aux_temporal_layer++;\n }\n aux_temporal_layer = 0;\n aux_spatial_layer++;\n }\n\n if (below_min_layer != slideshow_mode_active_) {\n if (below_min_layer || try_higher_layers) {\n slideshow_mode_active_ = below_min_layer;\n ELOG_DEBUG(\"Slideshow fallback mode %d\", slideshow_mode_active_);\n WebRtcConnection *connection = getContext()->getPipelineShared()->getService().get();\n if (connection) {\n connection->notifyUpdateToHandlers();\n }\n }\n }\n\n if (next_temporal_layer != temporal_layer_ || next_spatial_layer != spatial_layer_) {\n ELOG_DEBUG(\"message: Layer Switch, current_layer: %d\/%d, new_layer: %d\/%d\",\n spatial_layer_, temporal_layer_, next_spatial_layer, next_temporal_layer);\n setTemporalLayer(next_temporal_layer);\n setSpatialLayer(next_spatial_layer);\n\n \/\/ TODO(javier): should we wait for the actual spatial switch?\n \/\/ should we disable padding temporarily to avoid congestion (old padding + new bitrate)?\n setPadding(!isInMaxLayer());\n ELOG_DEBUG(\"message: Is padding enabled, padding_enabled_: %d\", padding_enabled_);\n }\n}\n\nvoid QualityManager::calculateMaxActiveLayer() {\n int max_active_spatial_layer = 5;\n int max_active_temporal_layer = 5;\n\n for (; max_active_spatial_layer > 0; max_active_spatial_layer--) {\n if (getInstantLayerBitrate(max_active_spatial_layer, 0) > 0) {\n break;\n }\n }\n for (; max_active_temporal_layer > 0; max_active_temporal_layer--) {\n if (getInstantLayerBitrate(max_active_spatial_layer, max_active_temporal_layer) > 0) {\n break;\n }\n }\n stats_->getNode()[\"qualityLayers\"].insertStat(\"maxActiveSpatialLayer\",\n CumulativeStat{static_cast(max_active_spatial_layer_)});\n stats_->getNode()[\"qualityLayers\"].insertStat(\"maxActiveTemporalLayer\",\n CumulativeStat{static_cast(max_active_temporal_layer_)});\n\n max_active_spatial_layer_ = max_active_spatial_layer;\n max_active_temporal_layer_ = max_active_temporal_layer;\n}\n\nuint64_t QualityManager::getInstantLayerBitrate(int spatial_layer, int temporal_layer) {\n if (!stats_->getNode()[\"qualityLayers\"].hasChild(spatial_layer) ||\n !stats_->getNode()[\"qualityLayers\"][spatial_layer].hasChild(temporal_layer)) {\n return 0;\n }\n\n MovingIntervalRateStat* layer_stat =\n reinterpret_cast(&stats_->getNode()[\"qualityLayers\"][spatial_layer][temporal_layer]);\n return layer_stat->value(kActiveLayerInterval);\n}\n\nbool QualityManager::isInBaseLayer() {\n return (spatial_layer_ == 0 && temporal_layer_ == 0);\n}\n\nbool QualityManager::isInMaxLayer() {\n return (spatial_layer_ >= max_active_spatial_layer_ && temporal_layer_ >= max_active_temporal_layer_);\n}\n\nvoid QualityManager::forceLayers(int spatial_layer, int temporal_layer) {\n if (spatial_layer == -1 || temporal_layer == -1) {\n forced_layers_ = false;\n return;\n }\n forced_layers_ = true;\n setPadding(false);\n\n spatial_layer_ = spatial_layer;\n temporal_layer_ = temporal_layer;\n}\n\nvoid QualityManager::setSpatialLayer(int spatial_layer) {\n if (!forced_layers_) {\n spatial_layer_ = spatial_layer;\n }\n stats_->getNode()[\"qualityLayers\"].insertStat(\"selectedSpatialLayer\",\n CumulativeStat{static_cast(spatial_layer_)});\n}\nvoid QualityManager::setTemporalLayer(int temporal_layer) {\n if (!forced_layers_) {\n temporal_layer_ = temporal_layer;\n }\n stats_->getNode()[\"qualityLayers\"].insertStat(\"selectedTemporalLayer\",\n CumulativeStat{static_cast(temporal_layer_)});\n}\n\nvoid QualityManager::setPadding(bool enabled) {\n if (padding_enabled_ != enabled) {\n padding_enabled_ = enabled;\n getContext()->getPipelineShared()->getService()->notifyUpdateToHandlers();\n }\n}\n\n} \/\/ namespace erizo\nFix an issue when enabling padding the first time (#950)#include \"rtp\/QualityManager.h\"\n#include \"WebRtcConnection.h\"\n\nnamespace erizo {\n\nDEFINE_LOGGER(QualityManager, \"rtp.QualityManager\");\n\nconstexpr duration QualityManager::kMinLayerSwitchInterval;\nconstexpr duration QualityManager::kActiveLayerInterval;\nconstexpr float QualityManager::kIncreaseLayerBitrateThreshold;\n\nQualityManager::QualityManager(std::shared_ptr the_clock)\n : initialized_{false}, enabled_{false}, padding_enabled_{false}, forced_layers_{false},\n slideshow_mode_active_{false}, spatial_layer_{0}, temporal_layer_{0}, max_active_spatial_layer_{0},\n max_active_temporal_layer_{0}, current_estimated_bitrate_{0}, last_quality_check_{the_clock->now()},\n last_activity_check_{the_clock->now()}, clock_{the_clock} {}\n\nvoid QualityManager::enable() {\n ELOG_DEBUG(\"message: Enabling QualityManager\");\n enabled_ = true;\n if (!forced_layers_) {\n setPadding(true);\n }\n}\n\nvoid QualityManager::disable() {\n ELOG_DEBUG(\"message: Disabling QualityManager\");\n enabled_ = false;\n setPadding(false);\n}\n\nvoid QualityManager::notifyQualityUpdate() {\n if (!enabled_) {\n return;\n }\n\n if (!initialized_) {\n auto pipeline = getContext()->getPipelineShared();\n if (!pipeline) {\n return;\n }\n stats_ = pipeline->getService();\n if (!stats_) {\n return;\n }\n if (!stats_->getNode()[\"total\"].hasChild(\"senderBitrateEstimation\")) {\n return;\n }\n initialized_ = true;\n }\n\n if (forced_layers_) {\n return;\n }\n time_point now = clock_->now();\n current_estimated_bitrate_ = stats_->getNode()[\"total\"][\"senderBitrateEstimation\"].value();\n uint64_t current_layer_instant_bitrate = getInstantLayerBitrate(spatial_layer_, temporal_layer_);\n bool estimated_is_under_layer_bitrate = current_estimated_bitrate_ < current_layer_instant_bitrate;\n\n if (now - last_activity_check_ > kActiveLayerInterval) {\n calculateMaxActiveLayer();\n last_activity_check_ = now;\n }\n\n bool layer_is_active = spatial_layer_ <= max_active_spatial_layer_;\n\n if (!layer_is_active || (estimated_is_under_layer_bitrate && !slideshow_mode_active_)) {\n ELOG_DEBUG(\"message: Forcing calculate new layer, \"\n \"estimated_is_under_layer_bitrate: %d, layer_is_active: %d\", estimated_is_under_layer_bitrate,\n layer_is_active);\n selectLayer(false);\n } else if (now - last_quality_check_ > kMinLayerSwitchInterval) {\n selectLayer(true);\n }\n}\n\nvoid QualityManager::selectLayer(bool try_higher_layers) {\n last_quality_check_ = clock_->now();\n int aux_temporal_layer = 0;\n int aux_spatial_layer = 0;\n int next_temporal_layer = 0;\n int next_spatial_layer = 0;\n float bitrate_margin = try_higher_layers ? kIncreaseLayerBitrateThreshold : 0;\n bool below_min_layer = true;\n ELOG_DEBUG(\"Calculate best layer with %lu, current layer %d\/%d\",\n current_estimated_bitrate_, spatial_layer_, temporal_layer_);\n for (auto &spatial_layer_node : stats_->getNode()[\"qualityLayers\"].getMap()) {\n for (auto &temporal_layer_node : stats_->getNode()[\"qualityLayers\"][spatial_layer_node.first.c_str()].getMap()) {\n ELOG_DEBUG(\"Bitrate for layer %d\/%d %lu\",\n aux_spatial_layer, aux_temporal_layer, temporal_layer_node.second->value());\n if (temporal_layer_node.second->value() != 0 &&\n (1. + bitrate_margin) * temporal_layer_node.second->value() < current_estimated_bitrate_) {\n next_temporal_layer = aux_temporal_layer;\n next_spatial_layer = aux_spatial_layer;\n below_min_layer = false;\n }\n aux_temporal_layer++;\n }\n aux_temporal_layer = 0;\n aux_spatial_layer++;\n }\n\n if (below_min_layer != slideshow_mode_active_) {\n if (below_min_layer || try_higher_layers) {\n slideshow_mode_active_ = below_min_layer;\n ELOG_DEBUG(\"Slideshow fallback mode %d\", slideshow_mode_active_);\n WebRtcConnection *connection = getContext()->getPipelineShared()->getService().get();\n if (connection) {\n connection->notifyUpdateToHandlers();\n }\n }\n }\n\n if (next_temporal_layer != temporal_layer_ || next_spatial_layer != spatial_layer_) {\n ELOG_DEBUG(\"message: Layer Switch, current_layer: %d\/%d, new_layer: %d\/%d\",\n spatial_layer_, temporal_layer_, next_spatial_layer, next_temporal_layer);\n setTemporalLayer(next_temporal_layer);\n setSpatialLayer(next_spatial_layer);\n\n \/\/ TODO(javier): should we wait for the actual spatial switch?\n \/\/ should we disable padding temporarily to avoid congestion (old padding + new bitrate)?\n setPadding(!isInMaxLayer());\n ELOG_DEBUG(\"message: Is padding enabled, padding_enabled_: %d\", padding_enabled_);\n }\n}\n\nvoid QualityManager::calculateMaxActiveLayer() {\n int max_active_spatial_layer = 5;\n int max_active_temporal_layer = 5;\n\n for (; max_active_spatial_layer > 0; max_active_spatial_layer--) {\n if (getInstantLayerBitrate(max_active_spatial_layer, 0) > 0) {\n break;\n }\n }\n for (; max_active_temporal_layer > 0; max_active_temporal_layer--) {\n if (getInstantLayerBitrate(max_active_spatial_layer, max_active_temporal_layer) > 0) {\n break;\n }\n }\n stats_->getNode()[\"qualityLayers\"].insertStat(\"maxActiveSpatialLayer\",\n CumulativeStat{static_cast(max_active_spatial_layer_)});\n stats_->getNode()[\"qualityLayers\"].insertStat(\"maxActiveTemporalLayer\",\n CumulativeStat{static_cast(max_active_temporal_layer_)});\n\n max_active_spatial_layer_ = max_active_spatial_layer;\n max_active_temporal_layer_ = max_active_temporal_layer;\n}\n\nuint64_t QualityManager::getInstantLayerBitrate(int spatial_layer, int temporal_layer) {\n if (!stats_->getNode()[\"qualityLayers\"].hasChild(spatial_layer) ||\n !stats_->getNode()[\"qualityLayers\"][spatial_layer].hasChild(temporal_layer)) {\n return 0;\n }\n\n MovingIntervalRateStat* layer_stat =\n reinterpret_cast(&stats_->getNode()[\"qualityLayers\"][spatial_layer][temporal_layer]);\n return layer_stat->value(kActiveLayerInterval);\n}\n\nbool QualityManager::isInBaseLayer() {\n return (spatial_layer_ == 0 && temporal_layer_ == 0);\n}\n\nbool QualityManager::isInMaxLayer() {\n return (spatial_layer_ >= max_active_spatial_layer_ && temporal_layer_ >= max_active_temporal_layer_);\n}\n\nvoid QualityManager::forceLayers(int spatial_layer, int temporal_layer) {\n if (spatial_layer == -1 || temporal_layer == -1) {\n forced_layers_ = false;\n return;\n }\n forced_layers_ = true;\n setPadding(false);\n\n spatial_layer_ = spatial_layer;\n temporal_layer_ = temporal_layer;\n}\n\nvoid QualityManager::setSpatialLayer(int spatial_layer) {\n if (!forced_layers_) {\n spatial_layer_ = spatial_layer;\n }\n stats_->getNode()[\"qualityLayers\"].insertStat(\"selectedSpatialLayer\",\n CumulativeStat{static_cast(spatial_layer_)});\n}\nvoid QualityManager::setTemporalLayer(int temporal_layer) {\n if (!forced_layers_) {\n temporal_layer_ = temporal_layer;\n }\n stats_->getNode()[\"qualityLayers\"].insertStat(\"selectedTemporalLayer\",\n CumulativeStat{static_cast(temporal_layer_)});\n}\n\nvoid QualityManager::setPadding(bool enabled) {\n if (padding_enabled_ != enabled) {\n padding_enabled_ = enabled;\n getContext()->getPipelineShared()->getService()->notifyUpdateToHandlers();\n }\n}\n\n} \/\/ namespace erizo\n<|endoftext|>"} {"text":"d6483158-2e4c-11e5-9284-b827eb9e62bed64d3e1e-2e4c-11e5-9284-b827eb9e62bed64d3e1e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cd46f638-2e4d-11e5-9284-b827eb9e62becd4be9cc-2e4d-11e5-9284-b827eb9e62becd4be9cc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4bafcc3e-2e4e-11e5-9284-b827eb9e62be4bb53854-2e4e-11e5-9284-b827eb9e62be4bb53854-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e70ebc6c-2e4e-11e5-9284-b827eb9e62bee713eb24-2e4e-11e5-9284-b827eb9e62bee713eb24-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ff7dcdec-2e4e-11e5-9284-b827eb9e62beff82c4e6-2e4e-11e5-9284-b827eb9e62beff82c4e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c4bf2cb4-2e4e-11e5-9284-b827eb9e62bec4c42c00-2e4e-11e5-9284-b827eb9e62bec4c42c00-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a5d00356-2e4d-11e5-9284-b827eb9e62bea5d4fbcc-2e4d-11e5-9284-b827eb9e62bea5d4fbcc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b07366d0-2e4e-11e5-9284-b827eb9e62beb078675c-2e4e-11e5-9284-b827eb9e62beb078675c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2c1ef17e-2e4e-11e5-9284-b827eb9e62be2c23ff7a-2e4e-11e5-9284-b827eb9e62be2c23ff7a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d800e094-2e4c-11e5-9284-b827eb9e62bed805f250-2e4c-11e5-9284-b827eb9e62bed805f250-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"16ffa15e-2e4d-11e5-9284-b827eb9e62be1704ba2c-2e4d-11e5-9284-b827eb9e62be1704ba2c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"04070c94-2e4e-11e5-9284-b827eb9e62be040bf98e-2e4e-11e5-9284-b827eb9e62be040bf98e-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c55a6456-2e4c-11e5-9284-b827eb9e62bec55f59de-2e4c-11e5-9284-b827eb9e62bec55f59de-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a3885814-2e4d-11e5-9284-b827eb9e62bea38d50bc-2e4d-11e5-9284-b827eb9e62bea38d50bc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e7c1012e-2e4e-11e5-9284-b827eb9e62bee7c62d5c-2e4e-11e5-9284-b827eb9e62bee7c62d5c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fb7cacc4-2e4c-11e5-9284-b827eb9e62befb81a990-2e4c-11e5-9284-b827eb9e62befb81a990-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fdd393b6-2e4c-11e5-9284-b827eb9e62befdd88628-2e4c-11e5-9284-b827eb9e62befdd88628-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0e4e1c60-2e4e-11e5-9284-b827eb9e62be0e531404-2e4e-11e5-9284-b827eb9e62be0e531404-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2929b0a4-2e4d-11e5-9284-b827eb9e62be292ea1d6-2e4d-11e5-9284-b827eb9e62be292ea1d6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"d4207cb4-2e4c-11e5-9284-b827eb9e62bed425a36a-2e4c-11e5-9284-b827eb9e62bed425a36a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"8b1bf88a-2e4d-11e5-9284-b827eb9e62be8b20f07e-2e4d-11e5-9284-b827eb9e62be8b20f07e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e39683aa-2e4c-11e5-9284-b827eb9e62bee39b8652-2e4c-11e5-9284-b827eb9e62bee39b8652-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a4638302-2e4e-11e5-9284-b827eb9e62bea4689b1c-2e4e-11e5-9284-b827eb9e62bea4689b1c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"98028ec4-2e4d-11e5-9284-b827eb9e62be98078cf8-2e4d-11e5-9284-b827eb9e62be98078cf8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"51afb0e6-2e4d-11e5-9284-b827eb9e62be51b4c176-2e4d-11e5-9284-b827eb9e62be51b4c176-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"03af4eb8-2e4f-11e5-9284-b827eb9e62be03b445c6-2e4f-11e5-9284-b827eb9e62be03b445c6-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2e4abe4c-2e4e-11e5-9284-b827eb9e62be2e4fceaa-2e4e-11e5-9284-b827eb9e62be2e4fceaa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ff242e9a-2e4e-11e5-9284-b827eb9e62beff2923aa-2e4e-11e5-9284-b827eb9e62beff2923aa-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3f53a53c-2e4e-11e5-9284-b827eb9e62be3f58b568-2e4e-11e5-9284-b827eb9e62be3f58b568-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0de8e416-2e4f-11e5-9284-b827eb9e62be0dedf276-2e4f-11e5-9284-b827eb9e62be0dedf276-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e2eac286-2e4c-11e5-9284-b827eb9e62bee2efcb3c-2e4c-11e5-9284-b827eb9e62bee2efcb3c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"bf22c4fa-2e4e-11e5-9284-b827eb9e62bebf27cbc6-2e4e-11e5-9284-b827eb9e62bebf27cbc6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"46e62a6e-2e4d-11e5-9284-b827eb9e62be46eb3130-2e4d-11e5-9284-b827eb9e62be46eb3130-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"8a92328a-2e4d-11e5-9284-b827eb9e62be8a9753aa-2e4d-11e5-9284-b827eb9e62be8a9753aa-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c77d647a-2e4e-11e5-9284-b827eb9e62bec7826286-2e4e-11e5-9284-b827eb9e62bec7826286-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e4a6d5f4-2e4e-11e5-9284-b827eb9e62bee4abe526-2e4e-11e5-9284-b827eb9e62bee4abe526-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"013d23c2-2e4e-11e5-9284-b827eb9e62be014221c4-2e4e-11e5-9284-b827eb9e62be014221c4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b9aba168-2e4e-11e5-9284-b827eb9e62beb9b0b658-2e4e-11e5-9284-b827eb9e62beb9b0b658-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"01bce9a0-2e4d-11e5-9284-b827eb9e62be01c1e7c0-2e4d-11e5-9284-b827eb9e62be01c1e7c0-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"900e5134-2e4e-11e5-9284-b827eb9e62be9013498c-2e4e-11e5-9284-b827eb9e62be9013498c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"116f80e0-2e4f-11e5-9284-b827eb9e62be117481b2-2e4f-11e5-9284-b827eb9e62be117481b2-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c869f696-2e4e-11e5-9284-b827eb9e62bec86eff42-2e4e-11e5-9284-b827eb9e62bec86eff42-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"216c7e36-2e4e-11e5-9284-b827eb9e62be217185f2-2e4e-11e5-9284-b827eb9e62be217185f2-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cf596092-2e4c-11e5-9284-b827eb9e62becf5e5d0e-2e4c-11e5-9284-b827eb9e62becf5e5d0e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5153a5ee-2e4d-11e5-9284-b827eb9e62be5158b412-2e4d-11e5-9284-b827eb9e62be5158b412-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"386a2840-2e4e-11e5-9284-b827eb9e62be386f1f08-2e4e-11e5-9284-b827eb9e62be386f1f08-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f2572fd2-2e4e-11e5-9284-b827eb9e62bef25c3e82-2e4e-11e5-9284-b827eb9e62bef25c3e82-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b782bae4-2e4d-11e5-9284-b827eb9e62beb787b300-2e4d-11e5-9284-b827eb9e62beb787b300-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1214ab76-2e4d-11e5-9284-b827eb9e62be12199e88-2e4d-11e5-9284-b827eb9e62be12199e88-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4c3ac2b2-2e4e-11e5-9284-b827eb9e62be4c3fceba-2e4e-11e5-9284-b827eb9e62be4c3fceba-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"36b97fdc-2e4e-11e5-9284-b827eb9e62be36be782a-2e4e-11e5-9284-b827eb9e62be36be782a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"23342344-2e4f-11e5-9284-b827eb9e62be23392902-2e4f-11e5-9284-b827eb9e62be23392902-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3200c212-2e4d-11e5-9284-b827eb9e62be3205bf38-2e4d-11e5-9284-b827eb9e62be3205bf38-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"826383c0-2e4d-11e5-9284-b827eb9e62be82687c90-2e4d-11e5-9284-b827eb9e62be82687c90-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"efaa892a-2e4c-11e5-9284-b827eb9e62beefafaed2-2e4c-11e5-9284-b827eb9e62beefafaed2-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"34d1a294-2e4e-11e5-9284-b827eb9e62be34d6986c-2e4e-11e5-9284-b827eb9e62be34d6986c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0ba8b1ba-2e4d-11e5-9284-b827eb9e62be0badc3a8-2e4d-11e5-9284-b827eb9e62be0badc3a8-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1e6ba630-2e4e-11e5-9284-b827eb9e62be1e70b2b0-2e4e-11e5-9284-b827eb9e62be1e70b2b0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"dead10f2-2e4c-11e5-9284-b827eb9e62bedeb93e7c-2e4c-11e5-9284-b827eb9e62bedeb93e7c-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"9e3dbf66-2e4d-11e5-9284-b827eb9e62be9e42baa2-2e4d-11e5-9284-b827eb9e62be9e42baa2-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fc7ee64e-2e4e-11e5-9284-b827eb9e62befc83f9e0-2e4e-11e5-9284-b827eb9e62befc83f9e0-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"7f1d1bb8-2e4d-11e5-9284-b827eb9e62be7f220d62-2e4d-11e5-9284-b827eb9e62be7f220d62-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"833fdcde-2e4e-11e5-9284-b827eb9e62be8344ea30-2e4e-11e5-9284-b827eb9e62be8344ea30-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c6c2d602-2e4c-11e5-9284-b827eb9e62bec6c7c68a-2e4c-11e5-9284-b827eb9e62bec6c7c68a-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"aa20dcec-2e4c-11e5-9284-b827eb9e62beaa25c9fa-2e4c-11e5-9284-b827eb9e62beaa25c9fa-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"79bcbea2-2e4e-11e5-9284-b827eb9e62be79c1c424-2e4e-11e5-9284-b827eb9e62be79c1c424-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fe373b46-2e4c-11e5-9284-b827eb9e62befe3c3420-2e4c-11e5-9284-b827eb9e62befe3c3420-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"be58d2b8-2e4d-11e5-9284-b827eb9e62bebe5dd182-2e4d-11e5-9284-b827eb9e62bebe5dd182-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"eab49294-2e4c-11e5-9284-b827eb9e62beeab9843e-2e4c-11e5-9284-b827eb9e62beeab9843e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"464721d4-2e4e-11e5-9284-b827eb9e62be464c2d50-2e4e-11e5-9284-b827eb9e62be464c2d50-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"6a9622fc-2e4d-11e5-9284-b827eb9e62be6a9b7842-2e4d-11e5-9284-b827eb9e62be6a9b7842-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2a21ef08-2e4d-11e5-9284-b827eb9e62be2a26e7ba-2e4d-11e5-9284-b827eb9e62be2a26e7ba-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"8948228a-2e4e-11e5-9284-b827eb9e62be894d302c-2e4e-11e5-9284-b827eb9e62be894d302c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2a6546ca-2e4f-11e5-9284-b827eb9e62be2a6a4c88-2e4f-11e5-9284-b827eb9e62be2a6a4c88-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"0b1be130-2e4e-11e5-9284-b827eb9e62be0b20d604-2e4e-11e5-9284-b827eb9e62be0b20d604-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"cb9c1c6e-2e4d-11e5-9284-b827eb9e62becba115fc-2e4d-11e5-9284-b827eb9e62becba115fc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fc488488-2e4d-11e5-9284-b827eb9e62befc4d748e-2e4d-11e5-9284-b827eb9e62befc4d748e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ed07b246-2e4d-11e5-9284-b827eb9e62beed0cac10-2e4d-11e5-9284-b827eb9e62beed0cac10-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"8bb3df28-2e4e-11e5-9284-b827eb9e62be8bb8e9dc-2e4e-11e5-9284-b827eb9e62be8bb8e9dc-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"29830ec4-2e4d-11e5-9284-b827eb9e62be298800e6-2e4d-11e5-9284-b827eb9e62be298800e6-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a638e9e8-2e4d-11e5-9284-b827eb9e62bea63ddf48-2e4d-11e5-9284-b827eb9e62bea63ddf48-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"db7535de-2e4e-11e5-9284-b827eb9e62bedb7a3d36-2e4e-11e5-9284-b827eb9e62bedb7a3d36-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"036dd110-2e4d-11e5-9284-b827eb9e62be0372ee98-2e4d-11e5-9284-b827eb9e62be0372ee98-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"6ab48cb0-2e4d-11e5-9284-b827eb9e62be6ab99200-2e4d-11e5-9284-b827eb9e62be6ab99200-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e58cab84-2e4d-11e5-9284-b827eb9e62bee591b8fe-2e4d-11e5-9284-b827eb9e62bee591b8fe-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"5206dba4-2e4e-11e5-9284-b827eb9e62be520c48e6-2e4e-11e5-9284-b827eb9e62be520c48e6-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"1cd2a0fe-2e4d-11e5-9284-b827eb9e62be1cd79410-2e4d-11e5-9284-b827eb9e62be1cd79410-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"3a5d3548-2e4e-11e5-9284-b827eb9e62be3a6257a8-2e4e-11e5-9284-b827eb9e62be3a6257a8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"28b1fdca-2e4d-11e5-9284-b827eb9e62be28b6ff28-2e4d-11e5-9284-b827eb9e62be28b6ff28-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"133cf33a-2e4f-11e5-9284-b827eb9e62be134203ca-2e4f-11e5-9284-b827eb9e62be134203ca-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"76fdb136-2e4d-11e5-9284-b827eb9e62be7702ab32-2e4d-11e5-9284-b827eb9e62be7702ab32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"2bdcba70-2e4e-11e5-9284-b827eb9e62be2be1cd80-2e4e-11e5-9284-b827eb9e62be2be1cd80-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"130e1c72-2e4f-11e5-9284-b827eb9e62be1313328e-2e4f-11e5-9284-b827eb9e62be1313328e-2e4f-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ebc64b82-2e4c-11e5-9284-b827eb9e62beebcb4448-2e4c-11e5-9284-b827eb9e62beebcb4448-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"a6362bc6-2e4e-11e5-9284-b827eb9e62bea63b385a-2e4e-11e5-9284-b827eb9e62bea63b385a-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"56d785ca-2e4e-11e5-9284-b827eb9e62be56dca6ea-2e4e-11e5-9284-b827eb9e62be56dca6ea-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"316fffca-2e4d-11e5-9284-b827eb9e62be3174f566-2e4d-11e5-9284-b827eb9e62be3174f566-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"f0b7e370-2e4d-11e5-9284-b827eb9e62bef0bd013e-2e4d-11e5-9284-b827eb9e62bef0bd013e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"78ec1630-2e4e-11e5-9284-b827eb9e62be78f137b4-2e4e-11e5-9284-b827eb9e62be78f137b4-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"b3784f04-2e4d-11e5-9284-b827eb9e62beb37d495a-2e4d-11e5-9284-b827eb9e62beb37d495a-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"80cd2b32-2e4e-11e5-9284-b827eb9e62be80d24d9c-2e4e-11e5-9284-b827eb9e62be80d24d9c-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"c66e4844-2e4c-11e5-9284-b827eb9e62bec6735bfe-2e4c-11e5-9284-b827eb9e62bec6735bfe-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"58529d8c-2e4d-11e5-9284-b827eb9e62be5857a64c-2e4d-11e5-9284-b827eb9e62be5857a64c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"91b2176e-2e4e-11e5-9284-b827eb9e62be91b711d8-2e4e-11e5-9284-b827eb9e62be91b711d8-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"755ef952-2e4d-11e5-9284-b827eb9e62be7563f358-2e4d-11e5-9284-b827eb9e62be7563f358-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"4a66c09a-2e4d-11e5-9284-b827eb9e62be4a6bdf9e-2e4d-11e5-9284-b827eb9e62be4a6bdf9e-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ad0232ee-2e4c-11e5-9284-b827eb9e62bead0725ce-2e4c-11e5-9284-b827eb9e62bead0725ce-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"fcd35b9e-2e4d-11e5-9284-b827eb9e62befcd85784-2e4d-11e5-9284-b827eb9e62befcd85784-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"eca3cdd0-2e4d-11e5-9284-b827eb9e62beeca8dbcc-2e4d-11e5-9284-b827eb9e62beeca8dbcc-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"edbc8db6-2e4c-11e5-9284-b827eb9e62beedc17e66-2e4c-11e5-9284-b827eb9e62beedc17e66-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"ee50676a-2e4d-11e5-9284-b827eb9e62beee55796c-2e4d-11e5-9284-b827eb9e62beee55796c-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"bb767e2a-2e4c-11e5-9284-b827eb9e62bebb7b851e-2e4c-11e5-9284-b827eb9e62bebb7b851e-2e4c-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"96761e30-2e4e-11e5-9284-b827eb9e62be967b2e16-2e4e-11e5-9284-b827eb9e62be967b2e16-2e4e-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"e1b05e02-2e4d-11e5-9284-b827eb9e62bee1b56a32-2e4d-11e5-9284-b827eb9e62bee1b56a32-2e4d-11e5-9284-b827eb9e62be<|endoftext|>"} {"text":"\/*\n * timeperiod.h - time period data entry widget\n * Program: kalarm\n * (C) 2003, 2004 by David Jarvie \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n#include \"kalarm.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \"combobox.h\"\n#include \"spinbox.h\"\n#include \"timespinbox.h\"\n#include \"timeperiod.moc\"\n\n\n\/\/ Collect these widget labels together to ensure consistent wording and\n\/\/ translations across different modules.\nQString TimePeriod::i18n_hours_mins() { return i18n(\"hours\/minutes\"); }\nQString TimePeriod::i18n_Hours_Mins() { return i18n(\"Hours\/Minutes\"); }\nQString TimePeriod::i18n_days() { return i18n(\"days\"); }\nQString TimePeriod::i18n_Days() { return i18n(\"Days\"); }\nQString TimePeriod::i18n_weeks() { return i18n(\"weeks\"); }\nQString TimePeriod::i18n_Weeks() { return i18n(\"Weeks\"); }\n\nstatic const int maxMinutes = 100*60-1; \/\/ absolute maximum value for hours:minutes = 99H59M\n\n\/*=============================================================================\n= Class TimePeriod\n= Contains a time unit combo box, plus a time spinbox, to select a time period.\n=============================================================================*\/\n\nTimePeriod::TimePeriod(bool allowHourMinute, QWidget* parent, const char* name)\n\t: QHBox(parent, name),\n\t mMaxDays(9999),\n\t mNoHourMinute(!allowHourMinute),\n\t mReadOnly(false)\n{\n\tsetSpacing(KDialog::spacingHint());\n\n\tmSpinStack = new QWidgetStack(this);\n\tmSpinBox = new SpinBox(mSpinStack);\n\tmSpinBox->setLineStep(1);\n\tmSpinBox->setLineShiftStep(10);\n\tmSpinBox->setRange(1, mMaxDays);\n\tconnect(mSpinBox, SIGNAL(valueChanged(int)), SLOT(slotDaysChanged(int)));\n\tmSpinStack->addWidget(mSpinBox, 0);\n\n\tmTimeSpinBox = new TimeSpinBox(0, 99999, mSpinStack);\n\tmTimeSpinBox->setRange(1, maxMinutes); \/\/ max 99H59M\n\tconnect(mTimeSpinBox, SIGNAL(valueChanged(int)), SLOT(slotTimeChanged(int)));\n\tmSpinStack->addWidget(mTimeSpinBox, 1);\n\n\tmSpinStack->setFixedSize(mSpinBox->sizeHint().expandedTo(mTimeSpinBox->sizeHint()));\n\tmHourMinuteRaised = mNoHourMinute;\n\tshowHourMin(!mNoHourMinute);\n\n\tmUnitsCombo = new ComboBox(false, this);\n\tif (mNoHourMinute)\n\t\tmDateOnlyOffset = 1;\n\telse\n\t{\n\t\tmDateOnlyOffset = 0;\n\t\tmUnitsCombo->insertItem(i18n_hours_mins());\n\t}\n\tmUnitsCombo->insertItem(i18n_days());\n\tmUnitsCombo->insertItem(i18n_weeks());\n\tmMaxUnitShown = WEEKS;\n\tmUnitsCombo->setFixedSize(mUnitsCombo->sizeHint());\n\tconnect(mUnitsCombo, SIGNAL(activated(int)), SLOT(slotUnitsSelected(int)));\n\n\tsetFocusProxy(mUnitsCombo);\n\tsetTabOrder(mUnitsCombo, mSpinStack);\n}\n\nvoid TimePeriod::setReadOnly(bool ro)\n{\n\tif (ro != mReadOnly)\n\t{\n\t\tmReadOnly = ro;\n\t\tmSpinBox->setReadOnly(ro);\n\t\tmTimeSpinBox->setReadOnly(ro);\n\t\tmUnitsCombo->setReadOnly(ro);\n\t}\n}\n\n\/******************************************************************************\n* Set whether the editor text is to be selected whenever spin buttons are\n* clicked. Default is to select them.\n*\/\nvoid TimePeriod::setSelectOnStep(bool sel)\n{\n\tmSpinBox->setSelectOnStep(sel);\n\tmTimeSpinBox->setSelectOnStep(sel);\n}\n\n\/******************************************************************************\n* Set the input focus on the count field.\n*\/\nvoid TimePeriod::setFocusOnCount()\n{\n\tmSpinStack->setFocus();\n}\n\n\/******************************************************************************\n* Set the maximum values for the hours:minutes and days\/weeks spinboxes.\n* If 'hourmin' = 0, the hours:minutes maximum is left unchanged.\n*\/\nvoid TimePeriod::setMaximum(int hourmin, int days)\n{\n\tint oldmins = minutes();\n\tif (hourmin > 0)\n\t{\n\t\tif (hourmin > maxMinutes)\n\t\t\thourmin = maxMinutes;\n\t\tmTimeSpinBox->setRange(1, hourmin);\n\t}\n\tmMaxDays = (days >= 0) ? days : 0;\n\tadjustDayWeekShown();\n\tsetUnitRange();\n\tint mins = minutes();\n\tif (mins != oldmins)\n\t\temit valueChanged(mins);\n}\n\n\/******************************************************************************\n * Get the specified number of minutes.\n * Reply = 0 if error.\n *\/\nint TimePeriod::minutes() const\n{\n\tswitch (mUnitsCombo->currentItem() + mDateOnlyOffset)\n\t{\n\t\tcase HOURS_MINUTES:\n\t\t\treturn mTimeSpinBox->value();\n\t\tcase DAYS:\n\t\t\treturn mSpinBox->value() * 24*60;\n\t\tcase WEEKS:\n\t\t\treturn mSpinBox->value() * 7*24*60;\n\t}\n\treturn 0;\n}\n\n\/******************************************************************************\n* Initialise the controls with a specified time period.\n* The time unit combo-box is initialised to 'defaultUnits', but if 'dateOnly'\n* is true, it will never be initialised to hours\/minutes.\n*\/\nvoid TimePeriod::setMinutes(int mins, bool dateOnly, TimePeriod::Units defaultUnits)\n{\n\tint oldmins = minutes();\n\tif (!dateOnly && mNoHourMinute)\n\t\tdateOnly = true;\n\tint item;\n\tif (mins)\n\t{\n\t\tint count = mins;\n\t\tif (mins % (24*60))\n\t\t\titem = HOURS_MINUTES;\n\t\telse if (mins % (7*24*60))\n\t\t{\n\t\t\titem = DAYS;\n\t\t\tcount = mins \/ (24*60);\n\t\t}\n\t\telse\n\t\t{\n\t\t\titem = WEEKS;\n\t\t\tcount = mins \/ (7*24*60);\n\t\t}\n\t\tif (item < mDateOnlyOffset)\n\t\t\titem = mDateOnlyOffset;\n\t\telse if (item > mMaxUnitShown)\n\t\t\titem = mMaxUnitShown;\n\t\tmUnitsCombo->setCurrentItem(item - mDateOnlyOffset);\n\t\tif (item == HOURS_MINUTES)\n\t\t\tmTimeSpinBox->setValue(count);\n\t\telse\n\t\t\tmSpinBox->setValue(count);\n\t\titem = setDateOnly(mins, dateOnly, false);\n\t}\n\telse\n\t{\n\t\titem = defaultUnits;\n\t\tif (item < mDateOnlyOffset)\n\t\t\titem = mDateOnlyOffset;\n\t\telse if (item > mMaxUnitShown)\n\t\t\titem = mMaxUnitShown;\n\t\tmUnitsCombo->setCurrentItem(item - mDateOnlyOffset);\n\t\tif (dateOnly && !mDateOnlyOffset || !dateOnly && mDateOnlyOffset)\n\t\t\titem = setDateOnly(mins, dateOnly, false);\n\t}\n\tshowHourMin(item == HOURS_MINUTES && !mNoHourMinute);\n\n\tint newmins = minutes();\n\tif (newmins != oldmins)\n\t\temit valueChanged(newmins);\n}\n\n\/******************************************************************************\n* Enable\/disable hours\/minutes units (if hours\/minutes were permitted in the\n* constructor).\n*\/\nTimePeriod::Units TimePeriod::setDateOnly(int mins, bool dateOnly, bool signal)\n{\n\tint oldmins;\n\tif (signal)\n\t\toldmins = minutes();\n\tint index = mUnitsCombo->currentItem();\n\tUnits units = static_cast(index + mDateOnlyOffset);\n\tif (!mNoHourMinute)\n\t{\n\t\tif (!dateOnly && mDateOnlyOffset)\n\t\t{\n\t\t\t\/\/ Change from date-only to allow hours\/minutes\n\t\t\tmUnitsCombo->insertItem(i18n_hours_mins(), 0);\n\t\t\tmDateOnlyOffset = 0;\n\t\t\tadjustDayWeekShown();\n\t\t\tmUnitsCombo->setCurrentItem(++index);\n\t\t}\n\t\telse if (dateOnly && !mDateOnlyOffset)\n\t\t{\n\t\t\t\/\/ Change from allowing hours\/minutes to date-only\n\t\t\tmUnitsCombo->removeItem(0);\n\t\t\tmDateOnlyOffset = 1;\n\t\t\tif (index)\n\t\t\t\t--index;\n\t\t\tadjustDayWeekShown();\n\t\t\tmUnitsCombo->setCurrentItem(index);\n\t\t\tif (units == HOURS_MINUTES)\n\t\t\t{\n\t\t\t\t\/\/ Set units to days and round up the warning period\n\t\t\t\tunits = DAYS;\n\t\t\t\tmUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset);\n\t\t\t\tmSpinBox->setValue((mins + 1439) \/ 1440);\n\t\t\t}\n\t\t\tshowHourMin(false);\n\t\t}\n\t}\n\n\tif (signal)\n\t{\n\t\tint newmins = minutes();\n\t\tif (newmins != oldmins)\n\t\t\temit valueChanged(newmins);\n\t}\n\treturn units;\n}\n\n\/******************************************************************************\n* Adjust the days\/weeks units shown to suit the maximum days limit.\n*\/\nvoid TimePeriod::adjustDayWeekShown()\n{\n\tUnits newMaxUnitShown = (mMaxDays >= 7) ? WEEKS : (mMaxDays || mDateOnlyOffset) ? DAYS : HOURS_MINUTES;\n\tif (newMaxUnitShown > mMaxUnitShown)\n\t{\n\t\tif (mMaxUnitShown < DAYS)\n\t\t\tmUnitsCombo->insertItem(i18n_days());\n\t\tif (newMaxUnitShown == WEEKS)\n\t\t\tmUnitsCombo->insertItem(i18n_weeks());\n\t}\n\telse if (newMaxUnitShown < mMaxUnitShown)\n\t{\n\t\tif (mMaxUnitShown == WEEKS)\n\t\t\tmUnitsCombo->removeItem(WEEKS - mDateOnlyOffset);\n\t\tif (newMaxUnitShown < DAYS)\n\t\t\tmUnitsCombo->removeItem(DAYS - mDateOnlyOffset);\n\t}\n\tmMaxUnitShown = newMaxUnitShown;\n}\n\n\/******************************************************************************\n* Set the maximum value which may be entered into the day\/week count field,\n* depending on the current unit selection.\n*\/\nvoid TimePeriod::setUnitRange()\n{\n\tint maxval;\n\tswitch (static_cast(mUnitsCombo->currentItem() + mDateOnlyOffset))\n\t{\n\t\tcase WEEKS:\n\t\t\tmaxval = mMaxDays \/ 7;\n\t\t\tif (maxval)\n\t\t\t\tbreak;\n\t\t\tmUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset);\n\t\t\t\/\/ fall through to DAYS\n\t\tcase DAYS:\n\t\t\tmaxval = mMaxDays ? mMaxDays : 1;\n\t\t\tbreak;\n\t\tcase HOURS_MINUTES:\n\t\tdefault:\n\t\t\treturn;\n\t}\n\tmSpinBox->setRange(1, maxval);\n}\n\n\/******************************************************************************\n* Called when a new item is made current in the time units combo box.\n*\/\nvoid TimePeriod::slotUnitsSelected(int index)\n{\n\tsetUnitRange();\n\tshowHourMin(index + mDateOnlyOffset == HOURS_MINUTES);\n\temit valueChanged(minutes());\n}\n\n\/******************************************************************************\n* Called when the value of the days\/weeks spin box changes.\n*\/\nvoid TimePeriod::slotDaysChanged(int)\n{\n\tif (!mHourMinuteRaised)\n\t\temit valueChanged(minutes());\n}\n\n\/******************************************************************************\n* Called when the value of the time spin box changes.\n*\/\nvoid TimePeriod::slotTimeChanged(int value)\n{\n\tif (mHourMinuteRaised)\n\t\temit valueChanged(value);\n}\n\n\/******************************************************************************\n * Set the currently displayed count widget.\n *\/\nvoid TimePeriod::showHourMin(bool hourMinute)\n{\n\tif (hourMinute != mHourMinuteRaised)\n\t{\n\t\tmHourMinuteRaised = hourMinute;\n\t\tif (hourMinute)\n\t\t{\n\t\t\tmSpinStack->raiseWidget(mTimeSpinBox);\n\t\t\tmSpinStack->setFocusProxy(mTimeSpinBox);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmSpinStack->raiseWidget(mSpinBox);\n\t\t\tmSpinStack->setFocusProxy(mSpinBox);\n\t\t}\n\t}\n}\n\n\/******************************************************************************\n * Set separate WhatsThis texts for the count spinboxes and the units combobox.\n * If the hours:minutes text is omitted, both spinboxes are set to the same\n * WhatsThis text.\n *\/\nvoid TimePeriod::setWhatsThis(const QString& units, const QString& dayWeek, const QString& hourMin)\n{\n\tQWhatsThis::add(mUnitsCombo, units);\n\tQWhatsThis::add(mSpinBox, dayWeek);\n\tQWhatsThis::add(mTimeSpinBox, (hourMin.isNull() ? dayWeek : hourMin));\n}\nFix compile warning\/*\n * timeperiod.h - time period data entry widget\n * Program: kalarm\n * (C) 2003, 2004 by David Jarvie \n *\n * This program is free software; you can redistribute it and\/or modify\n * it under the terms of the GNU General Public License as published by\n * the Free Software Foundation; either version 2 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.\n *\/\n\n#include \"kalarm.h\"\n\n#include \n#include \n\n#include \n#include \n\n#include \"combobox.h\"\n#include \"spinbox.h\"\n#include \"timespinbox.h\"\n#include \"timeperiod.moc\"\n\n\n\/\/ Collect these widget labels together to ensure consistent wording and\n\/\/ translations across different modules.\nQString TimePeriod::i18n_hours_mins() { return i18n(\"hours\/minutes\"); }\nQString TimePeriod::i18n_Hours_Mins() { return i18n(\"Hours\/Minutes\"); }\nQString TimePeriod::i18n_days() { return i18n(\"days\"); }\nQString TimePeriod::i18n_Days() { return i18n(\"Days\"); }\nQString TimePeriod::i18n_weeks() { return i18n(\"weeks\"); }\nQString TimePeriod::i18n_Weeks() { return i18n(\"Weeks\"); }\n\nstatic const int maxMinutes = 100*60-1; \/\/ absolute maximum value for hours:minutes = 99H59M\n\n\/*=============================================================================\n= Class TimePeriod\n= Contains a time unit combo box, plus a time spinbox, to select a time period.\n=============================================================================*\/\n\nTimePeriod::TimePeriod(bool allowHourMinute, QWidget* parent, const char* name)\n\t: QHBox(parent, name),\n\t mMaxDays(9999),\n\t mNoHourMinute(!allowHourMinute),\n\t mReadOnly(false)\n{\n\tsetSpacing(KDialog::spacingHint());\n\n\tmSpinStack = new QWidgetStack(this);\n\tmSpinBox = new SpinBox(mSpinStack);\n\tmSpinBox->setLineStep(1);\n\tmSpinBox->setLineShiftStep(10);\n\tmSpinBox->setRange(1, mMaxDays);\n\tconnect(mSpinBox, SIGNAL(valueChanged(int)), SLOT(slotDaysChanged(int)));\n\tmSpinStack->addWidget(mSpinBox, 0);\n\n\tmTimeSpinBox = new TimeSpinBox(0, 99999, mSpinStack);\n\tmTimeSpinBox->setRange(1, maxMinutes); \/\/ max 99H59M\n\tconnect(mTimeSpinBox, SIGNAL(valueChanged(int)), SLOT(slotTimeChanged(int)));\n\tmSpinStack->addWidget(mTimeSpinBox, 1);\n\n\tmSpinStack->setFixedSize(mSpinBox->sizeHint().expandedTo(mTimeSpinBox->sizeHint()));\n\tmHourMinuteRaised = mNoHourMinute;\n\tshowHourMin(!mNoHourMinute);\n\n\tmUnitsCombo = new ComboBox(false, this);\n\tif (mNoHourMinute)\n\t\tmDateOnlyOffset = 1;\n\telse\n\t{\n\t\tmDateOnlyOffset = 0;\n\t\tmUnitsCombo->insertItem(i18n_hours_mins());\n\t}\n\tmUnitsCombo->insertItem(i18n_days());\n\tmUnitsCombo->insertItem(i18n_weeks());\n\tmMaxUnitShown = WEEKS;\n\tmUnitsCombo->setFixedSize(mUnitsCombo->sizeHint());\n\tconnect(mUnitsCombo, SIGNAL(activated(int)), SLOT(slotUnitsSelected(int)));\n\n\tsetFocusProxy(mUnitsCombo);\n\tsetTabOrder(mUnitsCombo, mSpinStack);\n}\n\nvoid TimePeriod::setReadOnly(bool ro)\n{\n\tif (ro != mReadOnly)\n\t{\n\t\tmReadOnly = ro;\n\t\tmSpinBox->setReadOnly(ro);\n\t\tmTimeSpinBox->setReadOnly(ro);\n\t\tmUnitsCombo->setReadOnly(ro);\n\t}\n}\n\n\/******************************************************************************\n* Set whether the editor text is to be selected whenever spin buttons are\n* clicked. Default is to select them.\n*\/\nvoid TimePeriod::setSelectOnStep(bool sel)\n{\n\tmSpinBox->setSelectOnStep(sel);\n\tmTimeSpinBox->setSelectOnStep(sel);\n}\n\n\/******************************************************************************\n* Set the input focus on the count field.\n*\/\nvoid TimePeriod::setFocusOnCount()\n{\n\tmSpinStack->setFocus();\n}\n\n\/******************************************************************************\n* Set the maximum values for the hours:minutes and days\/weeks spinboxes.\n* If 'hourmin' = 0, the hours:minutes maximum is left unchanged.\n*\/\nvoid TimePeriod::setMaximum(int hourmin, int days)\n{\n\tint oldmins = minutes();\n\tif (hourmin > 0)\n\t{\n\t\tif (hourmin > maxMinutes)\n\t\t\thourmin = maxMinutes;\n\t\tmTimeSpinBox->setRange(1, hourmin);\n\t}\n\tmMaxDays = (days >= 0) ? days : 0;\n\tadjustDayWeekShown();\n\tsetUnitRange();\n\tint mins = minutes();\n\tif (mins != oldmins)\n\t\temit valueChanged(mins);\n}\n\n\/******************************************************************************\n * Get the specified number of minutes.\n * Reply = 0 if error.\n *\/\nint TimePeriod::minutes() const\n{\n\tswitch (mUnitsCombo->currentItem() + mDateOnlyOffset)\n\t{\n\t\tcase HOURS_MINUTES:\n\t\t\treturn mTimeSpinBox->value();\n\t\tcase DAYS:\n\t\t\treturn mSpinBox->value() * 24*60;\n\t\tcase WEEKS:\n\t\t\treturn mSpinBox->value() * 7*24*60;\n\t}\n\treturn 0;\n}\n\n\/******************************************************************************\n* Initialise the controls with a specified time period.\n* The time unit combo-box is initialised to 'defaultUnits', but if 'dateOnly'\n* is true, it will never be initialised to hours\/minutes.\n*\/\nvoid TimePeriod::setMinutes(int mins, bool dateOnly, TimePeriod::Units defaultUnits)\n{\n\tint oldmins = minutes();\n\tif (!dateOnly && mNoHourMinute)\n\t\tdateOnly = true;\n\tint item;\n\tif (mins)\n\t{\n\t\tint count = mins;\n\t\tif (mins % (24*60))\n\t\t\titem = HOURS_MINUTES;\n\t\telse if (mins % (7*24*60))\n\t\t{\n\t\t\titem = DAYS;\n\t\t\tcount = mins \/ (24*60);\n\t\t}\n\t\telse\n\t\t{\n\t\t\titem = WEEKS;\n\t\t\tcount = mins \/ (7*24*60);\n\t\t}\n\t\tif (item < mDateOnlyOffset)\n\t\t\titem = mDateOnlyOffset;\n\t\telse if (item > mMaxUnitShown)\n\t\t\titem = mMaxUnitShown;\n\t\tmUnitsCombo->setCurrentItem(item - mDateOnlyOffset);\n\t\tif (item == HOURS_MINUTES)\n\t\t\tmTimeSpinBox->setValue(count);\n\t\telse\n\t\t\tmSpinBox->setValue(count);\n\t\titem = setDateOnly(mins, dateOnly, false);\n\t}\n\telse\n\t{\n\t\titem = defaultUnits;\n\t\tif (item < mDateOnlyOffset)\n\t\t\titem = mDateOnlyOffset;\n\t\telse if (item > mMaxUnitShown)\n\t\t\titem = mMaxUnitShown;\n\t\tmUnitsCombo->setCurrentItem(item - mDateOnlyOffset);\n\t\tif (dateOnly && !mDateOnlyOffset || !dateOnly && mDateOnlyOffset)\n\t\t\titem = setDateOnly(mins, dateOnly, false);\n\t}\n\tshowHourMin(item == HOURS_MINUTES && !mNoHourMinute);\n\n\tint newmins = minutes();\n\tif (newmins != oldmins)\n\t\temit valueChanged(newmins);\n}\n\n\/******************************************************************************\n* Enable\/disable hours\/minutes units (if hours\/minutes were permitted in the\n* constructor).\n*\/\nTimePeriod::Units TimePeriod::setDateOnly(int mins, bool dateOnly, bool signal)\n{\n\tint oldmins = 0;\n\tif (signal)\n\t\toldmins = minutes();\n\tint index = mUnitsCombo->currentItem();\n\tUnits units = static_cast(index + mDateOnlyOffset);\n\tif (!mNoHourMinute)\n\t{\n\t\tif (!dateOnly && mDateOnlyOffset)\n\t\t{\n\t\t\t\/\/ Change from date-only to allow hours\/minutes\n\t\t\tmUnitsCombo->insertItem(i18n_hours_mins(), 0);\n\t\t\tmDateOnlyOffset = 0;\n\t\t\tadjustDayWeekShown();\n\t\t\tmUnitsCombo->setCurrentItem(++index);\n\t\t}\n\t\telse if (dateOnly && !mDateOnlyOffset)\n\t\t{\n\t\t\t\/\/ Change from allowing hours\/minutes to date-only\n\t\t\tmUnitsCombo->removeItem(0);\n\t\t\tmDateOnlyOffset = 1;\n\t\t\tif (index)\n\t\t\t\t--index;\n\t\t\tadjustDayWeekShown();\n\t\t\tmUnitsCombo->setCurrentItem(index);\n\t\t\tif (units == HOURS_MINUTES)\n\t\t\t{\n\t\t\t\t\/\/ Set units to days and round up the warning period\n\t\t\t\tunits = DAYS;\n\t\t\t\tmUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset);\n\t\t\t\tmSpinBox->setValue((mins + 1439) \/ 1440);\n\t\t\t}\n\t\t\tshowHourMin(false);\n\t\t}\n\t}\n\n\tif (signal)\n\t{\n\t\tint newmins = minutes();\n\t\tif (newmins != oldmins)\n\t\t\temit valueChanged(newmins);\n\t}\n\treturn units;\n}\n\n\/******************************************************************************\n* Adjust the days\/weeks units shown to suit the maximum days limit.\n*\/\nvoid TimePeriod::adjustDayWeekShown()\n{\n\tUnits newMaxUnitShown = (mMaxDays >= 7) ? WEEKS : (mMaxDays || mDateOnlyOffset) ? DAYS : HOURS_MINUTES;\n\tif (newMaxUnitShown > mMaxUnitShown)\n\t{\n\t\tif (mMaxUnitShown < DAYS)\n\t\t\tmUnitsCombo->insertItem(i18n_days());\n\t\tif (newMaxUnitShown == WEEKS)\n\t\t\tmUnitsCombo->insertItem(i18n_weeks());\n\t}\n\telse if (newMaxUnitShown < mMaxUnitShown)\n\t{\n\t\tif (mMaxUnitShown == WEEKS)\n\t\t\tmUnitsCombo->removeItem(WEEKS - mDateOnlyOffset);\n\t\tif (newMaxUnitShown < DAYS)\n\t\t\tmUnitsCombo->removeItem(DAYS - mDateOnlyOffset);\n\t}\n\tmMaxUnitShown = newMaxUnitShown;\n}\n\n\/******************************************************************************\n* Set the maximum value which may be entered into the day\/week count field,\n* depending on the current unit selection.\n*\/\nvoid TimePeriod::setUnitRange()\n{\n\tint maxval;\n\tswitch (static_cast(mUnitsCombo->currentItem() + mDateOnlyOffset))\n\t{\n\t\tcase WEEKS:\n\t\t\tmaxval = mMaxDays \/ 7;\n\t\t\tif (maxval)\n\t\t\t\tbreak;\n\t\t\tmUnitsCombo->setCurrentItem(DAYS - mDateOnlyOffset);\n\t\t\t\/\/ fall through to DAYS\n\t\tcase DAYS:\n\t\t\tmaxval = mMaxDays ? mMaxDays : 1;\n\t\t\tbreak;\n\t\tcase HOURS_MINUTES:\n\t\tdefault:\n\t\t\treturn;\n\t}\n\tmSpinBox->setRange(1, maxval);\n}\n\n\/******************************************************************************\n* Called when a new item is made current in the time units combo box.\n*\/\nvoid TimePeriod::slotUnitsSelected(int index)\n{\n\tsetUnitRange();\n\tshowHourMin(index + mDateOnlyOffset == HOURS_MINUTES);\n\temit valueChanged(minutes());\n}\n\n\/******************************************************************************\n* Called when the value of the days\/weeks spin box changes.\n*\/\nvoid TimePeriod::slotDaysChanged(int)\n{\n\tif (!mHourMinuteRaised)\n\t\temit valueChanged(minutes());\n}\n\n\/******************************************************************************\n* Called when the value of the time spin box changes.\n*\/\nvoid TimePeriod::slotTimeChanged(int value)\n{\n\tif (mHourMinuteRaised)\n\t\temit valueChanged(value);\n}\n\n\/******************************************************************************\n * Set the currently displayed count widget.\n *\/\nvoid TimePeriod::showHourMin(bool hourMinute)\n{\n\tif (hourMinute != mHourMinuteRaised)\n\t{\n\t\tmHourMinuteRaised = hourMinute;\n\t\tif (hourMinute)\n\t\t{\n\t\t\tmSpinStack->raiseWidget(mTimeSpinBox);\n\t\t\tmSpinStack->setFocusProxy(mTimeSpinBox);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tmSpinStack->raiseWidget(mSpinBox);\n\t\t\tmSpinStack->setFocusProxy(mSpinBox);\n\t\t}\n\t}\n}\n\n\/******************************************************************************\n * Set separate WhatsThis texts for the count spinboxes and the units combobox.\n * If the hours:minutes text is omitted, both spinboxes are set to the same\n * WhatsThis text.\n *\/\nvoid TimePeriod::setWhatsThis(const QString& units, const QString& dayWeek, const QString& hourMin)\n{\n\tQWhatsThis::add(mUnitsCombo, units);\n\tQWhatsThis::add(mSpinBox, dayWeek);\n\tQWhatsThis::add(mTimeSpinBox, (hourMin.isNull() ? dayWeek : hourMin));\n}\n<|endoftext|>"} {"text":"\/* -*- mode:C++; -*- *\/\n\/* MIT License -- MyThOS: The Many-Threads Operating System\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg\n *\/\n#include \"cpu\/LAPIC.hh\"\n#include \"cpu\/hwthread_pause.hh\"\n#include \"cpu\/ctrlregs.hh\"\n#include \"boot\/mlog.hh\"\n#include \"util\/assert.hh\"\n\nnamespace mythos {\n LAPIC lapic;\n\n void LAPIC::init() {\n MLOG_DETAIL(mlog::boot, \"initializing local xAPIC\");\n Register value;\n\n \/\/ init the Destination Format Register and the Logical\n \/\/ Destination Register Intel recommends to set DFR, LDR and TPR\n \/\/ before enabling an APIC. See e.g. \"AP-388 82489DX User's\n \/\/ Manual\" (Intel document number 292116).\n value = read(REG_DFR);\n MLOG_DETAIL(mlog::boot, \"APIC DFR\", DVARhex(value.value));\n value.model = 0xF; \/\/ flat mode\n write(REG_DFR, value);\n value = read(REG_LDR);\n MLOG_DETAIL(mlog::boot, \"APIC LDR\", DVARhex(value.value));\n value.destination = 1; \/\/ will not be used anyway\n write(REG_LDR, value);\n\n \/\/ init the local interrupt sources\n \/\/ all of them should be in invalid state anyway\n value.value = 0;\n value.masked = 1;\n write(REG_LVT_TIMER, value);\n write(REG_LVT_THERMAL, value);\n write(REG_LVT_PERFCNT, value);\n write(REG_LVT_LINT0, value);\n write(REG_LVT_LINT1, value);\n write(REG_LVT_ERROR, value);\n\n \/\/ enable all interrupts by task priority 0\n \/\/ see 10.8.6 Task Priority in IA-32e Mode\n \/\/ Loading the TPR with a task-priority class of 0 enables all external interrupts.\n \/\/ Loading the TPR with a task-priority class of 0FH (01111B) disables all external interrupts.\n \/\/ In 64-bit mode, software can read and write the TPR using the MOV CR8 instruction.\n value = read(REG_TASK_PRIO);\n value.task_prio_sub = 0;\n value.task_prio = 0;\n write(REG_TASK_PRIO, value);\n\n \/\/ After a crash, interrupts from previous run can still have ISR bit set.\n \/\/ Thus clear these with EndOfInterrupt.\n size_t queued = 0;\n for (size_t loops=0; loops<1000000; loops++) {\n for (size_t i=0; i<0x8; i++) queued |= read(REG_IRR + i*0x10).value;\n if (!queued) break;\n for (size_t i=0; i<0x8; i++) {\n\tvalue = read(REG_ISR + i*0x10);\n\tfor (size_t j=0; j<32; j++) {\n\t if (value.value & (1<(value.value));\n value.vector = 0xFF; \/\/ this interrupt should never be triggered anyway\n value.apic_enable = 1;\n value.focus_processor_checking = 0;\n value.eio_suppression = 0;\n MLOG_DETAIL(mlog::boot, \"SVR writing\", reinterpret_cast(value.value));\n write(REG_SVR, value);\n MLOG_DETAIL(mlog::boot, \"SVR after init\", reinterpret_cast(read(REG_SVR).value));\n\n MLOG_DETAIL(mlog::boot, \"lapic\", DVAR(x86::initialApicID()), DVAR(getId()));\n ASSERT(getId() == x86::initialApicID());\n\n \/\/ init Error register\n write(REG_ESR, 0); read(REG_ESR); \/\/ Due to the Pentium erratum 3AP.\n value = read(REG_LVT_ERROR);\n value.vector = 0xFF; \/\/ should never happen because we leave it masked\n value.masked = 1;\n write(REG_LVT_ERROR, value);\n \/\/ spec says clear errors after enabling vector.\n write(REG_ESR, 0); read(REG_ESR); \/\/ Due to the Pentium erratum 3AP.\n }\n\n void LAPIC::enablePeriodicTimer(uint8_t irq, uint32_t count) {\n MLOG_INFO(mlog::boot, \"enable periodic APIC timer\", DVAR(irq), DVAR(count));\n write(REG_TIMER_DCR, 0x0b); \/\/ divide bus clock by 0xa=128 or 0xb=1\n setInitialCount(count);\n write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(PERIODIC).masked(0).vector(irq));\n }\n\n void LAPIC::disableTimer() {\n MLOG_INFO(mlog::boot, \"disable APIC timer\");\n write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(ONESHOT).masked(1).vector(0));\n }\n\n bool LAPIC::broadcastInitIPIEdge() {\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n read(REG_ESR);\n writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_INIT, 0));\n \/\/hwthread_wait(10000);\n return true;\n }\n\n bool LAPIC::broadcastStartupIPI(size_t startIP) {\n ASSERT((startIP & 0x0FFF) == 0 && ((startIP>>12)>>8) == 0);\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n read(REG_ESR);\n writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_SIPI, uint8_t(startIP >> 12)));\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n uint32_t esr = read(REG_ESR).value & 0xEF;\n MLOG_DETAIL(mlog::boot, \"SIPI broadcast result\", DVARhex(esr));\n return true;\n }\n\n bool LAPIC::sendNMI(size_t destination) {\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n read(REG_ESR);\n writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_NMI, 0));\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n return true;\n }\n\n bool LAPIC::sendIRQ(size_t destination, uint8_t vector)\n {\n MLOG_INFO(mlog::boot, \"send IRQ:\", DVAR(destination), DVAR(vector));\n \/\/write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n \/\/read(REG_ESR);\n writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_FIXED, vector));\n \/\/write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n return true;\n }\n\n void LAPIC::writeIPI(size_t destination, Register icrlow) {\n ASSERT(destination<256);\n MLOG_DETAIL(mlog::boot, \"write ICR\", DVAR(destination), DVARhex(icrlow.value));\n\n while(read(REG_ICR_LOW).delivery_pending) hwthread_pause();\n\n write(REG_ICR_HIGH, Register().destination(destination));\n write(REG_ICR_LOW, icrlow);\n }\n\n} \/\/ namespace mythos\nQuick fix and documentation.\/* -*- mode:C++; -*- *\/\n\/* MIT License -- MyThOS: The Many-Threads Operating System\n *\n * Permission is hereby granted, free of charge, to any person\n * obtaining a copy of this software and associated documentation\n * files (the \"Software\"), to deal in the Software without\n * restriction, including without limitation the rights to use, copy,\n * modify, merge, publish, distribute, sublicense, and\/or sell copies\n * of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND\n * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS\n * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN\n * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN\n * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n * SOFTWARE.\n *\n * Copyright 2014 Randolf Rotta, Maik Krüger, and contributors, BTU Cottbus-Senftenberg\n *\/\n#include \"cpu\/LAPIC.hh\"\n#include \"cpu\/hwthread_pause.hh\"\n#include \"cpu\/ctrlregs.hh\"\n#include \"boot\/mlog.hh\"\n#include \"util\/assert.hh\"\n\nnamespace mythos {\n LAPIC lapic;\n\n void LAPIC::init() {\n MLOG_DETAIL(mlog::boot, \"initializing local xAPIC\");\n Register value;\n\n \/\/ init the Destination Format Register and the Logical\n \/\/ Destination Register Intel recommends to set DFR, LDR and TPR\n \/\/ before enabling an APIC. See e.g. \"AP-388 82489DX User's\n \/\/ Manual\" (Intel document number 292116).\n value = read(REG_DFR);\n MLOG_DETAIL(mlog::boot, \"APIC DFR\", DVARhex(value.value));\n value.model = 0xF; \/\/ flat mode\n write(REG_DFR, value);\n value = read(REG_LDR);\n MLOG_DETAIL(mlog::boot, \"APIC LDR\", DVARhex(value.value));\n value.destination = 1; \/\/ will not be used anyway\n write(REG_LDR, value);\n\n \/\/ init the local interrupt sources\n \/\/ all of them should be in invalid state anyway\n value.value = 0;\n value.masked = 1;\n write(REG_LVT_TIMER, value);\n write(REG_LVT_THERMAL, value);\n write(REG_LVT_PERFCNT, value);\n write(REG_LVT_LINT0, value);\n write(REG_LVT_LINT1, value);\n write(REG_LVT_ERROR, value);\n\n \/\/ enable all interrupts by task priority 0\n \/\/ see 10.8.6 Task Priority in IA-32e Mode\n \/\/ Loading the TPR with a task-priority class of 0 enables all external interrupts.\n \/\/ Loading the TPR with a task-priority class of 0FH (01111B) disables all external interrupts.\n \/\/ In 64-bit mode, software can read and write the TPR using the MOV CR8 instruction.\n value = read(REG_TASK_PRIO);\n value.task_prio_sub = 0;\n value.task_prio = 0;\n write(REG_TASK_PRIO, value);\n\n \/\/ After a crash, interrupts from previous run can still have ISR bit set.\n \/\/ Thus clear these with EndOfInterrupt.\n size_t queued = 0;\n for (size_t loops=0; loops<1000000; loops++) {\n for (size_t i=0; i<0x8; i++) queued |= read(REG_IRR + i*0x10).value;\n if (!queued) break;\n for (size_t i=0; i<0x8; i++) {\n\tvalue = read(REG_ISR + i*0x10);\n\tfor (size_t j=0; j<32; j++) {\n\t if (value.value & (1<(value.value));\n value.vector = 0xFF; \/\/ this interrupt should never be triggered anyway\n value.apic_enable = 1;\n value.focus_processor_checking = 0;\n value.eio_suppression = 0;\n MLOG_DETAIL(mlog::boot, \"SVR writing\", reinterpret_cast(value.value));\n write(REG_SVR, value);\n MLOG_DETAIL(mlog::boot, \"SVR after init\", reinterpret_cast(read(REG_SVR).value));\n\n MLOG_DETAIL(mlog::boot, \"lapic\", DVAR(x86::initialApicID()), DVAR(getId()));\n ASSERT(getId() == x86::initialApicID());\n\n \/\/ init Error register\n write(REG_ESR, 0); read(REG_ESR); \/\/ Due to the Pentium erratum 3AP.\n value = read(REG_LVT_ERROR);\n value.vector = 0xFF; \/\/ should never happen because we leave it masked\n value.masked = 1;\n write(REG_LVT_ERROR, value);\n \/\/ spec says clear errors after enabling vector.\n write(REG_ESR, 0); read(REG_ESR); \/\/ Due to the Pentium erratum 3AP.\n }\n\n void LAPIC::enablePeriodicTimer(uint8_t irq, uint32_t count) {\n MLOG_INFO(mlog::boot, \"enable periodic APIC timer\", DVAR(irq), DVAR(count));\n write(REG_TIMER_DCR, 0x0b); \/\/ divide bus clock by 0xa=128 or 0xb=1\n setInitialCount(count);\n write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(PERIODIC).masked(0).vector(irq));\n }\n\n void LAPIC::disableTimer() {\n MLOG_INFO(mlog::boot, \"disable APIC timer\");\n write(REG_LVT_TIMER, read(REG_LVT_TIMER).timer_mode(ONESHOT).masked(1).vector(0));\n }\n\n bool LAPIC::broadcastInitIPIEdge() {\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n read(REG_ESR);\n writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_INIT, 0));\n \/**\n * This delay must happen between `broadcastInitIPIEdge` and\n * `broadcastStartupIPI` in order for all hardware threads to\n * start on the real hardware (KNC).\n *\n * @todo How long should this delay be for a given architecture.\n * @todo Move the delay out of this low level function.\n *\/\n hwthread_wait(10000);\n return true;\n }\n\n bool LAPIC::broadcastStartupIPI(size_t startIP) {\n ASSERT((startIP & 0x0FFF) == 0 && ((startIP>>12)>>8) == 0);\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n read(REG_ESR);\n writeIPI(0, edgeIPI(ICR_DESTSHORT_NOTSELF, MODE_SIPI, uint8_t(startIP >> 12)));\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n uint32_t esr = read(REG_ESR).value & 0xEF;\n MLOG_DETAIL(mlog::boot, \"SIPI broadcast result\", DVARhex(esr));\n return true;\n }\n\n bool LAPIC::sendNMI(size_t destination) {\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n read(REG_ESR);\n writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_NMI, 0));\n write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n return true;\n }\n\n bool LAPIC::sendIRQ(size_t destination, uint8_t vector)\n {\n MLOG_INFO(mlog::boot, \"send IRQ:\", DVAR(destination), DVAR(vector));\n \/\/write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n \/\/read(REG_ESR);\n writeIPI(destination, edgeIPI(ICR_DESTSHORT_NO, MODE_FIXED, vector));\n \/\/write(REG_ESR, 0); \/\/ Be paranoid about clearing APIC errors.\n return true;\n }\n\n void LAPIC::writeIPI(size_t destination, Register icrlow) {\n ASSERT(destination<256);\n MLOG_DETAIL(mlog::boot, \"write ICR\", DVAR(destination), DVARhex(icrlow.value));\n\n while(read(REG_ICR_LOW).delivery_pending) hwthread_pause();\n\n write(REG_ICR_HIGH, Register().destination(destination));\n write(REG_ICR_LOW, icrlow);\n }\n\n} \/\/ namespace mythos\n<|endoftext|>"} {"text":"\/\/ This file is part of BlueSky\n\/\/ \n\/\/ BlueSky is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public License\n\/\/ as published by the Free Software Foundation; either version 3\n\/\/ of the License, or (at your option) any later version.\n\/\/ \n\/\/ BlueSky is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with BlueSky; if not, see .\n\n\/\/\n\/\/ C++ Implementation: bs_kernel_ston\n\/\/\n\/\/ Description:\n\/\/\n\/\/\n\/\/ Author: Гагарин Александр Владимирович , (C) 2008\n\/\/\n#include \"bs_kernel.h\"\n#include \"thread_pool.h\"\n#include \"bs_report.h\"\n#include \"bs_log_scribers.h\"\n\n\/\/#define LOKI_CLASS_LEVEL_THREADING\n#include \"loki\/Singleton.h\"\n\nusing namespace Loki;\nusing namespace std;\n\nnamespace blue_sky { namespace bs_private {\n\nstatic bool kernel_alive = false;\n\n\/*-----------------------------------------------------------------------------\n * Specific logging system wrappers\n *-----------------------------------------------------------------------------*\/\nstruct bs_log_wrapper : public bs_log\n{\n\tbs_log_wrapper ()\n\t{\n\t\tif (kernel_alive)\n\t\t{\n\t\t\tregister_signals ();\n\t\t}\n\n\t\tthis->add_channel (sp_channel (new bs_channel (OUT_LOG)));\n\t\tthis->add_channel (sp_channel (new bs_channel (ERR_LOG)));\n\n\t\tchar *c_dir = NULL;\n\t\tif (!(c_dir = getenv(\"BS_KERNEL_DIR\")))\n\t\t\tc_dir = (char *)\".\";\n\n\t\tthis->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber));\n\t\tthis->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string(\"\/blue_sky.log\"), ios::out|ios::app)));\n\t\tthis->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber));\n\t\tthis->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string(\"\/errors.log\"), ios::out|ios::app)));\n\n\t\tthis->get_locked (OUT_LOG) << output_time;\n\t\tthis->get_locked (ERR_LOG) << output_time;\n\t}\n\n\t\/\/static bool &\n\t\/\/kernel_dead ()\n\t\/\/{\n\t\/\/\tstatic bool kernel_dead_ = false;\n\n\t\/\/\treturn kernel_dead_;\n\t\/\/}\n\n\tbs_log & \n\tget_log () \n\t{\n\t\treturn *this;\n\t}\n\n\tvoid\n\tregister_signals ()\n\t{\n\t\tthis->add_signal (BS_SIGNAL_RANGE (bs_log));\n\t}\n};\n\nstruct thread_log_wrapper : public thread_log\n{\n\tthread_log_wrapper ()\n\t{\n\t}\n\n\tthread_log &\n\tget_log ()\n\t{\n\t\treturn *this;\n\t}\n\n\tvoid\n\tregister_signals ()\n\t{\n\t}\n\n\t\/\/static bool &\n\t\/\/kernel_dead ()\n\t\/\/{\n\t\/\/\tstatic bool kernel_dead_ = false;\n\n\t\/\/\treturn kernel_dead_;\n\t\/\/}\n};\n\n\/\/\/ @brief Wrapper allowing to do some initialization on first give_kernel()::Instance() call\n\/\/\/ just after the kernel class is created\nstruct wrapper_kernel {\n\n\t kernel* k_;\n\n\t kernel& (wrapper_kernel::*ref_fun_)();\n\n\t \/\/ constructor\n\t wrapper_kernel()\n\t\t : k_(new kernel), ref_fun_(&wrapper_kernel::initial_kernel_getter)\n\t {\n\t\t kernel_alive = true;\n\t }\n\n\t \/\/ normal getter - just returns kernel reference\n\t kernel& usual_kernel_getter() {\n\t\t return *k_;\n\t }\n\n\t \/\/ when kernel reference is obtained for the first time\n\t kernel& initial_kernel_getter() {\n\t\t \/\/ first switch to usual getter to avoid infinite constructor recursion during load_plugins()\n\t\t ref_fun_ = &wrapper_kernel::usual_kernel_getter;\n\t\t \/\/ initialize kernel\n\t\t k_->init();\n\n#ifdef BS_AUTOLOAD_PLUGINS\n\t\t \/\/ load plugins\n\t\t k_->LoadPlugins();\n#endif\n\t\t \/\/ return reference\n\t\t return *k_;\n\t }\n\n\t kernel& k_ref() {\n\t\treturn (this->*ref_fun_)();\n\t }\n\n\t ~wrapper_kernel() {\n\t\t\/\/ force kernel destruction\n\t\t delete k_;\n\n\t\t\/\/ signal that it is destroyed\n\t\tkernel_alive = false;\n\n\t\t\/\/bs_log_wrapper::kernel_dead () = true;\n\t\t\/\/thread_log_wrapper::kernel_dead () = true;\n\t }\n\/\/ \t\t\t kernel& k_ref() {\n\/\/ \t\t\t\t return k_;\n\/\/ \t\t\t }\n};\n\ntypedef SingletonHolder < bs_log_wrapper, CreateUsingNew, PhoenixSingleton > bs_log_holder;\ntypedef SingletonHolder < thread_log_wrapper, CreateUsingNew, PhoenixSingleton > thread_log_holder;\n\n}\t\/\/ namespace bs_private\n\n\n\/*-----------------------------------------------------------------------------\n * kernel signleton instantiation\n *-----------------------------------------------------------------------------*\/\n\/\/! multithreaded kernel singleton - disables\n\/\/typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,\n\/\/\tDefaultLifetime, ClassLevelLockable > kernel_holder;\n\n\/\/ kernel itself is fully multithreaded so we can use simple singleton\n\/\/ typedef SingletonHolder< bs_private::wrapper_kernel > kernel_holder;\n\n\/\/kernel singletone - master, fabs die after kernel dies\ntypedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,\n\tFollowIntoDeath::With< DefaultLifetime >::AsMasterLifetime > kernel_holder;\n\ntemplate< >\nBS_API kernel& singleton< kernel >::Instance()\n{\n\t\/\/cout << \"give_kernel.Instance() entered\" << endl;\n\treturn kernel_holder::Instance().k_ref();\n}\n\n\/\/! thread pool singleton\ntypedef SingletonHolder< blue_sky::worker_thread_pool, CreateUsingNew,\n\tFollowIntoDeath::AfterMaster< kernel_holder >::IsDestroyed > wtp_holder;\n\ntypedef singleton< worker_thread_pool > give_wtp;\n\ntemplate< >\nworker_thread_pool& singleton< worker_thread_pool >::Instance() {\n\treturn wtp_holder::Instance();\n}\n\n\/\/\tvoid kernel::add_task(const blue_sky::sp_com& task)\n\/\/\t{\n\/\/\t\tgive_wtp::Instance().add_command(task);\n\/\/\t}\n\n\n\/*-----------------------------------------------------------------------------\n * log singletons instantiation\n *-----------------------------------------------------------------------------*\/\ntypedef singleton bs_log_singleton;\ntypedef singleton thread_log_singleton;\n\ntemplate <> \n\tbs_log & \nsingleton ::Instance() \n{\n\treturn bs_private::bs_log_holder::Instance().get_log ();\n}\n\ntemplate <>\n\tthread_log &\nsingleton ::Instance ()\n{\n\treturn bs_private::thread_log_holder::Instance ().get_log ();\n}\n\n\tbs_log &\nkernel::get_log ()\n{\n\treturn bs_log_singleton::Instance ();\n}\n\n\tthread_log &\nkernel::get_tlog ()\n{\n\treturn thread_log_singleton::Instance ();\n}\n\n}\t\/\/ namespace blue_sky\n\n-- Safer and simplier version of commit on 20 Aug 2009\/\/ This file is part of BlueSky\n\/\/ \n\/\/ BlueSky is free software; you can redistribute it and\/or\n\/\/ modify it under the terms of the GNU Lesser General Public License\n\/\/ as published by the Free Software Foundation; either version 3\n\/\/ of the License, or (at your option) any later version.\n\/\/ \n\/\/ BlueSky is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/ \n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with BlueSky; if not, see .\n\n\/\/\n\/\/ C++ Implementation: bs_kernel_ston\n\/\/\n\/\/ Description:\n\/\/\n\/\/\n\/\/ Author: Гагарин Александр Владимирович , (C) 2008\n\/\/\n#include \"bs_kernel.h\"\n#include \"thread_pool.h\"\n#include \"bs_report.h\"\n#include \"bs_log_scribers.h\"\n\n\/\/#define LOKI_CLASS_LEVEL_THREADING\n#include \"loki\/Singleton.h\"\n\nusing namespace Loki;\nusing namespace std;\n\nnamespace blue_sky { namespace bs_private {\n\nstatic bool kernel_alive = false;\n\n\/*-----------------------------------------------------------------------------\n * Specific logging system wrappers\n *-----------------------------------------------------------------------------*\/\nstruct bs_log_wrapper : public bs_log\n{\n\tbs_log_wrapper ()\n\t{\n\t\tif (kernel_alive)\n\t\t{\n\t\t\tregister_signals ();\n\t\t}\n\n\t\tthis->add_channel (sp_channel (new bs_channel (OUT_LOG)));\n\t\tthis->add_channel (sp_channel (new bs_channel (ERR_LOG)));\n\n\t\tchar *c_dir = NULL;\n\t\tif (!(c_dir = getenv(\"BS_KERNEL_DIR\")))\n\t\t\tc_dir = (char *)\".\";\n\n\t\tthis->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber));\n\t\tthis->get_locked (OUT_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string(\"\/blue_sky.log\"), ios::out|ios::app)));\n\t\tthis->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::cout_scriber));\n\t\tthis->get_locked (ERR_LOG).get_channel ()->attach(sp_stream(new log::detail::file_scriber (string(c_dir) + string(\"\/errors.log\"), ios::out|ios::app)));\n\n\t\tthis->get_locked (OUT_LOG) << output_time;\n\t\tthis->get_locked (ERR_LOG) << output_time;\n\t}\n\n\t\/\/static bool &\n\t\/\/kernel_dead ()\n\t\/\/{\n\t\/\/\tstatic bool kernel_dead_ = false;\n\n\t\/\/\treturn kernel_dead_;\n\t\/\/}\n\n\tbs_log & \n\tget_log () \n\t{\n\t\treturn *this;\n\t}\n\n\tvoid\n\tregister_signals ()\n\t{\n\t\tthis->add_signal (BS_SIGNAL_RANGE (bs_log));\n\t}\n};\n\nstruct thread_log_wrapper : public thread_log\n{\n\tthread_log_wrapper ()\n\t{\n\t}\n\n\tthread_log &\n\tget_log ()\n\t{\n\t\treturn *this;\n\t}\n\n\tvoid\n\tregister_signals ()\n\t{\n\t}\n\n\t\/\/static bool &\n\t\/\/kernel_dead ()\n\t\/\/{\n\t\/\/\tstatic bool kernel_dead_ = false;\n\n\t\/\/\treturn kernel_dead_;\n\t\/\/}\n};\n\n\/\/\/ @brief Wrapper allowing to do some initialization on first give_kernel()::Instance() call\n\/\/\/ just after the kernel class is created\nstruct wrapper_kernel {\n\tkernel k_;\n\n\tkernel& (wrapper_kernel::*ref_fun_)();\n\n\t\/\/ constructor\n\twrapper_kernel()\n\t\t: ref_fun_(&wrapper_kernel::initial_kernel_getter)\n\t{\n\t\tkernel_alive = true;\n\t}\n\n\t\/\/ normal getter - just returns kernel reference\n\tkernel& usual_kernel_getter() {\n\t\treturn k_;\n\t}\n\n\t\/\/ when kernel reference is obtained for the first time\n\tkernel& initial_kernel_getter() {\n\t\t\/\/ first switch to usual getter to avoid infinite constructor recursion during load_plugins()\n\t\tref_fun_ = &wrapper_kernel::usual_kernel_getter;\n\t\t\/\/ initialize kernel\n\t\tk_.init();\n\n#ifdef BS_AUTOLOAD_PLUGINS\n\t\t\/\/ load plugins\n\t\tk_.LoadPlugins();\n#endif\n\t\t\/\/ return reference\n\t\treturn k_;\n\t}\n\n\tkernel& k_ref() {\n\t\treturn (this->*ref_fun_)();\n\t}\n\n\t~wrapper_kernel() {\n\t\t\/\/ signal that it is destroyed\n\t\tkernel_alive = false;\n\n\t\t\/\/bs_log_wrapper::kernel_dead () = true;\n\t\t\/\/thread_log_wrapper::kernel_dead () = true;\n\t}\n\t\/\/kernel& k_ref() {\n\t\/\/ return k_;\n\t\/\/}\n};\n\ntypedef SingletonHolder < bs_log_wrapper, CreateUsingNew, PhoenixSingleton > bs_log_holder;\ntypedef SingletonHolder < thread_log_wrapper, CreateUsingNew, PhoenixSingleton > thread_log_holder;\n\n}\t\/\/ namespace bs_private\n\n\n\/*-----------------------------------------------------------------------------\n * kernel signleton instantiation\n *-----------------------------------------------------------------------------*\/\n\/\/! multithreaded kernel singleton - disables\n\/\/typedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,\n\/\/\tDefaultLifetime, ClassLevelLockable > kernel_holder;\n\n\/\/ kernel itself is fully multithreaded so we can use simple singleton\n\/\/ typedef SingletonHolder< bs_private::wrapper_kernel > kernel_holder;\n\n\/\/kernel singletone - master, fabs die after kernel dies\ntypedef SingletonHolder< bs_private::wrapper_kernel, CreateUsingNew,\n\tFollowIntoDeath::With< DefaultLifetime >::AsMasterLifetime > kernel_holder;\n\ntemplate< >\nBS_API kernel& singleton< kernel >::Instance()\n{\n\t\/\/cout << \"give_kernel.Instance() entered\" << endl;\n\treturn kernel_holder::Instance().k_ref();\n}\n\n\/\/! thread pool singleton\ntypedef SingletonHolder< blue_sky::worker_thread_pool, CreateUsingNew,\n\tFollowIntoDeath::AfterMaster< kernel_holder >::IsDestroyed > wtp_holder;\n\ntypedef singleton< worker_thread_pool > give_wtp;\n\ntemplate< >\nworker_thread_pool& singleton< worker_thread_pool >::Instance() {\n\treturn wtp_holder::Instance();\n}\n\n\/\/\tvoid kernel::add_task(const blue_sky::sp_com& task)\n\/\/\t{\n\/\/\t\tgive_wtp::Instance().add_command(task);\n\/\/\t}\n\n\n\/*-----------------------------------------------------------------------------\n * log singletons instantiation\n *-----------------------------------------------------------------------------*\/\ntypedef singleton bs_log_singleton;\ntypedef singleton thread_log_singleton;\n\ntemplate <> \n\tbs_log & \nsingleton ::Instance() \n{\n\treturn bs_private::bs_log_holder::Instance().get_log ();\n}\n\ntemplate <>\n\tthread_log &\nsingleton ::Instance ()\n{\n\treturn bs_private::thread_log_holder::Instance ().get_log ();\n}\n\n\tbs_log &\nkernel::get_log ()\n{\n\treturn bs_log_singleton::Instance ();\n}\n\n\tthread_log &\nkernel::get_tlog ()\n{\n\treturn thread_log_singleton::Instance ();\n}\n\n}\t\/\/ namespace blue_sky\n\n<|endoftext|>"} {"text":"\/* Copyright 2009 Klarälvdalens Datakonsult AB\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*\/\n#include \"importarchivedialog.h\"\n\n#include \"kmfolder.h\"\n#include \"folderrequester.h\"\n#include \"kmmainwidget.h\"\n#include \"importjob.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace KMail;\n\nImportArchiveDialog::ImportArchiveDialog( QWidget *parent )\n : KDialog( parent ), mParentWidget( parent )\n{\n setObjectName( \"archive_folder_dialog\" );\n setCaption( i18n( \"Archive Folder\" ) );\n setButtons( Ok|Cancel );\n setDefaultButton( Ok );\n setModal( true );\n QWidget *mainWidget = new QWidget( this );\n QGridLayout *mainLayout = new QGridLayout( mainWidget );\n mainLayout->setSpacing( KDialog::spacingHint() );\n mainLayout->setMargin( KDialog::marginHint() );\n setMainWidget( mainWidget );\n\n int row = 0;\n\n \/\/ TODO: Explaination label\n \/\/ TODO: Use QFormLayout in KDE4\n \/\/ TODO: better label for \"Ok\" button\n\n QLabel *folderLabel = new QLabel( i18n( \"Folder:\" ), mainWidget );\n mainLayout->addWidget( folderLabel, row, 0 );\n mFolderRequester = new FolderRequester( mainWidget );\n mFolderRequester->setFolderTree( kmkernel->getKMMainWidget()->mainFolderView() );\n mainLayout->addWidget( mFolderRequester, row, 1 );\n row++;\n\n QLabel *fileNameLabel = new QLabel( i18n( \"Archive File:\" ), mainWidget );\n mainLayout->addWidget( fileNameLabel, row, 0 );\n mUrlRequester = new KUrlRequester( mainWidget );\n mUrlRequester->setMode( KFile::LocalOnly );\n mUrlRequester->setFilter( \"*.tar *.zip *.tar.gz *.tar.bz2\" );\n mainLayout->addWidget( mUrlRequester, row, 1 );\n row++;\n\n \/\/ TODO: what's this, tooltips\n\n mainLayout->setColumnStretch( 1, 1 );\n mainLayout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding ), row, 0 );\n\n \/\/ Make it a bit bigger, else the folder requester cuts off the text too early\n resize( 500, minimumSize().height() );\n}\n\nvoid ImportArchiveDialog::setFolder( KMFolder *defaultFolder )\n{\n mFolderRequester->setFolder( defaultFolder );\n}\n\nvoid ImportArchiveDialog::slotOk()\n{\n if ( !QFile::exists( mUrlRequester->url().path() ) ) {\n KMessageBox::information( this, i18n( \"Please select an archive file that should be imported.\" ),\n i18n( \"No archive file selected\" ) );\n return;\n }\n\n if ( !mFolderRequester->folder() ) {\n KMessageBox::information( this, i18n( \"Please select the folder where the archive should be imported to.\" ),\n i18n( \"No target folder selected\" ) );\n return;\n }\n\n \/\/ TODO: check if url is empty. or better yet, disable ok button until file is chosen\n\n ImportJob *importJob = new KMail::ImportJob( mParentWidget );\n importJob->setFile( mUrlRequester->url() );\n importJob->setRootFolder( mFolderRequester->folder() );\n importJob->start();\n accept();\n}\n\n#include \"importarchivedialog.moc\"\nSVN_MERGE Merged revisions 1048289 via svnmerge from svn+ssh:\/\/tmcguire@svn.kde.org\/home\/kde\/branches\/kdepim\/enterprise4\/kdepim\/* Copyright 2009 Klarälvdalens Datakonsult AB\n\n This program is free software; you can redistribute it and\/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation; either version 2 of\n the License or (at your option) version 3 or any later version\n accepted by the membership of KDE e.V. (or its successor approved\n by the membership of KDE e.V.), which shall act as a proxy\n defined in Section 14 of version 3 of the license.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program. If not, see .\n*\/\n#include \"importarchivedialog.h\"\n\n#include \"kmfolder.h\"\n#include \"folderrequester.h\"\n#include \"kmmainwidget.h\"\n#include \"importjob.h\"\n\n#include \n#include \n#include \n\n#include \n#include \n\nusing namespace KMail;\n\nImportArchiveDialog::ImportArchiveDialog( QWidget *parent )\n : KDialog( parent ), mParentWidget( parent )\n{\n setObjectName( \"import_archive_dialog\" );\n setCaption( i18n( \"Import Archive\" ) );\n setButtons( Ok|Cancel );\n setDefaultButton( Ok );\n setModal( true );\n QWidget *mainWidget = new QWidget( this );\n QGridLayout *mainLayout = new QGridLayout( mainWidget );\n mainLayout->setSpacing( KDialog::spacingHint() );\n mainLayout->setMargin( KDialog::marginHint() );\n setMainWidget( mainWidget );\n\n int row = 0;\n\n \/\/ TODO: Explaination label\n \/\/ TODO: Use QFormLayout in KDE4\n \/\/ TODO: better label for \"Ok\" button\n\n QLabel *folderLabel = new QLabel( i18n( \"Folder:\" ), mainWidget );\n mainLayout->addWidget( folderLabel, row, 0 );\n mFolderRequester = new FolderRequester( mainWidget );\n mFolderRequester->setFolderTree( kmkernel->getKMMainWidget()->mainFolderView() );\n mainLayout->addWidget( mFolderRequester, row, 1 );\n row++;\n\n QLabel *fileNameLabel = new QLabel( i18n( \"Archive File:\" ), mainWidget );\n mainLayout->addWidget( fileNameLabel, row, 0 );\n mUrlRequester = new KUrlRequester( mainWidget );\n mUrlRequester->setMode( KFile::LocalOnly );\n mUrlRequester->setFilter( \"*.tar *.zip *.tar.gz *.tar.bz2\" );\n mainLayout->addWidget( mUrlRequester, row, 1 );\n row++;\n\n \/\/ TODO: what's this, tooltips\n\n mainLayout->setColumnStretch( 1, 1 );\n mainLayout->addItem( new QSpacerItem( 1, 1, QSizePolicy::Expanding, QSizePolicy::Expanding ), row, 0 );\n\n \/\/ Make it a bit bigger, else the folder requester cuts off the text too early\n resize( 500, minimumSize().height() );\n}\n\nvoid ImportArchiveDialog::setFolder( KMFolder *defaultFolder )\n{\n mFolderRequester->setFolder( defaultFolder );\n}\n\nvoid ImportArchiveDialog::slotOk()\n{\n if ( !QFile::exists( mUrlRequester->url().path() ) ) {\n KMessageBox::information( this, i18n( \"Please select an archive file that should be imported.\" ),\n i18n( \"No archive file selected\" ) );\n return;\n }\n\n if ( !mFolderRequester->folder() ) {\n KMessageBox::information( this, i18n( \"Please select the folder where the archive should be imported to.\" ),\n i18n( \"No target folder selected\" ) );\n return;\n }\n\n \/\/ TODO: check if url is empty. or better yet, disable ok button until file is chosen\n\n ImportJob *importJob = new KMail::ImportJob( mParentWidget );\n importJob->setFile( mUrlRequester->url() );\n importJob->setRootFolder( mFolderRequester->folder() );\n importJob->start();\n accept();\n}\n\n#include \"importarchivedialog.moc\"\n<|endoftext|>"} {"text":"\/* KPilot\n**\n** Copyright (C) 1998-2001 by Dan Pilone\n** Copyright (C) 2003-2004 Reinhold Kainhofer \n**\n** This is all of KPilot's config-handling stuff.\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include \"options.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kpilotSettings.h\"\n#include \"kpilotConfig.h\"\n\n\n\/\/ This is a number indicating what configuration version\n\/\/ we're dealing with. Whenever new configuration options are\n\/\/ added that make it imperative for the user to take a\n\/\/ look at the configuration of KPilot (for example the\n\/\/ skipDB setting really needs user attention) we can change\n\/\/ (increase) this number.\n\/\/\n\/\/\n\/* static *\/ const uint KPilotConfig::ConfigurationVersion = 443;\n\n\/* static *\/ int KPilotConfig::getConfigVersion()\n{\n\tFUNCTIONSETUP;\n\n\tuint version = KPilotSettings::configVersion();\n\n\tif (version < ConfigurationVersion)\n\t{\n\t\tWARNINGKPILOT << \"Config file has old version \" << version << endl;\n\t}\n\telse\n\t{\n#ifdef DEBUG\n\t\tDEBUGKPILOT << fname\n\t\t\t<< \": Config file has version \" << version << endl;\n#endif\n\t}\n\n\treturn version;\n}\n\n\/* static *\/ void KPilotConfig::updateConfigVersion()\n{\n\tFUNCTIONSETUP;\n\tKPilotSettings::setConfigVersion( ConfigurationVersion );\n}\n\n\/* static *\/ QString KPilotConfig::getDefaultDBPath()\n{\n\tFUNCTIONSETUP;\n\tQString lastUser = KPilotSettings::userName();\n\tQString dbsubpath = CSL1(\"kpilot\/DBBackup\/\");\n\tQString defaultDBPath = KGlobal::dirs()->\n\t\tsaveLocation(\"data\", dbsubpath + lastUser + CSL1(\"\/\"));\n\treturn defaultDBPath;\n}\n\n\/* static *\/ int KPilotConfig::getDebugLevel(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\tif (p)\n\t{\n\t\tif (p->isSet(\"debug\"))\n\t\t{\n\t\t\tdebug_level = p->getOption(\"debug\").toInt();\n\t\t}\n\t}\n\n\treturn debug_level;\n}\n\nstatic QFont *thefont = 0L;\n\n\/* static *\/ const QFont & KPilotConfig::fixed()\n{\n\tFUNCTIONSETUP;\n\n\tif (!thefont)\n\t\tthefont = new QFont(KGlobalSettings::fixedFont());\n\n\treturn *thefont;\n}\n\n\nvoid KPilotConfig::addDirtyDatabase(QString db)\n{\n\tFUNCTIONSETUP;\n\tQStringList l(KPilotSettings::dirtyDatabases());\n\tif (!l.contains(db))\n\t{\n\t\tl.append(db);\n\t\tKPilotSettings::setDirtyDatabases(l);\n\t}\n}\n\n\nvoid KPilotConfig::addAppBlockChangedDatabase(QString db)\n{\n\tQStringList l(KPilotSettings::appBlockChangedDatabases());\n\tif (!l.contains(db))\n\t{\n\t\tl.append(db);\n\t\tKPilotSettings::setAppBlockChangedDatabases(l);\n\t}\n}\n\nvoid KPilotConfig::addFlagsChangedDatabase(QString db)\n{\n\tQStringList l(KPilotSettings::flagsChangedDatabases());\n\tif (!l.contains(db))\n\t{\n\t\tl.append(db);\n\t\tKPilotSettings::setFlagsChangedDatabases(l);\n\t}\n}\n\n\n\n\n\/* static *\/ QString KPilotConfig::versionDetails(int fileversion, bool run)\n{\n\tFUNCTIONSETUP;\n\tQString s = CSL1(\"

\");\n\ts += i18n(\"The configuration file is outdated.\");\n\ts += ' ';\n\ts += i18n(\"The configuration file has version %1, while KPilot \"\n\t\t\"needs version %2.\").arg(fileversion).arg(ConfigurationVersion);\n\tif (run)\n\t{\n\t\ts += ' ';\n\t\ts += i18n(\"Please run KPilot and check the configuration carefully \"\n\t\t\t\"to update the file.\");\n\t}\n\ts += CSL1(\"<\/p>

\");\n\ts += i18n(\"Important changes to watch for are:\");\n\ts += ' ';\n\tif (fileversion < 440)\n\t{\n\t\ts += i18n(\"Renamed conduits, Kroupware and file installer have \"\n\t\t\t\"been made conduits as well.\");\n\t\ts += ' ';\n\t\ts += i18n(\"Conflict resolution is now a global setting.\");\n\t\ts += ' ';\n\t}\n\tif (fileversion < 443)\n\t{\n\t\ts += i18n(\"Changed format of no-backup databases.\");\n\t\ts += ' ';\n\t}\n\t\/\/ Insert more recent additions here\n\n\n\treturn s;\n}\n\n\/* static *\/ void KPilotConfig::sorryVersionOutdated(int fileversion)\n{\n\tFUNCTIONSETUP;\n\tKMessageBox::detailedSorry(0L,\n\t\ti18n(\"The configuration file for KPilot is out-of \"\n\t\t\t\"date. Please run KPilot to update it.\"),\n\t\tKPilotConfig::versionDetails(fileversion,true),\n\t\ti18n(\"Configuration File Out-of Date\"));\n}\n\n\n\/* static *\/ KPilotConfig::RunMode KPilotConfig::interactiveUpdate()\n{\n\tFUNCTIONSETUP;\n\n\tint res = 0;\n\tunsigned int fileVersion = KPilotSettings::configVersion();\n\t\/\/ FIXME better config handling -> Move the config entries using kconf_update\n\n\t\/\/ It's OK if we're already at the required level.\n\tif (fileVersion >= KPilotConfig::ConfigurationVersion)\n\t{\n\t\treturn Normal;\n\t}\n\n\tif (0 == fileVersion) \/\/ No config file at all\n\t{\n\t\tres = KMessageBox::questionYesNoCancel(0L,\n\t\t\ti18n(\"KPilot is not configured for use. You may use \"\n\t\t\t\t\"the configuration wizard or the normal configure dialog \"\n\t\t\t\t\"to configure KPilot.\"),\n\t\t\ti18n(\"Not Configured\"),\n\t\t\tKGuiItem(i18n(\"Use &Wizard\")),\n\t\t\tKGuiItem(i18n(\"Use &Dialog\")));\n\t\tif (res == KMessageBox::Yes) return WizardAndContinue;\n\t\tif (res == KMessageBox::No) return ConfigureAndContinue;\n\n\t\treturn Cancel;\n\t}\n\n\tres = KMessageBox::warningContinueCancel(0L,\n\t\ti18n(\"The configuration file for KPilot is out-of \"\n\t\t\t\"date. KPilot can update some parts of the \"\n\t\t\t\"configuration automatically. Do you wish to \"\n\t\t\t\"continue?\"),\n\t\ti18n(\"Configuration File Out-of Date\"));\n\tif (res!=KMessageBox::Continue) return Cancel;\n\n\tDEBUGKPILOT << fname << \": Updating from \"\n\t\t<< fileVersion << \" to \" << ConfigurationVersion << endl;\n\n\tKPilotConfig::updateConfigVersion();\n\tKPilotSettings::writeConfig();\n\treturn ConfigureAndContinue;\n}\n\nvoid KPilotConfig::sync()\n{\n\tKPilotSettings::self()->config()->sync();\n}\nFix i18n\/* KPilot\n**\n** Copyright (C) 1998-2001 by Dan Pilone\n** Copyright (C) 2003-2004 Reinhold Kainhofer \n**\n** This is all of KPilot's config-handling stuff.\n*\/\n\n\/*\n** This program is free software; you can redistribute it and\/or modify\n** it under the terms of the GNU General Public License as published by\n** the Free Software Foundation; either version 2 of the License, or\n** (at your option) any later version.\n**\n** This program is distributed in the hope that it will be useful,\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n** GNU General Public License for more details.\n**\n** You should have received a copy of the GNU General Public License\n** along with this program in a file called COPYING; if not, write to\n** the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,\n** MA 02110-1301, USA.\n*\/\n\n\/*\n** Bug reports and questions can be sent to kde-pim@kde.org\n*\/\n\n#include \"options.h\"\n\n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"kpilotSettings.h\"\n#include \"kpilotConfig.h\"\n\n\n\/\/ This is a number indicating what configuration version\n\/\/ we're dealing with. Whenever new configuration options are\n\/\/ added that make it imperative for the user to take a\n\/\/ look at the configuration of KPilot (for example the\n\/\/ skipDB setting really needs user attention) we can change\n\/\/ (increase) this number.\n\/\/\n\/\/\n\/* static *\/ const uint KPilotConfig::ConfigurationVersion = 443;\n\n\/* static *\/ int KPilotConfig::getConfigVersion()\n{\n\tFUNCTIONSETUP;\n\n\tuint version = KPilotSettings::configVersion();\n\n\tif (version < ConfigurationVersion)\n\t{\n\t\tWARNINGKPILOT << \"Config file has old version \" << version << endl;\n\t}\n\telse\n\t{\n#ifdef DEBUG\n\t\tDEBUGKPILOT << fname\n\t\t\t<< \": Config file has version \" << version << endl;\n#endif\n\t}\n\n\treturn version;\n}\n\n\/* static *\/ void KPilotConfig::updateConfigVersion()\n{\n\tFUNCTIONSETUP;\n\tKPilotSettings::setConfigVersion( ConfigurationVersion );\n}\n\n\/* static *\/ QString KPilotConfig::getDefaultDBPath()\n{\n\tFUNCTIONSETUP;\n\tQString lastUser = KPilotSettings::userName();\n\tQString dbsubpath = CSL1(\"kpilot\/DBBackup\/\");\n\tQString defaultDBPath = KGlobal::dirs()->\n\t\tsaveLocation(\"data\", dbsubpath + lastUser + CSL1(\"\/\"));\n\treturn defaultDBPath;\n}\n\n\/* static *\/ int KPilotConfig::getDebugLevel(KCmdLineArgs *p)\n{\n\tFUNCTIONSETUP;\n\n\tif (p)\n\t{\n\t\tif (p->isSet(\"debug\"))\n\t\t{\n\t\t\tdebug_level = p->getOption(\"debug\").toInt();\n\t\t}\n\t}\n\n\treturn debug_level;\n}\n\nstatic QFont *thefont = 0L;\n\n\/* static *\/ const QFont & KPilotConfig::fixed()\n{\n\tFUNCTIONSETUP;\n\n\tif (!thefont)\n\t\tthefont = new QFont(KGlobalSettings::fixedFont());\n\n\treturn *thefont;\n}\n\n\nvoid KPilotConfig::addDirtyDatabase(QString db)\n{\n\tFUNCTIONSETUP;\n\tQStringList l(KPilotSettings::dirtyDatabases());\n\tif (!l.contains(db))\n\t{\n\t\tl.append(db);\n\t\tKPilotSettings::setDirtyDatabases(l);\n\t}\n}\n\n\nvoid KPilotConfig::addAppBlockChangedDatabase(QString db)\n{\n\tQStringList l(KPilotSettings::appBlockChangedDatabases());\n\tif (!l.contains(db))\n\t{\n\t\tl.append(db);\n\t\tKPilotSettings::setAppBlockChangedDatabases(l);\n\t}\n}\n\nvoid KPilotConfig::addFlagsChangedDatabase(QString db)\n{\n\tQStringList l(KPilotSettings::flagsChangedDatabases());\n\tif (!l.contains(db))\n\t{\n\t\tl.append(db);\n\t\tKPilotSettings::setFlagsChangedDatabases(l);\n\t}\n}\n\n\n\n\n\/* static *\/ QString KPilotConfig::versionDetails(int fileversion, bool run)\n{\n\tFUNCTIONSETUP;\n\tQString s = CSL1(\"

\");\n\ts += i18n(\"The configuration file is outdated.\");\n\ts += ' ';\n\ts += i18n(\"The configuration file has version %1, while KPilot \"\n\t\t\"needs version %2.\",fileversion,ConfigurationVersion);\n\tif (run)\n\t{\n\t\ts += ' ';\n\t\ts += i18n(\"Please run KPilot and check the configuration carefully \"\n\t\t\t\"to update the file.\");\n\t}\n\ts += CSL1(\"<\/p>

\");\n\ts += i18n(\"Important changes to watch for are:\");\n\ts += ' ';\n\tif (fileversion < 440)\n\t{\n\t\ts += i18n(\"Renamed conduits, Kroupware and file installer have \"\n\t\t\t\"been made conduits as well.\");\n\t\ts += ' ';\n\t\ts += i18n(\"Conflict resolution is now a global setting.\");\n\t\ts += ' ';\n\t}\n\tif (fileversion < 443)\n\t{\n\t\ts += i18n(\"Changed format of no-backup databases.\");\n\t\ts += ' ';\n\t}\n\t\/\/ Insert more recent additions here\n\n\n\treturn s;\n}\n\n\/* static *\/ void KPilotConfig::sorryVersionOutdated(int fileversion)\n{\n\tFUNCTIONSETUP;\n\tKMessageBox::detailedSorry(0L,\n\t\ti18n(\"The configuration file for KPilot is out-of \"\n\t\t\t\"date. Please run KPilot to update it.\"),\n\t\tKPilotConfig::versionDetails(fileversion,true),\n\t\ti18n(\"Configuration File Out-of Date\"));\n}\n\n\n\/* static *\/ KPilotConfig::RunMode KPilotConfig::interactiveUpdate()\n{\n\tFUNCTIONSETUP;\n\n\tint res = 0;\n\tunsigned int fileVersion = KPilotSettings::configVersion();\n\t\/\/ FIXME better config handling -> Move the config entries using kconf_update\n\n\t\/\/ It's OK if we're already at the required level.\n\tif (fileVersion >= KPilotConfig::ConfigurationVersion)\n\t{\n\t\treturn Normal;\n\t}\n\n\tif (0 == fileVersion) \/\/ No config file at all\n\t{\n\t\tres = KMessageBox::questionYesNoCancel(0L,\n\t\t\ti18n(\"KPilot is not configured for use. You may use \"\n\t\t\t\t\"the configuration wizard or the normal configure dialog \"\n\t\t\t\t\"to configure KPilot.\"),\n\t\t\ti18n(\"Not Configured\"),\n\t\t\tKGuiItem(i18n(\"Use &Wizard\")),\n\t\t\tKGuiItem(i18n(\"Use &Dialog\")));\n\t\tif (res == KMessageBox::Yes) return WizardAndContinue;\n\t\tif (res == KMessageBox::No) return ConfigureAndContinue;\n\n\t\treturn Cancel;\n\t}\n\n\tres = KMessageBox::warningContinueCancel(0L,\n\t\ti18n(\"The configuration file for KPilot is out-of \"\n\t\t\t\"date. KPilot can update some parts of the \"\n\t\t\t\"configuration automatically. Do you wish to \"\n\t\t\t\"continue?\"),\n\t\ti18n(\"Configuration File Out-of Date\"));\n\tif (res!=KMessageBox::Continue) return Cancel;\n\n\tDEBUGKPILOT << fname << \": Updating from \"\n\t\t<< fileVersion << \" to \" << ConfigurationVersion << endl;\n\n\tKPilotConfig::updateConfigVersion();\n\tKPilotSettings::writeConfig();\n\treturn ConfigureAndContinue;\n}\n\nvoid KPilotConfig::sync()\n{\n\tKPilotSettings::self()->config()->sync();\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dicimp.hxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: rt $ $Date: 2005-09-07 19:50:36 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_DICIMP_HXX_\n#define _LINGUISTIC_DICIMP_HXX_\n\n#include \n#include \n#include \n#include \n\n#include \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include \/\/ helper for implementations\n#include \/\/ helper for implementations\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include \n#endif\n\n#ifndef _STRING_HXX\n#include \n#endif\n\n#include \"misc.hxx\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define DIC_MAX_ENTRIES 2000\n\nint GetDicVersion( const sal_Char *pVerStr );\nconst String GetDicExtension();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass DictionaryNeo :\n public ::cppu::WeakImplHelper3\n <\n ::com::sun::star::linguistic2::XDictionary1,\n ::com::sun::star::linguistic2::XDictionary,\n ::com::sun::star::frame::XStorable\n >\n{\n\n ::cppu::OInterfaceContainerHelper aDicEvtListeners;\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > > aEntries;\n ::rtl::OUString aDicName;\n ::rtl::OUString aMainURL;\n ::com::sun::star::linguistic2::DictionaryType eDicType;\n INT16 nCount;\n INT16 nLanguage;\n INT16 nDicVersion;\n BOOL bNeedEntries;\n BOOL bIsModified;\n BOOL bIsActive;\n BOOL bIsReadonly;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n DictionaryNeo(const DictionaryNeo &);\n DictionaryNeo & operator = (const DictionaryNeo &);\n\n void launchEvent(INT16 nEvent,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > xEntry);\n\n ULONG loadEntries(const ::rtl::OUString &rMainURL);\n ULONG saveEntries(const ::rtl::OUString &rMainURL);\n int cmpDicEntry(const ::rtl::OUString &rWord1,\n const ::rtl::OUString &rWord2,\n BOOL bSimilarOnly = FALSE);\n BOOL seekEntry(const ::rtl::OUString &rWord, INT32 *pPos,\n BOOL bSimilarOnly = FALSE);\n BOOL isSorted();\n\n BOOL addEntry_Impl(const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > xDicEntry,\n BOOL bIsLoadEntries = FALSE);\n\npublic:\n DictionaryNeo();\n DictionaryNeo(const ::rtl::OUString &rName, INT16 nLang,\n ::com::sun::star::linguistic2::DictionaryType eType,\n const ::rtl::OUString &rMainURL);\n virtual ~DictionaryNeo();\n\n \/\/ XNamed\n virtual ::rtl::OUString SAL_CALL\n getName()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setName( const ::rtl::OUString& aName )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XDictionary1 (same as XDictionary but for sal_Int16 as language)\n \/\/ only the different ones are listed\n virtual sal_Int16 SAL_CALL\n getLanguage()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setLanguage( sal_Int16 nLang )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XDictionary\n virtual ::com::sun::star::linguistic2::DictionaryType SAL_CALL\n getDictionaryType()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setActive( sal_Bool bActivate )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isActive()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL\n getCount()\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::lang::Locale SAL_CALL\n getLocale()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setLocale( const ::com::sun::star::lang::Locale& aLocale )\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > SAL_CALL\n getEntry( const ::rtl::OUString& aWord )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n addEntry( const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry >& xDicEntry )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n add( const ::rtl::OUString& aWord, sal_Bool bIsNegative,\n const ::rtl::OUString& aRplcText )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n remove( const ::rtl::OUString& aWord )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isFull()\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > > SAL_CALL\n getEntries()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n clear()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n addDictionaryEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n removeDictionaryEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XStorable\n virtual sal_Bool SAL_CALL\n hasLocation()\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL\n getLocation()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isReadonly()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n store()\n throw(::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n storeAsURL( const ::rtl::OUString& aURL,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::PropertyValue >& aArgs )\n throw(::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n storeToURL( const ::rtl::OUString& aURL,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::PropertyValue >& aArgs )\n throw(::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException);\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass DicEntry :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::linguistic2::XDictionaryEntry\n >\n{\n ::rtl::OUString aDicWord, \/\/ including hyphen positions represented by \"=\"\n aReplacement; \/\/ including hyphen positions represented by \"=\"\n BOOL bIsNegativ;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n DicEntry(const DicEntry &);\n DicEntry & operator = (const DicEntry &);\n\n void splitDicFileWord(const ::rtl::OUString &rDicFileWord,\n ::rtl::OUString &rDicWord,\n ::rtl::OUString &rReplacement);\n\npublic:\n DicEntry();\n DicEntry(const ::rtl::OUString &rDicFileWord, BOOL bIsNegativ);\n DicEntry(const ::rtl::OUString &rDicWord, BOOL bIsNegativ,\n const ::rtl::OUString &rRplcText);\n virtual ~DicEntry();\n\n \/\/ XDictionaryEntry\n virtual ::rtl::OUString SAL_CALL\n getDictionaryWord() throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isNegative() throw(::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL\n getReplacementText() throw(::com::sun::star::uno::RuntimeException);\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\nINTEGRATION: CWS tl18 (1.5.24); FILE MERGED 2006\/03\/08 10:13:39 tl 1.5.24.1: #i60698# introducing new, optional tagged file format for user-dictionaries\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: dicimp.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: rt $ $Date: 2006-05-05 08:10:18 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef _LINGUISTIC_DICIMP_HXX_\n#define _LINGUISTIC_DICIMP_HXX_\n\n#include \n#include \n#include \n#include \n\n#include \/\/ CPPU_CURRENT_LANGUAGE_BINDING_NAME macro, which specify the environment type\n#include \/\/ helper for implementations\n#include \/\/ helper for implementations\n\n#ifndef _CPPUHELPER_INTERFACECONTAINER_H_\n#include \n#endif\n\n#ifndef _STRING_HXX\n#include \n#endif\n\n#ifndef _STREAM_HXX\n#include \n#endif\n\n#include \"misc.hxx\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#define DIC_MAX_ENTRIES 2000\n\nint ReadDicVersion( SvStream *pStream, USHORT &nLng, BOOL &bNeg );\nconst String GetDicExtension();\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass DictionaryNeo :\n public ::cppu::WeakImplHelper3\n <\n ::com::sun::star::linguistic2::XDictionary1,\n ::com::sun::star::linguistic2::XDictionary,\n ::com::sun::star::frame::XStorable\n >\n{\n\n ::cppu::OInterfaceContainerHelper aDicEvtListeners;\n ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > > aEntries;\n ::rtl::OUString aDicName;\n ::rtl::OUString aMainURL;\n ::com::sun::star::linguistic2::DictionaryType eDicType;\n INT16 nCount;\n INT16 nLanguage;\n INT16 nDicVersion;\n BOOL bNeedEntries;\n BOOL bIsModified;\n BOOL bIsActive;\n BOOL bIsReadonly;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n DictionaryNeo(const DictionaryNeo &);\n DictionaryNeo & operator = (const DictionaryNeo &);\n\n void launchEvent(INT16 nEvent,\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > xEntry);\n\n ULONG loadEntries(const ::rtl::OUString &rMainURL);\n ULONG saveEntries(const ::rtl::OUString &rMainURL);\n int cmpDicEntry(const ::rtl::OUString &rWord1,\n const ::rtl::OUString &rWord2,\n BOOL bSimilarOnly = FALSE);\n BOOL seekEntry(const ::rtl::OUString &rWord, INT32 *pPos,\n BOOL bSimilarOnly = FALSE);\n BOOL isSorted();\n\n BOOL addEntry_Impl(const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > xDicEntry,\n BOOL bIsLoadEntries = FALSE);\n\npublic:\n DictionaryNeo();\n DictionaryNeo(const ::rtl::OUString &rName, INT16 nLang,\n ::com::sun::star::linguistic2::DictionaryType eType,\n const ::rtl::OUString &rMainURL);\n virtual ~DictionaryNeo();\n\n \/\/ XNamed\n virtual ::rtl::OUString SAL_CALL\n getName()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setName( const ::rtl::OUString& aName )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XDictionary1 (same as XDictionary but for sal_Int16 as language)\n \/\/ only the different ones are listed\n virtual sal_Int16 SAL_CALL\n getLanguage()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setLanguage( sal_Int16 nLang )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XDictionary\n virtual ::com::sun::star::linguistic2::DictionaryType SAL_CALL\n getDictionaryType()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setActive( sal_Bool bActivate )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isActive()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Int16 SAL_CALL\n getCount()\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::lang::Locale SAL_CALL\n getLocale()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n setLocale( const ::com::sun::star::lang::Locale& aLocale )\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > SAL_CALL\n getEntry( const ::rtl::OUString& aWord )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n addEntry( const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry >& xDicEntry )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n add( const ::rtl::OUString& aWord, sal_Bool bIsNegative,\n const ::rtl::OUString& aRplcText )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n remove( const ::rtl::OUString& aWord )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isFull()\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::com::sun::star::uno::Sequence<\n ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEntry > > SAL_CALL\n getEntries()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n clear()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n addDictionaryEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener )\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n removeDictionaryEventListener( const ::com::sun::star::uno::Reference<\n ::com::sun::star::linguistic2::XDictionaryEventListener >& xListener )\n throw(::com::sun::star::uno::RuntimeException);\n\n \/\/ XStorable\n virtual sal_Bool SAL_CALL\n hasLocation()\n throw(::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL\n getLocation()\n throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isReadonly()\n throw(::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n store()\n throw(::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n storeAsURL( const ::rtl::OUString& aURL,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::PropertyValue >& aArgs )\n throw(::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException);\n virtual void SAL_CALL\n storeToURL( const ::rtl::OUString& aURL,\n const ::com::sun::star::uno::Sequence<\n ::com::sun::star::beans::PropertyValue >& aArgs )\n throw(::com::sun::star::io::IOException,\n ::com::sun::star::uno::RuntimeException);\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass DicEntry :\n public cppu::WeakImplHelper1\n <\n ::com::sun::star::linguistic2::XDictionaryEntry\n >\n{\n ::rtl::OUString aDicWord, \/\/ including hyphen positions represented by \"=\"\n aReplacement; \/\/ including hyphen positions represented by \"=\"\n BOOL bIsNegativ;\n\n \/\/ disallow copy-constructor and assignment-operator for now\n DicEntry(const DicEntry &);\n DicEntry & operator = (const DicEntry &);\n\n void splitDicFileWord(const ::rtl::OUString &rDicFileWord,\n ::rtl::OUString &rDicWord,\n ::rtl::OUString &rReplacement);\n\npublic:\n DicEntry();\n DicEntry(const ::rtl::OUString &rDicFileWord, BOOL bIsNegativ);\n DicEntry(const ::rtl::OUString &rDicWord, BOOL bIsNegativ,\n const ::rtl::OUString &rRplcText);\n virtual ~DicEntry();\n\n \/\/ XDictionaryEntry\n virtual ::rtl::OUString SAL_CALL\n getDictionaryWord() throw(::com::sun::star::uno::RuntimeException);\n virtual sal_Bool SAL_CALL\n isNegative() throw(::com::sun::star::uno::RuntimeException);\n virtual ::rtl::OUString SAL_CALL\n getReplacementText() throw(::com::sun::star::uno::RuntimeException);\n};\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#endif\n\n<|endoftext|>"} {"text":"Added warning when zphot falls out of confidence interval<|endoftext|>"} {"text":"Update fmcalc.cpp<|endoftext|>"} {"text":"Fix check for existing serial connection before flashing fw.<|endoftext|>"} {"text":"\/\/ This file provides a fast implementation of common vector operations, using\n\/\/ a templated and very lightweight vec class. The memory structure of a vec\n\/\/ instance is just a sequence of its components.\n\/\/ It also provides a vec_array class, whose memory structure is just the same\n\/\/ as a sequence of N*dimensions scalars. The [] operator is overloaded\n\/\/ to return vec instances.\n\/\/ The goal of these classes is to achieve similar performance as a primitive\n\/\/ array for the 1d case, while being able to write more general programs.\n\n\/\/ include guard\n#ifndef VEC_HPP\n#define VEC_HPP\n\n\/\/ need complex type for optimized template\n#include \n\n\/* -- vec class -- *\/\ntemplate \nclass vec { public:\n Type x[dim];\n\n inline vec() {};\n\n \/\/ copy constructor\n template \n inline vec(const vec &other_vec) {\n\n for (int i=0; i\n inline vec(otherType val) {\n for (int i=0; i\n inline vec &operator+=(const vec &v) {\n for (int i=0; i\n inline vec &operator-=(const vec &v) {\n for (int i=0; i\n inline vec &operator*=(const otherType &v) {\n for (int i=0; i\n inline vec &operator\/=(const otherType &v) {\n for (int i=0; i\n inline vec element_wise(otherType& (*func)(Type&)) {\n vec r;\n for (int i=0; i\ninline vec operator+(const vec &v, const vec &w) {\n vec r;\n\n for (int i=0; i\ninline vec operator-(const vec &v, const vec &w) {\n vec r;\n\n for (int i=0; i\ninline vec operator*(const vec &v, const Type &w) {\n vec r;\n\n for (int i=0; i\ninline vec operator*(const Type &w, const vec &v) {\n return v*w;\n};\n\n\/\/ division of vec by scalar\ntemplate \ninline vec operator\/(const vec &v, const Type &w) {\n vec r;\n\n for (int i=0; i\ninline Type operator*(const vec &v, const vec &w) {\n Type r(0);\n\n for (int i=0; i\ninline std::complex operator*(const vec > &v, const vec &w) {\n std::complex r(0);\n\n for (int i=0; i(v.x[i] * w.x[i]);\n }\n\n return r;\n};\ntemplate \ninline std::complex operator*(const vec &w, const vec > &v) {\n return v*w;\n};\n\n\/\/ implement real part of a vec\ntemplate \nvec real(const vec > &v) {\n vec r;\n\n for (int i=0; i\nvec imag(const vec > &v) {\n vec r;\n\n for (int i=0; i\nvec > conj(const vec > &v) {\n vec > r;\n\n for (int i=0; i\nType abs(const vec &v) {\n Type r, a;\n\n for (int i=0; i\nclass vec_array { public:\n Type *x;\n\n inline vec_array() {};\n\n inline vec_array(Type *a) {\n x = a;\n };\n\n inline vec &operator[](int i) {\n return *(vec *)(&x[dim*i]);\n }\n};\n\n\/* -- macro to compute the square of vec instances -- *\/\n#define SQR(x) ((x)*(x))\n\n#endif \/\/ end of include guard\nfix bug in vec.hpp\/\/ This file provides a fast implementation of common vector operations, using\n\/\/ a templated and very lightweight vec class. The memory structure of a vec\n\/\/ instance is just a sequence of its components.\n\/\/ It also provides a vec_array class, whose memory structure is just the same\n\/\/ as a sequence of N*dimensions scalars. The [] operator is overloaded\n\/\/ to return vec instances.\n\/\/ The goal of these classes is to achieve similar performance as a primitive\n\/\/ array for the 1d case, while being able to write more general programs.\n\n\/\/ include guard\n#ifndef VEC_HPP\n#define VEC_HPP\n\n\/\/ need complex type for optimized template\n#include \n\n\/* -- vec class -- *\/\ntemplate \nclass vec { public:\n Type x[dim];\n\n inline vec() {};\n\n \/\/ copy constructor\n template \n inline vec(const vec &other_vec) {\n\n for (int i=0; i\n inline vec(otherType val) {\n for (int i=0; i\n inline vec &operator+=(const vec &v) {\n for (int i=0; i\n inline vec &operator-=(const vec &v) {\n for (int i=0; i\n inline vec &operator*=(const otherType &v) {\n for (int i=0; i\n inline vec &operator\/=(const otherType &v) {\n for (int i=0; i\n inline vec element_wise(otherType& (*func)(Type&)) {\n vec r;\n for (int i=0; i\ninline vec operator+(const vec &v, const vec &w) {\n vec r;\n\n for (int i=0; i\ninline vec operator-(const vec &v, const vec &w) {\n vec r;\n\n for (int i=0; i\ninline vec operator*(const vec &v, const Type &w) {\n vec r;\n\n for (int i=0; i\ninline vec operator*(const Type &w, const vec &v) {\n return v*w;\n};\n\n\/\/ division of vec by scalar\ntemplate \ninline vec operator\/(const vec &v, const Type &w) {\n vec r;\n\n for (int i=0; i\ninline Type operator*(const vec &v, const vec &w) {\n Type r(0);\n\n for (int i=0; i\ninline std::complex operator*(const vec > &v, const vec &w) {\n std::complex r(0);\n\n for (int i=0; i(v.x[i] * w.x[i]);\n }\n\n return r;\n};\ntemplate \ninline std::complex operator*(const vec &w, const vec > &v) {\n return v*w;\n};\n\n\/\/ implement real part of a vec\ntemplate \nvec real(const vec > &v) {\n vec r;\n\n for (int i=0; i\nvec imag(const vec > &v) {\n vec r;\n\n for (int i=0; i\nvec > conj(const vec > &v) {\n vec > r;\n\n for (int i=0; i\nType abs(const vec &v) {\n Type r(0), a;\n\n for (int i=0; i\nclass vec_array { public:\n Type *x;\n\n inline vec_array() {};\n\n inline vec_array(Type *a) {\n x = a;\n };\n\n inline vec &operator[](int i) {\n return *(vec *)(&x[dim*i]);\n }\n};\n\n\/* -- macro to compute the square of vec instances -- *\/\n#define SQR(x) ((x)*(x))\n\n#endif \/\/ end of include guard\n<|endoftext|>"} {"text":"\/*\n* Copyright (c) 2013 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"VSScript.h\"\n#include \"VSHelper.h\"\n\n#ifdef _WIN32\nstatic inline QString nativeToQString(const wchar_t *str) {\n\treturn QString::fromWCharArray(str);\n}\n#else\nstatic inline QString nativeToQString(const char *str) {\n\treturn QString::fromLocal8Bit(str);\n}\n#endif\n\nconst VSAPI *vsapi = NULL;\nVSScript *se = NULL;\nVSNodeRef *node = NULL;\nFILE *outFile = NULL;\n\nint requests = 0;\nint outputIndex = 0;\nint outputFrames = 0;\nint requestedFrames = 0;\nint completedFrames = 0;\nint totalFrames = 0;\nint numPlanes = 0;\nbool y4m = false;\nbool outputError = false;\nbool showInfo = false;\nQMap reorderMap;\n\nQString errorMessage;\nQWaitCondition condition;\nQMutex mutex;\n\nvoid VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {\n completedFrames++;\n\n if (f) {\n reorderMap.insert(n, f);\n while (reorderMap.contains(outputFrames)) {\n const VSFrameRef *frame = reorderMap.take(outputFrames);\n if (!outputError) {\n\t\t\t\tif (y4m) {\n\t\t\t\t\tif (!fwrite(\"FRAME\\n\", 6, 1, outFile)) {\n\t\t\t\t\t\terrorMessage = \"Error: fwrite() call failed\";\n\t\t\t\t\t\ttotalFrames = requestedFrames;\n\t\t\t\t\t\toutputError = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!outputError) {\n\t\t\t\t\tconst VSFormat *fi = vsapi->getFrameFormat(frame);\n\t\t\t\t\tfor (int p = 0; p < fi->numPlanes; p++) {\n\t\t\t\t\t\tint stride = vsapi->getStride(frame, p);\n\t\t\t\t\t\tconst uint8_t *readPtr = vsapi->getReadPtr(frame, p);\n\t\t\t\t\t\tint rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;\n\t\t\t\t\t\tint height = vsapi->getFrameHeight(frame, p);\n\t\t\t\t\t\tfor (int y = 0; y < height; y++) {\n\t\t\t\t\t\t\tif (!fwrite(readPtr, rowSize, 1, outFile)) {\n\t\t\t\t\t\t\t\terrorMessage = \"Error: fwrite() call failed\";\n\t\t\t\t\t\t\t\ttotalFrames = requestedFrames;\n\t\t\t\t\t\t\t\toutputError = true;\n\t\t\t\t\t\t\t\tp = 100; \/\/ break out of the outer loop\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treadPtr += stride;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n vsapi->freeFrame(frame);\n outputFrames++;\n }\n } else {\n outputError = true;\n totalFrames = requestedFrames;\n if (errorMsg)\n errorMessage = QString(\"Error: Failed to retrieve frame \") + n + QString(\" with error: \") + QString::fromUtf8(errorMsg);\n else\n errorMessage = QString(\"Error: Failed to retrieve frame \") + n;\n }\n\n if (requestedFrames < totalFrames) {\n vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);\n requestedFrames++;\n }\n\n if (totalFrames == completedFrames) {\n QMutexLocker lock(&mutex);\n condition.wakeOne();\n }\n}\n\nbool outputNode() {\n if (requests < 1) {\n\t\tconst VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore());\n requests = info->numThreads;\n\t}\n\n\tconst VSVideoInfo *vi = vsapi->getVideoInfo(node);\n\ttotalFrames = vi->numFrames;\n\n\tif (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) {\n\t\terrorMessage = \"Error: Can only apply y4m headers to YUV and Gray format clips\";\n\t\tfprintf(stderr, \"%s\", errorMessage.toUtf8().constData());\n return true;\n\t}\n\n QString y4mFormat;\n QString numBits;\n\n if (y4m) {\n if (vi->format->colorFamily == cmGray) {\n y4mFormat = \"mono\";\n if (vi->format->bitsPerSample > 8)\n\t\t\t\ty4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample);\n\t\t} else if (vi->format->colorFamily == cmYUV) {\n\t\t\tif (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1)\n y4mFormat = \"420\";\n\t\t\telse if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0)\n y4mFormat = \"422\";\n\t\t\telse if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0)\n y4mFormat = \"444\";\n\t\t\telse if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2)\n y4mFormat = \"410\";\n\t\t\telse if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0)\n y4mFormat = \"411\";\n\t\t\telse if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1)\n y4mFormat = \"440\";\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"No y4m identifier exists for current format\");\n\t\t\t\treturn true;\n\t\t\t}\n\n if (vi->format->bitsPerSample > 8)\n y4mFormat = y4mFormat + \"p\" + QString::number(vi->format->bitsPerSample);\n\t\t} else {\n\t\t\tfprintf(stderr, \"No y4m identifier exists for current format\");\n\t\t\treturn true;\n\t\t}\n }\n\tif (!y4mFormat.isEmpty())\n y4mFormat = \"C\" + y4mFormat + \" \";\n\n\tQString header = \"YUV4MPEG2 \" + y4mFormat + \"W\" + QString::number(vi->width) + \" H\" + QString::number(vi->height) + \" F\" + QString::number(vi->fpsNum) + \":\" + QString::number(vi->fpsDen) + \" Ip A0:0\\n\";\n QByteArray rawHeader = header.toUtf8();\n\n if (y4m) {\n if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) {\n errorMessage = \"Error: fwrite() call failed\";\n\t\t\tfprintf(stderr, \"%s\", errorMessage.toUtf8().constData());\n\t\t\toutputError = true;\n\t\t\treturn outputError;\n }\n }\n\n\tQMutexLocker lock(&mutex);\n\n\tint intitalRequestSize = std::min(requests, totalFrames);\n\trequestedFrames = intitalRequestSize;\n\tfor (int n = 0; n < intitalRequestSize; n++)\n\t\tvsapi->getFrameAsync(n, node, frameDoneCallback, NULL);\n\n\tcondition.wait(&mutex);\n\n if (outputError) {\n fprintf(stderr, \"%s\", errorMessage.toUtf8().constData());\n }\n\n return outputError;\n}\n\nconst char *colorFamilyToString(int colorFamily) {\n\tswitch (colorFamily) {\n\tcase cmGray: return \"Gray\";\n\tcase cmRGB: return \"RGB\";\n\tcase cmYUV: return \"YUV\";\n\tcase cmYCoCg: return \"YCoCg\";\n\tcase cmCompat: return \"Compat\";\n\t}\n\treturn \"\";\n}\n\n\/\/ fixme, only allow info without output\n#ifdef _WIN32\nint wmain(int argc, wchar_t **argv) {\n#else\nint main(int argc, char **argv) {\n#endif\n\n if (argc < 3) {\n fprintf(stderr, \"VSPipe usage:\\n\");\n\t\tfprintf(stderr, \"Show script info: vspipe script.vpy - -info\\n\");\n fprintf(stderr, \"Write to stdout: vspipe script.vpy - [options]\\n\");\n fprintf(stderr, \"Write to file: vspipe script.vpy [options]\\n\");\n fprintf(stderr, \"Available options:\\n\");\n\t\tfprintf(stderr, \"Select output index: -index N\\n\");\n\t\tfprintf(stderr, \"Set number of concurrent frame requests: -requests N\\n\");\n\t\tfprintf(stderr, \"Add YUV4MPEG headers: -y4m\\n\");\n\t\tfprintf(stderr, \"Show video info: -info (overrides other options)\\n\");\n return 1;\n }\n\n\tQFile scriptFile(nativeToQString(argv[1]));\n\tif (!scriptFile.open(QIODevice::ReadOnly)) {\n fprintf(stderr, \"Failed to to open script file for reading\\n\");\n return 1;\n\t}\n\n\tif (scriptFile.size() > 1024*1024*16) {\n fprintf(stderr, \"Script files bigger than 16MB not allowed\\n\");\n return 1;\n\t}\n\n QByteArray scriptData = scriptFile.readAll();\n\tscriptFile.close();\n if (scriptData.isEmpty()) {\n fprintf(stderr, \"Failed to read script file or file is empty\\n\");\n return 1;\n }\n\n\tQString outputFilename = nativeToQString(argv[2]);\n\tif (outputFilename == \"-\") {\n\t\toutFile = stdout;\n\t} else {\n#ifdef _WIN32\n\t\toutFile = _wfopen(outputFilename.toStdWString().c_str(), L\"wb\");\n#else\n\t\toutFile = fopen(outputFilename.toLocal8Bit(), \"wb\");\n#endif\n\t\tif (!outFile) {\n\t\t\tfprintf(stderr, \"Failed to open output for writing\\n\");\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tfor (int arg = 3; arg < argc; arg++) {\n\t\tQString argString = nativeToQString(argv[arg]);\n\t\tif (argString == \"-y4m\") {\n\t\t\ty4m = true;\n\t\t} else if (argString == \"-info\") {\n\t\t\tshowInfo = true;\n\t\t} else if (argString == \"-index\") {\n\t\t\tbool ok = false;\n\t\t\tif (argc <= arg + 1) {\n\t\t\t\tfprintf(stderr, \"No index number specified\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tQString numString = nativeToQString(argv[arg+1]);\n\t\t\tindex = numString.toInt(&ok);\n\t\t\tif (!ok) {\n\t\t\t\tfprintf(stderr, \"Couldn't convert %s to an integer\", numString.toUtf8().constData());\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\targ++;\n\t\t} else if (argString == \"-requests\") {\n\t\t\tbool ok = false;\n\t\t\tif (argc <= arg + 1) {\n\t\t\t\tfprintf(stderr, \"No request number specified\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tQString numString = nativeToQString(argv[arg+1]);\n\t\t\trequests = numString.toInt(&ok);\n\t\t\tif (!ok) {\n\t\t\t\tfprintf(stderr, \"Couldn't convert %s to an integer\", numString.toUtf8().constData());\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\targ++;\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown argument: %s\\n\", argString.toUtf8().constData());\n\t\t\treturn 1;\n\t\t}\n\t}\n\n if (!vseval_init()) {\n fprintf(stderr, \"Failed to initialize VapourSynth environment\\n\");\n return 1;\n }\n\n vsapi = vseval_getVSApi();\n if (!vsapi) {\n fprintf(stderr, \"Failed to get VapourSynth API pointer\\n\");\n vseval_finalize();\n return 1;\n }\n\n\tif (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) {\n fprintf(stderr, \"Script evaluation failed:\\n%s\", vseval_getError(se));\n vseval_freeScript(se);\n vseval_finalize();\n return 1;\n }\n\n node = vseval_getOutput(se, outputIndex);\n if (!node) {\n fprintf(stderr, \"Failed to retrieve output node. Invalid index specified?\\n\");\n vseval_freeScript(se);\n vseval_finalize();\n return 1;\n }\n\n\tbool error = false;\n\tconst VSVideoInfo *vi = vsapi->getVideoInfo(node);\n\n\tif (showInfo) {\n\t\tfprintf(outFile, \"Width: %d\\n\", vi->width);\n\t\tfprintf(outFile, \"Height: %d\\n\", vi->height);\n\t\tfprintf(outFile, \"Frames: %d\\n\", vi->numFrames);\n\t\tfprintf(outFile, \"FPS: %d\/%d\\n\", vi->fpsNum, vi->fpsDen);\n\t\tif (vi->format) {\n\t\t\tfprintf(outFile, \"Format Name: %s\\n\", vi->format->name);\n\t\t\tfprintf(outFile, \"Color Family: %s\\n\", colorFamilyToString(vi->format->colorFamily));\n\t\t\tfprintf(outFile, \"Bits: %d\\n\", vi->format->bitsPerSample);\n\t\t\tfprintf(outFile, \"SubSampling W: %d\\n\", vi->format->subSamplingW);\n\t\t\tfprintf(outFile, \"SubSampling H: %d\\n\", vi->format->subSamplingH);\n\t\t} else {\n\t\t\tfprintf(outFile, \"Format Name: Variable\\n\");\n\t\t}\n\t} else {\n\t\tif (!isConstantFormat(vi) || vi->numFrames == 0) {\n\t\t\tfprintf(stderr, \"Cannot output clips with varying dimensions or unknown length\\n\");\n\t\t\tvseval_freeScript(se);\n\t\t\tvseval_finalize();\n\t\t\treturn 1;\n\t\t}\n\n\t\terror = outputNode();\n\t}\n\n\tfflush(outFile);\n\n vseval_freeScript(se);\n vseval_finalize();\n\n\treturn error;\n}\nFix previous commit\/*\n* Copyright (c) 2013 Fredrik Mellbin\n*\n* This file is part of VapourSynth.\n*\n* VapourSynth is free software; you can redistribute it and\/or\n* modify it under the terms of the GNU Lesser General Public\n* License as published by the Free Software Foundation; either\n* version 2.1 of the License, or (at your option) any later version.\n*\n* VapourSynth is distributed in the hope that it will be useful,\n* but WITHOUT ANY WARRANTY; without even the implied warranty of\n* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n* Lesser General Public License for more details.\n*\n* You should have received a copy of the GNU Lesser General Public\n* License along with VapourSynth; if not, write to the Free Software\n* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \"VSScript.h\"\n#include \"VSHelper.h\"\n\n#ifdef _WIN32\nstatic inline QString nativeToQString(const wchar_t *str) {\n\treturn QString::fromWCharArray(str);\n}\n#else\nstatic inline QString nativeToQString(const char *str) {\n\treturn QString::fromLocal8Bit(str);\n}\n#endif\n\nconst VSAPI *vsapi = NULL;\nVSScript *se = NULL;\nVSNodeRef *node = NULL;\nFILE *outFile = NULL;\n\nint requests = 0;\nint outputIndex = 0;\nint outputFrames = 0;\nint requestedFrames = 0;\nint completedFrames = 0;\nint totalFrames = 0;\nint numPlanes = 0;\nbool y4m = false;\nbool outputError = false;\nbool showInfo = false;\nQMap reorderMap;\n\nQString errorMessage;\nQWaitCondition condition;\nQMutex mutex;\n\nvoid VS_CC frameDoneCallback(void *userData, const VSFrameRef *f, int n, VSNodeRef *, const char *errorMsg) {\n completedFrames++;\n\n if (f) {\n reorderMap.insert(n, f);\n while (reorderMap.contains(outputFrames)) {\n const VSFrameRef *frame = reorderMap.take(outputFrames);\n if (!outputError) {\n\t\t\t\tif (y4m) {\n\t\t\t\t\tif (!fwrite(\"FRAME\\n\", 6, 1, outFile)) {\n\t\t\t\t\t\terrorMessage = \"Error: fwrite() call failed\";\n\t\t\t\t\t\ttotalFrames = requestedFrames;\n\t\t\t\t\t\toutputError = true;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!outputError) {\n\t\t\t\t\tconst VSFormat *fi = vsapi->getFrameFormat(frame);\n\t\t\t\t\tfor (int p = 0; p < fi->numPlanes; p++) {\n\t\t\t\t\t\tint stride = vsapi->getStride(frame, p);\n\t\t\t\t\t\tconst uint8_t *readPtr = vsapi->getReadPtr(frame, p);\n\t\t\t\t\t\tint rowSize = vsapi->getFrameWidth(frame, p) * fi->bytesPerSample;\n\t\t\t\t\t\tint height = vsapi->getFrameHeight(frame, p);\n\t\t\t\t\t\tfor (int y = 0; y < height; y++) {\n\t\t\t\t\t\t\tif (!fwrite(readPtr, rowSize, 1, outFile)) {\n\t\t\t\t\t\t\t\terrorMessage = \"Error: fwrite() call failed\";\n\t\t\t\t\t\t\t\ttotalFrames = requestedFrames;\n\t\t\t\t\t\t\t\toutputError = true;\n\t\t\t\t\t\t\t\tp = 100; \/\/ break out of the outer loop\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\treadPtr += stride;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n vsapi->freeFrame(frame);\n outputFrames++;\n }\n } else {\n outputError = true;\n totalFrames = requestedFrames;\n if (errorMsg)\n errorMessage = QString(\"Error: Failed to retrieve frame \") + n + QString(\" with error: \") + QString::fromUtf8(errorMsg);\n else\n errorMessage = QString(\"Error: Failed to retrieve frame \") + n;\n }\n\n if (requestedFrames < totalFrames) {\n vsapi->getFrameAsync(requestedFrames, node, frameDoneCallback, NULL);\n requestedFrames++;\n }\n\n if (totalFrames == completedFrames) {\n QMutexLocker lock(&mutex);\n condition.wakeOne();\n }\n}\n\nbool outputNode() {\n if (requests < 1) {\n\t\tconst VSCoreInfo *info = vsapi->getCoreInfo(vseval_getCore());\n requests = info->numThreads;\n\t}\n\n\tconst VSVideoInfo *vi = vsapi->getVideoInfo(node);\n\ttotalFrames = vi->numFrames;\n\n\tif (y4m && (vi->format->colorFamily != cmGray && vi->format->colorFamily != cmYUV)) {\n\t\terrorMessage = \"Error: Can only apply y4m headers to YUV and Gray format clips\";\n\t\tfprintf(stderr, \"%s\", errorMessage.toUtf8().constData());\n return true;\n\t}\n\n QString y4mFormat;\n QString numBits;\n\n if (y4m) {\n if (vi->format->colorFamily == cmGray) {\n y4mFormat = \"mono\";\n if (vi->format->bitsPerSample > 8)\n\t\t\t\ty4mFormat = y4mFormat + QString::number(vi->format->bitsPerSample);\n\t\t} else if (vi->format->colorFamily == cmYUV) {\n\t\t\tif (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 1)\n y4mFormat = \"420\";\n\t\t\telse if (vi->format->subSamplingW == 1 && vi->format->subSamplingH == 0)\n y4mFormat = \"422\";\n\t\t\telse if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 0)\n y4mFormat = \"444\";\n\t\t\telse if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 2)\n y4mFormat = \"410\";\n\t\t\telse if (vi->format->subSamplingW == 2 && vi->format->subSamplingH == 0)\n y4mFormat = \"411\";\n\t\t\telse if (vi->format->subSamplingW == 0 && vi->format->subSamplingH == 1)\n y4mFormat = \"440\";\n\t\t\telse {\n\t\t\t\tfprintf(stderr, \"No y4m identifier exists for current format\");\n\t\t\t\treturn true;\n\t\t\t}\n\n if (vi->format->bitsPerSample > 8)\n y4mFormat = y4mFormat + \"p\" + QString::number(vi->format->bitsPerSample);\n\t\t} else {\n\t\t\tfprintf(stderr, \"No y4m identifier exists for current format\");\n\t\t\treturn true;\n\t\t}\n }\n\tif (!y4mFormat.isEmpty())\n y4mFormat = \"C\" + y4mFormat + \" \";\n\n\tQString header = \"YUV4MPEG2 \" + y4mFormat + \"W\" + QString::number(vi->width) + \" H\" + QString::number(vi->height) + \" F\" + QString::number(vi->fpsNum) + \":\" + QString::number(vi->fpsDen) + \" Ip A0:0\\n\";\n QByteArray rawHeader = header.toUtf8();\n\n if (y4m) {\n if (!fwrite(rawHeader.constData(), rawHeader.size(), 1, outFile)) {\n errorMessage = \"Error: fwrite() call failed\";\n\t\t\tfprintf(stderr, \"%s\", errorMessage.toUtf8().constData());\n\t\t\toutputError = true;\n\t\t\treturn outputError;\n }\n }\n\n\tQMutexLocker lock(&mutex);\n\n\tint intitalRequestSize = std::min(requests, totalFrames);\n\trequestedFrames = intitalRequestSize;\n\tfor (int n = 0; n < intitalRequestSize; n++)\n\t\tvsapi->getFrameAsync(n, node, frameDoneCallback, NULL);\n\n\tcondition.wait(&mutex);\n\n if (outputError) {\n fprintf(stderr, \"%s\", errorMessage.toUtf8().constData());\n }\n\n return outputError;\n}\n\nconst char *colorFamilyToString(int colorFamily) {\n\tswitch (colorFamily) {\n\tcase cmGray: return \"Gray\";\n\tcase cmRGB: return \"RGB\";\n\tcase cmYUV: return \"YUV\";\n\tcase cmYCoCg: return \"YCoCg\";\n\tcase cmCompat: return \"Compat\";\n\t}\n\treturn \"\";\n}\n\n\/\/ fixme, only allow info without output\n#ifdef _WIN32\nint wmain(int argc, wchar_t **argv) {\n#else\nint main(int argc, char **argv) {\n#endif\n\n if (argc < 3) {\n fprintf(stderr, \"VSPipe usage:\\n\");\n\t\tfprintf(stderr, \"Show script info: vspipe script.vpy - -info\\n\");\n fprintf(stderr, \"Write to stdout: vspipe script.vpy - [options]\\n\");\n fprintf(stderr, \"Write to file: vspipe script.vpy [options]\\n\");\n fprintf(stderr, \"Available options:\\n\");\n\t\tfprintf(stderr, \"Select output index: -index N\\n\");\n\t\tfprintf(stderr, \"Set number of concurrent frame requests: -requests N\\n\");\n\t\tfprintf(stderr, \"Add YUV4MPEG headers: -y4m\\n\");\n\t\tfprintf(stderr, \"Show video info: -info (overrides other options)\\n\");\n return 1;\n }\n\n\tQFile scriptFile(nativeToQString(argv[1]));\n\tif (!scriptFile.open(QIODevice::ReadOnly)) {\n fprintf(stderr, \"Failed to to open script file for reading\\n\");\n return 1;\n\t}\n\n\tif (scriptFile.size() > 1024*1024*16) {\n fprintf(stderr, \"Script files bigger than 16MB not allowed\\n\");\n return 1;\n\t}\n\n QByteArray scriptData = scriptFile.readAll();\n\tscriptFile.close();\n if (scriptData.isEmpty()) {\n fprintf(stderr, \"Failed to read script file or file is empty\\n\");\n return 1;\n }\n\n\tQString outputFilename = nativeToQString(argv[2]);\n\tif (outputFilename == \"-\") {\n\t\toutFile = stdout;\n\t} else {\n#ifdef _WIN32\n\t\toutFile = _wfopen(outputFilename.toStdWString().c_str(), L\"wb\");\n#else\n\t\toutFile = fopen(outputFilename.toLocal8Bit(), \"wb\");\n#endif\n\t\tif (!outFile) {\n\t\t\tfprintf(stderr, \"Failed to open output for writing\\n\");\n\t\t\treturn 1;\n\t\t}\n\t}\n\n\tfor (int arg = 3; arg < argc; arg++) {\n\t\tQString argString = nativeToQString(argv[arg]);\n\t\tif (argString == \"-y4m\") {\n\t\t\ty4m = true;\n\t\t} else if (argString == \"-info\") {\n\t\t\tshowInfo = true;\n\t\t} else if (argString == \"-index\") {\n\t\t\tbool ok = false;\n\t\t\tif (argc <= arg + 1) {\n\t\t\t\tfprintf(stderr, \"No index number specified\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tQString numString = nativeToQString(argv[arg+1]);\n\t\t\toutputIndex = numString.toInt(&ok);\n\t\t\tif (!ok) {\n\t\t\t\tfprintf(stderr, \"Couldn't convert %s to an integer\", numString.toUtf8().constData());\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\targ++;\n\t\t} else if (argString == \"-requests\") {\n\t\t\tbool ok = false;\n\t\t\tif (argc <= arg + 1) {\n\t\t\t\tfprintf(stderr, \"No request number specified\");\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\tQString numString = nativeToQString(argv[arg+1]);\n\t\t\trequests = numString.toInt(&ok);\n\t\t\tif (!ok) {\n\t\t\t\tfprintf(stderr, \"Couldn't convert %s to an integer\", numString.toUtf8().constData());\n\t\t\t\treturn 1;\n\t\t\t}\n\t\t\targ++;\n\t\t} else {\n\t\t\tfprintf(stderr, \"Unknown argument: %s\\n\", argString.toUtf8().constData());\n\t\t\treturn 1;\n\t\t}\n\t}\n\n if (!vseval_init()) {\n fprintf(stderr, \"Failed to initialize VapourSynth environment\\n\");\n return 1;\n }\n\n vsapi = vseval_getVSApi();\n if (!vsapi) {\n fprintf(stderr, \"Failed to get VapourSynth API pointer\\n\");\n vseval_finalize();\n return 1;\n }\n\n\tif (vseval_evaluateScript(&se, scriptData.constData(), nativeToQString(argv[1]).toUtf8())) {\n fprintf(stderr, \"Script evaluation failed:\\n%s\", vseval_getError(se));\n vseval_freeScript(se);\n vseval_finalize();\n return 1;\n }\n\n node = vseval_getOutput(se, outputIndex);\n if (!node) {\n fprintf(stderr, \"Failed to retrieve output node. Invalid index specified?\\n\");\n vseval_freeScript(se);\n vseval_finalize();\n return 1;\n }\n\n\tbool error = false;\n\tconst VSVideoInfo *vi = vsapi->getVideoInfo(node);\n\n\tif (showInfo) {\n\t\tfprintf(outFile, \"Width: %d\\n\", vi->width);\n\t\tfprintf(outFile, \"Height: %d\\n\", vi->height);\n\t\tfprintf(outFile, \"Frames: %d\\n\", vi->numFrames);\n\t\tfprintf(outFile, \"FPS: %d\/%d\\n\", vi->fpsNum, vi->fpsDen);\n\t\tif (vi->format) {\n\t\t\tfprintf(outFile, \"Format Name: %s\\n\", vi->format->name);\n\t\t\tfprintf(outFile, \"Color Family: %s\\n\", colorFamilyToString(vi->format->colorFamily));\n\t\t\tfprintf(outFile, \"Bits: %d\\n\", vi->format->bitsPerSample);\n\t\t\tfprintf(outFile, \"SubSampling W: %d\\n\", vi->format->subSamplingW);\n\t\t\tfprintf(outFile, \"SubSampling H: %d\\n\", vi->format->subSamplingH);\n\t\t} else {\n\t\t\tfprintf(outFile, \"Format Name: Variable\\n\");\n\t\t}\n\t} else {\n\t\tif (!isConstantFormat(vi) || vi->numFrames == 0) {\n\t\t\tfprintf(stderr, \"Cannot output clips with varying dimensions or unknown length\\n\");\n\t\t\tvseval_freeScript(se);\n\t\t\tvseval_finalize();\n\t\t\treturn 1;\n\t\t}\n\n\t\terror = outputNode();\n\t}\n\n\tfflush(outFile);\n\n vseval_freeScript(se);\n vseval_finalize();\n\n\treturn error;\n}\n<|endoftext|>"} {"text":"Enable staking for p2sh-p2wkh.<|endoftext|>"} {"text":"#include \"GPIO.hh\"\n\n\/\/ STL\n#include \n#include \n\n#include \/\/ usleep()\n\nusing namespace std::chrono;\n\n\n\nhigh_resolution_clock::time_point beg;\nduration accum;\n\n\nclass Handler\n{\npublic:\n void handle(GPIO::Value val)\n {\n const high_resolution_clock::time_point end = high_resolution_clock::now();\n\n const auto time_span = end - beg;\n accum += time_span;\n std::cout << \"Latency: \" << time_span.count() << \" microseconds\" << std::endl;\n }\n};\n\n\nvoid myisr(GPIO::Value val)\n{\n const high_resolution_clock::time_point end = high_resolution_clock::now();\n\n const auto time_span = end - beg;\n accum += time_span;\n std::cout << \"Latency: \" << time_span.count() << \" microseconds\" << std::endl;\n}\n\n\nint main()\n{\n Handler h;\n\n accum = std::chrono::duration(0.0);\n\n\n\n\n \/\/ Member functions do not take any longer to call than global functions\n std::function global(myisr);\n\n std::function handleisr =\n std::bind(&Handler::handle, &h, std::placeholders::_1);\n\n {\n \/\/ Short GPIO 15 (input) to GPIO 27 (output) for the following latency test\n GPIO gpio1(27, GPIO::Direction::OUT);\n GPIO gpio2(15, GPIO::Edge::RISING, handleisr); \/\/ will be destroyed first,\n \/\/ so no spurious call to handleisr upon\n \/\/ destruction of GPIO 27\n\n usleep(125000);\n\n const unsigned int nIterations = 50;\n for(unsigned int i=0;iEnsure printed units are microseconds#include \"GPIO.hh\"\n\n\/\/ STL\n#include \n#include \n\n#include \/\/ usleep()\n\nusing namespace std::chrono;\n\n\n\nhigh_resolution_clock::time_point beg;\nduration accum;\n\n\nclass Handler\n{\npublic:\n void handle(GPIO::Value val)\n {\n const high_resolution_clock::time_point end = high_resolution_clock::now();\n\n const auto time_span = duration_cast(end - beg);\n accum += time_span;\n std::cout << \"Latency: \" << time_span.count() << \" microseconds\" << std::endl;\n }\n};\n\n\nvoid myisr(GPIO::Value val)\n{\n const high_resolution_clock::time_point end = high_resolution_clock::now();\n\n const auto time_span = end - beg;\n accum += time_span;\n std::cout << \"Latency: \" << time_span.count() << \" microseconds\" << std::endl;\n}\n\n\nint main()\n{\n Handler h;\n\n accum = std::chrono::duration(0.0);\n\n\n\n\n \/\/ Member functions do not take any longer to call than global functions\n std::function global(myisr);\n\n std::function handleisr =\n std::bind(&Handler::handle, &h, std::placeholders::_1);\n\n {\n \/\/ Short GPIO 15 (input) to GPIO 27 (output) for the following latency test\n GPIO gpio1(27, GPIO::Direction::OUT);\n GPIO gpio2(15, GPIO::Edge::RISING, handleisr); \/\/ will be destroyed first,\n \/\/ so no spurious call to handleisr upon\n \/\/ destruction of GPIO 27\n\n usleep(125000);\n\n const unsigned int nIterations = 50;\n for(unsigned int i=0;i"} {"text":"\/*\n * Copyright 2014 Cloudius Systems\n *\/\n\n\n#include \"database.hh\"\n#include \"core\/app-template.hh\"\n#include \"core\/distributed.hh\"\n#include \"thrift\/server.hh\"\n#include \"transport\/server.hh\"\n\nnamespace bpo = boost::program_options;\n\nint main(int ac, char** av) {\n app_template app;\n app.add_options()\n (\"cql-port\", bpo::value()->default_value(9042), \"CQL port\")\n (\"thrift-port\", bpo::value()->default_value(9160), \"Thrift port\")\n (\"datadir\", bpo::value()->default_value(\"\/var\/lib\/cassandra\/data\"), \"data directory\");\n\n auto server = std::make_unique>();;\n distributed db;\n\n return app.run(ac, av, [&] {\n auto&& config = app.configuration();\n uint16_t thrift_port = config[\"thrift-port\"].as();\n uint16_t cql_port = config[\"cql-port\"].as();\n sstring datadir = config[\"datadir\"].as();\n\n return db.start().then([datadir, &db] {\n return db.invoke_on_all(&database::init_from_data_directory, datadir);\n }).then([&db, cql_port, thrift_port] {\n auto cserver = new distributed;\n cserver->start(std::ref(db)).then([server = std::move(cserver), cql_port] () mutable {\n server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port});\n }).then([cql_port] {\n std::cout << \"CQL server listening on port \" << cql_port << \" ...\\n\";\n });\n auto tserver = new distributed;\n tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable {\n server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port});\n }).then([thrift_port] {\n std::cout << \"Thrift server listening on port \" << thrift_port << \" ...\\n\";\n });\n }).or_terminate();\n });\n}\nAvoid crash on ctrl-C\/*\n * Copyright 2014 Cloudius Systems\n *\/\n\n\n#include \"database.hh\"\n#include \"core\/app-template.hh\"\n#include \"core\/distributed.hh\"\n#include \"thrift\/server.hh\"\n#include \"transport\/server.hh\"\n\nnamespace bpo = boost::program_options;\n\nint main(int ac, char** av) {\n app_template app;\n app.add_options()\n (\"cql-port\", bpo::value()->default_value(9042), \"CQL port\")\n (\"thrift-port\", bpo::value()->default_value(9160), \"Thrift port\")\n (\"datadir\", bpo::value()->default_value(\"\/var\/lib\/cassandra\/data\"), \"data directory\");\n\n auto server = std::make_unique>();;\n distributed db;\n\n return app.run(ac, av, [&] {\n auto&& config = app.configuration();\n uint16_t thrift_port = config[\"thrift-port\"].as();\n uint16_t cql_port = config[\"cql-port\"].as();\n sstring datadir = config[\"datadir\"].as();\n\n return db.start().then([datadir, &db] {\n engine().at_exit([&db] { return db.stop(); });\n return db.invoke_on_all(&database::init_from_data_directory, datadir);\n }).then([&db, cql_port, thrift_port] {\n auto cserver = new distributed;\n cserver->start(std::ref(db)).then([server = std::move(cserver), cql_port] () mutable {\n server->invoke_on_all(&cql_server::listen, ipv4_addr{cql_port});\n }).then([cql_port] {\n std::cout << \"CQL server listening on port \" << cql_port << \" ...\\n\";\n });\n auto tserver = new distributed;\n tserver->start(std::ref(db)).then([server = std::move(tserver), thrift_port] () mutable {\n server->invoke_on_all(&thrift_server::listen, ipv4_addr{thrift_port});\n }).then([thrift_port] {\n std::cout << \"Thrift server listening on port \" << thrift_port << \" ...\\n\";\n });\n }).or_terminate();\n });\n}\n<|endoftext|>"} {"text":"#ifndef SIMPLE_IO\n#define SIMPLE_IO\n\n#include \n#include \n#include \n#include \n\n#ifndef NO_ZLIB\n#include \"zlib.h\"\n#endif\n\n\nclass FileInputType\n{\npublic:\n virtual bool getline(std::string &line) = 0;\n virtual ~FileInputType() { };\n};\n\nclass IFStreamInput : public FileInputType\n{\npublic:\n IFStreamInput(std::string filename) { ifstr.open(filename, std::ios_base::in); };\n ~IFStreamInput() { ifstr.close(); }\n bool getline(std::string &line) { return std::getline(ifstr, line); }\nprivate:\n std::ifstream ifstr;\n};\n\n#ifndef NO_ZLIB\nclass GZipFileInput : public FileInputType\n{\npublic:\n GZipFileInput(std::string filename);\n ~GZipFileInput();\n bool getline(std::string &line);\nprivate:\n gzFile gzf;\n};\n#endif\n\nclass SimpleFileInput\n{\npublic:\n SimpleFileInput(std::string filename);\n ~SimpleFileInput() { };\n bool getline(std::string &line) { return infs->getline(line); }\nprivate:\n bool ends_with(std::string const &filename,\n std::string const &suffix)\n {\n if (filename.length() < suffix.length()) return false;\n return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));\n }\n std::unique_ptr infs;\n};\n\n\nclass FileOutputType\n{\npublic:\n virtual void close() = 0;\n virtual FileOutputType& operator<<(const std::string &str) = 0;\n virtual FileOutputType& operator<<(int) = 0;\n virtual FileOutputType& operator<<(long int) = 0;\n virtual FileOutputType& operator<<(unsigned int) = 0;\n virtual FileOutputType& operator<<(long unsigned int) = 0;\n virtual FileOutputType& operator<<(float) = 0;\n virtual FileOutputType& operator<<(double) = 0;\n virtual ~FileOutputType() { };\n};\n\n\nclass OFStream: public FileOutputType\n{\npublic:\n OFStream(std::string filename);\n ~OFStream();\n void close();\n OFStream& operator<<(const std::string &str);\n OFStream& operator<<(int);\n OFStream& operator<<(long int);\n OFStream& operator<<(unsigned int);\n OFStream& operator<<(long unsigned int);\n OFStream& operator<<(float);\n OFStream& operator<<(double);\nprivate:\n std::ofstream ofstr;\n};\n\n\n#ifndef NO_ZLIB\nclass GZipFileOutput: public FileOutputType\n{\npublic:\n GZipFileOutput(std::string filename);\n ~GZipFileOutput();\n void close();\n GZipFileOutput& operator<<(const std::string &str);\n GZipFileOutput& operator<<(int);\n GZipFileOutput& operator<<(long int);\n GZipFileOutput& operator<<(unsigned int);\n GZipFileOutput& operator<<(long unsigned int);\n GZipFileOutput& operator<<(float);\n GZipFileOutput& operator<<(double);\nprivate:\n gzFile gzf;\n bool open;\n};\n#endif\n\n\nclass SimpleFileOutput\n{\npublic:\n SimpleFileOutput(std::string filename);\n ~SimpleFileOutput();\n void close();\n SimpleFileOutput& operator<<(const std::string &str);\n SimpleFileOutput& operator<<(int);\n SimpleFileOutput& operator<<(long int);\n SimpleFileOutput& operator<<(unsigned int);\n SimpleFileOutput& operator<<(long unsigned int);\n SimpleFileOutput& operator<<(float);\n SimpleFileOutput& operator<<(double);\nprivate:\n bool ends_with(std::string const &filename,\n std::string const &suffix)\n {\n if (filename.length() < suffix.length()) return false;\n return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));\n }\n std::unique_ptr outfs;\n};\n\n\n#endif\nExplicit bool conversion for compatibility.#ifndef SIMPLE_IO\n#define SIMPLE_IO\n\n#include \n#include \n#include \n#include \n\n#ifndef NO_ZLIB\n#include \"zlib.h\"\n#endif\n\n\nclass FileInputType\n{\npublic:\n virtual bool getline(std::string &line) = 0;\n virtual ~FileInputType() { };\n};\n\nclass IFStreamInput : public FileInputType\n{\npublic:\n IFStreamInput(std::string filename) { ifstr.open(filename, std::ios_base::in); };\n ~IFStreamInput() { ifstr.close(); }\n bool getline(std::string &line) { return (bool)std::getline(ifstr, \nline); }\nprivate:\n std::ifstream ifstr;\n};\n\n#ifndef NO_ZLIB\nclass GZipFileInput : public FileInputType\n{\npublic:\n GZipFileInput(std::string filename);\n ~GZipFileInput();\n bool getline(std::string &line);\nprivate:\n gzFile gzf;\n};\n#endif\n\nclass SimpleFileInput\n{\npublic:\n SimpleFileInput(std::string filename);\n ~SimpleFileInput() { };\n bool getline(std::string &line) { return infs->getline(line); }\nprivate:\n bool ends_with(std::string const &filename,\n std::string const &suffix)\n {\n if (filename.length() < suffix.length()) return false;\n return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));\n }\n std::unique_ptr infs;\n};\n\n\nclass FileOutputType\n{\npublic:\n virtual void close() = 0;\n virtual FileOutputType& operator<<(const std::string &str) = 0;\n virtual FileOutputType& operator<<(int) = 0;\n virtual FileOutputType& operator<<(long int) = 0;\n virtual FileOutputType& operator<<(unsigned int) = 0;\n virtual FileOutputType& operator<<(long unsigned int) = 0;\n virtual FileOutputType& operator<<(float) = 0;\n virtual FileOutputType& operator<<(double) = 0;\n virtual ~FileOutputType() { };\n};\n\n\nclass OFStream: public FileOutputType\n{\npublic:\n OFStream(std::string filename);\n ~OFStream();\n void close();\n OFStream& operator<<(const std::string &str);\n OFStream& operator<<(int);\n OFStream& operator<<(long int);\n OFStream& operator<<(unsigned int);\n OFStream& operator<<(long unsigned int);\n OFStream& operator<<(float);\n OFStream& operator<<(double);\nprivate:\n std::ofstream ofstr;\n};\n\n\n#ifndef NO_ZLIB\nclass GZipFileOutput: public FileOutputType\n{\npublic:\n GZipFileOutput(std::string filename);\n ~GZipFileOutput();\n void close();\n GZipFileOutput& operator<<(const std::string &str);\n GZipFileOutput& operator<<(int);\n GZipFileOutput& operator<<(long int);\n GZipFileOutput& operator<<(unsigned int);\n GZipFileOutput& operator<<(long unsigned int);\n GZipFileOutput& operator<<(float);\n GZipFileOutput& operator<<(double);\nprivate:\n gzFile gzf;\n bool open;\n};\n#endif\n\n\nclass SimpleFileOutput\n{\npublic:\n SimpleFileOutput(std::string filename);\n ~SimpleFileOutput();\n void close();\n SimpleFileOutput& operator<<(const std::string &str);\n SimpleFileOutput& operator<<(int);\n SimpleFileOutput& operator<<(long int);\n SimpleFileOutput& operator<<(unsigned int);\n SimpleFileOutput& operator<<(long unsigned int);\n SimpleFileOutput& operator<<(float);\n SimpleFileOutput& operator<<(double);\nprivate:\n bool ends_with(std::string const &filename,\n std::string const &suffix)\n {\n if (filename.length() < suffix.length()) return false;\n return (0 == filename.compare(filename.length()-suffix.length(), suffix.length(), suffix));\n }\n std::unique_ptr outfs;\n};\n\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"map.h\"\n\nusing namespace std;\n\nMap::Map() {}\n\nMap::~Map() {}\n\nvoid Map::LoadMap(string MapFileName){\n\tstring Temp;\n\tfstream MapFile;\n\tint X = 0;\n\tint Y = 0;\n\t\n\tMapFile.open (MapFileName, fstream::in);\n\twhile ( MapFile >> Temp ){\n\t\tcout << Temp;\n\t\tmapArray[X][Y] = (unsigned short int)stoi(Temp);\n\t\tX++;\n\t\tif (X > MaxX){X = 0; Y++;}\n\t}\n\tMapFile.close();\n}\n\nint Map::Point(int X, int Y){\n\treturn (int)mapArray[X][Y];\n}\n\nbool Map::Passable(int X, int Y){\n\treturn (mapArray[X][Y] < PassableThreshhold);\n}\n\nstring Map::GetPlot(int X, int Y){\n\t\/\/Returns a 20x20 chunk of the map\n\tstring RetVal;\n\tstring Temp;\n\tfor (int i = X; i < X + 20; i++){\n\t\tfor (int j = Y; j < Y + 20; j++){\n\t\t\tif (i <= MaxX && i > -1 && j <= MaxY && j > -1){\n\t\t\t\tTemp = to_string(mapArray[i][j]);\n\t\t\t\tif (Temp.length() == 1) { RetVal += \"0\";}\n\t\t\t\tRetVal += Temp;\n\t\t\t} else {\n\t\t\tRetVal += \"-1\";\n\t\t\t}\n\t\t}\n\t}\n\treturn RetVal;\n}Work in progress#include \n#include \n#include \n#include \"map.h\"\n\nusing namespace std;\n\nMap::Map() {}\n\nMap::~Map() {}\n\nvoid Map::LoadMap(string MapFileName){\n\tstring Temp;\n\tfstream MapFile;\n\tint X = 0;\n\tint Y = 0;\n\tint F = 0;\n\t\n\tMapFile.open (MapFileName, fstream::in);\n\twhile ( MapFile >> Temp ){\n\t\tfor (int i = 0; i < Temp.length(); i++){\n\t\t\tif (Temp[i] == \",\"){\n\t\t\t\tmapArray[X][Y] = (unsigned short int)stoi(Temp.substr(F,i-F));\n\t\t\t\tF = i+1;\n\t\t\t\tcout << mapArray[X][Y];\n\t\t\t}\n\t\tX++;\n\t\tif (X > MaxX){X = 0; Y++;}\n\t}\n\tMapFile.close();\n}\n\nint Map::Point(int X, int Y){\n\treturn (int)mapArray[X][Y];\n}\n\nbool Map::Passable(int X, int Y){\n\treturn (mapArray[X][Y] < PassableThreshhold);\n}\n\nstring Map::GetPlot(int X, int Y){\n\t\/\/Returns a 20x20 chunk of the map\n\tstring RetVal;\n\tstring Temp;\n\tfor (int i = X; i < X + 20; i++){\n\t\tfor (int j = Y; j < Y + 20; j++){\n\t\t\tif (i <= MaxX && i > -1 && j <= MaxY && j > -1){\n\t\t\t\tTemp = to_string(mapArray[i][j]);\n\t\t\t\tif (Temp.length() == 1) { RetVal += \"0\";}\n\t\t\t\tRetVal += Temp;\n\t\t\t} else {\n\t\t\tRetVal += \"-1\";\n\t\t\t}\n\t\t}\n\t}\n\treturn RetVal;\n}<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsystemdeviceinfo.h\"\n#include \"qsysteminfocommon_p.h\"\n#include \n\nQTM_BEGIN_NAMESPACE\n Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate)\n\n#ifdef QT_SIMULATOR\nQSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); }\n#endif\n\n\/\/ device\n \/*!\n \\class QSystemDeviceInfo\n \\ingroup systeminfo\n \\inmodule QtSystemInfo\n \\brief The QSystemDeviceInfo class provides access to device information from the system.\n\n \\fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)\n\n Constructs a QSystemDeviceInfo with the given \\a parent.\n *\/\n \/*!\n \\enum QSystemDisplayInfo::DisplayOrientation\n This enum describes the current orientation of the display.\n\n \\value Unknown Orientation could not be determined.\n \\value Landscape Orientation is in landscape.\n \\value Portrait Orientation is in portrait.\n \\value InvertedLandscape Orientation is landscape inverted.\n \\value InvertedPortrait Orientation is portrait inverted.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::batteryLevelChanged(int level)\n\n This signal is emitted when battery level has changed.\n \\a level is the new level.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status)\n\n This signal is emitted when battery status has changed.\n \\a status is the new status.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state)\n\n This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall.\n \\a state is the new power state.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile)\n\n This signal is emitted whenever the users active profile changes, specified by \\a profile.\n *\/\n\n\n \/*!\n \\enum QSystemDeviceInfo::BatteryStatus\n This enum describes the status of the main battery.\n\n \\value NoBatteryLevel Battery level undetermined.\n \\value BatteryCritical Battery level is critical 3% or less.\n \\value BatteryVeryLow Battery level is very low, 10% or less.\n \\value BatteryLow Battery level is low 40% or less.\n \\value BatteryNormal Battery level is above 40%.\n\n *\/\n \/*!\n \\enum QSystemDeviceInfo::PowerState\n This enum describes the power state:\n\n \\value UnknownPower Power error.\n \\value BatteryPower On battery power.\n \\value WallPower On wall power.\n \\value WallPowerChargingBattery On wall power and charging main battery.\n\n *\/\n \/*!\n \\enum QSystemDeviceInfo::Profile\n This enum describes the current operating profile of the device or computer.\n\n \\value UnknownProfile Profile unknown or error.\n \\value SilentProfile Silent profile.\n \\value NormalProfile Normal profile.\n \\value LoudProfile Loud profile.\n \\value VibProfile Vibrate profile.\n \\value OfflineProfile Offline profile.\n \\value PowersaveProfile Powersave profile.\n \\value CustomProfile Custom profile.\n\n *\/\n\n \/*!\n \\enum QSystemDeviceInfo::SimStatus\n This enum describes the status is the sim card or cards.\n\n \\value SimNotAvailable SIM is not available on this device.\n \\value SingleSimAvailable One SIM card is available on this.\n \\value DualSimAvailable Two SIM cards are available on this device.\n \\value SimLocked Device has SIM lock enabled.\n *\/\n\n \/*!\n \\enum QSystemDeviceInfo::InputMethod\n This enum describes the device method of user input.\n\n \\value Keys Device has key\/buttons.\n \\value Keypad Device has keypad (1,2,3, etc).\n \\value Keyboard Device has qwerty keyboard.\n \\value SingleTouch Device has single touch screen.\n \\value MultiTouch Device has muti touch screen.\n \\value Mouse Device has a mouse.\n *\/\n \/*!\n \\fn void QSystemDeviceInfo::bluetoothStateChanged(bool on)\n\n This signal is emitted whenever bluetooth state changes, specified by \\a on.\n *\/\n\nQSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)\n : QObject(parent), d(deviceInfoPrivate())\n{\n qRegisterMetaType(\"QSystemDeviceInfo::BatteryStatus\");\n qRegisterMetaType(\"QSystemDeviceInfo::PowerState\");\n qRegisterMetaType(\"QSystemDeviceInfo::SimStatus\");\n qRegisterMetaType(\"QSystemDeviceInfo::Profile\");\n qRegisterMetaType(\"QSystemDeviceInfo::InputMethodFlags\");\n\n connect(d,SIGNAL(batteryLevelChanged(int)),\n this,SIGNAL(batteryLevelChanged(int)));\n\n connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),\n this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));\n\n connect(d,SIGNAL(bluetoothStateChanged(bool)),\n this,SIGNAL(bluetoothStateChanged(bool)));\n\n connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),\n this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));\n\n connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),\n this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));\n }\n\n\/*!\n Destroys the QSystemDeviceInfo object.\n *\/\nQSystemDeviceInfo::~QSystemDeviceInfo()\n{\n}\n\n\n\/*!\n \\internal\n\n This function is called when the client connects to signals.\n\n \\sa connectNotify()\n*\/\n\nvoid QSystemDeviceInfo::connectNotify(const char *signal)\n{\n Q_UNUSED(signal);\n}\n\n\/*!\n \\internal\n\n This function is called when the client disconnects from the signals.\n\n \\sa connectNotify()\n*\/\nvoid QSystemDeviceInfo::disconnectNotify(const char *signal)\n{\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n batteryLevelChanged(int))))) {\n disconnect(d,SIGNAL(batteryLevelChanged(int)),\n this,SIGNAL(batteryLevelChanged(int)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {\n disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),\n this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n bluetoothStateChanged(bool))))) {\n disconnect(d,SIGNAL(bluetoothStateChanged(bool)),\n this,SIGNAL(bluetoothStateChanged(bool)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n currentProfileChanged(QSystemDeviceInfo::Profile))))) {\n disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),\n this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n powerStateChanged(QSystemDeviceInfo::PowerState))))) {\n disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),\n this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));\n }\n}\n\n\n\/*!\n \\property QSystemDeviceInfo::inputMethodType\n \\brief The supported inputmethods.\n\n Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.\n*\/\nQSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType()\n{\n return deviceInfoPrivate()->inputMethodType();\n}\n\n\/*!\n \\property QSystemDeviceInfo::imei\n \\brief The IMEI.\n\n Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.\n*\/\nQString QSystemDeviceInfo::imei()\n{\n return deviceInfoPrivate()->imei();\n}\n\n\/*!\n \\property QSystemDeviceInfo::imsi\n \\brief The IMSI.\n\n Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none.\n*\/\nQString QSystemDeviceInfo::imsi()\n{\n return deviceInfoPrivate()->imsi();\n}\n\n\/*!\n \\property QSystemDeviceInfo::manufacturer\n \\brief The manufacture's name.\n\n Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor\n of the motherboard.\n*\/\nQString QSystemDeviceInfo::manufacturer()\n{\n return deviceInfoPrivate()->manufacturer();\n}\n\n\/*!\n \\property QSystemDeviceInfo::model\n \\brief The model name.\n\n Returns the model information of the device. In the case of desktops where no\n model information is present, the CPU architect, such as i686, and machine type, such as Server,\n Desktop or Laptop.\n*\/\nQString QSystemDeviceInfo::model()\n{\n return deviceInfoPrivate()->model();\n}\n\n\/*!\n \\property QSystemDeviceInfo::productName\n \\brief The product name.\n\n Returns the product name of the device. In the case where no product information is available,\n\n*\/\nQString QSystemDeviceInfo::productName()\n{\n return deviceInfoPrivate()->productName();\n}\n\/*!\n \\property QSystemDeviceInfo::batteryLevel\n \\brief The battery level.\n\n Returns the battery charge level as percentage 1 - 100 scale.\n*\/\nint QSystemDeviceInfo::batteryLevel() const\n{\n return deviceInfoPrivate()->batteryLevel();\n}\n\n \/*!\n \\property QSystemDeviceInfo::batteryStatus\n \\brief The battery status.\n\n Returns the battery charge status.\n*\/\nQSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus()\n{\n int level = batteryLevel();\n if(level < 4) {\n return QSystemDeviceInfo::BatteryCritical;\n } else if(level < 11) {\n return QSystemDeviceInfo::BatteryVeryLow;\n } else if(level < 41) {\n return QSystemDeviceInfo::BatteryLow;\n } else if(level > 40) {\n return QSystemDeviceInfo::BatteryNormal;\n }\n\n return QSystemDeviceInfo::NoBatteryLevel;\n}\n\n\/*!\n \\property QSystemDeviceInfo::simStatus\n \\brief the status of the sim card.\n Returns the QSystemDeviceInfo::simStatus status of SIM card.\n*\/\nQSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus()\n{\n return deviceInfoPrivate()->simStatus();\n}\n\/*!\n \\property QSystemDeviceInfo::isDeviceLocked\n \\brief Device lock.\n\n Returns true if the device is locked, otherwise false.\n*\/\nbool QSystemDeviceInfo::isDeviceLocked()\n{\n return deviceInfoPrivate()->isDeviceLocked();\n}\n\n\/*!\n \\property QSystemDeviceInfo::currentProfile\n \\brief the device profile\n Gets the current QSystemDeviceInfo::currentProfile device profile.\n*\/\nQSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile()\n{\n return deviceInfoPrivate()->currentProfile();\n}\n\n\/*!\n \\property QSystemDeviceInfo::currentPowerState\n \\brief the power state.\n\n Gets the current QSystemDeviceInfo::currentPowerState state.\n*\/\nQSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState()\n{\n return deviceInfoPrivate()->currentPowerState();\n}\n\n\/*!\n \\property QSystemDeviceInfo::currentBluetoothPowerState\n \\brief bluetooth power state.\n\n Gets the current bluetooth power state.\n *\/\nbool QSystemDeviceInfo::currentBluetoothPowerState()\n{\n return deviceInfoPrivate()->currentBluetoothPowerState();\n}\n\n#include \"moc_qsystemdeviceinfo.cpp\"\n\nQTM_END_NAMESPACE\n\nMinor fix to the documentation\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"qsystemdeviceinfo.h\"\n#include \"qsysteminfocommon_p.h\"\n#include \n\nQTM_BEGIN_NAMESPACE\n Q_GLOBAL_STATIC(QSystemDeviceInfoPrivate, deviceInfoPrivate)\n\n#ifdef QT_SIMULATOR\nQSystemDeviceInfoPrivate *getSystemDeviceInfoPrivate() { return deviceInfoPrivate(); }\n#endif\n\n\/\/ device\n \/*!\n \\class QSystemDeviceInfo\n \\ingroup systeminfo\n \\inmodule QtSystemInfo\n \\brief The QSystemDeviceInfo class provides access to device information from the system.\n *\/\n\n \/*!\n \\fn QSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)\n\n Constructs a QSystemDeviceInfo with the given \\a parent.\n *\/\n\n \/*!\n \\enum QSystemDisplayInfo::DisplayOrientation\n This enum describes the current orientation of the display.\n\n \\value Unknown Orientation could not be determined.\n \\value Landscape Orientation is in landscape.\n \\value Portrait Orientation is in portrait.\n \\value InvertedLandscape Orientation is landscape inverted.\n \\value InvertedPortrait Orientation is portrait inverted.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::batteryLevelChanged(int level)\n\n This signal is emitted when battery level has changed.\n \\a level is the new level.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::batteryStatusChanged(QSystemDeviceInfo::BatteryStatus status)\n\n This signal is emitted when battery status has changed.\n \\a status is the new status.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::powerStateChanged(QSystemDeviceInfo::PowerState state)\n\n This signal is emitted when the power state has changed, such as when a phone gets plugged in to the wall.\n \\a state is the new power state.\n *\/\n\n \/*!\n \\fn void QSystemDeviceInfo::currentProfileChanged(QSystemDeviceInfo::Profile profile)\n\n This signal is emitted whenever the users active profile changes, specified by \\a profile.\n *\/\n\n\n \/*!\n \\enum QSystemDeviceInfo::BatteryStatus\n This enum describes the status of the main battery.\n\n \\value NoBatteryLevel Battery level undetermined.\n \\value BatteryCritical Battery level is critical 3% or less.\n \\value BatteryVeryLow Battery level is very low, 10% or less.\n \\value BatteryLow Battery level is low 40% or less.\n \\value BatteryNormal Battery level is above 40%.\n\n *\/\n \/*!\n \\enum QSystemDeviceInfo::PowerState\n This enum describes the power state:\n\n \\value UnknownPower Power error.\n \\value BatteryPower On battery power.\n \\value WallPower On wall power.\n \\value WallPowerChargingBattery On wall power and charging main battery.\n\n *\/\n \/*!\n \\enum QSystemDeviceInfo::Profile\n This enum describes the current operating profile of the device or computer.\n\n \\value UnknownProfile Profile unknown or error.\n \\value SilentProfile Silent profile.\n \\value NormalProfile Normal profile.\n \\value LoudProfile Loud profile.\n \\value VibProfile Vibrate profile.\n \\value OfflineProfile Offline profile.\n \\value PowersaveProfile Powersave profile.\n \\value CustomProfile Custom profile.\n\n *\/\n\n \/*!\n \\enum QSystemDeviceInfo::SimStatus\n This enum describes the status is the sim card or cards.\n\n \\value SimNotAvailable SIM is not available on this device.\n \\value SingleSimAvailable One SIM card is available on this.\n \\value DualSimAvailable Two SIM cards are available on this device.\n \\value SimLocked Device has SIM lock enabled.\n *\/\n\n \/*!\n \\enum QSystemDeviceInfo::InputMethod\n This enum describes the device method of user input.\n\n \\value Keys Device has key\/buttons.\n \\value Keypad Device has keypad (1,2,3, etc).\n \\value Keyboard Device has qwerty keyboard.\n \\value SingleTouch Device has single touch screen.\n \\value MultiTouch Device has muti touch screen.\n \\value Mouse Device has a mouse.\n *\/\n \/*!\n \\fn void QSystemDeviceInfo::bluetoothStateChanged(bool on)\n\n This signal is emitted whenever bluetooth state changes, specified by \\a on.\n *\/\n\nQSystemDeviceInfo::QSystemDeviceInfo(QObject *parent)\n : QObject(parent), d(deviceInfoPrivate())\n{\n qRegisterMetaType(\"QSystemDeviceInfo::BatteryStatus\");\n qRegisterMetaType(\"QSystemDeviceInfo::PowerState\");\n qRegisterMetaType(\"QSystemDeviceInfo::SimStatus\");\n qRegisterMetaType(\"QSystemDeviceInfo::Profile\");\n qRegisterMetaType(\"QSystemDeviceInfo::InputMethodFlags\");\n\n connect(d,SIGNAL(batteryLevelChanged(int)),\n this,SIGNAL(batteryLevelChanged(int)));\n\n connect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),\n this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));\n\n connect(d,SIGNAL(bluetoothStateChanged(bool)),\n this,SIGNAL(bluetoothStateChanged(bool)));\n\n connect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),\n this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));\n\n connect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),\n this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));\n }\n\n\/*!\n Destroys the QSystemDeviceInfo object.\n *\/\nQSystemDeviceInfo::~QSystemDeviceInfo()\n{\n}\n\n\n\/*!\n \\internal\n\n This function is called when the client connects to signals.\n\n \\sa connectNotify()\n*\/\n\nvoid QSystemDeviceInfo::connectNotify(const char *signal)\n{\n Q_UNUSED(signal);\n}\n\n\/*!\n \\internal\n\n This function is called when the client disconnects from the signals.\n\n \\sa connectNotify()\n*\/\nvoid QSystemDeviceInfo::disconnectNotify(const char *signal)\n{\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n batteryLevelChanged(int))))) {\n disconnect(d,SIGNAL(batteryLevelChanged(int)),\n this,SIGNAL(batteryLevelChanged(int)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n batteryStatusChanged(QSystemDeviceInfo::BatteryStatus))))) {\n disconnect(d,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)),\n this,SIGNAL(batteryStatusChanged(QSystemDeviceInfo::BatteryStatus)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n bluetoothStateChanged(bool))))) {\n disconnect(d,SIGNAL(bluetoothStateChanged(bool)),\n this,SIGNAL(bluetoothStateChanged(bool)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n currentProfileChanged(QSystemDeviceInfo::Profile))))) {\n disconnect(d,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)),\n this,SIGNAL(currentProfileChanged(QSystemDeviceInfo::Profile)));\n }\n if (QLatin1String(signal) == QLatin1String(QMetaObject::normalizedSignature(SIGNAL(\n powerStateChanged(QSystemDeviceInfo::PowerState))))) {\n disconnect(d,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)),\n this,SIGNAL(powerStateChanged(QSystemDeviceInfo::PowerState)));\n }\n}\n\n\n\/*!\n \\property QSystemDeviceInfo::inputMethodType\n \\brief The supported inputmethods.\n\n Returns the QSystemDeviceInfo::InputMethodFlags InputMethodType that the system uses.\n*\/\nQSystemDeviceInfo::InputMethodFlags QSystemDeviceInfo::inputMethodType()\n{\n return deviceInfoPrivate()->inputMethodType();\n}\n\n\/*!\n \\property QSystemDeviceInfo::imei\n \\brief The IMEI.\n\n Returns the International Mobile Equipment Identity (IMEI), or a null QString in the case of none.\n*\/\nQString QSystemDeviceInfo::imei()\n{\n return deviceInfoPrivate()->imei();\n}\n\n\/*!\n \\property QSystemDeviceInfo::imsi\n \\brief The IMSI.\n\n Returns the International Mobile Subscriber Identity (IMSI), or a null QString in the case of none.\n*\/\nQString QSystemDeviceInfo::imsi()\n{\n return deviceInfoPrivate()->imsi();\n}\n\n\/*!\n \\property QSystemDeviceInfo::manufacturer\n \\brief The manufacture's name.\n\n Returns the name of the manufacturer of this device. In the case of desktops, the name of the vendor\n of the motherboard.\n*\/\nQString QSystemDeviceInfo::manufacturer()\n{\n return deviceInfoPrivate()->manufacturer();\n}\n\n\/*!\n \\property QSystemDeviceInfo::model\n \\brief The model name.\n\n Returns the model information of the device. In the case of desktops where no\n model information is present, the CPU architect, such as i686, and machine type, such as Server,\n Desktop or Laptop.\n*\/\nQString QSystemDeviceInfo::model()\n{\n return deviceInfoPrivate()->model();\n}\n\n\/*!\n \\property QSystemDeviceInfo::productName\n \\brief The product name.\n\n Returns the product name of the device. In the case where no product information is available,\n\n*\/\nQString QSystemDeviceInfo::productName()\n{\n return deviceInfoPrivate()->productName();\n}\n\/*!\n \\property QSystemDeviceInfo::batteryLevel\n \\brief The battery level.\n\n Returns the battery charge level as percentage 1 - 100 scale.\n*\/\nint QSystemDeviceInfo::batteryLevel() const\n{\n return deviceInfoPrivate()->batteryLevel();\n}\n\n \/*!\n \\property QSystemDeviceInfo::batteryStatus\n \\brief The battery status.\n\n Returns the battery charge status.\n*\/\nQSystemDeviceInfo::BatteryStatus QSystemDeviceInfo::batteryStatus()\n{\n int level = batteryLevel();\n if(level < 4) {\n return QSystemDeviceInfo::BatteryCritical;\n } else if(level < 11) {\n return QSystemDeviceInfo::BatteryVeryLow;\n } else if(level < 41) {\n return QSystemDeviceInfo::BatteryLow;\n } else if(level > 40) {\n return QSystemDeviceInfo::BatteryNormal;\n }\n\n return QSystemDeviceInfo::NoBatteryLevel;\n}\n\n\/*!\n \\property QSystemDeviceInfo::simStatus\n \\brief the status of the sim card.\n Returns the QSystemDeviceInfo::simStatus status of SIM card.\n*\/\nQSystemDeviceInfo::SimStatus QSystemDeviceInfo::simStatus()\n{\n return deviceInfoPrivate()->simStatus();\n}\n\/*!\n \\property QSystemDeviceInfo::isDeviceLocked\n \\brief Device lock.\n\n Returns true if the device is locked, otherwise false.\n*\/\nbool QSystemDeviceInfo::isDeviceLocked()\n{\n return deviceInfoPrivate()->isDeviceLocked();\n}\n\n\/*!\n \\property QSystemDeviceInfo::currentProfile\n \\brief the device profile\n Gets the current QSystemDeviceInfo::currentProfile device profile.\n*\/\nQSystemDeviceInfo::Profile QSystemDeviceInfo::currentProfile()\n{\n return deviceInfoPrivate()->currentProfile();\n}\n\n\/*!\n \\property QSystemDeviceInfo::currentPowerState\n \\brief the power state.\n\n Gets the current QSystemDeviceInfo::currentPowerState state.\n*\/\nQSystemDeviceInfo::PowerState QSystemDeviceInfo::currentPowerState()\n{\n return deviceInfoPrivate()->currentPowerState();\n}\n\n\/*!\n \\property QSystemDeviceInfo::currentBluetoothPowerState\n \\brief bluetooth power state.\n\n Gets the current bluetooth power state.\n *\/\nbool QSystemDeviceInfo::currentBluetoothPowerState()\n{\n return deviceInfoPrivate()->currentBluetoothPowerState();\n}\n\n#include \"moc_qsystemdeviceinfo.cpp\"\n\nQTM_END_NAMESPACE\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nnamespace mtp\n{\n\tnamespace\n\t{\n\t\tconst std::string UknownArtist\t\t(\"UknownArtist\");\n\t\tconst std::string UknownAlbum\t\t(\"UknownAlbum\");\n\t\tconst std::string VariousArtists\t(\"VariousArtists\");\n\t}\n\n\tLibrary::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)\n\t{\n\t\tNameToObjectIdMap list;\n\t\tauto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);\n\t\tlist.reserve(folders.ObjectHandles.size());\n\n\t\tfor(auto id : folders.ObjectHandles)\n\t\t{\n\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);\n\t\t\tlist.insert(std::make_pair(name, id));\n\t\t}\n\t\treturn list;\n\t}\n\n\tObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)\n\t{\n\t\tauto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);\n\t\tfor (auto id : objects.ObjectHandles)\n\t\t{\n\t\t\tauto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);\n\t\t\tif (name == oname)\n\t\t\t\treturn id;\n\t\t}\n\t\treturn _session->CreateDirectory(name, parentId, _storage).ObjectId;\n\t}\n\n\tLibrary::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session)\n\t{\n\t\tauto storages = _session->GetStorageIDs();\n\t\tif (storages.StorageIDs.empty())\n\t\t\tthrow std::runtime_error(\"no storages found\");\n\n\t\tu64 progress = 0, total = 0;\n\t\tif (reporter)\n\t\t\treporter(State::Initialising, progress, total);\n\n\t\t_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);\n\t\t{\n\t\t\tauto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);\n\t\t\t_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();\n\t\t}\n\n\t\t_storage = storages.StorageIDs[0]; \/\/picking up first storage.\n\t\t\/\/zune fails to create artist\/album without storage id\n\n\t\t{\n\t\t\tmsg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);\n\t\t\tfor (auto id : rootFolders.ObjectHandles)\n\t\t\t{\n\t\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);\n\t\t\t\tif (name == \"Artists\")\n\t\t\t\t\t_artistsFolder = id;\n\t\t\t\telse if (name == \"Albums\")\n\t\t\t\t\t_albumsFolder = id;\n\t\t\t\telse if (name == \"Music\")\n\t\t\t\t\t_musicFolder = id;\n\t\t\t}\n\t\t}\n\t\tif (_artistSupported && _artistsFolder == ObjectId())\n\t\t\t_artistsFolder = _session->CreateDirectory(\"Artists\", Session::Root, _storage).ObjectId;\n\t\tif (_albumsFolder == ObjectId())\n\t\t\t_albumsFolder = _session->CreateDirectory(\"Albums\", Session::Root, _storage).ObjectId;\n\t\tif (_musicFolder == ObjectId())\n\t\t\t_musicFolder = _session->CreateDirectory(\"Music\", Session::Root, _storage).ObjectId;\n\n\t\tdebug(\"artists folder: \", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);\n\t\tdebug(\"albums folder: \", _albumsFolder.Id);\n\t\tdebug(\"music folder: \", _musicFolder.Id);\n\n\t\tauto musicFolders = ListAssociations(_musicFolder);\n\n\t\tusing namespace mtp;\n\n\t\tmsg::ObjectHandles artists;\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tdebug(\"getting artists...\");\n\t\t\tif (reporter)\n\t\t\t\treporter(State::QueryingArtists, progress, total);\n\t\t\tartists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);\n\n\t\t\ttotal += artists.ObjectHandles.size();\n\t\t\tif (reporter)\n\t\t\t\treporter(State::LoadingArtists, progress, total);\n\t\t}\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tfor (auto id : artists.ObjectHandles)\n\t\t\t{\n\t\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);\n\t\t\t\tdebug(\"artist: \", name, \"\\t\", id.Id);\n\t\t\t\tauto artist = std::make_shared();\n\t\t\t\tartist->Id = id;\n\t\t\t\tartist->Name = name;\n\t\t\t\tauto it = musicFolders.find(name);\n\t\t\t\tif (it != musicFolders.end())\n\t\t\t\t\tartist->MusicFolderId = it->second;\n\t\t\t\telse\n\t\t\t\t\tartist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;\n\n\t\t\t\t_artists.insert(std::make_pair(name, artist));\n\t\t\t\tif (reporter)\n\t\t\t\t\treporter(State::LoadingArtists, ++progress, total);\n\t\t\t}\n\t\t}\n\n\t\tstd::unordered_map albumFolders;\n\t\t{\n\t\t\tdebug(\"getting albums...\");\n\t\t\tif (reporter)\n\t\t\t\treporter(State::QueryingAlbums, progress, total);\n\n\t\t\tauto albums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);\n\t\t\ttotal += albums.ObjectHandles.size();\n\t\t\tif (reporter)\n\t\t\t\treporter(State::LoadingAlbums, progress, total);\n\n\t\t\tfor (auto id : albums.ObjectHandles)\n\t\t\t{\n\t\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);\n\t\t\t\tauto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);\n\t\t\t\tstd::string albumDate;\n\n\t\t\t\tif (_albumDateAuthoredSupported)\n\t\t\t\t\talbumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);\n\n\t\t\t\tauto artist = GetArtist(artistName);\n\t\t\t\tif (!artist)\n\t\t\t\t\tartist = CreateArtist(artistName);\n\n\t\t\t\tdebug(\"album: \", artistName, \" -- \", name, \"\\t\", id.Id, \"\\t\", albumDate);\n\t\t\t\tauto album = std::make_shared();\n\t\t\t\talbum->Name = name;\n\t\t\t\talbum->Artist = artist;\n\t\t\t\talbum->Id = id;\n\t\t\t\talbum->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;\n\t\t\t\tif (albumFolders.find(artist) == albumFolders.end()) {\n\t\t\t\t\talbumFolders[artist] = ListAssociations(artist->MusicFolderId);\n\t\t\t\t}\n\t\t\t\tauto it = albumFolders.find(artist);\n\t\t\t\tif (it == albumFolders.end())\n\t\t\t\t\tthrow std::runtime_error(\"no iterator after insert, internal error\");\n\n\t\t\t\t{\n\t\t\t\t\tauto refs = _session->GetObjectReferences(id).ObjectHandles;\n\t\t\t\t\tstd::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));\n\t\t\t\t\tfor(auto trackId : refs)\n\t\t\t\t\t{\n\t\t\t\t\t\tauto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);\n\t\t\t\t\t\tauto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);\n\t\t\t\t\t\tdebug(\"[\", index, \"]: \", name);\n\t\t\t\t\t\talbum->Tracks.insert(std::make_pair(name, index));\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tconst auto & albums = it->second;\n\t\t\t\tauto alit = albums.find(name);\n\t\t\t\tif (alit != albums.end())\n\t\t\t\t\talbum->MusicFolderId = alit->second;\n\t\t\t\telse\n\t\t\t\t\talbum->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;\n\n\t\t\t\t_albums.insert(std::make_pair(std::make_pair(artist, name), album));\n\t\t\t\tif (reporter)\n\t\t\t\t\treporter(State::LoadingAlbums, ++progress, total);\n\t\t\t}\n\t\t}\n\n\t\tif (reporter)\n\t\t\treporter(State::Loaded, progress, total);\n\t}\n\n\tLibrary::~Library()\n\t{ }\n\n\tLibrary::ArtistPtr Library::GetArtist(std::string name)\n\t{\n\t\tif (name.empty())\n\t\t\tname = UknownArtist;\n\n\t\tauto it = _artists.find(name);\n\t\treturn it != _artists.end()? it->second: ArtistPtr();\n\t}\n\n\n\tLibrary::ArtistPtr Library::CreateArtist(std::string name)\n\t{\n\t\tif (name.empty())\n\t\t\tname = UknownArtist;\n\n\t\tauto artist = std::make_shared();\n\t\tartist->Name = name;\n\t\tartist->MusicFolderId = GetOrCreate(_musicFolder, name);\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tByteArray propList;\n\t\t\tOutputStream os(propList);\n\n\t\t\tos.Write32(2); \/\/number of props\n\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Name));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(name);\n\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::ObjectFilename));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(name + \".art\");\n\n\t\t\tauto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);\n\t\t\tartist->Id = response.ObjectId;\n\t\t}\n\n\t\t_artists.insert(std::make_pair(name, artist));\n\t\treturn artist;\n\t}\n\n\tLibrary::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)\n\t{\n\t\tif (name.empty())\n\t\t\tname = UknownAlbum;\n\n\t\tauto it = _albums.find(std::make_pair(artist, name));\n\t\treturn it != _albums.end()? it->second: AlbumPtr();\n\t}\n\n\tLibrary::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)\n\t{\n\t\tif (!artist)\n\t\t\tthrow std::runtime_error(\"artists is required\");\n\n\t\tif (name.empty())\n\t\t\tname = UknownAlbum;\n\n\t\tByteArray propList;\n\t\tOutputStream os(propList);\n\t\tbool sendYear = year != 0 && _albumDateAuthoredSupported;\n\n\t\tos.Write32(3 + (sendYear? 1: 0)); \/\/number of props\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::ArtistId));\n\t\t\tos.Write16(static_cast(DataTypeCode::Uint32));\n\t\t\tos.Write32(artist->Id.Id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Artist));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(artist->Name);\n\t\t}\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::Name));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(name);\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::ObjectFilename));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(artist->Name + \"--\" + name + \".alb\");\n\n\t\tif (sendYear)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::DateAuthored));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(ConvertYear(year));\n\t\t}\n\n\t\tauto album = std::make_shared();\n\t\talbum->Artist = artist;\n\t\talbum->Name = name;\n\t\talbum->Year = year;\n\t\talbum->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);\n\n\t\tauto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);\n\t\talbum->Id = response.ObjectId;\n\n\t\t_albums.insert(std::make_pair(std::make_pair(artist, name), album));\n\t\treturn album;\n\t}\n\n\tbool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)\n\t{\n\t\tif (!album)\n\t\t\treturn false;\n\n\t\tauto & tracks = album->Tracks;\n\t\tauto range = tracks.equal_range(name);\n\t\tfor(auto i = range.first; i != range.second; ++i)\n\t\t{\n\t\t\tif (i->second == trackIndex)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tLibrary::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,\n\t\tconst AlbumPtr & album,\n\t\tObjectFormat type,\n\t\tstd::string name, const std::string & genre, int trackIndex,\n\t\tconst std::string &filename, size_t size)\n\t{\n\t\tByteArray propList;\n\t\tOutputStream os(propList);\n\n\t\tos.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); \/\/number of props\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::ArtistId));\n\t\t\tos.Write16(static_cast(DataTypeCode::Uint32));\n\t\t\tos.Write32(artist->Id.Id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Artist));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(artist->Name);\n\t\t}\n\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::Name));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(name);\n\n\t\tif (trackIndex)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Track));\n\t\t\tos.Write16(static_cast(DataTypeCode::Uint16));\n\t\t\tos.Write16(trackIndex);\n\t\t}\n\n\t\tif (!genre.empty())\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Genre));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(genre);\n\t\t}\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::ObjectFilename));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(filename);\n\n\t\tauto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);\n\t\tNewTrackInfo ti;\n\t\tti.Id = response.ObjectId;\n\t\tti.Name = name;\n\t\tti.Index = trackIndex;\n\t\treturn ti;\n\t}\n\n\tvoid Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)\n\t{\n\t\tif (!album)\n\t\t\treturn;\n\n\t\tauto & refs = album->Refs;\n\t\tauto & tracks = album->Tracks;\n\n\t\tmsg::ObjectHandles handles;\n\t\tstd::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));\n\t\thandles.ObjectHandles.push_back(ti.Id);\n\t\t_session->SetObjectReferences(album->Id, handles);\n\t\trefs.insert(ti.Id);\n\t\ttracks.insert(std::make_pair(ti.Name, ti.Index));\n\t}\n\n\n\tbool Library::Supported(const mtp::SessionPtr & session)\n\t{\n\t\tauto & gdi = session->GetDeviceInfo();\n\t\treturn\n\t\t\tgdi.Supports(OperationCode::SendObjectPropList) &&\n\t\t\tgdi.Supports(OperationCode::SetObjectReferences) &&\n\t\t\tgdi.Supports(ObjectFormat::AbstractAudioAlbum);\n\t\t;\n\t}\n\n}\nload object refs at the beginning, providing consistent total#include \n#include \n#include \n#include \n\nnamespace mtp\n{\n\tnamespace\n\t{\n\t\tconst std::string UknownArtist\t\t(\"UknownArtist\");\n\t\tconst std::string UknownAlbum\t\t(\"UknownAlbum\");\n\t\tconst std::string VariousArtists\t(\"VariousArtists\");\n\t}\n\n\tLibrary::NameToObjectIdMap Library::ListAssociations(ObjectId parentId)\n\t{\n\t\tNameToObjectIdMap list;\n\t\tauto folders = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);\n\t\tlist.reserve(folders.ObjectHandles.size());\n\n\t\tfor(auto id : folders.ObjectHandles)\n\t\t{\n\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);\n\t\t\tlist.insert(std::make_pair(name, id));\n\t\t}\n\t\treturn list;\n\t}\n\n\tObjectId Library::GetOrCreate(ObjectId parentId, const std::string &name)\n\t{\n\t\tauto objects = _session->GetObjectHandles(_storage, mtp::ObjectFormat::Association, parentId);\n\t\tfor (auto id : objects.ObjectHandles)\n\t\t{\n\t\t\tauto oname = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);\n\t\t\tif (name == oname)\n\t\t\t\treturn id;\n\t\t}\n\t\treturn _session->CreateDirectory(name, parentId, _storage).ObjectId;\n\t}\n\n\tLibrary::Library(const mtp::SessionPtr & session, ProgressReporter && reporter): _session(session)\n\t{\n\t\tauto storages = _session->GetStorageIDs();\n\t\tif (storages.StorageIDs.empty())\n\t\t\tthrow std::runtime_error(\"no storages found\");\n\n\t\tu64 progress = 0, total = 0;\n\t\tif (reporter)\n\t\t\treporter(State::Initialising, progress, total);\n\n\t\t_artistSupported = _session->GetDeviceInfo().Supports(ObjectFormat::Artist);\n\t\t{\n\t\t\tauto propsSupported = _session->GetObjectPropertiesSupported(ObjectFormat::AbstractAudioAlbum);\n\t\t\t_albumDateAuthoredSupported = std::find(propsSupported.ObjectPropertyCodes.begin(), propsSupported.ObjectPropertyCodes.end(), ObjectProperty::DateAuthored) != propsSupported.ObjectPropertyCodes.end();\n\t\t}\n\n\t\t_storage = storages.StorageIDs[0]; \/\/picking up first storage.\n\t\t\/\/zune fails to create artist\/album without storage id\n\n\t\t{\n\t\t\tmsg::ObjectHandles rootFolders = _session->GetObjectHandles(Session::AllStorages, mtp::ObjectFormat::Association, Session::Root);\n\t\t\tfor (auto id : rootFolders.ObjectHandles)\n\t\t\t{\n\t\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::ObjectFilename);\n\t\t\t\tif (name == \"Artists\")\n\t\t\t\t\t_artistsFolder = id;\n\t\t\t\telse if (name == \"Albums\")\n\t\t\t\t\t_albumsFolder = id;\n\t\t\t\telse if (name == \"Music\")\n\t\t\t\t\t_musicFolder = id;\n\t\t\t}\n\t\t}\n\t\tif (_artistSupported && _artistsFolder == ObjectId())\n\t\t\t_artistsFolder = _session->CreateDirectory(\"Artists\", Session::Root, _storage).ObjectId;\n\t\tif (_albumsFolder == ObjectId())\n\t\t\t_albumsFolder = _session->CreateDirectory(\"Albums\", Session::Root, _storage).ObjectId;\n\t\tif (_musicFolder == ObjectId())\n\t\t\t_musicFolder = _session->CreateDirectory(\"Music\", Session::Root, _storage).ObjectId;\n\n\t\tdebug(\"artists folder: \", _artistsFolder != ObjectId()? _artistsFolder.Id: 0);\n\t\tdebug(\"albums folder: \", _albumsFolder.Id);\n\t\tdebug(\"music folder: \", _musicFolder.Id);\n\n\t\tauto musicFolders = ListAssociations(_musicFolder);\n\n\t\tusing namespace mtp;\n\n\t\tmsg::ObjectHandles artists, albums;\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tdebug(\"getting artists...\");\n\t\t\tif (reporter)\n\t\t\t\treporter(State::QueryingArtists, progress, total);\n\t\t\tartists = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::Artist, Session::Device);\n\n\t\t\ttotal += artists.ObjectHandles.size();\n\t\t\tif (reporter)\n\t\t\t\treporter(State::LoadingArtists, progress, total);\n\t\t}\n\t\t{\n\t\t\tdebug(\"getting albums...\");\n\t\t\tif (reporter)\n\t\t\t\treporter(State::QueryingAlbums, progress, total);\n\n\t\t\talbums = _session->GetObjectHandles(Session::AllStorages, ObjectFormat::AbstractAudioAlbum, Session::Device);\n\t\t\ttotal += albums.ObjectHandles.size();\n\t\t\tif (reporter)\n\t\t\t\treporter(State::LoadingAlbums, progress, total);\n\t\t}\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tfor (auto id : artists.ObjectHandles)\n\t\t\t{\n\t\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);\n\t\t\t\tdebug(\"artist: \", name, \"\\t\", id.Id);\n\t\t\t\tauto artist = std::make_shared();\n\t\t\t\tartist->Id = id;\n\t\t\t\tartist->Name = name;\n\t\t\t\tauto it = musicFolders.find(name);\n\t\t\t\tif (it != musicFolders.end())\n\t\t\t\t\tartist->MusicFolderId = it->second;\n\t\t\t\telse\n\t\t\t\t\tartist->MusicFolderId = _session->CreateDirectory(name, _musicFolder, _storage).ObjectId;\n\n\t\t\t\t_artists.insert(std::make_pair(name, artist));\n\t\t\t\tif (reporter)\n\t\t\t\t\treporter(State::LoadingArtists, ++progress, total);\n\t\t\t}\n\t\t}\n\n\t\tstd::unordered_map albumFolders;\n\t\tfor (auto id : albums.ObjectHandles)\n\t\t{\n\t\t\tauto name = _session->GetObjectStringProperty(id, ObjectProperty::Name);\n\t\t\tauto artistName = _session->GetObjectStringProperty(id, ObjectProperty::Artist);\n\t\t\tstd::string albumDate;\n\n\t\t\tif (_albumDateAuthoredSupported)\n\t\t\t\talbumDate = _session->GetObjectStringProperty(id, ObjectProperty::DateAuthored);\n\n\t\t\tauto artist = GetArtist(artistName);\n\t\t\tif (!artist)\n\t\t\t\tartist = CreateArtist(artistName);\n\n\t\t\tdebug(\"album: \", artistName, \" -- \", name, \"\\t\", id.Id, \"\\t\", albumDate);\n\t\t\tauto album = std::make_shared();\n\t\t\talbum->Name = name;\n\t\t\talbum->Artist = artist;\n\t\t\talbum->Id = id;\n\t\t\talbum->Year = !albumDate.empty()? ConvertDateTime(albumDate): 0;\n\t\t\tif (albumFolders.find(artist) == albumFolders.end()) {\n\t\t\t\talbumFolders[artist] = ListAssociations(artist->MusicFolderId);\n\t\t\t}\n\t\t\tauto it = albumFolders.find(artist);\n\t\t\tif (it == albumFolders.end())\n\t\t\t\tthrow std::runtime_error(\"no iterator after insert, internal error\");\n\n\t\t\t{\n\t\t\t\tauto refs = _session->GetObjectReferences(id).ObjectHandles;\n\t\t\t\tstd::copy(refs.begin(), refs.end(), std::inserter(album->Refs, album->Refs.begin()));\n\t\t\t\tfor(auto trackId : refs)\n\t\t\t\t{\n\t\t\t\t\tauto name = _session->GetObjectStringProperty(trackId, ObjectProperty::Name);\n\t\t\t\t\tauto index = _session->GetObjectIntegerProperty(trackId, ObjectProperty::Track);\n\t\t\t\t\tdebug(\"[\", index, \"]: \", name);\n\t\t\t\t\talbum->Tracks.insert(std::make_pair(name, index));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tconst auto & albums = it->second;\n\t\t\tauto alit = albums.find(name);\n\t\t\tif (alit != albums.end())\n\t\t\t\talbum->MusicFolderId = alit->second;\n\t\t\telse\n\t\t\t\talbum->MusicFolderId = _session->CreateDirectory(name, artist->MusicFolderId, _storage).ObjectId;\n\n\t\t\t_albums.insert(std::make_pair(std::make_pair(artist, name), album));\n\t\t\tif (reporter)\n\t\t\t\treporter(State::LoadingAlbums, ++progress, total);\n\t\t}\n\n\t\tif (reporter)\n\t\t\treporter(State::Loaded, progress, total);\n\t}\n\n\tLibrary::~Library()\n\t{ }\n\n\tLibrary::ArtistPtr Library::GetArtist(std::string name)\n\t{\n\t\tif (name.empty())\n\t\t\tname = UknownArtist;\n\n\t\tauto it = _artists.find(name);\n\t\treturn it != _artists.end()? it->second: ArtistPtr();\n\t}\n\n\n\tLibrary::ArtistPtr Library::CreateArtist(std::string name)\n\t{\n\t\tif (name.empty())\n\t\t\tname = UknownArtist;\n\n\t\tauto artist = std::make_shared();\n\t\tartist->Name = name;\n\t\tartist->MusicFolderId = GetOrCreate(_musicFolder, name);\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tByteArray propList;\n\t\t\tOutputStream os(propList);\n\n\t\t\tos.Write32(2); \/\/number of props\n\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Name));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(name);\n\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::ObjectFilename));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(name + \".art\");\n\n\t\t\tauto response = _session->SendObjectPropList(_storage, _artistsFolder, ObjectFormat::Artist, 0, propList);\n\t\t\tartist->Id = response.ObjectId;\n\t\t}\n\n\t\t_artists.insert(std::make_pair(name, artist));\n\t\treturn artist;\n\t}\n\n\tLibrary::AlbumPtr Library::GetAlbum(const ArtistPtr & artist, std::string name)\n\t{\n\t\tif (name.empty())\n\t\t\tname = UknownAlbum;\n\n\t\tauto it = _albums.find(std::make_pair(artist, name));\n\t\treturn it != _albums.end()? it->second: AlbumPtr();\n\t}\n\n\tLibrary::AlbumPtr Library::CreateAlbum(const ArtistPtr & artist, std::string name, int year)\n\t{\n\t\tif (!artist)\n\t\t\tthrow std::runtime_error(\"artists is required\");\n\n\t\tif (name.empty())\n\t\t\tname = UknownAlbum;\n\n\t\tByteArray propList;\n\t\tOutputStream os(propList);\n\t\tbool sendYear = year != 0 && _albumDateAuthoredSupported;\n\n\t\tos.Write32(3 + (sendYear? 1: 0)); \/\/number of props\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::ArtistId));\n\t\t\tos.Write16(static_cast(DataTypeCode::Uint32));\n\t\t\tos.Write32(artist->Id.Id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Artist));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(artist->Name);\n\t\t}\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::Name));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(name);\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::ObjectFilename));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(artist->Name + \"--\" + name + \".alb\");\n\n\t\tif (sendYear)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::DateAuthored));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(ConvertYear(year));\n\t\t}\n\n\t\tauto album = std::make_shared();\n\t\talbum->Artist = artist;\n\t\talbum->Name = name;\n\t\talbum->Year = year;\n\t\talbum->MusicFolderId = GetOrCreate(artist->MusicFolderId, name);\n\n\t\tauto response = _session->SendObjectPropList(_storage, _albumsFolder, ObjectFormat::AbstractAudioAlbum, 0, propList);\n\t\talbum->Id = response.ObjectId;\n\n\t\t_albums.insert(std::make_pair(std::make_pair(artist, name), album));\n\t\treturn album;\n\t}\n\n\tbool Library::HasTrack(const AlbumPtr & album, const std::string &name, int trackIndex)\n\t{\n\t\tif (!album)\n\t\t\treturn false;\n\n\t\tauto & tracks = album->Tracks;\n\t\tauto range = tracks.equal_range(name);\n\t\tfor(auto i = range.first; i != range.second; ++i)\n\t\t{\n\t\t\tif (i->second == trackIndex)\n\t\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\tLibrary::NewTrackInfo Library::CreateTrack(const ArtistPtr & artist,\n\t\tconst AlbumPtr & album,\n\t\tObjectFormat type,\n\t\tstd::string name, const std::string & genre, int trackIndex,\n\t\tconst std::string &filename, size_t size)\n\t{\n\t\tByteArray propList;\n\t\tOutputStream os(propList);\n\n\t\tos.Write32(3 + (!genre.empty()? 1: 0) + (trackIndex? 1: 0)); \/\/number of props\n\n\t\tif (_artistSupported)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::ArtistId));\n\t\t\tos.Write16(static_cast(DataTypeCode::Uint32));\n\t\t\tos.Write32(artist->Id.Id);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Artist));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(artist->Name);\n\t\t}\n\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::Name));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(name);\n\n\t\tif (trackIndex)\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Track));\n\t\t\tos.Write16(static_cast(DataTypeCode::Uint16));\n\t\t\tos.Write16(trackIndex);\n\t\t}\n\n\t\tif (!genre.empty())\n\t\t{\n\t\t\tos.Write32(0); \/\/object handle\n\t\t\tos.Write16(static_cast(ObjectProperty::Genre));\n\t\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\t\tos.WriteString(genre);\n\t\t}\n\n\t\tos.Write32(0); \/\/object handle\n\t\tos.Write16(static_cast(ObjectProperty::ObjectFilename));\n\t\tos.Write16(static_cast(DataTypeCode::String));\n\t\tos.WriteString(filename);\n\n\t\tauto response = _session->SendObjectPropList(_storage, album->MusicFolderId, type, size, propList);\n\t\tNewTrackInfo ti;\n\t\tti.Id = response.ObjectId;\n\t\tti.Name = name;\n\t\tti.Index = trackIndex;\n\t\treturn ti;\n\t}\n\n\tvoid Library::AddTrack(AlbumPtr album, const NewTrackInfo & ti)\n\t{\n\t\tif (!album)\n\t\t\treturn;\n\n\t\tauto & refs = album->Refs;\n\t\tauto & tracks = album->Tracks;\n\n\t\tmsg::ObjectHandles handles;\n\t\tstd::copy(refs.begin(), refs.end(), std::back_inserter(handles.ObjectHandles));\n\t\thandles.ObjectHandles.push_back(ti.Id);\n\t\t_session->SetObjectReferences(album->Id, handles);\n\t\trefs.insert(ti.Id);\n\t\ttracks.insert(std::make_pair(ti.Name, ti.Index));\n\t}\n\n\n\tbool Library::Supported(const mtp::SessionPtr & session)\n\t{\n\t\tauto & gdi = session->GetDeviceInfo();\n\t\treturn\n\t\t\tgdi.Supports(OperationCode::SendObjectPropList) &&\n\t\t\tgdi.Supports(OperationCode::SetObjectReferences) &&\n\t\t\tgdi.Supports(ObjectFormat::AbstractAudioAlbum);\n\t\t;\n\t}\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: OOXMLStreamImpl.hxx,v $\n *\n * $Revision: 1.6 $\n *\n * last change: $Author: kz $ $Date: 2008-03-05 17:06:57 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n#ifndef INCLUDED_OOXML_STREAM_IMPL_HXX\n#define INCLUDED_OOXML_STREAM_IMPL_HXX\n\n#ifndef INCLUDED_OOXML_DOCUMENT_HXX\n#include \n#endif\n\n#ifndef _COMPHELPER_STORAGEHELPER_HXX\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_EMBED_XRELATIONSHIPACCESS_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_IO_XSTREAM_HPP_\n#include \n#endif\n\nnamespace writerfilter {\nnamespace ooxml\n{\n\nusing namespace com::sun::star;\n\nclass OOXMLStreamImpl : public OOXMLStream\n{\n void init();\n\n uno::Reference mxContext;\n uno::Reference mxStorage;\n uno::Reference mxInputStream;\n uno::Reference mxRelationshipAccess;\n uno::Reference mxDocumentStream;\n uno::Reference mxFastParser;\n uno::Reference mxFastTokenHandler;\n\n StreamType_t mnStreamType;\n\n rtl::OUString msId;\n rtl::OUString msPath;\n\n bool getTarget(uno::Reference\n xRelationshipAccess,\n StreamType_t nStreamType,\n const ::rtl::OUString & rId,\n ::rtl::OUString & rDocumentTarget);\npublic:\n typedef boost::shared_ptr Pointer_t;\n\n OOXMLStreamImpl\n (OOXMLStreamImpl & rStream, StreamType_t nType);\n OOXMLStreamImpl\n (uno::Reference xContext,\n uno::Reference xStorage,\n StreamType_t nType);\n OOXMLStreamImpl(OOXMLStreamImpl & rStream, const rtl::OUString & rId);\n OOXMLStreamImpl\n (uno::Reference xContext,\n uno::Reference xStorage,\n const rtl::OUString & rId);\n\n virtual ~OOXMLStreamImpl();\n\n virtual uno::Reference getParser();\n virtual uno::Reference getFastParser();\n virtual uno::Reference getDocumentStream();\n virtual uno::Reference getInputStream();\n virtual uno::Reference getContext();\n ::rtl::OUString getTargetForId(const ::rtl::OUString & rId);\n virtual uno::Reference\n getFastTokenHandler(uno::Reference rContext);\n\n void setInputStream(uno::Reference rxInputStream);\n};\n}}\n#endif \/\/ INCLUDED_OOXML_STREAM_IMPL_HXX\nINTEGRATION: CWS changefileheader (1.6.4); FILE MERGED 2008\/04\/01 16:06:46 thb 1.6.4.3: #i85898# Stripping all external header guards 2008\/04\/01 13:02:32 thb 1.6.4.2: #i85898# Stripping all external header guards 2008\/03\/28 15:53:03 rt 1.6.4.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: OOXMLStreamImpl.hxx,v $\n * $Revision: 1.7 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n#ifndef INCLUDED_OOXML_STREAM_IMPL_HXX\n#define INCLUDED_OOXML_STREAM_IMPL_HXX\n\n#include \n#include \n#include \n#include \n\nnamespace writerfilter {\nnamespace ooxml\n{\n\nusing namespace com::sun::star;\n\nclass OOXMLStreamImpl : public OOXMLStream\n{\n void init();\n\n uno::Reference mxContext;\n uno::Reference mxStorage;\n uno::Reference mxInputStream;\n uno::Reference mxRelationshipAccess;\n uno::Reference mxDocumentStream;\n uno::Reference mxFastParser;\n uno::Reference mxFastTokenHandler;\n\n StreamType_t mnStreamType;\n\n rtl::OUString msId;\n rtl::OUString msPath;\n\n bool getTarget(uno::Reference\n xRelationshipAccess,\n StreamType_t nStreamType,\n const ::rtl::OUString & rId,\n ::rtl::OUString & rDocumentTarget);\npublic:\n typedef boost::shared_ptr Pointer_t;\n\n OOXMLStreamImpl\n (OOXMLStreamImpl & rStream, StreamType_t nType);\n OOXMLStreamImpl\n (uno::Reference xContext,\n uno::Reference xStorage,\n StreamType_t nType);\n OOXMLStreamImpl(OOXMLStreamImpl & rStream, const rtl::OUString & rId);\n OOXMLStreamImpl\n (uno::Reference xContext,\n uno::Reference xStorage,\n const rtl::OUString & rId);\n\n virtual ~OOXMLStreamImpl();\n\n virtual uno::Reference getParser();\n virtual uno::Reference getFastParser();\n virtual uno::Reference getDocumentStream();\n virtual uno::Reference getInputStream();\n virtual uno::Reference getContext();\n ::rtl::OUString getTargetForId(const ::rtl::OUString & rId);\n virtual uno::Reference\n getFastTokenHandler(uno::Reference rContext);\n\n void setInputStream(uno::Reference rxInputStream);\n};\n}}\n#endif \/\/ INCLUDED_OOXML_STREAM_IMPL_HXX\n<|endoftext|>"} {"text":"Create 1542 - Reading Books.cpp<|endoftext|>"} {"text":"\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"history_sql.h\"\n\n\nnamespace history {\n\nconst float HistoryDatabase::kLatestSchema = 1.0;\nconst float HistoryDatabase::kLatestSupportedSchema = 1.0;\nconst unsigned HistoryDatabase::kLatestSchemaRevision = 1;\n\nconst std::string HistoryDatabase::kFqrnKey = \"fqrn\";\n\n\n\/**\n * This method creates a new database file and initializes the database schema.\n *\/\nbool HistoryDatabase::CreateEmptyDatabase() {\n assert (read_write());\n return sqlite::Sql(sqlite_db(),\n \"CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, \"\n \" timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, \"\n \" CONSTRAINT pk_tags PRIMARY KEY (name))\").Execute();\n}\n\n\nbool HistoryDatabase::InsertInitialValues(const std::string &repository_name) {\n assert (read_write());\n return this->SetProperty(kFqrnKey, repository_name);\n}\n\n\nbool HistoryDatabase::CheckSchemaCompatibility() {\n return ! ((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) ||\n (schema_version() > kLatestSchema + kSchemaEpsilon));\n}\n\n\nbool HistoryDatabase::LiveSchemaUpgradeIfNecessary() {\n assert (read_write());\n\n if (schema_revision() == 0) {\n LogCvmfs(kLogHistory, kLogDebug, \"upgrading schema revision\");\n\n sqlite::Sql sql_upgrade(sqlite_db(), \"ALTER TABLE tags ADD size INTEGER;\");\n if (!sql_upgrade.Execute()) {\n LogCvmfs(kLogHistory, kLogDebug, \"failed to upgrade tags table\");\n return false;\n }\n\n set_schema_revision(1);\n if (! StoreSchemaRevision()) {\n LogCvmfs(kLogHistory, kLogDebug, \"failed tp upgrade schema revision\");\n return false;\n }\n }\n\n return true;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nconst std::string SqlRetrieveTag::tag_database_fields =\n \"name, hash, revision, timestamp, channel, description, size\";\n\nconst std::string& SqlRetrieveTag::GetDatabaseFields() const {\n return SqlRetrieveTag::tag_database_fields;\n}\n\nHistory::Tag SqlRetrieveTag::RetrieveTag() const {\n History::Tag result;\n result.name = RetrieveString(0);\n result.root_hash = shash::MkFromHexPtr(shash::HexPtr(RetrieveString(1)));\n result.revision = RetrieveInt64(2);\n result.timestamp = RetrieveInt64(3);\n result.channel = static_cast(RetrieveInt64(4));\n result.description = RetrieveString(5);\n result.size = RetrieveInt64(6);\n return result;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlInsertTag::SqlInsertTag(const HistoryDatabase *database) {\n const std::string stmt =\n \"INSERT INTO tags (\" + GetDatabaseFields() + \")\"\n \"VALUES (\" + GetDatabasePlaceholders() + \");\";\n Init(database->sqlite_db(), stmt);\n}\n\nconst std::string SqlInsertTag::tag_database_placeholders =\n \":name, :hash, :revision, :timestamp, :channel, :description, :size\";\n\nconst std::string& SqlInsertTag::GetDatabasePlaceholders() const {\n return SqlInsertTag::tag_database_placeholders;\n}\n\nbool SqlInsertTag::BindTag(const History::Tag &tag) {\n return (\n BindText (1, tag.name) &&\n BindTextTransient(2, tag.root_hash.ToString()) && \/\/ temporary from ToString\n BindInt64 (3, tag.revision) &&\n BindInt64 (4, tag.timestamp) &&\n BindInt64 (5, tag.channel) &&\n BindText (6, tag.description) &&\n BindInt64 (7, tag.size)\n );\n}\n\n\nSqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) {\n const std::string stmt = \"DELETE FROM tags WHERE name = :name;\";\n const bool success = Init(database->sqlite_db(), stmt);\n assert (success);\n}\n\nbool SqlRemoveTag::BindName(const std::string &name) {\n return BindText(1, name);\n}\n\n\nSqlFindTag::SqlFindTag(const HistoryDatabase *database) {\n const std::string stmt =\n \"SELECT \" + GetDatabaseFields() + \" FROM tags \"\n \"WHERE name = :name LIMIT 1;\";\n Init(database->sqlite_db(), stmt);\n}\n\nbool SqlFindTag::BindName(const std::string &name) {\n return BindText(1, name);\n}\n\n\nSqlCountTags::SqlCountTags(const HistoryDatabase *database) {\n Init(database->sqlite_db(), \"SELECT count(*) FROM tags;\");\n}\n\nint SqlCountTags::RetrieveCount() const {\n return RetrieveInt64(0);\n}\n\n\nSqlListTags::SqlListTags(const HistoryDatabase *database) {\n Init(database->sqlite_db(), \"SELECT \" + GetDatabaseFields() + \" FROM tags \"\n \"ORDER BY revision DESC;\");\n}\n\n\n\n\n\n\n\n\n\nbool SqlTag::BindTag(const History::Tag &tag) {\n return (\n BindText(1, tag.name) &&\n BindTextTransient(2, tag.root_hash.ToString()) && \/\/ temporary from ToString\n BindInt64(3, tag.revision) &&\n BindInt64(4, tag.timestamp) &&\n BindInt64(5, tag.channel) &&\n BindText(6, tag.description) &&\n BindInt64(7, tag.size)\n );\n}\n\n\nHistory::Tag SqlTag::RetrieveTag() {\n History::Tag result;\n result.name = std::string(reinterpret_cast(RetrieveText(0)));\n const std::string hash_str(reinterpret_cast(RetrieveText(1)));\n result.root_hash = shash::MkFromHexPtr(shash::HexPtr(hash_str));\n result.revision = RetrieveInt64(2);\n result.timestamp = RetrieveInt64(3);\n result.channel = static_cast(RetrieveInt64(4));\n result.description = std::string(reinterpret_cast(RetrieveText(5)));\n result.size = RetrieveInt64(6);\n return result;\n}\n\n\n\n\n\n\n\n\n}; \/* namespace history *\/\nassert success of `Sql::Init()`\/**\n * This file is part of the CernVM File System.\n *\/\n\n#include \"history_sql.h\"\n\n\nnamespace history {\n\nconst float HistoryDatabase::kLatestSchema = 1.0;\nconst float HistoryDatabase::kLatestSupportedSchema = 1.0;\nconst unsigned HistoryDatabase::kLatestSchemaRevision = 1;\n\nconst std::string HistoryDatabase::kFqrnKey = \"fqrn\";\n\n\n\/**\n * This method creates a new database file and initializes the database schema.\n *\/\nbool HistoryDatabase::CreateEmptyDatabase() {\n assert (read_write());\n return sqlite::Sql(sqlite_db(),\n \"CREATE TABLE tags (name TEXT, hash TEXT, revision INTEGER, \"\n \" timestamp INTEGER, channel INTEGER, description TEXT, size INTEGER, \"\n \" CONSTRAINT pk_tags PRIMARY KEY (name))\").Execute();\n}\n\n\nbool HistoryDatabase::InsertInitialValues(const std::string &repository_name) {\n assert (read_write());\n return this->SetProperty(kFqrnKey, repository_name);\n}\n\n\nbool HistoryDatabase::CheckSchemaCompatibility() {\n return ! ((schema_version() < kLatestSupportedSchema - kSchemaEpsilon) ||\n (schema_version() > kLatestSchema + kSchemaEpsilon));\n}\n\n\nbool HistoryDatabase::LiveSchemaUpgradeIfNecessary() {\n assert (read_write());\n\n if (schema_revision() == 0) {\n LogCvmfs(kLogHistory, kLogDebug, \"upgrading schema revision\");\n\n sqlite::Sql sql_upgrade(sqlite_db(), \"ALTER TABLE tags ADD size INTEGER;\");\n if (!sql_upgrade.Execute()) {\n LogCvmfs(kLogHistory, kLogDebug, \"failed to upgrade tags table\");\n return false;\n }\n\n set_schema_revision(1);\n if (! StoreSchemaRevision()) {\n LogCvmfs(kLogHistory, kLogDebug, \"failed tp upgrade schema revision\");\n return false;\n }\n }\n\n return true;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nconst std::string SqlRetrieveTag::tag_database_fields =\n \"name, hash, revision, timestamp, channel, description, size\";\n\nconst std::string& SqlRetrieveTag::GetDatabaseFields() const {\n return SqlRetrieveTag::tag_database_fields;\n}\n\nHistory::Tag SqlRetrieveTag::RetrieveTag() const {\n History::Tag result;\n result.name = RetrieveString(0);\n result.root_hash = shash::MkFromHexPtr(shash::HexPtr(RetrieveString(1)));\n result.revision = RetrieveInt64(2);\n result.timestamp = RetrieveInt64(3);\n result.channel = static_cast(RetrieveInt64(4));\n result.description = RetrieveString(5);\n result.size = RetrieveInt64(6);\n return result;\n}\n\n\n\/\/------------------------------------------------------------------------------\n\n\nSqlInsertTag::SqlInsertTag(const HistoryDatabase *database) {\n const std::string stmt =\n \"INSERT INTO tags (\" + GetDatabaseFields() + \")\"\n \"VALUES (\" + GetDatabasePlaceholders() + \");\";\n const bool success = Init(database->sqlite_db(), stmt);\n assert (success);\n}\n\nconst std::string SqlInsertTag::tag_database_placeholders =\n \":name, :hash, :revision, :timestamp, :channel, :description, :size\";\n\nconst std::string& SqlInsertTag::GetDatabasePlaceholders() const {\n return SqlInsertTag::tag_database_placeholders;\n}\n\nbool SqlInsertTag::BindTag(const History::Tag &tag) {\n return (\n BindText (1, tag.name) &&\n BindTextTransient(2, tag.root_hash.ToString()) && \/\/ temporary from ToString\n BindInt64 (3, tag.revision) &&\n BindInt64 (4, tag.timestamp) &&\n BindInt64 (5, tag.channel) &&\n BindText (6, tag.description) &&\n BindInt64 (7, tag.size)\n );\n}\n\n\nSqlRemoveTag::SqlRemoveTag(const HistoryDatabase *database) {\n const std::string stmt = \"DELETE FROM tags WHERE name = :name;\";\n const bool success = Init(database->sqlite_db(), stmt);\n assert (success);\n}\n\nbool SqlRemoveTag::BindName(const std::string &name) {\n return BindText(1, name);\n}\n\n\nSqlFindTag::SqlFindTag(const HistoryDatabase *database) {\n const std::string stmt =\n \"SELECT \" + GetDatabaseFields() + \" FROM tags \"\n \"WHERE name = :name LIMIT 1;\";\n const bool success = Init(database->sqlite_db(), stmt);\n assert (success);\n}\n\nbool SqlFindTag::BindName(const std::string &name) {\n return BindText(1, name);\n}\n\n\nSqlCountTags::SqlCountTags(const HistoryDatabase *database) {\n const bool success = Init(database->sqlite_db(),\n \"SELECT count(*) FROM tags;\");\n assert (success);\n}\n\nint SqlCountTags::RetrieveCount() const {\n return RetrieveInt64(0);\n}\n\n\nSqlListTags::SqlListTags(const HistoryDatabase *database) {\n const bool success = Init(database->sqlite_db(),\n \"SELECT \" + GetDatabaseFields() + \" FROM tags \"\n \"ORDER BY revision DESC;\");\n assert (success);\n}\n\n\n\n\n\n\n\n\n\nbool SqlTag::BindTag(const History::Tag &tag) {\n return (\n BindText(1, tag.name) &&\n BindTextTransient(2, tag.root_hash.ToString()) && \/\/ temporary from ToString\n BindInt64(3, tag.revision) &&\n BindInt64(4, tag.timestamp) &&\n BindInt64(5, tag.channel) &&\n BindText(6, tag.description) &&\n BindInt64(7, tag.size)\n );\n}\n\n\nHistory::Tag SqlTag::RetrieveTag() {\n History::Tag result;\n result.name = std::string(reinterpret_cast(RetrieveText(0)));\n const std::string hash_str(reinterpret_cast(RetrieveText(1)));\n result.root_hash = shash::MkFromHexPtr(shash::HexPtr(hash_str));\n result.revision = RetrieveInt64(2);\n result.timestamp = RetrieveInt64(3);\n result.channel = static_cast(RetrieveInt64(4));\n result.description = std::string(reinterpret_cast(RetrieveText(5)));\n result.size = RetrieveInt64(6);\n return result;\n}\n\n\n\n\n\n\n\n\n}; \/* namespace history *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accessiblemenubasecomponent.hxx,v $\n *\n * $Revision: 1.3 $\n *\n * last change: $Author: vg $ $Date: 2008-01-28 14:13:14 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#ifndef ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX\n#define ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX\n\n#ifndef _COM_SUN_STAR_ACCESSIBILITY_XACCESSIBLE_HPP_\n#include \n#endif\n#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_\n#include \n#endif\n\n#ifndef _COM_SUN_STAR_AWT_POINT_HPP_\n#include \n#endif\n\n#ifndef COMPHELPER_ACCESSIBLE_COMPONENT_HELPER_HXX\n#include \n#endif\n#ifndef _CPPUHELPER_IMPLBASE2_HXX\n#include \n#endif\n\n#ifndef _LINK_HXX\n#include \n#endif\n\n#include \n\nclass Menu;\nclass VclSimpleEvent;\nclass VclMenuEvent;\nclass VCLExternalSolarLock;\n\nnamespace utl {\nclass AccessibleStateSetHelper;\n}\n\n\/\/ ----------------------------------------------------\n\/\/ class OAccessibleMenuBaseComponent\n\/\/ ----------------------------------------------------\n\ntypedef ::comphelper::OAccessibleExtendedComponentHelper AccessibleExtendedComponentHelper_BASE;\n\ntypedef ::cppu::ImplHelper2<\n ::com::sun::star::accessibility::XAccessible,\n ::com::sun::star::lang::XServiceInfo > OAccessibleMenuBaseComponent_BASE;\n\nclass OAccessibleMenuBaseComponent : public AccessibleExtendedComponentHelper_BASE,\n public OAccessibleMenuBaseComponent_BASE\n{\n friend class OAccessibleMenuItemComponent;\n friend class VCLXAccessibleMenuItem;\n friend class VCLXAccessibleMenu;\n\nprivate:\n VCLExternalSolarLock* m_pExternalLock;\n\nprotected:\n typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren;\n\n AccessibleChildren m_aAccessibleChildren;\n Menu* m_pMenu;\n\n sal_Bool m_bEnabled;\n sal_Bool m_bFocused;\n sal_Bool m_bVisible;\n sal_Bool m_bSelected;\n sal_Bool m_bChecked;\n\n Menu* GetMenu() { return m_pMenu; }\n\n virtual sal_Bool IsEnabled();\n virtual sal_Bool IsFocused();\n virtual sal_Bool IsVisible();\n virtual sal_Bool IsSelected();\n virtual sal_Bool IsChecked();\n\n void SetEnabled( sal_Bool bEnabled );\n void SetFocused( sal_Bool bFocused );\n void SetVisible( sal_Bool bVisible );\n void SetSelected( sal_Bool bSelected );\n void SetChecked( sal_Bool bChecked );\n\n void UpdateEnabled( sal_Int32 i, sal_Bool bEnabled );\n void UpdateFocused( sal_Int32 i, sal_Bool bFocused );\n void UpdateVisible();\n void UpdateSelected( sal_Int32 i, sal_Bool bSelected );\n void UpdateChecked( sal_Int32 i, sal_Bool bChecked );\n void UpdateAccessibleName( sal_Int32 i );\n void UpdateItemText( sal_Int32 i );\n\n sal_Int32 GetChildCount();\n\n ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChild( sal_Int32 i );\n ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAt( const ::com::sun::star::awt::Point& rPoint );\n\n void InsertChild( sal_Int32 i );\n void RemoveChild( sal_Int32 i );\n\n virtual sal_Bool IsHighlighted();\n sal_Bool IsChildHighlighted();\n\n void SelectChild( sal_Int32 i );\n void DeSelectAll();\n sal_Bool IsChildSelected( sal_Int32 i );\n\n virtual void Select();\n virtual void DeSelect();\n virtual void Click();\n virtual sal_Bool IsPopupMenuOpen();\n\n DECL_LINK( MenuEventListener, VclSimpleEvent* );\n\n virtual void ProcessMenuEvent( const VclMenuEvent& rVclMenuEvent );\n\n virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ) = 0;\n\n \/\/ XComponent\n virtual void SAL_CALL disposing();\n\npublic:\n OAccessibleMenuBaseComponent( Menu* pMenu );\n virtual ~OAccessibleMenuBaseComponent();\n\n void SetStates();\n\n \/\/ XInterface\n DECLARE_XINTERFACE()\n\n \/\/ XTypeProvider\n DECLARE_XTYPEPROVIDER()\n\n \/\/ XServiceInfo\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XAccessible\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XAccessibleContext\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException);\n};\n\n#endif \/\/ ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX\n\nINTEGRATION: CWS changefileheader (1.3.10); FILE MERGED 2008\/04\/01 14:58:49 thb 1.3.10.3: #i85898# Stripping all external header guards 2008\/04\/01 10:45:13 thb 1.3.10.2: #i85898# Stripping all external header guards 2008\/03\/28 15:57:43 rt 1.3.10.1: #i87441# Change license header to LPGL v3.\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accessiblemenubasecomponent.hxx,v $\n * $Revision: 1.4 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n#ifndef ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX\n#define ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX\n\n#include \n#include \n#include \n#include \n#ifndef _CPPUHELPER_IMPLBASE2_HXX\n#include \n#endif\n#include \n\n#include \n\nclass Menu;\nclass VclSimpleEvent;\nclass VclMenuEvent;\nclass VCLExternalSolarLock;\n\nnamespace utl {\nclass AccessibleStateSetHelper;\n}\n\n\/\/ ----------------------------------------------------\n\/\/ class OAccessibleMenuBaseComponent\n\/\/ ----------------------------------------------------\n\ntypedef ::comphelper::OAccessibleExtendedComponentHelper AccessibleExtendedComponentHelper_BASE;\n\ntypedef ::cppu::ImplHelper2<\n ::com::sun::star::accessibility::XAccessible,\n ::com::sun::star::lang::XServiceInfo > OAccessibleMenuBaseComponent_BASE;\n\nclass OAccessibleMenuBaseComponent : public AccessibleExtendedComponentHelper_BASE,\n public OAccessibleMenuBaseComponent_BASE\n{\n friend class OAccessibleMenuItemComponent;\n friend class VCLXAccessibleMenuItem;\n friend class VCLXAccessibleMenu;\n\nprivate:\n VCLExternalSolarLock* m_pExternalLock;\n\nprotected:\n typedef ::std::vector< ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > > AccessibleChildren;\n\n AccessibleChildren m_aAccessibleChildren;\n Menu* m_pMenu;\n\n sal_Bool m_bEnabled;\n sal_Bool m_bFocused;\n sal_Bool m_bVisible;\n sal_Bool m_bSelected;\n sal_Bool m_bChecked;\n\n Menu* GetMenu() { return m_pMenu; }\n\n virtual sal_Bool IsEnabled();\n virtual sal_Bool IsFocused();\n virtual sal_Bool IsVisible();\n virtual sal_Bool IsSelected();\n virtual sal_Bool IsChecked();\n\n void SetEnabled( sal_Bool bEnabled );\n void SetFocused( sal_Bool bFocused );\n void SetVisible( sal_Bool bVisible );\n void SetSelected( sal_Bool bSelected );\n void SetChecked( sal_Bool bChecked );\n\n void UpdateEnabled( sal_Int32 i, sal_Bool bEnabled );\n void UpdateFocused( sal_Int32 i, sal_Bool bFocused );\n void UpdateVisible();\n void UpdateSelected( sal_Int32 i, sal_Bool bSelected );\n void UpdateChecked( sal_Int32 i, sal_Bool bChecked );\n void UpdateAccessibleName( sal_Int32 i );\n void UpdateItemText( sal_Int32 i );\n\n sal_Int32 GetChildCount();\n\n ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChild( sal_Int32 i );\n ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessible > GetChildAt( const ::com::sun::star::awt::Point& rPoint );\n\n void InsertChild( sal_Int32 i );\n void RemoveChild( sal_Int32 i );\n\n virtual sal_Bool IsHighlighted();\n sal_Bool IsChildHighlighted();\n\n void SelectChild( sal_Int32 i );\n void DeSelectAll();\n sal_Bool IsChildSelected( sal_Int32 i );\n\n virtual void Select();\n virtual void DeSelect();\n virtual void Click();\n virtual sal_Bool IsPopupMenuOpen();\n\n DECL_LINK( MenuEventListener, VclSimpleEvent* );\n\n virtual void ProcessMenuEvent( const VclMenuEvent& rVclMenuEvent );\n\n virtual void FillAccessibleStateSet( utl::AccessibleStateSetHelper& rStateSet ) = 0;\n\n \/\/ XComponent\n virtual void SAL_CALL disposing();\n\npublic:\n OAccessibleMenuBaseComponent( Menu* pMenu );\n virtual ~OAccessibleMenuBaseComponent();\n\n void SetStates();\n\n \/\/ XInterface\n DECLARE_XINTERFACE()\n\n \/\/ XTypeProvider\n DECLARE_XTYPEPROVIDER()\n\n \/\/ XServiceInfo\n virtual sal_Bool SAL_CALL supportsService( const ::rtl::OUString& rServiceName ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XAccessible\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleContext > SAL_CALL getAccessibleContext( ) throw (::com::sun::star::uno::RuntimeException);\n\n \/\/ XAccessibleContext\n virtual ::com::sun::star::uno::Reference< ::com::sun::star::accessibility::XAccessibleStateSet > SAL_CALL getAccessibleStateSet( ) throw (::com::sun::star::uno::RuntimeException);\n};\n\n#endif \/\/ ACCESSIBILITY_STANDARD_ACCESSIBLEMENUBASECOMPONENT_HXX\n\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tdoc_services.cxx,v $\n *\n * $Revision: 1.4 $\n *\n * last change: $Author: hr $ $Date: 2006-06-20 05:32:19 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n#include \"com\/sun\/star\/lang\/XMultiServiceFactory.hpp\"\n#include \"com\/sun\/star\/lang\/XSingleServiceFactory.hpp\"\n#include \"com\/sun\/star\/registry\/XRegistryKey.hpp\"\n\n#include \"tdoc_provider.hxx\"\n#include \"tdoc_documentcontentfactory.hxx\"\n\nusing namespace com::sun::star;\nusing namespace tdoc_ucp;\n\n\/\/=========================================================================\nstatic sal_Bool writeInfo( void * pRegistryKey,\n const rtl::OUString & rImplementationName,\n uno::Sequence< rtl::OUString > const & rServiceNames )\n{\n rtl::OUString aKeyName( rtl::OUString::createFromAscii( \"\/\" ) );\n aKeyName += rImplementationName;\n aKeyName += rtl::OUString::createFromAscii( \"\/UNO\/SERVICES\" );\n\n uno::Reference< registry::XRegistryKey > xKey;\n try\n {\n xKey = static_cast< registry::XRegistryKey * >(\n pRegistryKey )->createKey( aKeyName );\n }\n catch ( registry::InvalidRegistryException const & )\n {\n }\n\n if ( !xKey.is() )\n return sal_False;\n\n sal_Bool bSuccess = sal_True;\n\n for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )\n {\n try\n {\n xKey->createKey( rServiceNames[ n ] );\n }\n catch ( registry::InvalidRegistryException const & )\n {\n bSuccess = sal_False;\n break;\n }\n }\n return bSuccess;\n}\n\n\/\/=========================================================================\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** \/*ppEnv*\/ )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/=========================================================================\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void * \/*pServiceManager*\/, void * pRegistryKey )\n{\n return pRegistryKey &&\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Content Provider.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n writeInfo( pRegistryKey,\n ContentProvider::getImplementationName_Static(),\n ContentProvider::getSupportedServiceNames_Static() ) &&\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Document Content Factory.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n writeInfo( pRegistryKey,\n DocumentContentFactory::getImplementationName_Static(),\n DocumentContentFactory::getSupportedServiceNames_Static() );\n}\n\n\/\/=========================================================================\nextern \"C\" void * SAL_CALL component_getFactory(\n const sal_Char * pImplName, void * pServiceManager, void * \/*pRegistryKey*\/ )\n{\n void * pRet = 0;\n\n uno::Reference< lang::XMultiServiceFactory > xSMgr(\n reinterpret_cast< lang::XMultiServiceFactory * >(\n pServiceManager ) );\n uno::Reference< lang::XSingleServiceFactory > xFactory;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Content Provider.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n if ( ContentProvider::getImplementationName_Static().\n compareToAscii( pImplName ) == 0 )\n {\n xFactory = ContentProvider::createServiceFactory( xSMgr );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Document Content Factory.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n else if ( DocumentContentFactory::getImplementationName_Static().\n compareToAscii( pImplName ) == 0 )\n {\n xFactory = DocumentContentFactory::createServiceFactory( xSMgr );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n if ( xFactory.is() )\n {\n xFactory->acquire();\n pRet = xFactory.get();\n }\n\n return pRet;\n}\n\nINTEGRATION: CWS pchfix02 (1.4.20); FILE MERGED 2006\/09\/01 17:55:52 kaib 1.4.20.1: #i68856# Added header markers and pch files\/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: tdoc_services.cxx,v $\n *\n * $Revision: 1.5 $\n *\n * last change: $Author: obo $ $Date: 2006-09-17 14:03:00 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_ucb.hxx\"\n\n#include \"com\/sun\/star\/lang\/XMultiServiceFactory.hpp\"\n#include \"com\/sun\/star\/lang\/XSingleServiceFactory.hpp\"\n#include \"com\/sun\/star\/registry\/XRegistryKey.hpp\"\n\n#include \"tdoc_provider.hxx\"\n#include \"tdoc_documentcontentfactory.hxx\"\n\nusing namespace com::sun::star;\nusing namespace tdoc_ucp;\n\n\/\/=========================================================================\nstatic sal_Bool writeInfo( void * pRegistryKey,\n const rtl::OUString & rImplementationName,\n uno::Sequence< rtl::OUString > const & rServiceNames )\n{\n rtl::OUString aKeyName( rtl::OUString::createFromAscii( \"\/\" ) );\n aKeyName += rImplementationName;\n aKeyName += rtl::OUString::createFromAscii( \"\/UNO\/SERVICES\" );\n\n uno::Reference< registry::XRegistryKey > xKey;\n try\n {\n xKey = static_cast< registry::XRegistryKey * >(\n pRegistryKey )->createKey( aKeyName );\n }\n catch ( registry::InvalidRegistryException const & )\n {\n }\n\n if ( !xKey.is() )\n return sal_False;\n\n sal_Bool bSuccess = sal_True;\n\n for ( sal_Int32 n = 0; n < rServiceNames.getLength(); ++n )\n {\n try\n {\n xKey->createKey( rServiceNames[ n ] );\n }\n catch ( registry::InvalidRegistryException const & )\n {\n bSuccess = sal_False;\n break;\n }\n }\n return bSuccess;\n}\n\n\/\/=========================================================================\nextern \"C\" void SAL_CALL component_getImplementationEnvironment(\n const sal_Char ** ppEnvTypeName, uno_Environment ** \/*ppEnv*\/ )\n{\n *ppEnvTypeName = CPPU_CURRENT_LANGUAGE_BINDING_NAME;\n}\n\n\/\/=========================================================================\nextern \"C\" sal_Bool SAL_CALL component_writeInfo(\n void * \/*pServiceManager*\/, void * pRegistryKey )\n{\n return pRegistryKey &&\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Content Provider.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n writeInfo( pRegistryKey,\n ContentProvider::getImplementationName_Static(),\n ContentProvider::getSupportedServiceNames_Static() ) &&\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Document Content Factory.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n writeInfo( pRegistryKey,\n DocumentContentFactory::getImplementationName_Static(),\n DocumentContentFactory::getSupportedServiceNames_Static() );\n}\n\n\/\/=========================================================================\nextern \"C\" void * SAL_CALL component_getFactory(\n const sal_Char * pImplName, void * pServiceManager, void * \/*pRegistryKey*\/ )\n{\n void * pRet = 0;\n\n uno::Reference< lang::XMultiServiceFactory > xSMgr(\n reinterpret_cast< lang::XMultiServiceFactory * >(\n pServiceManager ) );\n uno::Reference< lang::XSingleServiceFactory > xFactory;\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Content Provider.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n if ( ContentProvider::getImplementationName_Static().\n compareToAscii( pImplName ) == 0 )\n {\n xFactory = ContentProvider::createServiceFactory( xSMgr );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n \/\/ Transient Documents Document Content Factory.\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n else if ( DocumentContentFactory::getImplementationName_Static().\n compareToAscii( pImplName ) == 0 )\n {\n xFactory = DocumentContentFactory::createServiceFactory( xSMgr );\n }\n\n \/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n if ( xFactory.is() )\n {\n xFactory->acquire();\n pRet = xFactory.get();\n }\n\n return pRet;\n}\n\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \n#include \n\n#include \n\nusing namespace ackward::logging;\n\nBOOST_AUTO_TEST_SUITE( logging )\nBOOST_AUTO_TEST_SUITE( logRecord )\n\nBOOST_AUTO_TEST_CASE( constructor )\n{\n LogRecord(L\"foo\",\n DEBUG(),\n L\"\/some\/path\/name\",\n 101,\n L\"Message\",\n boost::python::tuple());\n\n LogRecord(L\"foo\",\n DEBUG(),\n L\"\/some\/path\/name\",\n 101,\n L\"Message\",\n boost::python::tuple(),\n boost::python::make_tuple(\n boost::python::object(),\n boost::python::object(),\n boost::python::object()));\n}\n\nBOOST_AUTO_TEST_CASE( getMessage )\n{\n LogRecord r(L\"foo\",\n DEBUG(),\n L\"\/some\/path\/name\",\n 101,\n L\"Message\",\n boost::python::tuple());\n BOOST_CHECK(r.getMessage() == L\"Message\");\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\ndisabled tests that don't work right now.#include \n\n#include \n\n#include \n#include \n\n#include \n\nusing namespace ackward::logging;\n\nnamespace\n{\n\nstruct Fixture\n{\n Fixture() :\n rec (L\"foo\",\n DEBUG(),\n L\"\/some\/path\/name\",\n 101,\n L\"Message\",\n boost::python::tuple())\n {}\n\n LogRecord rec;\n};\n\n}\n\nBOOST_AUTO_TEST_SUITE( logging )\nBOOST_FIXTURE_TEST_SUITE( logRecord, Fixture )\n\nBOOST_AUTO_TEST_CASE( constructor )\n{\n LogRecord(L\"foo\",\n DEBUG(),\n L\"\/some\/path\/name\",\n 101,\n L\"Message\",\n boost::python::tuple(),\n boost::python::make_tuple(\n boost::python::object(),\n boost::python::object(),\n boost::python::object()));\n}\n\nBOOST_AUTO_TEST_CASE( getMessage )\n{\n BOOST_CHECK(rec.getMessage() == L\"Message\");\n}\n\nBOOST_AUTO_TEST_CASE( args )\n{\n boost::python::tuple args = rec.args;\n}\n\n\/\/ BOOST_AUTO_TEST_CASE( asctime )\n\/\/ {\n\/\/ std::wstring at = rec.asctime;\n\/\/ }\n\nBOOST_AUTO_TEST_CASE( created )\n{\n float c = rec.created;\n}\n\n\/\/ BOOST_AUTO_TEST_CASE( exc_info )\n\/\/ {\n\/\/ boost::python::tuple ei = rec.exc_info;\n\/\/ }\n\nBOOST_AUTO_TEST_CASE( filename )\n{\n std::wstring fn = rec.filename;\n}\n\n\/\/ BOOST_AUTO_TEST_CASE( funcName )\n\/\/ {\n\/\/ std::wstring fn = rec.funcName;\n\/\/ }\n\nBOOST_AUTO_TEST_CASE( levelname )\n{\n std::wstring ln = rec.levelname;\n}\n\nBOOST_AUTO_TEST_CASE( levelno )\n{\n int ln = rec.levelno;\n}\n\nBOOST_AUTO_TEST_CASE( lineno )\n{\n int ln = rec.lineno;\n}\n\nBOOST_AUTO_TEST_CASE( module )\n{\n std::wstring m = rec.module;\n}\n\nBOOST_AUTO_TEST_CASE( msecs )\n{\n float ms = rec.msecs;\n}\n\n\/\/ BOOST_AUTO_TEST_CASE( message )\n\/\/ {\n\/\/ std::wstring m = rec.message;\n\/\/ }\n\nBOOST_AUTO_TEST_CASE( msg )\n{\n std::wstring m = rec.msg;\n}\n\nBOOST_AUTO_TEST_CASE( name )\n{\n std::wstring n = rec.name;\n}\n\nBOOST_AUTO_TEST_CASE( pathname )\n{\n std::wstring pn = rec.pathname;\n}\n\nBOOST_AUTO_TEST_CASE( process )\n{\n int p = rec.process;\n}\n\nBOOST_AUTO_TEST_CASE( processName )\n{\n std::wstring pn = rec.processName;\n}\n\nBOOST_AUTO_TEST_CASE( relateveCreated )\n{\n float rc = rec.relativeCreated;\n}\n\nBOOST_AUTO_TEST_CASE( stack_info )\n{\n boost::python::object si = rec.stack_info;\n}\n\nBOOST_AUTO_TEST_CASE( thread )\n{\n unsigned long t = rec.thread;\n}\n\nBOOST_AUTO_TEST_CASE( threadName )\n{\n std::wstring tn = rec.threadName;\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/\/ @(#)root\/meta:$Id: TGWin32InterpreterProxy.cxx 38517 2011-03-18 20:20:16Z pcanal $\n\/\/ Author: Valeriy Onuchin 15\/11\/2003\n\n\n\/*************************************************************************\n * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGWin32InterpreterProxy \/\/\n\/\/ \/\/\n\/\/ This class defines thread-safe interface to a command line \/\/\n\/\/ interpreter (CINT). \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"TGWin32ProxyDefs.h\"\n#include \"TGWin32InterpreterProxy.h\"\n#include \"TROOT.h\"\n#include \"TGWin32.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/______________________________________________________________________________\nTInterpreter *TGWin32InterpreterProxy::RealObject()\n{\n \/\/ returns TCint object\n\n return gROOT->GetInterpreter();\n}\n\nRETURN_PROXY_OBJECT(Interpreter)\nVOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1)\nRETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname)\nVOID_METHOD_ARG0(Interpreter,ClearFileBusy,1)\nVOID_METHOD_ARG0(Interpreter,ClearStack,1)\nVOID_METHOD_ARG0(Interpreter,EndOfLineAction,1)\nVOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1)\nRETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries)\nRETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options); \nRETURN_METHOD_ARG0(Interpreter,char*,GetPrompt)\nRETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs)\nRETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath)\nRETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system)\nRETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile)\nRETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap)\nRETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps)\nRETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps)\nRETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library)\nVOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1)\nRETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error)\nRETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error)\nVOID_METHOD_ARG0(Interpreter,PrintIntro,1)\ntypedef char* (*GetlineFunc_t)(const char* prompt);\ntypedef void (*HistaddFunc_t)(char* line);\nVOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\\\n\t\t HistaddFunc_t, histaddFunc, 1)\nVOID_METHOD_ARG0(Interpreter,Reset,1)\nVOID_METHOD_ARG0(Interpreter,ResetAll,1)\nVOID_METHOD_ARG0(Interpreter,ResetGlobals,1)\nVOID_METHOD_ARG1(Interpreter,ResetGlobalVar,void*,obj)\nVOID_METHOD_ARG0(Interpreter,RewindDictionary,1)\nRETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj)\nVOID_METHOD_ARG0(Interpreter,SaveContext,1)\nVOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1)\nVOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals)\nVOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions)\nVOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes)\nVOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload)\nRETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload)\nRETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m)\nVOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl)\nRETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params)\nRETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto)\nRETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params)\nRETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto)\nRETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s)\nRETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s)\nRETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full)\nVOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1)\nVOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1)\nVOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1)\nRETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error)\nRETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable)\nVOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1)\nRETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s)\n\/\/Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); }\nAdd missing parameter\/\/ @(#)root\/meta:$Id: TGWin32InterpreterProxy.cxx 38517 2011-03-18 20:20:16Z pcanal $\n\/\/ Author: Valeriy Onuchin 15\/11\/2003\n\n\n\/*************************************************************************\n * Copyright (C) 1995-2001, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGWin32InterpreterProxy \/\/\n\/\/ \/\/\n\/\/ This class defines thread-safe interface to a command line \/\/\n\/\/ interpreter (CINT). \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\n#include \"TGWin32ProxyDefs.h\"\n#include \"TGWin32InterpreterProxy.h\"\n#include \"TROOT.h\"\n#include \"TGWin32.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/______________________________________________________________________________\nTInterpreter *TGWin32InterpreterProxy::RealObject()\n{\n \/\/ returns TCint object\n\n return gROOT->GetInterpreter();\n}\n\nRETURN_PROXY_OBJECT(Interpreter)\nVOID_METHOD_ARG1(Interpreter,AddIncludePath,const char*,path,1)\nRETURN_METHOD_ARG1(Interpreter,Int_t,AutoLoad,const char *,classname)\nVOID_METHOD_ARG0(Interpreter,ClearFileBusy,1)\nVOID_METHOD_ARG0(Interpreter,ClearStack,1)\nVOID_METHOD_ARG0(Interpreter,EndOfLineAction,1)\nVOID_METHOD_ARG0(Interpreter,EnableAutoLoading,1)\nRETURN_METHOD_ARG0(Interpreter,Int_t,InitializeDictionaries)\nRETURN_METHOD_ARG3(Interpreter,Int_t,GenerateDictionary,const char*,classes,const char*,headers,const char*,options); \nRETURN_METHOD_ARG0(Interpreter,char*,GetPrompt)\nRETURN_METHOD_ARG0(Interpreter,const char*,GetSharedLibs)\nRETURN_METHOD_ARG0(Interpreter,const char*,GetIncludePath)\nRETURN_METHOD_ARG2(Interpreter,Int_t,Load,const char*,filenam,Bool_t,system)\nRETURN_METHOD_ARG1(Interpreter,Int_t,LoadLibraryMap,const char*,rootmapfile)\nRETURN_METHOD_ARG0(Interpreter,Int_t,RescanLibraryMap)\nRETURN_METHOD_ARG0(Interpreter,Int_t,ReloadAllSharedLibraryMaps)\nRETURN_METHOD_ARG0(Interpreter,Int_t,UnloadAllSharedLibraryMaps)\nRETURN_METHOD_ARG1(Interpreter,Int_t,UnloadLibraryMap,const char*,library)\nVOID_METHOD_ARG2(Interpreter,LoadMacro,const char*,filename,TInterpreter::EErrorCode*,error,1)\nRETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLine,const char*,line,TInterpreter::EErrorCode*,error)\nRETURN_METHOD_ARG2(Interpreter,Long_t,ProcessLineSynch,const char*,line,TInterpreter::EErrorCode*,error)\nVOID_METHOD_ARG0(Interpreter,PrintIntro,1)\ntypedef char* (*GetlineFunc_t)(const char* prompt);\ntypedef void (*HistaddFunc_t)(char* line);\nVOID_METHOD_ARG2(Interpreter,SetGetline,GetlineFunc_t, getlineFunc,\\\n\t\t HistaddFunc_t, histaddFunc, 1)\nVOID_METHOD_ARG0(Interpreter,Reset,1)\nVOID_METHOD_ARG0(Interpreter,ResetAll,1)\nVOID_METHOD_ARG0(Interpreter,ResetGlobals,1)\nVOID_METHOD_ARG1(Interpreter,ResetGlobalVar,void*,obj,1)\nVOID_METHOD_ARG0(Interpreter,RewindDictionary,1)\nRETURN_METHOD_ARG1(Interpreter,Int_t,DeleteGlobal,void*,obj)\nVOID_METHOD_ARG0(Interpreter,SaveContext,1)\nVOID_METHOD_ARG0(Interpreter,SaveGlobalsContext,1)\nVOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobals)\nVOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfGlobalFunctions)\nVOID_METHOD_ARG0_LOCK(Interpreter,UpdateListOfTypes)\nVOID_METHOD_ARG2_LOCK(Interpreter,SetClassInfo,TClass*,cl,Bool_t,reload)\nRETURN_METHOD_ARG2(Interpreter,Bool_t,CheckClassInfo,const char*,name,Bool_t,autoload)\nRETURN_METHOD_ARG2(Interpreter,Long_t,Calc,const char*,line,TInterpreter::EErrorCode*,error)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfBaseClasses,TClass*,cl)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfDataMembers,TClass*,cl)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethods,TClass*,cl)\nVOID_METHOD_ARG1_LOCK(Interpreter,CreateListOfMethodArgs,TFunction*,m)\nVOID_METHOD_ARG1_LOCK(Interpreter,UpdateListOfMethods,TClass*,cl)\nRETURN_METHOD_ARG3(Interpreter,TString,GetMangledName,TClass*,cl,const char*,method,const char*,params)\nRETURN_METHOD_ARG3(Interpreter,TString,GetMangledNameWithPrototype,TClass*,cl,const char*,method,const char*,proto)\nRETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethod,TClass*,cl,const char*,method,const char*,params)\nRETURN_METHOD_ARG3(Interpreter,void*,GetInterfaceMethodWithPrototype,TClass*,cl,const char*,method,const char*,proto)\nRETURN_METHOD_ARG1(Interpreter,const char*,GetClassSharedLibs,const char*,s)\nRETURN_METHOD_ARG1(Interpreter,const char*,GetSharedLibDeps,const char*,s)\nRETURN_METHOD_ARG2(Interpreter,const char*,GetInterpreterTypeName,const char*,s,Bool_t,full)\nVOID_METHOD_ARG3(Interpreter,Execute,const char*,function,const char*,params,int*,error,1)\nVOID_METHOD_ARG5(Interpreter,Execute,TObject*,obj,TClass*,cl,const char*,method,const char*,params,int*,error,1)\nVOID_METHOD_ARG5(Interpreter,Execute,TObject*,object,TClass*,cl,TMethod*,method,TObjArray*,params,int*,error,1)\nRETURN_METHOD_ARG2(Interpreter,Long_t,ExecuteMacro,const char*,filename,TInterpreter::EErrorCode*,error)\nRETURN_METHOD_ARG1(Interpreter,Bool_t,SetErrorMessages,Bool_t,enable)\nVOID_METHOD_ARG1(Interpreter,SetProcessLineLock,Bool_t,lock,1)\nRETURN_METHOD_ARG1(Interpreter,const char*,TypeName,const char*,s)\n\/\/Bool_t TGWin32InterpreterProxy::CheckClassInfo(const char* name) { return RealObject()->CheckClassInfo(name); }\n<|endoftext|>"} {"text":"\/*------------------------------------------------------------------------------\n\n Copyright (c) 2004 Media Development Loan Fund\n \n This file is part of the Campcaster project.\n http:\/\/campcaster.campware.org\/\n To report bugs, send an e-mail to bugs@campware.org\n \n Campcaster is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n Campcaster is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Campcaster; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \n \n Author : $Author$\n Version : $Revision$\n Location : $URL$\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#define DEBUG_PREFIX \"GstreamerPlayer\"\n#include \"LiveSupport\/Core\/Debug.h\"\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n\n#include \"GstreamerPlayer.h\"\n\n\nusing namespace boost::posix_time;\nusing namespace LiveSupport::Core;\nusing namespace LiveSupport::PlaylistExecutor;\n\n\/* =================================================== local data structures *\/\n\n\n\/* ================================================ local constants & macros *\/\n\n\/**\n * The name of the config element for this class\n *\/\nconst std::string GstreamerPlayer::configElementNameStr = \"gstreamerPlayer\";\n\n\/**\n * The name of the audio device attribute.\n *\/\nstatic const std::string audioDeviceName = \"audioDevice\";\n\n\n\/* =============================================== local function prototypes *\/\n\n\n\/* ============================================================= module code *\/\n\nstatic gboolean my_bus_callback (GstBus *bus, GstMessage *message, gpointer data)\n{\n\n GstreamerPlayer* const player = (GstreamerPlayer*) data;\n\n switch (GST_MESSAGE_TYPE (message)) {\n case GST_MESSAGE_EOS:\n if(player->playNextSmil()){\n break;\n }\n player->close();\n \/\/ Important: We *must* use an idle function call here, so that the signal handler returns\n \/\/ before fireOnStopEvent() is executed.\n g_idle_add(GstreamerPlayer::fireOnStopEvent, data);\n break;\n case GST_MESSAGE_ERROR:\n \/\/ We make sure that we don't send multiple error messages in a row to the GUI\n if (!player->m_errorWasRaised) {\n GError *gerror;\n gchar *debug;\n gst_message_parse_error (message, &gerror, &debug);\n player->m_errorMessage.reset(new const Glib::ustring(gerror->message));\n player->m_errorWasRaised = true;\n \n std::cerr << \"gstreamer error: \" << gerror->message << std::endl;\n g_error_free (gerror);\n g_free (debug);\n \/\/ Important: We *must* use an idle function call here, so that the signal handler returns \n \/\/ before fireOnStopEvent() is executed.\n g_idle_add(GstreamerPlayer::fireOnStopEvent, data);\n }\n break;\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Configure the Audio Player.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: configure(const xmlpp::Element & element)\n throw (std::invalid_argument,\n std::logic_error)\n{\n DEBUG_FUNC_INFO\n\n if (element.get_name() != configElementNameStr) {\n std::string eMsg = \"Bad configuration element \";\n eMsg += element.get_name();\n throw std::invalid_argument(eMsg);\n }\n\n const xmlpp::Attribute * attribute = 0;\n\n if ((attribute = element.get_attribute(audioDeviceName))) {\n m_audioDevice = attribute->get_value();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Initialize the Audio Player\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: initialize(void) throw (std::exception)\n{\n DEBUG_FUNC_INFO\n\n if (m_initialized) {\n return;\n }\n\n \/\/ initialize the gstreamer library\n if (!gst_init_check(0, 0, 0)) {\n throw std::runtime_error(\"couldn't initialize the gstreamer library\");\n }\n\n m_playContext = new GstreamerPlayContext();\n\n m_playContext->setParentData(this);\n\n \/\/ set up other variables\n m_initialized = true;\n}\n\n\n\/*------------------------------------------------------------------------------\n * De-initialize the Gstreamer Player\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: deInitialize(void) throw ()\n{\n DEBUG_FUNC_INFO\n\n if (m_initialized) {\n m_playContext->closeContext();\n delete m_playContext;\n m_playContext = NULL;\n m_initialized = false;\n }\n}\n\n\/*------------------------------------------------------------------------------\n * Attach an event listener.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener)\n throw ()\n{\n m_listeners.push_back(eventListener);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Detach an event listener.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener)\n throw (std::invalid_argument)\n{\n ListenerVector::iterator it = m_listeners.begin();\n ListenerVector::iterator end = m_listeners.end();\n\n while (it != end) {\n if (*it == eventListener) {\n m_listeners.erase(it);\n return;\n }\n ++it;\n }\n\n throw std::invalid_argument(\"supplied event listener not found\");\n}\n\n\n\/*------------------------------------------------------------------------------\n * Send the onStop event to all attached listeners.\n *----------------------------------------------------------------------------*\/\ngboolean\nGstreamerPlayer :: fireOnStopEvent(gpointer self) throw ()\n{\n DEBUG_BLOCK\n\n\n GstreamerPlayer* const player = (GstreamerPlayer*) self;\n\n ListenerVector::iterator it = player->m_listeners.begin();\n ListenerVector::iterator end = player->m_listeners.end();\n while (it != end) {\n (*it)->onStop(player->m_errorMessage);\n ++it;\n }\n\n player->m_errorMessage.reset();\n\n \/\/ false == Don't call this idle function again\n return false;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Preload a file, to speed up the subsequent open() call. \n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: preload(const std::string fileUrl)\n throw (std::invalid_argument,\n std::runtime_error)\n{\n DEBUG_BLOCK\n \/\/According to the Gstreamer documentation, stream buffering happens\n \/\/automatically when the pipeline is set to GST_STATE_PAUSED.\n \/\/As this state is now set automatically in the open function,\n \/\/we no longer have a need for preloading.\n}\n\n\n\/*------------------------------------------------------------------------------\n * Specify which file to play\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: open(const std::string fileUri)\n throw (std::invalid_argument,\n std::runtime_error)\n{\n DEBUG_BLOCK\n\n if (isOpen()) {\n close();\n }\n \n m_smilOffset = 0L;\n\n debug() << \"Opening URL: \" << fileUri << endl;\n debug() << \"Timestamp: \" << *TimeConversion::now() << endl;\n\n m_errorMessage.reset();\n m_errorWasRaised = false;\n\n m_playContext->setAudioDevice(m_audioDevice);\n if (fileUri.find(std::string(\".smil\")) != std::string::npos) {\n m_smilHandler = new SmilHandler();\n m_smilHandler->openSmilFile(fileUri.c_str());\n AudioDescription *audioDescription = m_smilHandler->getNext();\n m_open=m_playContext->openSource(audioDescription);\n }else{\n m_open=m_playContext->openSource(fileUri.c_str());\n }\n\n if(!m_open){\n m_errorMessage.reset(new const Glib::ustring(\"GstreamerPlayer :: open failed! Please consult console output for details.\"));\n m_errorWasRaised = true;\n fireOnStopEvent(this);\n }\n}\n\nbool \nGstreamerPlayer :: playNextSmil(void) throw ()\n{\n DEBUG_BLOCK\n m_currentPlayLength = m_playContext->getPosition();\/\/this gets the length of the stream that just completed\n m_playContext->closeContext();\n if(m_smilHandler == NULL){\n return false;\n }\n AudioDescription *audioDescription = m_smilHandler->getNext();\n if(audioDescription == NULL){\/\/no more audio entries to play\n delete m_smilHandler;\n m_smilHandler = NULL;\n return false;\n }\n if(!m_playContext->openSource(audioDescription)){\n return false;\n }\n m_smilOffset += m_currentPlayLength;\n m_playContext->playContext();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Tell if we've been opened.\n *----------------------------------------------------------------------------*\/\nbool\nGstreamerPlayer :: isOpen(void) throw ()\n{\n return m_open;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Get the length of the current audio clip.\n * Currently not used by the Studio, but may be used later on.\n *----------------------------------------------------------------------------*\/\nPtr::Ref\nGstreamerPlayer :: getPlaylength(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n \n if (!isOpen()) {\n throw std::logic_error(\"player not open\");\n }\n \n Ptr::Ref length;\n \n gint64 ns = m_playContext->getPlayLength();\n \n length.reset(new time_duration(microsec(ns \/ 1000LL)));\n\n debug() << length << endl;\n return length;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Get the current position of the current audio clip.\n *----------------------------------------------------------------------------*\/\nPtr::Ref\nGstreamerPlayer :: getPosition(void) throw (std::logic_error)\n{\n Ptr::Ref length;\n\n if (!isOpen()) {\n throw std::logic_error(\"player not open\");\n }\n\n gint64 ns = m_playContext->getPosition();\n\n length.reset(new time_duration(microseconds((m_smilOffset + ns) \/ 1000LL)));\n\n return length;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Start playing\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: start(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n if (!isOpen()) {\n throw std::logic_error(\"GstreamerPlayer not opened yet\");\n }\n\n if (!isPlaying()) {\n m_playContext->playContext();\n }else{\n error() << \"Already playing!\" << endl;\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Pause the player\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: pause(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n if (isPlaying()) {\n m_playContext->pauseContext();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Tell if we're playing\n *----------------------------------------------------------------------------*\/\nbool\nGstreamerPlayer :: isPlaying(void) throw ()\n{\n return m_playContext->isPlaying();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Stop playing\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: stop(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n if (!isOpen()) {\n throw std::logic_error(\"GstreamerPlayer not opened yet\");\n }\n\n if (isPlaying()) {\n m_playContext->stopContext();\n }\n}\n \n\n\/*------------------------------------------------------------------------------\n * Close the currently opened audio file.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: close(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n m_playContext->stopContext();\n m_playContext->closeContext();\n if(m_smilHandler != NULL){\n delete m_smilHandler;\n m_smilHandler = NULL;\n }\n\n m_open = false;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Get the volume of the player. *Unimplemented*: Feature is currently not used.\n *----------------------------------------------------------------------------*\/\nunsigned int\nGstreamerPlayer :: getVolume(void) throw ()\n{\n return 0;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Set the volume of the player. *Unimplemented*: Feature is currently not used.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: setVolume(unsigned int volume) throw ()\n{}\n\n\n\/*------------------------------------------------------------------------------\n * Set the audio device.\n *----------------------------------------------------------------------------*\/\nbool\nGstreamerPlayer :: setAudioDevice(const std::string &deviceName) \n throw ()\n{\n DEBUG_BLOCK\n\n debug() << \"Using device: \" << deviceName << endl;\n\n if (deviceName.size() == 0) {\n return false;\n }\n\n m_playContext->setAudioDevice(deviceName);\n\n return true;\n}\n\nFixing ticket #2292\/*------------------------------------------------------------------------------\n\n Copyright (c) 2004 Media Development Loan Fund\n \n This file is part of the Campcaster project.\n http:\/\/campcaster.campware.org\/\n To report bugs, send an e-mail to bugs@campware.org\n \n Campcaster is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n \n Campcaster is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n \n You should have received a copy of the GNU General Public License\n along with Campcaster; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n \n \n Author : $Author$\n Version : $Revision$\n Location : $URL$\n\n------------------------------------------------------------------------------*\/\n\n\/* ============================================================ include files *\/\n\n#ifdef HAVE_CONFIG_H\n#include \"configure.h\"\n#endif\n\n#define DEBUG_PREFIX \"GstreamerPlayer\"\n#include \"LiveSupport\/Core\/Debug.h\"\n\n#include \"LiveSupport\/Core\/TimeConversion.h\"\n\n#include \"GstreamerPlayer.h\"\n\n\nusing namespace boost::posix_time;\nusing namespace LiveSupport::Core;\nusing namespace LiveSupport::PlaylistExecutor;\n\n\/* =================================================== local data structures *\/\n\n\n\/* ================================================ local constants & macros *\/\n\n\/**\n * The name of the config element for this class\n *\/\nconst std::string GstreamerPlayer::configElementNameStr = \"gstreamerPlayer\";\n\n\/**\n * The name of the audio device attribute.\n *\/\nstatic const std::string audioDeviceName = \"audioDevice\";\n\n\n\/* =============================================== local function prototypes *\/\n\n\n\/* ============================================================= module code *\/\n\nstatic gboolean my_bus_callback (GstBus *bus, GstMessage *message, gpointer data)\n{\n\n GstreamerPlayer* const player = (GstreamerPlayer*) data;\n\n switch (GST_MESSAGE_TYPE (message)) {\n case GST_MESSAGE_EOS:\n if(player->playNextSmil()){\n break;\n }\n player->close();\n \/\/ Important: We *must* use an idle function call here, so that the signal handler returns\n \/\/ before fireOnStopEvent() is executed.\n g_idle_add(GstreamerPlayer::fireOnStopEvent, data);\n break;\n case GST_MESSAGE_ERROR:\n \/\/ We make sure that we don't send multiple error messages in a row to the GUI\n if (!player->m_errorWasRaised) {\n GError *gerror;\n gchar *debug;\n gst_message_parse_error (message, &gerror, &debug);\n player->m_errorMessage.reset(new const Glib::ustring(gerror->message));\n player->m_errorWasRaised = true;\n \n std::cerr << \"gstreamer error: \" << gerror->message << std::endl;\n g_error_free (gerror);\n g_free (debug);\n \/\/ Important: We *must* use an idle function call here, so that the signal handler returns \n \/\/ before fireOnStopEvent() is executed.\n g_idle_add(GstreamerPlayer::fireOnStopEvent, data);\n }\n break;\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Configure the Audio Player.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: configure(const xmlpp::Element & element)\n throw (std::invalid_argument,\n std::logic_error)\n{\n DEBUG_FUNC_INFO\n\n if (element.get_name() != configElementNameStr) {\n std::string eMsg = \"Bad configuration element \";\n eMsg += element.get_name();\n throw std::invalid_argument(eMsg);\n }\n\n const xmlpp::Attribute * attribute = 0;\n\n if ((attribute = element.get_attribute(audioDeviceName))) {\n m_audioDevice = attribute->get_value();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Initialize the Audio Player\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: initialize(void) throw (std::exception)\n{\n DEBUG_FUNC_INFO\n\n if (m_initialized) {\n return;\n }\n\n \/\/ initialize the gstreamer library\n if (!gst_init_check(0, 0, 0)) {\n throw std::runtime_error(\"couldn't initialize the gstreamer library\");\n }\n\n m_playContext = new GstreamerPlayContext();\n\n m_playContext->setParentData(this);\n\n \/\/ set up other variables\n m_initialized = true;\n}\n\n\n\/*------------------------------------------------------------------------------\n * De-initialize the Gstreamer Player\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: deInitialize(void) throw ()\n{\n DEBUG_FUNC_INFO\n\n if (m_initialized) {\n m_playContext->closeContext();\n delete m_playContext;\n m_playContext = NULL;\n m_initialized = false;\n }\n}\n\n\/*------------------------------------------------------------------------------\n * Attach an event listener.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: attachListener(AudioPlayerEventListener* eventListener)\n throw ()\n{\n m_listeners.push_back(eventListener);\n}\n\n\n\/*------------------------------------------------------------------------------\n * Detach an event listener.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: detachListener(AudioPlayerEventListener* eventListener)\n throw (std::invalid_argument)\n{\n ListenerVector::iterator it = m_listeners.begin();\n ListenerVector::iterator end = m_listeners.end();\n\n while (it != end) {\n if (*it == eventListener) {\n m_listeners.erase(it);\n return;\n }\n ++it;\n }\n\n throw std::invalid_argument(\"supplied event listener not found\");\n}\n\n\n\/*------------------------------------------------------------------------------\n * Send the onStop event to all attached listeners.\n *----------------------------------------------------------------------------*\/\ngboolean\nGstreamerPlayer :: fireOnStopEvent(gpointer self) throw ()\n{\n DEBUG_BLOCK\n\n\n GstreamerPlayer* const player = (GstreamerPlayer*) self;\n\n ListenerVector::iterator it = player->m_listeners.begin();\n ListenerVector::iterator end = player->m_listeners.end();\n while (it != end) {\n (*it)->onStop(player->m_errorMessage);\n ++it;\n }\n\n player->m_errorMessage.reset();\n\n \/\/ false == Don't call this idle function again\n return false;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Preload a file, to speed up the subsequent open() call. \n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: preload(const std::string fileUrl)\n throw (std::invalid_argument,\n std::runtime_error)\n{\n DEBUG_BLOCK\n \/\/According to the Gstreamer documentation, stream buffering happens\n \/\/automatically when the pipeline is set to GST_STATE_PAUSED.\n \/\/As this state is now set automatically in the open function,\n \/\/we no longer have a need for preloading.\n}\n\n\n\/*------------------------------------------------------------------------------\n * Specify which file to play\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: open(const std::string fileUri)\n throw (std::invalid_argument,\n std::runtime_error)\n{\n DEBUG_BLOCK\n\n if (isOpen()) {\n close();\n }\n \n m_smilOffset = 0L;\n\n debug() << \"Opening URL: \" << fileUri << endl;\n debug() << \"Timestamp: \" << *TimeConversion::now() << endl;\n\n m_errorMessage.reset();\n m_errorWasRaised = false;\n\n m_playContext->setAudioDevice(m_audioDevice);\n if (fileUri.find(std::string(\".smil\")) != std::string::npos) {\n m_smilHandler = new SmilHandler();\n m_smilHandler->openSmilFile(fileUri.c_str());\n AudioDescription *audioDescription = m_smilHandler->getNext();\n m_open=m_playContext->openSource(audioDescription);\n }else{\n m_open=m_playContext->openSource(fileUri.c_str());\n }\n\n if(!m_open){\n m_errorMessage.reset(new const Glib::ustring(\"GstreamerPlayer :: open failed! Please consult console output for details.\"));\n m_errorWasRaised = true;\n fireOnStopEvent(this);\n }\n}\n\nbool \nGstreamerPlayer :: playNextSmil(void) throw ()\n{\n DEBUG_BLOCK\n m_currentPlayLength = m_playContext->getPosition();\/\/this gets the length of the stream that just completed\n m_playContext->closeContext();\n if(m_smilHandler == NULL){\n return false;\n }\n AudioDescription *audioDescription = m_smilHandler->getNext();\n if(audioDescription == NULL){\/\/no more audio entries to play\n delete m_smilHandler;\n m_smilHandler = NULL;\n return false;\n }\n if(!m_playContext->openSource(audioDescription)){\n return false;\n }\n m_smilOffset += m_currentPlayLength;\n m_playContext->playContext();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Tell if we've been opened.\n *----------------------------------------------------------------------------*\/\nbool\nGstreamerPlayer :: isOpen(void) throw ()\n{\n return m_open;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Get the length of the current audio clip.\n * Currently not used by the Studio, but may be used later on.\n *----------------------------------------------------------------------------*\/\nPtr::Ref\nGstreamerPlayer :: getPlaylength(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n \n if (!isOpen()) {\n throw std::logic_error(\"player not open\");\n }\n \n Ptr::Ref length;\n \n gint64 ns = m_playContext->getPlayLength();\n \n length.reset(new time_duration(microsec(ns \/ 1000LL)));\n\n debug() << \"playlength is: \" << *length << endl; \n return length;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Get the current position of the current audio clip.\n *----------------------------------------------------------------------------*\/\nPtr::Ref\nGstreamerPlayer :: getPosition(void) throw (std::logic_error)\n{\n Ptr::Ref length;\n\n if (!isOpen()) {\n throw std::logic_error(\"player not open\");\n }\n\n gint64 ns = m_playContext->getPosition();\n\n length.reset(new time_duration(microseconds((m_smilOffset + ns) \/ 1000LL)));\n\n return length;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Start playing\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: start(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n if (!isOpen()) {\n throw std::logic_error(\"GstreamerPlayer not opened yet\");\n }\n\n if (!isPlaying()) {\n m_playContext->playContext();\n }else{\n error() << \"Already playing!\" << endl;\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Pause the player\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: pause(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n if (isPlaying()) {\n m_playContext->pauseContext();\n }\n}\n\n\n\/*------------------------------------------------------------------------------\n * Tell if we're playing\n *----------------------------------------------------------------------------*\/\nbool\nGstreamerPlayer :: isPlaying(void) throw ()\n{\n return m_playContext->isPlaying();\n}\n\n\n\/*------------------------------------------------------------------------------\n * Stop playing\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: stop(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n if (!isOpen()) {\n throw std::logic_error(\"GstreamerPlayer not opened yet\");\n }\n\n if (isPlaying()) {\n m_playContext->stopContext();\n }\n}\n \n\n\/*------------------------------------------------------------------------------\n * Close the currently opened audio file.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: close(void) throw (std::logic_error)\n{\n DEBUG_BLOCK\n\n m_playContext->stopContext();\n m_playContext->closeContext();\n if(m_smilHandler != NULL){\n delete m_smilHandler;\n m_smilHandler = NULL;\n }\n\n m_open = false;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Get the volume of the player. *Unimplemented*: Feature is currently not used.\n *----------------------------------------------------------------------------*\/\nunsigned int\nGstreamerPlayer :: getVolume(void) throw ()\n{\n return 0;\n}\n\n\n\/*------------------------------------------------------------------------------\n * Set the volume of the player. *Unimplemented*: Feature is currently not used.\n *----------------------------------------------------------------------------*\/\nvoid\nGstreamerPlayer :: setVolume(unsigned int volume) throw ()\n{}\n\n\n\/*------------------------------------------------------------------------------\n * Set the audio device.\n *----------------------------------------------------------------------------*\/\nbool\nGstreamerPlayer :: setAudioDevice(const std::string &deviceName) \n throw ()\n{\n DEBUG_BLOCK\n\n debug() << \"Using device: \" << deviceName << endl;\n\n if (deviceName.size() == 0) {\n return false;\n }\n\n m_playContext->setAudioDevice(deviceName);\n\n return true;\n}\n\n<|endoftext|>"} {"text":"\/\/ bslmt_semaphoreimpl_darwin.cpp -*-C++-*-\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ NOTICE\n\/\/\n\/\/ This component is not up to date with current BDE coding standards, and\n\/\/ should not be used as an example for new development.\n\/\/ ----------------------------------------------------------------------------\n\n#include \n\n#include \nBSLS_IDENT_RCSID(bslmt_semaphoreimpl_darwin_cpp,\"$Id$ $CSID$\")\n\n#ifdef BSLS_PLATFORM_OS_DARWIN\n\n#include \/\/ for testing only\n#include \/\/ for testing only\n#include \/\/ for testing only\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \/\/ 'snprintf'\n#include \n#include \n#include \/\/ needed before sys\/posix_sem.h to define\n \/\/ 'itimerval'\n#include \/\/ 'PSEMNAMLEN'\n\n#ifndef SEM_NAME_LEN\n#define SEM_NAME_LEN PSEMNAMLEN\n#endif\n\nnamespace BloombergLP {\n\n \/\/ ----------------------------------------------\n \/\/ class SemaphoreImpl\n \/\/ ----------------------------------------------\n\nconst char *\nbslmt::SemaphoreImpl::s_semaphorePrefix\n = \"bslmt_semaphore_\";\n\nnamespace {\n\nvoid\nmakeUniqueName(char *buffer, const char *prefix, bsls::Types::UintPtr suffix)\n \/\/ Create a sufficiently unique name for a semaphore object. Note that the\n \/\/ name of the semaphore shouldn't exceed SEM_NAME_LEN characters (31).\n{\n snprintf(buffer, SEM_NAME_LEN, \"%s%04x_%04x\",\n prefix,\n (getpid() & 0xffff),\n (suffix & 0xffff));\n}\n\n} \/\/ close unnamed namespace\n\n\/\/ CREATORS\nbslmt::SemaphoreImpl::SemaphoreImpl(\n int count)\n{\n char semaphoreName[SEM_NAME_LEN + 1];\n\n makeUniqueName(semaphoreName,\n s_semaphorePrefix,\n reinterpret_cast(this));\n\n do {\n \/\/ create a named semaphore with exclusive access\n d_sem_p = ::sem_open(semaphoreName,\n O_CREAT | O_EXCL,\n S_IRUSR | S_IWUSR,\n count);\n } while (d_sem_p == SEM_FAILED && (errno == EEXIST || errno == EINTR));\n\n BSLS_ASSERT(d_sem_p != SEM_FAILED);\n\n \/\/ At this point the current thread is the sole owner of the semaphore with\n \/\/ this name. No other thread can create a semaphore with the same name\n \/\/ until we disassociate the name from the semaphore handle. Note that\n \/\/ even though the name is unlinked from the semaphore, we still try to use\n \/\/ sufficiently unique names because if the process is killed before it\n \/\/ unlinks the name, no other process can create a semaphore with that\n \/\/ name.\n int result = ::sem_unlink(semaphoreName);\n\n (void) result;\n BSLS_ASSERT(result == 0);\n}\n\n\/\/ MANIPULATORS\nvoid bslmt::SemaphoreImpl::post(int number)\n{\n for (int i = 0; i < number; i++) {\n post();\n }\n}\n\nvoid\nbslmt::SemaphoreImpl::wait()\n{\n sem_t * sem_p = d_sem_p;\n int result = 0;\n\n do {\n result = ::sem_wait(sem_p);\n } while (result != 0 && errno == EINTR);\n\n BSLS_ASSERT(result == 0);\n}\n\n} \/\/ close enterprise namespace\n\n#endif \/\/ BSLS_PLATFORM_OS_DARWIN\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2015 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\nadd cast to suppress warning\/\/ bslmt_semaphoreimpl_darwin.cpp -*-C++-*-\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ NOTICE\n\/\/\n\/\/ This component is not up to date with current BDE coding standards, and\n\/\/ should not be used as an example for new development.\n\/\/ ----------------------------------------------------------------------------\n\n#include \n\n#include \nBSLS_IDENT_RCSID(bslmt_semaphoreimpl_darwin_cpp,\"$Id$ $CSID$\")\n\n#ifdef BSLS_PLATFORM_OS_DARWIN\n\n#include \/\/ for testing only\n#include \/\/ for testing only\n#include \/\/ for testing only\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \/\/ 'snprintf'\n#include \n#include \n#include \/\/ needed before sys\/posix_sem.h to define\n \/\/ 'itimerval'\n#include \/\/ 'PSEMNAMLEN'\n\n#ifndef SEM_NAME_LEN\n#define SEM_NAME_LEN PSEMNAMLEN\n#endif\n\nnamespace BloombergLP {\n\n \/\/ ----------------------------------------------\n \/\/ class SemaphoreImpl\n \/\/ ----------------------------------------------\n\nconst char *\nbslmt::SemaphoreImpl::s_semaphorePrefix\n = \"bslmt_semaphore_\";\n\nnamespace {\n\nvoid\nmakeUniqueName(char *buffer, const char *prefix, bsls::Types::UintPtr suffix)\n \/\/ Create a sufficiently unique name for a semaphore object. Note that the\n \/\/ name of the semaphore shouldn't exceed SEM_NAME_LEN characters (31).\n{\n snprintf(buffer, SEM_NAME_LEN, \"%s%04x_%04x\",\n prefix,\n (getpid() & 0xffff),\n static_cast(suffix & 0xffff));\n}\n\n} \/\/ close unnamed namespace\n\n\/\/ CREATORS\nbslmt::SemaphoreImpl::SemaphoreImpl(\n int count)\n{\n char semaphoreName[SEM_NAME_LEN + 1];\n\n makeUniqueName(semaphoreName,\n s_semaphorePrefix,\n reinterpret_cast(this));\n\n do {\n \/\/ create a named semaphore with exclusive access\n d_sem_p = ::sem_open(semaphoreName,\n O_CREAT | O_EXCL,\n S_IRUSR | S_IWUSR,\n count);\n } while (d_sem_p == SEM_FAILED && (errno == EEXIST || errno == EINTR));\n\n BSLS_ASSERT(d_sem_p != SEM_FAILED);\n\n \/\/ At this point the current thread is the sole owner of the semaphore with\n \/\/ this name. No other thread can create a semaphore with the same name\n \/\/ until we disassociate the name from the semaphore handle. Note that\n \/\/ even though the name is unlinked from the semaphore, we still try to use\n \/\/ sufficiently unique names because if the process is killed before it\n \/\/ unlinks the name, no other process can create a semaphore with that\n \/\/ name.\n int result = ::sem_unlink(semaphoreName);\n\n (void) result;\n BSLS_ASSERT(result == 0);\n}\n\n\/\/ MANIPULATORS\nvoid bslmt::SemaphoreImpl::post(int number)\n{\n for (int i = 0; i < number; i++) {\n post();\n }\n}\n\nvoid\nbslmt::SemaphoreImpl::wait()\n{\n sem_t * sem_p = d_sem_p;\n int result = 0;\n\n do {\n result = ::sem_wait(sem_p);\n } while (result != 0 && errno == EINTR);\n\n BSLS_ASSERT(result == 0);\n}\n\n} \/\/ close enterprise namespace\n\n#endif \/\/ BSLS_PLATFORM_OS_DARWIN\n\n\/\/ ----------------------------------------------------------------------------\n\/\/ Copyright 2015 Bloomberg Finance L.P.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/ ----------------------------- END-OF-FILE ----------------------------------\n<|endoftext|>"} {"text":"\/\/\/ This file contains the implementation of VNS\n#include \"header\/vns-priv.hpp\"\n\nusing namespace std;\n\nnamespace pcp {\n\tSolution bestSolution;\n\tSolution origSolution;\n\n\tbool checkValid(Solution* s);\n\n\t\/\/\/ Some constants\n\tconst int NUM_VNS = 1;\n\tconst int SHAKE_START = 1;\n\t\n\t\/\/\/ Implementation of VNS, see vns.hpp\n\tSolution vnsRun(Solution& best, Solution& orig, int unsuccessfulShake, int shakeStart, int shakeIncrement, int maxTime) {\n\n\t\t\/\/\/ Backup the starting solutions\n\t\tbestSolution = new Solution(best);\n\t\torigSolution = new Solution(orig);\n\t\t\n\t\tcout<<\"Best solution uses \"<name() <findLocalMin(best, orig);\n\t\t\t\tcout<<\"Valid solution: \"<<((checkValid(improved)) ? \"true\" : \"false\");\n\t\t\t\tcout<colorsUsed < toImprove->colorsUsed) {\n\t\t\t\t\tdelete toImprove;\n\t\t\t\t\ttoImprove = improved;\n\t\t\t\t\t\n\t\t\t\t\tcout<<\"Improvement found with \"<name()<colorsUsed < best.colorsUsed) {\n\t\t\t\tcout<<\"Improvement to global best solution found\"< unsuccessfulShake) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint shakeNeighbor = rand() % NUM_VNS;\n\n\t\t\tVNS_Unit *shaker = neighbors[shakeNeighbor];\n\t\t\ttoImprove = shaker->shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement));\n\n\t\t\t\/\/\/ No time left, abort main loop\n\t\t\tif (startTime + maxTime < time(NULL)) {\n\t\t\t\tcout<<\"Time's up\"< vIter;\n\tint parts[s->numParts];\n\ttypedef boost::graph_traits::adjacency_iterator AdjIter;\n\tVertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g);\n\tbool valid = true;\n\t\n\tfor (int i = 0; i < s->numParts; i++) {\n\t\tparts[i] = 0;\n\t}\n\t\n\tfor (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) {\n\t\tparts[vParts[*vIter.first]] = 1;\n\t\t\n\t\tpair aIter;\n\t\tfor (aIter = adjacent_vertices(*vIter.first, *s->g); \n\t\t\t aIter.first != aIter.second; aIter.first++) {\n\t\t\t\n\t\t\tif (s->partition[vParts[*aIter.first]] == \n\t\t\t\t s->partition[vParts[*vIter.first]]) {\n\t\t\t\t\n\t\t\t\tvalid = false;\n\t\t\t\tcerr<<\"Solution is invalid\"<partition[vParts[*vIter.first]];\n\t\t\t\tcerr<numParts; i++) {\n\t\tif (parts[i] == 0) {\n\t\t\tvalid = false;\n\t\t\tcerr<<\"Solution is invalid\"<Fixed intentation in vns-loop\/\/\/ This file contains the implementation of VNS\n#include \"header\/vns-priv.hpp\"\n\nusing namespace std;\n\nnamespace pcp {\n\tSolution bestSolution;\n\tSolution origSolution;\n\n\tbool checkValid(Solution* s);\n\n\t\/\/\/ Some constants\n\tconst int NUM_VNS = 1;\n\tconst int SHAKE_START = 1;\n\t\n\t\/\/\/ Implementation of VNS, see vns.hpp\n\tSolution vnsRun(Solution& best, Solution& orig, int unsuccessfulShake, int shakeStart, int shakeIncrement, int maxTime) {\n\n\t\t\/\/\/ Backup the starting solutions\n\t\tbestSolution = new Solution(best);\n\t\torigSolution = new Solution(orig);\n\t\t\n\t\tcout<<\"Best solution uses \"<name() <findLocalMin(best, orig);\n\t\t\t\tcout<<\"Valid solution: \"<<((checkValid(improved)) ? \"true\" : \"false\");\n\t\t\t\tcout<colorsUsed < toImprove->colorsUsed) {\n\t\t\t\t\tdelete toImprove;\n\t\t\t\t\ttoImprove = improved;\n\t\t\t\t\t\n\t\t\t\t\tcout<<\"Improvement found with \"<name()<colorsUsed < best.colorsUsed) {\n\t\t\t\tcout<<\"Improvement to global best solution found\"< unsuccessfulShake) {\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t}\n\t\t\t\n\t\t\tint shakeNeighbor = rand() % NUM_VNS;\n\n\t\t\tVNS_Unit *shaker = neighbors[shakeNeighbor];\n\t\t\ttoImprove = shaker->shuffleSolution(*toImprove, orig, (shakeSteps += shakeIncrement));\n\n\t\t\t\/\/\/ No time left, abort main loop\n\t\t\tif (startTime + maxTime < time(NULL)) {\n\t\t\t\tcout<<\"Time's up\"< vIter;\n\t\tint parts[s->numParts];\n\t\ttypedef boost::graph_traits::adjacency_iterator AdjIter;\n\t\tVertexPart_Map vParts = get(boost::vertex_index1_t(), *s->g);\n\t\tbool valid = true;\n\t\n\t\tfor (int i = 0; i < s->numParts; i++) {\n\t\t\tparts[i] = 0;\n\t\t}\n\t\n\t\tfor (vIter = vertices(*s->g); vIter.first != vIter.second; vIter.first++) {\n\t\t\tparts[vParts[*vIter.first]] = 1;\n\t\t\n\t\t\tpair aIter;\n\t\t\tfor (aIter = adjacent_vertices(*vIter.first, *s->g); \n\t\t\t\t aIter.first != aIter.second; aIter.first++) {\n\t\t\t\n\t\t\t\tif (s->partition[vParts[*aIter.first]] == \n\t\t\t\t\t s->partition[vParts[*vIter.first]]) {\n\t\t\t\t\n\t\t\t\t\tvalid = false;\n\t\t\t\t\tcerr<<\"Solution is invalid\"<partition[vParts[*vIter.first]];\n\t\t\t\t\tcerr<numParts; i++) {\n\t\t\tif (parts[i] == 0) {\n\t\t\t\tvalid = false;\n\t\t\t\tcerr<<\"Solution is invalid\"<"} {"text":"\/\/ Copyright (c) 2011 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/views\/controls\/menu\/menu_config.h\"\n\n#include \"build\/build_config.h\"\n\nnamespace views {\n\nstatic MenuConfig* config_instance = NULL;\n\nMenuConfig::MenuConfig()\n : text_color(SK_ColorBLACK),\n item_top_margin(3),\n item_bottom_margin(4),\n item_no_icon_top_margin(1),\n item_no_icon_bottom_margin(3),\n item_left_margin(4),\n label_to_arrow_padding(10),\n arrow_to_edge_padding(5),\n icon_to_label_padding(8),\n gutter_to_label(5),\n check_width(16),\n check_height(16),\n radio_width(16),\n radio_height(16),\n arrow_height(9),\n arrow_width(9),\n gutter_width(0),\n separator_height(6),\n render_gutter(false),\n show_mnemonics(false),\n scroll_arrow_height(3),\n label_to_accelerator_padding(10),\n show_accelerators(true) {\n}\n\nMenuConfig::~MenuConfig() {}\n\nvoid MenuConfig::Reset() {\n delete config_instance;\n config_instance = NULL;\n}\n\n\/\/ static\nconst MenuConfig& MenuConfig::instance() {\n if (!config_instance)\n config_instance = Create();\n return *config_instance;\n}\n\n} \/\/ namespace views\nMake menu items 40px tall when touch-optimized-ui is set.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"ui\/views\/controls\/menu\/menu_config.h\"\n\n#include \"base\/command_line.h\"\n#include \"build\/build_config.h\"\n#include \"ui\/base\/ui_base_switches.h\"\n\nnamespace views {\n\nstatic MenuConfig* config_instance = NULL;\n\nMenuConfig::MenuConfig()\n : text_color(SK_ColorBLACK),\n item_top_margin(3),\n item_bottom_margin(4),\n item_no_icon_top_margin(1),\n item_no_icon_bottom_margin(3),\n item_left_margin(4),\n label_to_arrow_padding(10),\n arrow_to_edge_padding(5),\n icon_to_label_padding(8),\n gutter_to_label(5),\n check_width(16),\n check_height(16),\n radio_width(16),\n radio_height(16),\n arrow_height(9),\n arrow_width(9),\n gutter_width(0),\n separator_height(6),\n render_gutter(false),\n show_mnemonics(false),\n scroll_arrow_height(3),\n label_to_accelerator_padding(10),\n show_accelerators(true) {\n \/\/ Use 40px tall menu items when running in touch optimized mode.\n if (CommandLine::ForCurrentProcess()->HasSwitch(\n switches::kTouchOptimizedUI)) {\n item_top_margin = item_no_icon_top_margin = 12;\n item_bottom_margin = item_no_icon_bottom_margin = 13;\n }\n}\n\nMenuConfig::~MenuConfig() {}\n\nvoid MenuConfig::Reset() {\n delete config_instance;\n config_instance = NULL;\n}\n\n\/\/ static\nconst MenuConfig& MenuConfig::instance() {\n if (!config_instance)\n config_instance = Create();\n return *config_instance;\n}\n\n} \/\/ namespace views\n<|endoftext|>"} {"text":"#ifndef ITER_ZIP_HPP_\n#define ITER_ZIP_HPP_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\n\nnamespace iter {\n template \n class Zipped;\n\n template \n Zipped zip(Containers&&...);\n\n \/\/ specialization for at least 1 template argument\n template \n class Zipped {\n using ZipIterDeref =\n std::tuple,\n iterator_deref...>;\n\n friend Zipped zip(\n Container&&, RestContainers&&...);\n\n template \n friend class Zipped;\n\n private:\n Container container;\n Zipped rest_zipped;\n Zipped(Container container, RestContainers&&... rest)\n : container(std::forward(container)),\n rest_zipped{std::forward(rest)...}\n { }\n\n public:\n class Iterator :\n public std::iterator\n {\n private:\n using RestIter =\n typename Zipped::Iterator;\n\n iterator_type iter;\n RestIter rest_iter;\n public:\n constexpr static const bool is_base_iter = false;\n Iterator(iterator_type it, const RestIter& rest)\n : iter{it},\n rest_iter{rest}\n { }\n\n Iterator& operator++() {\n ++this->iter;\n ++this->rest_iter;\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->iter != other.iter &&\n (RestIter::is_base_iter ||\n this->rest_iter != other.rest_iter);\n }\n\n auto operator*() ->\n decltype(std::tuple_cat(\n std::tuple>{\n *this->iter},\n *this->rest_iter))\n {\n return std::tuple_cat(\n std::tuple>{\n *this->iter},\n *this->rest_iter);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::begin(this->rest_zipped)};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->rest_zipped)};\n }\n };\n\n\n template <>\n class Zipped<> {\n public:\n class Iterator\n : public std::iterator>\n {\n public:\n constexpr static const bool is_base_iter = true;\n\n Iterator() { }\n Iterator(const Iterator&) { }\n Iterator& operator=(const Iterator&) { return *this; }\n\n Iterator& operator++() {\n return *this;\n }\n\n Iterator operator++(int) {\n return *this;\n }\n\n \/\/ if this were to return true, there would be no need\n \/\/ for the is_base_iter static class attribute.\n \/\/ However, returning false causes an empty zip() call\n \/\/ to reach the \"end\" immediately. Returning true here\n \/\/ instead results in an infinite loop in the zip() case\n bool operator!=(const Iterator&) const {\n return false;\n }\n\n std::tuple<> operator*() {\n return std::tuple<>{};\n }\n };\n\n Iterator begin() {\n return {};\n }\n\n Iterator end() {\n return {};\n }\n };\n\n template \n Zipped zip(Containers&&... containers) {\n return {std::forward(containers)...};\n }\n}\n\n#endif \/\/ #ifndef ITER_ZIP_HPP_\nadds zip ==#ifndef ITER_ZIP_HPP_\n#define ITER_ZIP_HPP_\n\n#include \"iterbase.hpp\"\n\n#include \n#include \n#include \n\n\nnamespace iter {\n template \n class Zipped;\n\n template \n Zipped zip(Containers&&...);\n\n \/\/ specialization for at least 1 template argument\n template \n class Zipped {\n using ZipIterDeref =\n std::tuple,\n iterator_deref...>;\n\n friend Zipped zip(\n Container&&, RestContainers&&...);\n\n template \n friend class Zipped;\n\n private:\n Container container;\n Zipped rest_zipped;\n Zipped(Container container, RestContainers&&... rest)\n : container(std::forward(container)),\n rest_zipped{std::forward(rest)...}\n { }\n\n public:\n class Iterator :\n public std::iterator\n {\n private:\n using RestIter =\n typename Zipped::Iterator;\n\n iterator_type iter;\n RestIter rest_iter;\n public:\n constexpr static const bool is_base_iter = false;\n Iterator(iterator_type it, const RestIter& rest)\n : iter{it},\n rest_iter{rest}\n { }\n\n Iterator& operator++() {\n ++this->iter;\n ++this->rest_iter;\n return *this;\n }\n\n Iterator operator++(int) {\n auto ret = *this;\n ++*this;\n return ret;\n }\n\n bool operator!=(const Iterator& other) const {\n return this->iter != other.iter &&\n (RestIter::is_base_iter ||\n this->rest_iter != other.rest_iter);\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this == other);\n }\n\n auto operator*() ->\n decltype(std::tuple_cat(\n std::tuple>{\n *this->iter},\n *this->rest_iter))\n {\n return std::tuple_cat(\n std::tuple>{\n *this->iter},\n *this->rest_iter);\n }\n };\n\n Iterator begin() {\n return {std::begin(this->container),\n std::begin(this->rest_zipped)};\n }\n\n Iterator end() {\n return {std::end(this->container),\n std::end(this->rest_zipped)};\n }\n };\n\n\n template <>\n class Zipped<> {\n public:\n class Iterator\n : public std::iterator>\n {\n public:\n constexpr static const bool is_base_iter = true;\n\n Iterator() { }\n Iterator(const Iterator&) { }\n Iterator& operator=(const Iterator&) { return *this; }\n\n Iterator& operator++() {\n return *this;\n }\n\n Iterator operator++(int) {\n return *this;\n }\n\n \/\/ if this were to return true, there would be no need\n \/\/ for the is_base_iter static class attribute.\n \/\/ However, returning false causes an empty zip() call\n \/\/ to reach the \"end\" immediately. Returning true here\n \/\/ instead results in an infinite loop in the zip() case\n bool operator!=(const Iterator&) const {\n return false;\n }\n\n bool operator==(const Iterator& other) const {\n return !(*this != other);\n }\n\n std::tuple<> operator*() {\n return std::tuple<>{};\n }\n };\n\n Iterator begin() {\n return {};\n }\n\n Iterator end() {\n return {};\n }\n };\n\n template \n Zipped zip(Containers&&... containers) {\n return {std::forward(containers)...};\n }\n}\n\n#endif \/\/ #ifndef ITER_ZIP_HPP_\n<|endoftext|>"} {"text":"#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"moveit_recorder\/utils.h\"\n#include \"moveit_recorder\/experiment_utils.h\"\n#include \"moveit_recorder\/trajectory_video_lookup.h\"\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"split_screen_creator\");\n ros::NodeHandle node_handle; \n ros::AsyncSpinner spinner(1);\n spinner.start();\n\n boost::program_options::options_description desc;\n desc.add_options()\n (\"help\", \"Show help message\")\n (\"regex\", boost::program_options::value(), \"Regex of named videos to make 4x4 split screen with\")\n (\"save_dir\",boost::program_options::value(), \"Directory for videos\");\n boost::program_options::variables_map vm;\n boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);\n boost::program_options::store(po, vm);\n boost::program_options::notify(vm);\n\n if (vm.count(\"help\") || argc == 1) \/\/ show help if no parameters passed\n {\n std::cout << desc << std::endl;\n return 1;\n }\n\n try\n {\n std::string save_dir = utils::get_option(vm, \"save_dir\", \"\");\n boost::regex vid_regex(utils::get_option(vm, \"regex\", \"view.\"));\n boost::filesystem::path save_directory(save_dir);\n \n \/\/ read the bag file to get the file names\n ROS_INFO(\"Opening bag at %s\", save_directory.string().c_str());\n TrajectoryVideoLookup video_lookup_table;\n video_lookup_table.loadFromBag( save_directory.string() );\n \n \/\/ create split screen from regex matched videos\n TrajectoryVideoLookup::iterator traj_it = video_lookup_table.begin();\n for(; traj_it!=video_lookup_table.end();++traj_it)\n {\n std::vector videos;\n TrajectoryVideoLookupEntry::iterator video_it = traj_it->second.begin();\n for(int v=0; v<4; v++)\n {\n boost::cmatch matches;\n if(boost::regex_match( video_it->name.c_str(), matches, vid_regex ))\n {\n videos.push_back( video_it->file );\n video_it++;\n }\n if(video_it==traj_it->second.end())\n video_it=traj_it->second.begin();\n }\n if(videos.size()!=4)\n ROS_WARN(\"No videos matching the regex, unable to create split screen video for trajectory id=\\\"%s\\\"\",traj_it->first.c_str());\n else\n {\n std::string combined = (save_directory \/ boost::str(boost::format(\"%s_%s.%s\") % traj_it->first\n % \"split\"\n % \"ogv\")).string();\n std::string combine_command = boost::str(boost::format(\"ffmpeg -i %s -i %s -i %s -i %s -filter_complex \\'[0:v]scale=iw\/2:ih\/2[rescale1];[1:v]scale=iw\/2:ih\/2[rescale2];[2:v]scale=iw\/2:ih\/2[rescale3];[3:v]scale=iw\/2:ih\/2[rescale4];[rescale1]pad=2*iw:2*ih[topleft];[topleft][rescale2]overlay=W\/2:0[topright];[topright][rescale3]overlay=0:H\/2[bottomleft];[bottomleft][rescale4]overlay=W\/2:H\/2[final]\\' -map [final] -b 10000k %s\") %videos[0] %videos[1] %videos[2] %videos[3] %combined);\n \n std::string response = utils::system::runCommand(combine_command);\n\n video_lookup_table.putVideoFile(traj_it->first, \"split\", combined);\n }\n }\n video_lookup_table.saveToBag( save_directory.string() );\n }\n catch(...)\n {\n std::cout << \"Failure!\" << std::endl;\n }\n\n ROS_INFO(\"Finished creating splitscreen videos.\");\n ros::shutdown();\n\n return 0;\n}\nadded name prefix argument to node to specify name for resulting video#include \n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\n#include \"moveit_recorder\/utils.h\"\n#include \"moveit_recorder\/experiment_utils.h\"\n#include \"moveit_recorder\/trajectory_video_lookup.h\"\n\nint main(int argc, char** argv)\n{\n ros::init(argc, argv, \"split_screen_creator\");\n ros::NodeHandle node_handle; \n ros::AsyncSpinner spinner(1);\n spinner.start();\n\n boost::program_options::options_description desc;\n desc.add_options()\n (\"help\", \"Show help message\")\n (\"prefix\", boost::program_options::value(), \"Prefix of 2x2 merged video\")\n (\"regex\", boost::program_options::value(), \"Regex of named videos to make 2x2 split screen with\")\n (\"save_dir\",boost::program_options::value(), \"Directory for videos\");\n boost::program_options::variables_map vm;\n boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);\n boost::program_options::store(po, vm);\n boost::program_options::notify(vm);\n\n if (vm.count(\"help\") || argc == 1) \/\/ show help if no parameters passed\n {\n std::cout << desc << std::endl;\n return 1;\n }\n\n try\n {\n std::string splitscreen_prefix = utils::get_option(vm, \"prefix\", \"split\");\n std::string save_dir = utils::get_option(vm, \"save_dir\", \"\");\n boost::regex vid_regex(utils::get_option(vm, \"regex\", \"view.\"));\n boost::filesystem::path save_directory(save_dir);\n \n \/\/ read the bag file to get the file names\n ROS_INFO(\"Opening bag at %s\", save_directory.string().c_str());\n TrajectoryVideoLookup video_lookup_table;\n video_lookup_table.loadFromBag( save_directory.string() );\n \n \/\/ create split screen from regex matched videos\n TrajectoryVideoLookup::iterator traj_it = video_lookup_table.begin();\n for(; traj_it!=video_lookup_table.end();++traj_it)\n {\n std::vector videos;\n TrajectoryVideoLookupEntry::iterator video_it = traj_it->second.begin();\n for(; video_it!=traj_it->second.end(); ++video_it)\n {\n boost::cmatch matches;\n if(boost::regex_match( video_it->name.c_str(), matches, vid_regex ))\n videos.push_back( video_it->file );\n }\n if(videos.size()!=4)\n ROS_WARN(\"No videos matching the regex, unable to create split screen video for trajectory id=\\\"%s\\\"\",traj_it->first.c_str());\n else\n {\n std::string combined = (save_directory \/ boost::str(boost::format(\"%s-%s.%s\") % traj_it->first\n % splitscreen_prefix\n % \"ogv\")).string();\n std::string combine_command = boost::str(boost::format(\"ffmpeg -i %s -i %s -i %s -i %s -filter_complex \\'[0:v]scale=iw\/2:ih\/2[rescale1];[1:v]scale=iw\/2:ih\/2[rescale2];[2:v]scale=iw\/2:ih\/2[rescale3];[3:v]scale=iw\/2:ih\/2[rescale4];[rescale1]pad=2*iw:2*ih[topleft];[topleft][rescale2]overlay=W\/2:0[topright];[topright][rescale3]overlay=0:H\/2[bottomleft];[bottomleft][rescale4]overlay=W\/2:H\/2[final]\\' -map [final] -b 10000k %s\") %videos[0] %videos[1] %videos[2] %videos[3] %combined);\n \n std::string response = utils::system::runCommand(combine_command);\n\n video_lookup_table.putVideoFile(traj_it->first, splitscreen_prefix, combined);\n }\n }\n video_lookup_table.saveToBag( save_directory.string() );\n }\n catch(...)\n {\n std::cout << \"Failure!\" << std::endl;\n }\n\n ROS_INFO(\"Finished creating splitscreen videos.\");\n ros::shutdown();\n\n return 0;\n}\n<|endoftext|>"} {"text":"#include \"SkCGUtils.h\"\n#include \"SkBitmap.h\"\n#include \"SkColorPriv.h\"\n\nstatic void SkBitmap_ReleaseInfo(void* info, const void* pixelData, size_t size) {\n SkBitmap* bitmap = reinterpret_cast(info);\n delete bitmap;\n}\n\n#define HAS_ARGB_SHIFTS(a, r, g, b) \\\n (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \\\n && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b))\n\nstatic SkBitmap* prepareForImageRef(const SkBitmap& bm,\n size_t* bitsPerComponent,\n CGBitmapInfo* info) {\n bool upscaleTo32 = false;\n\n switch (bm.config()) {\n case SkBitmap::kRGB_565_Config:\n upscaleTo32 = true;\n \/\/ fall through\n case SkBitmap::kARGB_8888_Config:\n *bitsPerComponent = 8;\n#if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 0, 8, 16) \\\n || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(0, 24, 16, 8)\n *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast;\n#elif defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) \\\n || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0)\n \/\/ Matches the CGBitmapInfo that Apple recommends for best\n \/\/ performance, used by google chrome.\n *info = kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst;\n#else\n\/\/ ...add more formats as required...\n#warning Cannot convert SkBitmap to CGImageRef with these shiftmasks. \\\n This will probably not work.\n \/\/ Legacy behavior. Perhaps turn this into an error at some\n \/\/ point.\n *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast;\n#endif\n break;\n#if 0\n case SkBitmap::kRGB_565_Config:\n \/\/ doesn't see quite right. Are they thinking 1555?\n *bitsPerComponent = 5;\n *info = kCGBitmapByteOrder16Little;\n break;\n#endif\n case SkBitmap::kARGB_4444_Config:\n *bitsPerComponent = 4;\n *info = kCGBitmapByteOrder16Little | kCGImageAlphaPremultipliedLast;\n break;\n default:\n return NULL;\n }\n\n SkBitmap* copy;\n if (upscaleTo32) {\n copy = new SkBitmap;\n \/\/ here we make a ceep copy of the pixels, since CG won't take our\n \/\/ 565 directly\n bm.copyTo(copy, SkBitmap::kARGB_8888_Config);\n } else {\n copy = new SkBitmap(bm);\n }\n return copy;\n}\n\n#undef HAS_ARGB_SHIFTS\n\nCGImageRef SkCreateCGImageRefWithColorspace(const SkBitmap& bm,\n CGColorSpaceRef colorSpace) {\n size_t bitsPerComponent SK_INIT_TO_AVOID_WARNING;\n CGBitmapInfo info SK_INIT_TO_AVOID_WARNING;\n\n SkBitmap* bitmap = prepareForImageRef(bm, &bitsPerComponent, &info);\n if (NULL == bitmap) {\n return NULL;\n }\n\n const int w = bitmap->width();\n const int h = bitmap->height();\n const size_t s = bitmap->getSize();\n\n \/\/ our provider \"owns\" the bitmap*, and will take care of deleting it\n\t\/\/ we initially lock it, so we can access the pixels. The bitmap will be deleted in the release\n\t\/\/ proc, which will in turn unlock the pixels\n\tbitmap->lockPixels();\n CGDataProviderRef dataRef = CGDataProviderCreateWithData(bitmap, bitmap->getPixels(), s,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SkBitmap_ReleaseInfo);\n\n bool releaseColorSpace = false;\n if (NULL == colorSpace) {\n colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);\n releaseColorSpace = true;\n }\n\n CGImageRef ref = CGImageCreate(w, h, bitsPerComponent,\n bitmap->bytesPerPixel() * 8,\n bitmap->rowBytes(), colorSpace, info, dataRef,\n NULL, false, kCGRenderingIntentDefault);\n\n if (releaseColorSpace) {\n CGColorSpaceRelease(colorSpace);\n }\n CGDataProviderRelease(dataRef);\n return ref;\n}\n\nvoid SkCGDrawBitmap(CGContextRef cg, const SkBitmap& bm, float x, float y) {\n CGImageRef img = SkCreateCGImageRef(bm);\n\n if (img) {\n CGRect r = CGRectMake(0, 0, bm.width(), bm.height());\n\n CGContextSaveGState(cg);\n CGContextTranslateCTM(cg, x, r.size.height + y);\n CGContextScaleCTM(cg, 1, -1);\n\n CGContextDrawImage(cg, r, img);\n\n CGContextRestoreGState(cg);\n\n CGImageRelease(img);\n }\n}\n\n\n\nrevert to DeviceRGB colorspace by default, which was changed accidentially in rev. 637#include \"SkCGUtils.h\"\n#include \"SkBitmap.h\"\n#include \"SkColorPriv.h\"\n\nstatic void SkBitmap_ReleaseInfo(void* info, const void* pixelData, size_t size) {\n SkBitmap* bitmap = reinterpret_cast(info);\n delete bitmap;\n}\n\n#define HAS_ARGB_SHIFTS(a, r, g, b) \\\n (SK_A32_SHIFT == (a) && SK_R32_SHIFT == (r) \\\n && SK_G32_SHIFT == (g) && SK_B32_SHIFT == (b))\n\nstatic SkBitmap* prepareForImageRef(const SkBitmap& bm,\n size_t* bitsPerComponent,\n CGBitmapInfo* info) {\n bool upscaleTo32 = false;\n\n switch (bm.config()) {\n case SkBitmap::kRGB_565_Config:\n upscaleTo32 = true;\n \/\/ fall through\n case SkBitmap::kARGB_8888_Config:\n *bitsPerComponent = 8;\n#if defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 0, 8, 16) \\\n || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(0, 24, 16, 8)\n *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast;\n#elif defined(SK_CPU_LENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0) \\\n || defined(SK_CPU_BENDIAN) && HAS_ARGB_SHIFTS(24, 16, 8, 0)\n \/\/ Matches the CGBitmapInfo that Apple recommends for best\n \/\/ performance, used by google chrome.\n *info = kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst;\n#else\n\/\/ ...add more formats as required...\n#warning Cannot convert SkBitmap to CGImageRef with these shiftmasks. \\\n This will probably not work.\n \/\/ Legacy behavior. Perhaps turn this into an error at some\n \/\/ point.\n *info = kCGBitmapByteOrder32Big | kCGImageAlphaPremultipliedLast;\n#endif\n break;\n#if 0\n case SkBitmap::kRGB_565_Config:\n \/\/ doesn't see quite right. Are they thinking 1555?\n *bitsPerComponent = 5;\n *info = kCGBitmapByteOrder16Little;\n break;\n#endif\n case SkBitmap::kARGB_4444_Config:\n *bitsPerComponent = 4;\n *info = kCGBitmapByteOrder16Little | kCGImageAlphaPremultipliedLast;\n break;\n default:\n return NULL;\n }\n\n SkBitmap* copy;\n if (upscaleTo32) {\n copy = new SkBitmap;\n \/\/ here we make a ceep copy of the pixels, since CG won't take our\n \/\/ 565 directly\n bm.copyTo(copy, SkBitmap::kARGB_8888_Config);\n } else {\n copy = new SkBitmap(bm);\n }\n return copy;\n}\n\n#undef HAS_ARGB_SHIFTS\n\nCGImageRef SkCreateCGImageRefWithColorspace(const SkBitmap& bm,\n CGColorSpaceRef colorSpace) {\n size_t bitsPerComponent SK_INIT_TO_AVOID_WARNING;\n CGBitmapInfo info SK_INIT_TO_AVOID_WARNING;\n\n SkBitmap* bitmap = prepareForImageRef(bm, &bitsPerComponent, &info);\n if (NULL == bitmap) {\n return NULL;\n }\n\n const int w = bitmap->width();\n const int h = bitmap->height();\n const size_t s = bitmap->getSize();\n\n \/\/ our provider \"owns\" the bitmap*, and will take care of deleting it\n\t\/\/ we initially lock it, so we can access the pixels. The bitmap will be deleted in the release\n\t\/\/ proc, which will in turn unlock the pixels\n\tbitmap->lockPixels();\n CGDataProviderRef dataRef = CGDataProviderCreateWithData(bitmap, bitmap->getPixels(), s,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t SkBitmap_ReleaseInfo);\n\n bool releaseColorSpace = false;\n if (NULL == colorSpace) {\n colorSpace = CGColorSpaceCreateDeviceRGB();\n releaseColorSpace = true;\n }\n\n CGImageRef ref = CGImageCreate(w, h, bitsPerComponent,\n bitmap->bytesPerPixel() * 8,\n bitmap->rowBytes(), colorSpace, info, dataRef,\n NULL, false, kCGRenderingIntentDefault);\n\n if (releaseColorSpace) {\n CGColorSpaceRelease(colorSpace);\n }\n CGDataProviderRelease(dataRef);\n return ref;\n}\n\nvoid SkCGDrawBitmap(CGContextRef cg, const SkBitmap& bm, float x, float y) {\n CGImageRef img = SkCreateCGImageRef(bm);\n\n if (img) {\n CGRect r = CGRectMake(0, 0, bm.width(), bm.height());\n\n CGContextSaveGState(cg);\n CGContextTranslateCTM(cg, x, r.size.height + y);\n CGContextScaleCTM(cg, 1, -1);\n\n CGContextDrawImage(cg, r, img);\n\n CGContextRestoreGState(cg);\n\n CGImageRelease(img);\n }\n}\n\n\n\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef _WIN32\n#include \"iceoryx_utils\/internal\/posix_wrapper\/access_control.hpp\"\n#include \"iceoryx_utils\/platform\/pwd.hpp\"\n#include \"iceoryx_utils\/platform\/stat.hpp\"\n#include \"test.hpp\"\n\n#include \n\nusing namespace ::testing;\nusing namespace iox::posix;\n\nconstexpr const char* TestFileName = \"\/tmp\/AclTestFile.tmp\";\n\nclass AccessController_test : public Test\n{\n public:\n AccessController_test()\n {\n }\n\n void SetUp()\n {\n internal::CaptureStderr();\n m_fileStream = fopen(TestFileName, \"w\");\n m_fileDescriptor = fileno(m_fileStream);\n }\n\n void TearDown()\n {\n fclose(m_fileStream);\n std::remove(TestFileName);\n\n std::string output = internal::GetCapturedStderr();\n if (Test::HasFailure())\n {\n std::cout << output << std::endl;\n }\n }\n\n ~AccessController_test()\n {\n }\n\n iox::posix::AccessController m_accessController;\n FILE* m_fileStream;\n int m_fileDescriptor;\n};\n\nTEST_F(AccessController_test, writeStandardPermissions)\n{\n \/\/ should fail beacuse no access rights have been specified yet\n bool result = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_FALSE(result);\n\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n\n \/\/ should fail because group and others is missing\n result = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_FALSE(result);\n\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::NONE);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::READ);\n\n \/\/ should succeed now\n result = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_TRUE(result);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n acl_t localACL = acl_from_text(\"u::rw,g::-,o::r\");\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, writeSpecialUserPermissions)\n{\n bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER,\n AccessController::Permission::READWRITE);\n \/\/ no name specified\n EXPECT_FALSE(entryAdded);\n\n std::string currentUserName(getpwuid(geteuid())->pw_name);\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserName);\n EXPECT_TRUE(entryAdded);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n \/\/ standard permissions not yet defined\n EXPECT_FALSE(entriesWrittenToFile);\n\n \/\/ add standard permissions\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_TRUE(entriesWrittenToFile);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n std::string localACLShortText = \"u:\" + currentUserName + \":rw,u::rw,g::r,o::-,m::rw\";\n acl_t localACL = acl_from_text(localACLShortText.c_str());\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, writeSpecialGroupPermissions)\n{\n bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP,\n AccessController::Permission::READWRITE);\n \/\/ no name specified\n EXPECT_FALSE(entryAdded);\n\n std::string groupName = \"root\";\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName);\n EXPECT_TRUE(entryAdded);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n \/\/ standard permissions not yet defined\n EXPECT_FALSE(entriesWrittenToFile);\n\n \/\/ add standard permissions\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_TRUE(entriesWrittenToFile);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n acl_t localACL = acl_from_text(\"g:root:rw,u::rw,g::r,o::-,m::rw\");\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, writeSpecialPermissionsWithID)\n{\n std::string currentUserName(getpwuid(geteuid())->pw_name);\n uid_t currentUserId(getpwuid(geteuid())->pw_uid);\n gid_t groupId = 0; \/\/ root\n\n bool entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserId);\n\n EXPECT_TRUE(entryAdded);\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupId);\n\n EXPECT_TRUE(entryAdded);\n\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n\n EXPECT_TRUE(entriesWrittenToFile);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n std::string localACLShortText = \"u:\" + currentUserName + \":rw,u::rw,g:root:rw,g::r,o::-,m::rw\";\n acl_t localACL = acl_from_text(localACLShortText.c_str());\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, addNameInWrongPlace)\n{\n std::string currentUserName(getpwuid(geteuid())->pw_name);\n\n \/\/ this is not allowed as the default user should not be named explicitly\n m_accessController.addPermissionEntry(\n AccessController::Category::USER, AccessController::Permission::READWRITE, currentUserName);\n\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n bool writtenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_FALSE(writtenToFile);\n}\n\nTEST_F(AccessController_test, addManyPermissions)\n{\n std::string groupName = \"root\";\n\n bool entryAdded;\n for (int i = 0; i < AccessController::MaxNumOfPermissions; ++i)\n {\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName);\n\n ASSERT_TRUE(entryAdded);\n }\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName);\n\n EXPECT_FALSE(entryAdded);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n\n \/\/ the same specific group has been entered several times\n EXPECT_FALSE(entriesWrittenToFile);\n}\n\nTEST_F(AccessController_test, addStrangeNames)\n{\n bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER,\n AccessController::Permission::READWRITE,\n \"VeryUnlikelyThatThisUserExistsOnThisMachine123456\");\n \/\/ non-existing user name specified\n EXPECT_FALSE(entryAdded);\n\n entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP,\n AccessController::Permission::READWRITE,\n \"NeverEverEverSuchAGroupNameExisted\");\n \/\/ non-existing group name specified\n EXPECT_FALSE(entryAdded);\n}\n#endif\niox-#32 disabling acl tests since they are not supported\/\/ Copyright (c) 2019 by Robert Bosch GmbH. All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#if !defined(_WIN32) && !defined(__APPLE__)\n#include \"iceoryx_utils\/internal\/posix_wrapper\/access_control.hpp\"\n#include \"iceoryx_utils\/platform\/pwd.hpp\"\n#include \"iceoryx_utils\/platform\/stat.hpp\"\n#include \"test.hpp\"\n\n#include \n\nusing namespace ::testing;\nusing namespace iox::posix;\n\nconstexpr const char* TestFileName = \"\/tmp\/AclTestFile.tmp\";\n\nclass AccessController_test : public Test\n{\n public:\n AccessController_test()\n {\n }\n\n void SetUp()\n {\n internal::CaptureStderr();\n m_fileStream = fopen(TestFileName, \"w\");\n m_fileDescriptor = fileno(m_fileStream);\n }\n\n void TearDown()\n {\n fclose(m_fileStream);\n std::remove(TestFileName);\n\n std::string output = internal::GetCapturedStderr();\n if (Test::HasFailure())\n {\n std::cout << output << std::endl;\n }\n }\n\n ~AccessController_test()\n {\n }\n\n iox::posix::AccessController m_accessController;\n FILE* m_fileStream;\n int m_fileDescriptor;\n};\n\nTEST_F(AccessController_test, writeStandardPermissions)\n{\n \/\/ should fail beacuse no access rights have been specified yet\n bool result = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_FALSE(result);\n\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n\n \/\/ should fail because group and others is missing\n result = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_FALSE(result);\n\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::NONE);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::READ);\n\n \/\/ should succeed now\n result = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_TRUE(result);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n acl_t localACL = acl_from_text(\"u::rw,g::-,o::r\");\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, writeSpecialUserPermissions)\n{\n bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER,\n AccessController::Permission::READWRITE);\n \/\/ no name specified\n EXPECT_FALSE(entryAdded);\n\n std::string currentUserName(getpwuid(geteuid())->pw_name);\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserName);\n EXPECT_TRUE(entryAdded);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n \/\/ standard permissions not yet defined\n EXPECT_FALSE(entriesWrittenToFile);\n\n \/\/ add standard permissions\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_TRUE(entriesWrittenToFile);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n std::string localACLShortText = \"u:\" + currentUserName + \":rw,u::rw,g::r,o::-,m::rw\";\n acl_t localACL = acl_from_text(localACLShortText.c_str());\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, writeSpecialGroupPermissions)\n{\n bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP,\n AccessController::Permission::READWRITE);\n \/\/ no name specified\n EXPECT_FALSE(entryAdded);\n\n std::string groupName = \"root\";\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName);\n EXPECT_TRUE(entryAdded);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n \/\/ standard permissions not yet defined\n EXPECT_FALSE(entriesWrittenToFile);\n\n \/\/ add standard permissions\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_TRUE(entriesWrittenToFile);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n acl_t localACL = acl_from_text(\"g:root:rw,u::rw,g::r,o::-,m::rw\");\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, writeSpecialPermissionsWithID)\n{\n std::string currentUserName(getpwuid(geteuid())->pw_name);\n uid_t currentUserId(getpwuid(geteuid())->pw_uid);\n gid_t groupId = 0; \/\/ root\n\n bool entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_USER, AccessController::Permission::READWRITE, currentUserId);\n\n EXPECT_TRUE(entryAdded);\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupId);\n\n EXPECT_TRUE(entryAdded);\n\n m_accessController.addPermissionEntry(AccessController::Category::USER, AccessController::Permission::READWRITE);\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n\n EXPECT_TRUE(entriesWrittenToFile);\n\n acl_t fileACL = acl_get_fd(m_fileDescriptor);\n std::string localACLShortText = \"u:\" + currentUserName + \":rw,u::rw,g:root:rw,g::r,o::-,m::rw\";\n acl_t localACL = acl_from_text(localACLShortText.c_str());\n\n std::string fileACLText(acl_to_text(fileACL, nullptr));\n std::string localACLText(acl_to_text(localACL, nullptr));\n\n EXPECT_EQ(fileACLText, localACLText);\n\n acl_free(fileACL);\n acl_free(localACL);\n}\n\nTEST_F(AccessController_test, addNameInWrongPlace)\n{\n std::string currentUserName(getpwuid(geteuid())->pw_name);\n\n \/\/ this is not allowed as the default user should not be named explicitly\n m_accessController.addPermissionEntry(\n AccessController::Category::USER, AccessController::Permission::READWRITE, currentUserName);\n\n m_accessController.addPermissionEntry(AccessController::Category::GROUP, AccessController::Permission::READ);\n m_accessController.addPermissionEntry(AccessController::Category::OTHERS, AccessController::Permission::NONE);\n\n bool writtenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n EXPECT_FALSE(writtenToFile);\n}\n\nTEST_F(AccessController_test, addManyPermissions)\n{\n std::string groupName = \"root\";\n\n bool entryAdded;\n for (int i = 0; i < AccessController::MaxNumOfPermissions; ++i)\n {\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName);\n\n ASSERT_TRUE(entryAdded);\n }\n\n entryAdded = m_accessController.addPermissionEntry(\n AccessController::Category::SPECIFIC_GROUP, AccessController::Permission::READWRITE, groupName);\n\n EXPECT_FALSE(entryAdded);\n\n bool entriesWrittenToFile = m_accessController.writePermissionsToFile(m_fileDescriptor);\n\n \/\/ the same specific group has been entered several times\n EXPECT_FALSE(entriesWrittenToFile);\n}\n\nTEST_F(AccessController_test, addStrangeNames)\n{\n bool entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_USER,\n AccessController::Permission::READWRITE,\n \"VeryUnlikelyThatThisUserExistsOnThisMachine123456\");\n \/\/ non-existing user name specified\n EXPECT_FALSE(entryAdded);\n\n entryAdded = m_accessController.addPermissionEntry(AccessController::Category::SPECIFIC_GROUP,\n AccessController::Permission::READWRITE,\n \"NeverEverEverSuchAGroupNameExisted\");\n \/\/ non-existing group name specified\n EXPECT_FALSE(entryAdded);\n}\n#endif\n<|endoftext|>"} {"text":"#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__\n#define __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__\n\n#include \"vector_tile.pb.h\"\n\nnamespace mapnik { namespace vector_tile_impl {\n\nclass Geometry {\n\npublic:\n inline explicit Geometry(vector_tile::Tile_Feature const& f,\n double tile_x, double tile_y,\n double scale_x, double scale_y);\n\n enum command : uint8_t {\n end = 0,\n move_to = 1,\n line_to = 2,\n close = 7\n };\n\n inline command next(double& rx, double& ry);\n\nprivate:\n vector_tile::Tile_Feature const& f_;\n double scale_x_;\n double scale_y_;\n uint32_t k;\n uint32_t geoms_;\n uint8_t cmd;\n uint32_t length;\n double x, y;\n double ox, oy;\n};\n\nGeometry::Geometry(vector_tile::Tile_Feature const& f,\n double tile_x, double tile_y,\n double scale_x, double scale_y)\n : f_(f),\n scale_x_(scale_x),\n scale_y_(scale_y),\n k(0),\n geoms_(f_.geometry_size()),\n cmd(1),\n length(0),\n x(tile_x), y(tile_y),\n ox(0), oy(0) {}\n\nGeometry::command Geometry::next(double& rx, double& ry) {\n if (k < geoms_) {\n if (length == 0) {\n uint32_t cmd_length = static_cast(f_.geometry(k++));\n cmd = cmd_length & 0x7;\n length = cmd_length >> 3;\n }\n\n --length;\n\n if (cmd == move_to || cmd == line_to) {\n int32_t dx = f_.geometry(k++);\n int32_t dy = f_.geometry(k++);\n dx = ((dx >> 1) ^ (-(dx & 1)));\n dy = ((dy >> 1) ^ (-(dy & 1)));\n x += (static_cast(dx) \/ scale_x_);\n y += (static_cast(dy) \/ scale_y_);\n rx = x;\n ry = y;\n if (cmd == move_to) {\n ox = x;\n oy = y;\n return move_to;\n } else {\n return line_to;\n }\n } else if (cmd == close) {\n rx = ox;\n ry = oy;\n return close;\n } else {\n fprintf(stderr, \"unknown command: %d\\n\", cmd);\n return end;\n }\n } else {\n return end;\n }\n}\n\ninline mapnik::geometry::geometry decode_geometry(vector_tile::Tile_Feature const& f,\n double tile_x, double tile_y,\n double scale_x, double scale_y)\n{\n\n Geometry::command cmd;\n Geometry geoms(f,tile_x,tile_y,scale_x,scale_y);\n double x1, y1;\n switch (f.type())\n {\n case vector_tile::Tile_GeomType_POINT:\n {\n mapnik::geometry::multi_point mp;\n while ((cmd = geoms.next(x1, y1)) != Geometry::end) {\n mp.emplace_back(mapnik::geometry::point(x1,y1));\n }\n std::size_t num_points = mp.size();\n if (num_points == 1)\n {\n \/\/ return the single point\n return mapnik::geometry::geometry(std::move(mp[0]));;\n }\n else if (num_points > 1)\n {\n \/\/ return multipoint\n return mapnik::geometry::geometry(std::move(mp));;\n }\n break;\n }\n case vector_tile::Tile_GeomType_LINESTRING:\n {\n mapnik::geometry::multi_line_string mp;\n mp.emplace_back();\n bool first = true;\n while ((cmd = geoms.next(x1, y1)) != Geometry::end) {\n if (cmd == Geometry::move_to) {\n if (first)\n {\n first = false;\n }\n else\n {\n mp.emplace_back();\n }\n }\n mp.back().add_coord(x1,y1);\n }\n std::size_t num_lines = mp.size();\n if (num_lines == 1)\n {\n \/\/ return the single line\n return mapnik::geometry::geometry(std::move(mp[0]));;\n }\n else if (num_lines > 1)\n {\n \/\/ return multiline\n return mapnik::geometry::geometry(std::move(mp));;\n }\n break;\n }\n case vector_tile::Tile_GeomType_POLYGON:\n {\n \/\/ TODO - support for multipolygons\n \/\/mapnik::geometry::multi_polygon;\n mapnik::geometry::polygon poly;\n std::vector rings;\n rings.emplace_back();\n double x2,y2;\n bool first = true;\n while ((cmd = geoms.next(x1, y1)) != Geometry::end) {\n if (cmd == Geometry::move_to)\n {\n x2 = x1;\n y2 = y1;\n if (first)\n {\n first = false;\n }\n else\n {\n rings.emplace_back();\n }\n }\n else if (cmd == Geometry::close)\n {\n rings.back().add_coord(x2,y2);\n continue;\n }\n rings.back().add_coord(x1,y1);\n }\n std::size_t num_rings = rings.size();\n if (num_rings == 1)\n {\n \/\/ return the single polygon\n mapnik::geometry::polygon poly;\n poly.set_exterior_ring(std::move(rings[0]));\n return mapnik::geometry::geometry(std::move(poly));\n }\n for (unsigned i = 0; i < num_rings;++i)\n {\n mapnik::geometry::polygon poly;\n if (i == 0)\n {\n poly.set_exterior_ring(std::move(rings[i]));\n }\n else\n {\n poly.add_hole(std::move(rings[i]));\n }\n return mapnik::geometry::geometry(std::move(poly));\n }\n return poly;\n break;\n }\n case vector_tile::Tile_GeomType_UNKNOWN:\n default:\n {\n throw std::runtime_error(\"unhandled geometry type during decoding\");\n break;\n }\n }\n return mapnik::geometry::geometry();\n}\n\n}} \/\/ end ns\n\n\n#endif \/\/ __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__\nfix polygon decoder to deal with multiple polygons encoded as multiple paths#ifndef __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__\n#define __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__\n\n#include \"vector_tile.pb.h\"\n\n#include \n\nnamespace mapnik { namespace vector_tile_impl {\n\nclass Geometry {\n\npublic:\n inline explicit Geometry(vector_tile::Tile_Feature const& f,\n double tile_x, double tile_y,\n double scale_x, double scale_y);\n\n enum command : uint8_t {\n end = 0,\n move_to = 1,\n line_to = 2,\n close = 7\n };\n\n inline command next(double& rx, double& ry);\n\nprivate:\n vector_tile::Tile_Feature const& f_;\n double scale_x_;\n double scale_y_;\n uint32_t k;\n uint32_t geoms_;\n uint8_t cmd;\n uint32_t length;\n double x, y;\n double ox, oy;\n};\n\nGeometry::Geometry(vector_tile::Tile_Feature const& f,\n double tile_x, double tile_y,\n double scale_x, double scale_y)\n : f_(f),\n scale_x_(scale_x),\n scale_y_(scale_y),\n k(0),\n geoms_(f_.geometry_size()),\n cmd(1),\n length(0),\n x(tile_x), y(tile_y),\n ox(0), oy(0) {}\n\nGeometry::command Geometry::next(double& rx, double& ry) {\n if (k < geoms_) {\n if (length == 0) {\n uint32_t cmd_length = static_cast(f_.geometry(k++));\n cmd = cmd_length & 0x7;\n length = cmd_length >> 3;\n }\n\n --length;\n\n if (cmd == move_to || cmd == line_to) {\n int32_t dx = f_.geometry(k++);\n int32_t dy = f_.geometry(k++);\n dx = ((dx >> 1) ^ (-(dx & 1)));\n dy = ((dy >> 1) ^ (-(dy & 1)));\n x += (static_cast(dx) \/ scale_x_);\n y += (static_cast(dy) \/ scale_y_);\n rx = x;\n ry = y;\n if (cmd == move_to) {\n ox = x;\n oy = y;\n return move_to;\n } else {\n return line_to;\n }\n } else if (cmd == close) {\n rx = ox;\n ry = oy;\n return close;\n } else {\n fprintf(stderr, \"unknown command: %d\\n\", cmd);\n return end;\n }\n } else {\n return end;\n }\n}\n\ninline mapnik::geometry::geometry decode_geometry(vector_tile::Tile_Feature const& f,\n double tile_x, double tile_y,\n double scale_x, double scale_y)\n{\n\n Geometry::command cmd;\n Geometry geoms(f,tile_x,tile_y,scale_x,scale_y);\n double x1, y1;\n switch (f.type())\n {\n case vector_tile::Tile_GeomType_POINT:\n {\n mapnik::geometry::multi_point mp;\n while ((cmd = geoms.next(x1, y1)) != Geometry::end) {\n mp.emplace_back(mapnik::geometry::point(x1,y1));\n }\n std::size_t num_points = mp.size();\n if (num_points == 1)\n {\n \/\/ return the single point\n return mapnik::geometry::geometry(std::move(mp[0]));;\n }\n else if (num_points > 1)\n {\n \/\/ return multipoint\n return mapnik::geometry::geometry(std::move(mp));;\n }\n break;\n }\n case vector_tile::Tile_GeomType_LINESTRING:\n {\n mapnik::geometry::multi_line_string mp;\n mp.emplace_back();\n bool first = true;\n while ((cmd = geoms.next(x1, y1)) != Geometry::end) {\n if (cmd == Geometry::move_to) {\n if (first)\n {\n first = false;\n }\n else\n {\n mp.emplace_back();\n }\n }\n mp.back().add_coord(x1,y1);\n }\n std::size_t num_lines = mp.size();\n if (num_lines == 1)\n {\n \/\/ return the single line\n return mapnik::geometry::geometry(std::move(mp[0]));;\n }\n else if (num_lines > 1)\n {\n \/\/ return multiline\n return mapnik::geometry::geometry(std::move(mp));;\n }\n break;\n }\n case vector_tile::Tile_GeomType_POLYGON:\n {\n \/\/ TODO - support for multipolygons\n \/\/mapnik::geometry::multi_polygon;\n mapnik::geometry::polygon poly;\n std::vector rings;\n rings.emplace_back();\n double x2,y2;\n bool first = true;\n while ((cmd = geoms.next(x1, y1)) != Geometry::end)\n {\n if (cmd == Geometry::move_to)\n {\n x2 = x1;\n y2 = y1;\n if (first)\n {\n first = false;\n }\n else\n {\n rings.emplace_back();\n }\n }\n else if (cmd == Geometry::close)\n {\n rings.back().add_coord(x2,y2);\n continue;\n }\n rings.back().add_coord(x1,y1);\n }\n\n auto rings_itr = std::make_move_iterator(rings.begin());\n auto rings_end = std::make_move_iterator(rings.end());\n std::size_t num_rings = rings.size();\n if (num_rings == 1)\n {\n \/\/ return the single polygon without interior rings\n mapnik::geometry::polygon poly;\n poly.set_exterior_ring(std::move(*rings_itr));\n return mapnik::geometry::geometry(std::move(poly));\n }\n\n mapnik::geometry::multi_polygon multi_poly;\n multi_poly.emplace_back();\n first = true;\n for (; rings_itr != rings_end; ++rings_itr)\n {\n if (first)\n {\n \/\/ first ring always exterior\n multi_poly.back().set_exterior_ring(std::move(*rings_itr));\n first = false;\n }\n else if (!mapnik::util::is_clockwise(*rings_itr)) \/\/ no-move --> const&\n {\n multi_poly.emplace_back(); \/\/ start new polygon\n multi_poly.back().set_exterior_ring(std::move(*rings_itr));\n }\n else\n {\n multi_poly.back().add_hole(std::move(*rings_itr));\n }\n }\n if (multi_poly.size() == 1)\n {\n auto itr = std::make_move_iterator(multi_poly.begin());\n return mapnik::geometry::geometry(std::move(*itr));\n }\n else\n {\n return mapnik::geometry::geometry(std::move(multi_poly));\n }\n break;\n }\n case vector_tile::Tile_GeomType_UNKNOWN:\n default:\n {\n throw std::runtime_error(\"unhandled geometry type during decoding\");\n break;\n }\n }\n return mapnik::geometry::geometry();\n}\n\n}} \/\/ end ns\n\n\n#endif \/\/ __MAPNIK_VECTOR_TILE_GEOMETRY_DECODER_H__\n<|endoftext|>"} {"text":"\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"Step8.h\"\n\n#include \"QmitkStdMultiWidget.h\"\n\n#include \"mitkGlobalInteraction.h\"\n#include \"mitkRenderingManager.h\"\n\n#include \n#include \n\n\/\/##Documentation\n\/\/## @brief As Step6, but with QmitkStdMultiWidget as widget\nStep8::Step8(int argc, char* argv[], QWidget *parent) :\n\tStep6(argc, argv, parent)\n{\n}\n\nvoid Step8::SetupWidgets()\n{\n\t\/\/*************************************************************************\n\t\/\/ Part I: Create windows and pass the tree to it\n\t\/\/*************************************************************************\n\n\t\/\/ Create toplevel widget with vertical layout\n\tQVBoxLayout* vlayout = new QVBoxLayout(this);\n\tvlayout->setMargin(0);\n\tvlayout->setSpacing(2);\n\n\t\/\/ Create viewParent widget with horizontal layout\n\tQWidget* viewParent = new QWidget(this);\n\tvlayout->addWidget(viewParent);\n\tQHBoxLayout* hlayout = new QHBoxLayout(viewParent);\n\thlayout->setMargin(0);\n\n\t\/\/*************************************************************************\n\t\/\/ Part Ia: create and initialize QmitkStdMultiWidget\n\t\/\/*************************************************************************\n\tQmitkStdMultiWidget* multiWidget = new QmitkStdMultiWidget(viewParent);\n\n\thlayout->addWidget(multiWidget);\n\n\t\/\/ Tell the multiWidget which DataStorage to render\n\tmultiWidget->SetDataStorage(m_DataStorage);\n\n\t\/\/ Initialize views as transversal, sagittal, coronar (from\n\t\/\/ top-left to bottom)\n\tmitk::TimeSlicedGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D(\n\t\t\tm_DataStorage->GetAll());\n\tmitk::RenderingManager::GetInstance()->InitializeViews(geo);\n\n\t\/\/ Initialize bottom-right view as 3D view\n\tmultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID(\n\t\t\tmitk::BaseRenderer::Standard3D);\n\n\t\/\/ Enable standard handler for levelwindow-slider\n\tmultiWidget->EnableStandardLevelWindow();\n\n\t\/\/ Add the displayed views to the DataStorage to see their positions in 2D and 3D\n\tmultiWidget->AddDisplayPlaneSubTree();\n\tmultiWidget->AddPlanesToDataStorage();\n\tmultiWidget->SetWidgetPlanesVisibility(true);\n\n\t\/\/*************************************************************************\n\t\/\/ Part II: Setup standard interaction with the mouse\n\t\/\/*************************************************************************\n\n\t\/\/ Moving the cut-planes to click-point\n\tmultiWidget->EnableNavigationControllerEventListening();\n\n\t\/\/ Zooming and panning\n\tmitk::GlobalInteraction::GetInstance()->AddListener(\n\t\t\tmultiWidget->GetMoveAndZoomInteractor());\n}\n\/**\n \\example Step8.cpp\n *\/\nRemove obsolete code\/*=========================================================================\n\nProgram: Medical Imaging & Interaction Toolkit\nLanguage: C++\nDate: $Date$\nVersion: $Revision$\n\nCopyright (c) German Cancer Research Center, Division of Medical and\nBiological Informatics. All rights reserved.\nSee MITKCopyright.txt or http:\/\/www.mitk.org\/copyright.html for details.\n\nThis software is distributed WITHOUT ANY WARRANTY; without even\nthe implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR\nPURPOSE. See the above copyright notices for more information.\n\n=========================================================================*\/\n\n#include \"Step8.h\"\n\n#include \"QmitkStdMultiWidget.h\"\n\n#include \"mitkGlobalInteraction.h\"\n#include \"mitkRenderingManager.h\"\n\n#include \n#include \n\n\/\/##Documentation\n\/\/## @brief As Step6, but with QmitkStdMultiWidget as widget\nStep8::Step8(int argc, char* argv[], QWidget *parent) :\n\tStep6(argc, argv, parent)\n{\n}\n\nvoid Step8::SetupWidgets()\n{\n\t\/\/*************************************************************************\n\t\/\/ Part I: Create windows and pass the tree to it\n\t\/\/*************************************************************************\n\n\t\/\/ Create toplevel widget with vertical layout\n\tQVBoxLayout* vlayout = new QVBoxLayout(this);\n\tvlayout->setMargin(0);\n\tvlayout->setSpacing(2);\n\n\t\/\/ Create viewParent widget with horizontal layout\n\tQWidget* viewParent = new QWidget(this);\n\tvlayout->addWidget(viewParent);\n\tQHBoxLayout* hlayout = new QHBoxLayout(viewParent);\n\thlayout->setMargin(0);\n\n\t\/\/*************************************************************************\n\t\/\/ Part Ia: create and initialize QmitkStdMultiWidget\n\t\/\/*************************************************************************\n\tQmitkStdMultiWidget* multiWidget = new QmitkStdMultiWidget(viewParent);\n\n\thlayout->addWidget(multiWidget);\n\n\t\/\/ Tell the multiWidget which DataStorage to render\n\tmultiWidget->SetDataStorage(m_DataStorage);\n\n\t\/\/ Initialize views as transversal, sagittal, coronar (from\n\t\/\/ top-left to bottom)\n\tmitk::TimeSlicedGeometry::Pointer geo = m_DataStorage->ComputeBoundingGeometry3D(\n\t\t\tm_DataStorage->GetAll());\n\tmitk::RenderingManager::GetInstance()->InitializeViews(geo);\n\n\t\/\/ Initialize bottom-right view as 3D view\n\tmultiWidget->GetRenderWindow4()->GetRenderer()->SetMapperID(\n\t\t\tmitk::BaseRenderer::Standard3D);\n\n\t\/\/ Enable standard handler for levelwindow-slider\n\tmultiWidget->EnableStandardLevelWindow();\n\n\t\/\/ Add the displayed views to the DataStorage to see their positions in 2D and 3D\n\tmultiWidget->AddDisplayPlaneSubTree();\n\tmultiWidget->AddPlanesToDataStorage();\n\tmultiWidget->SetWidgetPlanesVisibility(true);\n\n\t\/\/*************************************************************************\n\t\/\/ Part II: Setup standard interaction with the mouse\n\t\/\/*************************************************************************\n\n\t\/\/ Moving the cut-planes to click-point\n\tmultiWidget->EnableNavigationControllerEventListening();\n}\n\/**\n \\example Step8.cpp\n *\/\n<|endoftext|>"} {"text":"\/*\n For more information, please see: http:\/\/software.sci.utah.edu\n\n The MIT License\n\n Copyright (c) 2009 Scientific Computing and Imaging Institute,\n University of Utah.\n\n \n Permission is hereby granted, free of charge, to any person obtaining a\n copy of this software and associated documentation files (the \"Software\"),\n to deal in the Software without restriction, including without limitation\n the rights to use, copy, modify, merge, publish, distribute, sublicense,\n and\/or sell copies of the Software, and to permit persons to whom the\n Software is furnished to do so, subject to the following conditions:\n\n The above copyright notice and this permission notice shall be included\n in all copies or substantial portions of the Software.\n\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\n THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\n DEALINGS IN THE SOFTWARE.\n Author : Moritz Dannhauer\n Last modification : March 16 2014 (ported from SCIRun4)\n TODO: Nrrd aoutput\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Utility;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun;\n\ntemplate \nbool \nMapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo,\n\t\t\t FieldHandle& input, \n FieldHandle& output);\n\n\ntemplate \nbool \nMapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo,\n FieldHandle& input, \n FieldHandle& output)\n{\n\t\t\t \n std::string method = algo->get_option(MapFieldDataFromElemToNodeAlgo::Method);\n\n VField *ifield = input->vfield();\n VField *ofield = output->vfield();\n\n \/\/\/ Make sure that the data vector has the same length\n ofield->resize_fdata();\n \n VMesh* mesh = input->vmesh();\n\n VMesh::Elem::array_type elems;\n VMesh::Node::iterator it, eit;\n VMesh::Node::size_type sz;\n\n mesh->synchronize(SCIRun::Mesh::NODE_NEIGHBORS_E);\n\n mesh->begin(it);\n mesh->end(eit);\n \n mesh->size(sz);\n\t\n index_type cnt = 0, c = 0;\n \n if (method == \"Interpolation\")\n {\n algo->remark(\"Interpolation of piecewise constant data is done by averaging adjoining values\");\n }\n \n if ((method == \"Interpolation\")||(method == \"Average\"))\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval;\n for (size_t p = 0; p < nsize; p++)\n {\n ifield->get_value(tval,elems[p]);\n val += tval;\n }\n val = static_cast(val*(1.0\/static_cast(nsize)));\n ofield->set_value(val,*(it));\n ++it;\n cnt++;\n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n } \n }\n \n } else\n if (method == \"Max\")\t\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval(0); \n if (nsize > 0)\n {\n ifield->get_value(val,elems[0]);\n for (size_t p = 1; p < nsize; p++)\n {\n ifield->get_value(tval,elems[p]);\n if (tval > val) val = tval;\n }\n }\n ofield->set_value(val,*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n if (method == \"Min\")\t\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *it);\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval(0);\n if (nsize > 0)\n {\n ifield->get_value(val,elems[0]);\n for (size_t p = 1; p < nsize; p++)\n {\n ifield->value(tval,elems[p]);\n if (tval < val) val = tval;\n } \n }\n ofield->set_value(val,*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n if (method==\"Sum\")\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval(0);\n for (size_t p = 0; p < nsize; p++)\n {\n ifield->get_value(tval,elems[p]);\n val += tval;\n }\n ofield->set_value(val,*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n if (method == \"Median\")\n {\n std::vector valarray;\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n valarray.resize(nsize);\n for (size_t p = 0; p < nsize; p++)\n {\n ifield->get_value(valarray[p],elems[p]);\n }\n sort(valarray.begin(),valarray.end());\n int idx = static_cast((valarray.size()\/2));\n ofield->set_value(valarray[idx],*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n {\n algo->remark(\"Method is not implemented!\"); \n return false;\n }\n \t\t\t \n return true;\n}\n\n\nMapFieldDataFromElemToNodeAlgo::MapFieldDataFromElemToNodeAlgo()\n{\n add_option(Method,\"Interpolation\",\"Interpolation|Average|Min|Max|Sum|Median|None\");\n}\n\nAlgorithmParameterName MapFieldDataFromElemToNodeAlgo::Method(\"Method\");\n\nAlgorithmOutput MapFieldDataFromElemToNodeAlgo::run_generic(const AlgorithmInput& input) const\n{\n auto input_field = input.get(Variables::InputField);\n \n FieldHandle output_field;\n output_field = run(input_field);\n \n AlgorithmOutput output;\n output[Variables::OutputField] = output_field;\n\n return output;\n}\n\n\/\/\/ Function call to convert data from Field into Matrix data\nFieldHandle MapFieldDataFromElemToNodeAlgo::run(FieldHandle input_field) const\n{ \n FieldHandle output;\n\n if (!input_field)\n {\n THROW_ALGORITHM_INPUT_ERROR(\"Input field is not allocated\");\n } \n \n FieldInformation fi(input_field);\n FieldInformation fo(input_field);\n \n if (fi.is_lineardata())\n {\n THROW_ALGORITHM_INPUT_ERROR(\"Data is already located at nodes\"); \n }\n \n if (!(fi.is_constantdata()))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"The input data needs to be located at the elements\");\n }\n \n fo.make_lineardata();\n \n output = CreateField(fo,input_field->mesh());\n \n if (!output)\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output field cannot be allocated\");\n } \n \n if (input_field->vfield()->is_signed_integer())\n {\n if(!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n\t THROW_ALGORITHM_INPUT_ERROR(\"output int field cannot be allocated\");\n\t } \n } else \n \t \n if (input_field->vfield()->is_unsigned_integer()) \n {\n if(!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output uint field cannot be allocated\");\n }\n } else\n \n if (input_field->vfield()->is_scalar())\n {\n if (!MapFieldDataFromElemToNodeT(this,input_field,output))\n { \n THROW_ALGORITHM_INPUT_ERROR(\"output scalar field cannot be allocated\");\n }\n } else\n \n if (input_field->vfield()->is_vector()) \n {\n if (!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output vector field cannot be allocated\"); \n }\n } else\n \n if (input_field->vfield()->is_tensor()) \n {\n if (!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output tensor field cannot be allocated\"); \n }\n } else\n {\n THROW_ALGORITHM_INPUT_ERROR(\" Unknown field data type \"); \n } \n \n return output;\n}\nReformat. Fixes #582\/*\nFor more information, please see: http:\/\/software.sci.utah.edu\n\nThe MIT License\n\nCopyright (c) 2009 Scientific Computing and Imaging Institute,\nUniversity of Utah.\n\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the \"Software\"),\nto deal in the Software without restriction, including without limitation\nthe rights to use, copy, modify, merge, publish, distribute, sublicense,\nand\/or sell copies of the Software, and to permit persons to whom the\nSoftware is furnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL\nTHE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\nFROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\nAuthor : Moritz Dannhauer\nLast modification : March 16 2014 (ported from SCIRun4)\nTODO: Nrrd aoutput\n*\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nusing namespace SCIRun::Core::Algorithms::Fields;\nusing namespace SCIRun::Core::Geometry;\nusing namespace SCIRun::Core::Datatypes;\nusing namespace SCIRun::Core::Utility;\nusing namespace SCIRun::Core::Algorithms;\nusing namespace SCIRun::Core::Logging;\nusing namespace SCIRun;\n\ntemplate \nbool \n MapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo,\n FieldHandle& input, \n FieldHandle& output);\n\n\ntemplate \nbool \n MapFieldDataFromElemToNodeT(const MapFieldDataFromElemToNodeAlgo *algo,\n FieldHandle& input, \n FieldHandle& output)\n{\n\n std::string method = algo->get_option(MapFieldDataFromElemToNodeAlgo::Method);\n\n VField *ifield = input->vfield();\n VField *ofield = output->vfield();\n\n \/\/\/ Make sure that the data vector has the same length\n ofield->resize_fdata();\n\n VMesh* mesh = input->vmesh();\n\n VMesh::Elem::array_type elems;\n VMesh::Node::iterator it, eit;\n VMesh::Node::size_type sz;\n\n mesh->synchronize(SCIRun::Mesh::NODE_NEIGHBORS_E);\n\n mesh->begin(it);\n mesh->end(eit);\n\n mesh->size(sz);\n\n index_type cnt = 0, c = 0;\n\n if (method == \"Interpolation\")\n {\n algo->remark(\"Interpolation of piecewise constant data is done by averaging adjoining values\");\n }\n\n if ((method == \"Interpolation\")||(method == \"Average\"))\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval;\n for (size_t p = 0; p < nsize; p++)\n {\n ifield->get_value(tval,elems[p]);\n val += tval;\n }\n val = static_cast(val*(1.0\/static_cast(nsize)));\n ofield->set_value(val,*(it));\n ++it;\n cnt++;\n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n } \n }\n\n } else\n if (method == \"Max\")\t\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval(0); \n if (nsize > 0)\n {\n ifield->get_value(val,elems[0]);\n for (size_t p = 1; p < nsize; p++)\n {\n ifield->get_value(tval,elems[p]);\n if (tval > val) val = tval;\n }\n }\n ofield->set_value(val,*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n if (method == \"Min\")\t\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *it);\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval(0);\n if (nsize > 0)\n {\n ifield->get_value(val,elems[0]);\n for (size_t p = 1; p < nsize; p++)\n {\n ifield->value(tval,elems[p]);\n if (tval < val) val = tval;\n } \n }\n ofield->set_value(val,*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n if (method==\"Sum\")\n {\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n DATA val(0);\n DATA tval(0);\n for (size_t p = 0; p < nsize; p++)\n {\n ifield->get_value(tval,elems[p]);\n val += tval;\n }\n ofield->set_value(val,*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n if (method == \"Median\")\n {\n std::vector valarray;\n while (it != eit)\n {\n mesh->get_elems(elems, *(it));\n size_t nsize = elems.size();\n valarray.resize(nsize);\n for (size_t p = 0; p < nsize; p++)\n {\n ifield->get_value(valarray[p],elems[p]);\n }\n sort(valarray.begin(),valarray.end());\n int idx = static_cast((valarray.size()\/2));\n ofield->set_value(valarray[idx],*(it));\n ++it;\n cnt++; \n if (cnt==1000) \n { \n cnt=0; c+=1000; \n algo->update_progress(c\/sz); \n }\n }\n } else\n {\n algo->remark(\"Method is not implemented!\"); \n return false;\n }\n\n return true;\n}\n\n\nMapFieldDataFromElemToNodeAlgo::MapFieldDataFromElemToNodeAlgo()\n{\n add_option(Method,\"Interpolation\",\"Interpolation|Average|Min|Max|Sum|Median|None\");\n}\n\nAlgorithmParameterName MapFieldDataFromElemToNodeAlgo::Method(\"Method\");\n\nAlgorithmOutput MapFieldDataFromElemToNodeAlgo::run_generic(const AlgorithmInput& input) const\n{\n auto input_field = input.get(Variables::InputField);\n\n FieldHandle output_field;\n output_field = run(input_field);\n\n AlgorithmOutput output;\n output[Variables::OutputField] = output_field;\n\n return output;\n}\n\n\/\/\/ Function call to convert data from Field into Matrix data\nFieldHandle MapFieldDataFromElemToNodeAlgo::run(FieldHandle input_field) const\n{ \n FieldHandle output;\n\n if (!input_field)\n {\n THROW_ALGORITHM_INPUT_ERROR(\"Input field is not allocated\");\n } \n\n FieldInformation fi(input_field);\n FieldInformation fo(input_field);\n\n if (fi.is_lineardata())\n {\n THROW_ALGORITHM_INPUT_ERROR(\"Data is already located at nodes\"); \n }\n\n if (!(fi.is_constantdata()))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"The input data needs to be located at the elements\");\n }\n\n fo.make_lineardata();\n\n output = CreateField(fo,input_field->mesh());\n\n if (!output)\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output field cannot be allocated\");\n } \n\n if (input_field->vfield()->is_signed_integer())\n {\n if(!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output int field cannot be allocated\");\n } \n }\n else if (input_field->vfield()->is_unsigned_integer()) \n {\n if(!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output uint field cannot be allocated\");\n }\n } else if (input_field->vfield()->is_scalar())\n {\n if (!MapFieldDataFromElemToNodeT(this,input_field,output))\n { \n THROW_ALGORITHM_INPUT_ERROR(\"output scalar field cannot be allocated\");\n }\n } else if (input_field->vfield()->is_vector()) \n {\n if (!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output vector field cannot be allocated\"); \n }\n } else if (input_field->vfield()->is_tensor()) \n {\n if (!MapFieldDataFromElemToNodeT(this,input_field,output))\n {\n THROW_ALGORITHM_INPUT_ERROR(\"output tensor field cannot be allocated\"); \n }\n } \n else\n {\n THROW_ALGORITHM_INPUT_ERROR(\" Unknown field data type \"); \n } \n\n return output;\n}\n<|endoftext|>"} {"text":"#include \"Archs\/SuperH\/CShInstruction.h\"\n\n#include \"Archs\/SuperH\/SuperH.h\"\n#include \"Archs\/SuperH\/ShOpcodes.h\"\n#include \"Archs\/SuperH\/ShParser.h\"\n#include \"Core\/Common.h\"\n#include \"Core\/FileManager.h\"\n#include \"Core\/Misc.h\"\n\nCShInstruction::CShInstruction(ShOpcodeData& opcode, ShImmediateData& immediate, ShRegisterData& registers)\n{\n\tthis->opcodeData = opcode;\n\tthis->immediateData = immediate;\n\tthis->registerData = registers;\n}\n\nCShInstruction::~CShInstruction()\n{\n\n}\n\nint getImmediateBits(ShImmediateType type)\n{\n\tswitch (type)\n\t{\n\tcase ShImmediateType::Immediate4:\n\t\treturn 4;\n\tcase ShImmediateType::Immediate8:\n\t\treturn 8;\n\tcase ShImmediateType::Immediate12:\n\t\treturn 12;\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\nbool CShInstruction::Validate(const ValidateState &state)\n{\n\t\/\/bool Result = false;\n\n\t\/\/bool previousNop = addNop;\n\t\/\/addNop = false;\n\n\tRamPos = g_fileManager->getVirtualAddress();\n\tif (RamPos % 2)\n\t{\n\t\tLogger::queueError(Logger::Error, \"opcode not aligned to word boundary\");\n\t\treturn false;\n\t}\n\n\t\/\/ check immediates\n\tif (immediateData.primary.type != ShImmediateType::None)\n\t{\n\t\tif (immediateData.primary.expression.isLoaded())\n\t\t{\n\t\t\tif (!immediateData.primary.expression.evaluateInteger(immediateData.primary.value))\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Invalid immediate expression\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\timmediateData.primary.originalValue = immediateData.primary.value;\n\t\t}\n\n\t\tif (opcodeData.opcode.flags & SH_MUSTBEALIGNED)\t\/\/ immediate must be aligned\n\t\t{\n\t\t\tif ((opcodeData.opcode.flags & SH_IMM16) && (immediateData.primary.value % 2))\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Immediate must be 2-byte aligned\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ((opcodeData.opcode.flags & SH_IMM32) && (immediateData.primary.value % 4))\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Immediate must be 4-byte aligned\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tint immediateBits = getImmediateBits(immediateData.primary.type);\n\t\tint maxImmediate = ((1 << immediateBits) - 1);\n\n\t\tif (opcodeData.opcode.flags & SH_IMMREL)\t\/\/ relative\n\t\t{\n\t\t\tint ldSize = (opcodeData.opcode.flags & SH_IMM32) ? 4 : 2;\n\t\t\tint rPos = (opcodeData.opcode.flags & SH_IMM32) ? ((RamPos+4) & 0xFFFFFFFFFFFFFFFC) : (RamPos+4);\n\t\t\tint range = maxImmediate*ldSize;\n\t\t\tint hiRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? (range\/2) : range;\n\t\t\tint lowRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? -(range\/2) : 0;\n\n\t\t\tint num = (int) (immediateData.primary.value-rPos);\n\n\t\t\tif (num > hiRange || num < lowRange)\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Branch\/move target %08X out of range\", immediateData.primary.value);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\timmediateData.primary.value = num;\n\t\t}\n\n\t\tif (opcodeData.opcode.flags & SH_IMM16)\n\t\t\timmediateData.primary.value = immediateData.primary.value >> 1;\n\t\telse if (opcodeData.opcode.flags & SH_IMM32)\n\t\t\timmediateData.primary.value = immediateData.primary.value >> 2;\n\t\t\n\t\tunsigned int mask = (0xFFFFFFFF << (32-immediateBits)) >> (32-immediateBits);\n\t\tint digits = (immediateBits+3) \/ 4;\n\n\t\tif ((unsigned int)std::abs(immediateData.primary.value) > mask)\n\t\t{\n\t\t\tLogger::queueError(Logger::Error, \"Immediate value 0x%0*X out of range\",digits,immediateData.primary.value);\n\t\t\treturn false;\n\t\t}\n\n\t\timmediateData.primary.value &= mask;\n\t}\n\n#if 0\n\t\/\/ check load delay\n\tif (Sh.hasLoadDelay() && Sh.GetLoadDelay() && !IgnoreLoadDelay)\n\t{\n\t\tbool fix = false;\n\n\t\tif (registerData.grd.num != -1 && registerData.grd.num == Sh.GetLoadDelayRegister())\n\t\t{\n\t\t\tLogger::queueError(Logger::Warning, \"register %S may not be available due to load delay\",registerData.grd.name);\n\t\t\tfix = true;\n\t\t} else if (registerData.grs.num != -1 && registerData.grs.num == Sh.GetLoadDelayRegister())\n\t\t{\n\t\t\tLogger::queueError(Logger::Warning, \"register %S may not be available due to load delay\",registerData.grs.name);\n\t\t\tfix = true;\n\t\t} else if (registerData.grt.num != -1 && registerData.grt.num == Sh.GetLoadDelayRegister()\n\t\t\t&& !(opcodeData.opcode.flags & MO_IGNORERTD))\n\t\t{\n\t\t\tLogger::queueError(Logger::Warning, \"register %S may not be available due to load delay\",registerData.grt.name);\n\t\t\tfix = true;\n\t\t}\n\n\t\tif (Sh.GetFixLoadDelay() && fix)\n\t\t{\n\t\t\taddNop = true;\n\t\t\tLogger::queueError(Logger::Notice, \"added nop to ensure correct behavior\");\n\t\t}\n\t}\n\n\tif ((opcodeData.opcode.flags & MO_NODELAYSLOT) && Sh.GetDelaySlot() && !IgnoreLoadDelay)\n\t{\n\t\tLogger::queueError(Logger::Error, \"This instruction can't be in a delay slot\");\n\t}\n\n\tSh.SetDelaySlot((opcodeData.opcode.flags & MO_DELAY) != 0);\n\n\t\/\/ now check if this opcode causes a load delay\n\tif (Sh.hasLoadDelay())\n\t\tSh.SetLoadDelay((opcodeData.opcode.flags & MO_DELAYRT) != 0,registerData.grt.num);\n\t\n\tif (previousNop != addNop)\n\t\tResult = true;\n#endif\n\n\tg_fileManager->advanceMemory(2); \/\/addNop ? 4 : 2\n\treturn false;\n}\n\nvoid CShInstruction::Encode() const\n{\n\t\/\/if (addNop)\n\t\/\/\tg_fileManager->writeU32(0);\n\n\tuint16_t encoding = opcodeData.opcode.base;\n\n\tswitch (opcodeData.opcode.format)\n\t{\n\tcase SHFMT_0: \/\/ xxxx xxxx xxxx xxxx\n\t\tbreak;\n\tcase SHFMT_N: \/\/ xxxx nnnn xxxx xxxx\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tbreak;\n\tcase SHFMT_M: \/\/ xxxx mmmm xxxx xxxx\n\t\tencoding |= (registerData.grs.num & 0xF) << 8;\n\t\tbreak;\n\tcase SHFMT_NM: \/\/ xxxx nnnn mmmm xxxx\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= (registerData.grs.num & 0xF) << 4;\n\t\tbreak;\n\tcase SHFMT_MD: \/\/ xxxx xxxx mmmm dddd\n\t\tencoding |= (registerData.grs.num & 0xF) << 4;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_ND4: \/\/ xxxx xxxx nnnn dddd\n\t\tencoding |= (registerData.grt.num & 0xF) << 4;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_NMD: \/\/ xxxx nnnn mmmm dddd\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= (registerData.grs.num & 0xF) << 4;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_D: \/\/ xxxx xxxx dddd dddd\n\tcase SHFMT_D12: \/\/ xxxx dddd dddd dddd\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_ND8: \/\/ xxxx nnnn dddd dddd\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_I: \/\/ xxxx xxxx iiii iiii\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_NI: \/\/ xxxx nnnn iiii iiii\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\t}\n\n\tg_fileManager->writeU16((uint16_t)encoding);\n}\n\nvoid CShInstruction::writeTempData(TempData& tempData) const\n{\n\tShOpcodeFormatter formatter;\n\ttempData.writeLine(RamPos, formatter.formatOpcode(opcodeData,registerData,immediateData));\n}\nAdd a comment regarding delayed instructions in SuperH#include \"Archs\/SuperH\/CShInstruction.h\"\n\n#include \"Archs\/SuperH\/SuperH.h\"\n#include \"Archs\/SuperH\/ShOpcodes.h\"\n#include \"Archs\/SuperH\/ShParser.h\"\n#include \"Core\/Common.h\"\n#include \"Core\/FileManager.h\"\n#include \"Core\/Misc.h\"\n\nCShInstruction::CShInstruction(ShOpcodeData& opcode, ShImmediateData& immediate, ShRegisterData& registers)\n{\n\tthis->opcodeData = opcode;\n\tthis->immediateData = immediate;\n\tthis->registerData = registers;\n}\n\nCShInstruction::~CShInstruction()\n{\n\n}\n\nint getImmediateBits(ShImmediateType type)\n{\n\tswitch (type)\n\t{\n\tcase ShImmediateType::Immediate4:\n\t\treturn 4;\n\tcase ShImmediateType::Immediate8:\n\t\treturn 8;\n\tcase ShImmediateType::Immediate12:\n\t\treturn 12;\n\tdefault:\n\t\treturn 0;\n\t}\n}\n\nbool CShInstruction::Validate(const ValidateState &state)\n{\n\t\/\/bool Result = false;\n\n\t\/\/bool previousNop = addNop;\n\t\/\/addNop = false;\n\n\tRamPos = g_fileManager->getVirtualAddress();\n\tif (RamPos % 2)\n\t{\n\t\tLogger::queueError(Logger::Error, \"opcode not aligned to word boundary\");\n\t\treturn false;\n\t}\n\n\t\/\/ check immediates\n\tif (immediateData.primary.type != ShImmediateType::None)\n\t{\n\t\tif (immediateData.primary.expression.isLoaded())\n\t\t{\n\t\t\tif (!immediateData.primary.expression.evaluateInteger(immediateData.primary.value))\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Invalid immediate expression\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\timmediateData.primary.originalValue = immediateData.primary.value;\n\t\t}\n\n\t\tif (opcodeData.opcode.flags & SH_MUSTBEALIGNED)\t\/\/ immediate must be aligned\n\t\t{\n\t\t\tif ((opcodeData.opcode.flags & SH_IMM16) && (immediateData.primary.value % 2))\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Immediate must be 2-byte aligned\");\n\t\t\t\treturn false;\n\t\t\t}\n\n\t\t\tif ((opcodeData.opcode.flags & SH_IMM32) && (immediateData.primary.value % 4))\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Immediate must be 4-byte aligned\");\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\tint immediateBits = getImmediateBits(immediateData.primary.type);\n\t\tint maxImmediate = ((1 << immediateBits) - 1);\n\n\t\tif (opcodeData.opcode.flags & SH_IMMREL)\t\/\/ relative\n\t\t{\n\t\t\tint ldSize = (opcodeData.opcode.flags & SH_IMM32) ? 4 : 2;\n\t\t\tint rPos = (opcodeData.opcode.flags & SH_IMM32) ? ((RamPos+4) & 0xFFFFFFFFFFFFFFFC) : (RamPos+4);\n\t\t\tint range = maxImmediate*ldSize;\n\t\t\tint hiRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? (range\/2) : range;\n\t\t\tint lowRange = (opcodeData.opcode.flags & SH_IMMSIGNED) ? -(range\/2) : 0;\n\n\t\t\tint num = (int) (immediateData.primary.value-rPos);\n\n\t\t\tif (num > hiRange || num < lowRange)\n\t\t\t{\n\t\t\t\tLogger::queueError(Logger::Error, \"Branch\/move target %08X out of range\", immediateData.primary.value);\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\timmediateData.primary.value = num;\n\t\t}\n\n\t\tif (opcodeData.opcode.flags & SH_IMM16)\n\t\t\timmediateData.primary.value = immediateData.primary.value >> 1;\n\t\telse if (opcodeData.opcode.flags & SH_IMM32)\n\t\t\timmediateData.primary.value = immediateData.primary.value >> 2;\n\t\t\n\t\tunsigned int mask = (0xFFFFFFFF << (32-immediateBits)) >> (32-immediateBits);\n\t\tint digits = (immediateBits+3) \/ 4;\n\n\t\tif ((unsigned int)std::abs(immediateData.primary.value) > mask)\n\t\t{\n\t\t\tLogger::queueError(Logger::Error, \"Immediate value 0x%0*X out of range\",digits,immediateData.primary.value);\n\t\t\treturn false;\n\t\t}\n\n\t\timmediateData.primary.value &= mask;\n\t}\n\n \/\/\n \/\/ NOTE: SuperH *does* have delayed instructions, but\n \/\/ I'm not entirely sure how they work exactly yet,\n \/\/ so leaving this functionality off.\n \/\/\n\n#if 0\n\t\/\/ check load delay\n\tif (Sh.hasLoadDelay() && Sh.GetLoadDelay() && !IgnoreLoadDelay)\n\t{\n\t\tbool fix = false;\n\n\t\tif (registerData.grd.num != -1 && registerData.grd.num == Sh.GetLoadDelayRegister())\n\t\t{\n\t\t\tLogger::queueError(Logger::Warning, \"register %S may not be available due to load delay\",registerData.grd.name);\n\t\t\tfix = true;\n\t\t} else if (registerData.grs.num != -1 && registerData.grs.num == Sh.GetLoadDelayRegister())\n\t\t{\n\t\t\tLogger::queueError(Logger::Warning, \"register %S may not be available due to load delay\",registerData.grs.name);\n\t\t\tfix = true;\n\t\t} else if (registerData.grt.num != -1 && registerData.grt.num == Sh.GetLoadDelayRegister()\n\t\t\t&& !(opcodeData.opcode.flags & MO_IGNORERTD))\n\t\t{\n\t\t\tLogger::queueError(Logger::Warning, \"register %S may not be available due to load delay\",registerData.grt.name);\n\t\t\tfix = true;\n\t\t}\n\n\t\tif (Sh.GetFixLoadDelay() && fix)\n\t\t{\n\t\t\taddNop = true;\n\t\t\tLogger::queueError(Logger::Notice, \"added nop to ensure correct behavior\");\n\t\t}\n\t}\n\n\tif ((opcodeData.opcode.flags & MO_NODELAYSLOT) && Sh.GetDelaySlot() && !IgnoreLoadDelay)\n\t{\n\t\tLogger::queueError(Logger::Error, \"This instruction can't be in a delay slot\");\n\t}\n\n\tSh.SetDelaySlot((opcodeData.opcode.flags & MO_DELAY) != 0);\n\n\t\/\/ now check if this opcode causes a load delay\n\tif (Sh.hasLoadDelay())\n\t\tSh.SetLoadDelay((opcodeData.opcode.flags & MO_DELAYRT) != 0,registerData.grt.num);\n\t\n\tif (previousNop != addNop)\n\t\tResult = true;\n#endif\n\n\tg_fileManager->advanceMemory(2); \/\/addNop ? 4 : 2\n\treturn false;\n}\n\nvoid CShInstruction::Encode() const\n{\n\t\/\/if (addNop)\n\t\/\/\tg_fileManager->writeU32(0);\n\n\tuint16_t encoding = opcodeData.opcode.base;\n\n\tswitch (opcodeData.opcode.format)\n\t{\n\tcase SHFMT_0: \/\/ xxxx xxxx xxxx xxxx\n\t\tbreak;\n\tcase SHFMT_N: \/\/ xxxx nnnn xxxx xxxx\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tbreak;\n\tcase SHFMT_M: \/\/ xxxx mmmm xxxx xxxx\n\t\tencoding |= (registerData.grs.num & 0xF) << 8;\n\t\tbreak;\n\tcase SHFMT_NM: \/\/ xxxx nnnn mmmm xxxx\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= (registerData.grs.num & 0xF) << 4;\n\t\tbreak;\n\tcase SHFMT_MD: \/\/ xxxx xxxx mmmm dddd\n\t\tencoding |= (registerData.grs.num & 0xF) << 4;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_ND4: \/\/ xxxx xxxx nnnn dddd\n\t\tencoding |= (registerData.grt.num & 0xF) << 4;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_NMD: \/\/ xxxx nnnn mmmm dddd\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= (registerData.grs.num & 0xF) << 4;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_D: \/\/ xxxx xxxx dddd dddd\n\tcase SHFMT_D12: \/\/ xxxx dddd dddd dddd\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_ND8: \/\/ xxxx nnnn dddd dddd\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_I: \/\/ xxxx xxxx iiii iiii\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\tcase SHFMT_NI: \/\/ xxxx nnnn iiii iiii\n\t\tencoding |= (registerData.grt.num & 0xF) << 8;\n\t\tencoding |= immediateData.primary.value;\n\t\tbreak;\n\t}\n\n\tg_fileManager->writeU16((uint16_t)encoding);\n}\n\nvoid CShInstruction::writeTempData(TempData& tempData) const\n{\n\tShOpcodeFormatter formatter;\n\ttempData.writeLine(RamPos, formatter.formatOpcode(opcodeData,registerData,immediateData));\n}\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2009-2018, Intel Corporation\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * 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.\n * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS 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.\n*\/\n\/\/ written by Roman Dementiev\n\/\/ Austen Ott\n\/\/ Jim Harris (FreeBSD)\n\n#include \n#include \n#include \n#include \n#ifndef _MSC_VER\n#include \n#endif\n#include \"types.h\"\n#include \"msr.h\"\n#include \n\n#ifdef _MSC_VER\n\n#include \n#include \"utils.h\"\n#include \"Winmsrdriver\\win7\\msrstruct.h\"\n#include \"winring0\/OlsApiInitExt.h\"\n\n#endif\n\n#if defined(__FreeBSD__) || defined(__DragonFly__)\n#include \n#include \n#endif\n\n#include \n\nnamespace pcm {\n\n#ifdef _MSC_VER\n\nextern HMODULE hOpenLibSys;\n\n\/\/ here comes an implementatation for Windows\nMsrHandle::MsrHandle(uint32 cpu) : cpu_id(cpu)\n{\n hDriver = CreateFile(L\"\\\\\\\\.\\\\RDMSR\", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\n if (hDriver == INVALID_HANDLE_VALUE && hOpenLibSys == NULL)\n throw std::exception();\n}\n\nMsrHandle::~MsrHandle()\n{\n if (hDriver != INVALID_HANDLE_VALUE) CloseHandle(hDriver);\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n if (hDriver != INVALID_HANDLE_VALUE)\n {\n MSR_Request req;\n ULONG64 result;\n DWORD reslength = 0;\n req.core_id = cpu_id;\n req.msr_address = msr_number;\n req.write_value = value;\n BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_WRITE, &req, sizeof(MSR_Request), &result, sizeof(uint64), &reslength, NULL);\n assert(status && \"Error in DeviceIoControl\");\n return status ? sizeof(uint64) : 0;\n }\n\n cvt_ds cvt;\n cvt.ui64 = value;\n\n ThreadGroupTempAffinity affinity(cpu_id);\n DWORD status = Wrmsr((DWORD)msr_number, cvt.ui32.low, cvt.ui32.high);\n\n return status ? sizeof(uint64) : 0;\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n if (hDriver != INVALID_HANDLE_VALUE)\n {\n MSR_Request req;\n \/\/ ULONG64 result;\n DWORD reslength = 0;\n req.core_id = cpu_id;\n req.msr_address = msr_number;\n BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_READ, &req, sizeof(MSR_Request), value, sizeof(uint64), &reslength, NULL);\n assert(status && \"Error in DeviceIoControl\");\n return (int32)reslength;\n }\n\n cvt_ds cvt;\n cvt.ui64 = 0;\n\n ThreadGroupTempAffinity affinity(cpu_id);\n DWORD status = Rdmsr((DWORD)msr_number, &(cvt.ui32.low), &(cvt.ui32.high));\n\n if (status) *value = cvt.ui64;\n\n return status ? sizeof(uint64) : 0;\n}\n\n#elif __APPLE__\n\/\/ OSX Version\n\nMSRAccessor * MsrHandle::driver = NULL;\nint MsrHandle::num_handles = 0;\n\nMsrHandle::MsrHandle(uint32 cpu)\n{\n cpu_id = cpu;\n if (!driver)\n {\n driver = new MSRAccessor();\n MsrHandle::num_handles = 1;\n }\n else\n {\n MsrHandle::num_handles++;\n }\n}\n\nMsrHandle::~MsrHandle()\n{\n MsrHandle::num_handles--;\n if (MsrHandle::num_handles == 0)\n {\n delete driver;\n driver = NULL;\n }\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n return driver->write(cpu_id, msr_number, value);\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n return driver->read(cpu_id, msr_number, value);\n}\n\nint32 MsrHandle::buildTopology(uint32 num_cores, void * ptr)\n{\n return driver->buildTopology(num_cores, ptr);\n}\n\nuint32 MsrHandle::getNumInstances()\n{\n return driver->getNumInstances();\n}\n\nuint32 MsrHandle::incrementNumInstances()\n{\n return driver->incrementNumInstances();\n}\n\nuint32 MsrHandle::decrementNumInstances()\n{\n return driver->decrementNumInstances();\n}\n\n#elif defined(__FreeBSD__) || defined(__DragonFly__)\n\nMsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu)\n{\n char path[200];\n snprintf(path, 200, \"\/dev\/cpuctl%d\", cpu);\n int handle = ::open(path, O_RDWR);\n if (handle < 0) throw std::exception();\n fd = handle;\n}\n\nMsrHandle::~MsrHandle()\n{\n if (fd >= 0) ::close(fd);\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n cpuctl_msr_args_t args;\n int ret;\n\n args.msr = msr_number;\n args.data = value;\n ret = ::ioctl(fd, CPUCTL_WRMSR, &args);\n if (ret) return ret;\n return sizeof(value);\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n cpuctl_msr_args_t args;\n int32 ret;\n\n args.msr = msr_number;\n ret = ::ioctl(fd, CPUCTL_RDMSR, &args);\n if (ret) return ret;\n *value = args.data;\n return sizeof(*value);\n}\n\n#else\n\/\/ here comes a Linux version\nMsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu)\n{\n char * path = new char[200];\n snprintf(path, 200, \"\/dev\/cpu\/%d\/msr\", cpu);\n int handle = ::open(path, O_RDWR);\n if (handle < 0)\n { \/\/ try Android msr device path\n snprintf(path, 200, \"\/dev\/msr%d\", cpu);\n handle = ::open(path, O_RDWR);\n }\n delete[] path;\n if (handle < 0)\n {\n std::cerr << \"PCM Error: can't open MSR handle for core \" << cpu << \"\\n\";\n throw std::exception();\n }\n fd = handle;\n}\n\nMsrHandle::~MsrHandle()\n{\n if (fd >= 0) ::close(fd);\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n#if 0\n static std::mutex m;\n std::lock_guard g(m);\n std::cout << \"DEBUG: writing MSR 0x\" << std::hex << msr_number << \" value 0x\" << value << \" on cpu \" << std::dec << cpu_id << std::endl;\n#endif\n return ::pwrite(fd, (const void *)&value, sizeof(uint64), msr_number);\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n return ::pread(fd, (void *)value, sizeof(uint64), msr_number);\n}\n\n#endif\n\n} \/\/ namespace pcm\nallow writes for Linux MSR driver\/*\nCopyright (c) 2009-2018, Intel Corporation\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n * 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.\n * Neither the name of Intel Corporation nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.\n\nTHIS 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.\n*\/\n\/\/ written by Roman Dementiev\n\/\/ Austen Ott\n\/\/ Jim Harris (FreeBSD)\n\n#include \n#include \n#include \n#include \n#ifndef _MSC_VER\n#include \n#endif\n#include \"types.h\"\n#include \"msr.h\"\n#include \"utils.h\"\n#include \n\n#ifdef _MSC_VER\n\n#include \n#include \"utils.h\"\n#include \"Winmsrdriver\\win7\\msrstruct.h\"\n#include \"winring0\/OlsApiInitExt.h\"\n\n#endif\n\n#if defined(__FreeBSD__) || defined(__DragonFly__)\n#include \n#include \n#endif\n\n#include \n\nnamespace pcm {\n\n#ifdef _MSC_VER\n\nextern HMODULE hOpenLibSys;\n\n\/\/ here comes an implementatation for Windows\nMsrHandle::MsrHandle(uint32 cpu) : cpu_id(cpu)\n{\n hDriver = CreateFile(L\"\\\\\\\\.\\\\RDMSR\", GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL);\n\n if (hDriver == INVALID_HANDLE_VALUE && hOpenLibSys == NULL)\n throw std::exception();\n}\n\nMsrHandle::~MsrHandle()\n{\n if (hDriver != INVALID_HANDLE_VALUE) CloseHandle(hDriver);\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n if (hDriver != INVALID_HANDLE_VALUE)\n {\n MSR_Request req;\n ULONG64 result;\n DWORD reslength = 0;\n req.core_id = cpu_id;\n req.msr_address = msr_number;\n req.write_value = value;\n BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_WRITE, &req, sizeof(MSR_Request), &result, sizeof(uint64), &reslength, NULL);\n assert(status && \"Error in DeviceIoControl\");\n return status ? sizeof(uint64) : 0;\n }\n\n cvt_ds cvt;\n cvt.ui64 = value;\n\n ThreadGroupTempAffinity affinity(cpu_id);\n DWORD status = Wrmsr((DWORD)msr_number, cvt.ui32.low, cvt.ui32.high);\n\n return status ? sizeof(uint64) : 0;\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n if (hDriver != INVALID_HANDLE_VALUE)\n {\n MSR_Request req;\n \/\/ ULONG64 result;\n DWORD reslength = 0;\n req.core_id = cpu_id;\n req.msr_address = msr_number;\n BOOL status = DeviceIoControl(hDriver, IO_CTL_MSR_READ, &req, sizeof(MSR_Request), value, sizeof(uint64), &reslength, NULL);\n assert(status && \"Error in DeviceIoControl\");\n return (int32)reslength;\n }\n\n cvt_ds cvt;\n cvt.ui64 = 0;\n\n ThreadGroupTempAffinity affinity(cpu_id);\n DWORD status = Rdmsr((DWORD)msr_number, &(cvt.ui32.low), &(cvt.ui32.high));\n\n if (status) *value = cvt.ui64;\n\n return status ? sizeof(uint64) : 0;\n}\n\n#elif __APPLE__\n\/\/ OSX Version\n\nMSRAccessor * MsrHandle::driver = NULL;\nint MsrHandle::num_handles = 0;\n\nMsrHandle::MsrHandle(uint32 cpu)\n{\n cpu_id = cpu;\n if (!driver)\n {\n driver = new MSRAccessor();\n MsrHandle::num_handles = 1;\n }\n else\n {\n MsrHandle::num_handles++;\n }\n}\n\nMsrHandle::~MsrHandle()\n{\n MsrHandle::num_handles--;\n if (MsrHandle::num_handles == 0)\n {\n delete driver;\n driver = NULL;\n }\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n return driver->write(cpu_id, msr_number, value);\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n return driver->read(cpu_id, msr_number, value);\n}\n\nint32 MsrHandle::buildTopology(uint32 num_cores, void * ptr)\n{\n return driver->buildTopology(num_cores, ptr);\n}\n\nuint32 MsrHandle::getNumInstances()\n{\n return driver->getNumInstances();\n}\n\nuint32 MsrHandle::incrementNumInstances()\n{\n return driver->incrementNumInstances();\n}\n\nuint32 MsrHandle::decrementNumInstances()\n{\n return driver->decrementNumInstances();\n}\n\n#elif defined(__FreeBSD__) || defined(__DragonFly__)\n\nMsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu)\n{\n char path[200];\n snprintf(path, 200, \"\/dev\/cpuctl%d\", cpu);\n int handle = ::open(path, O_RDWR);\n if (handle < 0) throw std::exception();\n fd = handle;\n}\n\nMsrHandle::~MsrHandle()\n{\n if (fd >= 0) ::close(fd);\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n cpuctl_msr_args_t args;\n int ret;\n\n args.msr = msr_number;\n args.data = value;\n ret = ::ioctl(fd, CPUCTL_WRMSR, &args);\n if (ret) return ret;\n return sizeof(value);\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n cpuctl_msr_args_t args;\n int32 ret;\n\n args.msr = msr_number;\n ret = ::ioctl(fd, CPUCTL_RDMSR, &args);\n if (ret) return ret;\n *value = args.data;\n return sizeof(*value);\n}\n\n#else\n\/\/ here comes a Linux version\nMsrHandle::MsrHandle(uint32 cpu) : fd(-1), cpu_id(cpu)\n{\n constexpr auto allowWritesPath = \"\/sys\/module\/msr\/parameters\/allow_writes\";\n static bool writesEnabled = false;\n if (writesEnabled == false)\n {\n if (readSysFS(allowWritesPath, true).length() > 0)\n {\n writeSysFS(allowWritesPath, \"on\", false);\n }\n writesEnabled = true;\n }\n char * path = new char[200];\n snprintf(path, 200, \"\/dev\/cpu\/%d\/msr\", cpu);\n int handle = ::open(path, O_RDWR);\n if (handle < 0)\n { \/\/ try Android msr device path\n snprintf(path, 200, \"\/dev\/msr%d\", cpu);\n handle = ::open(path, O_RDWR);\n }\n delete[] path;\n if (handle < 0)\n {\n std::cerr << \"PCM Error: can't open MSR handle for core \" << cpu << \"\\n\";\n throw std::exception();\n }\n fd = handle;\n}\n\nMsrHandle::~MsrHandle()\n{\n if (fd >= 0) ::close(fd);\n}\n\nint32 MsrHandle::write(uint64 msr_number, uint64 value)\n{\n#if 0\n static std::mutex m;\n std::lock_guard g(m);\n std::cout << \"DEBUG: writing MSR 0x\" << std::hex << msr_number << \" value 0x\" << value << \" on cpu \" << std::dec << cpu_id << std::endl;\n#endif\n return ::pwrite(fd, (const void *)&value, sizeof(uint64), msr_number);\n}\n\nint32 MsrHandle::read(uint64 msr_number, uint64 * value)\n{\n return ::pread(fd, (void *)value, sizeof(uint64), msr_number);\n}\n\n#endif\n\n} \/\/ namespace pcm\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lieonn.hh\"\ntypedef myfloat num_t;\n\n#if ! defined(_FLOAT_BITS_)\n#define _FLOAT_BITS_ 63\n#endif\n#include \n\nint main(int argc, char* argv[]) {\n SimpleMatrix A(8 + 1, 6);\n SimpleVector left(A.rows());\n SimpleVector right(A.rows());\n for(int j = 0; j < 8; j ++) {\n SimpleVector work(4);\n work[0] = num_t(j & 1 ? 1 : 2) \/ num_t(2);\n work[1] = num_t((j >> 1) & 1 ? 1 : 2) \/ num_t(2);\n work[2] = num_t((j >> 2) & 1 ? 1 : 2) \/ num_t(2);\n work[3] = num_t(!((j & 1) && ((j >> 1) & 1)) && ((j >> 2) & 1) ? 2 : 1) \/ num_t(2);\n A.row(j) = makeProgramInvariant(work).first;\n assert(A.cols() == A.row(j).size());\n left[j] = - (right[j] = sqrt(A.epsilon));\n }\n for(int j = 0; j < A.cols(); j ++)\n A(8, j) = num_t(4 == j ? 1 : 0);\n left[8] = sqrt(sqrt(A.epsilon));\n right[8] = num_t(1) \/ sqrt(sqrt(A.epsilon));\n const auto in(A.inner(left, right));\n std::cout << A * in << std::endl;\n return 0;\n}\n\nfix last.#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"lieonn.hh\"\ntypedef myfloat num_t;\n\n#if ! defined(_FLOAT_BITS_)\n#define _FLOAT_BITS_ 63\n#endif\n#include \n\nint main(int argc, char* argv[]) {\n SimpleMatrix A(8 + 1, 6);\n SimpleVector left(A.rows());\n SimpleVector right(A.rows());\n for(int j = 0; j < 8; j ++) {\n SimpleVector work(4);\n work[0] = num_t(j & 1 ? 1 : 2) \/ num_t(2);\n work[1] = num_t((j >> 1) & 1 ? 1 : 2) \/ num_t(2);\n work[2] = num_t((j >> 2) & 1 ? 1 : 2) \/ num_t(2);\n work[3] = num_t(!((j & 1) && ((j >> 1) & 1)) && ((j >> 2) & 1) ? 2 : 1) \/ num_t(2);\n A.row(j) = makeProgramInvariant(work).first;\n assert(A.cols() == A.row(j).size());\n left[j] = - (right[j] = sqrt(A.epsilon));\n }\n for(int j = 0; j < A.cols(); j ++)\n A(8, j) = num_t(3 == j ? 1 : 0);\n left[8] = sqrt(sqrt(A.epsilon));\n right[8] = num_t(1) \/ sqrt(sqrt(A.epsilon));\n const auto in(A.inner(left, right));\n std::cout << A * in << std::endl;\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n\nTEST(mixFun, abs) {\n auto f = [](const auto& x) {\n using std::abs;\n return abs(x);\n };\n stan::test::expect_common_nonzero_unary(f);\n stan::test::expect_value(f, 0);\n stan::test::expect_value(f, 0.0);\n\n stan::test::expect_ad(f, -3);\n stan::test::expect_ad(f, -2);\n stan::test::expect_ad(f, 2);\n\n stan::test::expect_ad(f, -17.3);\n stan::test::expect_ad(f, -0.68);\n stan::test::expect_ad(f, 0.68);\n stan::test::expect_ad(f, 2.0);\n stan::test::expect_ad(f, 4.0);\n\n \/\/ not differentiable at zero\n for (double re : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n for (double im : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n stan::test::expect_ad(f, std::complex(re, im));\n }\n }\n}\nTEST(mixFun, absReturnType) {\n \/\/ validate return types not overpromoted to complex by assignability\n std::complex a = 3;\n stan::math::var b = abs(a);\n\n std::complex> c = 3;\n stan::math::fvar d = abs(c);\n SUCCEED();\n}\n\nTEST(mathMixMatFun, abs_varmat) {\n using stan::math::vec_concat;\n using stan::test::expect_ad_vector_matvar;\n using stan::test::internal::common_nonzero_args;\n auto f = [](const auto& x1) {\n using stan::math::abs;\n return abs(x1);\n };\n std::vector com_args = common_nonzero_args();\n std::vector args{0, -3, -2, 2, -17.3, -0.68, 2, 4};\n auto all_args = vec_concat(com_args, args);\n Eigen::VectorXd A(all_args.size());\n for (int i = 0; i < all_args.size(); ++i) {\n A(i) = all_args[i];\n }\n expect_ad_vector_matvar(f, A);\n}\nDon't test abs gradients at 0 cause they don't exist (Issue #2101)#include \n#include \n#include \n#include \n#include \n\nTEST(mixFun, abs) {\n auto f = [](const auto& x) {\n using std::abs;\n return abs(x);\n };\n stan::test::expect_common_nonzero_unary(f);\n stan::test::expect_value(f, 0);\n stan::test::expect_value(f, 0.0);\n\n stan::test::expect_ad(f, -3);\n stan::test::expect_ad(f, -2);\n stan::test::expect_ad(f, 2);\n\n stan::test::expect_ad(f, -17.3);\n stan::test::expect_ad(f, -0.68);\n stan::test::expect_ad(f, 0.68);\n stan::test::expect_ad(f, 2.0);\n stan::test::expect_ad(f, 4.0);\n\n \/\/ not differentiable at zero\n for (double re : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n for (double im : std::vector{-4, -2.5, -1.5, -0.3, 1.3, 2.1, 3.9}) {\n stan::test::expect_ad(f, std::complex(re, im));\n }\n }\n}\nTEST(mixFun, absReturnType) {\n \/\/ validate return types not overpromoted to complex by assignability\n std::complex a = 3;\n stan::math::var b = abs(a);\n\n std::complex> c = 3;\n stan::math::fvar d = abs(c);\n SUCCEED();\n}\n\nTEST(mathMixMatFun, abs_varmat) {\n using stan::math::vec_concat;\n using stan::test::expect_ad_vector_matvar;\n using stan::test::internal::common_nonzero_args;\n auto f = [](const auto& x1) {\n using stan::math::abs;\n return abs(x1);\n };\n std::vector com_args = common_nonzero_args();\n std::vector args{-3, 2, -0.68, 1};\n auto all_args = vec_concat(com_args, args);\n Eigen::VectorXd A(all_args.size());\n for (int i = 0; i < all_args.size(); ++i) {\n A(i) = all_args[i];\n }\n expect_ad_vector_matvar(f, A);\n}\n<|endoftext|>"} {"text":"Use valueChanged not sliderMoved<|endoftext|>"} {"text":"fix: add missing include file<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_ERR_IS_MAT_FINITE_HPP\n#define STAN_MATH_PRIM_ERR_IS_MAT_FINITE_HPP\n\n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return true<\/code> is the specified matrix is finite.\n * @tparam T Scalar type of the matrix, requires class method\n * .allFinite()<\/code>\n * @tparam EigMat A type derived from `EigenBase`\n * @param y Matrix to test\n * @return true<\/code> if the matrix is finite\n **\/\ntemplate * = nullptr>\ninline bool is_mat_finite(const EigMat& y) {\n return y.allFinite();\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\nadd to_ref for is_mat_finite#ifndef STAN_MATH_PRIM_ERR_IS_MAT_FINITE_HPP\n#define STAN_MATH_PRIM_ERR_IS_MAT_FINITE_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return true<\/code> is the specified matrix is finite.\n * @tparam T Scalar type of the matrix, requires class method\n * .allFinite()<\/code>\n * @tparam EigMat A type derived from `EigenBase`\n * @param y Matrix to test\n * @return true<\/code> if the matrix is finite\n **\/\ntemplate * = nullptr>\ninline bool is_mat_finite(const EigMat& y) {\n return to_ref(y).allFinite();\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"Keep Gups from sending unnecessary completions<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP\n#define STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the lower- and upper-bounded scalar derived by\n * transforming the specified free scalar given the specified\n * lower and upper bounds.\n *\n *

The transform is the transformed and scaled inverse logit,\n *\n *

\\f$f(x) = L + (U - L) \\mbox{logit}^{-1}(x)\\f$\n *\n * @tparam T Type of scalar.\n * @tparam L Type of lower bound.\n * @tparam U Type of upper bound.\n * @param[in] x Free scalar to transform.\n * @param[in] lb Lower bound.\n * @param[in] ub Upper bound.\n * @return Lower- and upper-bounded scalar derived from transforming\n * the free scalar.\n * @throw std::domain_error if ub <= lb\n *\/\ntemplate \ninline auto lub_constrain(const T& x, const L& lb, const U& ub) {\n const auto& x_ref = to_ref(x);\n const auto& lb_ref = to_ref(lb);\n const auto& ub_ref = to_ref(ub);\n\n check_less(\"lub_constrain\", \"lb\", value_of(lb_ref), value_of(ub_ref));\n check_finite(\"lub_constrain\", \"lb\", value_of(lb_ref));\n check_finite(\"lub_constrain\", \"ub\", value_of(ub_ref));\n\n return eval(\n add(elt_multiply(subtract(ub_ref, lb_ref), inv_logit(x_ref)), lb_ref));\n}\n\n\/**\n * Return the lower- and upper-bounded scalar derived by\n * transforming the specified free scalar given the specified\n * lower and upper bounds and increment the specified log\n * density with the log absolute Jacobian determinant.\n *\n *

The transform is as defined in\n * lub_constrain(T, double, double)<\/code>. The log absolute\n * Jacobian determinant is given by\n *\n *

\\f$\\log \\left| \\frac{d}{dx} \\left(\n * L + (U-L) \\mbox{logit}^{-1}(x) \\right)\n * \\right|\\f$\n *\n *

\\f$ {} = \\log |\n * (U-L)\n * \\, (\\mbox{logit}^{-1}(x))\n * \\, (1 - \\mbox{logit}^{-1}(x)) |\\f$\n *\n *

\\f$ {} = \\log (U - L) + \\log (\\mbox{logit}^{-1}(x))\n * + \\log (1 - \\mbox{logit}^{-1}(x))\\f$\n *\n * @tparam T Type of scalar.\n * @tparam L Type of lower bound.\n * @tparam U Type of upper bound.\n * @param[in] x Free scalar to transform.\n * @param[in] lb Lower bound.\n * @param[in] ub Upper bound.\n * @param[in,out] lp Log probability scalar reference.\n * @return Lower- and upper-bounded scalar derived from transforming\n * the free scalar.\n * @throw std::domain_error if ub <= lb\n *\/\ntemplate \ninline auto lub_constrain(const T& x, const L& lb, const U& ub,\n return_type_t& lp) {\n const auto& x_ref = to_ref(x);\n const auto& lb_ref = to_ref(lb);\n const auto& ub_ref = to_ref(ub);\n\n check_less(\"lub_constrain\", \"lb\", value_of(lb_ref), value_of(ub_ref));\n check_finite(\"lub_constrain\", \"lb\", value_of(lb_ref));\n check_finite(\"lub_constrain\", \"ub\", value_of(ub_ref));\n\n const auto& diff = to_ref(subtract(ub_ref, lb_ref));\n \n lp += sum(add(log(diff),\n subtract(-abs(x_ref), multiply(2, log1p_exp(-abs(x_ref))))));\n return eval(add(elt_multiply(diff, inv_logit(x_ref)), lb_ref));\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n[Jenkins] auto-formatting by clang-format version 6.0.0-1ubuntu2~16.04.1 (tags\/RELEASE_600\/final)#ifndef STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP\n#define STAN_MATH_PRIM_FUN_LUB_CONSTRAIN_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\n\n\/**\n * Return the lower- and upper-bounded scalar derived by\n * transforming the specified free scalar given the specified\n * lower and upper bounds.\n *\n *

The transform is the transformed and scaled inverse logit,\n *\n *

\\f$f(x) = L + (U - L) \\mbox{logit}^{-1}(x)\\f$\n *\n * @tparam T Type of scalar.\n * @tparam L Type of lower bound.\n * @tparam U Type of upper bound.\n * @param[in] x Free scalar to transform.\n * @param[in] lb Lower bound.\n * @param[in] ub Upper bound.\n * @return Lower- and upper-bounded scalar derived from transforming\n * the free scalar.\n * @throw std::domain_error if ub <= lb\n *\/\ntemplate \ninline auto lub_constrain(const T& x, const L& lb, const U& ub) {\n const auto& x_ref = to_ref(x);\n const auto& lb_ref = to_ref(lb);\n const auto& ub_ref = to_ref(ub);\n\n check_less(\"lub_constrain\", \"lb\", value_of(lb_ref), value_of(ub_ref));\n check_finite(\"lub_constrain\", \"lb\", value_of(lb_ref));\n check_finite(\"lub_constrain\", \"ub\", value_of(ub_ref));\n\n return eval(\n add(elt_multiply(subtract(ub_ref, lb_ref), inv_logit(x_ref)), lb_ref));\n}\n\n\/**\n * Return the lower- and upper-bounded scalar derived by\n * transforming the specified free scalar given the specified\n * lower and upper bounds and increment the specified log\n * density with the log absolute Jacobian determinant.\n *\n *

The transform is as defined in\n * lub_constrain(T, double, double)<\/code>. The log absolute\n * Jacobian determinant is given by\n *\n *

\\f$\\log \\left| \\frac{d}{dx} \\left(\n * L + (U-L) \\mbox{logit}^{-1}(x) \\right)\n * \\right|\\f$\n *\n *

\\f$ {} = \\log |\n * (U-L)\n * \\, (\\mbox{logit}^{-1}(x))\n * \\, (1 - \\mbox{logit}^{-1}(x)) |\\f$\n *\n *

\\f$ {} = \\log (U - L) + \\log (\\mbox{logit}^{-1}(x))\n * + \\log (1 - \\mbox{logit}^{-1}(x))\\f$\n *\n * @tparam T Type of scalar.\n * @tparam L Type of lower bound.\n * @tparam U Type of upper bound.\n * @param[in] x Free scalar to transform.\n * @param[in] lb Lower bound.\n * @param[in] ub Upper bound.\n * @param[in,out] lp Log probability scalar reference.\n * @return Lower- and upper-bounded scalar derived from transforming\n * the free scalar.\n * @throw std::domain_error if ub <= lb\n *\/\ntemplate \ninline auto lub_constrain(const T& x, const L& lb, const U& ub,\n return_type_t& lp) {\n const auto& x_ref = to_ref(x);\n const auto& lb_ref = to_ref(lb);\n const auto& ub_ref = to_ref(ub);\n\n check_less(\"lub_constrain\", \"lb\", value_of(lb_ref), value_of(ub_ref));\n check_finite(\"lub_constrain\", \"lb\", value_of(lb_ref));\n check_finite(\"lub_constrain\", \"ub\", value_of(ub_ref));\n\n const auto& diff = to_ref(subtract(ub_ref, lb_ref));\n\n lp += sum(add(log(diff),\n subtract(-abs(x_ref), multiply(2, log1p_exp(-abs(x_ref))))));\n return eval(add(elt_multiply(diff, inv_logit(x_ref)), lb_ref));\n}\n\n} \/\/ namespace math\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/** @file\n @brief Implementation\n\n @date 2015\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"DeviceWrapper.h\"\n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n\/\/ - none\n\nnamespace osvr {\nnamespace common {\n\n DeviceWrapper::DeviceWrapper(std::string const &name,\n vrpn_ConnectionPtr const &conn, bool client)\n : vrpn_BaseClass(name.c_str(), conn.get()), m_conn(conn),\n m_client(client) {\n vrpn_BaseClass::init();\n m_setup(conn, common::RawSenderType(d_sender_id));\n\n \/\/ Clients: don't print \"haven't heard from server\" messages.\n if (client) {\n shutup = true;\n }\n }\n\n DeviceWrapper::~DeviceWrapper() {}\n\n void DeviceWrapper::mainloop() { update(); }\n\n void DeviceWrapper::m_update() {\n if (m_client) {\n client_mainloop();\n m_getConnection()->mainloop();\n } else {\n server_mainloop();\n }\n }\n\n int DeviceWrapper::register_types() {\n return 0; \/\/ success\n }\n} \/\/ namespace common\n} \/\/ namespace osvr\nMainloop connection first in client devices.\/** @file\n @brief Implementation\n\n @date 2015\n\n @author\n Sensics, Inc.\n \n*\/\n\n\/\/ Copyright 2015 Sensics, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n\/\/ Internal Includes\n#include \"DeviceWrapper.h\"\n\n\/\/ Library\/third-party includes\n\/\/ - none\n\n\/\/ Standard includes\n\/\/ - none\n\nnamespace osvr {\nnamespace common {\n\n DeviceWrapper::DeviceWrapper(std::string const &name,\n vrpn_ConnectionPtr const &conn, bool client)\n : vrpn_BaseClass(name.c_str(), conn.get()), m_conn(conn),\n m_client(client) {\n vrpn_BaseClass::init();\n m_setup(conn, common::RawSenderType(d_sender_id));\n\n \/\/ Clients: don't print \"haven't heard from server\" messages.\n if (client) {\n shutup = true;\n }\n }\n\n DeviceWrapper::~DeviceWrapper() {}\n\n void DeviceWrapper::mainloop() { update(); }\n\n void DeviceWrapper::m_update() {\n if (m_client) {\n m_getConnection()->mainloop();\n client_mainloop();\n } else {\n server_mainloop();\n }\n }\n\n int DeviceWrapper::register_types() {\n return 0; \/\/ success\n }\n} \/\/ namespace common\n} \/\/ namespace osvr\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"6502.h\"\n\n\/\/ For testing purposes\n#include \"opcodes.h\"\n\nstatic bool\nLoadProgram(ram_t *Ram, const char *Filename)\n{\n FILE *File = fopen(Filename, \"rb\");\n bool Result = false;\n if (File) {\n Result = true;\n fseek(File, 0, SEEK_END);\n u16 ProgramSize = ftell(File);\n fseek(File, 0, SEEK_SET);\n u8 *Program = (u8 *)calloc(ProgramSize, 1);\n fread(Program, 1, ProgramSize, File);\n fclose(File);\n free(Program);\n\n LoadProgram(Ram, Program, ProgramSize);\n }\n return Result;\n}\n\nstatic void\nMemoryDump(ram_t *Ram, u16 StartAddress, u16 Length, u16 ColumnWidth, u16 MarkAddress = 0)\n{\n for (u16 Address = StartAddress; \n Address < StartAddress + Length;\n )\n {\n printf(\"%4x \", Address);\n for (u16 Offset = 0; Offset < ColumnWidth; ++Offset) {\n bool MarkThisOne = (MarkAddress > 0 && MarkAddress == Address);\n if (MarkThisOne) {\n printf(\"[\");\n }\n printf(\"%-2x\", Ram->Data[Address++]);\n if (MarkThisOne) {\n printf(\"]\");\n } else {\n printf(\" \");\n }\n }\n printf(\"\\n\");\n }\n}\n\nstatic void\nMonitor(cpu_t *Cpu, ram_t *Ram)\n{\n const char *StatusFlags = \"\\nNOIBDIZC A X Y PC SP Memory snapshot (%04x - %04x)\\n%s %-2x %-2x %-2x %-2x %-2x \";\n const char *Menu = \"[s]ingle-step [r]estart [g]oto [+\/-] PC [m]emory s[t]ack [q]uit >\";\n bool Running = true;\n u16 MemoryDumpStart = 0;\n u8 MemoryDumpCount = 20;\n while (Running) {\n char Input[128] = {0};\n printf(StatusFlags, MemoryDumpStart, MemoryDumpStart + MemoryDumpCount, GetStatusRegisters(Cpu->SR), Cpu->A, Cpu->X, Cpu->Y, Cpu->PC, Cpu->SP);\n \/\/ Print memory footprint\n for (u16 MemoryAddress = MemoryDumpStart;\n MemoryAddress < MemoryDumpStart + MemoryDumpCount;\n ++MemoryAddress)\n {\n printf(\"%2x \", Ram->Data[MemoryAddress]);\n }\n printf(\"\\n\");\n opcode_e OpCode = (opcode_e)Ram->Data[Cpu->PC];\n instruction_t Instruction = DecodeOpCode(OpCode);\n char *OpCodeName = \"(not impl)\";\n if (Instruction.Func) {\n OpCodeName = Instruction.OpCodeName;\n }\n printf(\"%2X: %9s (%2x) \", Cpu->PC, OpCodeName, OpCode);\n \n printf(Menu);\n scanf(\"%127s\", Input);\n \n if (Input) {\n for (char *CurrentInput = Input; *CurrentInput; ++CurrentInput) {\n switch (*CurrentInput) {\n case 'r':\n memset(Cpu, 0, sizeof(cpu_t));\n break;\n\n case 'q':\n Running = false;\n break;\n\n case 's':\n SingleStepProgram(Cpu, Ram);\n break;\n\n case 't':\n MemoryDump(Ram, STACK_ADDR(0), 0xFF, 0xF, STACK_ADDR(Cpu->SP));\n break;\n\n case 'g':\n {\n printf(\"Enter new PC: \");\n scanf(\"%d\", &Cpu->PC);\n break;\n }\n\n case '+':\n Cpu->PC++;\n break;\n\n case '-':\n Cpu->PC--;\n break;\n\n case 'm':\n MemoryDump(Ram, MemoryDumpStart, 128, 16, MemoryDumpStart);\n break;\n\n }\n }\n }\n }\n}\n\nint\nmain(int argc, char *argv[])\n{\n cpu_t Cpu = {0};\n ram_t Ram = {0};\n\n \/\/*\n u8 Program[] = {\n ASL_zpg, 0, PHP\n };\n Ram.Data[0] = 0xAA;\n u8 ProgramCount = sizeof(Program) \/ sizeof(Program[0]);\n LoadProgram(&Ram, Program, ProgramCount, 0x10);\n \/\/*\/\n \/\/LoadProgram(&Ram, \"rom\/atari2600\/Vid_olym.bin\");\n \/\/ SingleStepProgram(&Cpu, &Ram);\n Monitor(&Cpu, &Ram);\n\n printf(\"Program ran for %i cycles.\\n\", Cpu.CycleCount);\n\n return 0;\n}\nPretty print opname(opcode) additionalbytes#include \n#include \n#include \n#include \"6502.h\"\n\n\/\/ For testing purposes\n#include \"opcodes.h\"\n\nstatic bool\nLoadProgram(ram_t *Ram, const char *Filename)\n{\n FILE *File = fopen(Filename, \"rb\");\n bool Result = false;\n if (File) {\n Result = true;\n fseek(File, 0, SEEK_END);\n u16 ProgramSize = ftell(File);\n fseek(File, 0, SEEK_SET);\n u8 *Program = (u8 *)calloc(ProgramSize, 1);\n fread(Program, 1, ProgramSize, File);\n fclose(File);\n free(Program);\n\n LoadProgram(Ram, Program, ProgramSize);\n }\n return Result;\n}\n\nstatic void\nMemoryDump(ram_t *Ram, u16 StartAddress, u16 Length, u16 ColumnWidth, u16 MarkAddress = 0)\n{\n for (u16 Address = StartAddress; \n Address < StartAddress + Length;\n )\n {\n printf(\"%4x \", Address);\n for (u16 Offset = 0; Offset < ColumnWidth; ++Offset) {\n bool MarkThisOne = (MarkAddress > 0 && MarkAddress == Address);\n if (MarkThisOne) {\n printf(\"[\");\n }\n printf(\"%-2x\", Ram->Data[Address++]);\n if (MarkThisOne) {\n printf(\"]\");\n } else {\n printf(\" \");\n }\n }\n printf(\"\\n\");\n }\n}\n\nstatic void\nMonitor(cpu_t *Cpu, ram_t *Ram)\n{\n const char *StatusFlags = \"\\nNOIBDIZC A X Y PC SP Memory snapshot (%04x - %04x)\\n%s %-2x %-2x %-2x %-2x %-2x \";\n const char *Menu = \"[s]ingle-step [r]estart [g]oto [+\/-] PC [m]emory s[t]ack [q]uit >\";\n bool Running = true;\n u16 MemoryDumpStart = 0;\n u8 MemoryDumpCount = 20;\n while (Running) {\n char Input[128] = {0};\n printf(StatusFlags, MemoryDumpStart, MemoryDumpStart + MemoryDumpCount, GetStatusRegisters(Cpu->SR), Cpu->A, Cpu->X, Cpu->Y, Cpu->PC, Cpu->SP);\n \/\/ Print memory footprint\n for (u16 MemoryAddress = MemoryDumpStart;\n MemoryAddress < MemoryDumpStart + MemoryDumpCount;\n ++MemoryAddress)\n {\n printf(\"%2x \", Ram->Data[MemoryAddress]);\n }\n printf(\"\\n\");\n opcode_e OpCode = (opcode_e)Ram->Data[Cpu->PC];\n instruction_t Instruction = DecodeOpCode(OpCode);\n char *OpCodeName = \"(not impl)\";\n if (Instruction.Func) {\n OpCodeName = Instruction.OpCodeName;\n }\n \/\/printf(\"%2X: %9s (%2x) \", Cpu->PC, OpCodeName, OpCode);\n printf(\"%s(%02x)\", OpCodeName, OpCode);\n for (u8 i = 0; i < Instruction.Bytes; ++i) {\n printf(\" %2x\", Ram->Data[Cpu->PC + i + 1]);\n }\n printf(\" \");\n\n printf(Menu);\n scanf(\"%127s\", Input);\n \n if (Input) {\n for (char *CurrentInput = Input; *CurrentInput; ++CurrentInput) {\n switch (*CurrentInput) {\n case 'r':\n memset(Cpu, 0, sizeof(cpu_t));\n break;\n\n case 'q':\n Running = false;\n break;\n\n case 's':\n SingleStepProgram(Cpu, Ram);\n break;\n\n case 't':\n MemoryDump(Ram, STACK_ADDR(0), 0xFF, 0xF, STACK_ADDR(Cpu->SP));\n break;\n\n case 'g':\n {\n printf(\"Enter new PC: \");\n scanf(\"%d\", &Cpu->PC);\n break;\n }\n\n case '+':\n Cpu->PC++;\n break;\n\n case '-':\n Cpu->PC--;\n break;\n\n case 'm':\n MemoryDump(Ram, MemoryDumpStart, 128, 16, MemoryDumpStart);\n break;\n\n }\n }\n }\n }\n}\n\nint\nmain(int argc, char *argv[])\n{\n cpu_t Cpu = {0};\n ram_t Ram = {0};\n\n \/\/*\n u8 Program[] = {\n ASL_zpg, 0, PHP\n };\n Ram.Data[0] = 0xAA;\n u8 ProgramCount = sizeof(Program) \/ sizeof(Program[0]);\n LoadProgram(&Ram, Program, ProgramCount, 0x10);\n \/\/*\/\n \/\/LoadProgram(&Ram, \"rom\/atari2600\/Vid_olym.bin\");\n \/\/ SingleStepProgram(&Cpu, &Ram);\n Monitor(&Cpu, &Ram);\n\n printf(\"Program ran for %i cycles.\\n\", Cpu.CycleCount);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/**************************************************************************\n * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/\/.\n\/\/.\n\/\/.\n\/\/.\n\/\/.\n#include \n#include \n#include \"AliRunDigitizer.h\"\n#include \n#include \"AliLog.h\"\n#include \n#include \n#include \"AliHMPIDDigitizer.h\"\n#include \"AliHMPIDReconstructor.h\"\n#include \"AliHMPIDDigit.h\"\n#include \"AliHMPID.h\"\n#include \"AliHMPIDParam.h\"\n#include \n#include \n#include \n#include \n\nClassImp(AliHMPIDDigitizer)\n\nBool_t AliHMPIDDigitizer::fgDoNoise=kTRUE;\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nvoid AliHMPIDDigitizer::Exec(Option_t*)\n{\n\/\/ This methode is responsible for merging sdigits to a list of digits\n\/\/Disintegration leeds to the fact that one hit affects several neighbouring pads, which means that the same pad might be affected by few hits. \n AliDebug(1,Form(\"Start with %i input(s) for event %i\",fManager->GetNinputs(),fManager->GetOutputEventNr()));\n\/\/First we read all sdigits from all inputs \n AliRunLoader *pInRunLoader=0;\/\/in and out Run loaders\n AliLoader *pInRichLoader=0;\/\/in and out HMPID loaders \n static TClonesArray sdigs(\"AliHMPIDDigit\");\/\/tmp storage for sdigits sum up from all input files\n Int_t total=0;\n for(Int_t inFileN=0;inFileNGetNinputs();inFileN++){\/\/files loop\n pInRunLoader = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inFileN)); \/\/get run loader from current input \n pInRichLoader = pInRunLoader->GetLoader(\"HMPIDLoader\"); if(pInRichLoader==0) continue; \/\/no HMPID in this input, check the next input\n if (!pInRunLoader->GetAliRun()) pInRunLoader->LoadgAlice();\n AliHMPID* pInRich=(AliHMPID*)pInRunLoader->GetAliRun()->GetDetector(\"HMPID\"); \/\/take HMPID from current input\n pInRichLoader->LoadSDigits(); pInRichLoader->TreeS()->GetEntry(0); \/\/take list of HMPID sdigits from current input \n AliDebug(1,Form(\"input %i has %i sdigits\",inFileN,pInRich->SdiLst()->GetEntries()));\n for(Int_t i=0;iSdiLst()->GetEntries();i++){ \/\/collect sdigits from current input\n AliHMPIDDigit *pSDig=(AliHMPIDDigit*)pInRich->SdiLst()->At(i);\n pSDig->AddTidOffset(fManager->GetMask(inFileN)); \/\/apply TID shift since all inputs count tracks independently starting from 0\n new(sdigs[total++]) AliHMPIDDigit(*pSDig); \n }\n pInRichLoader->UnloadSDigits(); pInRich->SdiReset(); \/\/close current input and reset \n }\/\/files loop\n\n \/\/PH if(sdigs.GetEntries()==0) return; \/\/no sdigits collected, nothing to convert \n \n AliRunLoader *pOutRunLoader = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName()); \/\/open output stream (only 1 possible)\n AliLoader *pOutRichLoader = pOutRunLoader->GetLoader(\"HMPIDLoader\"); \/\/take output HMPID loader\n AliRun *pArun = pOutRunLoader->GetAliRun();\n AliHMPID *pOutRich = (AliHMPID*)pArun->GetDetector(\"HMPID\"); \/\/take output HMPID\n pOutRichLoader->MakeTree(\"D\"); pOutRich->MakeBranch(\"D\"); \/\/create TreeD in output stream\n\n Sdi2Dig(&sdigs,pOutRich->DigLst());\n \n pOutRichLoader->TreeD()->Fill(); \/\/fill the output tree with the list of digits\n pOutRichLoader->WriteDigits(\"OVERWRITE\"); \/\/serialize them to file\n \n sdigs.Clear(); \/\/remove all tmp sdigits\n pOutRichLoader->UnloadDigits(); pOutRich->DigReset();\n}\/\/Exec()\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nvoid AliHMPIDDigitizer::Sdi2Dig(TClonesArray *pSdiLst,TObjArray *pDigLst)\n{\n\/\/ Converts list of sdigits to 7 lists of digits, one per each chamber\n\/\/ Arguments: pSDigLst - list of all sdigits\n\/\/ pDigLst - list of 7 lists of digits \n\/\/ Returns: none \n \n TClonesArray *pLst[7]; Int_t iCnt[7];\n\n for(Int_t i=0;i<7;i++){\n pLst[i]=(TClonesArray*)(*pDigLst)[i];\n iCnt[i]=0; if(pLst[i]->GetEntries()!=0) AliErrorClass(\"Some of digits lists is not empty\"); \/\/in principle those lists should be empty \n }\n\n TMatrixF *pM[7];\n \n AliCDBEntry *pDaqSigEnt = AliCDBManager::Instance()->Get(\"HMPID\/Calib\/DaqSig\"); \/\/contains TObjArray of TObjArray 14 TMatrixF sigmas values for pads \n if(pDaqSigEnt){\n TObjArray *pDaqSig = (TObjArray*)pDaqSigEnt->GetObject();\n for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){ \/\/chambers loop \n pM[iCh] = (TMatrixF*)pDaqSig->At(iCh); \n }\n }\n else{\n for (Int_t iCh=0; iCh<7; iCh++)\n for (Int_t i=0; i<160; i++)\n for (Int_t j=0; j<144; j++)\n (*pM[iCh])(i,j) = 1.0; \n }\n \n \/\/ make noise array\n Float_t arrNoise[7][6][80][48];\n if(fgDoNoise) {\n for (Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++)\n for (Int_t iPc=AliHMPIDParam::kMinPc;iPc<=AliHMPIDParam::kMaxPc;iPc++)\n for(Int_t iPx=AliHMPIDParam::kMinPx;iPx<=AliHMPIDParam::kMaxPx;iPx++)\n for(Int_t iPy=AliHMPIDParam::kMinPy;iPy<=AliHMPIDParam::kMaxPy;iPy++){\n Int_t padX = (iPc%2)*AliHMPIDParam::kPadPcX+iPx; \n Int_t padY = (iPc\/2)*AliHMPIDParam::kPadPcY+iPy;\n arrNoise[iCh][iPc][iPx][iPy] = gRandom->Gaus(0,(*pM[iCh])(padX,padY));\n } \n } \n \n pSdiLst->Sort(); \n \n Int_t iPad=-1,iCh=-1,iNdigPad=-1,aTids[3]={-1,-1,-1}; Float_t q=-1;\n for(Int_t i=0;iGetEntries();i++){ \/\/sdigits loop (sorted)\n AliHMPIDDigit *pSdig=(AliHMPIDDigit*)pSdiLst->At(i); \/\/take current sdigit\n if(pSdig->Pad()==iPad){ \/\/if the same pad \n q+=pSdig->Q(); \/\/sum up charge\n iNdigPad++; if(iNdigPad<=3) aTids[iNdigPad-1]=pSdig->GetTrack(0); \/\/collect TID \n continue;\n }\n if(i!=0 && iCh>=AliHMPIDParam::kMinCh && iCh<=AliHMPIDParam::kMaxCh){\n AliHMPIDParam::Instance()->SetThreshold(TMath::Nint(((*pM[iCh])(pSdig->PadChX(),pSdig->PadChY()))*AliHMPIDParam::Nsig())); \n if(AliHMPIDParam::IsOverTh(q)) new((*pLst[iCh])[iCnt[iCh]++]) AliHMPIDDigit(iPad,(Int_t)q,aTids);} \/\/do not create digit for the very first sdigit \n \n iPad=pSdig->Pad(); iCh=AliHMPIDParam::A2C(iPad); \/\/new sdigit comes, reset collectors\n iNdigPad=1;\n aTids[0]=pSdig->GetTrack(0);aTids[1]=aTids[2]=-1; \n q=pSdig->Q();\n if(fgDoNoise) q+=arrNoise[iCh][pSdig->Pc()][pSdig->PadPcX()][pSdig->PadPcY()];\n arrNoise[iCh][pSdig->Pc()][pSdig->PadPcX()][pSdig->PadPcY()]=0;\n }\/\/sdigits loop (sorted)\n \n if(iCh>=AliHMPIDParam::kMinCh && iCh<=AliHMPIDParam::kMaxCh){\n Int_t pc = AliHMPIDParam::A2P(iPad);\n Int_t padX = (pc%2)*AliHMPIDParam::kPadPcX+AliHMPIDParam::A2X(iPad); \n Int_t padY = (pc\/2)*AliHMPIDParam::kPadPcY+AliHMPIDParam::A2Y(iPad);\n AliHMPIDParam::Instance()->SetThreshold(TMath::Nint(((*pM[iCh])(padX,padY))*AliHMPIDParam::Nsig()));\n if(AliHMPIDParam::IsOverTh(q)) new((*pLst[iCh])[iCnt[iCh]++]) AliHMPIDDigit(iPad,(Int_t)q,aTids);} \/\/add the last one, in case of empty sdigits list q=-1 \n \n\/\/ add noise pad above threshold with no signal merged...if any\n if(!fgDoNoise) return;\n \n aTids[0]=aTids[1]=aTids[2]=-1;\n for (Int_t iChCurr=AliHMPIDParam::kMinCh;iChCurr<=AliHMPIDParam::kMaxCh;iChCurr++){\n for (Int_t iPc=AliHMPIDParam::kMinPc;iPc<=AliHMPIDParam::kMaxPc;iPc++)\n for(Int_t iPx=AliHMPIDParam::kMinPx;iPx<=AliHMPIDParam::kMaxPx;iPx++)\n for(Int_t iPy=AliHMPIDParam::kMinPy;iPy<=AliHMPIDParam::kMaxPy;iPy++) {\n Float_t qNoise = arrNoise[iChCurr][iPc][iPx][iPy];\n Int_t padX = (iPc%2)*AliHMPIDParam::kPadPcX+iPx; \n Int_t padY = (iPc\/2)*AliHMPIDParam::kPadPcY+iPy;\n AliHMPIDParam::Instance()->SetThreshold(TMath::Nint(((*pM[iChCurr])(padX,padY))*AliHMPIDParam::Nsig()));\n if(AliHMPIDParam::IsOverTh(qNoise)) new((*pLst[iChCurr])[iCnt[iChCurr]++]) AliHMPIDDigit(AliHMPIDParam::Abs(iChCurr,iPc,iPx,iPy),(Int_t)qNoise,aTids);\n }\n } \n}\/\/Sdi2Dig()\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nMinors\/**************************************************************************\n * Copyright(c) 1998-2000, ALICE Experiment at CERN, All rights reserved. *\n * *\n * Author: The ALICE Off-line Project. *\n * Contributors are mentioned in the code where appropriate. *\n * *\n * Permission to use, copy, modify and distribute this software and its *\n * documentation strictly for non-commercial purposes is hereby granted *\n * without fee, provided that the above copyright notice appears in all *\n * copies and that both the copyright notice and this permission notice *\n * appear in the supporting documentation. The authors make no claims *\n * about the suitability of this software for any purpose. It is *\n * provided \"as is\" without express or implied warranty. *\n **************************************************************************\/\n\/\/.\n\/\/.\n\/\/.\n\/\/.\n\/\/.\n#include \n#include \n#include \"AliRunDigitizer.h\"\n#include \n#include \"AliLog.h\"\n#include \n#include \n#include \"AliHMPIDDigitizer.h\"\n#include \"AliHMPIDReconstructor.h\"\n#include \"AliHMPIDDigit.h\"\n#include \"AliHMPID.h\"\n#include \"AliHMPIDParam.h\"\n#include \n#include \n#include \n#include \n\nClassImp(AliHMPIDDigitizer)\n\nBool_t AliHMPIDDigitizer::fgDoNoise=kTRUE;\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nvoid AliHMPIDDigitizer::Exec(Option_t*)\n{\n\/\/ This methode is responsible for merging sdigits to a list of digits\n\/\/Disintegration leeds to the fact that one hit affects several neighbouring pads, which means that the same pad might be affected by few hits. \n AliDebug(1,Form(\"Start with %i input(s) for event %i\",fManager->GetNinputs(),fManager->GetOutputEventNr()));\n\/\/First we read all sdigits from all inputs \n AliRunLoader *pInRunLoader=0;\/\/in and out Run loaders\n AliLoader *pInRichLoader=0;\/\/in and out HMPID loaders \n static TClonesArray sdigs(\"AliHMPIDDigit\");\/\/tmp storage for sdigits sum up from all input files\n Int_t total=0;\n for(Int_t inFileN=0;inFileNGetNinputs();inFileN++){\/\/files loop\n pInRunLoader = AliRunLoader::GetRunLoader(fManager->GetInputFolderName(inFileN)); \/\/get run loader from current input \n pInRichLoader = pInRunLoader->GetLoader(\"HMPIDLoader\"); if(pInRichLoader==0) continue; \/\/no HMPID in this input, check the next input\n if (!pInRunLoader->GetAliRun()) pInRunLoader->LoadgAlice();\n AliHMPID* pInRich=(AliHMPID*)pInRunLoader->GetAliRun()->GetDetector(\"HMPID\"); \/\/take HMPID from current input\n pInRichLoader->LoadSDigits(); pInRichLoader->TreeS()->GetEntry(0); \/\/take list of HMPID sdigits from current input \n AliDebug(1,Form(\"input %i has %i sdigits\",inFileN,pInRich->SdiLst()->GetEntries()));\n for(Int_t i=0;iSdiLst()->GetEntries();i++){ \/\/collect sdigits from current input\n AliHMPIDDigit *pSDig=(AliHMPIDDigit*)pInRich->SdiLst()->At(i);\n pSDig->AddTidOffset(fManager->GetMask(inFileN)); \/\/apply TID shift since all inputs count tracks independently starting from 0\n new(sdigs[total++]) AliHMPIDDigit(*pSDig); \n }\n pInRichLoader->UnloadSDigits(); pInRich->SdiReset(); \/\/close current input and reset \n }\/\/files loop\n\n \/\/PH if(sdigs.GetEntries()==0) return; \/\/no sdigits collected, nothing to convert \n \n AliRunLoader *pOutRunLoader = AliRunLoader::GetRunLoader(fManager->GetOutputFolderName()); \/\/open output stream (only 1 possible)\n AliLoader *pOutRichLoader = pOutRunLoader->GetLoader(\"HMPIDLoader\"); \/\/take output HMPID loader\n AliRun *pArun = pOutRunLoader->GetAliRun();\n AliHMPID *pOutRich = (AliHMPID*)pArun->GetDetector(\"HMPID\"); \/\/take output HMPID\n pOutRichLoader->MakeTree(\"D\"); pOutRich->MakeBranch(\"D\"); \/\/create TreeD in output stream\n\n Sdi2Dig(&sdigs,pOutRich->DigLst());\n \n pOutRichLoader->TreeD()->Fill(); \/\/fill the output tree with the list of digits\n pOutRichLoader->WriteDigits(\"OVERWRITE\"); \/\/serialize them to file\n \n sdigs.Clear(); \/\/remove all tmp sdigits\n pOutRichLoader->UnloadDigits(); pOutRich->DigReset();\n}\/\/Exec()\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\nvoid AliHMPIDDigitizer::Sdi2Dig(TClonesArray *pSdiLst,TObjArray *pDigLst)\n{\n\/\/ Converts list of sdigits to 7 lists of digits, one per each chamber\n\/\/ Arguments: pSDigLst - list of all sdigits\n\/\/ pDigLst - list of 7 lists of digits \n\/\/ Returns: none \n \n TClonesArray *pLst[7]; Int_t iCnt[7];\n\n for(Int_t i=0;i<7;i++){\n pLst[i]=(TClonesArray*)(*pDigLst)[i];\n iCnt[i]=0; if(pLst[i]->GetEntries()!=0) AliErrorClass(\"Some of digits lists is not empty\"); \/\/in principle those lists should be empty \n }\n \n \/\/ make noise array\n Float_t arrNoise[7][6][80][48], arrSigmaPed[7][6][80][48];\n if(fgDoNoise) {\n for (Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++)\n for (Int_t iPc=AliHMPIDParam::kMinPc;iPc<=AliHMPIDParam::kMaxPc;iPc++)\n for(Int_t iPx=AliHMPIDParam::kMinPx;iPx<=AliHMPIDParam::kMaxPx;iPx++)\n for(Int_t iPy=AliHMPIDParam::kMinPy;iPy<=AliHMPIDParam::kMaxPy;iPy++){\n arrNoise[iCh][iPc][iPx][iPy] = gRandom->Gaus(0,1.);\n arrSigmaPed[iCh][iPc][iPx][iPy] = 1.;\n }\n \n AliCDBEntry *pDaqSigEnt = AliCDBManager::Instance()->Get(\"HMPID\/Calib\/DaqSig\"); \/\/contains TObjArray of TObjArray 14 TMatrixF sigmas values for pads \n \n if(pDaqSigEnt){\n TObjArray *pDaqSig = (TObjArray*)pDaqSigEnt->GetObject();\n for(Int_t iCh=AliHMPIDParam::kMinCh;iCh<=AliHMPIDParam::kMaxCh;iCh++){ \/\/chambers loop \n\tTMatrixF *pM = (TMatrixF*)pDaqSig->At(iCh); \n\tfor (Int_t iPc=AliHMPIDParam::kMinPc;iPc<=AliHMPIDParam::kMaxPc;iPc++)\n\t for(Int_t iPx=AliHMPIDParam::kMinPx;iPx<=AliHMPIDParam::kMaxPx;iPx++)\n\t for(Int_t iPy=AliHMPIDParam::kMinPy;iPy<=AliHMPIDParam::kMaxPy;iPy++){\n\t Int_t padX = (iPc%2)*AliHMPIDParam::kPadPcX+iPx; \n\t Int_t padY = (iPc\/2)*AliHMPIDParam::kPadPcY+iPy;\n\t if((*pM)(padX,padY)>0.){\n\t\tarrNoise[iCh][iPc][iPx][iPy] = gRandom->Gaus(0,(*pM)(padX,padY));\n\t\tarrSigmaPed[iCh][iPc][iPx][iPy] = (*pM)(padX,padY);}\n\t else{\n\t\tarrNoise[iCh][iPc][iPx][iPy] = gRandom->Gaus(0,1.);\n\t\tarrSigmaPed[iCh][iPc][iPx][iPy] = 1.;}\n\t } \n }\n }\n } \n \n pSdiLst->Sort(); \n \n Int_t iPad=-1,iCh=-1,iNdigPad=-1,aTids[3]={-1,-1,-1}; Float_t q=-1;\n for(Int_t i=0;iGetEntries();i++){ \/\/sdigits loop (sorted)\n AliHMPIDDigit *pSdig=(AliHMPIDDigit*)pSdiLst->At(i); \/\/take current sdigit\n if(pSdig->Pad()==iPad){ \/\/if the same pad \n q+=pSdig->Q(); \/\/sum up charge\n iNdigPad++; if(iNdigPad<=3) aTids[iNdigPad-1]=pSdig->GetTrack(0); \/\/collect TID \n continue;\n }\n if(i!=0 && iCh>=AliHMPIDParam::kMinCh && iCh<=AliHMPIDParam::kMaxCh){\n AliHMPIDParam::Instance()->SetThreshold((TMath::Nint(arrSigmaPed[iCh][pSdig->Pc()][pSdig->PadPcX()][pSdig->PadPcY()])*AliHMPIDParam::Nsig()));\n if(AliHMPIDParam::IsOverTh(q)) new((*pLst[iCh])[iCnt[iCh]++]) AliHMPIDDigit(iPad,(Int_t)q,aTids);} \/\/do not create digit for the very first sdigit \n \n iPad=pSdig->Pad(); iCh=AliHMPIDParam::A2C(iPad); \/\/new sdigit comes, reset collectors\n iNdigPad=1;\n aTids[0]=pSdig->GetTrack(0);aTids[1]=aTids[2]=-1; \n q=pSdig->Q();\n if(fgDoNoise) q+=arrNoise[iCh][pSdig->Pc()][pSdig->PadPcX()][pSdig->PadPcY()];\n arrNoise[iCh][pSdig->Pc()][pSdig->PadPcX()][pSdig->PadPcY()]=0;\n }\/\/sdigits loop (sorted)\n \n if(iCh>=AliHMPIDParam::kMinCh && iCh<=AliHMPIDParam::kMaxCh){\n Int_t pc = AliHMPIDParam::A2P(iPad);\n Int_t px = AliHMPIDParam::A2X(iPad); \n Int_t py = AliHMPIDParam::A2Y(iPad);\n AliHMPIDParam::Instance()->SetThreshold((TMath::Nint(arrSigmaPed[iCh][pc][px][py])*AliHMPIDParam::Nsig()));\n if(AliHMPIDParam::IsOverTh(q)) new((*pLst[iCh])[iCnt[iCh]++]) AliHMPIDDigit(iPad,(Int_t)q,aTids);\n } \/\/add the last one, in case of empty sdigits list q=-1 \n \n\/\/ add noise pad above threshold with no signal merged...if any\n if(!fgDoNoise) return;\n \n aTids[0]=aTids[1]=aTids[2]=-1;\n for (Int_t iChCurr=AliHMPIDParam::kMinCh;iChCurr<=AliHMPIDParam::kMaxCh;iChCurr++){\n for (Int_t iPc=AliHMPIDParam::kMinPc;iPc<=AliHMPIDParam::kMaxPc;iPc++)\n for(Int_t iPx=AliHMPIDParam::kMinPx;iPx<=AliHMPIDParam::kMaxPx;iPx++)\n for(Int_t iPy=AliHMPIDParam::kMinPy;iPy<=AliHMPIDParam::kMaxPy;iPy++) {\n Float_t qNoise = arrNoise[iChCurr][iPc][iPx][iPy];\n AliHMPIDParam::Instance()->SetThreshold((TMath::Nint(arrSigmaPed[iChCurr][iPc][iPx][iPy])*AliHMPIDParam::Nsig()));\n if(AliHMPIDParam::IsOverTh(qNoise)) new((*pLst[iChCurr])[iCnt[iChCurr]++]) AliHMPIDDigit(AliHMPIDParam::Abs(iChCurr,iPc,iPx,iPy),(Int_t)qNoise,aTids);\n }\n } \n}\/\/Sdi2Dig()\n\/\/++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_PRIM_SCAL_FUN_GRAD_2F1_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_GRAD_2F1_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n \/\/ Gradient of the hypergeometric function 2F1(a, b | c | z)\n \/\/ with respect to a and c\n \/**\n * Gradient of the hypergeometric function, 2F1(a1, a2, b1, z)\n * with respect to a1 and b1 only.\n *\n * The generalized hypergeometric function is a power series. This\n * implementation computes gradient by computing the power series\n * directly stopping when the series converges to within\n * precision<\/code> or takes max_steps<\/code>.\n *\n * If more than <\/code>max_steps<\/code> are taken without\n * converging, the function will throw a domain_error.\n *\n * @tparam T type of arguments and result\n * @param[out] gradA11 output argument for partial w.r.t. a1\n * @param[out] gradB1 output argument for partial w.r.t. b1\n * @param[in] a1 a1, see generalized hypergeometric function definition.\n * @param[in] a2 a2, see generalized hypergeometric function definition.\n * @param[in] b1 b1, see generalized hypergeometric function definition.\n * @param[in] z z, see generalized hypergeometric function definition.\n * @param[in] precision precision of the infinite sum. defaults to 1e-6\n * @param[in] max_steps number of steps to take. defaults to 10000\n * @throw @throws std::domain_error if not converged after max_steps\n *\n *\/\n template\n void grad_2F1(T& gradA1, T& gradB1, const T& a1, const T& a2,\n const T& b1, const T& z, T precision = 1e-6, int max_steps = 1e5) {\n using std::fabs;\n\n gradA1 = 0;\n gradB1 = 0;\n\n T gradA1old = 0;\n T gradB1old = 0;\n\n int k = 0;\n T tDak = 1.0 \/ (a1 - 1);\n\n do {\n const T r = ( (a1 + k) \/ (b1 + k) ) * ( (a2 + k) \/ (k + 1) ) * z;\n tDak = r * tDak * (a1 + (k - 1)) \/ (a1 + k);\n\n if (is_nan(r) || r == 0)\n break;\n\n gradA1old = r * gradA1old + tDak;\n gradB1old = r * gradB1old - tDak * ((a1 + k) \/ (b1 + k));\n\n gradA1 += gradA1old;\n gradB1 += gradB1old;\n\n ++k;\n if (k >= max_steps) {\n domain_error(\"grad_2F1\", \"k (internal counter)\", max_steps,\n \"exceeded \",\n \" iterations, hypergeometric function did not converge.\");\n }\n } while (fabs(tDak * (a1 + (k - 1)) ) > precision);\n }\n\n }\n}\n#endif\nFix code tag.#ifndef STAN_MATH_PRIM_SCAL_FUN_GRAD_2F1_HPP\n#define STAN_MATH_PRIM_SCAL_FUN_GRAD_2F1_HPP\n\n#include \n#include \n#include \n\nnamespace stan {\n namespace math {\n\n \/\/ Gradient of the hypergeometric function 2F1(a, b | c | z)\n \/\/ with respect to a and c\n \/**\n * Gradient of the hypergeometric function, 2F1(a1, a2, b1, z)\n * with respect to a1 and b1 only.\n *\n * The generalized hypergeometric function is a power series. This\n * implementation computes gradient by computing the power series\n * directly stopping when the series converges to within\n * precision<\/code> or takes max_steps<\/code>.\n *\n * If more than max_steps<\/code> are taken without\n * converging, the function will throw a domain_error.\n *\n * @tparam T type of arguments and result\n * @param[out] gradA11 output argument for partial w.r.t. a1\n * @param[out] gradB1 output argument for partial w.r.t. b1\n * @param[in] a1 a1, see generalized hypergeometric function definition.\n * @param[in] a2 a2, see generalized hypergeometric function definition.\n * @param[in] b1 b1, see generalized hypergeometric function definition.\n * @param[in] z z, see generalized hypergeometric function definition.\n * @param[in] precision precision of the infinite sum. defaults to 1e-6\n * @param[in] max_steps number of steps to take. defaults to 10000\n * @throw @throws std::domain_error if not converged after max_steps\n *\n *\/\n template\n void grad_2F1(T& gradA1, T& gradB1, const T& a1, const T& a2,\n const T& b1, const T& z, T precision = 1e-6, int max_steps = 1e5) {\n using std::fabs;\n\n gradA1 = 0;\n gradB1 = 0;\n\n T gradA1old = 0;\n T gradB1old = 0;\n\n int k = 0;\n T tDak = 1.0 \/ (a1 - 1);\n\n do {\n const T r = ( (a1 + k) \/ (b1 + k) ) * ( (a2 + k) \/ (k + 1) ) * z;\n tDak = r * tDak * (a1 + (k - 1)) \/ (a1 + k);\n\n if (is_nan(r) || r == 0)\n break;\n\n gradA1old = r * gradA1old + tDak;\n gradB1old = r * gradB1old - tDak * ((a1 + k) \/ (b1 + k));\n\n gradA1 += gradA1old;\n gradB1 += gradB1old;\n\n ++k;\n if (k >= max_steps) {\n domain_error(\"grad_2F1\", \"k (internal counter)\", max_steps,\n \"exceeded \",\n \" iterations, hypergeometric function did not converge.\");\n }\n } while (fabs(tDak * (a1 + (k - 1)) ) > precision);\n }\n\n }\n}\n#endif\n<|endoftext|>"} {"text":"#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP\n#define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\ntemplate \nstruct reduce_sum_impl, ReturnType, M,\n Args...> {\n template \n static T& deep_copy(T& arg) {\n return arg;\n }\n\n static var deep_copy(const var& arg) { return var(arg.val()); }\n\n static std::vector deep_copy(const std::vector& arg) {\n std::vector copy(arg.size());\n for (size_t i = 0; i < arg.size(); ++i) {\n copy[i] = arg[i].val();\n }\n return copy;\n }\n\n template \n static Eigen::Matrix deep_copy(\n const Eigen::Matrix& arg) {\n Eigen::Matrix copy(arg.size());\n for (size_t i = 0; i < arg.size(); ++i) {\n copy(i) = arg(i).val();\n }\n return copy;\n }\n\n \/\/ TODO(Steve): Move this somewhere smarter\n \/\/ Fails to compile if type T does not have member operator(Integral)\n template \n using operator_paren_access_t = decltype(std::declval()(int{}));\n\n template \n static double* accumulate_adjoints(double* dest, const var& x,\n const Pargs&... args) {\n *dest += x.adj();\n return accumulate_adjoints(dest + 1, args...);\n }\n\n \/\/ Works with anything that has operator[Integral] defined\n template ...>\n static double* accumulate_adjoints(double* dest, const Vec& x,\n const Pargs&... args) {\n for (size_t i = 0; i < x.size(); ++i) {\n dest[i] += x[i].adj();\n }\n return accumulate_adjoints(dest + x.size(), args...);\n }\n\n \/\/ Works on anything with a operator()\n template >...,\n require_t>>...>\n static double* accumulate_adjoints(double* dest, const Mat& x,\n const Pargs&... args) {\n Eigen::Map(dest, x.size()) += x.adj();\n return accumulate_adjoints(dest + x.size(), args...);\n }\n\n \/\/ Anything with a scalar type of Arithmetic gets tossed\n template >...,\n typename... Pargs>\n static double* accumulate_adjoints(double* dest, Arith&& x,\n const Pargs&... args) {\n return accumulate_adjoints(dest, args...);\n }\n\n static double* accumulate_adjoints(double* x) { return x; }\n\n struct recursive_reducer {\n size_t num_shared_terms_;\n const std::vector& vmapped_;\n std::tuple args_tuple_;\n size_t tuple_size_ = sizeof...(Args);\n\n double sum_;\n Eigen::VectorXd args_adjoints_;\n\n recursive_reducer(size_t num_shared_terms, const std::vector& vmapped,\n const Args&... args)\n : num_shared_terms_(num_shared_terms),\n vmapped_(vmapped),\n args_tuple_(args...),\n sum_(0.0),\n args_adjoints_(Eigen::VectorXd::Zero(num_shared_terms_)) {}\n\n recursive_reducer(recursive_reducer& other, tbb::split)\n : num_shared_terms_(other.num_shared_terms_),\n vmapped_(other.vmapped_),\n args_tuple_(other.args_tuple_),\n sum_(0.0),\n args_adjoints_(Eigen::VectorXd::Zero(num_shared_terms_)) {}\n\n void operator()(const tbb::blocked_range& r) {\n if (r.empty())\n return;\n\n auto start = vmapped_.begin();\n std::advance(start, r.begin());\n auto end = vmapped_.begin();\n std::advance(end, r.end());\n std::vector sub_slice(start, end);\n\n try {\n start_nested();\n\n \/\/ create a deep copy of all var's so that these are not\n \/\/ linked to any outer AD tree\n\n auto args_tuple_local_copy = apply(\n [&](auto&&... args) { return std::make_tuple(deep_copy(args)...); },\n args_tuple_);\n\n var sub_sum_v = apply(\n [&r, &sub_slice](auto&&... args) {\n return ReduceFunction()(r.begin(), r.end() - 1, sub_slice,\n args...);\n },\n args_tuple_local_copy);\n\n sub_sum_v.grad();\n\n sum_ += sub_sum_v.val();\n\n \/\/ This should accumulate the adjoints from args_tuple_local_copy into\n \/\/ the memory of args_adjoints_\n apply(\n [&](auto&&... args) {\n return accumulate_adjoints(args_adjoints_.data(), args...);\n },\n args_tuple_local_copy);\n } catch (const std::exception& e) {\n recover_memory_nested();\n throw;\n }\n recover_memory_nested();\n }\n\n void join(const recursive_reducer& rhs) {\n sum_ += rhs.sum_;\n args_adjoints_ += rhs.args_adjoints_;\n }\n };\n\n \/\/ Fails to compile if type T does not have callable member size()\n template \n using member_size_t = decltype(std::declval().size());\n\n \/\/ TODO(Steve): add requires for generic containers\n template >...,\n require_t>>..., typename... Pargs>\n size_t count_var_impl(size_t count, const Container& x,\n const Pargs&... args) const {\n return count_var_impl(count + x.size(), args...);\n }\n\n \/\/ TODO(Steve): add this back if you want it cause Ben commented it out cause\n \/\/ it was causing ambiguities\n \/*template >...,\n require_t>>...,\n typename... Pargs>\n size_t count_var_impl(size_t count, const Container& x,\n const Pargs&... args) const {\n return count_var_impl(count, args...);\n }*\/\n\n template \n size_t count_var_impl(size_t count, const var& x,\n const Pargs&... args) const {\n return count_var_impl(count + 1, args...);\n }\n\n template >...>\n size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const {\n return count_var_impl(count, args...);\n }\n\n size_t count_var_impl(size_t count) const { return count; }\n\n \/**\n * Count the number of scalars of type T in the input argument list\n *\n * @tparam Pargs Types of input arguments\n * @return Number of scalars of type T in input\n *\/\n template \n size_t count_var(const Pargs&... args) const {\n return count_var_impl(0, args...);\n }\n\n template \n void save_varis(vari** dest, const var& x, const Pargs&... args) const {\n *dest = x.vi_;\n save_varis(dest + 1, args...);\n }\n\n template ...>\n void save_varis(vari** dest, const Vec& x, const Pargs&... args) const {\n for (size_t i = 0; i < x.size(); ++i) {\n dest[i] = x[i].vi_;\n }\n save_varis(dest + x.size(), args...);\n }\n\n template >...,\n require_t>>...>\n void save_varis(vari** dest, const Mat& x, const Pargs&... args) const {\n for (size_t i = 0; i < x.size(); ++i) {\n dest[i] = x(i).vi_;\n }\n save_varis(dest + x.size(), args...);\n }\n\n template >...,\n typename... Pargs>\n void save_varis(vari** dest, const R& x, const Pargs&... args) const {\n save_varis(dest, args...);\n }\n\n void save_varis(vari**) const {}\n\n var operator()(const std::vector& vmapped, std::size_t grainsize,\n const Args&... args) const {\n const std::size_t num_jobs = vmapped.size();\n\n if (num_jobs == 0)\n return var(0.0);\n\n const std::size_t num_sliced_terms = count_var(vmapped);\n const std::size_t num_shared_terms = count_var(args...);\n\n auto vmapped_copy = deep_copy(vmapped);\n\n recursive_reducer worker(num_shared_terms, vmapped_copy, args...);\n\n#ifdef STAN_DETERMINISTIC\n tbb::static_partitioner partitioner;\n tbb::parallel_deterministic_reduce(\n tbb::blocked_range(0, num_jobs, grainsize), worker,\n partitioner);\n#else\n tbb::parallel_reduce(\n tbb::blocked_range(0, num_jobs, grainsize), worker);\n#endif\n\n vari** varis = ChainableStack::instance_->memalloc_.alloc_array(\n num_sliced_terms + num_shared_terms);\n double* partials = ChainableStack::instance_->memalloc_.alloc_array(\n num_sliced_terms + num_shared_terms);\n\n save_varis(varis, vmapped);\n save_varis(varis + num_sliced_terms, args...);\n\n for (size_t i = 0; i < num_sliced_terms; ++i)\n partials[i] = 0.0;\n accumulate_adjoints(partials, vmapped_copy);\n\n for (size_t i = 0; i < num_shared_terms; ++i) {\n partials[num_sliced_terms + i] = worker.args_adjoints_(i);\n }\n\n return var(new precomputed_gradients_vari(\n worker.sum_, num_sliced_terms + num_shared_terms, varis, partials));\n }\n};\n} \/\/ namespace internal\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\nmake things work with proper cleanup#ifndef STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP\n#define STAN_MATH_REV_SCAL_FUNCTOR_REDUCE_SUM_HPP\n\n#include \n#include \n\n#include \n#include \n#include \n\n#include \n#include \n#include \n\nnamespace stan {\nnamespace math {\nnamespace internal {\n\ntemplate \nstruct reduce_sum_impl, ReturnType, M,\n Args...> {\n template \n static T& deep_copy(T& arg) {\n return arg;\n }\n\n static var deep_copy(const var& arg) { return var(arg.val()); }\n\n static std::vector deep_copy(const std::vector& arg) {\n std::vector copy(arg.size());\n for (size_t i = 0; i < arg.size(); ++i) {\n copy[i] = arg[i].val();\n }\n return copy;\n }\n\n template \n static Eigen::Matrix deep_copy(\n const Eigen::Matrix& arg) {\n Eigen::Matrix copy(arg.size());\n for (size_t i = 0; i < arg.size(); ++i) {\n copy(i) = arg(i).val();\n }\n return copy;\n }\n\n \/\/ TODO(Steve): Move this somewhere smarter\n \/\/ Fails to compile if type T does not have member operator(Integral)\n template \n using operator_paren_access_t = decltype(std::declval()(int{}));\n\n template \n static double* accumulate_adjoints(double* dest, const var& x,\n const Pargs&... args) {\n *dest += x.adj();\n return accumulate_adjoints(dest + 1, args...);\n }\n\n \/\/ Works with anything that has operator[Integral] defined\n template ...>\n static double* accumulate_adjoints(double* dest, const Vec& x,\n const Pargs&... args) {\n for (size_t i = 0; i < x.size(); ++i) {\n dest[i] += x[i].adj();\n }\n return accumulate_adjoints(dest + x.size(), args...);\n }\n\n \/\/ Works on anything with a operator()\n template >...,\n require_t>>...>\n static double* accumulate_adjoints(double* dest, const Mat& x,\n const Pargs&... args) {\n Eigen::Map(dest, x.size()) += x.adj();\n return accumulate_adjoints(dest + x.size(), args...);\n }\n\n \/\/ Anything with a scalar type of Arithmetic gets tossed\n template >...,\n typename... Pargs>\n static double* accumulate_adjoints(double* dest, Arith&& x,\n const Pargs&... args) {\n return accumulate_adjoints(dest, args...);\n }\n\n static double* accumulate_adjoints(double* x) { return x; }\n\n struct recursive_reducer {\n size_t num_shared_terms_;\n const std::vector& vmapped_;\n std::tuple args_tuple_;\n size_t tuple_size_ = sizeof...(Args);\n\n double sum_;\n Eigen::VectorXd args_adjoints_;\n\n recursive_reducer(size_t num_shared_terms, const std::vector& vmapped,\n const Args&... args)\n : num_shared_terms_(num_shared_terms),\n vmapped_(vmapped),\n args_tuple_(args...),\n sum_(0.0),\n args_adjoints_(Eigen::VectorXd::Zero(num_shared_terms_)) {}\n\n recursive_reducer(recursive_reducer& other, tbb::split)\n : num_shared_terms_(other.num_shared_terms_),\n vmapped_(other.vmapped_),\n args_tuple_(other.args_tuple_),\n sum_(0.0),\n args_adjoints_(Eigen::VectorXd::Zero(num_shared_terms_)) {}\n\n void operator()(const tbb::blocked_range& r) {\n if (r.empty())\n return;\n\n auto start = vmapped_.begin();\n std::advance(start, r.begin());\n auto end = vmapped_.begin();\n std::advance(end, r.end());\n\n try {\n start_nested();\n\n \/\/ create a deep copy of all var's so that these are not\n \/\/ linked to any outer AD tree\n const std::vector sub_slice(start, end);\n\n auto args_tuple_local_copy = apply(\n [&](auto&&... args) { return std::make_tuple(deep_copy(args)...); },\n args_tuple_);\n\n var sub_sum_v = apply(\n [&r, &sub_slice](auto&&... args) {\n return ReduceFunction()(r.begin(), r.end() - 1, sub_slice,\n args...);\n },\n args_tuple_local_copy);\n\n sub_sum_v.grad();\n\n sum_ += sub_sum_v.val();\n\n \/\/ This should accumulate the adjoints from args_tuple_local_copy into\n \/\/ the memory of args_adjoints_\n apply(\n [&](auto&&... args) {\n return accumulate_adjoints(args_adjoints_.data(), args...);\n },\n args_tuple_local_copy);\n } catch (const std::exception& e) {\n recover_memory_nested();\n throw;\n }\n recover_memory_nested();\n }\n\n void join(const recursive_reducer& rhs) {\n sum_ += rhs.sum_;\n args_adjoints_ += rhs.args_adjoints_;\n }\n };\n\n \/\/ Fails to compile if type T does not have callable member size()\n template \n using member_size_t = decltype(std::declval().size());\n\n \/\/ TODO(Steve): add requires for generic containers\n template >...,\n require_t>>..., typename... Pargs>\n size_t count_var_impl(size_t count, const Container& x,\n const Pargs&... args) const {\n return count_var_impl(count + x.size(), args...);\n }\n\n \/\/ TODO(Steve): add this back if you want it cause Ben commented it out cause\n \/\/ it was causing ambiguities\n \/*template >...,\n require_t>>...,\n typename... Pargs>\n size_t count_var_impl(size_t count, const Container& x,\n const Pargs&... args) const {\n return count_var_impl(count, args...);\n }*\/\n\n template \n size_t count_var_impl(size_t count, const var& x,\n const Pargs&... args) const {\n return count_var_impl(count + 1, args...);\n }\n\n template >...>\n size_t count_var_impl(size_t count, Arith& x, const Pargs&... args) const {\n return count_var_impl(count, args...);\n }\n\n size_t count_var_impl(size_t count) const { return count; }\n\n \/**\n * Count the number of scalars of type T in the input argument list\n *\n * @tparam Pargs Types of input arguments\n * @return Number of scalars of type T in input\n *\/\n template \n size_t count_var(const Pargs&... args) const {\n return count_var_impl(0, args...);\n }\n\n template \n void save_varis(vari** dest, const var& x, const Pargs&... args) const {\n *dest = x.vi_;\n save_varis(dest + 1, args...);\n }\n\n template ...>\n void save_varis(vari** dest, const Vec& x, const Pargs&... args) const {\n for (size_t i = 0; i < x.size(); ++i) {\n dest[i] = x[i].vi_;\n }\n save_varis(dest + x.size(), args...);\n }\n\n template >...,\n require_t>>...>\n void save_varis(vari** dest, const Mat& x, const Pargs&... args) const {\n for (size_t i = 0; i < x.size(); ++i) {\n dest[i] = x(i).vi_;\n }\n save_varis(dest + x.size(), args...);\n }\n\n template >...,\n typename... Pargs>\n void save_varis(vari** dest, const R& x, const Pargs&... args) const {\n save_varis(dest, args...);\n }\n\n void save_varis(vari**) const {}\n\n var operator()(const std::vector& vmapped, std::size_t grainsize,\n const Args&... args) const {\n const std::size_t num_jobs = vmapped.size();\n\n if (num_jobs == 0)\n return var(0.0);\n\n const std::size_t num_sliced_terms = count_var(vmapped);\n const std::size_t num_shared_terms = count_var(args...);\n\n vari** varis = ChainableStack::instance_->memalloc_.alloc_array(\n num_sliced_terms + num_shared_terms);\n double* partials = ChainableStack::instance_->memalloc_.alloc_array(\n num_sliced_terms + num_shared_terms);\n\n double sum = 0;\n\n try {\n start_nested();\n\n auto vmapped_copy = deep_copy(vmapped);\n\n recursive_reducer worker(num_shared_terms, vmapped_copy, args...);\n\n#ifdef STAN_DETERMINISTIC\n tbb::static_partitioner partitioner;\n tbb::parallel_deterministic_reduce(\n tbb::blocked_range(0, num_jobs, grainsize), worker,\n partitioner);\n#else\n tbb::parallel_reduce(\n tbb::blocked_range(0, num_jobs, grainsize), worker);\n#endif\n\n save_varis(varis, vmapped);\n save_varis(varis + num_sliced_terms, args...);\n\n for (size_t i = 0; i < num_sliced_terms; ++i)\n partials[i] = 0.0;\n accumulate_adjoints(partials, vmapped_copy);\n\n for (size_t i = 0; i < num_shared_terms; ++i) {\n partials[num_sliced_terms + i] = worker.args_adjoints_(i);\n }\n\n sum = worker.sum_;\n\n } catch (const std::exception& e) {\n recover_memory_nested();\n throw;\n }\n recover_memory_nested();\n\n return var(new precomputed_gradients_vari(\n sum, num_sliced_terms + num_shared_terms, varis, partials));\n }\n};\n} \/\/ namespace internal\n\n} \/\/ namespace math\n} \/\/ namespace stan\n\n#endif\n<|endoftext|>"} {"text":"\/**\n * @file\n *\n * @brief Tests for leaf plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\n *\/\n\n#include \"leaf.hpp\"\n\n#include \n#include \n\n#include \n\nusing ckdb::keyNew;\n\nusing CppKeySet = kdb::KeySet;\nusing CppKey = kdb::Key;\n\n\/\/ -- Macros -------------------------------------------------------------------------------------------------------------------------------\n\n#define OPEN_PLUGIN(parentName, filepath) \\\n\tCppKeySet modules{ 0, KS_END }; \\\n\tCppKeySet config{ 0, KS_END }; \\\n\telektraModulesInit (modules.getKeySet (), 0); \\\n\tCppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \\\n\tPlugin * plugin = elektraPluginOpen (\"leaf\", modules.getKeySet (), config.getKeySet (), *parent); \\\n\texit_if_fail (plugin != NULL, \"Could not open leaf plugin\");\n\n#define CLOSE_PLUGIN() \\\n\tksDel (modules.release ()); \\\n\tconfig.release (); \\\n\telektraPluginClose (plugin, 0); \\\n\telektraModulesClose (modules.getKeySet (), 0)\n\n#define PREFIX \"user\/tests\/leaf\/\"\n\n\/\/ -- Functions ----------------------------------------------------------------------------------------------------------------------------\n\nvoid test_set (CppKeySet keys, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n{\n\tOPEN_PLUGIN (PREFIX, \"file\/path\"); \/\/! OCLint (too few branches switch, empty if statement)\n\n\tsucceed_if_same (plugin->kdbSet (plugin, keys.getKeySet (), *parent), \/\/! OCLint (too few branches switch, empty if statement)\n\t\t\t status, \"Call of `kdbSet` failed\");\n\n\tcompare_keyset (keys, expected); \/\/! OCLint (too few branches switch)\n\n\tCLOSE_PLUGIN ();\n}\n\nvoid test_get (CppKeySet keys, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n{\n\tOPEN_PLUGIN (PREFIX, \"file\/path\"); \/\/! OCLint (too few branches switch, empty if statement)\n\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), \/\/! OCLint (too few branches switch, empty if statement)\n\t\t\t status, \"Call of `kdbGet` failed\");\n\n\tcompare_keyset (keys, expected); \/\/! OCLint (too few branches switch)\n\n\tCLOSE_PLUGIN ();\n}\n\n\/\/ -- Tests --------------------------------------------------------------------------------------------------------------------------------\n\nTEST (leaf, basics)\n{\n\tOPEN_PLUGIN (\"system\/elektra\/modules\/leaf\", \"\")\n\n\tCppKeySet keys{ 0, KS_END };\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,\n\t\t\t \"Unable to retrieve plugin contract\");\n\n\tCLOSE_PLUGIN ();\n}\n\nTEST (leaf, get)\n{\n\ttest_get (\n#include \"leaf\/simple_set.hpp\"\n\t\t,\n#include \"leaf\/simple_get.hpp\"\n\t);\n}\n\nTEST (leaf, set)\n{\n\ttest_set (\n#include \"leaf\/empty.hpp\"\n\t\t,\n#include \"leaf\/empty.hpp\"\n\t\t, ELEKTRA_PLUGIN_STATUS_NO_UPDATE);\n\n\ttest_set (\n#include \"leaf\/simple_get.hpp\"\n\t\t,\n#include \"leaf\/simple_set.hpp\"\n\t);\n}\nLeaf: Add roundtrip test\/**\n * @file\n *\n * @brief Tests for leaf plugin\n *\n * @copyright BSD License (see LICENSE.md or https:\/\/www.libelektra.org)\n *\n *\/\n\n#include \"leaf.hpp\"\n\n#include \n#include \n\n#include \n\nusing ckdb::keyNew;\n\nusing CppKeySet = kdb::KeySet;\nusing CppKey = kdb::Key;\n\n\/\/ -- Macros -------------------------------------------------------------------------------------------------------------------------------\n\n#define OPEN_PLUGIN(parentName, filepath) \\\n\tCppKeySet modules{ 0, KS_END }; \\\n\tCppKeySet config{ 0, KS_END }; \\\n\telektraModulesInit (modules.getKeySet (), 0); \\\n\tCppKey parent{ parentName, KEY_VALUE, filepath, KEY_END }; \\\n\tPlugin * plugin = elektraPluginOpen (\"leaf\", modules.getKeySet (), config.getKeySet (), *parent); \\\n\texit_if_fail (plugin != NULL, \"Could not open leaf plugin\");\n\n#define CLOSE_PLUGIN() \\\n\tksDel (modules.release ()); \\\n\tconfig.release (); \\\n\telektraPluginClose (plugin, 0); \\\n\telektraModulesClose (modules.getKeySet (), 0)\n\n#define PREFIX \"user\/tests\/leaf\/\"\n\n\/\/ -- Functions ----------------------------------------------------------------------------------------------------------------------------\n\nvoid test_set (CppKeySet keys, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n{\n\tOPEN_PLUGIN (PREFIX, \"file\/path\"); \/\/! OCLint (too few branches switch, empty if statement)\n\n\tsucceed_if_same (plugin->kdbSet (plugin, keys.getKeySet (), *parent), \/\/! OCLint (too few branches switch, empty if statement)\n\t\t\t status, \"Call of `kdbSet` failed\");\n\n\tcompare_keyset (keys, expected); \/\/! OCLint (too few branches switch)\n\n\tCLOSE_PLUGIN ();\n}\n\nvoid test_get (CppKeySet keys, CppKeySet expected, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n{\n\tOPEN_PLUGIN (PREFIX, \"file\/path\"); \/\/! OCLint (too few branches switch, empty if statement)\n\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), \/\/! OCLint (too few branches switch, empty if statement)\n\t\t\t status, \"Call of `kdbGet` failed\");\n\n\tcompare_keyset (keys, expected); \/\/! OCLint (too few branches switch)\n\n\tCLOSE_PLUGIN ();\n}\n\nvoid test_roundtrip (CppKeySet keys, int const status = ELEKTRA_PLUGIN_STATUS_SUCCESS)\n#ifdef __llvm__\n\t__attribute__ ((annotate (\"oclint:suppress[high ncss method]\")))\n#endif\n{\n\tCppKeySet input = keys.dup ();\n\n\tOPEN_PLUGIN (PREFIX, \"file\/path\"); \/\/! OCLint (too few branches switch, empty if statement)\n\n\tsucceed_if_same (plugin->kdbSet (plugin, keys.getKeySet (), *parent), \/\/! OCLint (too few branches switch, empty if statement)\n\t\t\t status, \"Call of `kdbSet` failed\");\n\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), \/\/! OCLint (too few branches switch, empty if statement)\n\t\t\t status, \"Call of `kdbGet` failed\");\n\n\tcompare_keyset (input, keys); \/\/! OCLint (too few branches switch)\n\n\tCLOSE_PLUGIN ();\n}\n\n\/\/ -- Tests --------------------------------------------------------------------------------------------------------------------------------\n\nTEST (leaf, basics)\n{\n\tOPEN_PLUGIN (\"system\/elektra\/modules\/leaf\", \"\")\n\n\tCppKeySet keys{ 0, KS_END };\n\tsucceed_if_same (plugin->kdbGet (plugin, keys.getKeySet (), *parent), ELEKTRA_PLUGIN_STATUS_SUCCESS,\n\t\t\t \"Unable to retrieve plugin contract\");\n\n\tCLOSE_PLUGIN ();\n}\n\nTEST (leaf, get)\n{\n\ttest_get (\n#include \"leaf\/simple_set.hpp\"\n\t\t,\n#include \"leaf\/simple_get.hpp\"\n\t);\n}\n\nTEST (leaf, set)\n{\n\ttest_set (\n#include \"leaf\/empty.hpp\"\n\t\t,\n#include \"leaf\/empty.hpp\"\n\t\t, ELEKTRA_PLUGIN_STATUS_NO_UPDATE);\n\n\ttest_set (\n#include \"leaf\/simple_get.hpp\"\n\t\t,\n#include \"leaf\/simple_set.hpp\"\n\t);\n}\n\nTEST (leaf, roundtrip)\n{\n\ttest_roundtrip (\n#include \"leaf\/simple_get.hpp\"\n\t);\n}\n<|endoftext|>"} {"text":"#include \"Dial.h\"\n\/\/Constructor\nDial::Dial(){\n\tif(buf = (char *)malloc(BUF_SIZE+1)) memset(buf,0,BUF_SIZE+1); \/\/Had to add one more, to avoid some bug\n}\n\nDial::Dial(unsigned int radius, unsigned int minLimit, unsigned int setpoint, unsigned int maxLimit)\n{\t\n\tif(buf = (char *)malloc(BUF_SIZE+1)) memset(buf,0,BUF_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tthis->setSize(radius);\n\tthis->setLimits(minLimit,setpoint,maxLimit);\n\tthis->setColors(BLACK,BLUE,WHITE);\n\tinit();\n}\n\nDial::~Dial(){}\n\n\/\/Methods\nvoid Dial::init(){\n\tIndicator::init();\n\ttype = 0x21;\n\tthis->hiLimit = scaleMax;\n\tthis->lowLimit = scaleMin;\n\tthis->currentValue = setpoint;\n\tthis->maxDegree = 315;\n\tthis->minDegree = 585;\n\tthis->tickSize = 10;\n\tthis->gap = 5;\n\tthis->tickDegree = 45;\n\tthis->showVal = true;\n\tthis->showTicks = true;\n}\n\nvoid Dial::clear(){\n\tfor(int i = BUF_SIZE-1; i >= 0; i--)\n\t{\n\t\t\tbuf[i] = 0;\n\t}\n}\n\nvoid Dial::setSize(int radius){\n\tthis->w = radius*2;\n\tthis->h = radius*2;\n\tthis->radius = radius;\n}\n\nvoid Dial::drawBorder(){\n\tint color = this->fgColor;\n\t\/*\n\tif(currentValue >= hiLimit) color = hiLimitColor;\n\tif(currentValue <= lowLimit) color = lowLimitColor;\n\n\t\/*\n\tfor(int i=0; i < this->borderWidth; i++)\n\t{\n \tmyCanvas->tft->drawCircle(x,y,radius-i,color);\n }\n\t*\/\n\tmyCanvas->tft->fillCircle(x,y,radius,color);\n\t\/\/myCanvas->tft->fillCircle(x,y,radius-borderWidth,bgColor);\n\t\/\/drawFace();\n}\n\nvoid Dial::drawFace(){\n\t\/\/ Draw face\n\tmyCanvas->tft->fillCircle(x,y,radius - this->borderWidth,this->bgColor);\n\t\n\t\/\/ Draw border \n\t\/\/drawBorder();\n\n\tint X1,Y1,X2,Y2;\n\t \n \/\/ Draw ticks\n\tif(showTicks){\n\t\tfor(int i=maxDegree; i<=minDegree; i+=tickDegree)\n\t\t{\n\t\t\tX1 = getX(x,i,radius-tickSize);\n\t\t\tY1 = getY(y,i,radius-tickSize);\n\t\t\tX2 = getX(x,i,radius-borderWidth);\n\t\t\tY2 = getY(y,i,radius-borderWidth); \n\t\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,borderColor);\n\t\t}\n\t}else{\n\t\tint i = minDegree;\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,borderColor);\n\t\t\n\t\ti = maxDegree;\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,borderColor);\t\n\t}\n\t\n\t\/\/ Draw Setpoint line\n\tif(setpoint){\n\t\tint i = map(setpoint,scaleMin,scaleMax,minDegree,maxDegree);\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,setpointColor);\n\t} \n\t\n\t\/\/ Draw High limit line\n\tif(hiLimit < scaleMax){\n\t\tint i = map(hiLimit,scaleMin,scaleMax,minDegree,maxDegree);\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,hiLimitColor);\n\t} \t\n\t\n\t\/\/ Draw Low Limit line\n\tif(lowLimit > scaleMin){\n\t\tint i = map(lowLimit,scaleMin,scaleMax,minDegree,maxDegree);\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,lowLimitColor);\n\t} \t \n\t\n\t\/\/ Draw min value\n\tsetNum(scaleMin);\n\tmyCanvas->tft->drawString(buf,x-radius+FONT_SPACE,y+radius-FONT_Y,1,borderColor);\n\n\t\/\/ Draw max value\n\tsetNum(scaleMax);\n\tmyCanvas->tft->drawString(buf,getX(x,maxDegree,radius-tickSize),y+radius-FONT_Y,1,borderColor);\n\n}\n\nvoid Dial::drawNeedle(int cX, int cY, int degree, int radius, int color){\n\tdegree = map(constrain(degree,scaleMin,scaleMax),scaleMin,scaleMax,585,315);\n\n\tint pX1,pY1,pX2,pY2,pX3,pY3;\n\n\tpX1 = getX(cX,degree-90,4);\n\tpY1 = getY(cY,degree-90,4);\n\tpX2 = getX(cX,degree+90,4);\n\tpY2 = getY(cY,degree+90,4);\n\tpX3 = getX(cX,degree,radius);\n\tpY3 = getY(cY,degree,radius);\n\n\tmyCanvas->tft->fillTriangle(pX1,pY1,pX2,pY2,pX3,pY3,color);\n\tmyCanvas->tft->fillCircle(cX,cY,4,color);\n\t\/*\n\t\/\/ Outer triangle\n\tmyCanvas->tft->drawLine(pX1,pY1,pX2,pY2,color);\n\tmyCanvas->tft->drawLine(pX1,pY1,pX3,pY3,color);\n\tmyCanvas->tft->drawLine(pX2,pY2,pX3,pY3,color);\n\n\tpX1 = getX(cX,degree-90,2);\n\tpY1 = getY(cY,degree-90,2);\n\tpX2 = getX(cX,degree+90,2);\n\tpY2 = getY(cY,degree+90,2);\n\n\t\/\/ Inner Triangle\n\tmyCanvas->tft->drawLine(pX1,pY1,pX2,pY2,color);\n\tmyCanvas->tft->drawLine(pX1,pY1,pX3,pY3,color);\n\tmyCanvas->tft->drawLine(pX2,pY2,pX3,pY3,color); \n\n\t\/\/ Center Line\n\tmyCanvas->tft->drawLine(cX,cY,pX3,pY3,color);\n\t*\/\n}\n\nvoid Dial::drawNeedleAndValue(){\n\tint color = fgColor;\n\t\n\t\/\/ Draw needle\n\tdrawNeedle(x,y,previousValue,radius-tickSize-gap,bgColor);\n\tif(currentValue >= hiLimit) color = hiLimitColor;\n\tif(currentValue <= lowLimit) color = lowLimitColor;\n\tdrawNeedle(x,y,currentValue,radius-tickSize-gap,color);\n\t\n\tif(showVal){\n\t\t\/\/ Draw current value\n\t\tint dSpace;\n\t\tint fontSize = 2;\n\t\tif(currentValue<10) dSpace = 3 * fontSize;\n\t\tif(currentValue>=10) dSpace = 6 * fontSize;\n\t\tif(currentValue>99) dSpace = 9 * fontSize;\n\t\tmyCanvas->tft->fillRect(x-9*fontSize,y+radius-12*fontSize,18*fontSize,8*fontSize,bgColor);\n\t\tmyCanvas->tft->drawNumber(currentValue,x-dSpace,y+radius-12*fontSize,fontSize,color);\n\t}\t\n}\n\nint Dial::getX(int cX,int deg, int radius){\n\treturn (cX + radius * cos(deg*PI\/180));\n}\n\nint Dial::getY(int cY, int deg, int radius){\n\treturn (cY - radius * sin(deg*PI\/180));\n}\n\n\n\/\/Overriden virtual methods\nvoid Dial::show(){\n\t\/\/ Draw face\n\tdrawBorder();\n\tdrawFace();\n\tdrawNeedleAndValue();\n\t\/\/update();\n}\n\nvoid Dial::update(){\n\tif(!visible) return;\n\t\n\tif(!forcedUpdate){\t\n\t\tif(previousValue == currentValue) return;\n\t}\n\t\n\t\/\/ Limit crossing forces border to redraw\n\t\/*\n\tif(previousValue < hiLimit && previousValue > lowLimit){\n\t\tif(currentValue >= hiLimit || currentValue <= lowLimit) drawBorder();\n\t}\n\tif(previousValue >= hiLimit){\n\t\tif(currentValue < hiLimit) drawBorder();\n\t}\n\tif(previousValue <= lowLimit){\n\t\tif(currentValue > lowLimit) drawBorder();\n\t}\n\t*\/\n\tdrawNeedleAndValue();\n}\nUpdate Dial#include \"Dial.h\"\n\/\/Constructor\nDial::Dial(){\n\tif(buf = (char *)malloc(BUF_SIZE+1)) memset(buf,0,BUF_SIZE+1); \/\/Had to add one more, to avoid some bug\n}\n\nDial::Dial(unsigned int radius, unsigned int minLimit, unsigned int setpoint, unsigned int maxLimit)\n{\t\n\tif(buf = (char *)malloc(BUF_SIZE+1)) memset(buf,0,BUF_SIZE+1); \/\/Had to add one more, to avoid some bug\n\tthis->setSize(radius);\n\tthis->setLimits(minLimit,setpoint,maxLimit);\n\tthis->setColors(BLACK,BLUE,WHITE);\n\tinit();\n}\n\nDial::~Dial(){}\n\n\/\/Methods\nvoid Dial::init(){\n\tIndicator::init();\n\ttype = 0x21;\n\tthis->hiLimit = scaleMax;\n\tthis->lowLimit = scaleMin;\n\tthis->currentValue = scaleMin;\n\tthis->maxDegree = 315;\n\tthis->minDegree = 585;\n\tthis->tickSize = 10;\n\tthis->gap = 5;\n\tthis->tickDegree = 45;\n\tthis->showVal = true;\n\tthis->showTicks = true;\n}\n\nvoid Dial::clear(){\n\tfor(int i = BUF_SIZE-1; i >= 0; i--)\n\t{\n\t\t\tbuf[i] = 0;\n\t}\n}\n\nvoid Dial::setSize(int radius){\n\tthis->w = radius*2;\n\tthis->h = radius*2;\n\tthis->radius = radius;\n}\n\nvoid Dial::drawBorder(){\n\tint color = this->fgColor;\n\t\/*\n\tif(currentValue >= hiLimit) color = hiLimitColor;\n\tif(currentValue <= lowLimit) color = lowLimitColor;\n\n\t\/*\n\tfor(int i=0; i < this->borderWidth; i++)\n\t{\n \tmyCanvas->tft->drawCircle(x,y,radius-i,color);\n }\n\t*\/\n\tmyCanvas->tft->fillCircle(x,y,radius,color);\n\t\/\/myCanvas->tft->fillCircle(x,y,radius-borderWidth,bgColor);\n\t\/\/drawFace();\n}\n\nvoid Dial::drawFace(){\n\t\/\/ Draw face\n\tmyCanvas->tft->fillCircle(x,y,radius - this->borderWidth,this->bgColor);\n\t\n\t\/\/ Draw border \n\t\/\/drawBorder();\n\n\tint X1,Y1,X2,Y2;\n\t \n \/\/ Draw ticks\n\tif(showTicks){\n\t\tfor(int i=maxDegree; i<=minDegree; i+=tickDegree)\n\t\t{\n\t\t\tX1 = getX(x,i,radius-tickSize);\n\t\t\tY1 = getY(y,i,radius-tickSize);\n\t\t\tX2 = getX(x,i,radius-borderWidth);\n\t\t\tY2 = getY(y,i,radius-borderWidth); \n\t\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,borderColor);\n\t\t}\n\t}else{\n\t\tint i = minDegree;\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,borderColor);\n\t\t\n\t\ti = maxDegree;\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,borderColor);\t\n\t}\n\t\n\t\/\/ Draw Setpoint line\n\tif(setpoint){\n\t\tint i = map(setpoint,scaleMin,scaleMax,minDegree,maxDegree);\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,setpointColor);\n\t} \n\t\n\t\/\/ Draw High limit line\n\tif(hiLimit < scaleMax){\n\t\tint i = map(hiLimit,scaleMin,scaleMax,minDegree,maxDegree);\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,hiLimitColor);\n\t} \t\n\t\n\t\/\/ Draw Low Limit line\n\tif(lowLimit > scaleMin){\n\t\tint i = map(lowLimit,scaleMin,scaleMax,minDegree,maxDegree);\n\t\tX1 = getX(x,i,radius-tickSize);\n\t\tY1 = getY(y,i,radius-tickSize);\n\t\tX2 = getX(x,i,radius-borderWidth);\n\t\tY2 = getY(y,i,radius-borderWidth); \n\t\tmyCanvas->tft->drawLine(X1,Y1,X2,Y2,lowLimitColor);\n\t} \t \n\t\n\t\/\/ Draw min value\n\tsetNum(scaleMin);\n\tmyCanvas->tft->drawString(buf,x-radius+FONT_SPACE,y+radius-FONT_Y,1,borderColor);\n\n\t\/\/ Draw max value\n\tsetNum(scaleMax);\n\tmyCanvas->tft->drawString(buf,getX(x,maxDegree,radius-tickSize),y+radius-FONT_Y,1,borderColor);\n\n}\n\nvoid Dial::drawNeedle(int cX, int cY, int degree, int radius, int color){\n\tdegree = map(constrain(degree,scaleMin,scaleMax),scaleMin,scaleMax,585,315);\n\n\tint pX1,pY1,pX2,pY2,pX3,pY3;\n\n\tpX1 = getX(cX,degree-90,4);\n\tpY1 = getY(cY,degree-90,4);\n\tpX2 = getX(cX,degree+90,4);\n\tpY2 = getY(cY,degree+90,4);\n\tpX3 = getX(cX,degree,radius);\n\tpY3 = getY(cY,degree,radius);\n\n\tmyCanvas->tft->fillTriangle(pX1,pY1,pX2,pY2,pX3,pY3,color);\n\tmyCanvas->tft->fillCircle(cX,cY,4,color);\n\t\/*\n\t\/\/ Outer triangle\n\tmyCanvas->tft->drawLine(pX1,pY1,pX2,pY2,color);\n\tmyCanvas->tft->drawLine(pX1,pY1,pX3,pY3,color);\n\tmyCanvas->tft->drawLine(pX2,pY2,pX3,pY3,color);\n\n\tpX1 = getX(cX,degree-90,2);\n\tpY1 = getY(cY,degree-90,2);\n\tpX2 = getX(cX,degree+90,2);\n\tpY2 = getY(cY,degree+90,2);\n\n\t\/\/ Inner Triangle\n\tmyCanvas->tft->drawLine(pX1,pY1,pX2,pY2,color);\n\tmyCanvas->tft->drawLine(pX1,pY1,pX3,pY3,color);\n\tmyCanvas->tft->drawLine(pX2,pY2,pX3,pY3,color); \n\n\t\/\/ Center Line\n\tmyCanvas->tft->drawLine(cX,cY,pX3,pY3,color);\n\t*\/\n}\n\nvoid Dial::drawNeedleAndValue(){\n\tint color = fgColor;\n\t\n\t\/\/ Draw needle\n\tdrawNeedle(x,y,previousValue,radius-tickSize-gap,bgColor);\n\tif(currentValue >= hiLimit) color = hiLimitColor;\n\tif(currentValue <= lowLimit) color = lowLimitColor;\n\tdrawNeedle(x,y,currentValue,radius-tickSize-gap,color);\n\t\n\tif(showVal){\n\t\t\/\/ Draw current value\n\t\tint dSpace;\n\t\tint fontSize = 2;\n\t\tif(currentValue<10) dSpace = 3 * fontSize;\n\t\tif(currentValue>=10) dSpace = 6 * fontSize;\n\t\tif(currentValue>99) dSpace = 9 * fontSize;\n\t\tif(currentValue>999) dSpace = 12 * fontSize;\n\t\tmyCanvas->tft->fillRect(x-12*fontSize,y+radius-12*fontSize,24*fontSize,8*fontSize,bgColor);\n\t\tmyCanvas->tft->drawNumber(currentValue,x-dSpace,y+radius-12*fontSize,fontSize,color);\n\t}\t\n}\n\nint Dial::getX(int cX,int deg, int radius){\n\treturn (cX + radius * cos(deg*PI\/180));\n}\n\nint Dial::getY(int cY, int deg, int radius){\n\treturn (cY - radius * sin(deg*PI\/180));\n}\n\n\n\/\/Overriden virtual methods\nvoid Dial::show(){\n\t\/\/ Draw face\n\tdrawBorder();\n\tdrawFace();\n\tdrawNeedleAndValue();\n\t\/\/update();\n}\n\nvoid Dial::update(){\n\tif(!visible) return;\n\t\n\tif(!forcedUpdate){\t\n\t\tif(previousValue == currentValue) return;\n\t}\n\t\n\t\/\/ Limit crossing forces border to redraw\n\t\/*\n\tif(previousValue < hiLimit && previousValue > lowLimit){\n\t\tif(currentValue >= hiLimit || currentValue <= lowLimit) drawBorder();\n\t}\n\tif(previousValue >= hiLimit){\n\t\tif(currentValue < hiLimit) drawBorder();\n\t}\n\tif(previousValue <= lowLimit){\n\t\tif(currentValue > lowLimit) drawBorder();\n\t}\n\t*\/\n\tdrawNeedleAndValue();\n}\n<|endoftext|>"} {"text":"[generator] Fix build on OS X<|endoftext|>"} {"text":"#include \"Game.h\"\n\nGame::Game()\n{\n \/\/Set default variables\n width = 800;\n height = 600;\n vsync = false;\n fullscreen = false;\n fog = true;\n mazeSize = 40;\n \n \/\/Try to load configuration\n loadConfig();\n \n \/\/If user set wrong size, correct it\n if(mazeSize > MAZE_MAXSIZE)\n mazeSize = MAZE_MAXSIZE;\n \n if(mazeSize < MAZE_MINSIZE)\n mazeSize = MAZE_MINSIZE;\n}\n\nvoid Game::loadConfig()\n{\n vector options;\n std::string option, value;\n bool isOption = true;\n \n ifstream fin(\"config.cfg\");\n \n if(!fin.is_open())\n {\n cout << \"Failed to load config file. Setting default variables.\" << endl;\n return;\n }\n \n while(!fin.eof())\n {\n std::string tmp;\n fin >> tmp;\n options.push_back(tmp);\n }\n \n fin.close();\n \n for(unsigned int i = 0; i < options.size(); i++)\n {\n for(unsigned int j = 0; j < options[i].size(); j++)\n {\n \/\/'=' catched, so now we picking value, not option\n if(options[i][j] == '=')\n {\n isOption = false;\n continue;\n }\n \n if(isOption)\n option += options[i][j];\n \n if(!isOption)\n value += options[i][j];\n }\n \n \/\/Save game options\n if(option.compare(\"width\") == 0)\n width = atoi(value.c_str());\n \n if(option.compare(\"height\") == 0)\n height = atoi(value.c_str());\n \n if(option.compare(\"mazeSize\") == 0)\n mazeSize = atoi(value.c_str());\n \n if(option.compare(\"vsync\") == 0)\n {\n if(value.compare(\"true\") == 0)\n vsync = true;\n else if (value.compare(\"false\") == 0)\n vsync = false;\n }\n \n if(option.compare(\"fullscreen\") == 0)\n {\n if(value.compare(\"true\") == 0)\n fullscreen = true;\n else if (value.compare(\"false\") == 0)\n fullscreen = false;\n }\n \n if(option.compare(\"fog\") == 0)\n {\n if(value.compare(\"true\") == 0)\n fog = true;\n else if (value.compare(\"false\") == 0)\n fog = false;\n }\n \n \/\/Clear variables to use it in next loop step\n option=\"\";\n value=\"\";\n isOption = true;\n }\n}\n\nvoid Game::startGame()\n{\n \/\/Create Irrlicht device and get pointer to driver and scene manager\n device = createDevice(EDT_OPENGL, dimension2d(width, height), 32, fullscreen, false, vsync, 0);\n \n srand(time(0));\n \n driver = device->getVideoDriver();\n scenemgr = device->getSceneManager();\n \n device->setWindowCaption(L\"3D Maze\");\n \n \/\/Create map\n Map map(mazeSize);\n map.createMap(driver, scenemgr);\n \n IMeshSceneNode *mapNode = scenemgr->addMeshSceneNode(map.getMapMesh());\n mapNode->setMaterialFlag(EMF_LIGHTING, true);\n mapNode->getMaterial(0).FogEnable = false;\n \n ICameraSceneNode *camera = scenemgr->addCameraSceneNodeFPS();\n camera->setTarget(vector3df(90,4,45));\n camera->setFarValue(1000);\n device->getCursorControl()->setVisible(false);\n \n scenemgr->setAmbientLight(SColorf(1, 1, 1, 255));\n \n \/\/Main loop\n while(device->run())\n {\n if(device->isWindowActive())\n {\n driver->beginScene(true, true, SColor(255,0,0,0));\n \n scenemgr->drawAll();\n \n driver->endScene();\n }\n else\n device->yield();\n }\n \n device->drop();\n}\n\n\nShow debug messages#include \"Game.h\"\n\nGame::Game()\n{\n \/\/Set default variables\n width = 800;\n height = 600;\n vsync = false;\n fullscreen = false;\n fog = true;\n mazeSize = 40;\n \n \/\/Try to load configuration\n loadConfig();\n \n \/\/If user set wrong size, correct it\n if(mazeSize > MAZE_MAXSIZE)\n mazeSize = MAZE_MAXSIZE;\n \n if(mazeSize < MAZE_MINSIZE)\n mazeSize = MAZE_MINSIZE;\n \n cout << \"\\nStarting mode \" << width << \"x\" << height << \", vsync=\" << vsync << \", fullscreen=\" << fullscreen << \", maze size=\" << mazeSize << \", fog=\" << fog << endl;\n}\n\nvoid Game::loadConfig()\n{\n vector options;\n std::string option, value;\n bool isOption = true;\n \n ifstream fin(\"config.cfg\");\n \n if(!fin.is_open())\n {\n cout << \"Failed to load config file. Setting default variables.\" << endl;\n return;\n }\n \n while(!fin.eof())\n {\n std::string tmp;\n fin >> tmp;\n options.push_back(tmp);\n }\n \n fin.close();\n \n for(unsigned int i = 0; i < options.size(); i++)\n {\n for(unsigned int j = 0; j < options[i].size(); j++)\n {\n \/\/'=' catched, so now we picking value, not option\n if(options[i][j] == '=')\n {\n isOption = false;\n continue;\n }\n \n if(isOption)\n option += options[i][j];\n \n if(!isOption)\n value += options[i][j];\n }\n \n \/\/Save game options\n if(option.compare(\"width\") == 0)\n width = atoi(value.c_str());\n \n if(option.compare(\"height\") == 0)\n height = atoi(value.c_str());\n \n if(option.compare(\"mazeSize\") == 0)\n mazeSize = atoi(value.c_str());\n \n if(option.compare(\"vsync\") == 0)\n {\n if(value.compare(\"true\") == 0)\n vsync = true;\n else if (value.compare(\"false\") == 0)\n vsync = false;\n }\n \n if(option.compare(\"fullscreen\") == 0)\n {\n if(value.compare(\"true\") == 0)\n fullscreen = true;\n else if (value.compare(\"false\") == 0)\n fullscreen = false;\n }\n \n if(option.compare(\"fog\") == 0)\n {\n if(value.compare(\"true\") == 0)\n fog = true;\n else if (value.compare(\"false\") == 0)\n fog = false;\n }\n \n \/\/Clear variables to use it in next loop step\n option=\"\";\n value=\"\";\n isOption = true;\n }\n}\n\nvoid Game::startGame()\n{\n \/\/Create Irrlicht device and get pointer to driver and scene manager\n device = createDevice(EDT_OPENGL, dimension2d(width, height), 32, fullscreen, false, vsync, 0);\n \n srand(time(0));\n \n driver = device->getVideoDriver();\n scenemgr = device->getSceneManager();\n \n device->setWindowCaption(L\"3D Maze\");\n \n \/\/Create map\n Map map(mazeSize);\n map.createMap(driver, scenemgr);\n \n IMeshSceneNode *mapNode = scenemgr->addMeshSceneNode(map.getMapMesh());\n mapNode->setMaterialFlag(EMF_LIGHTING, true);\n mapNode->getMaterial(0).FogEnable = false;\n \n ICameraSceneNode *camera = scenemgr->addCameraSceneNodeFPS();\n camera->setTarget(vector3df(90,4,45));\n camera->setFarValue(1000);\n device->getCursorControl()->setVisible(false);\n \n scenemgr->setAmbientLight(SColorf(1, 1, 1, 255));\n \n \/\/Main loop\n while(device->run())\n {\n if(device->isWindowActive())\n {\n driver->beginScene(true, true, SColor(255,0,0,0));\n \n scenemgr->drawAll();\n \n driver->endScene();\n }\n else\n device->yield();\n }\n \n device->drop();\n}\n\n\n<|endoftext|>"} {"text":"#include \"evaluate_circuit.h\"\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace qflex {\nnamespace {\n\nclass GetOutputStatesTest : public testing::Test {\n public:\n void TestOutputExpectations() {\n get_output_states(ordering_, &final_qubits_, &output_states_);\n EXPECT_EQ(final_qubits_, expected_final_qubits_);\n EXPECT_EQ(output_states_, expected_output_states_);\n }\n\n protected:\n std::vector> final_qubits_, expected_final_qubits_;\n std::vector output_states_, expected_output_states_;\n std::list ordering_;\n};\n\n\/\/ ExpandPatch should not affect output states.\nTEST_F(GetOutputStatesTest, IgnoresExpandPatch) {\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 0}));\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 1}));\n expected_final_qubits_ = {};\n expected_output_states_ = {\"\"};\n TestOutputExpectations();\n}\n\n\/\/ MergePatches should not affect output states.\nTEST_F(GetOutputStatesTest, IgnoresMergePatches) {\n ordering_.emplace_back(MergePatches(\"a\", \"b\"));\n ordering_.emplace_back(MergePatches(\"b\", \"c\"));\n expected_final_qubits_ = {};\n expected_output_states_ = {\"\"};\n TestOutputExpectations();\n}\n\n\/\/ Non-terminal cuts should not affect output states.\nTEST_F(GetOutputStatesTest, IgnoresNonTerminalCuts) {\n ordering_.emplace_back(CutIndex({{0, 0}, {0, 1}}, {1, 2}));\n ordering_.emplace_back(CutIndex({{0, 0}, {1, 0}}, {3}));\n expected_final_qubits_ = {};\n expected_output_states_ = {\"\"};\n TestOutputExpectations();\n}\n\n\/\/ Terminal cuts are listed in the order applied.\nTEST_F(GetOutputStatesTest, TerminalCutsDefineOutputStates) {\n ordering_.emplace_back(CutIndex({{0, 1}}, {0}));\n ordering_.emplace_back(CutIndex({{0, 0}}, {0, 1}));\n ordering_.emplace_back(CutIndex({{1, 0}}, {1}));\n expected_final_qubits_ = {{0, 1}, {0, 0}, {1, 0}};\n expected_output_states_ = {\"001\", \"011\"};\n TestOutputExpectations();\n}\n\n\/\/ Terminal cuts with no values will be evaluated as \"0\" and \"1\", since output\n\/\/ states can only be one of those two values.\nTEST_F(GetOutputStatesTest, BlankCutValuesEvaluateBothStates) {\n ordering_.emplace_back(CutIndex({{0, 1}}));\n ordering_.emplace_back(CutIndex({{0, 0}}));\n ordering_.emplace_back(CutIndex({{1, 0}}));\n expected_final_qubits_ = {{0, 1}, {0, 0}, {1, 0}};\n expected_output_states_ = {\"000\", \"001\", \"010\", \"011\",\n \"100\", \"101\", \"110\", \"111\"};\n TestOutputExpectations();\n}\n\n\/\/ When a mixture of operations are applied, only terminal cuts affect the\n\/\/ output states.\nTEST_F(GetOutputStatesTest, OnlyUseTerminalCuts) {\n ordering_.emplace_back(CutIndex({{0, 1}, {1, 1}}, {1, 2}));\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 1}));\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 0}));\n ordering_.emplace_back(ExpandPatch(\"a\", {1, 0}));\n ordering_.emplace_back(CutIndex({{2, 1}}));\n ordering_.emplace_back(ExpandPatch(\"b\", {2, 1}));\n ordering_.emplace_back(ExpandPatch(\"b\", {1, 1}));\n ordering_.emplace_back(MergePatches(\"a\", \"b\"));\n expected_final_qubits_ = {{2, 1}};\n expected_output_states_ = {\"0\", \"1\"};\n TestOutputExpectations();\n}\n\n\/\/ Nullptr input in get_output_states()\nTEST(GetOutputStatesDeathTest, InvalidInput) {\n std::list ordering;\n std::vector> final_qubits;\n std::vector output_states;\n\n \/\/ Final qubits cannot be null pointer.\n EXPECT_DEATH(get_output_states(ordering, nullptr, &output_states), \"\");\n\n \/\/ Output states cannot be null pointer.\n EXPECT_DEATH(get_output_states(ordering, &final_qubits, nullptr), \"\");\n}\n\n\/\/ Grid layout with trailing whitespace.\nconstexpr char kTestGrid[] = R\"(0 1 1 0\n 1 1 1 1\n 0 1 0 0\n )\";\n\nTEST(ReadGridTest, ValidGrid3x4) {\n std::stringstream stream(kTestGrid);\n std::vector> off_qubits =\n read_grid_layout_from_stream(&stream, 3, 4);\n std::vector> expected_off = {\n {0, 0}, {0, 3}, {2, 0}, {2, 2}, {2, 3}};\n EXPECT_EQ(off_qubits, expected_off);\n}\n\nTEST(ReadGridTest, ValidGrid6x2) {\n std::stringstream stream(kTestGrid);\n std::vector> off_qubits =\n read_grid_layout_from_stream(&stream, 6, 2);\n std::vector> expected_off = {\n {0, 0}, {1, 1}, {4, 0}, {5, 0}, {5, 1}};\n EXPECT_EQ(off_qubits, expected_off);\n}\n\n\/\/ Grid data is too large: 3 * 4 > 5 * 2\nTEST(ReadGridDeathTest, InvalidGrid5x2) {\n std::stringstream stream(kTestGrid);\n EXPECT_DEATH(read_grid_layout_from_stream(&stream, 5, 2), \"\");\n}\n\n\/\/ Grid data is too small: 3 * 4 < 5 * 3\nTEST(ReadGridDeathTest, InvalidGrid5x3) {\n std::stringstream stream(kTestGrid);\n EXPECT_DEATH(read_grid_layout_from_stream(&stream, 5, 3), \"\");\n}\n\n\/\/ Below are config strings for a simple grid with one \"off\" qubit and one cut:\n\/\/ 0 - 1\n\/\/ | x --> cut between (0,1) and (1,1)\n\/\/ 2 - 3\n\/\/ |\n\/\/ 4 5 --> qubit at (2,0) is off; (2,1) is in final region.\n\/\/ This circuit should return the input string with amplitude ~= 1 when summing\n\/\/ over the cut values, but only when the output of (2,1) is a zero.\nconstexpr char kSimpleCircuit[] = R\"(5\n0 h 0\n0 h 1\n0 h 2\n0 h 3\n0 h 5\n1 t 0\n1 t 1\n1 t 2\n1 t 3\n1 t 5\n1 cz 0 1\n2 cx 0 2\n3 cx 1 3\n4 cz 2 3\n5 cz 3 5\n11 cz 0 1\n12 cx 0 2\n13 cx 1 3\n14 cz 2 3\n15 cx 3 5\n17 h 0\n17 h 1\n17 h 2\n17 h 3\n17 h 5)\";\n\nconstexpr char kSimpleOrdering[] = R\"(#\ncut () 1 3\nexpand a 1\nexpand a 0\nexpand a 2\ncut () 5\nexpand b 5\nexpand b 3\nmerge a b\n)\";\n\nconstexpr char kSimpleGrid[] = R\"(1 1\n 1 1\n 0 1)\";\n\n\/\/ Perform a full evaluation of a very simple circuit.\nTEST(EvaluateCircuitTest, SimpleCircuit) {\n std::stringstream circuit_data(kSimpleCircuit);\n std::stringstream ordering_data(kSimpleOrdering);\n std::stringstream grid_data(kSimpleGrid);\n\n QflexInput input;\n input.I = 3;\n input.J = 2;\n input.K = 2;\n input.circuit_data = &circuit_data;\n input.ordering_data = &ordering_data;\n input.grid_data = &grid_data;\n input.initial_state = \"00000\";\n input.final_state_A = \"1100\";\n\n std::vector>> amplitudes =\n EvaluateCircuit(&input);\n\n ASSERT_EQ(amplitudes.size(), 2);\n EXPECT_EQ(amplitudes[0].first, \"1100 0\");\n EXPECT_EQ(amplitudes[1].first, \"1100 1\");\n EXPECT_NEAR(amplitudes[0].second.real(), 0.10669, 1e-5);\n EXPECT_NEAR(amplitudes[0].second.imag(), 0.04419, 1e-5);\n EXPECT_NEAR(amplitudes[1].second.real(), -0.01831, 1e-5);\n EXPECT_NEAR(amplitudes[1].second.imag(), -0.25758, 1e-5);\n}\n\n\/\/ Nullptr input in EvaluateCircuit()\nTEST(EvaluateCircuitDeathTest, InvalidInput) {\n \/\/ Input cannot be null pointer.\n EXPECT_DEATH(EvaluateCircuit(nullptr), \"\");\n}\n\n} \/\/ namespace\n} \/\/ namespace qflex\n\nint main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nfixed SimpleCircuit test#include \"evaluate_circuit.h\"\n\n#include \"gmock\/gmock.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace qflex {\nnamespace {\n\nclass GetOutputStatesTest : public testing::Test {\n public:\n void TestOutputExpectations() {\n get_output_states(ordering_, &final_qubits_, &output_states_);\n EXPECT_EQ(final_qubits_, expected_final_qubits_);\n EXPECT_EQ(output_states_, expected_output_states_);\n }\n\n protected:\n std::vector> final_qubits_, expected_final_qubits_;\n std::vector output_states_, expected_output_states_;\n std::list ordering_;\n};\n\n\/\/ ExpandPatch should not affect output states.\nTEST_F(GetOutputStatesTest, IgnoresExpandPatch) {\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 0}));\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 1}));\n expected_final_qubits_ = {};\n expected_output_states_ = {\"\"};\n TestOutputExpectations();\n}\n\n\/\/ MergePatches should not affect output states.\nTEST_F(GetOutputStatesTest, IgnoresMergePatches) {\n ordering_.emplace_back(MergePatches(\"a\", \"b\"));\n ordering_.emplace_back(MergePatches(\"b\", \"c\"));\n expected_final_qubits_ = {};\n expected_output_states_ = {\"\"};\n TestOutputExpectations();\n}\n\n\/\/ Non-terminal cuts should not affect output states.\nTEST_F(GetOutputStatesTest, IgnoresNonTerminalCuts) {\n ordering_.emplace_back(CutIndex({{0, 0}, {0, 1}}, {1, 2}));\n ordering_.emplace_back(CutIndex({{0, 0}, {1, 0}}, {3}));\n expected_final_qubits_ = {};\n expected_output_states_ = {\"\"};\n TestOutputExpectations();\n}\n\n\/\/ Terminal cuts are listed in the order applied.\nTEST_F(GetOutputStatesTest, TerminalCutsDefineOutputStates) {\n ordering_.emplace_back(CutIndex({{0, 1}}, {0}));\n ordering_.emplace_back(CutIndex({{0, 0}}, {0, 1}));\n ordering_.emplace_back(CutIndex({{1, 0}}, {1}));\n expected_final_qubits_ = {{0, 1}, {0, 0}, {1, 0}};\n expected_output_states_ = {\"001\", \"011\"};\n TestOutputExpectations();\n}\n\n\/\/ Terminal cuts with no values will be evaluated as \"0\" and \"1\", since output\n\/\/ states can only be one of those two values.\nTEST_F(GetOutputStatesTest, BlankCutValuesEvaluateBothStates) {\n ordering_.emplace_back(CutIndex({{0, 1}}));\n ordering_.emplace_back(CutIndex({{0, 0}}));\n ordering_.emplace_back(CutIndex({{1, 0}}));\n expected_final_qubits_ = {{0, 1}, {0, 0}, {1, 0}};\n expected_output_states_ = {\"000\", \"001\", \"010\", \"011\",\n \"100\", \"101\", \"110\", \"111\"};\n TestOutputExpectations();\n}\n\n\/\/ When a mixture of operations are applied, only terminal cuts affect the\n\/\/ output states.\nTEST_F(GetOutputStatesTest, OnlyUseTerminalCuts) {\n ordering_.emplace_back(CutIndex({{0, 1}, {1, 1}}, {1, 2}));\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 1}));\n ordering_.emplace_back(ExpandPatch(\"a\", {0, 0}));\n ordering_.emplace_back(ExpandPatch(\"a\", {1, 0}));\n ordering_.emplace_back(CutIndex({{2, 1}}));\n ordering_.emplace_back(ExpandPatch(\"b\", {2, 1}));\n ordering_.emplace_back(ExpandPatch(\"b\", {1, 1}));\n ordering_.emplace_back(MergePatches(\"a\", \"b\"));\n expected_final_qubits_ = {{2, 1}};\n expected_output_states_ = {\"0\", \"1\"};\n TestOutputExpectations();\n}\n\n\/\/ Nullptr input in get_output_states()\nTEST(GetOutputStatesDeathTest, InvalidInput) {\n std::list ordering;\n std::vector> final_qubits;\n std::vector output_states;\n\n \/\/ Final qubits cannot be null pointer.\n EXPECT_DEATH(get_output_states(ordering, nullptr, &output_states), \"\");\n\n \/\/ Output states cannot be null pointer.\n EXPECT_DEATH(get_output_states(ordering, &final_qubits, nullptr), \"\");\n}\n\n\/\/ Grid layout with trailing whitespace.\nconstexpr char kTestGrid[] = R\"(0 1 1 0\n 1 1 1 1\n 0 1 0 0\n )\";\n\nTEST(ReadGridTest, ValidGrid3x4) {\n std::stringstream stream(kTestGrid);\n std::vector> off_qubits =\n read_grid_layout_from_stream(&stream, 3, 4);\n std::vector> expected_off = {\n {0, 0}, {0, 3}, {2, 0}, {2, 2}, {2, 3}};\n EXPECT_EQ(off_qubits, expected_off);\n}\n\nTEST(ReadGridTest, ValidGrid6x2) {\n std::stringstream stream(kTestGrid);\n std::vector> off_qubits =\n read_grid_layout_from_stream(&stream, 6, 2);\n std::vector> expected_off = {\n {0, 0}, {1, 1}, {4, 0}, {5, 0}, {5, 1}};\n EXPECT_EQ(off_qubits, expected_off);\n}\n\n\/\/ Grid data is too large: 3 * 4 > 5 * 2\nTEST(ReadGridDeathTest, InvalidGrid5x2) {\n std::stringstream stream(kTestGrid);\n EXPECT_DEATH(read_grid_layout_from_stream(&stream, 5, 2), \"\");\n}\n\n\/\/ Grid data is too small: 3 * 4 < 5 * 3\nTEST(ReadGridDeathTest, InvalidGrid5x3) {\n std::stringstream stream(kTestGrid);\n EXPECT_DEATH(read_grid_layout_from_stream(&stream, 5, 3), \"\");\n}\n\n\/\/ Below are config strings for a simple grid with one \"off\" qubit and one cut:\n\/\/ 0 - 1\n\/\/ | x --> cut between (0,1) and (1,1)\n\/\/ 2 - 3\n\/\/ |\n\/\/ 4 5 --> qubit at (2,0) is off; (2,1) is in final region.\n\/\/ This circuit should return the input string with amplitude ~= 1 when summing\n\/\/ over the cut values, but only when the output of (2,1) is a zero.\nconstexpr char kSimpleCircuit[] = R\"(5\n0 h 0\n0 h 1\n0 h 2\n0 h 3\n0 h 5\n1 t 0\n1 t 1\n1 t 2\n1 t 3\n1 t 5\n2 cz 0 1\n3 cx 0 2\n4 cx 1 3\n5 cz 2 3\n6 cz 3 5\n11 cz 0 1\n12 cx 0 2\n13 cx 1 3\n14 cz 2 3\n15 cx 3 5\n17 h 0\n17 h 1\n17 h 2\n17 h 3\n17 h 5)\";\n\nconstexpr char kSimpleOrdering[] = R\"(#\ncut () 1 3\nexpand a 1\nexpand a 0\nexpand a 2\ncut () 5\nexpand b 5\nexpand b 3\nmerge a b\n)\";\n\nconstexpr char kSimpleGrid[] = R\"(1 1\n 1 1\n 0 1)\";\n\n\/\/ Perform a full evaluation of a very simple circuit.\nTEST(EvaluateCircuitTest, SimpleCircuit) {\n std::stringstream circuit_data(kSimpleCircuit);\n std::stringstream ordering_data(kSimpleOrdering);\n std::stringstream grid_data(kSimpleGrid);\n\n QflexInput input;\n input.I = 3;\n input.J = 2;\n input.K = 2;\n input.circuit_data = &circuit_data;\n input.ordering_data = &ordering_data;\n input.grid_data = &grid_data;\n input.initial_state = \"00000\";\n input.final_state_A = \"1100\";\n\n std::vector>> amplitudes =\n EvaluateCircuit(&input);\n\n ASSERT_EQ(amplitudes.size(), 2);\n EXPECT_EQ(amplitudes[0].first, \"1100 0\");\n EXPECT_EQ(amplitudes[1].first, \"1100 1\");\n EXPECT_NEAR(amplitudes[0].second.real(), 0.10669, 1e-5);\n EXPECT_NEAR(amplitudes[0].second.imag(), 0.04419, 1e-5);\n EXPECT_NEAR(amplitudes[1].second.real(), -0.01831, 1e-5);\n EXPECT_NEAR(amplitudes[1].second.imag(), -0.25758, 1e-5);\n}\n\n\/\/ Nullptr input in EvaluateCircuit()\nTEST(EvaluateCircuitDeathTest, InvalidInput) {\n \/\/ Input cannot be null pointer.\n EXPECT_DEATH(EvaluateCircuit(nullptr), \"\");\n}\n\n} \/\/ namespace\n} \/\/ namespace qflex\n\nint main(int argc, char** argv) {\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/frame\/app_non_client_frame_view_aura.h\"\n\n#include \"base\/debug\/stack_trace.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_frame.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/compositor\/layer.h\"\n#include \"ui\/gfx\/compositor\/scoped_layer_animation_settings.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/point.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/window\/non_client_view.h\"\n\nnamespace {\n\/\/ The number of pixels to use as a hover zone at the top of the screen.\nconst int kTopMargin = 1;\n\/\/ How long the hover animation takes if uninterrupted.\nconst int kHoverFadeDurationMs = 130;\n\/\/ The number of pixels within the shadow to draw the buttons.\nconst int kShadowStart = 28;\n}\n\nclass AppNonClientFrameViewAura::ControlView\n : public views::View, public views::ButtonListener {\n public:\n explicit ControlView(AppNonClientFrameViewAura* owner) :\n owner_(owner),\n close_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_CLOSE)),\n restore_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_RESTORE)) {\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n separator_ =\n *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SEPARATOR).ToSkBitmap();\n shadow_ = *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToSkBitmap();\n AddChildView(close_button_);\n AddChildView(restore_button_);\n }\n\n virtual void Layout() OVERRIDE {\n restore_button_->SetPosition(gfx::Point(kShadowStart, 0));\n close_button_->SetPosition(\n gfx::Point(kShadowStart + close_button_->width() + separator_.width(),\n 0));\n }\n\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return gfx::Size(shadow_.width(), shadow_.height());\n }\n\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n views::View::OnPaint(canvas);\n canvas->DrawBitmapInt(\n separator_, restore_button_->x() + restore_button_->width(), 0);\n canvas->DrawBitmapInt(shadow_, 0, 0);\n }\n\n void ButtonPressed(\n views::Button* sender,\n const views::Event& event) OVERRIDE {\n if (sender == close_button_)\n owner_->Close();\n else if (sender == restore_button_)\n owner_->Restore();\n }\n\n private:\n \/\/ Gets an image representing 3 bitmaps laid out horizontally that will be\n \/\/ used as the normal, hot and pushed states for the created button.\n views::ImageButton* CreateImageButton(int resource_id) {\n views::ImageButton* button = new views::ImageButton(this);\n const SkBitmap* all_images =\n ResourceBundle::GetSharedInstance().GetImageNamed(\n resource_id).ToSkBitmap();\n int width = all_images->width() \/ 3;\n int height = all_images->height();\n\n SkBitmap normal, hot, pushed;\n all_images->extractSubset(\n &normal,\n SkIRect::MakeXYWH(0, 0, width, height));\n all_images->extractSubset(\n &hot,\n SkIRect::MakeXYWH(width, 0, width, height));\n all_images->extractSubset(\n &pushed,\n SkIRect::MakeXYWH(2 * width, 0, width, height));\n button->SetImage(views::CustomButton::BS_NORMAL, &normal);\n button->SetImage(views::CustomButton::BS_HOT, &hot);\n button->SetImage(views::CustomButton::BS_PUSHED, &pushed);\n\n button->SizeToPreferredSize();\n return button;\n }\n\n AppNonClientFrameViewAura* owner_;\n views::ImageButton* close_button_;\n views::ImageButton* restore_button_;\n SkBitmap separator_;\n SkBitmap shadow_;\n\n DISALLOW_COPY_AND_ASSIGN(ControlView);\n};\n\nclass AppNonClientFrameViewAura::Host : public views::MouseWatcherHost {\n public:\n explicit Host(AppNonClientFrameViewAura* owner) : owner_(owner) {}\n virtual ~Host() {}\n\n virtual bool Contains(\n const gfx::Point& screen_point,\n views::MouseWatcherHost::MouseEventType type) {\n gfx::Rect top_margin = owner_->GetScreenBounds();\n top_margin.set_height(kTopMargin);\n gfx::Rect control_bounds = owner_->GetControlBounds();\n control_bounds.Inset(kShadowStart, 0, 0, kShadowStart);\n return top_margin.Contains(screen_point) ||\n control_bounds.Contains(screen_point);\n }\n\n AppNonClientFrameViewAura* owner_;\n\n DISALLOW_COPY_AND_ASSIGN(Host);\n};\n\nAppNonClientFrameViewAura::AppNonClientFrameViewAura(\n BrowserFrame* frame, BrowserView* browser_view)\n : BrowserNonClientFrameView(frame, browser_view),\n control_view_(new ControlView(this)),\n control_widget_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n mouse_watcher_(new Host(this), this)) {\n}\n\nAppNonClientFrameViewAura::~AppNonClientFrameViewAura() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForClientView() const {\n gfx::Rect bounds = GetLocalBounds();\n bounds.Inset(0, kTopMargin, 0, 0);\n return bounds;\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n gfx::Rect bounds = client_bounds;\n bounds.Inset(0, -kTopMargin, 0, 0);\n return bounds;\n}\n\nint AppNonClientFrameViewAura::NonClientHitTest(\n const gfx::Point& point) {\n return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;\n}\n\nvoid AppNonClientFrameViewAura::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n}\n\nvoid AppNonClientFrameViewAura::ResetWindowControls() {\n}\n\nvoid AppNonClientFrameViewAura::UpdateWindowIcon() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForTabStrip(\n views::View* tabstrip) const {\n return gfx::Rect();\n}\n\nint AppNonClientFrameViewAura::GetHorizontalTabStripVerticalOffset(\n bool restored) const {\n return 0;\n}\n\nvoid AppNonClientFrameViewAura::UpdateThrobber(bool running) {\n}\n\nvoid AppNonClientFrameViewAura::OnMouseEntered(\n const views::MouseEvent& event) {\n if (!control_widget_) {\n control_widget_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);\n params.parent = browser_view()->GetNativeHandle();\n params.transparent = true;\n control_widget_->Init(params);\n control_widget_->SetContentsView(control_view_);\n aura::Window* window = control_widget_->GetNativeView();\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n window->SetBounds(control_bounds);\n control_widget_->Show();\n }\n\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n layer->SetBounds(GetControlBounds());\n layer->SetOpacity(1);\n\n mouse_watcher_.Start();\n}\n\nvoid AppNonClientFrameViewAura::MouseMovedOutOfHost() {\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n layer->SetBounds(control_bounds);\n layer->SetOpacity(0);\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetControlBounds() const {\n gfx::Size preferred = control_view_->GetPreferredSize();\n gfx::Point location(width() - preferred.width(), 0);\n ConvertPointToWidget(this, &location);\n return gfx::Rect(\n location.x(), location.y(),\n preferred.width(), preferred.height());\n}\n\nvoid AppNonClientFrameViewAura::Close() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Close();\n}\n\nvoid AppNonClientFrameViewAura::Restore() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Restore();\n}\nCreate black background for full screen app windows BUG=118111 TEST=Visual\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/frame\/app_non_client_frame_view_aura.h\"\n\n#include \"base\/debug\/stack_trace.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_frame.h\"\n#include \"chrome\/browser\/ui\/views\/frame\/browser_view.h\"\n#include \"grit\/ui_resources.h\"\n#include \"ui\/aura\/window.h\"\n#include \"ui\/base\/animation\/slide_animation.h\"\n#include \"ui\/base\/hit_test.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n#include \"ui\/gfx\/canvas.h\"\n#include \"ui\/gfx\/compositor\/layer.h\"\n#include \"ui\/gfx\/compositor\/scoped_layer_animation_settings.h\"\n#include \"ui\/gfx\/image\/image.h\"\n#include \"ui\/gfx\/point.h\"\n#include \"ui\/gfx\/rect.h\"\n#include \"ui\/gfx\/size.h\"\n#include \"ui\/views\/controls\/button\/image_button.h\"\n#include \"ui\/views\/widget\/widget.h\"\n#include \"ui\/views\/window\/non_client_view.h\"\n\nnamespace {\n\/\/ The number of pixels to use as a hover zone at the top of the screen.\nconst int kTopMargin = 1;\n\/\/ How long the hover animation takes if uninterrupted.\nconst int kHoverFadeDurationMs = 130;\n\/\/ The number of pixels within the shadow to draw the buttons.\nconst int kShadowStart = 28;\n}\n\nclass AppNonClientFrameViewAura::ControlView\n : public views::View, public views::ButtonListener {\n public:\n explicit ControlView(AppNonClientFrameViewAura* owner) :\n owner_(owner),\n close_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_CLOSE)),\n restore_button_(CreateImageButton(IDR_AURA_WINDOW_FULLSCREEN_RESTORE)) {\n ResourceBundle& rb = ResourceBundle::GetSharedInstance();\n separator_ =\n *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SEPARATOR).ToSkBitmap();\n shadow_ = *rb.GetImageNamed(IDR_AURA_WINDOW_FULLSCREEN_SHADOW).ToSkBitmap();\n AddChildView(close_button_);\n AddChildView(restore_button_);\n }\n\n virtual void Layout() OVERRIDE {\n restore_button_->SetPosition(gfx::Point(kShadowStart, 0));\n close_button_->SetPosition(\n gfx::Point(kShadowStart + close_button_->width() + separator_.width(),\n 0));\n }\n\n virtual gfx::Size GetPreferredSize() OVERRIDE {\n return gfx::Size(shadow_.width(), shadow_.height());\n }\n\n virtual void OnPaint(gfx::Canvas* canvas) OVERRIDE {\n views::View::OnPaint(canvas);\n canvas->DrawBitmapInt(\n separator_, restore_button_->x() + restore_button_->width(), 0);\n canvas->DrawBitmapInt(shadow_, 0, 0);\n }\n\n void ButtonPressed(\n views::Button* sender,\n const views::Event& event) OVERRIDE {\n if (sender == close_button_)\n owner_->Close();\n else if (sender == restore_button_)\n owner_->Restore();\n }\n\n private:\n \/\/ Gets an image representing 3 bitmaps laid out horizontally that will be\n \/\/ used as the normal, hot and pushed states for the created button.\n views::ImageButton* CreateImageButton(int resource_id) {\n views::ImageButton* button = new views::ImageButton(this);\n const SkBitmap* all_images =\n ResourceBundle::GetSharedInstance().GetImageNamed(\n resource_id).ToSkBitmap();\n int width = all_images->width() \/ 3;\n int height = all_images->height();\n\n SkBitmap normal, hot, pushed;\n all_images->extractSubset(\n &normal,\n SkIRect::MakeXYWH(0, 0, width, height));\n all_images->extractSubset(\n &hot,\n SkIRect::MakeXYWH(width, 0, width, height));\n all_images->extractSubset(\n &pushed,\n SkIRect::MakeXYWH(2 * width, 0, width, height));\n button->SetImage(views::CustomButton::BS_NORMAL, &normal);\n button->SetImage(views::CustomButton::BS_HOT, &hot);\n button->SetImage(views::CustomButton::BS_PUSHED, &pushed);\n\n button->SizeToPreferredSize();\n return button;\n }\n\n AppNonClientFrameViewAura* owner_;\n views::ImageButton* close_button_;\n views::ImageButton* restore_button_;\n SkBitmap separator_;\n SkBitmap shadow_;\n\n DISALLOW_COPY_AND_ASSIGN(ControlView);\n};\n\nclass AppNonClientFrameViewAura::Host : public views::MouseWatcherHost {\n public:\n explicit Host(AppNonClientFrameViewAura* owner) : owner_(owner) {}\n virtual ~Host() {}\n\n virtual bool Contains(\n const gfx::Point& screen_point,\n views::MouseWatcherHost::MouseEventType type) {\n gfx::Rect top_margin = owner_->GetScreenBounds();\n top_margin.set_height(kTopMargin);\n gfx::Rect control_bounds = owner_->GetControlBounds();\n control_bounds.Inset(kShadowStart, 0, 0, kShadowStart);\n return top_margin.Contains(screen_point) ||\n control_bounds.Contains(screen_point);\n }\n\n AppNonClientFrameViewAura* owner_;\n\n DISALLOW_COPY_AND_ASSIGN(Host);\n};\n\nAppNonClientFrameViewAura::AppNonClientFrameViewAura(\n BrowserFrame* frame, BrowserView* browser_view)\n : BrowserNonClientFrameView(frame, browser_view),\n control_view_(new ControlView(this)),\n control_widget_(NULL),\n ALLOW_THIS_IN_INITIALIZER_LIST(\n mouse_watcher_(new Host(this), this)) {\n set_background(views::Background::CreateSolidBackground(SK_ColorBLACK));\n}\n\nAppNonClientFrameViewAura::~AppNonClientFrameViewAura() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForClientView() const {\n gfx::Rect bounds = GetLocalBounds();\n bounds.Inset(0, kTopMargin, 0, 0);\n return bounds;\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetWindowBoundsForClientBounds(\n const gfx::Rect& client_bounds) const {\n gfx::Rect bounds = client_bounds;\n bounds.Inset(0, -kTopMargin, 0, 0);\n return bounds;\n}\n\nint AppNonClientFrameViewAura::NonClientHitTest(\n const gfx::Point& point) {\n return bounds().Contains(point) ? HTCLIENT : HTNOWHERE;\n}\n\nvoid AppNonClientFrameViewAura::GetWindowMask(const gfx::Size& size,\n gfx::Path* window_mask) {\n}\n\nvoid AppNonClientFrameViewAura::ResetWindowControls() {\n}\n\nvoid AppNonClientFrameViewAura::UpdateWindowIcon() {\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetBoundsForTabStrip(\n views::View* tabstrip) const {\n return gfx::Rect();\n}\n\nint AppNonClientFrameViewAura::GetHorizontalTabStripVerticalOffset(\n bool restored) const {\n return 0;\n}\n\nvoid AppNonClientFrameViewAura::UpdateThrobber(bool running) {\n}\n\nvoid AppNonClientFrameViewAura::OnMouseEntered(\n const views::MouseEvent& event) {\n if (!control_widget_) {\n control_widget_ = new views::Widget;\n views::Widget::InitParams params(views::Widget::InitParams::TYPE_CONTROL);\n params.parent = browser_view()->GetNativeHandle();\n params.transparent = true;\n control_widget_->Init(params);\n control_widget_->SetContentsView(control_view_);\n aura::Window* window = control_widget_->GetNativeView();\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n window->SetBounds(control_bounds);\n control_widget_->Show();\n }\n\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n layer->SetBounds(GetControlBounds());\n layer->SetOpacity(1);\n\n mouse_watcher_.Start();\n}\n\nvoid AppNonClientFrameViewAura::MouseMovedOutOfHost() {\n ui::Layer* layer = control_widget_->GetNativeView()->layer();\n\n ui::ScopedLayerAnimationSettings scoped_setter(layer->GetAnimator());\n scoped_setter.SetTransitionDuration(\n base::TimeDelta::FromMilliseconds(kHoverFadeDurationMs));\n gfx::Rect control_bounds = GetControlBounds();\n control_bounds.set_y(control_bounds.y() - control_bounds.height());\n layer->SetBounds(control_bounds);\n layer->SetOpacity(0);\n}\n\ngfx::Rect AppNonClientFrameViewAura::GetControlBounds() const {\n gfx::Size preferred = control_view_->GetPreferredSize();\n gfx::Point location(width() - preferred.width(), 0);\n ConvertPointToWidget(this, &location);\n return gfx::Rect(\n location.x(), location.y(),\n preferred.width(), preferred.height());\n}\n\nvoid AppNonClientFrameViewAura::Close() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Close();\n}\n\nvoid AppNonClientFrameViewAura::Restore() {\n if (control_widget_)\n control_widget_->Close();\n control_widget_ = NULL;\n mouse_watcher_.Stop();\n frame()->Restore();\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \ntypedef long long lld;\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n int n, m, x;\n cin >> n >> m;\n vector need(n);\n for (int i = 0; i < n; ++i) {\n cin >> need[i];\n }\n vector curr(m);\n for (int i = 0; i < m; ++i) {\n cin >> curr[i];\n }\n sort(need.begin(), need.end());\n sort(curr.begin(), curr.end());\n int ans = 0;\n for (int i = 0, p = 0; i < need.size(); ++i) {\n while (p < curr.size() && curr[p] < need[i]) {\n ++p; \n }\n if (p < curr.size() && curr[p] >= need[i]) {\n continue;\n }\n ++ans;\n } \n cout << ans << endl;\n return 0;\n}\n\nWrong answer on test 4: http:\/\/codeforces.com\/contest\/387\/submission\/5928442#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \ntypedef long long lld;\n\nusing namespace std;\n\nint main(int argc, char* argv[]) {\n int n, m, x;\n cin >> n >> m;\n vector need(n);\n for (int i = 0; i < n; ++i) {\n cin >> need[i];\n }\n vector curr(m);\n for (int i = 0; i < m; ++i) {\n cin >> curr[i];\n }\n sort(need.begin(), need.end());\n sort(curr.begin(), curr.end());\n int ans = n;\n for (int i = 0, p = 0; i < need.size(); ++i) {\n while (p < curr.size() && curr[p] < need[i]) {\n ++p; \n }\n if (p < curr.size() && curr[p] >= need[i]) {\n --ans;\n }\n } \n cout << ans << endl;\n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \"util.h\"\n\nuint8_t lastError = ERROR_NONE;\n\n\/\/ bringt den Chip in den Fehler-Modus und blockiert ihn \nvoid error(const char* tag, const char* message, boolean blinkFast)\n{\n\twriteEEPROM(\"fError\");\n\twriteEEPROM(message);\n\n\tserialPrintF(\"error(tag = \");\n\tserialPrint(tag);\n\tserialPrintF(\", message = \");\n\tserialPrint(message);\n\tserialPrintlnF(\")\");\n\n\twhile (true) {\n\t\ttoogleRedLed();\n\n\t\tif (blinkFast)\n\t\t\tdelay(250);\n\t\telse\n\t\t\tdelay(500);\n\t\twdt_yield();\n\t}\n}\n\nvoid internalError()\n{\n\tinternalError(ERROR_INTERNAL);\n}\n\nvoid internalError(uint8_t error)\n{\n\twriteEEPROM(\"iError\");\n\twriteEEPROM(error);\n\n\twdt_yield();\n\tserialPrintF(\"Error(error = \");\n\tserialPrint(error);\n\tserialPrintlnF(\")\");\n\n\tlastError = error;\n\tblinkRedLedShort(true);\n}\n\nvoid protocolError(uint8_t error)\n{\n\twriteEEPROM(\"pError\");\n\twriteEEPROM(error);\n\n\twdt_yield();\n\tserialPrintF(\"protocolError(error = \");\n\tserialPrint(error);\n\tserialPrintlnF(\")\");\n\n\tlastError = error;\n\tblinkRedLedShort(true);\n}\n\nchar getHexChar(int32_t x)\n{\n\tx &= 0xF;\n\tif (x >= 10)\n\t\treturn 'A' + (x - 10);\n\treturn '0' + x;\n}\n\nunsigned long timersData[TIMER_COUNT];\n\nvoid startTime(uint8_t index) {\n\tif (index >= TIMER_COUNT)\n\t\treturn internalError(ERROR_INTERNAL_INVALID_TIMER);\n\n\ttimersData[index] = micros();\n}\n\nint32_t endTime(uint8_t index) {\n\tif (index >= TIMER_COUNT) {\n\t\tinternalError(ERROR_INTERNAL_INVALID_TIMER);\n\t\treturn 0;\n\t}\n\n\tunsigned long end = micros();\n\tif (end > timersData[index])\n\t\treturn end - timersData[index];\n\treturn 0;\n}\n\nuint32_t freeRam() {\n\t\/\/ siehe http:\/\/playground.arduino.cc\/Code\/AvailableMemory\n\textern int32_t __heap_start, *__brkval;\n\tint32_t v;\n\treturn ((int32_t)&v - (__brkval == 0 ? (int32_t)&__heap_start : (int32_t)__brkval));\n}\n\nuint32_t logPosition = 16;\n\nvoid initEEPROM()\n{\n\tlogPosition = 16;\n}\n\nvoid writeEEPROM(uint8_t value)\n{\n#if ENABLE_EEPROM_LOG\n\tlogPosition = logPosition % 1000;\n\twhile (!eeprom_is_ready())\n\t\twdt_yield();\n\n\t_EEPUT(logPosition++, value);\n#endif\n\twdt_yield();\n}\n\nvoid writeEEPROM(const char * str)\n{\n\tuint32_t len = strlen(str);\n\n\tfor (uint32_t i = 0; i < len; i++)\n\t\twriteEEPROM((uint8_t)str[i]);\n\n\twriteEEPROM((uint8_t)' ');\n}Clear EEPROM in initEEPROM()#include \"util.h\"\n\nuint8_t lastError = ERROR_NONE;\n\n\/\/ bringt den Chip in den Fehler-Modus und blockiert ihn \nvoid error(const char* tag, const char* message, boolean blinkFast)\n{\n\twriteEEPROM(\"fError\");\n\twriteEEPROM(message);\n\n\tserialPrintF(\"error(tag = \");\n\tserialPrint(tag);\n\tserialPrintF(\", message = \");\n\tserialPrint(message);\n\tserialPrintlnF(\")\");\n\n\twhile (true) {\n\t\ttoogleRedLed();\n\n\t\tif (blinkFast)\n\t\t\tdelay(250);\n\t\telse\n\t\t\tdelay(500);\n\t\twdt_yield();\n\t}\n}\n\nvoid internalError()\n{\n\tinternalError(ERROR_INTERNAL);\n}\n\nvoid internalError(uint8_t error)\n{\n\twriteEEPROM(\"iError\");\n\twriteEEPROM(error);\n\n\twdt_yield();\n\tserialPrintF(\"Error(error = \");\n\tserialPrint(error);\n\tserialPrintlnF(\")\");\n\n\tlastError = error;\n\tblinkRedLedShort(true);\n}\n\nvoid protocolError(uint8_t error)\n{\n\twriteEEPROM(\"pError\");\n\twriteEEPROM(error);\n\n\twdt_yield();\n\tserialPrintF(\"protocolError(error = \");\n\tserialPrint(error);\n\tserialPrintlnF(\")\");\n\n\tlastError = error;\n\tblinkRedLedShort(true);\n}\n\nchar getHexChar(int32_t x)\n{\n\tx &= 0xF;\n\tif (x >= 10)\n\t\treturn 'A' + (x - 10);\n\treturn '0' + x;\n}\n\nunsigned long timersData[TIMER_COUNT];\n\nvoid startTime(uint8_t index) {\n\tif (index >= TIMER_COUNT)\n\t\treturn internalError(ERROR_INTERNAL_INVALID_TIMER);\n\n\ttimersData[index] = micros();\n}\n\nint32_t endTime(uint8_t index) {\n\tif (index >= TIMER_COUNT) {\n\t\tinternalError(ERROR_INTERNAL_INVALID_TIMER);\n\t\treturn 0;\n\t}\n\n\tunsigned long end = micros();\n\tif (end > timersData[index])\n\t\treturn end - timersData[index];\n\treturn 0;\n}\n\nuint32_t freeRam() {\n\t\/\/ siehe http:\/\/playground.arduino.cc\/Code\/AvailableMemory\n\textern int32_t __heap_start, *__brkval;\n\tint32_t v;\n\treturn ((int32_t)&v - (__brkval == 0 ? (int32_t)&__heap_start : (int32_t)__brkval));\n}\n\n#define DEFAULT_LOG_POSITION 16\n\nuint32_t logPosition = DEFAULT_LOG_POSITION;\n\nvoid initEEPROM()\n{\n\t\/\/ Clear EEPROM\n\tlogPosition = DEFAULT_LOG_POSITION;\n\tfor (int i = 0; i < 200; i++)\n\t\twriteEEPROM((uint8_t)'?');\n\tlogPosition = DEFAULT_LOG_POSITION;\n}\n\nvoid writeEEPROM(uint8_t value)\n{\n#if ENABLE_EEPROM_LOG\n\tlogPosition = logPosition % 1000;\n\twhile (!eeprom_is_ready())\n\t\twdt_yield();\n\n\t_EEPUT(logPosition++, value);\n#endif\n\twdt_yield();\n}\n\nvoid writeEEPROM(const char * str)\n{\n\tuint32_t len = strlen(str);\n\n\tfor (uint32_t i = 0; i < len; i++)\n\t\twriteEEPROM((uint8_t)str[i]);\n\n\twriteEEPROM((uint8_t)' ');\n}<|endoftext|>"} {"text":"#include \r\n\r\n#include \r\n\r\n#include \"Settings.h\"\r\n#include \"Main.h\"\r\n#include \"VideoBase.h\"\r\n#include \"Loader.h\"\r\n#include \"Window.h\"\r\n#include \"Text.h\"\r\n#include \"Info.h\"\r\n#include \"Error.h\"\r\n#include \"GamePlay.h\"\r\n\r\n\r\n\r\n#define SPLASH_RESOURCE NULL\r\n#define SPLASH_FILE \"SPLASH.JPG\"\r\n\r\n#define SPLASH_FONT_NAME \"Arial\"\r\n#define SPLASH_FONT_SIZE_AT_H600 12\r\n#define SPLASH_FONT_SIZE (SPLASH_FONT_SIZE_AT_H600*CWindow::GetHeight()\/600)\r\n#define SPLASH_TEXT_SPACING_COEFF 1.75f\r\n\r\n#define SPLASH_TEXT_COLOR_R 0.75f\r\n#define SPLASH_TEXT_COLOR_G 0.75f\r\n#define SPLASH_TEXT_COLOR_B 0.75f\r\n\r\n#define RESTART_ALLOWED true\r\n#define RESTART_TIME 10.0f\r\n\r\n\r\n\r\n\r\nint CGamePlay::splash_tex=0;\r\nchar CGamePlay::load_text[256];\r\nCGamePlay::splash_rect CGamePlay::splash_pos;\r\nCBody CGamePlay::mainbody;\r\nCCamera CGamePlay::camera;\r\nCStarMap CGamePlay::starmap;\r\nCClock CGamePlay::clock;\r\nCLensFlare CGamePlay::lensflare;\r\nbool CGamePlay::flares=false;\r\nbool CGamePlay::planetinfo=false;\r\nCText CGamePlay::splashtext;\r\nCInfo CGamePlay::info;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nCGamePlay::CGamePlay()\r\n{\r\n}\r\n\r\n\r\n\r\n\r\n\r\nCGamePlay::~CGamePlay()\r\n{\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::Init()\r\n{\r\n\tbool ret=true;\r\n\tif (!splashtext.BuildFTFont(SPLASH_FONT_NAME,SPLASH_FONT_SIZE))\r\n\t\tCError::LogError(WARNING_CODE,\"Failed to load the splash text font - ignoring.\");\r\n\tif (!InitScene())\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t\tOnUserAbortLoad();\r\n\t\telse\r\n\t\t\tCError::LogError(ERROR_CODE,\"Unable to load scene critical data - aborting.\");\r\n\t\tDestroyScene();\r\n\t\tret=false;\r\n\t}\r\n\tFreeSplash();\r\n\tsplashtext.Free();\r\n\treturn ret;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::ShutDown()\r\n{\r\n\tDestroyScene();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::CalcSplashRect()\r\n{\r\n\tint w=CWindow::GetWidth();\r\n\tint h=CWindow::GetHeight();\r\n\tsplash_pos.x1=(w*3<=h*4?0:(w-h*4\/3)\/2);\r\n\tsplash_pos.x2=(w*3<=h*4?w:(w+h*4\/3)\/2);\r\n\tsplash_pos.y1=(w*3>=h*4?0:(h-w*3\/4)\/2);\r\n\tsplash_pos.y2=(w*3>=h*4?h:(h+w*3\/4)\/2);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::LoadSplash()\r\n{\r\n\tCalcSplashRect();\r\n\tCLoader loader;\r\n\tloader.WithResource(SPLASH_RESOURCE);\r\n\tsplash_tex=loader.LoadTexture(SPLASH_FILE,NULL,CVideoBase::GetOptMipmaps(),CVideoBase::GetOptLinear());\r\n\treturn (splash_tex>0);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::FreeSplash()\r\n{\r\n\tglDeleteTextures(1,(GLuint*)&splash_tex);\r\n\tsplash_tex=0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::InitLight()\r\n{\r\n\tGLfloat LightAmbient[4] = { 1.0f, 1.0f, 1.0f, 1.0f };\r\n\tGLfloat LightDiffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f };\r\n\tGLfloat LightSpecular[4] = { 1.0f, 1.0f, 1.0f, 1.0f };\r\n\tglLightfv(GL_LIGHT1,GL_AMBIENT,LightAmbient);\r\n\tglLightfv(GL_LIGHT1,GL_DIFFUSE,LightDiffuse);\r\n\tglLightfv(GL_LIGHT1,GL_SPECULAR,LightSpecular);\r\n\tglEnable(GL_LIGHT1);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::OnUserAbortLoad()\r\n{\r\n\t\/\/ log new error\r\n\tCError::LogError(ERROR_CODE,\"User aborted load.\");\r\n\t\/\/ get first error, and if it's \"user abort\", clear the log so it's not printed\r\n\tif (CError::ErrorsOccured())\r\n\t{\r\n\t\tint code;\r\n\t\tchar string[ERROR_MAXLEN];\r\n\t\tCError::Rewind();\r\n\t\tCError::GetNextError(&code,string);\r\n\t\tstrlwr(string);\r\n\t\tif (strstr(string,\"user\") && strstr(string,\"abort\"))\r\n\t\t\tCError::Clear();\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::UserAbortedLoad()\r\n{\r\n\tstatic bool userabort=false;\r\n\tif (!userabort)\r\n\t\tuserabort=!MessagePump();\r\n\treturn userabort;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::InitScene()\r\n{\r\n\t{\r\n\t\tSetSplashText(\"Loading splash screen... \");\r\n\t\tif (!LoadSplash())\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the splash screen - ignoring.\");\r\n\t}\r\n\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading bodies... \");\r\n\t\tif (!mainbody.Load())\r\n\t\t{\r\n\t\t\tCError::LogError(ERROR_CODE,\"Failed to load the bodies - aborting.\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tflares=CVideoBase::GetOptLensFlares();\r\n\tif (flares)\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading lens flares... \");\r\n\t\tif (!lensflare.Load(&mainbody))\r\n\t\t{\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the lens flares - ignoring.\");\r\n\t\t\tflares=false;\r\n\t\t}\r\n\t}\r\n\r\n\tplanetinfo=(CSettings::PlanetInfo==TRUE);\r\n\tif (planetinfo)\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading info text font... \");\r\n\t\tif (!info.Load())\r\n\t\t{\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the planet info - ignoring.\");\r\n\t\t\tplanetinfo=false;\r\n\t\t}\r\n\t}\r\n\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading starmap... \");\r\n\t\tif (!starmap.Load())\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the starmap - ignoring.\");\r\n\t}\r\n\r\n\tif (CSettings::ClockOn)\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading clock... \");\r\n\t\tif (!clock.Load())\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the clock - ignoring.\");\r\n\t}\r\n\r\n\tif (UserAbortedLoad())\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\tSetSplashText(\"Done.\");\r\n\r\n\tsrand((unsigned int)timeGetTime());\r\n\tInitLight();\r\n\tcamera.Init(&mainbody,(planetinfo?&info:NULL),CWindow::GetWidth(),CWindow::GetHeight());\r\n\treturn FadeOutSplash();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::DestroyScene()\r\n{\r\n\tstarmap.Free();\r\n\tlensflare.Free();\r\n\tflares=false;\r\n\tif (CSettings::ClockOn)\r\n\t\tclock.Free();\r\n\tmainbody.Destroy();\r\n\tinfo.Free();\r\n\tplanetinfo=false;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::UpdateScene()\r\n{\r\n\tfloat seconds;\r\n\tstatic DWORD starttime=timeGetTime();\r\n\tint milidelta;\r\n\tmilidelta=(timeGetTime()-starttime);\r\n\tseconds=milidelta*0.001f;\r\n\tmainbody.Update(seconds);\r\n\tcamera.Update(seconds);\r\n\tif (flares)\r\n\t\tlensflare.UpdateTime(seconds);\r\n\tif (planetinfo)\r\n\t\tinfo.Update(seconds);\r\n\tif (CSettings::ClockOn==TRUE && milidelta>=500)\r\n\t\tclock.Update();\r\n\tif (RESTART_ALLOWED)\r\n\t{\r\n\t\tif (seconds>=max(RESTART_TIME,CAMERA_INIT_FADE_TIME))\r\n\t\t{\r\n\t\t\tmainbody.Restart();\r\n\t\t\tcamera.Restart(seconds);\r\n\t\t\tif (flares)\r\n\t\t\t\tlensflare.Restart();\r\n\t\t\tif (planetinfo)\r\n\t\t\t\tinfo.Restart();\r\n\t\t\tstarttime=starttime+milidelta;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::DrawScene()\r\n{\r\n\tGLfloat LightPosition[4] = { 0.0f, 0.0f, 0.0f, 1.0f };\r\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\tglLoadIdentity();\r\n\tcamera.ApplyRotation();\r\n\tstarmap.Draw();\r\n\tcamera.ApplyTranslation();\r\n\tglLightfv(GL_LIGHT1,GL_POSITION,LightPosition);\r\n\tmainbody.Draw(flares?&lensflare:NULL);\r\n\tif (flares)\r\n\t{\r\n\t\tlensflare.Draw();\r\n\t}\r\n\tif (planetinfo || CSettings::ClockOn)\r\n\t{\r\n\t\tPrepare2D(CWindow::GetWidth(),CWindow::GetHeight());\r\n\t\tif (planetinfo)\r\n\t\t\tinfo.Draw();\r\n\t\tif (CSettings::ClockOn)\r\n\t\t\tclock.Draw();\r\n\t\tRestore3D();\r\n\t}\r\n\tcamera.DrawFade();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::Frame()\r\n{\r\n\tUpdateScene();\r\n\tSwapBuffers(wglGetCurrentDC());\r\n\tDrawScene();\r\n\tglFlush();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::Prepare2D(int width, int height)\r\n{\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglPushMatrix();\r\n\tglLoadIdentity();\r\n\tgluOrtho2D(0,width,0,height);\r\n\tglMatrixMode(GL_MODELVIEW);\r\n\tglPushAttrib(GL_ENABLE_BIT);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::Restore3D()\r\n{\r\n\tglPopAttrib();\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglPopMatrix();\r\n\tglMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::UpdateSplash(const char *subtext)\r\n{\r\n\tchar text[256];\r\n\tstrcpy(text,load_text);\r\n\tstrcat(text,subtext);\r\n\tDrawSplash(text);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::RenderSplashInner(const char *text)\r\n{\r\n\tglLoadIdentity();\r\n\tglDisable(GL_LIGHTING);\r\n\tglDisable(GL_DEPTH_TEST);\r\n\tglDisable(GL_CULL_FACE);\r\n\tglEnable(GL_TEXTURE_2D);\r\n\tif (splash_tex>0)\r\n\t{\r\n\t\tglColor4f(1,1,1,1);\r\n\t\tglBindTexture(GL_TEXTURE_2D,splash_tex);\r\n\t\tglBegin(GL_QUADS);\r\n\t\t{\r\n\t\t\tglTexCoord2f(0,0.25f);\r\n\t\t\tglVertex2f((float)splash_pos.x1,(float)splash_pos.y1);\r\n\t\t\tglTexCoord2f(1,0.25f);\r\n\t\t\tglVertex2f((float)splash_pos.x2,(float)splash_pos.y1);\r\n\t\t\tglTexCoord2f(1,1);\r\n\t\t\tglVertex2f((float)splash_pos.x2,(float)splash_pos.y2);\r\n\t\t\tglTexCoord2f(0,1);\r\n\t\t\tglVertex2f((float)splash_pos.x1,(float)splash_pos.y2);\r\n\t\t}\r\n\t\tglEnd();\r\n\t}\r\n\tint w=CWindow::GetWidth();\r\n\tfloat th;\r\n\tsplashtext.GetTextSize(text,NULL,&th);\r\n\tint text_under_height=(int)(th*(SPLASH_TEXT_SPACING_COEFF-1.0f));\r\n\tint band_height=(int)(th*(2.0*SPLASH_TEXT_SPACING_COEFF-1.0f));\r\n\tglDisable(GL_TEXTURE_2D);\r\n\tglColor4f(0,0,0,1);\r\n\tglBegin(GL_QUADS);\r\n\t{\r\n\t\tglVertex2f(0.0f,0.0f);\r\n\t\tglVertex2f((float)w,0.0f);\r\n\t\tglVertex2f((float)w,(float)band_height);\r\n\t\tglVertex2f(0.0f,(float)band_height);\r\n\t}\r\n\tglEnd();\r\n\tglEnable(GL_TEXTURE_2D);\r\n\tglEnable(GL_BLEND);\r\n\tglTranslatef(0.0f,(float)text_under_height,0.0f);\r\n\tglColor4f(SPLASH_TEXT_COLOR_R,SPLASH_TEXT_COLOR_G,SPLASH_TEXT_COLOR_B,1.0f);\r\n\tsplashtext.Print(text);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::DrawSplash(const char *text)\r\n{\r\n\tPrepare2D(CWindow::GetWidth(),CWindow::GetHeight());\r\n\tglPushAttrib(GL_POLYGON_BIT);\r\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\tRenderSplashInner(text);\r\n\tglPopAttrib();\r\n\tRestore3D();\r\n\tglFlush();\r\n\tSwapBuffers(wglGetCurrentDC());\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::SetSplashText(const char *text)\r\n{\r\n\tstrcpy(load_text,text);\r\n\tDrawSplash(text);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::FadeOutSplash()\r\n{\r\n\tint w=CWindow::GetWidth();\r\n\tint h=CWindow::GetHeight();\r\n\tint starttime=timeGetTime();\r\n\tfloat seconds;\r\n\tdo\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tseconds=(float)(timeGetTime()-starttime)*0.001f;\r\n\t\tfloat alpha=min(seconds\/CAMERA_INIT_FADE_TIME,1.0f);\r\n\t\t{\r\n\t\t\tPrepare2D(w,h);\r\n\t\t\tglPushAttrib(GL_POLYGON_BIT);\r\n\t\t\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\t\t\tRenderSplashInner(load_text);\r\n\t\t\tglLoadIdentity();\r\n\t\t\tglDisable(GL_DEPTH_TEST);\r\n\t\t\tglDisable(GL_TEXTURE_2D);\r\n\t\t\tglEnable(GL_BLEND);\r\n\t\t\tglColor4f(0,0,0,alpha);\r\n\t\t\tglBegin(GL_QUADS);\r\n\t\t\t{\r\n\t\t\t\tglVertex2f(0,0);\r\n\t\t\t\tglVertex2f((float)w,0);\r\n\t\t\t\tglVertex2f((float)w,(float)h);\r\n\t\t\t\tglVertex2f(0,(float)h);\r\n\t\t\t}\r\n\t\t\tglEnd();\r\n\t\t\tglPopAttrib();\r\n\t\t\tRestore3D();\r\n\t\t\tglFlush();\r\n\t\t\tSwapBuffers(wglGetCurrentDC());\r\n\t\t}\r\n\t}\r\n\twhile (secondsRefactoring for readability.#include \r\n\r\n#include \r\n\r\n#include \"Settings.h\"\r\n#include \"Main.h\"\r\n#include \"VideoBase.h\"\r\n#include \"Loader.h\"\r\n#include \"Window.h\"\r\n#include \"Text.h\"\r\n#include \"Info.h\"\r\n#include \"Error.h\"\r\n#include \"GamePlay.h\"\r\n\r\n\r\n\r\n#define SPLASH_RESOURCE NULL\r\n#define SPLASH_FILE \"SPLASH.JPG\"\r\n\r\n#define SPLASH_FONT_NAME \"Arial\"\r\n#define SPLASH_FONT_SIZE_AT_H600 12\r\n#define SPLASH_FONT_SIZE (SPLASH_FONT_SIZE_AT_H600*CWindow::GetHeight()\/600)\r\n#define SPLASH_TEXT_SPACING_COEFF 1.75f\r\n\r\n#define SPLASH_TEXT_COLOR_R 0.75f\r\n#define SPLASH_TEXT_COLOR_G 0.75f\r\n#define SPLASH_TEXT_COLOR_B 0.75f\r\n\r\n#define RESTART_ALLOWED true\r\n#define RESTART_TIME 10.0f\r\n\r\n\r\n\r\n\r\nint CGamePlay::splash_tex=0;\r\nchar CGamePlay::load_text[256];\r\nCGamePlay::splash_rect CGamePlay::splash_pos;\r\nCBody CGamePlay::mainbody;\r\nCCamera CGamePlay::camera;\r\nCStarMap CGamePlay::starmap;\r\nCClock CGamePlay::clock;\r\nCLensFlare CGamePlay::lensflare;\r\nbool CGamePlay::flares=false;\r\nbool CGamePlay::planetinfo=false;\r\nCText CGamePlay::splashtext;\r\nCInfo CGamePlay::info;\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nCGamePlay::CGamePlay()\r\n{\r\n}\r\n\r\n\r\n\r\n\r\n\r\nCGamePlay::~CGamePlay()\r\n{\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::Init()\r\n{\r\n\tbool ret=true;\r\n\tif (!splashtext.BuildFTFont(SPLASH_FONT_NAME,SPLASH_FONT_SIZE))\r\n\t\tCError::LogError(WARNING_CODE,\"Failed to load the splash text font - ignoring.\");\r\n\tif (!InitScene())\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t\tOnUserAbortLoad();\r\n\t\telse\r\n\t\t\tCError::LogError(ERROR_CODE,\"Unable to load scene critical data - aborting.\");\r\n\t\tDestroyScene();\r\n\t\tret=false;\r\n\t}\r\n\tFreeSplash();\r\n\tsplashtext.Free();\r\n\treturn ret;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::ShutDown()\r\n{\r\n\tDestroyScene();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::CalcSplashRect()\r\n{\r\n\tint w=CWindow::GetWidth();\r\n\tint h=CWindow::GetHeight();\r\n\tif (w*3>=h*4)\r\n\t{\r\n\t\tsplash_pos.x1=(w-h*4\/3)\/2;\r\n\t\tsplash_pos.x2=(w+h*4\/3)\/2;\r\n\t\tsplash_pos.y1=0;\r\n\t\tsplash_pos.y2=h;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tsplash_pos.x1=0;\r\n\t\tsplash_pos.x2=w;\r\n\t\tsplash_pos.y1=(h-w*3\/4)\/2;\r\n\t\tsplash_pos.y2=(h+w*3\/4)\/2;\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::LoadSplash()\r\n{\r\n\tCalcSplashRect();\r\n\tCLoader loader;\r\n\tloader.WithResource(SPLASH_RESOURCE);\r\n\tsplash_tex=loader.LoadTexture(SPLASH_FILE,NULL,CVideoBase::GetOptMipmaps(),CVideoBase::GetOptLinear());\r\n\treturn (splash_tex>0);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::FreeSplash()\r\n{\r\n\tglDeleteTextures(1,(GLuint*)&splash_tex);\r\n\tsplash_tex=0;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::InitLight()\r\n{\r\n\tGLfloat LightAmbient[4] = { 1.0f, 1.0f, 1.0f, 1.0f };\r\n\tGLfloat LightDiffuse[4] = { 1.0f, 1.0f, 1.0f, 1.0f };\r\n\tGLfloat LightSpecular[4] = { 1.0f, 1.0f, 1.0f, 1.0f };\r\n\tglLightfv(GL_LIGHT1,GL_AMBIENT,LightAmbient);\r\n\tglLightfv(GL_LIGHT1,GL_DIFFUSE,LightDiffuse);\r\n\tglLightfv(GL_LIGHT1,GL_SPECULAR,LightSpecular);\r\n\tglEnable(GL_LIGHT1);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::OnUserAbortLoad()\r\n{\r\n\t\/\/ log new error\r\n\tCError::LogError(ERROR_CODE,\"User aborted load.\");\r\n\t\/\/ get first error, and if it's \"user abort\", clear the log so it's not printed\r\n\tif (CError::ErrorsOccured())\r\n\t{\r\n\t\tint code;\r\n\t\tchar string[ERROR_MAXLEN];\r\n\t\tCError::Rewind();\r\n\t\tCError::GetNextError(&code,string);\r\n\t\tstrlwr(string);\r\n\t\tif (strstr(string,\"user\") && strstr(string,\"abort\"))\r\n\t\t\tCError::Clear();\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::UserAbortedLoad()\r\n{\r\n\tstatic bool userabort=false;\r\n\tif (!userabort)\r\n\t\tuserabort=!MessagePump();\r\n\treturn userabort;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::InitScene()\r\n{\r\n\t{\r\n\t\tSetSplashText(\"Loading splash screen... \");\r\n\t\tif (!LoadSplash())\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the splash screen - ignoring.\");\r\n\t}\r\n\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading bodies... \");\r\n\t\tif (!mainbody.Load())\r\n\t\t{\r\n\t\t\tCError::LogError(ERROR_CODE,\"Failed to load the bodies - aborting.\");\r\n\t\t\treturn false;\r\n\t\t}\r\n\t}\r\n\r\n\tflares=CVideoBase::GetOptLensFlares();\r\n\tif (flares)\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading lens flares... \");\r\n\t\tif (!lensflare.Load(&mainbody))\r\n\t\t{\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the lens flares - ignoring.\");\r\n\t\t\tflares=false;\r\n\t\t}\r\n\t}\r\n\r\n\tplanetinfo=(CSettings::PlanetInfo==TRUE);\r\n\tif (planetinfo)\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading info text font... \");\r\n\t\tif (!info.Load())\r\n\t\t{\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the planet info - ignoring.\");\r\n\t\t\tplanetinfo=false;\r\n\t\t}\r\n\t}\r\n\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading starmap... \");\r\n\t\tif (!starmap.Load())\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the starmap - ignoring.\");\r\n\t}\r\n\r\n\tif (CSettings::ClockOn)\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tSetSplashText(\"Loading clock... \");\r\n\t\tif (!clock.Load())\r\n\t\t\tCError::LogError(WARNING_CODE,\"Failed to load the clock - ignoring.\");\r\n\t}\r\n\r\n\tif (UserAbortedLoad())\r\n\t{\r\n\t\treturn false;\r\n\t}\r\n\tSetSplashText(\"Done.\");\r\n\r\n\tsrand((unsigned int)timeGetTime());\r\n\tInitLight();\r\n\tcamera.Init(&mainbody,(planetinfo?&info:NULL),CWindow::GetWidth(),CWindow::GetHeight());\r\n\treturn FadeOutSplash();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::DestroyScene()\r\n{\r\n\tstarmap.Free();\r\n\tlensflare.Free();\r\n\tflares=false;\r\n\tif (CSettings::ClockOn)\r\n\t\tclock.Free();\r\n\tmainbody.Destroy();\r\n\tinfo.Free();\r\n\tplanetinfo=false;\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::UpdateScene()\r\n{\r\n\tfloat seconds;\r\n\tstatic DWORD starttime=timeGetTime();\r\n\tint milidelta;\r\n\tmilidelta=(timeGetTime()-starttime);\r\n\tseconds=milidelta*0.001f;\r\n\tmainbody.Update(seconds);\r\n\tcamera.Update(seconds);\r\n\tif (flares)\r\n\t\tlensflare.UpdateTime(seconds);\r\n\tif (planetinfo)\r\n\t\tinfo.Update(seconds);\r\n\tif (CSettings::ClockOn==TRUE && milidelta>=500)\r\n\t\tclock.Update();\r\n\tif (RESTART_ALLOWED)\r\n\t{\r\n\t\tif (seconds>=max(RESTART_TIME,CAMERA_INIT_FADE_TIME))\r\n\t\t{\r\n\t\t\tmainbody.Restart();\r\n\t\t\tcamera.Restart(seconds);\r\n\t\t\tif (flares)\r\n\t\t\t\tlensflare.Restart();\r\n\t\t\tif (planetinfo)\r\n\t\t\t\tinfo.Restart();\r\n\t\t\tstarttime=starttime+milidelta;\r\n\t\t}\r\n\t}\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::DrawScene()\r\n{\r\n\tGLfloat LightPosition[4] = { 0.0f, 0.0f, 0.0f, 1.0f };\r\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\tglLoadIdentity();\r\n\tcamera.ApplyRotation();\r\n\tstarmap.Draw();\r\n\tcamera.ApplyTranslation();\r\n\tglLightfv(GL_LIGHT1,GL_POSITION,LightPosition);\r\n\tmainbody.Draw(flares?&lensflare:NULL);\r\n\tif (flares)\r\n\t{\r\n\t\tlensflare.Draw();\r\n\t}\r\n\tif (planetinfo || CSettings::ClockOn)\r\n\t{\r\n\t\tPrepare2D(CWindow::GetWidth(),CWindow::GetHeight());\r\n\t\tif (planetinfo)\r\n\t\t\tinfo.Draw();\r\n\t\tif (CSettings::ClockOn)\r\n\t\t\tclock.Draw();\r\n\t\tRestore3D();\r\n\t}\r\n\tcamera.DrawFade();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::Frame()\r\n{\r\n\tUpdateScene();\r\n\tSwapBuffers(wglGetCurrentDC());\r\n\tDrawScene();\r\n\tglFlush();\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::Prepare2D(int width, int height)\r\n{\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglPushMatrix();\r\n\tglLoadIdentity();\r\n\tgluOrtho2D(0,width,0,height);\r\n\tglMatrixMode(GL_MODELVIEW);\r\n\tglPushAttrib(GL_ENABLE_BIT);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::Restore3D()\r\n{\r\n\tglPopAttrib();\r\n\tglMatrixMode(GL_PROJECTION);\r\n\tglPopMatrix();\r\n\tglMatrixMode(GL_MODELVIEW);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::UpdateSplash(const char *subtext)\r\n{\r\n\tchar text[256];\r\n\tstrcpy(text,load_text);\r\n\tstrcat(text,subtext);\r\n\tDrawSplash(text);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::RenderSplashInner(const char *text)\r\n{\r\n\tglLoadIdentity();\r\n\tglDisable(GL_LIGHTING);\r\n\tglDisable(GL_DEPTH_TEST);\r\n\tglDisable(GL_CULL_FACE);\r\n\tglEnable(GL_TEXTURE_2D);\r\n\tif (splash_tex>0)\r\n\t{\r\n\t\tglColor4f(1,1,1,1);\r\n\t\tglBindTexture(GL_TEXTURE_2D,splash_tex);\r\n\t\tglBegin(GL_QUADS);\r\n\t\t{\r\n\t\t\tglTexCoord2f(0,0.25f);\r\n\t\t\tglVertex2f((float)splash_pos.x1,(float)splash_pos.y1);\r\n\t\t\tglTexCoord2f(1,0.25f);\r\n\t\t\tglVertex2f((float)splash_pos.x2,(float)splash_pos.y1);\r\n\t\t\tglTexCoord2f(1,1);\r\n\t\t\tglVertex2f((float)splash_pos.x2,(float)splash_pos.y2);\r\n\t\t\tglTexCoord2f(0,1);\r\n\t\t\tglVertex2f((float)splash_pos.x1,(float)splash_pos.y2);\r\n\t\t}\r\n\t\tglEnd();\r\n\t}\r\n\tint w=CWindow::GetWidth();\r\n\tfloat th;\r\n\tsplashtext.GetTextSize(text,NULL,&th);\r\n\tint text_under_height=(int)(th*(SPLASH_TEXT_SPACING_COEFF-1.0f));\r\n\tint band_height=(int)(th*(2.0*SPLASH_TEXT_SPACING_COEFF-1.0f));\r\n\tglDisable(GL_TEXTURE_2D);\r\n\tglColor4f(0,0,0,1);\r\n\tglBegin(GL_QUADS);\r\n\t{\r\n\t\tglVertex2f(0.0f,0.0f);\r\n\t\tglVertex2f((float)w,0.0f);\r\n\t\tglVertex2f((float)w,(float)band_height);\r\n\t\tglVertex2f(0.0f,(float)band_height);\r\n\t}\r\n\tglEnd();\r\n\tglEnable(GL_TEXTURE_2D);\r\n\tglEnable(GL_BLEND);\r\n\tglTranslatef(0.0f,(float)text_under_height,0.0f);\r\n\tglColor4f(SPLASH_TEXT_COLOR_R,SPLASH_TEXT_COLOR_G,SPLASH_TEXT_COLOR_B,1.0f);\r\n\tsplashtext.Print(text);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::DrawSplash(const char *text)\r\n{\r\n\tPrepare2D(CWindow::GetWidth(),CWindow::GetHeight());\r\n\tglPushAttrib(GL_POLYGON_BIT);\r\n\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\tRenderSplashInner(text);\r\n\tglPopAttrib();\r\n\tRestore3D();\r\n\tglFlush();\r\n\tSwapBuffers(wglGetCurrentDC());\r\n}\r\n\r\n\r\n\r\n\r\n\r\nvoid CGamePlay::SetSplashText(const char *text)\r\n{\r\n\tstrcpy(load_text,text);\r\n\tDrawSplash(text);\r\n}\r\n\r\n\r\n\r\n\r\n\r\nbool CGamePlay::FadeOutSplash()\r\n{\r\n\tint w=CWindow::GetWidth();\r\n\tint h=CWindow::GetHeight();\r\n\tint starttime=timeGetTime();\r\n\tfloat seconds;\r\n\tdo\r\n\t{\r\n\t\tif (UserAbortedLoad())\r\n\t\t{\r\n\t\t\treturn false;\r\n\t\t}\r\n\t\tseconds=(float)(timeGetTime()-starttime)*0.001f;\r\n\t\tfloat alpha=min(seconds\/CAMERA_INIT_FADE_TIME,1.0f);\r\n\t\t{\r\n\t\t\tPrepare2D(w,h);\r\n\t\t\tglPushAttrib(GL_POLYGON_BIT);\r\n\t\t\tglClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);\r\n\t\t\tRenderSplashInner(load_text);\r\n\t\t\tglLoadIdentity();\r\n\t\t\tglDisable(GL_DEPTH_TEST);\r\n\t\t\tglDisable(GL_TEXTURE_2D);\r\n\t\t\tglEnable(GL_BLEND);\r\n\t\t\tglColor4f(0,0,0,alpha);\r\n\t\t\tglBegin(GL_QUADS);\r\n\t\t\t{\r\n\t\t\t\tglVertex2f(0,0);\r\n\t\t\t\tglVertex2f((float)w,0);\r\n\t\t\t\tglVertex2f((float)w,(float)h);\r\n\t\t\t\tglVertex2f(0,(float)h);\r\n\t\t\t}\r\n\t\t\tglEnd();\r\n\t\t\tglPopAttrib();\r\n\t\t\tRestore3D();\r\n\t\t\tglFlush();\r\n\t\t\tSwapBuffers(wglGetCurrentDC());\r\n\t\t}\r\n\t}\r\n\twhile (seconds"} {"text":"Correct out-of-order transform instances (#2025)<|endoftext|>"} {"text":"\/** \n * @file llnotificationsconsole.cpp\n * @brief Debugging console for unified notifications.\n *\n * $LicenseInfo:firstyear=2003&license=viewergpl$\n * \n * Copyright (c) 2003-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llfloaternotificationsconsole.h\"\n#include \"llnotifications.h\"\n#include \"lluictrlfactory.h\"\n#include \"llbutton.h\"\n#include \"llscrolllistctrl.h\"\n#include \"llscrolllistitem.h\"\n#include \"llpanel.h\"\n#include \"llcombobox.h\"\n\nconst S32 NOTIFICATION_PANEL_HEADER_HEIGHT = 20;\nconst S32 HEADER_PADDING = 38;\n\nclass LLNotificationChannelPanel : public LLPanel\n{\npublic:\n\tLLNotificationChannelPanel(const std::string& channel_name);\n\tBOOL postBuild();\n\nprivate:\n\tbool update(const LLSD& payload, bool passed_filter);\n\tstatic void toggleClick(void* user_data);\n\tstatic void onClickNotification(void* user_data);\n\tstatic void onClickNotificationReject(void* user_data);\n\tLLNotificationChannelPtr mChannelPtr;\n\tLLNotificationChannelPtr mChannelRejectsPtr;\n};\n\nLLNotificationChannelPanel::LLNotificationChannelPanel(const std::string& channel_name) \n\t: LLPanel()\n{\n\tmChannelPtr = LLNotifications::instance().getChannel(channel_name);\n\tmChannelRejectsPtr = LLNotificationChannelPtr(\n\t\tLLNotificationChannel::buildChannel(channel_name + \"rejects\", mChannelPtr->getParentChannelName(),\n\t\t\t\t\t\t\t\t\t\t\t!boost::bind(mChannelPtr->getFilter(), _1)));\n\tLLUICtrlFactory::instance().buildPanel(this, \"panel_notifications_channel.xml\");\n}\n\nBOOL LLNotificationChannelPanel::postBuild()\n{\n\tLLButton* header_button = getChild(\"header\");\n\theader_button->setLabel(mChannelPtr->getName());\n\theader_button->setClickedCallback(toggleClick, this);\n\n\tmChannelPtr->connectChanged(boost::bind(&LLNotificationChannelPanel::update, this, _1, true));\n\tmChannelRejectsPtr->connectChanged(boost::bind(&LLNotificationChannelPanel::update, this, _1, false));\n\n\tLLScrollListCtrl* scroll = getChild(\"notifications_list\");\n\tscroll->setDoubleClickCallback(onClickNotification, this);\n\tscroll->setRect(LLRect( getRect().mLeft, getRect().mTop, getRect().mRight, 0));\n\tscroll = getChild(\"notification_rejects_list\");\n\tscroll->setDoubleClickCallback(onClickNotificationReject, this);\n\tscroll->setRect(LLRect( getRect().mLeft, getRect().mTop, getRect().mRight, 0));\n\treturn TRUE;\n}\n\n\/\/static\nvoid LLNotificationChannelPanel::toggleClick(void *user_data)\n{\n\tLLNotificationChannelPanel* self = (LLNotificationChannelPanel*)user_data;\n\tif (!self) return;\n\t\n\tLLButton* header_button = self->getChild(\"header\");\n\t\n\tLLLayoutStack* stack = dynamic_cast(self->getParent());\n\tif (stack)\n\t{\n\t\tstack->collapsePanel(self, header_button->getToggleState());\n\t}\n\n\t\/\/ turn off tab stop for collapsed panel\n\tself->getChild(\"notifications_list\")->setTabStop(!header_button->getToggleState());\n\tself->getChild(\"notifications_list\")->setVisible(!header_button->getToggleState());\n\tself->getChild(\"notification_rejects_list\")->setTabStop(!header_button->getToggleState());\n\tself->getChild(\"notification_rejects_list\")->setVisible(!header_button->getToggleState());\n}\n\n\/*static*\/\nvoid LLNotificationChannelPanel::onClickNotification(void* user_data)\n{\n\tLLNotificationChannelPanel* self = (LLNotificationChannelPanel*)user_data;\n\tif (!self) return;\n\tLLScrollListItem* firstselected = self->getChild(\"notifications_list\")->getFirstSelected();\n\tllassert(firstselected);\n\tif (firstselected)\n\t{\n\t\tvoid* data = firstselected->getUserdata();\n\t\tif (data)\n\t\t{\n\t\t\tgFloaterView->getParentFloater(self)->addDependentFloater(new LLFloaterNotification((LLNotification*)data), TRUE);\n\t\t}\n\t}\n}\n\n\/*static*\/\nvoid LLNotificationChannelPanel::onClickNotificationReject(void* user_data)\n{\n\tLLNotificationChannelPanel* self = (LLNotificationChannelPanel*)user_data;\n\tif (!self) return;\n\tLLScrollListItem* firstselected = self->getChild(\"notification_rejects_list\")->getFirstSelected();\n\tllassert(firstselected);\n\tif (firstselected)\n\t{\n\t\tvoid* data = firstselected->getUserdata();\n\t\tif (data)\n\t\t{\n\t\t\tgFloaterView->getParentFloater(self)->addDependentFloater(new LLFloaterNotification((LLNotification*)data), TRUE);\n\t\t}\n\t}\n}\n\nbool LLNotificationChannelPanel::update(const LLSD& payload, bool passed_filter)\n{\n\tLLNotificationPtr notification = LLNotifications::instance().find(payload[\"id\"].asUUID());\n\tif (notification)\n\t{\n\t\tLLSD row;\n\t\trow[\"columns\"][0][\"value\"] = notification->getName();\n\t\trow[\"columns\"][0][\"column\"] = \"name\";\n\n\t\trow[\"columns\"][1][\"value\"] = notification->getMessage();\n\t\trow[\"columns\"][1][\"column\"] = \"content\";\n\n\t\trow[\"columns\"][2][\"value\"] = notification->getDate();\n\t\trow[\"columns\"][2][\"column\"] = \"date\";\n\t\trow[\"columns\"][2][\"type\"] = \"date\";\n\n\t\tLLScrollListItem* sli = passed_filter ? \n\t\t\tgetChild(\"notifications_list\")->addElement(row) :\n\t\t\tgetChild(\"notification_rejects_list\")->addElement(row);\n\t\tsli->setUserdata(&(*notification));\n\t}\n\n\treturn false;\n}\n\n\/\/\n\/\/ LLFloaterNotificationConsole\n\/\/\nLLFloaterNotificationConsole::LLFloaterNotificationConsole(const LLSD& key)\n: LLFloater(key)\n{\n\tmCommitCallbackRegistrar.add(\"ClickAdd\", boost::bind(&LLFloaterNotificationConsole::onClickAdd, this));\t\n\n\t\/\/LLUICtrlFactory::instance().buildFloater(this, \"floater_notifications_console.xml\");\n}\n\nBOOL LLFloaterNotificationConsole::postBuild()\n{\n\t\/\/ these are in the order of processing\n\taddChannel(\"Unexpired\");\n\taddChannel(\"Ignore\");\n\taddChannel(\"Visible\", true);\n\t\/\/ all the ones below attach to the Visible channel\n\taddChannel(\"History\");\n\taddChannel(\"Alerts\");\n\taddChannel(\"AlertModal\");\n\taddChannel(\"Group Notifications\");\n\taddChannel(\"Notifications\");\n\taddChannel(\"NotificationTips\");\n\n\/\/\tgetChild(\"add_notification\")->setClickedCallback(onClickAdd, this);\n\n\tLLComboBox* notifications = getChild(\"notification_types\");\n\tLLNotifications::TemplateNames names = LLNotifications::instance().getTemplateNames();\n\tfor (LLNotifications::TemplateNames::iterator template_it = names.begin();\n\t\ttemplate_it != names.end();\n\t\t++template_it)\n\t{\n\t\tnotifications->add(*template_it);\n\t}\n\tnotifications->sortByName();\n\n\treturn TRUE;\n}\n\nvoid LLFloaterNotificationConsole::addChannel(const std::string& name, bool open)\n{\n\tLLLayoutStack& stack = getChildRef(\"notification_channels\");\n\tLLNotificationChannelPanel* panelp = new LLNotificationChannelPanel(name);\n\tstack.addPanel(panelp, 0, NOTIFICATION_PANEL_HEADER_HEIGHT, S32_MAX, S32_MAX, TRUE, TRUE, LLLayoutStack::ANIMATE);\n\n\tLLButton& header_button = panelp->getChildRef(\"header\");\n\theader_button.setToggleState(!open);\n\tstack.collapsePanel(panelp, !open);\n\n\tupdateResizeLimits();\n}\n\nvoid LLFloaterNotificationConsole::removeChannel(const std::string& name)\n{\n\tLLPanel* panelp = getChild(name);\n\tgetChildRef(\"notification_channels\").removePanel(panelp);\n\tdelete panelp;\n\n\tupdateResizeLimits();\n}\n\n\/\/static \nvoid LLFloaterNotificationConsole::updateResizeLimits()\n{\n\tconst LLFloater::Params& floater_params = LLFloater::getDefaultParams();\n\tS32 floater_header_size = floater_params.header_height;\n\n\tLLLayoutStack& stack = getChildRef(\"notification_channels\");\n\tsetResizeLimits(getMinWidth(), floater_header_size + HEADER_PADDING + ((NOTIFICATION_PANEL_HEADER_HEIGHT + 3) * stack.getNumPanels()));\n}\n\nvoid LLFloaterNotificationConsole::onClickAdd()\n{\n\tstd::string message_name = getChild(\"notification_types\")->getValue().asString();\n\tif (!message_name.empty())\n\t{\n\t\tLLNotifications::instance().add(message_name, LLSD(), LLSD());\n\t}\n}\n\n\n\/\/=============== LLFloaterNotification ================\n\nLLFloaterNotification::LLFloaterNotification(LLNotification* note) \n:\tLLFloater(LLSD()),\n\tmNote(note)\n{\n\tLLUICtrlFactory::instance().buildFloater(this, \"floater_notification.xml\", NULL);\n}\n\nBOOL LLFloaterNotification::postBuild()\n{\n\tsetTitle(mNote->getName());\n\tgetChild(\"payload\")->setValue(mNote->getMessage());\n\n\tLLComboBox* responses_combo = getChild(\"response\");\n\tLLCtrlListInterface* response_list = responses_combo->getListInterface();\n\tLLNotificationFormPtr form(mNote->getForm());\n\tif(!form)\n\t{\n\t\treturn TRUE;\n\t}\n\n\tresponses_combo->setCommitCallback(onCommitResponse, this);\n\n\tLLSD form_sd = form->asLLSD();\n\n\tfor (LLSD::array_const_iterator form_item = form_sd.beginArray(); form_item != form_sd.endArray(); ++form_item)\n\t{\n\t\tif ( (*form_item)[\"type\"].asString() != \"button\") continue;\n\t\tstd::string text = (*form_item)[\"text\"].asString();\n\t\tresponse_list->addSimpleElement(text);\n\t}\n\n\treturn TRUE;\n}\n\nvoid LLFloaterNotification::respond()\n{\n\tLLComboBox* responses_combo = getChild(\"response\");\n\tLLCtrlListInterface* response_list = responses_combo->getListInterface();\n\tconst std::string& trigger = response_list->getSelectedValue().asString();\n\t\/\/llinfos << trigger << llendl;\n\n\tLLSD response = mNote->getResponseTemplate();\n\tresponse[trigger] = true;\n\tmNote->respond(response);\n}\nEXT-7460 FIXED (VWR-19451) Viewer crashes when opening notifications console.\/** \n * @file llnotificationsconsole.cpp\n * @brief Debugging console for unified notifications.\n *\n * $LicenseInfo:firstyear=2003&license=viewergpl$\n * \n * Copyright (c) 2003-2009, Linden Research, Inc.\n * \n * Second Life Viewer Source Code\n * The source code in this file (\"Source Code\") is provided by Linden Lab\n * to you under the terms of the GNU General Public License, version 2.0\n * (\"GPL\"), unless you have obtained a separate licensing agreement\n * (\"Other License\"), formally executed by you and Linden Lab. Terms of\n * the GPL can be found in doc\/GPL-license.txt in this distribution, or\n * online at http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/gplv2\n * \n * There are special exceptions to the terms and conditions of the GPL as\n * it is applied to this Source Code. View the full text of the exception\n * in the file doc\/FLOSS-exception.txt in this software distribution, or\n * online at\n * http:\/\/secondlifegrid.net\/programs\/open_source\/licensing\/flossexception\n * \n * By copying, modifying or distributing this software, you acknowledge\n * that you have read and understood your obligations described above,\n * and agree to abide by those obligations.\n * \n * ALL LINDEN LAB SOURCE CODE IS PROVIDED \"AS IS.\" LINDEN LAB MAKES NO\n * WARRANTIES, EXPRESS, IMPLIED OR OTHERWISE, REGARDING ITS ACCURACY,\n * COMPLETENESS OR PERFORMANCE.\n * $\/LicenseInfo$\n *\/\n\n#include \"llviewerprecompiledheaders.h\"\n#include \"llfloaternotificationsconsole.h\"\n#include \"llnotifications.h\"\n#include \"lluictrlfactory.h\"\n#include \"llbutton.h\"\n#include \"llscrolllistctrl.h\"\n#include \"llscrolllistitem.h\"\n#include \"llpanel.h\"\n#include \"llcombobox.h\"\n\nconst S32 NOTIFICATION_PANEL_HEADER_HEIGHT = 20;\nconst S32 HEADER_PADDING = 38;\n\nclass LLNotificationChannelPanel : public LLPanel\n{\npublic:\n\tLLNotificationChannelPanel(const std::string& channel_name);\n\tBOOL postBuild();\n\nprivate:\n\tbool update(const LLSD& payload, bool passed_filter);\n\tstatic void toggleClick(void* user_data);\n\tstatic void onClickNotification(void* user_data);\n\tstatic void onClickNotificationReject(void* user_data);\n\tLLNotificationChannelPtr mChannelPtr;\n\tLLNotificationChannelPtr mChannelRejectsPtr;\n};\n\nLLNotificationChannelPanel::LLNotificationChannelPanel(const std::string& channel_name) \n\t: LLPanel()\n{\n\tmChannelPtr = LLNotifications::instance().getChannel(channel_name);\n\tmChannelRejectsPtr = LLNotificationChannelPtr(\n\t\tLLNotificationChannel::buildChannel(channel_name + \"rejects\", mChannelPtr->getParentChannelName(),\n\t\t\t\t\t\t\t\t\t\t\t!boost::bind(mChannelPtr->getFilter(), _1)));\n\tLLUICtrlFactory::instance().buildPanel(this, \"panel_notifications_channel.xml\");\n}\n\nBOOL LLNotificationChannelPanel::postBuild()\n{\n\tLLButton* header_button = getChild(\"header\");\n\theader_button->setLabel(mChannelPtr->getName());\n\theader_button->setClickedCallback(toggleClick, this);\n\n\tmChannelPtr->connectChanged(boost::bind(&LLNotificationChannelPanel::update, this, _1, true));\n\tmChannelRejectsPtr->connectChanged(boost::bind(&LLNotificationChannelPanel::update, this, _1, false));\n\n\tLLScrollListCtrl* scroll = getChild(\"notifications_list\");\n\tscroll->setDoubleClickCallback(onClickNotification, this);\n\tscroll->setRect(LLRect( getRect().mLeft, getRect().mTop, getRect().mRight, 0));\n\tscroll = getChild(\"notification_rejects_list\");\n\tscroll->setDoubleClickCallback(onClickNotificationReject, this);\n\tscroll->setRect(LLRect( getRect().mLeft, getRect().mTop, getRect().mRight, 0));\n\treturn TRUE;\n}\n\n\/\/static\nvoid LLNotificationChannelPanel::toggleClick(void *user_data)\n{\n\tLLNotificationChannelPanel* self = (LLNotificationChannelPanel*)user_data;\n\tif (!self) return;\n\t\n\tLLButton* header_button = self->getChild(\"header\");\n\t\n\tLLLayoutStack* stack = dynamic_cast(self->getParent());\n\tif (stack)\n\t{\n\t\tstack->collapsePanel(self, header_button->getToggleState());\n\t}\n\n\t\/\/ turn off tab stop for collapsed panel\n\tself->getChild(\"notifications_list\")->setTabStop(!header_button->getToggleState());\n\tself->getChild(\"notifications_list\")->setVisible(!header_button->getToggleState());\n\tself->getChild(\"notification_rejects_list\")->setTabStop(!header_button->getToggleState());\n\tself->getChild(\"notification_rejects_list\")->setVisible(!header_button->getToggleState());\n}\n\n\/*static*\/\nvoid LLNotificationChannelPanel::onClickNotification(void* user_data)\n{\n\tLLNotificationChannelPanel* self = (LLNotificationChannelPanel*)user_data;\n\tif (!self) return;\n\tLLScrollListItem* firstselected = self->getChild(\"notifications_list\")->getFirstSelected();\n\tllassert(firstselected);\n\tif (firstselected)\n\t{\n\t\tvoid* data = firstselected->getUserdata();\n\t\tif (data)\n\t\t{\n\t\t\tgFloaterView->getParentFloater(self)->addDependentFloater(new LLFloaterNotification((LLNotification*)data), TRUE);\n\t\t}\n\t}\n}\n\n\/*static*\/\nvoid LLNotificationChannelPanel::onClickNotificationReject(void* user_data)\n{\n\tLLNotificationChannelPanel* self = (LLNotificationChannelPanel*)user_data;\n\tif (!self) return;\n\tLLScrollListItem* firstselected = self->getChild(\"notification_rejects_list\")->getFirstSelected();\n\tllassert(firstselected);\n\tif (firstselected)\n\t{\n\t\tvoid* data = firstselected->getUserdata();\n\t\tif (data)\n\t\t{\n\t\t\tgFloaterView->getParentFloater(self)->addDependentFloater(new LLFloaterNotification((LLNotification*)data), TRUE);\n\t\t}\n\t}\n}\n\nbool LLNotificationChannelPanel::update(const LLSD& payload, bool passed_filter)\n{\n\tLLNotificationPtr notification = LLNotifications::instance().find(payload[\"id\"].asUUID());\n\tif (notification)\n\t{\n\t\tLLSD row;\n\t\trow[\"columns\"][0][\"value\"] = notification->getName();\n\t\trow[\"columns\"][0][\"column\"] = \"name\";\n\n\t\trow[\"columns\"][1][\"value\"] = notification->getMessage();\n\t\trow[\"columns\"][1][\"column\"] = \"content\";\n\n\t\trow[\"columns\"][2][\"value\"] = notification->getDate();\n\t\trow[\"columns\"][2][\"column\"] = \"date\";\n\t\trow[\"columns\"][2][\"type\"] = \"date\";\n\n\t\tLLScrollListItem* sli = passed_filter ? \n\t\t\tgetChild(\"notifications_list\")->addElement(row) :\n\t\t\tgetChild(\"notification_rejects_list\")->addElement(row);\n\t\tsli->setUserdata(&(*notification));\n\t}\n\n\treturn false;\n}\n\n\/\/\n\/\/ LLFloaterNotificationConsole\n\/\/\nLLFloaterNotificationConsole::LLFloaterNotificationConsole(const LLSD& key)\n: LLFloater(key)\n{\n\tmCommitCallbackRegistrar.add(\"ClickAdd\", boost::bind(&LLFloaterNotificationConsole::onClickAdd, this));\t\n\n\t\/\/LLUICtrlFactory::instance().buildFloater(this, \"floater_notifications_console.xml\");\n}\n\nBOOL LLFloaterNotificationConsole::postBuild()\n{\n\t\/\/ these are in the order of processing\n\taddChannel(\"Unexpired\");\n\taddChannel(\"Ignore\");\n\taddChannel(\"Visible\", true);\n\t\/\/ all the ones below attach to the Visible channel\n\taddChannel(\"Persistent\");\n\taddChannel(\"Alerts\");\n\taddChannel(\"AlertModal\");\n\taddChannel(\"Group Notifications\");\n\taddChannel(\"Notifications\");\n\taddChannel(\"NotificationTips\");\n\n\/\/\tgetChild(\"add_notification\")->setClickedCallback(onClickAdd, this);\n\n\tLLComboBox* notifications = getChild(\"notification_types\");\n\tLLNotifications::TemplateNames names = LLNotifications::instance().getTemplateNames();\n\tfor (LLNotifications::TemplateNames::iterator template_it = names.begin();\n\t\ttemplate_it != names.end();\n\t\t++template_it)\n\t{\n\t\tnotifications->add(*template_it);\n\t}\n\tnotifications->sortByName();\n\n\treturn TRUE;\n}\n\nvoid LLFloaterNotificationConsole::addChannel(const std::string& name, bool open)\n{\n\tLLLayoutStack& stack = getChildRef(\"notification_channels\");\n\tLLNotificationChannelPanel* panelp = new LLNotificationChannelPanel(name);\n\tstack.addPanel(panelp, 0, NOTIFICATION_PANEL_HEADER_HEIGHT, S32_MAX, S32_MAX, TRUE, TRUE, LLLayoutStack::ANIMATE);\n\n\tLLButton& header_button = panelp->getChildRef(\"header\");\n\theader_button.setToggleState(!open);\n\tstack.collapsePanel(panelp, !open);\n\n\tupdateResizeLimits();\n}\n\nvoid LLFloaterNotificationConsole::removeChannel(const std::string& name)\n{\n\tLLPanel* panelp = getChild(name);\n\tgetChildRef(\"notification_channels\").removePanel(panelp);\n\tdelete panelp;\n\n\tupdateResizeLimits();\n}\n\n\/\/static \nvoid LLFloaterNotificationConsole::updateResizeLimits()\n{\n\tconst LLFloater::Params& floater_params = LLFloater::getDefaultParams();\n\tS32 floater_header_size = floater_params.header_height;\n\n\tLLLayoutStack& stack = getChildRef(\"notification_channels\");\n\tsetResizeLimits(getMinWidth(), floater_header_size + HEADER_PADDING + ((NOTIFICATION_PANEL_HEADER_HEIGHT + 3) * stack.getNumPanels()));\n}\n\nvoid LLFloaterNotificationConsole::onClickAdd()\n{\n\tstd::string message_name = getChild(\"notification_types\")->getValue().asString();\n\tif (!message_name.empty())\n\t{\n\t\tLLNotifications::instance().add(message_name, LLSD(), LLSD());\n\t}\n}\n\n\n\/\/=============== LLFloaterNotification ================\n\nLLFloaterNotification::LLFloaterNotification(LLNotification* note) \n:\tLLFloater(LLSD()),\n\tmNote(note)\n{\n\tLLUICtrlFactory::instance().buildFloater(this, \"floater_notification.xml\", NULL);\n}\n\nBOOL LLFloaterNotification::postBuild()\n{\n\tsetTitle(mNote->getName());\n\tgetChild(\"payload\")->setValue(mNote->getMessage());\n\n\tLLComboBox* responses_combo = getChild(\"response\");\n\tLLCtrlListInterface* response_list = responses_combo->getListInterface();\n\tLLNotificationFormPtr form(mNote->getForm());\n\tif(!form)\n\t{\n\t\treturn TRUE;\n\t}\n\n\tresponses_combo->setCommitCallback(onCommitResponse, this);\n\n\tLLSD form_sd = form->asLLSD();\n\n\tfor (LLSD::array_const_iterator form_item = form_sd.beginArray(); form_item != form_sd.endArray(); ++form_item)\n\t{\n\t\tif ( (*form_item)[\"type\"].asString() != \"button\") continue;\n\t\tstd::string text = (*form_item)[\"text\"].asString();\n\t\tresponse_list->addSimpleElement(text);\n\t}\n\n\treturn TRUE;\n}\n\nvoid LLFloaterNotification::respond()\n{\n\tLLComboBox* responses_combo = getChild(\"response\");\n\tLLCtrlListInterface* response_list = responses_combo->getListInterface();\n\tconst std::string& trigger = response_list->getSelectedValue().asString();\n\t\/\/llinfos << trigger << llendl;\n\n\tLLSD response = mNote->getResponseTemplate();\n\tresponse[trigger] = true;\n\tmNote->respond(response);\n}\n<|endoftext|>"} {"text":" \/*************************************************************************\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accpreview.cxx,v $\n *\n * $Revision: 1.10 $\n *\n * last change: $Author: hr $ $Date: 2007-09-27 08:23:51 $\n *\n * The Contents of this file are made available subject to\n * the terms of GNU Lesser General Public License Version 2.1.\n *\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2005 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n\n#ifndef _SV_SVAPP_HXX\n#include \n#endif\n\n#ifndef _RTL_UUID_H_\n#include \n#endif\n#ifndef _ACCESS_HRC\n#include \"access.hrc\"\n#endif\n#ifndef _ACCPREVIEW_HXX\n#include \n#endif\n\n\nconst sal_Char sServiceName[] = \"com.sun.star.text.AccessibleTextDocumentPageView\";\nconst sal_Char sImplementationName[] = \"com.sun.star.comp.Writer.SwAccessibleDocumentPageView\";\n\n\n\/\/ using namespace accessibility;\n\nusing ::com::sun::star::lang::IndexOutOfBoundsException;\nusing ::com::sun::star::uno::RuntimeException;\nusing ::com::sun::star::uno::Sequence;\nusing ::rtl::OUString;\n\n\n\n\n\/\/\n\/\/ SwAccessiblePreview\n\/\/\n\nSwAccessiblePreview::SwAccessiblePreview( SwAccessibleMap *pMp ) :\n SwAccessibleDocumentBase( pMp )\n{\n SetName( GetResource( STR_ACCESS_DOC_NAME ) );\n}\n\nSwAccessiblePreview::~SwAccessiblePreview()\n{\n}\n\nOUString SwAccessiblePreview::getImplementationName( )\n throw( RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( sImplementationName ) );\n}\n\nsal_Bool SwAccessiblePreview::supportsService( const OUString& rServiceName )\n throw( RuntimeException )\n{\n return rServiceName.equalsAsciiL(\n RTL_CONSTASCII_STRINGPARAM( sServiceName) ) ||\n rServiceName.equalsAsciiL(\n RTL_CONSTASCII_STRINGPARAM( sAccessibleServiceName ) );\n}\n\nSequence SwAccessiblePreview::getSupportedServiceNames( )\n throw( RuntimeException )\n{\n Sequence aSeq( 2 );\n aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( sServiceName ) );\n aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( sAccessibleServiceName ) );\n return aSeq;\n}\n\nSequence< sal_Int8 > SAL_CALL SwAccessiblePreview::getImplementationId()\n throw(RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\nINTEGRATION: CWS changefileheader (1.10.242); FILE MERGED 2008\/04\/01 15:56:43 thb 1.10.242.3: #i85898# Stripping all external header guards 2008\/04\/01 12:53:46 thb 1.10.242.2: #i85898# Stripping all external header guards 2008\/03\/31 16:53:39 rt 1.10.242.1: #i87441# Change license header to LPGL v3. \/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2008 by Sun Microsystems, Inc.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * $RCSfile: accpreview.cxx,v $\n * $Revision: 1.11 $\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\/\/ MARKER(update_precomp.py): autogen include statement, do not remove\n#include \"precompiled_sw.hxx\"\n\n\n#include \n#include \n#ifndef _ACCESS_HRC\n#include \"access.hrc\"\n#endif\n#include \n\n\nconst sal_Char sServiceName[] = \"com.sun.star.text.AccessibleTextDocumentPageView\";\nconst sal_Char sImplementationName[] = \"com.sun.star.comp.Writer.SwAccessibleDocumentPageView\";\n\n\n\/\/ using namespace accessibility;\n\nusing ::com::sun::star::lang::IndexOutOfBoundsException;\nusing ::com::sun::star::uno::RuntimeException;\nusing ::com::sun::star::uno::Sequence;\nusing ::rtl::OUString;\n\n\n\n\n\/\/\n\/\/ SwAccessiblePreview\n\/\/\n\nSwAccessiblePreview::SwAccessiblePreview( SwAccessibleMap *pMp ) :\n SwAccessibleDocumentBase( pMp )\n{\n SetName( GetResource( STR_ACCESS_DOC_NAME ) );\n}\n\nSwAccessiblePreview::~SwAccessiblePreview()\n{\n}\n\nOUString SwAccessiblePreview::getImplementationName( )\n throw( RuntimeException )\n{\n return OUString( RTL_CONSTASCII_USTRINGPARAM( sImplementationName ) );\n}\n\nsal_Bool SwAccessiblePreview::supportsService( const OUString& rServiceName )\n throw( RuntimeException )\n{\n return rServiceName.equalsAsciiL(\n RTL_CONSTASCII_STRINGPARAM( sServiceName) ) ||\n rServiceName.equalsAsciiL(\n RTL_CONSTASCII_STRINGPARAM( sAccessibleServiceName ) );\n}\n\nSequence SwAccessiblePreview::getSupportedServiceNames( )\n throw( RuntimeException )\n{\n Sequence aSeq( 2 );\n aSeq[0] = OUString( RTL_CONSTASCII_USTRINGPARAM( sServiceName ) );\n aSeq[1] = OUString( RTL_CONSTASCII_USTRINGPARAM( sAccessibleServiceName ) );\n return aSeq;\n}\n\nSequence< sal_Int8 > SAL_CALL SwAccessiblePreview::getImplementationId()\n throw(RuntimeException)\n{\n vos::OGuard aGuard(Application::GetSolarMutex());\n static Sequence< sal_Int8 > aId( 16 );\n static sal_Bool bInit = sal_False;\n if(!bInit)\n {\n rtl_createUuid( (sal_uInt8 *)(aId.getArray() ), 0, sal_True );\n bInit = sal_True;\n }\n return aId;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n\nlong estimate_a(long *pack) {\n return (\n 4 + pack[0] * 8 +\n 4 + 1 + pack[1] * 8 * 5 +\n 4 + 1 + pack[2] * 8 * 5 + 3 * 11 * 1 +\n 4 + 1 + pack[3] * 8 * 5 + 3 * 11 * 2 +\n 4 + 1 + pack[4] * 8 * 5 + 3 * 11 * 4 +\n 4 + 1 + pack[5] * 8 * 5 + 3 * 11 * 6\n );\n}\n\nlong estimate_b(long *pack) {\n return (\n 4 + pack[0] * 9 +\n 4 + 1 + pack[1] * 9 * 5 +\n 4 + 1 + pack[2] * 9 * 5 + 4 * 2 * 3 * 8 * 1 +\n 4 + 1 + pack[3] * 9 * 5 + 4 * 2 * 3 * 8 * 2 +\n 4 + 1 + pack[4] * 9 * 5 + 4 * 2 * 3 * 8 * 4 +\n 4 + 1 + pack[5] * 9 * 5 + 4 * 2 * 3 * 8 * 6\n );\n}\n\nint main(int argc, char **argv) {\n if (argc <= 1) {\n std::cout << \"Usage: stat \" << std::endl;\n return 1;\n }\n\n kyotocabinet::TreeDB db;\n\n if (!db.open(argv[1], kyotocabinet::TreeDB::OREADER)) {\n std::cout << \"Could not open database.\" << std::endl;\n return 2;\n }\n\n std::auto_ptr cur(db.cursor());\n cur->jump();\n\n std::string key, value;\n\n long pack[] = {0, 0, 0, 0, 0, 0};\n long total = 0;\n\n std::cout << \"Scanning ...\" << std::endl;\n\n while (cur->get(&key, &value, true)) {\n total++;\n if (value.size() == 8) {\n pack[0]++;\n } else {\n pack[value.at(0)]++;\n }\n\n if (total % 50000 == 0) {\n std::cerr << \".\";\n }\n }\n\n std::cerr << std::endl;\n\n for (int i = 0; i < 5; i++) {\n std::cout << \"Pack format \" << i << \": \" << pack[i] << \" nodes \" << std::endl;\n }\n\n std::cout << \"Unique positions: \" << total << std::endl;\n\n std::cout << std::endl;\n\n std::cout << \"Scheme A: \" << estimate_a(pack) << \" bytes\" << std::endl;\n std::cout << \"Scheme B: \" << estimate_b(pack) << \" bytes\" << std::endl;\n std::cout << \"B\/A: \" << ((double)estimate_b(pack)\/estimate_a(pack)) << std::endl;\n\n return 0;\n}\nDo not require lock for stats#include \n#include \n\n#include \n\nlong estimate_a(long *pack) {\n return (\n 4 + pack[0] * 8 +\n 4 + 1 + pack[1] * 8 * 5 +\n 4 + 1 + pack[2] * 8 * 5 + 3 * 11 * 1 +\n 4 + 1 + pack[3] * 8 * 5 + 3 * 11 * 2 +\n 4 + 1 + pack[4] * 8 * 5 + 3 * 11 * 4 +\n 4 + 1 + pack[5] * 8 * 5 + 3 * 11 * 6\n );\n}\n\nlong estimate_b(long *pack) {\n return (\n 4 + pack[0] * 9 +\n 4 + 1 + pack[1] * 9 * 5 +\n 4 + 1 + pack[2] * 9 * 5 + 4 * 2 * 3 * 8 * 1 +\n 4 + 1 + pack[3] * 9 * 5 + 4 * 2 * 3 * 8 * 2 +\n 4 + 1 + pack[4] * 9 * 5 + 4 * 2 * 3 * 8 * 4 +\n 4 + 1 + pack[5] * 9 * 5 + 4 * 2 * 3 * 8 * 6\n );\n}\n\nint main(int argc, char **argv) {\n if (argc <= 1) {\n std::cout << \"Usage: stat \" << std::endl;\n return 1;\n }\n\n kyotocabinet::TreeDB db;\n\n if (!db.open(argv[1], kyotocabinet::TreeDB::OREADER | kyotocabinet::TreeDB::ONOLOCK)) {\n std::cout << \"Could not open database.\" << std::endl;\n return 2;\n }\n\n std::auto_ptr cur(db.cursor());\n cur->jump();\n\n std::string key, value;\n\n long pack[] = {0, 0, 0, 0, 0, 0};\n long total = 0;\n\n std::cout << \"Scanning ...\" << std::endl;\n\n while (cur->get(&key, &value, true)) {\n total++;\n if (value.size() == 8) {\n pack[0]++;\n } else {\n pack[value.at(0)]++;\n }\n\n if (total % 50000 == 0) {\n std::cerr << \".\";\n }\n }\n\n std::cerr << std::endl;\n\n for (int i = 0; i < 5; i++) {\n std::cout << \"Pack format \" << i << \": \" << pack[i] << \" nodes \" << std::endl;\n }\n\n std::cout << \"Unique positions: \" << total << std::endl;\n\n std::cout << std::endl;\n\n std::cout << \"Scheme A: \" << estimate_a(pack) << \" bytes\" << std::endl;\n std::cout << \"Scheme B: \" << estimate_b(pack) << \" bytes\" << std::endl;\n std::cout << \"B\/A: \" << ((double)estimate_b(pack)\/estimate_a(pack)) << std::endl;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\n#ifdef __GNUC__\n#include \n#include \n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\nnamespace folly {\nnamespace symbolizer {\n\nnamespace {\n\n\/**\n * Read a hex value.\n *\/\nuintptr_t readHex(StringPiece& sp) {\n uintptr_t val = 0;\n const char* p = sp.begin();\n for (; p != sp.end(); ++p) {\n unsigned int v;\n if (*p >= '0' && *p <= '9') {\n v = (*p - '0');\n } else if (*p >= 'a' && *p <= 'f') {\n v = (*p - 'a') + 10;\n } else if (*p >= 'A' && *p <= 'F') {\n v = (*p - 'A') + 10;\n } else {\n break;\n }\n val = (val << 4) + v;\n }\n sp.assign(p, sp.end());\n return val;\n}\n\n\/**\n * Skip over non-space characters.\n *\/\nvoid skipNS(StringPiece& sp) {\n const char* p = sp.begin();\n for (; p != sp.end() && (*p != ' ' && *p != '\\t'); ++p) { }\n sp.assign(p, sp.end());\n}\n\n\/**\n * Skip over space and tab characters.\n *\/\nvoid skipWS(StringPiece& sp) {\n const char* p = sp.begin();\n for (; p != sp.end() && (*p == ' ' || *p == '\\t'); ++p) { }\n sp.assign(p, sp.end());\n}\n\n\/**\n * Parse a line from \/proc\/self\/maps\n *\/\nbool parseProcMapsLine(StringPiece line,\n uintptr_t& from,\n uintptr_t& to,\n uintptr_t& fileOff,\n bool& isSelf,\n StringPiece& fileName) {\n isSelf = false;\n \/\/ from to perm offset dev inode path\n \/\/ 00400000-00405000 r-xp 00000000 08:03 35291182 \/bin\/cat\n if (line.empty()) {\n return false;\n }\n\n \/\/ Remove trailing newline, if any\n if (line.back() == '\\n') {\n line.pop_back();\n }\n\n \/\/ from\n from = readHex(line);\n if (line.empty() || line.front() != '-') {\n return false;\n }\n line.pop_front();\n\n \/\/ to\n to = readHex(line);\n if (line.empty() || line.front() != ' ') {\n return false;\n }\n line.pop_front();\n\n \/\/ perms\n skipNS(line);\n if (line.empty() || line.front() != ' ') {\n return false;\n }\n line.pop_front();\n\n uintptr_t fileOffset = readHex(line);\n if (line.empty() || line.front() != ' ') {\n return false;\n }\n line.pop_front();\n \/\/ main mapping starts at 0 but there can be multi-segment binary\n \/\/ such as\n \/\/ from to perm offset dev inode path\n \/\/ 00400000-00405000 r-xp 00000000 08:03 54011424 \/bin\/foo\n \/\/ 00600000-00605000 r-xp 00020000 08:03 54011424 \/bin\/foo\n \/\/ 00800000-00805000 r-xp 00040000 08:03 54011424 \/bin\/foo\n \/\/ if the offset > 0, this indicates to the caller that the baseAddress\n \/\/ need to be used for undo relocation step.\n fileOff = fileOffset;\n\n \/\/ dev\n skipNS(line);\n if (line.empty() || line.front() != ' ') {\n return false;\n }\n line.pop_front();\n\n \/\/ inode\n skipNS(line);\n if (line.empty() || line.front() != ' ') {\n return false;\n }\n\n \/\/ if inode is 0, such as in case of ANON pages, there should be atleast\n \/\/ one white space before EOL\n skipWS(line);\n if (line.empty()) {\n \/\/ There will be no fileName for ANON text pages\n \/\/ if the parsing came this far without a fileName, then from\/to address\n \/\/ may contain text in ANON pages.\n isSelf = true;\n fileName.clear();\n return true;\n }\n\n fileName = line;\n return true;\n}\n\nElfCache* defaultElfCache() {\n static constexpr size_t defaultCapacity = 500;\n static auto cache = new ElfCache(defaultCapacity);\n return cache;\n}\n\n} \/\/ namespace\n\nvoid SymbolizedFrame::set(const std::shared_ptr& file,\n uintptr_t address) {\n clear();\n found = true;\n\n address += file->getBaseAddress();\n auto sym = file->getDefinitionByAddress(address);\n if (!sym.first) {\n return;\n }\n\n file_ = file;\n name = file->getSymbolName(sym);\n\n Dwarf(file.get()).findAddress(address, location);\n}\n\n\nSymbolizer::Symbolizer(ElfCacheBase* cache)\n : cache_(cache ?: defaultElfCache()) {\n}\n\nvoid Symbolizer::symbolize(const uintptr_t* addresses,\n SymbolizedFrame* frames,\n size_t addressCount) {\n size_t remaining = 0;\n for (size_t i = 0; i < addressCount; ++i) {\n auto& frame = frames[i];\n if (!frame.found) {\n ++remaining;\n frame.clear();\n }\n }\n\n if (remaining == 0) { \/\/ we're done\n return;\n }\n\n int fd = openNoInt(\"\/proc\/self\/maps\", O_RDONLY);\n if (fd == -1) {\n return;\n }\n\n char selfFile[PATH_MAX + 8];\n ssize_t selfSize;\n if ((selfSize = readlink(\"\/proc\/self\/exe\", selfFile, PATH_MAX + 1)) == -1) {\n \/\/ something terribly wrong\n return;\n }\n selfFile[selfSize] = '\\0';\n\n char buf[PATH_MAX + 100]; \/\/ Long enough for any line\n LineReader reader(fd, buf, sizeof(buf));\n\n while (remaining != 0) {\n StringPiece line;\n if (reader.readLine(line) != LineReader::kReading) {\n break;\n }\n\n \/\/ Parse line\n uintptr_t from;\n uintptr_t to;\n uintptr_t fileOff;\n uintptr_t base;\n bool isSelf = false; \/\/ fileName can potentially be '\/proc\/self\/exe'\n StringPiece fileName;\n if (!parseProcMapsLine(line, from, to, fileOff, isSelf, fileName)) {\n continue;\n }\n\n base = from;\n bool first = true;\n std::shared_ptr elfFile;\n\n \/\/ case of text on ANON?\n \/\/ Recompute from\/to\/base from the executable\n if (isSelf && fileName.empty()) {\n elfFile = cache_->getFile(selfFile);\n\n if (elfFile != nullptr) {\n auto textSection = elfFile->getSectionByName(\".text\");\n base = elfFile->getBaseAddress();\n from = textSection->sh_addr;\n to = from + textSection->sh_size;\n fileName = selfFile;\n first = false; \/\/ no need to get this file again from the cache\n }\n }\n\n \/\/ See if any addresses are here\n for (size_t i = 0; i < addressCount; ++i) {\n auto& frame = frames[i];\n if (frame.found) {\n continue;\n }\n\n uintptr_t address = addresses[i];\n\n if (from > address || address >= to) {\n continue;\n }\n\n \/\/ Found\n frame.found = true;\n --remaining;\n\n \/\/ Open the file on first use\n if (first) {\n first = false;\n elfFile = cache_->getFile(fileName);\n\n \/\/ Need to get the correct base address as from\n \/\/ when fileOff > 0\n if (fileOff && elfFile != nullptr) {\n base = elfFile->getBaseAddress();\n }\n }\n\n if (!elfFile) {\n continue;\n }\n\n \/\/ Undo relocation\n frame.set(elfFile, address - base);\n }\n }\n\n closeNoInt(fd);\n}\n\nnamespace {\nconstexpr char kHexChars[] = \"0123456789abcdef\";\nconstexpr auto kAddressColor = SymbolizePrinter::Color::BLUE;\nconstexpr auto kFunctionColor = SymbolizePrinter::Color::PURPLE;\nconstexpr auto kFileColor = SymbolizePrinter::Color::DEFAULT;\n} \/\/ namespace\n\nconstexpr char AddressFormatter::bufTemplate[];\nconstexpr std::array\n SymbolizePrinter::kColorMap;\n\nAddressFormatter::AddressFormatter() {\n memcpy(buf_, bufTemplate, sizeof(buf_));\n}\n\nfolly::StringPiece AddressFormatter::format(uintptr_t address) {\n \/\/ Can't use sprintf, not async-signal-safe\n static_assert(sizeof(uintptr_t) <= 8, \"huge uintptr_t?\");\n char* end = buf_ + sizeof(buf_) - 1 - (16 - 2 * sizeof(uintptr_t));\n char* p = end;\n *p-- = '\\0';\n while (address != 0) {\n *p-- = kHexChars[address & 0xf];\n address >>= 4;\n }\n\n return folly::StringPiece(buf_, end);\n}\n\nvoid SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {\n if (options_ & TERSE) {\n printTerse(address, frame);\n return;\n }\n\n SCOPE_EXIT { color(Color::DEFAULT); };\n\n if (!(options_ & NO_FRAME_ADDRESS)) {\n color(kAddressColor);\n\n AddressFormatter formatter;\n doPrint(formatter.format(address));\n }\n\n const char padBuf[] = \" \";\n folly::StringPiece pad(padBuf,\n sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));\n\n color(kFunctionColor);\n if (!frame.found) {\n doPrint(\" (not found)\");\n return;\n }\n\n if (!frame.name || frame.name[0] == '\\0') {\n doPrint(\" (unknown)\");\n } else {\n char demangledBuf[2048];\n demangle(frame.name, demangledBuf, sizeof(demangledBuf));\n doPrint(\" \");\n doPrint(demangledBuf[0] == '\\0' ? frame.name : demangledBuf);\n }\n\n if (!(options_ & NO_FILE_AND_LINE)) {\n color(kFileColor);\n char fileBuf[PATH_MAX];\n fileBuf[0] = '\\0';\n if (frame.location.hasFileAndLine) {\n frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));\n doPrint(\"\\n\");\n doPrint(pad);\n doPrint(fileBuf);\n\n char buf[22];\n uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);\n doPrint(\":\");\n doPrint(StringPiece(buf, n));\n }\n\n if (frame.location.hasMainFile) {\n char mainFileBuf[PATH_MAX];\n mainFileBuf[0] = '\\0';\n frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));\n if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {\n doPrint(\"\\n\");\n doPrint(pad);\n doPrint(\"-> \");\n doPrint(mainFileBuf);\n }\n }\n }\n}\n\nvoid SymbolizePrinter::color(SymbolizePrinter::Color color) {\n if ((options_ & COLOR) == 0 &&\n ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {\n return;\n }\n if (color < 0 || color >= kColorMap.size()) {\n return;\n }\n doPrint(kColorMap[color]);\n}\n\nvoid SymbolizePrinter::println(uintptr_t address,\n const SymbolizedFrame& frame) {\n print(address, frame);\n doPrint(\"\\n\");\n}\n\nvoid SymbolizePrinter::printTerse(uintptr_t address,\n const SymbolizedFrame& frame) {\n if (frame.found && frame.name && frame.name[0] != '\\0') {\n char demangledBuf[2048] = {0};\n demangle(frame.name, demangledBuf, sizeof(demangledBuf));\n doPrint(demangledBuf[0] == '\\0' ? frame.name : demangledBuf);\n } else {\n \/\/ Can't use sprintf, not async-signal-safe\n static_assert(sizeof(uintptr_t) <= 8, \"huge uintptr_t?\");\n char buf[] = \"0x0000000000000000\";\n char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));\n char* p = end;\n *p-- = '\\0';\n while (address != 0) {\n *p-- = kHexChars[address & 0xf];\n address >>= 4;\n }\n doPrint(StringPiece(buf, end));\n }\n}\n\nvoid SymbolizePrinter::println(const uintptr_t* addresses,\n const SymbolizedFrame* frames,\n size_t frameCount) {\n for (size_t i = 0; i < frameCount; ++i) {\n println(addresses[i], frames[i]);\n }\n}\n\nnamespace {\n\nint getFD(const std::ios& stream) {\n#ifdef __GNUC__\n std::streambuf* buf = stream.rdbuf();\n using namespace __gnu_cxx;\n\n {\n auto sbuf = dynamic_cast*>(buf);\n if (sbuf) {\n return fileno(sbuf->file());\n }\n }\n {\n auto sbuf = dynamic_cast*>(buf);\n if (sbuf) {\n return sbuf->fd();\n }\n }\n#endif \/\/ __GNUC__\n return -1;\n}\n\nbool isColorfulTty(int options, int fd) {\n if ((options & SymbolizePrinter::TERSE) != 0 ||\n (options & SymbolizePrinter::COLOR_IF_TTY) == 0 ||\n fd < 0 || !::isatty(fd)) {\n return false;\n }\n auto term = ::getenv(\"TERM\");\n return !(term == nullptr || term[0] == '\\0' || strcmp(term, \"dumb\") == 0);\n}\n\n} \/\/ anonymous namespace\n\nOStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)\n : SymbolizePrinter(options, isColorfulTty(options, getFD(out))),\n out_(out) {\n}\n\nvoid OStreamSymbolizePrinter::doPrint(StringPiece sp) {\n out_ << sp;\n}\n\nFDSymbolizePrinter::FDSymbolizePrinter(int fd, int options, size_t bufferSize)\n : SymbolizePrinter(options, isColorfulTty(options, fd)),\n fd_(fd),\n buffer_(bufferSize ? IOBuf::create(bufferSize) : nullptr) {\n}\n\nFDSymbolizePrinter::~FDSymbolizePrinter() {\n flush();\n}\n\nvoid FDSymbolizePrinter::doPrint(StringPiece sp) {\n if (buffer_) {\n if (sp.size() > buffer_->tailroom()) {\n flush();\n writeFull(fd_, sp.data(), sp.size());\n } else {\n memcpy(buffer_->writableTail(), sp.data(), sp.size());\n buffer_->append(sp.size());\n }\n } else {\n writeFull(fd_, sp.data(), sp.size());\n }\n}\n\nvoid FDSymbolizePrinter::flush() {\n if (buffer_ && !buffer_->empty()) {\n writeFull(fd_, buffer_->data(), buffer_->length());\n buffer_->clear();\n }\n}\n\nFILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)\n : SymbolizePrinter(options, isColorfulTty(options, fileno(file))),\n file_(file) {\n}\n\nvoid FILESymbolizePrinter::doPrint(StringPiece sp) {\n fwrite(sp.data(), 1, sp.size(), file_);\n}\n\nvoid StringSymbolizePrinter::doPrint(StringPiece sp) {\n buf_.append(sp.data(), sp.size());\n}\n\n} \/\/ namespace symbolizer\n} \/\/ namespace folly\nUse _r_debug instead of \/proc\/\/maps for folly::symbolizer\/*\n * Copyright 2016 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#ifdef __GNUC__\n#include \n#include \n#endif\n\n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n\n\n\/*\n * This is declared in `link.h' on Linux platforms, but apparently not on the\n * Mac version of the file. It's harmless to declare again, in any case.\n *\n * Note that declaring it with `extern \"C\"` results in linkage conflicts.\n *\/\nextern struct r_debug _r_debug;\n\nnamespace folly {\nnamespace symbolizer {\n\nnamespace {\n\nElfCache* defaultElfCache() {\n static constexpr size_t defaultCapacity = 500;\n static auto cache = new ElfCache(defaultCapacity);\n return cache;\n}\n\n} \/\/ namespace\n\nvoid SymbolizedFrame::set(const std::shared_ptr& file,\n uintptr_t address) {\n clear();\n found = true;\n\n address += file->getBaseAddress();\n auto sym = file->getDefinitionByAddress(address);\n if (!sym.first) {\n return;\n }\n\n file_ = file;\n name = file->getSymbolName(sym);\n\n Dwarf(file.get()).findAddress(address, location);\n}\n\n\nSymbolizer::Symbolizer(ElfCacheBase* cache)\n : cache_(cache ?: defaultElfCache()) {\n}\n\nvoid Symbolizer::symbolize(const uintptr_t* addresses,\n SymbolizedFrame* frames,\n size_t addrCount) {\n size_t remaining = 0;\n for (size_t i = 0; i < addrCount; ++i) {\n auto& frame = frames[i];\n if (!frame.found) {\n ++remaining;\n frame.clear();\n }\n }\n\n if (remaining == 0) { \/\/ we're done\n return;\n }\n\n if (_r_debug.r_version != 1) {\n return;\n }\n\n char selfPath[PATH_MAX + 8];\n ssize_t selfSize;\n if ((selfSize = readlink(\"\/proc\/self\/exe\", selfPath, PATH_MAX + 1)) == -1) {\n \/\/ Something has gone terribly wrong.\n return;\n }\n selfPath[selfSize] = '\\0';\n\n for (auto lmap = _r_debug.r_map;\n lmap != nullptr && remaining != 0;\n lmap = lmap->l_next) {\n \/\/ The empty string is used in place of the filename for the link_map\n \/\/ corresponding to the running executable. Additionally, the `l_addr' is\n \/\/ 0 and the link_map appears to be first in the list---but none of this\n \/\/ behavior appears to be documented, so checking for the empty string is\n \/\/ as good as anything.\n auto const objPath = lmap->l_name[0] != '\\0' ? lmap->l_name : selfPath;\n\n auto const elfFile = cache_->getFile(objPath);\n if (!elfFile) {\n continue;\n }\n\n \/\/ Get the address at which the object is loaded. We have to use the ELF\n \/\/ header for the running executable, since its `l_addr' is zero, but we\n \/\/ should use `l_addr' for everything else---in particular, if the object\n \/\/ is position-independent, getBaseAddress() (which is p_vaddr) will be 0.\n auto const base = lmap->l_addr != 0\n ? lmap->l_addr\n : elfFile->getBaseAddress();\n\n for (size_t i = 0; i < addrCount && remaining != 0; ++i) {\n auto& frame = frames[i];\n if (frame.found) {\n continue;\n }\n\n auto const addr = addresses[i];\n \/\/ Get the unrelocated, ELF-relative address.\n auto const adjusted = addr - base;\n\n if (elfFile->getSectionContainingAddress(adjusted)) {\n frame.set(elfFile, adjusted);\n --remaining;\n }\n }\n }\n}\n\nnamespace {\nconstexpr char kHexChars[] = \"0123456789abcdef\";\nconstexpr auto kAddressColor = SymbolizePrinter::Color::BLUE;\nconstexpr auto kFunctionColor = SymbolizePrinter::Color::PURPLE;\nconstexpr auto kFileColor = SymbolizePrinter::Color::DEFAULT;\n} \/\/ namespace\n\nconstexpr char AddressFormatter::bufTemplate[];\nconstexpr std::array\n SymbolizePrinter::kColorMap;\n\nAddressFormatter::AddressFormatter() {\n memcpy(buf_, bufTemplate, sizeof(buf_));\n}\n\nfolly::StringPiece AddressFormatter::format(uintptr_t address) {\n \/\/ Can't use sprintf, not async-signal-safe\n static_assert(sizeof(uintptr_t) <= 8, \"huge uintptr_t?\");\n char* end = buf_ + sizeof(buf_) - 1 - (16 - 2 * sizeof(uintptr_t));\n char* p = end;\n *p-- = '\\0';\n while (address != 0) {\n *p-- = kHexChars[address & 0xf];\n address >>= 4;\n }\n\n return folly::StringPiece(buf_, end);\n}\n\nvoid SymbolizePrinter::print(uintptr_t address, const SymbolizedFrame& frame) {\n if (options_ & TERSE) {\n printTerse(address, frame);\n return;\n }\n\n SCOPE_EXIT { color(Color::DEFAULT); };\n\n if (!(options_ & NO_FRAME_ADDRESS)) {\n color(kAddressColor);\n\n AddressFormatter formatter;\n doPrint(formatter.format(address));\n }\n\n const char padBuf[] = \" \";\n folly::StringPiece pad(padBuf,\n sizeof(padBuf) - 1 - (16 - 2 * sizeof(uintptr_t)));\n\n color(kFunctionColor);\n if (!frame.found) {\n doPrint(\" (not found)\");\n return;\n }\n\n if (!frame.name || frame.name[0] == '\\0') {\n doPrint(\" (unknown)\");\n } else {\n char demangledBuf[2048];\n demangle(frame.name, demangledBuf, sizeof(demangledBuf));\n doPrint(\" \");\n doPrint(demangledBuf[0] == '\\0' ? frame.name : demangledBuf);\n }\n\n if (!(options_ & NO_FILE_AND_LINE)) {\n color(kFileColor);\n char fileBuf[PATH_MAX];\n fileBuf[0] = '\\0';\n if (frame.location.hasFileAndLine) {\n frame.location.file.toBuffer(fileBuf, sizeof(fileBuf));\n doPrint(\"\\n\");\n doPrint(pad);\n doPrint(fileBuf);\n\n char buf[22];\n uint32_t n = uint64ToBufferUnsafe(frame.location.line, buf);\n doPrint(\":\");\n doPrint(StringPiece(buf, n));\n }\n\n if (frame.location.hasMainFile) {\n char mainFileBuf[PATH_MAX];\n mainFileBuf[0] = '\\0';\n frame.location.mainFile.toBuffer(mainFileBuf, sizeof(mainFileBuf));\n if (!frame.location.hasFileAndLine || strcmp(fileBuf, mainFileBuf)) {\n doPrint(\"\\n\");\n doPrint(pad);\n doPrint(\"-> \");\n doPrint(mainFileBuf);\n }\n }\n }\n}\n\nvoid SymbolizePrinter::color(SymbolizePrinter::Color color) {\n if ((options_ & COLOR) == 0 &&\n ((options_ & COLOR_IF_TTY) == 0 || !isTty_)) {\n return;\n }\n if (color < 0 || color >= kColorMap.size()) {\n return;\n }\n doPrint(kColorMap[color]);\n}\n\nvoid SymbolizePrinter::println(uintptr_t address,\n const SymbolizedFrame& frame) {\n print(address, frame);\n doPrint(\"\\n\");\n}\n\nvoid SymbolizePrinter::printTerse(uintptr_t address,\n const SymbolizedFrame& frame) {\n if (frame.found && frame.name && frame.name[0] != '\\0') {\n char demangledBuf[2048] = {0};\n demangle(frame.name, demangledBuf, sizeof(demangledBuf));\n doPrint(demangledBuf[0] == '\\0' ? frame.name : demangledBuf);\n } else {\n \/\/ Can't use sprintf, not async-signal-safe\n static_assert(sizeof(uintptr_t) <= 8, \"huge uintptr_t?\");\n char buf[] = \"0x0000000000000000\";\n char* end = buf + sizeof(buf) - 1 - (16 - 2 * sizeof(uintptr_t));\n char* p = end;\n *p-- = '\\0';\n while (address != 0) {\n *p-- = kHexChars[address & 0xf];\n address >>= 4;\n }\n doPrint(StringPiece(buf, end));\n }\n}\n\nvoid SymbolizePrinter::println(const uintptr_t* addresses,\n const SymbolizedFrame* frames,\n size_t frameCount) {\n for (size_t i = 0; i < frameCount; ++i) {\n println(addresses[i], frames[i]);\n }\n}\n\nnamespace {\n\nint getFD(const std::ios& stream) {\n#ifdef __GNUC__\n std::streambuf* buf = stream.rdbuf();\n using namespace __gnu_cxx;\n\n {\n auto sbuf = dynamic_cast*>(buf);\n if (sbuf) {\n return fileno(sbuf->file());\n }\n }\n {\n auto sbuf = dynamic_cast*>(buf);\n if (sbuf) {\n return sbuf->fd();\n }\n }\n#endif \/\/ __GNUC__\n return -1;\n}\n\nbool isColorfulTty(int options, int fd) {\n if ((options & SymbolizePrinter::TERSE) != 0 ||\n (options & SymbolizePrinter::COLOR_IF_TTY) == 0 ||\n fd < 0 || !::isatty(fd)) {\n return false;\n }\n auto term = ::getenv(\"TERM\");\n return !(term == nullptr || term[0] == '\\0' || strcmp(term, \"dumb\") == 0);\n}\n\n} \/\/ anonymous namespace\n\nOStreamSymbolizePrinter::OStreamSymbolizePrinter(std::ostream& out, int options)\n : SymbolizePrinter(options, isColorfulTty(options, getFD(out))),\n out_(out) {\n}\n\nvoid OStreamSymbolizePrinter::doPrint(StringPiece sp) {\n out_ << sp;\n}\n\nFDSymbolizePrinter::FDSymbolizePrinter(int fd, int options, size_t bufferSize)\n : SymbolizePrinter(options, isColorfulTty(options, fd)),\n fd_(fd),\n buffer_(bufferSize ? IOBuf::create(bufferSize) : nullptr) {\n}\n\nFDSymbolizePrinter::~FDSymbolizePrinter() {\n flush();\n}\n\nvoid FDSymbolizePrinter::doPrint(StringPiece sp) {\n if (buffer_) {\n if (sp.size() > buffer_->tailroom()) {\n flush();\n writeFull(fd_, sp.data(), sp.size());\n } else {\n memcpy(buffer_->writableTail(), sp.data(), sp.size());\n buffer_->append(sp.size());\n }\n } else {\n writeFull(fd_, sp.data(), sp.size());\n }\n}\n\nvoid FDSymbolizePrinter::flush() {\n if (buffer_ && !buffer_->empty()) {\n writeFull(fd_, buffer_->data(), buffer_->length());\n buffer_->clear();\n }\n}\n\nFILESymbolizePrinter::FILESymbolizePrinter(FILE* file, int options)\n : SymbolizePrinter(options, isColorfulTty(options, fileno(file))),\n file_(file) {\n}\n\nvoid FILESymbolizePrinter::doPrint(StringPiece sp) {\n fwrite(sp.data(), 1, sp.size(), file_);\n}\n\nvoid StringSymbolizePrinter::doPrint(StringPiece sp) {\n buf_.append(sp.data(), sp.size());\n}\n\n} \/\/ namespace symbolizer\n} \/\/ namespace folly\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ TODO: Replace this as soon as possible with a more modern option\n\/\/ parser interface.\n#include \n\n#include \"filtrations\/Data.hh\"\n\n#include \"geometry\/RipsExpander.hh\"\n\n#include \"persistenceDiagrams\/Norms.hh\"\n#include \"persistenceDiagrams\/PersistenceDiagram.hh\"\n\n#include \"persistentHomology\/ConnectedComponents.hh\"\n\n#include \"topology\/CliqueGraph.hh\"\n#include \"topology\/ConnectedComponents.hh\"\n#include \"topology\/Simplex.hh\"\n#include \"topology\/SimplicialComplex.hh\"\n\n#include \"topology\/io\/EdgeLists.hh\"\n#include \"topology\/io\/GML.hh\"\n#include \"topology\/io\/Pajek.hh\"\n\n#include \"utilities\/Filesystem.hh\"\n\nusing DataType = double;\nusing VertexType = unsigned;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\nusing PersistenceDiagram = aleph::PersistenceDiagram;\n\nstd::string formatOutput( const std::string& prefix, unsigned k, unsigned K )\n{\n std::ostringstream stream;\n stream << prefix;\n stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k;\n stream << \".txt\";\n\n return stream.str();\n}\n\nvoid usage()\n{\n std::cerr << \"Usage: clique-persistence-diagram [--invert-weights] [--reverse] FILE K\\n\"\n << \"\\n\"\n << \"Calculates the clique persistence diagram for FILE, which is\\n\"\n << \"supposed to be a weighted graph. The K parameter denotes the\\n\"\n << \"maximum dimension of a simplex for extracting a clique graph\\n\"\n << \"and tracking persistence of clique communities.\\n\\n\"\n << \"\"\n << \"Optional arguments:\\n\"\n << \" --invert-weights: If specified, inverts input weights. This\\n\"\n << \" is useful if the original weights measure\\n\"\n << \" the strength of a relationship, and not a\\n\"\n << \" dissimilarity.\\n\"\n << \"\\n\"\n << \" --reverse : Reverses the enumeration order of cliques\\n\"\n << \" by looking for higher-dimensional cliques\\n\"\n << \" before enumerating lower-dimensional ones\\n\"\n << \" instead of the other way around.\\n\"\n << \"\\n\\n\";\n}\n\nint main( int argc, char** argv )\n{\n static option commandLineOptions[] =\n {\n { \"invert-weights\", no_argument, nullptr, 'i' },\n { \"reverse\" , no_argument, nullptr, 'r' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n bool invertWeights = false;\n bool reverse = false;\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"ir\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'i':\n invertWeights = true;\n break;\n\n case 'r':\n reverse = true;\n break;\n\n default:\n break;\n }\n }\n\n if( (argc - optind ) < 2 )\n {\n usage();\n return -1;\n }\n\n std::string filename = argv[optind++];\n unsigned maxK = static_cast( std::stoul( argv[optind++] ) );\n\n SimplicialComplex K;\n\n \/\/ Input -------------------------------------------------------------\n\n std::cerr << \"* Reading '\" << filename << \"'...\";\n\n \/\/ Optional map of node labels. If the graph contains node labels and\n \/\/ I am able to read them, this map will be filled.\n std::map labels;\n\n if( aleph::utilities::extension( filename ) == \".gml\" )\n {\n aleph::topology::io::GMLReader reader;\n reader( filename, K );\n\n auto labelMap = reader.getNodeAttribute( \"label\" );\n\n \/\/ Note that this assumes that the labels are convertible to\n \/\/ numbers.\n \/\/\n \/\/ TODO: Solve this generically?\n for( auto&& pair : labelMap )\n if( !pair.second.empty() )\n labels[ static_cast( std::stoul( pair.first ) ) ] = pair.second;\n\n if( labels.empty() )\n labels.clear();\n }\n else if( aleph::utilities::extension( filename ) == \".net\" )\n {\n aleph::topology::io::PajekReader reader;\n reader( filename, K );\n\n auto labelMap = reader.getLabelMap();\n\n \/\/ Note that this assumes that the labels are convertible to\n \/\/ numbers.\n \/\/\n \/\/ TODO: Solve this generically?\n for( auto&& pair : labelMap )\n if( !pair.second.empty() )\n labels[ static_cast( std::stoul( pair.first ) ) ] = pair.second;\n\n if( labels.empty() )\n labels.clear();\n\n }\n else\n {\n aleph::io::EdgeListReader reader;\n reader.setReadWeights( true );\n reader.setTrimLines( true );\n\n reader( filename, K );\n }\n\n std::cerr << \"finished\\n\";\n\n DataType maxWeight = std::numeric_limits::lowest();\n for( auto&& simplex : K )\n maxWeight = std::max( maxWeight, simplex.data() );\n\n if( invertWeights )\n {\n std::cerr << \"* Inverting filtration weights...\";\n\n for( auto it = K.begin(); it != K.end(); ++it )\n {\n if( K.dimension() == 0 )\n continue;\n\n auto s = *it;\n s.setData( maxWeight - s.data() );\n\n K.replace( it, s );\n }\n\n std::cerr << \"finished\\n\";\n }\n\n \/\/ Expansion ---------------------------------------------------------\n\n std::cerr << \"* Expanding simplicial complex to k=\" << maxK << \"...\";\n\n aleph::geometry::RipsExpander ripsExpander;\n K = ripsExpander( K, maxK );\n K = ripsExpander.assignMaximumWeight( K );\n\n std::cerr << \"finished\\n\"\n << \"* Expanded simplicial complex has \" << K.size() << \" simplices\\n\";\n\n K.sort( aleph::filtrations::Data() );\n\n \/\/ Stores the accumulated persistence of vertices. Persistence\n \/\/ accumulates if a vertex participates in a clique community.\n std::map accumulatedPersistenceMap;\n\n \/\/ Stores the number of clique communities a vertex is a part of.\n \/\/ I am using this only for debugging the algorithm.\n std::map numberOfCliqueCommunities;\n\n std::vector totalPersistenceValues;\n totalPersistenceValues.reserve( maxK );\n\n for( unsigned k = 1; k <= maxK; k++ )\n {\n std::cerr << \"* Extracting \" << k << \"-cliques graph...\";\n\n auto C\n = aleph::topology::getCliqueGraph( K, k );\n\n C.sort( aleph::filtrations::Data() );\n\n std::cerr << \"finished\\n\";\n\n std::cerr << \"* \" << k << \"-cliques graph has \" << C.size() << \" simplices\\n\";\n\n if( C.empty() )\n {\n std::cerr << \"* Stopping here because no further cliques for processing exist\\n\";\n break;\n }\n\n auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram( C );\n auto&& pd = std::get<0>( tuple );\n auto&& pp = std::get<1>( tuple );\n\n auto itPoint = pd.begin();\n for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair )\n {\n \/\/ Skip zero-dimensional persistence pairs\n if( itPoint->x() == itPoint->y() )\n {\n ++itPoint;\n continue;\n }\n\n SimplicialComplex filteredComplex;\n\n {\n std::vector simplices;\n if( itPair->second < C.size() )\n {\n simplices.reserve( itPair->second );\n\n std::copy( C.begin() + itPair->first, C.begin() + itPair->second, std::back_inserter( simplices ) );\n filteredComplex = SimplicialComplex( simplices.begin(), simplices.end() );\n }\n else\n filteredComplex = C;\n }\n\n auto uf = calculateConnectedComponents( filteredComplex );\n auto desiredRoot = *C.at( itPair->first ).begin();\n auto root = uf.find( desiredRoot ); \/\/ Normally, this should be a self-assignment,\n \/\/ but in some cases the order of traversal is\n \/\/ slightly different, resulting in unexpected\n \/\/ roots.\n\n std::set cliqueVertices;\n std::vector vertices;\n uf.get( root, std::back_inserter( vertices ) );\n\n for( auto&& vertex : vertices )\n {\n \/\/ Notice that the vertex identifier represents the index\n \/\/ within the filtration of the _original_ complex, hence\n \/\/ I can just access the corresponding simplex that way.\n auto s = K.at( vertex );\n\n cliqueVertices.insert( s.begin(), s.end() );\n }\n\n for( auto&& cliqueVertex : cliqueVertices )\n {\n auto persistence = std::isfinite( itPoint->persistence() ) ? std::pow( itPoint->persistence(), 2 ) : std::pow( 2*maxWeight - itPoint->x(), 2 );\n\n accumulatedPersistenceMap[cliqueVertex] += persistence;\n numberOfCliqueCommunities[cliqueVertex] += 1;\n }\n\n ++itPoint;\n }\n\n {\n using namespace aleph::utilities;\n auto outputFilename = formatOutput( \"\/tmp\/\" + stem( basename( filename ) ) + \"_k\", k, maxK );\n\n std::cerr << \"* Storing output in '\" << outputFilename << \"'...\\n\";\n\n pd.removeDiagonal();\n\n std::transform( pd.begin(), pd.end(), pd.begin(),\n [&maxWeight] ( const PersistenceDiagram::Point& p )\n {\n if( !std::isfinite( p.y() ) )\n return PersistenceDiagram::Point( p.x(), maxWeight );\n else\n return PersistenceDiagram::Point( p );\n } );\n\n totalPersistenceValues.push_back( aleph::totalPersistence( pd, 1.0 ) );\n\n std::ofstream out( outputFilename );\n out << \"# Original filename: \" << filename << \"\\n\";\n out << \"# k : \" << k << \"\\n\";\n out << pd << \"\\n\";\n }\n }\n\n {\n using namespace aleph::utilities;\n auto outputFilename = \"\/tmp\/\" + stem( basename( filename ) ) + \".txt\";\n\n std::cerr << \"* Storing accumulated persistence values in '\" << outputFilename << \"'...\\n\";\n\n std::ofstream out( outputFilename );\n\n auto normalizationFactor\n = std::accumulate( totalPersistenceValues.begin(), totalPersistenceValues.end(), 0.0 );\n\n for( auto&& pair : accumulatedPersistenceMap )\n out << pair.first << \"\\t\" << pair.second \/ normalizationFactor << \"\\t\" << numberOfCliqueCommunities.at(pair.first) << ( labels.empty() ? \"\" : \"\\t\" + labels.at( pair.first ) ) << \"\\n\";\n }\n}\nMade calculation of centrality measure optional#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\/\/ TODO: Replace this as soon as possible with a more modern option\n\/\/ parser interface.\n#include \n\n#include \"filtrations\/Data.hh\"\n\n#include \"geometry\/RipsExpander.hh\"\n\n#include \"persistenceDiagrams\/Norms.hh\"\n#include \"persistenceDiagrams\/PersistenceDiagram.hh\"\n\n#include \"persistentHomology\/ConnectedComponents.hh\"\n\n#include \"topology\/CliqueGraph.hh\"\n#include \"topology\/ConnectedComponents.hh\"\n#include \"topology\/Simplex.hh\"\n#include \"topology\/SimplicialComplex.hh\"\n\n#include \"topology\/io\/EdgeLists.hh\"\n#include \"topology\/io\/GML.hh\"\n#include \"topology\/io\/Pajek.hh\"\n\n#include \"utilities\/Filesystem.hh\"\n\nusing DataType = double;\nusing VertexType = unsigned;\nusing Simplex = aleph::topology::Simplex;\nusing SimplicialComplex = aleph::topology::SimplicialComplex;\nusing PersistenceDiagram = aleph::PersistenceDiagram;\n\nstd::string formatOutput( const std::string& prefix, unsigned k, unsigned K )\n{\n std::ostringstream stream;\n stream << prefix;\n stream << std::setw( int( std::log10( K ) + 1 ) ) << std::setfill( '0' ) << k;\n stream << \".txt\";\n\n return stream.str();\n}\n\nvoid usage()\n{\n std::cerr << \"Usage: clique-persistence-diagram [--invert-weights] [--reverse] FILE K\\n\"\n << \"\\n\"\n << \"Calculates the clique persistence diagram for FILE, which is\\n\"\n << \"supposed to be a weighted graph. The K parameter denotes the\\n\"\n << \"maximum dimension of a simplex for extracting a clique graph\\n\"\n << \"and tracking persistence of clique communities.\\n\\n\"\n << \"\"\n << \"******************\\n\"\n << \"Optional arguments\\n\"\n << \"******************\\n\"\n << \"\\n\"\n << \" --centrality : If specified, calculates centralities for\\n\"\n << \" all vertices. Note that this uses copious\\n\"\n << \" amounts of time because *all* communities\\n\"\n << \" need to be extracted and inspected.\\n\"\n << \"\\n\"\n << \" --invert-weights: If specified, inverts input weights. This\\n\"\n << \" is useful if the original weights measure\\n\"\n << \" the strength of a relationship, and not a\\n\"\n << \" dissimilarity.\\n\"\n << \"\\n\"\n << \" --reverse : Reverses the enumeration order of cliques\\n\"\n << \" by looking for higher-dimensional cliques\\n\"\n << \" before enumerating lower-dimensional ones\\n\"\n << \" instead of the other way around.\\n\"\n << \"\\n\\n\";\n}\n\nint main( int argc, char** argv )\n{\n static option commandLineOptions[] =\n {\n { \"centrality\" , no_argument, nullptr, 'c' },\n { \"invert-weights\", no_argument, nullptr, 'i' },\n { \"reverse\" , no_argument, nullptr, 'r' },\n { nullptr , 0 , nullptr, 0 }\n };\n\n bool calculateCentrality = false;\n bool invertWeights = false;\n bool reverse = false;\n\n int option = 0;\n while( ( option = getopt_long( argc, argv, \"cir\", commandLineOptions, nullptr ) ) != -1 )\n {\n switch( option )\n {\n case 'c':\n calculateCentrality = true;\n break;\n\n case 'i':\n invertWeights = true;\n break;\n\n case 'r':\n reverse = true;\n break;\n\n default:\n break;\n }\n }\n\n if( (argc - optind ) < 2 )\n {\n usage();\n return -1;\n }\n\n std::string filename = argv[optind++];\n unsigned maxK = static_cast( std::stoul( argv[optind++] ) );\n\n SimplicialComplex K;\n\n \/\/ Input -------------------------------------------------------------\n\n std::cerr << \"* Reading '\" << filename << \"'...\";\n\n \/\/ Optional map of node labels. If the graph contains node labels and\n \/\/ I am able to read them, this map will be filled.\n std::map labels;\n\n if( aleph::utilities::extension( filename ) == \".gml\" )\n {\n aleph::topology::io::GMLReader reader;\n reader( filename, K );\n\n auto labelMap = reader.getNodeAttribute( \"label\" );\n\n \/\/ Note that this assumes that the labels are convertible to\n \/\/ numbers.\n \/\/\n \/\/ TODO: Solve this generically?\n for( auto&& pair : labelMap )\n if( !pair.second.empty() )\n labels[ static_cast( std::stoul( pair.first ) ) ] = pair.second;\n\n if( labels.empty() )\n labels.clear();\n }\n else if( aleph::utilities::extension( filename ) == \".net\" )\n {\n aleph::topology::io::PajekReader reader;\n reader( filename, K );\n\n auto labelMap = reader.getLabelMap();\n\n \/\/ Note that this assumes that the labels are convertible to\n \/\/ numbers.\n \/\/\n \/\/ TODO: Solve this generically?\n for( auto&& pair : labelMap )\n if( !pair.second.empty() )\n labels[ static_cast( std::stoul( pair.first ) ) ] = pair.second;\n\n if( labels.empty() )\n labels.clear();\n\n }\n else\n {\n aleph::io::EdgeListReader reader;\n reader.setReadWeights( true );\n reader.setTrimLines( true );\n\n reader( filename, K );\n }\n\n std::cerr << \"finished\\n\";\n\n DataType maxWeight = std::numeric_limits::lowest();\n for( auto&& simplex : K )\n maxWeight = std::max( maxWeight, simplex.data() );\n\n if( invertWeights )\n {\n std::cerr << \"* Inverting filtration weights...\";\n\n for( auto it = K.begin(); it != K.end(); ++it )\n {\n if( K.dimension() == 0 )\n continue;\n\n auto s = *it;\n s.setData( maxWeight - s.data() );\n\n K.replace( it, s );\n }\n\n std::cerr << \"finished\\n\";\n }\n\n \/\/ Expansion ---------------------------------------------------------\n\n std::cerr << \"* Expanding simplicial complex to k=\" << maxK << \"...\";\n\n aleph::geometry::RipsExpander ripsExpander;\n K = ripsExpander( K, maxK );\n K = ripsExpander.assignMaximumWeight( K );\n\n std::cerr << \"finished\\n\"\n << \"* Expanded simplicial complex has \" << K.size() << \" simplices\\n\";\n\n K.sort( aleph::filtrations::Data() );\n\n \/\/ Stores the accumulated persistence of vertices. Persistence\n \/\/ accumulates if a vertex participates in a clique community.\n std::map accumulatedPersistenceMap;\n\n \/\/ Stores the number of clique communities a vertex is a part of.\n \/\/ I am using this only for debugging the algorithm.\n std::map numberOfCliqueCommunities;\n\n std::vector totalPersistenceValues;\n totalPersistenceValues.reserve( maxK );\n\n for( unsigned k = 1; k <= maxK; k++ )\n {\n std::cerr << \"* Extracting \" << k << \"-cliques graph...\";\n\n auto C\n = aleph::topology::getCliqueGraph( K, k );\n\n C.sort( aleph::filtrations::Data() );\n\n std::cerr << \"finished\\n\";\n\n std::cerr << \"* \" << k << \"-cliques graph has \" << C.size() << \" simplices\\n\";\n\n if( C.empty() )\n {\n std::cerr << \"* Stopping here because no further cliques for processing exist\\n\";\n break;\n }\n\n auto&& tuple = aleph::calculateZeroDimensionalPersistenceDiagram( C );\n auto&& pd = std::get<0>( tuple );\n auto&& pp = std::get<1>( tuple );\n\n pd.removeDiagonal();\n\n if( calculateCentrality )\n {\n std::cerr << \"* Calculating centrality measure (this may take a very long time!)...\";\n\n auto itPoint = pd.begin();\n for( auto itPair = pp.begin(); itPair != pp.end(); ++itPair )\n {\n SimplicialComplex filteredComplex;\n\n {\n std::vector simplices;\n if( itPair->second < C.size() )\n {\n simplices.reserve( itPair->second );\n\n std::copy( C.begin() + itPair->first, C.begin() + itPair->second, std::back_inserter( simplices ) );\n filteredComplex = SimplicialComplex( simplices.begin(), simplices.end() );\n }\n else\n filteredComplex = C;\n }\n\n auto uf = calculateConnectedComponents( filteredComplex );\n auto desiredRoot = *C.at( itPair->first ).begin();\n auto root = uf.find( desiredRoot ); \/\/ Normally, this should be a self-assignment,\n \/\/ but in some cases the order of traversal is\n \/\/ slightly different, resulting in unexpected\n \/\/ roots.\n\n std::set cliqueVertices;\n std::vector vertices;\n uf.get( root, std::back_inserter( vertices ) );\n\n for( auto&& vertex : vertices )\n {\n \/\/ Notice that the vertex identifier represents the index\n \/\/ within the filtration of the _original_ complex, hence\n \/\/ I can just access the corresponding simplex that way.\n auto s = K.at( vertex );\n\n cliqueVertices.insert( s.begin(), s.end() );\n }\n\n for( auto&& cliqueVertex : cliqueVertices )\n {\n auto persistence = std::isfinite( itPoint->persistence() ) ? std::pow( itPoint->persistence(), 2 ) : std::pow( 2*maxWeight - itPoint->x(), 2 );\n\n accumulatedPersistenceMap[cliqueVertex] += persistence;\n numberOfCliqueCommunities[cliqueVertex] += 1;\n }\n\n ++itPoint;\n }\n\n std::cerr << \"finished\\n\";\n }\n\n {\n using namespace aleph::utilities;\n auto outputFilename = formatOutput( \"\/tmp\/\" + stem( basename( filename ) ) + \"_k\", k, maxK );\n\n std::cerr << \"* Storing output in '\" << outputFilename << \"'...\\n\";\n\n std::transform( pd.begin(), pd.end(), pd.begin(),\n [&maxWeight] ( const PersistenceDiagram::Point& p )\n {\n if( !std::isfinite( p.y() ) )\n return PersistenceDiagram::Point( p.x(), maxWeight );\n else\n return PersistenceDiagram::Point( p );\n } );\n\n totalPersistenceValues.push_back( aleph::totalPersistence( pd, 1.0 ) );\n\n std::ofstream out( outputFilename );\n out << \"# Original filename: \" << filename << \"\\n\";\n out << \"# k : \" << k << \"\\n\";\n out << pd << \"\\n\";\n }\n }\n\n {\n using namespace aleph::utilities;\n auto outputFilename = \"\/tmp\/\" + stem( basename( filename ) ) + \".txt\";\n\n std::cerr << \"* Storing accumulated persistence values in '\" << outputFilename << \"'...\\n\";\n\n std::ofstream out( outputFilename );\n\n auto normalizationFactor\n = std::accumulate( totalPersistenceValues.begin(), totalPersistenceValues.end(), 0.0 );\n\n for( auto&& pair : accumulatedPersistenceMap )\n out << pair.first << \"\\t\" << pair.second \/ normalizationFactor << \"\\t\" << numberOfCliqueCommunities.at(pair.first) << ( labels.empty() ? \"\" : \"\\t\" + labels.at( pair.first ) ) << \"\\n\";\n }\n}\n<|endoftext|>"} {"text":"\/**\n *Licensed to the Apache Software Foundation (ASF) under one\n *or more contributor license agreements. See the NOTICE file\n *distributed with this work for additional information\n *regarding copyright ownership. The ASF licenses this file\n *to you under the Apache License, Version 2.0 (the\n *\"License\"); you may not use this file except in compliance\n *with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *Unless required by applicable law or agreed to in writing,\n *software distributed under the License is distributed on an\n *\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n *specific language governing permissions and limitations\n *under the License.\n *\/\n\/*\n * bundle_cache_test.cpp\n *\n * \\date Feb 11, 2013\n * \\author Apache Celix Project Team<\/a>\n * \\copyright Apache License, Version 2.0\n *\/\n#include \n#include \n\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTest\/TestHarness_c.h\"\n#include \"CppUTest\/CommandLineTestRunner.h\"\n#include \"CppUTestExt\/MockSupport.h\"\n\nextern \"C\" {\n#include \n#include \"bundle_cache_private.h\"\n}\n\nint main(int argc, char** argv) {\n\treturn RUN_ALL_TESTS(argc, argv);\n}\n\nTEST_GROUP(bundle_cache) {\n\tapr_pool_t *pool;\n\n\tvoid setup(void) {\n\t\tapr_initialize();\n\t\tapr_pool_create(&pool, NULL);\n\t}\n\n\tvoid teardown() {\n\t\tapr_pool_destroy(pool);\n\t\tmock().checkExpectations();\n\t\tmock().clear();\n\t}\n};\n\nTEST(bundle_cache, create) {\n\tproperties_pt configuration = (properties_pt) 0x10;\n\n\tmock().expectOneCall(\"properties_get\")\n\t\t.withParameter(\"properties\", configuration)\n\t\t.withParameter(\"key\", \"org.osgi.framework.storage\")\n\t\t.andReturnValue((char *) NULL);\n\n\tmock().expectOneCall(\"properties_destroy\")\n\t\t.withParameter(\"properties\", configuration);\n\n\tbundle_cache_pt cache = NULL;\n\tcelix_status_t status = bundleCache_create(configuration, pool, &cache);\n\tLONGS_EQUAL(CELIX_SUCCESS, status);\n}\n\nTEST(bundle_cache, deleteTree) {\n\tbundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));\n\tchar cacheDir[] = \"bundle_cache_test_directory\";\n\tchar cacheFile[] = \"bundle_cache_test_directory\/temp\";\n\tcache->cacheDir = cacheDir;\n\tcache->mp = pool;\n\n\tapr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\tapr_file_t *file;\n\tapr_file_mktemp(&file, cacheFile, APR_UREAD|APR_UWRITE, pool);\n\n\tcelix_status_t status = bundleCache_delete(cache);\n\n\tLONGS_EQUAL(CELIX_SUCCESS, status);\n\n}\n\nTEST(bundle_cache, getArchive) {\n\tbundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));\n\tchar cacheDir[] = \"bundle_cache_test_directory\";\n\tcache->cacheDir = cacheDir;\n\tcache->mp = pool;\n\n\tchar bundle0[] = \"bundle_cache_test_directory\/bundle0\";\n\tchar bundle1[] = \"bundle_cache_test_directory\/bundle1\";\n\tapr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\tapr_dir_make(bundle0, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\tapr_dir_make(bundle1, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\n\tbundle_archive_pt archive = (bundle_archive_pt) 0x10;\n\tmock().expectOneCall(\"bundleArchive_recreate\")\n\t\t.withParameter(\"archiveRoot\", bundle1)\n\t\t.withParameter(\"mp\", pool)\n\t\t.andOutputParameter(\"bundle_archive\", archive)\n\t\t.andReturnValue(CELIX_SUCCESS);\n\n\tarray_list_pt archives = NULL;\n\tcelix_status_t status = bundleCache_getArchives(cache, pool, &archives);\n\n\tLONGS_EQUAL(CELIX_SUCCESS, status);\n\tCHECK(archives);\n\tLONGS_EQUAL(1, arrayList_size(archives));\n\tPOINTERS_EQUAL(archive, arrayList_get(archives, 0));\n\n\tapr_dir_remove(bundle0, pool);\n\tapr_dir_remove(bundle1, pool);\n\tapr_dir_remove(cacheDir, pool);\n}\n\nTEST(bundle_cache, createArchive) {\n\tbundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));\n\tchar cacheDir[] = \"bundle_cache_test_directory\";\n\tcache->cacheDir = cacheDir;\n\n\tchar archiveRoot[] = \"bundle_cache_test_directory\/bundle1\";\n\tint id = 1;\n\tchar location[] = \"test.zip\";\n\tbundle_archive_pt archive = (bundle_archive_pt) 0x10;\n\tmock().expectOneCall(\"bundleArchive_create\")\n\t\t.withParameter(\"archiveRoot\", archiveRoot)\n\t\t.withParameter(\"id\", id)\n\t\t.withParameter(\"location\", location)\n\t\t.withParameter(\"inputFile\", (char *) NULL)\n\t\t.withParameter(\"mp\", pool)\n\t\t.andOutputParameter(\"bundle_archive\", archive)\n\t\t.andReturnValue(CELIX_SUCCESS);\n\n\tbundle_archive_pt actual;\n\tbundleCache_createArchive(cache, pool, 1l, location, NULL, &actual);\n\tPOINTERS_EQUAL(archive, actual);\n}\nCELIX-102: Fixed test.\/**\n *Licensed to the Apache Software Foundation (ASF) under one\n *or more contributor license agreements. See the NOTICE file\n *distributed with this work for additional information\n *regarding copyright ownership. The ASF licenses this file\n *to you under the Apache License, Version 2.0 (the\n *\"License\"); you may not use this file except in compliance\n *with the License. You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n *Unless required by applicable law or agreed to in writing,\n *software distributed under the License is distributed on an\n *\"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY\n * KIND, either express or implied. See the License for the\n *specific language governing permissions and limitations\n *under the License.\n *\/\n\/*\n * bundle_cache_test.cpp\n *\n * \\date Feb 11, 2013\n * \\author Apache Celix Project Team<\/a>\n * \\copyright Apache License, Version 2.0\n *\/\n#include \n#include \n\n#include \"CppUTest\/TestHarness.h\"\n#include \"CppUTest\/TestHarness_c.h\"\n#include \"CppUTest\/CommandLineTestRunner.h\"\n#include \"CppUTestExt\/MockSupport.h\"\n\nextern \"C\" {\n#include \n#include \"bundle_cache_private.h\"\n}\n\nint main(int argc, char** argv) {\n\treturn RUN_ALL_TESTS(argc, argv);\n}\n\nTEST_GROUP(bundle_cache) {\n\tapr_pool_t *pool;\n\n\tvoid setup(void) {\n\t\tapr_initialize();\n\t\tapr_pool_create(&pool, NULL);\n\t}\n\n\tvoid teardown() {\n\t\tapr_pool_destroy(pool);\n\t\tmock().checkExpectations();\n\t\tmock().clear();\n\t}\n};\n\nTEST(bundle_cache, create) {\n\tproperties_pt configuration = (properties_pt) 0x10;\n\n\tmock().expectOneCall(\"properties_get\")\n\t\t.withParameter(\"properties\", configuration)\n\t\t.withParameter(\"key\", \"org.osgi.framework.storage\")\n\t\t.andReturnValue((char *) NULL);\n\n\tbundle_cache_pt cache = NULL;\n\tcelix_status_t status = bundleCache_create(configuration, pool, &cache);\n\tLONGS_EQUAL(CELIX_SUCCESS, status);\n}\n\nTEST(bundle_cache, deleteTree) {\n\tbundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));\n\tchar cacheDir[] = \"bundle_cache_test_directory\";\n\tchar cacheFile[] = \"bundle_cache_test_directory\/temp\";\n\tcache->cacheDir = cacheDir;\n\tcache->mp = pool;\n\n\tapr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\tapr_file_t *file;\n\tapr_file_mktemp(&file, cacheFile, APR_UREAD|APR_UWRITE, pool);\n\n\tcelix_status_t status = bundleCache_delete(cache);\n\n\tLONGS_EQUAL(CELIX_SUCCESS, status);\n\n}\n\nTEST(bundle_cache, getArchive) {\n\tbundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));\n\tchar cacheDir[] = \"bundle_cache_test_directory\";\n\tcache->cacheDir = cacheDir;\n\tcache->mp = pool;\n\n\tchar bundle0[] = \"bundle_cache_test_directory\/bundle0\";\n\tchar bundle1[] = \"bundle_cache_test_directory\/bundle1\";\n\tapr_dir_make(cacheDir, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\tapr_dir_make(bundle0, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\tapr_dir_make(bundle1, APR_UREAD|APR_UWRITE|APR_UEXECUTE, pool);\n\n\tbundle_archive_pt archive = (bundle_archive_pt) 0x10;\n\tmock().expectOneCall(\"bundleArchive_recreate\")\n\t\t.withParameter(\"archiveRoot\", bundle1)\n\t\t.withParameter(\"mp\", pool)\n\t\t.andOutputParameter(\"bundle_archive\", archive)\n\t\t.andReturnValue(CELIX_SUCCESS);\n\n\tarray_list_pt archives = NULL;\n\tcelix_status_t status = bundleCache_getArchives(cache, pool, &archives);\n\n\tLONGS_EQUAL(CELIX_SUCCESS, status);\n\tCHECK(archives);\n\tLONGS_EQUAL(1, arrayList_size(archives));\n\tPOINTERS_EQUAL(archive, arrayList_get(archives, 0));\n\n\tapr_dir_remove(bundle0, pool);\n\tapr_dir_remove(bundle1, pool);\n\tapr_dir_remove(cacheDir, pool);\n}\n\nTEST(bundle_cache, createArchive) {\n\tbundle_cache_pt cache = (bundle_cache_pt) apr_palloc(pool, sizeof(*cache));\n\tchar cacheDir[] = \"bundle_cache_test_directory\";\n\tcache->cacheDir = cacheDir;\n\n\tchar archiveRoot[] = \"bundle_cache_test_directory\/bundle1\";\n\tint id = 1;\n\tchar location[] = \"test.zip\";\n\tbundle_archive_pt archive = (bundle_archive_pt) 0x10;\n\tmock().expectOneCall(\"bundleArchive_create\")\n\t\t.withParameter(\"archiveRoot\", archiveRoot)\n\t\t.withParameter(\"id\", id)\n\t\t.withParameter(\"location\", location)\n\t\t.withParameter(\"inputFile\", (char *) NULL)\n\t\t.withParameter(\"mp\", pool)\n\t\t.andOutputParameter(\"bundle_archive\", archive)\n\t\t.andReturnValue(CELIX_SUCCESS);\n\n\tbundle_archive_pt actual;\n\tbundleCache_createArchive(cache, pool, 1l, location, NULL, &actual);\n\tPOINTERS_EQUAL(archive, actual);\n}\n<|endoftext|>"} {"text":"\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"MaterialPropertyIO.h\"\n#include \"MaterialPropertyStorage.h\"\n\n\nconst unsigned int MaterialPropertyIO::file_version = 1;\n\nstruct MSMPHeader\n{\n char _id[4]; \/\/ 4 letter ID\n unsigned int _file_version; \/\/ file version\n};\n\n\nMaterialPropertyIO::MaterialPropertyIO(MaterialPropertyStorage & material_props, MaterialPropertyStorage & bnd_material_props) :\n _material_props(material_props),\n _bnd_material_props(bnd_material_props)\n{\n}\n\nMaterialPropertyIO::~MaterialPropertyIO()\n{\n}\n\nvoid\nMaterialPropertyIO::write(const std::string & file_name)\n{\n std::ofstream out(file_name.c_str(), std::ios::out | std::ios::binary);\n\n \/\/ header\n MSMPHeader head;\n memcpy(head._id, \"MSMP\", 4);\n head._file_version = file_version;\n out.write((const char *) &head, sizeof(head));\n\n HashMap > & props = _material_props.props();\n HashMap > & propsOld = _material_props.propsOld();\n HashMap > & propsOlder = _material_props.propsOlder();\n\n HashMap > & bnd_props = _bnd_material_props.props();\n HashMap > & bnd_propsOld = _bnd_material_props.propsOld();\n HashMap > & bnd_propsOlder = _bnd_material_props.propsOlder();\n\n \/\/ number of blocks\n \/\/ TODO: go over elements and figure out the groups of elements we are going to write in a file\n unsigned int n_blocks = 1; \/\/ just one for right now\n out.write((const char *) &n_blocks, sizeof(n_blocks));\n\n \/\/ number of quadrature points\n \/\/ we go grab element 0, side 0 (it's volumetric mat. properties) and 0th property (all should be sized the same)\n unsigned int n_qps = props[0][0][0]->size(); \/\/ we expect to have element 0 always (lame)\n out.write((const char *) &n_qps, sizeof(n_qps));\n\n \/\/ save the number of elements in this block (since we do only 1 block right now, we store everything)\n unsigned int n_elems = props.size();\n out.write((const char *) &n_elems, sizeof(n_elems));\n\n \/\/ properties\n std::set & stateful_props = _material_props.statefulProps();\n std::vector prop_ids;\n prop_ids.insert(prop_ids.end(), stateful_props.begin(), stateful_props.end());\n std::sort(prop_ids.begin(), prop_ids.end());\n\n unsigned int n_props = prop_ids.size(); \/\/ number of properties in this block\n out.write((const char *) &n_props, sizeof(n_props));\n \/\/ property names\n for (unsigned int i = 0; i < n_props; ++i)\n {\n std::string prop_name = _material_props.statefulPropNames()[i];\n out.write(prop_name.c_str(), prop_name.length() + 1); \/\/ do not forget the trailing zero ;-)\n }\n\n \/\/ save current material properties\n for (unsigned int e = 0; e < n_elems; ++e)\n {\n unsigned int elem_id = e;\n out.write((const char *) &elem_id, sizeof(elem_id));\n\n \/\/ write out the properties themselves\n for (unsigned int i = 0; i < n_props; ++i)\n {\n unsigned int pid = prop_ids[i];\n props[e][0][pid]->store(out);\n propsOld[e][0][pid]->store(out);\n if (_material_props.hasOlderProperties())\n propsOlder[e][0][pid]->store(out);\n }\n }\n\n \/\/ save the material props on sides\n unsigned int n_sides = bnd_props[0].size();\n out.write((const char *) &n_sides, sizeof(n_sides));\n\n \/\/ save current material properties\n for (unsigned int e = 0; e < n_elems; ++e)\n {\n unsigned int elem_id = e;\n out.write((const char *) &elem_id, sizeof(elem_id));\n\n for (unsigned int s = 0; s < n_sides; ++s)\n {\n \/\/ write out the properties themselves\n for (unsigned int i = 0; i < n_props; ++i)\n {\n unsigned int pid = prop_ids[i];\n bnd_props[e][s][pid]->store(out);\n bnd_propsOld[e][s][pid]->store(out);\n if (_material_props.hasOlderProperties())\n bnd_propsOlder[e][s][pid]->store(out);\n }\n }\n }\n\n \/\/ TODO: end of the loop over blocks\n\n out.close();\n}\n\nvoid\nMaterialPropertyIO::read(const std::string & file_name)\n{\n std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary);\n\n \/\/ header\n MSMPHeader head;\n in.read((char *) &head, sizeof(head));\n\n \/\/ check the header\n if (!(head._id[0] == 'M' && head._id[1] == 'S' && head._id[2] == 'M' && head._id[3] == 'P'))\n mooseError(\"Corrupted material properties file\");\n \/\/ check the file version\n if (head._file_version > file_version)\n mooseError(\"Trying to restart from a newer file version - you need to update MOOSE\");\n\n \/\/ grab some references we will need to later\n HashMap > & props = _material_props.props();\n HashMap > & propsOld = _material_props.propsOld();\n HashMap > & propsOlder = _material_props.propsOlder();\n\n HashMap > & bnd_props = _bnd_material_props.props();\n HashMap > & bnd_propsOld = _bnd_material_props.propsOld();\n HashMap > & bnd_propsOlder = _bnd_material_props.propsOlder();\n\n std::map stateful_prop_names = _material_props.statefulPropNames();\n std::map stateful_prop_ids; \/\/ inverse map of stateful_prop_names\n for (std::map::iterator it = stateful_prop_names.begin(); it != stateful_prop_names.end(); ++it)\n stateful_prop_ids[it->second] = it->first;\n\n \/\/ number of blocks\n unsigned int n_blocks = 0;\n in.read((char *) &n_blocks, sizeof(n_blocks));\n\n \/\/ loop over block\n for (unsigned int blk_id = 0; blk_id < n_blocks; blk_id++)\n {\n \/\/ number of quadrature points\n unsigned int n_qps = 0;\n in.read((char *) &n_qps, sizeof(n_qps));\n \/\/ number of elements\n unsigned int n_elems = props.size();\n in.read((char *) &n_elems, sizeof(n_elems));\n \/\/ number of properties in this block\n unsigned int n_props = 0;\n in.read((char *) &n_props, sizeof(n_props));\n \/\/ property names\n std::vector prop_names;\n\n for (unsigned int i = 0; i < n_props; ++i)\n {\n std::string prop_name;\n char ch = 0;\n do {\n in.read(&ch, 1);\n if (ch != '\\0')\n prop_name += ch;\n } while (ch != '\\0');\n prop_names.push_back(prop_name);\n }\n\n for (unsigned int e = 0; e < n_elems; ++e)\n {\n unsigned int elem_id = 0;\n in.read((char *) &elem_id, sizeof(elem_id));\n\n \/\/ read in the properties themselves\n for (unsigned int i = 0; i < n_props; ++i)\n {\n unsigned int pid = stateful_prop_ids[prop_names[i]];\n\n props[e][0][pid]->load(in);\n propsOld[e][0][pid]->load(in);\n if (_material_props.hasOlderProperties()) \/\/ this should actually check if the value is stored in the file (we do not store it right now)\n propsOlder[e][0][pid]->load(in);\n }\n }\n\n \/\/ load in the material props on sides\n unsigned int n_sides = 0;\n in.read((char *) &n_sides, sizeof(n_sides));\n\n for (unsigned int e = 0; e < n_elems; ++e)\n {\n unsigned int elem_id = 0;\n in.read((char *) &elem_id, sizeof(elem_id));\n\n for (unsigned int s = 0; s < n_sides; ++s)\n {\n \/\/ read in the properties themselves\n for (unsigned int i = 0; i < n_props; ++i)\n {\n unsigned int pid = stateful_prop_ids[prop_names[i]];\n\n bnd_props[e][s][pid]->load(in);\n bnd_propsOld[e][s][pid]->load(in);\n if (_material_props.hasOlderProperties()) \/\/ this should actually check if the value is stored in the file (we do not store it right now)\n bnd_propsOlder[e][s][pid]->load(in);\n }\n }\n }\n\n }\n\n in.close();\n}\nFixing incorrect indexing into material property names array (closes #1138)\/****************************************************************\/\n\/* DO NOT MODIFY THIS HEADER *\/\n\/* MOOSE - Multiphysics Object Oriented Simulation Environment *\/\n\/* *\/\n\/* (c) 2010 Battelle Energy Alliance, LLC *\/\n\/* ALL RIGHTS RESERVED *\/\n\/* *\/\n\/* Prepared by Battelle Energy Alliance, LLC *\/\n\/* Under Contract No. DE-AC07-05ID14517 *\/\n\/* With the U. S. Department of Energy *\/\n\/* *\/\n\/* See COPYRIGHT for full restrictions *\/\n\/****************************************************************\/\n\n#include \"MaterialPropertyIO.h\"\n#include \"MaterialPropertyStorage.h\"\n\n\nconst unsigned int MaterialPropertyIO::file_version = 1;\n\nstruct MSMPHeader\n{\n char _id[4]; \/\/ 4 letter ID\n unsigned int _file_version; \/\/ file version\n};\n\n\nMaterialPropertyIO::MaterialPropertyIO(MaterialPropertyStorage & material_props, MaterialPropertyStorage & bnd_material_props) :\n _material_props(material_props),\n _bnd_material_props(bnd_material_props)\n{\n}\n\nMaterialPropertyIO::~MaterialPropertyIO()\n{\n}\n\nvoid\nMaterialPropertyIO::write(const std::string & file_name)\n{\n std::ofstream out(file_name.c_str(), std::ios::out | std::ios::binary);\n\n \/\/ header\n MSMPHeader head;\n memcpy(head._id, \"MSMP\", 4);\n head._file_version = file_version;\n out.write((const char *) &head, sizeof(head));\n\n HashMap > & props = _material_props.props();\n HashMap > & propsOld = _material_props.propsOld();\n HashMap > & propsOlder = _material_props.propsOlder();\n\n HashMap > & bnd_props = _bnd_material_props.props();\n HashMap > & bnd_propsOld = _bnd_material_props.propsOld();\n HashMap > & bnd_propsOlder = _bnd_material_props.propsOlder();\n\n \/\/ number of blocks\n \/\/ TODO: go over elements and figure out the groups of elements we are going to write in a file\n unsigned int n_blocks = 1; \/\/ just one for right now\n out.write((const char *) &n_blocks, sizeof(n_blocks));\n\n \/\/ number of quadrature points\n \/\/ we go grab element 0, side 0 (it's volumetric mat. properties) and 0th property (all should be sized the same)\n unsigned int n_qps = props[0][0][0]->size(); \/\/ we expect to have element 0 always (lame)\n out.write((const char *) &n_qps, sizeof(n_qps));\n\n \/\/ save the number of elements in this block (since we do only 1 block right now, we store everything)\n unsigned int n_elems = props.size();\n out.write((const char *) &n_elems, sizeof(n_elems));\n\n \/\/ properties\n std::set & stateful_props = _material_props.statefulProps();\n std::vector prop_ids;\n prop_ids.insert(prop_ids.end(), stateful_props.begin(), stateful_props.end());\n std::sort(prop_ids.begin(), prop_ids.end());\n\n unsigned int n_props = prop_ids.size(); \/\/ number of properties in this block\n out.write((const char *) &n_props, sizeof(n_props));\n \/\/ property names\n for (unsigned int i = 0; i < n_props; i++)\n {\n unsigned int pid = prop_ids[i];\n std::string prop_name = _material_props.statefulPropNames()[pid];\n out.write(prop_name.c_str(), prop_name.length() + 1); \/\/ do not forget the trailing zero ;-)\n }\n\n \/\/ save current material properties\n for (unsigned int e = 0; e < n_elems; e++)\n {\n unsigned int elem_id = e;\n out.write((const char *) &elem_id, sizeof(elem_id));\n\n \/\/ write out the properties themselves\n for (unsigned int i = 0; i < n_props; i++)\n {\n unsigned int pid = prop_ids[i];\n props[e][0][pid]->store(out);\n propsOld[e][0][pid]->store(out);\n if (_material_props.hasOlderProperties())\n propsOlder[e][0][pid]->store(out);\n }\n }\n\n \/\/ save the material props on sides\n unsigned int n_sides = bnd_props[0].size();\n out.write((const char *) &n_sides, sizeof(n_sides));\n\n \/\/ save current material properties\n for (unsigned int e = 0; e < n_elems; e++)\n {\n unsigned int elem_id = e;\n out.write((const char *) &elem_id, sizeof(elem_id));\n\n for (unsigned int s = 0; s < n_sides; s++)\n {\n \/\/ write out the properties themselves\n for (unsigned int i = 0; i < n_props; i++)\n {\n unsigned int pid = prop_ids[i];\n bnd_props[e][s][pid]->store(out);\n bnd_propsOld[e][s][pid]->store(out);\n if (_material_props.hasOlderProperties())\n bnd_propsOlder[e][s][pid]->store(out);\n }\n }\n }\n\n \/\/ TODO: end of the loop over blocks\n\n out.close();\n}\n\nvoid\nMaterialPropertyIO::read(const std::string & file_name)\n{\n std::ifstream in(file_name.c_str(), std::ios::in | std::ios::binary);\n\n \/\/ header\n MSMPHeader head;\n in.read((char *) &head, sizeof(head));\n\n \/\/ check the header\n if (!(head._id[0] == 'M' && head._id[1] == 'S' && head._id[2] == 'M' && head._id[3] == 'P'))\n mooseError(\"Corrupted material properties file\");\n \/\/ check the file version\n if (head._file_version > file_version)\n mooseError(\"Trying to restart from a newer file version - you need to update MOOSE\");\n\n \/\/ grab some references we will need to later\n HashMap > & props = _material_props.props();\n HashMap > & propsOld = _material_props.propsOld();\n HashMap > & propsOlder = _material_props.propsOlder();\n\n HashMap > & bnd_props = _bnd_material_props.props();\n HashMap > & bnd_propsOld = _bnd_material_props.propsOld();\n HashMap > & bnd_propsOlder = _bnd_material_props.propsOlder();\n\n std::map stateful_prop_names = _material_props.statefulPropNames();\n std::map stateful_prop_ids; \/\/ inverse map of stateful_prop_names\n for (std::map::iterator it = stateful_prop_names.begin(); it != stateful_prop_names.end(); ++it)\n stateful_prop_ids[it->second] = it->first;\n\n \/\/ number of blocks\n unsigned int n_blocks = 0;\n in.read((char *) &n_blocks, sizeof(n_blocks));\n\n \/\/ loop over block\n for (unsigned int blk_id = 0; blk_id < n_blocks; blk_id++)\n {\n \/\/ number of quadrature points\n unsigned int n_qps = 0;\n in.read((char *) &n_qps, sizeof(n_qps));\n \/\/ number of elements\n unsigned int n_elems = props.size();\n in.read((char *) &n_elems, sizeof(n_elems));\n \/\/ number of properties in this block\n unsigned int n_props = 0;\n in.read((char *) &n_props, sizeof(n_props));\n \/\/ property names\n std::vector prop_names;\n\n for (unsigned int i = 0; i < n_props; i++)\n {\n std::string prop_name;\n char ch = 0;\n do {\n in.read(&ch, 1);\n if (ch != '\\0')\n prop_name += ch;\n } while (ch != '\\0');\n prop_names.push_back(prop_name);\n }\n\n for (unsigned int e = 0; e < n_elems; e++)\n {\n unsigned int elem_id = 0;\n in.read((char *) &elem_id, sizeof(elem_id));\n\n \/\/ read in the properties themselves\n for (unsigned int i = 0; i < n_props; i++)\n {\n unsigned int pid = stateful_prop_ids[prop_names[i]];\n\n props[e][0][pid]->load(in);\n propsOld[e][0][pid]->load(in);\n if (_material_props.hasOlderProperties()) \/\/ this should actually check if the value is stored in the file (we do not store it right now)\n propsOlder[e][0][pid]->load(in);\n }\n }\n\n \/\/ load in the material props on sides\n unsigned int n_sides = 0;\n in.read((char *) &n_sides, sizeof(n_sides));\n\n for (unsigned int e = 0; e < n_elems; e++)\n {\n unsigned int elem_id = 0;\n in.read((char *) &elem_id, sizeof(elem_id));\n\n for (unsigned int s = 0; s < n_sides; s++)\n {\n \/\/ read in the properties themselves\n for (unsigned int i = 0; i < n_props; i++)\n {\n unsigned int pid = stateful_prop_ids[prop_names[i]];\n\n bnd_props[e][s][pid]->load(in);\n bnd_propsOld[e][s][pid]->load(in);\n if (_material_props.hasOlderProperties()) \/\/ this should actually check if the value is stored in the file (we do not store it right now)\n bnd_propsOlder[e][s][pid]->load(in);\n }\n }\n }\n\n }\n\n in.close();\n}\n<|endoftext|>"} {"text":"\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: cat %s | %cling -I %S -Xclang -verify\n\/\/ XFAIL:*\n\/\/ Test incompleteType\n\n\n.rawInput 1\nclass __attribute__((annotate(\"Def.h\"))) C;\n\/\/expected-warning + {{}}\n\/\/expected-note + {{}}\n.rawInput 0\n\nC c;\n\/\/expected-error {{}}\n\nImprove and reenable test.\/\/------------------------------------------------------------------------------\n\/\/ CLING - the C++ LLVM-based InterpreterG :)\n\/\/\n\/\/ This file is dual-licensed: you can choose to license it under the University\n\/\/ of Illinois Open Source License or the GNU Lesser General Public License. See\n\/\/ LICENSE.TXT for details.\n\/\/------------------------------------------------------------------------------\n\n\/\/ RUN: cat %s | %cling -I %S -Xclang -verify\n\/\/ Test incompleteType\n\n.rawInput 1\nclass __attribute__((annotate(\"Def.h\"))) C;\n\/\/expected-note + {{}}\n.rawInput 0\n\nC c; \/\/expected-error {{variable has incomplete type 'C'}}\n.q\n<|endoftext|>"} {"text":"\/*\n\t\t\t\tCopyright \n\t\tSee file COPYING for copying conditions.*\/\n\n\n#include \"server\/zone\/objects\/resource\/ResourceContainer.h\"\n#include \"server\/zone\/objects\/resource\/ResourceSpawn.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectDeltaMessage3.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectMessage3.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectMessage6.h\"\n#include \"server\/zone\/ZoneClientSession.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/objects\/tangible\/TangibleObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n\nvoid ResourceContainerImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object) {\n\tTangibleObjectImplementation::fillAttributeList(alm, object);\n\n\tStringBuffer ssQuantity;\n\tssQuantity << stackQuantity << \"\/\" << ResourceContainer::MAXSIZE;\n\n\talm->insertAttribute(\"resource_name\", getSpawnName());\n\talm->insertAttribute(\"resource_contents\", ssQuantity);\n\n\tif (spawnObject != NULL)\n\t\tspawnObject->fillAttributeList(alm, object);\n\telse\n\t\tobject->sendSystemMessage(\"error resource container has no spawn object\");\n}\n\nvoid ResourceContainerImplementation::sendBaselinesTo(SceneObject* player) {\n\tinfo(\"sending rnco baselines\");\n\n\tBaseMessage* rnco3 = new ResourceContainerObjectMessage3(_this.get());\n\tplayer->sendMessage(rnco3);\n\n\tBaseMessage* rnco6 = new ResourceContainerObjectMessage6(_this.get());\n\tplayer->sendMessage(rnco6);\n}\n\nvoid ResourceContainerImplementation::setUseCount(uint32 newQuantity, bool notifyClient) {\n\tsetQuantity(newQuantity, notifyClient);\n}\n\nvoid ResourceContainerImplementation::setQuantity(uint32 quantity, bool doNotify, bool ignoreMax) {\n\tLocker _locker(_this.get());\n\tManagedReference parent = getParent().get();\n\tstackQuantity = quantity;\n\n\tif(stackQuantity < 1) {\n\n\t\tif(parent != NULL) {\n\t\t\t\/*parent->broadcastDestroy(_this.get(), true);\n\t\t\tparent->removeObject(_this.get(), false);*\/\n\t\t\t\/\/setParent(NULL);\n\n\t\t\tdestroyObjectFromWorld(true);\n\t\t}\n\n\t\tdestroyObjectFromDatabase(true);\n\t\treturn;\n\t}\n\n\tint newStackSize = 0;\n\n\tif (!ignoreMax && stackQuantity > ResourceContainer::MAXSIZE) {\n\n\t\tnewStackSize = stackQuantity - ResourceContainer::MAXSIZE;\n\t\tstackQuantity = ResourceContainer::MAXSIZE;\n\t}\n\n\tif (newStackSize > 0) {\n\t\tif (parent != NULL) {\n\n\t\t\tResourceContainer* harvestedResource = spawnObject->createResource(newStackSize);\n\n\t\t\tif (parent->transferObject(harvestedResource, -1, true)) {\n\t\t\t\tparent->broadcastObject(harvestedResource, true);\n\t\t\t} else {\n\t\t\t\tharvestedResource->destroyObjectFromDatabase(true);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!doNotify)\n\t\treturn;\n\n\tResourceContainerObjectDeltaMessage3* rcnod3 =\n\t\t\tnew ResourceContainerObjectDeltaMessage3(_this.get());\n\n\trcnod3->updateQuantity();\n\trcnod3->close();\n\n\tbroadcastMessage(rcnod3, true);\n}\n\nvoid ResourceContainerImplementation::split(int newStackSize) {\n\tif (getQuantity() <= newStackSize)\n\t\treturn;\n\n\tif(newStackSize > getQuantity())\n\t\tnewStackSize = getQuantity();\n\n\tManagedReference sceneParent = cast(parent.get().get());\n\n\tif (sceneParent == NULL)\n\t\treturn;\n\n\tLocker locker(spawnObject);\n\n\tManagedReference newResource = spawnObject->createResource(newStackSize);\n\n\tlocker.release();\n\n\tif(newResource == NULL)\n\t\treturn;\n\n\tLocker rlocker(newResource);\n\n\tif (newResource->getSpawnObject() == NULL) {\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t\treturn;\n\t}\n\n\tif(sceneParent->transferObject(newResource, -1, true)) {\n\t\tsceneParent->broadcastObject(newResource, true);\n\n\t\tsetQuantity(getQuantity() - newStackSize);\n\t} else {\n\t\tStringBuffer errorMessage;\n\t\terrorMessage << \"Unable to split resource in container type: \" << sceneParent->getGameObjectType() << \" \" << sceneParent->getDisplayedName();\n\t\terror(errorMessage.toString());\n\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t}\n}\n\nvoid ResourceContainerImplementation::split(int newStackSize, CreatureObject* player) {\n\n\tManagedReference inventory = player->getSlottedObject(\"inventory\");\n\n\tif (inventory == NULL)\n\t\treturn;\n\n\tLocker locker(spawnObject);\n\n\tManagedReference newResource = spawnObject->createResource(newStackSize);\n\n\tlocker.release();\n\n\tif (newResource == NULL)\n\t\treturn;\n\n\tLocker rlocker(newResource);\n\n\tif (newResource->getSpawnObject() == NULL) {\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t\treturn;\n\t}\n\n\tif(inventory->transferObject(newResource, -1, true)) {\n\t\tnewResource->sendTo(player, true);\n\n\t\tsetQuantity(getQuantity() - newStackSize);\n\t} else {\n\t\terror(\"Unable to split resource to player: \" + player->getFirstName());\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t}\n}\n\nvoid ResourceContainerImplementation::combine(ResourceContainer* fromContainer) {\n\tLocker _locker(_this.get());\n\tLocker clocker(fromContainer, _this.get());\n\n\tsetQuantity(getQuantity() + fromContainer->getQuantity());\n\tfromContainer->setQuantity(0);\n\n\tfromContainer->destroyObjectFromWorld(true);\n\tfromContainer->destroyObjectFromDatabase(true);\n}\n\nvoid ResourceContainerImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {\n\tTangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);\n\n\tif (spawnObject != NULL)\n\t\tspawnObject->decreaseContainerReferenceCount();\n}\n[Fixed] stability issue\/*\n\t\t\t\tCopyright \n\t\tSee file COPYING for copying conditions.*\/\n\n\n#include \"server\/zone\/objects\/resource\/ResourceContainer.h\"\n#include \"server\/zone\/objects\/resource\/ResourceSpawn.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectDeltaMessage3.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectMessage3.h\"\n#include \"server\/zone\/packets\/resource\/ResourceContainerObjectMessage6.h\"\n#include \"server\/zone\/ZoneClientSession.h\"\n#include \"server\/zone\/ZoneServer.h\"\n#include \"server\/zone\/objects\/tangible\/TangibleObject.h\"\n#include \"server\/zone\/objects\/creature\/CreatureObject.h\"\n\nvoid ResourceContainerImplementation::fillAttributeList(AttributeListMessage* alm, CreatureObject* object) {\n\tTangibleObjectImplementation::fillAttributeList(alm, object);\n\n\tStringBuffer ssQuantity;\n\tssQuantity << stackQuantity << \"\/\" << ResourceContainer::MAXSIZE;\n\n\talm->insertAttribute(\"resource_name\", getSpawnName());\n\talm->insertAttribute(\"resource_contents\", ssQuantity);\n\n\tif (spawnObject != NULL)\n\t\tspawnObject->fillAttributeList(alm, object);\n\telse\n\t\tobject->sendSystemMessage(\"error resource container has no spawn object\");\n}\n\nvoid ResourceContainerImplementation::sendBaselinesTo(SceneObject* player) {\n\tinfo(\"sending rnco baselines\");\n\n\tBaseMessage* rnco3 = new ResourceContainerObjectMessage3(_this.get());\n\tplayer->sendMessage(rnco3);\n\n\tBaseMessage* rnco6 = new ResourceContainerObjectMessage6(_this.get());\n\tplayer->sendMessage(rnco6);\n}\n\nvoid ResourceContainerImplementation::setUseCount(uint32 newQuantity, bool notifyClient) {\n\tsetQuantity(newQuantity, notifyClient);\n}\n\nvoid ResourceContainerImplementation::setQuantity(uint32 quantity, bool doNotify, bool ignoreMax) {\n\tLocker _locker(_this.get());\n\tManagedReference parent = getParent().get();\n\tstackQuantity = quantity;\n\n\tif(stackQuantity < 1) {\n\n\t\tif(parent != NULL) {\n\t\t\t\/*parent->broadcastDestroy(_this.get(), true);\n\t\t\tparent->removeObject(_this.get(), false);*\/\n\t\t\t\/\/setParent(NULL);\n\n\t\t\tdestroyObjectFromWorld(true);\n\t\t}\n\n\t\tdestroyObjectFromDatabase(true);\n\t\treturn;\n\t}\n\n\tint newStackSize = 0;\n\n\tif (!ignoreMax && stackQuantity > ResourceContainer::MAXSIZE) {\n\n\t\tnewStackSize = stackQuantity - ResourceContainer::MAXSIZE;\n\t\tstackQuantity = ResourceContainer::MAXSIZE;\n\t}\n\n\tif (newStackSize > 0) {\n\t\tif (parent != NULL) {\n\n\t\t\tLocker locker(spawnObject);\n\n\t\t\tResourceContainer* harvestedResource = spawnObject->createResource(newStackSize);\n\n\t\t\tlocker.release();\n\n\t\t\tLocker clocker(harvestedResource, _this.get());\n\n\t\t\tif (parent->transferObject(harvestedResource, -1, true)) {\n\t\t\t\tparent->broadcastObject(harvestedResource, true);\n\t\t\t} else {\n\t\t\t\tharvestedResource->destroyObjectFromDatabase(true);\n\t\t\t}\n\t\t}\n\t}\n\n\tif(!doNotify)\n\t\treturn;\n\n\tResourceContainerObjectDeltaMessage3* rcnod3 =\n\t\t\tnew ResourceContainerObjectDeltaMessage3(_this.get());\n\n\trcnod3->updateQuantity();\n\trcnod3->close();\n\n\tbroadcastMessage(rcnod3, true);\n}\n\nvoid ResourceContainerImplementation::split(int newStackSize) {\n\tif (getQuantity() <= newStackSize)\n\t\treturn;\n\n\tif(newStackSize > getQuantity())\n\t\tnewStackSize = getQuantity();\n\n\tManagedReference sceneParent = cast(parent.get().get());\n\n\tif (sceneParent == NULL)\n\t\treturn;\n\n\tLocker locker(spawnObject);\n\n\tManagedReference newResource = spawnObject->createResource(newStackSize);\n\n\tlocker.release();\n\n\tif(newResource == NULL)\n\t\treturn;\n\n\tLocker rlocker(newResource);\n\n\tif (newResource->getSpawnObject() == NULL) {\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t\treturn;\n\t}\n\n\tif(sceneParent->transferObject(newResource, -1, true)) {\n\t\tsceneParent->broadcastObject(newResource, true);\n\n\t\tsetQuantity(getQuantity() - newStackSize);\n\t} else {\n\t\tStringBuffer errorMessage;\n\t\terrorMessage << \"Unable to split resource in container type: \" << sceneParent->getGameObjectType() << \" \" << sceneParent->getDisplayedName();\n\t\terror(errorMessage.toString());\n\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t}\n}\n\nvoid ResourceContainerImplementation::split(int newStackSize, CreatureObject* player) {\n\n\tManagedReference inventory = player->getSlottedObject(\"inventory\");\n\n\tif (inventory == NULL)\n\t\treturn;\n\n\tLocker locker(spawnObject);\n\n\tManagedReference newResource = spawnObject->createResource(newStackSize);\n\n\tlocker.release();\n\n\tif (newResource == NULL)\n\t\treturn;\n\n\tLocker rlocker(newResource);\n\n\tif (newResource->getSpawnObject() == NULL) {\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t\treturn;\n\t}\n\n\tif(inventory->transferObject(newResource, -1, true)) {\n\t\tnewResource->sendTo(player, true);\n\n\t\tsetQuantity(getQuantity() - newStackSize);\n\t} else {\n\t\terror(\"Unable to split resource to player: \" + player->getFirstName());\n\t\tnewResource->destroyObjectFromDatabase(true);\n\t}\n}\n\nvoid ResourceContainerImplementation::combine(ResourceContainer* fromContainer) {\n\tLocker _locker(_this.get());\n\tLocker clocker(fromContainer, _this.get());\n\n\tsetQuantity(getQuantity() + fromContainer->getQuantity());\n\tfromContainer->setQuantity(0);\n\n\tfromContainer->destroyObjectFromWorld(true);\n\tfromContainer->destroyObjectFromDatabase(true);\n}\n\nvoid ResourceContainerImplementation::destroyObjectFromDatabase(bool destroyContainedObjects) {\n\tTangibleObjectImplementation::destroyObjectFromDatabase(destroyContainedObjects);\n\n\tif (spawnObject != NULL)\n\t\tspawnObject->decreaseContainerReferenceCount();\n}\n<|endoftext|>"} {"text":"#include \"fht.h\"\n\n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"test_utils.h\"\n\nusing lsh::compare_vectors;\nusing lsh::fht;\nusing std::vector;\n\nconst float eps = 0.0001;\n\nTEST(PolytopeHashTest, FHTTest1) {\n vector data1 = {0.0, 1.0, 0.0, 0.0};\n vector expected_result1 = {1.0, -1.0, 1.0, -1.0};\n int log_dim1 = std::log2(data1.size());\n fht(data1.data(), data1.size(), log_dim1);\n compare_vectors(expected_result1, data1, eps);\n}\nremoving old FHT test<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \"chtable.hpp\"\n#include \"hash_mixer.hpp\"\n\n\n\nnamespace chtable{\ntemplate <>\nclass Hash {\n\tHashMixer hashf_;\npublic:\n\tHash(unsigned k, unsigned seed) : hashf_(k, seed){}\n\tunsigned operator () (unsigned i, unsigned k) const\n\t{\n\t\treturn hashf_(i, k);\n\t}\n};\n}\nstatic inline unsigned random(unsigned x)\n{\n\treturn (x * 16807) % ((2 << 31) - 1);\n}\n\n\n\ntemplate\nstruct ChtableTester{\n\tunsigned data [LENGTH];\n\tunsigned membership[LENGTH];\n\tChtable t;\n\tdouble maxLoad;\n\tdouble count;\n\tdouble capacity;\n\tdouble totalLoad;\n\tChtableTester()\n\t\t:t(13, 2)\n\t{\n\t\tunsigned seed = 10;\n\t\tfor(int i = 0; i < LENGTH; i++)\n\t\t{\n\t\t\tseed = random(seed);\n\t\t\tdata[i] = seed;\n\t\t\tmembership[i] = 0;\n\t\t}\n\t\t\n\t\tmaxLoad = 0;\n\t\ttotalLoad = 0;\n\t}\n\t\n\tclock_t testInsert()\n\t{\n\t\tclock_t t1 = clock();\n\t\tfor(unsigned i = 0; i < LENGTH; i++) {\n\t\t\tbool good = t.Set(data[i], i);\n\t\t\tassert(good);\n\n\t\t\tbool found;\n\t\t\tunsigned val;\n\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\tassert(found);\n\t\t\tassert(val == i);\n\t\t\t\n\t\t\tcount = t.count();\n\t\t\tcapacity = t.capacity();\n\t\t\tdouble load = count \/ capacity;\n\t\t\ttotalLoad += load;\n\t\t\tif(load > maxLoad)\n\t\t\t\tmaxLoad = load;\n\t\t}\n\t\tclock_t t2 = clock();\n\t\treturn t2 - t1;\n\t}\n\tvoid testFind()\n\t{\n\t\tfor(unsigned i = 0; i < LENGTH; i++)\n\t\t{\n\t\t\tbool found;\n\t\t\tunsigned val;\n\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\tif( !found )\n\t\t\t\tfputs(\"find error\\n\", stderr);\n\t\t\telse if( val != i)\n\t\t\t\tfputs(\"data error 3\\n\", stderr);\n\t\t}\n\t}\n\t\n\tvoid testDelete()\n\t{\n\t\tfor(unsigned i = 0; i < LENGTH; i++)\n\t\t{\n\t\t\tbool found;\n\t\t\tunsigned val;\n\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\tif( found )\n\t\t\t{\n\t\t\t\tt.Delete(data[i]);\n\t\t\t\t\n\t\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\t\tif( found )\n\t\t\t\t\tputs(\"removal error\");\n\t\t\t}\n\t\t}\n\t}\n\tvoid testIterator()\n\t{\n\t\tfor(auto & pair : t)\n\t\t{\n\t\t\tunsigned i = pair.val;\n\t\t\tif(data[i] != pair.key)\n\t\t\t\tfputs(\"data error\\n\", stderr);\n\t\t}\n\t}\n};\nint main(void)\n{\n\t\n\tChtableTester<30000> t;\n\tclock_t insertTime = t.testInsert();\n\t\n\tstd::cout << \"count: \" << t.count << std::endl <<\n\t\t\"capacity: \" << t.capacity << std::endl <<\n\t\t\"max load: \" << t.maxLoad << std::endl <<\n\t\t\"current load: \" << t.count \/ t.capacity << std::endl << \n\t\t\"average load: \" << t.totalLoad \/ t.count << std::endl <<\n\t\t\"time: \" << insertTime << std::endl;\n\tt.testFind();\n\tt.testDelete();\n\tt.testIterator();\n\t\/\/ test iterator\n\t\n\t\n\t\/\/ test find\n\t\n\t\n\t\/\/ test removal\n\t\n\t\n\t\n\treturn 0;\n }\nmore detailed test program#include \n#include \n#include \n#include \"chtable.hpp\"\n#include \"hash_mixer.hpp\"\n\n\n\nnamespace chtable{\ntemplate <>\nclass Hash {\n\tHashMixer hashf_;\npublic:\n\tHash(unsigned k, unsigned seed) : hashf_(k, seed){}\n\tunsigned operator () (unsigned i, unsigned k) const\n\t{\n\t\treturn hashf_(i, k);\n\t}\n};\n}\nstatic inline unsigned random(unsigned x)\n{\n\treturn (x * 16807) % ((2 << 31) - 1);\n}\n\n\n\ntemplate\nstruct ChtableTester{\n\tunsigned data [LENGTH];\n\tunsigned membership[LENGTH];\n\tChtable t;\n\tdouble maxLoad;\n\tdouble count;\n\tdouble capacity;\n\tdouble totalLoad;\n\tChtableTester()\n\t\t:t(30000, 2)\n\t{\n\t\tunsigned seed = 10;\n\t\tfor(int i = 0; i < LENGTH; i++)\n\t\t{\n\t\t\tseed = random(seed);\n\t\t\tdata[i] = seed;\n\t\t\tmembership[i] = 0;\n\t\t}\n\t\t\n\t\tmaxLoad = 0;\n\t\ttotalLoad = 0;\n\t}\n\t\n\tclock_t testInsert()\n\t{\n\t\tclock_t t1 = clock();\n\t\tfor(unsigned i = 0; i < LENGTH; i++) {\n\t\t\tt.Set(data[i], i);\n\n\t\t\tbool found;\n\t\t\tunsigned val;\n\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\tassert(found);\n\t\t\tassert(val == i);\n\t\t\t\n\t\t\tcount = t.count();\n\t\t\tcapacity = t.capacity();\n\t\t\tdouble load = count \/ capacity;\n\t\t\ttotalLoad += load;\n\t\t\tif(load > maxLoad)\n\t\t\t\tmaxLoad = load;\n\t\t}\n\t\tclock_t t2 = clock();\n\t\treturn t2 - t1;\n\t}\n\tclock_t testFind()\n\t{\n\t\tclock_t t1 = clock();\n\t\tfor(unsigned i = 0; i < LENGTH; i++)\n\t\t{\n\t\t\tbool found;\n\t\t\tunsigned val;\n\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\tif( !found )\n\t\t\t\tfputs(\"find error\\n\", stderr);\n\t\t\telse if( val != i)\n\t\t\t\tfputs(\"data error 3\\n\", stderr);\n\t\t}\n\t\tclock_t t2 = clock();\n\t\treturn t2 - t1;\n\t}\n\t\n\tclock_t testDelete()\n\t{\n\t\tclock_t t1 = clock();\n\t\tfor(unsigned i = 0; i < LENGTH; i++)\n\t\t{\n\t\t\tbool found;\n\t\t\tunsigned val;\n\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\tif( found )\n\t\t\t{\n\t\t\t\tbool good = t.Delete(data[i]);\n\t\t\t\tassert(good);\n\t\t\t\tstd::tie(val, found) = t.Get(data[i]);\n\t\t\t\tif( found )\n\t\t\t\t\tputs(\"removal error\");\n\t\t\t}\n\t\t}\n\t\tclock_t t2 = clock();\n\t\treturn t2 - t1;\n\t}\n\tclock_t testIterator()\n\t{\n\t\tclock_t t1 = clock();\n\t\tfor(auto pair : t)\n\t\t{\n\t\t\tunsigned i = pair.val;\n\t\t\tif(data[i] != pair.key)\n\t\t\t\tfputs(\"iterator error\\n\", stderr);\n\t\t}\n\t\tclock_t t2 = clock();\n\t\treturn t2 - t1;\n\t}\n};\nint main(void)\n{\n\t\n\tChtableTester<30000> t;\n\tclock_t insertTime = t.testInsert();\n\t\n\tstd::cout << \"count: \" << t.count << std::endl <<\n\t\t\"capacity: \" << t.capacity << std::endl <<\n\t\t\"max load: \" << t.maxLoad << std::endl <<\n\t\t\"current load: \" << t.count \/ t.capacity << std::endl << \n\t\t\"average load: \" << t.totalLoad \/ t.count << std::endl <<\n\t\t\"insert time: \" << insertTime << std::endl;\n\t\t\n\tclock_t findTime = t.testFind();\n\tstd::cout << \"find time: \" << findTime << std::endl;\n\t\n\tclock_t iterTime = t.testIterator();\n\tstd::cout << \"iter time: \" << iterTime << std::endl;\n\t\n\tclock_t deleteTime = t.testDelete();\n\tstd::cout << \"delete time: \" << deleteTime << std::endl;\n\n\treturn 0;\n }\n<|endoftext|>"} {"text":"\/\/ RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -Wmicrosoft -verify -fms-extensions -fexceptions -fcxx-exceptions\n\n\n\/\/ ::type_info is predeclared with forward class declartion\nvoid f(const type_info &a);\n\n\n\/\/ Microsoft doesn't validate exception specification.\nvoid foo(); \/\/ expected-note {{previous declaration}}\nvoid foo() throw(); \/\/ expected-warning {{exception specification in declaration does not match previous declaration}}\n\nvoid r6() throw(...); \/\/ expected-note {{previous declaration}}\nvoid r6() throw(int); \/\/ expected-warning {{exception specification in declaration does not match previous declaration}}\n\nstruct Base {\n virtual void f2();\n virtual void f3() throw(...);\n};\n\nstruct Derived : Base {\n virtual void f2() throw(...);\n virtual void f3();\n};\n\n\n\/\/ MSVC allows type definition in anonymous union and struct\nstruct A\n{\n union \n {\n int a;\n struct B \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n { \n int c;\n } d;\n\n union C \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n {\n int e;\n int ee;\n } f;\n\n typedef int D; \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n struct F; \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n };\n\n struct\n {\n int a2;\n\n struct B2 \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n {\n int c2;\n } d2;\n \n\tunion C2 \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n {\n int e2;\n int ee2;\n } f2;\n\n typedef int D2; \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n struct F2; \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n };\n};\n\n\/\/ __stdcall handling\nstruct M {\n int __stdcall addP();\n float __stdcall subtractP(); \n};\n\ntemplate void h1(T (__stdcall M::* const )()) { }\n\nvoid m1() {\n h1(&M::addP);\n h1(&M::subtractP);\n} \n\n\/\/MSVC allows forward enum declaration\nenum ENUM; \/\/ expected-warning {{forward references to 'enum' types are a Microsoft extension}}\nENUM *var = 0; \nENUM var2 = (ENUM)3;\nenum ENUM1* var3 = 0;\/\/ expected-warning {{forward references to 'enum' types are a Microsoft extension}}\n\n\nenum ENUM2 {\n\tENUM2_a = (enum ENUM2) 4,\n\tENUM2_b = 0x9FFFFFFF, \/\/ expected-warning {{enumerator value is not representable in the underlying type 'int'}}\n\tENUM2_c = 0x100000000 \/\/ expected-warning {{enumerator value is not representable in the underlying type 'int'}}\n};\n\n\nvoid f(long long);\nvoid f(int);\n \nint main()\n{\n \/\/ This is an ambiguous call in standard C++.\n \/\/ This calls f(long long) in Microsoft mode because LL is always signed.\n f(0xffffffffffffffffLL);\n f(0xffffffffffffffffi64);\n}\n\n\/\/ Enumeration types with a fixed underlying type.\nconst int seventeen = 17;\ntypedef int Int;\n\nstruct X0 {\n enum E1 : Int { SomeOtherValue } field; \/\/ expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}\n enum E1 : seventeen;\n};\n\nenum : long long { \/\/ expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}\n SomeValue = 0x100000000\n};\n\n\nclass AAA {\n__declspec(dllimport) void f(void) { }\nvoid f2(void);\n};\n\n__declspec(dllimport) void AAA::f2(void) { \/\/ expected-error {{dllimport attribute can be applied only to symbol}}\n\n}\n\n\n\ntemplate \nclass BB {\npublic:\n void f(int g = 10 ); \/\/ expected-note {{previous definition is here}}\n};\n\ntemplate \nvoid BB::f(int g = 0) { } \/\/ expected-warning {{redefinition of default argument}}\n\n\nnamespace MissingTypename {\n\ntemplate class A {\npublic:\n\t typedef int TYPE;\n};\n\ntemplate class B {\npublic:\n\t typedef int TYPE;\n};\n\n\ntemplate\nclass C : private A, public B {\npublic:\n typedef A Base1;\n typedef B Base2;\n typedef A Base3;\n\n A::TYPE a1; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n Base1::TYPE a2; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n\n B::TYPE a3; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n Base2::TYPE a4; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n\n A::TYPE a5; \/\/ expected-error {{missing 'typename' prior to dependent type name}}\n Base3::TYPE a6; \/\/ expected-error {{missing 'typename' prior to dependent type name}}\n };\n\n}\n\n\n\n\nextern void static_func();\nvoid static_func(); \/\/ expected-note {{previous declaration is here}}\n\n\nstatic void static_func() \/\/ expected-warning {{static declaration of 'static_func' follows non-static declaration}}\n{\n\n}\n\nlong function_prototype(int a);\nlong (*function_ptr)(int a);\n\nvoid function_to_voidptr_conv() {\n void *a1 = function_prototype;\n void *a2 = &function_prototype;\n void *a1 = function_ptr;\n void *a2 = &function_ptr;\n}\nFix test.\/\/ RUN: %clang_cc1 %s -triple i686-pc-win32 -fsyntax-only -Wmicrosoft -verify -fms-extensions -fexceptions -fcxx-exceptions\n\n\n\/\/ ::type_info is predeclared with forward class declartion\nvoid f(const type_info &a);\n\n\n\/\/ Microsoft doesn't validate exception specification.\nvoid foo(); \/\/ expected-note {{previous declaration}}\nvoid foo() throw(); \/\/ expected-warning {{exception specification in declaration does not match previous declaration}}\n\nvoid r6() throw(...); \/\/ expected-note {{previous declaration}}\nvoid r6() throw(int); \/\/ expected-warning {{exception specification in declaration does not match previous declaration}}\n\nstruct Base {\n virtual void f2();\n virtual void f3() throw(...);\n};\n\nstruct Derived : Base {\n virtual void f2() throw(...);\n virtual void f3();\n};\n\n\n\/\/ MSVC allows type definition in anonymous union and struct\nstruct A\n{\n union \n {\n int a;\n struct B \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n { \n int c;\n } d;\n\n union C \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n {\n int e;\n int ee;\n } f;\n\n typedef int D; \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n struct F; \/\/ expected-warning {{types declared in an anonymous union are a Microsoft extension}}\n };\n\n struct\n {\n int a2;\n\n struct B2 \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n {\n int c2;\n } d2;\n \n\tunion C2 \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n {\n int e2;\n int ee2;\n } f2;\n\n typedef int D2; \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n struct F2; \/\/ expected-warning {{types declared in an anonymous struct are a Microsoft extension}}\n };\n};\n\n\/\/ __stdcall handling\nstruct M {\n int __stdcall addP();\n float __stdcall subtractP(); \n};\n\ntemplate void h1(T (__stdcall M::* const )()) { }\n\nvoid m1() {\n h1(&M::addP);\n h1(&M::subtractP);\n} \n\n\/\/MSVC allows forward enum declaration\nenum ENUM; \/\/ expected-warning {{forward references to 'enum' types are a Microsoft extension}}\nENUM *var = 0; \nENUM var2 = (ENUM)3;\nenum ENUM1* var3 = 0;\/\/ expected-warning {{forward references to 'enum' types are a Microsoft extension}}\n\n\nenum ENUM2 {\n\tENUM2_a = (enum ENUM2) 4,\n\tENUM2_b = 0x9FFFFFFF, \/\/ expected-warning {{enumerator value is not representable in the underlying type 'int'}}\n\tENUM2_c = 0x100000000 \/\/ expected-warning {{enumerator value is not representable in the underlying type 'int'}}\n};\n\n\nvoid f(long long);\nvoid f(int);\n \nint main()\n{\n \/\/ This is an ambiguous call in standard C++.\n \/\/ This calls f(long long) in Microsoft mode because LL is always signed.\n f(0xffffffffffffffffLL);\n f(0xffffffffffffffffi64);\n}\n\n\/\/ Enumeration types with a fixed underlying type.\nconst int seventeen = 17;\ntypedef int Int;\n\nstruct X0 {\n enum E1 : Int { SomeOtherValue } field; \/\/ expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}\n enum E1 : seventeen;\n};\n\nenum : long long { \/\/ expected-warning{{enumeration types with a fixed underlying type are a Microsoft extension}}\n SomeValue = 0x100000000\n};\n\n\nclass AAA {\n__declspec(dllimport) void f(void) { }\nvoid f2(void);\n};\n\n__declspec(dllimport) void AAA::f2(void) { \/\/ expected-error {{dllimport attribute can be applied only to symbol}}\n\n}\n\n\n\ntemplate \nclass BB {\npublic:\n void f(int g = 10 ); \/\/ expected-note {{previous definition is here}}\n};\n\ntemplate \nvoid BB::f(int g = 0) { } \/\/ expected-warning {{redefinition of default argument}}\n\n\nnamespace MissingTypename {\n\ntemplate class A {\npublic:\n\t typedef int TYPE;\n};\n\ntemplate class B {\npublic:\n\t typedef int TYPE;\n};\n\n\ntemplate\nclass C : private A, public B {\npublic:\n typedef A Base1;\n typedef B Base2;\n typedef A Base3;\n\n A::TYPE a1; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n Base1::TYPE a2; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n\n B::TYPE a3; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n Base2::TYPE a4; \/\/ expected-warning {{missing 'typename' prior to dependent type name}}\n\n A::TYPE a5; \/\/ expected-error {{missing 'typename' prior to dependent type name}}\n Base3::TYPE a6; \/\/ expected-error {{missing 'typename' prior to dependent type name}}\n };\n\n}\n\n\n\n\nextern void static_func();\nvoid static_func(); \/\/ expected-note {{previous declaration is here}}\n\n\nstatic void static_func() \/\/ expected-warning {{static declaration of 'static_func' follows non-static declaration}}\n{\n\n}\n\nlong function_prototype(int a);\nlong (*function_ptr)(int a);\n\nvoid function_to_voidptr_conv() {\n void *a1 = function_prototype;\n void *a2 = &function_prototype;\n void *a3 = function_ptr;\n}\n<|endoftext|>"} {"text":"\r\n\/*\r\n * benchmark_bwtree_full.cpp - This file contains test suites for command\r\n * benchmark-bwtree-full\r\n *\/\r\n\r\n#include \"test_suite.h\"\r\n\r\n\/*\r\n * BenchmarkBwTreeRandInsert() - As name suggests\r\n *\r\n * Note that for this function we do not pass a bwtree instance for it and \r\n * instead we make and destroy the object inside the function, since we\r\n * do not use this function's result to test read (i.e. all read operations\r\n * are tested upon a sequentially populated BwTree instance)\r\n *\/\r\nvoid BenchmarkBwTreeRandInsert(int key_num, int thread_num) {\r\n \/\/ Get an empty trrr; do not print its construction message\r\n TreeType *t = GetEmptyTree(true);\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[thread_num];\r\n for(int i = 0;i < thread_num;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n \/\/ This generates a permutation on [0, key_num)\r\n Permutation perm{(size_t)key_num, 0};\r\n \r\n auto func = [key_num, \r\n &thread_time, \r\n thread_num,\r\n &perm](uint64_t thread_id, TreeType *t) {\r\n long int start_key = key_num \/ thread_num * (long)thread_id;\r\n long int end_key = start_key + key_num \/ thread_num;\r\n\r\n \/\/ Declare timer and start it immediately\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int i = start_key;i < end_key;i++) {\r\n long long int key = perm[i];\r\n \r\n t->Insert(key, key);\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (key_num \/ thread_num) \/ (1024.0 * 1024.0) \/ duration \\\r\n << \" million random insert\/sec\" << \"\\n\";\r\n\r\n \/\/ Print L3 total accesses and cache misses\r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(thread_num, func, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < thread_num;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << thread_num << \" Threads BwTree: overall \"\r\n << (key_num \/ (1024.0 * 1024.0) * thread_num) \/ elapsed_seconds\r\n << \" million random insert\/sec\" << \"\\n\";\r\n \r\n \/\/ Remove the tree instance\r\n delete t;\r\n \r\n return;\r\n}\r\n\r\n\/*\r\n * BenchmarkBwTreeSeqInsert() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeSeqInsert(TreeType *t, \r\n int key_num, \r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n\r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n\r\n auto func = [key_num, \r\n &thread_time, \r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n long int start_key = key_num \/ num_thread * (long)thread_id;\r\n long int end_key = start_key + key_num \/ num_thread;\r\n\r\n \/\/ Declare timer and start it immediately\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int i = start_key;i < end_key;i++) {\r\n t->Insert(i, i);\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (key_num \/ num_thread) \/ (1024.0 * 1024.0) \/ duration \\\r\n << \" million insert\/sec\" << \"\\n\";\r\n \r\n \/\/ Print L3 total accesses and cache misses\r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n\r\n thread_time[thread_id] = duration;\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (key_num \/ (1024.0 * 1024.0) * num_thread) \/ elapsed_seconds\r\n << \" million insert\/sec\" << \"\\n\";\r\n \r\n return;\r\n}\r\n\r\n\/*\r\n * BenchmarkBwTreeSeqRead() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeSeqRead(TreeType *t, \r\n int key_num,\r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n int iter = 1;\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n auto func = [key_num, \r\n iter, \r\n &thread_time, \r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n std::vector v{};\r\n\r\n v.reserve(1);\r\n\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int j = 0;j < iter;j++) {\r\n for(int i = 0;i < key_num;i++) {\r\n t->GetValue(i, v);\r\n\r\n v.clear();\r\n }\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (iter * key_num \/ (1024.0 * 1024.0)) \/ duration \\\r\n << \" million read\/sec\" << \"\\n\";\r\n \r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func, t);\r\n \r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (iter * key_num \/ (1024.0 * 1024.0) * num_thread * num_thread) \/ elapsed_seconds\r\n << \" million read\/sec\" << \"\\n\";\r\n\r\n return;\r\n}\r\n\r\n\/*\r\n * BenchmarkBwTreeRandRead() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeRandRead(TreeType *t, \r\n int key_num,\r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n int iter = 1;\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n auto func2 = [key_num, \r\n iter, \r\n &thread_time,\r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n std::vector v{};\r\n\r\n v.reserve(1);\r\n \r\n \/\/ This is the random number generator we use\r\n SimpleInt64Random<0, 30 * 1024 * 1024> h{};\r\n\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int j = 0;j < iter;j++) {\r\n for(int i = 0;i < key_num;i++) {\r\n \/\/int key = uniform_dist(e1);\r\n long int key = (long int)h((uint64_t)i, thread_id);\r\n\r\n t->GetValue(key, v);\r\n\r\n v.clear();\r\n }\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (iter * key_num \/ (1024.0 * 1024.0)) \/ duration \\\r\n << \" million read (random)\/sec\" << \"\\n\";\r\n \r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func2, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (iter * key_num \/ (1024.0 * 1024.0) * num_thread * num_thread) \/ elapsed_seconds\r\n << \" million read (random)\/sec\" << \"\\n\";\r\n\r\n return;\r\n}\r\n\r\n\r\n\/*\r\n * BenchmarkBwTreeZipfRead() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeZipfRead(TreeType *t, \r\n int key_num,\r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n int iter = 1;\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n \/\/ Generate zipfian distribution into this list\r\n std::vector zipfian_key_list{};\r\n zipfian_key_list.reserve(key_num);\r\n \r\n \/\/ Initialize it with time() as the random seed\r\n Zipfian zipf{(uint64_t)key_num, 0.99, (uint64_t)time(NULL)};\r\n \r\n \/\/ Populate the array with random numbers \r\n for(int i = 0;i < key_num;i++) {\r\n zipfian_key_list.push_back(zipf.Get()); \r\n }\r\n \r\n auto func2 = [key_num, \r\n iter, \r\n &thread_time,\r\n &zipfian_key_list,\r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n \/\/ This is the start and end index we read into the zipfian array\r\n long int start_index = key_num \/ num_thread * (long)thread_id;\r\n long int end_index = start_index + key_num \/ num_thread;\r\n \r\n std::vector v{};\r\n\r\n v.reserve(1);\r\n\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int j = 0;j < iter;j++) {\r\n for(long i = start_index;i < end_index;i++) {\r\n long int key = zipfian_key_list[i];\r\n\r\n t->GetValue(key, v);\r\n\r\n v.clear();\r\n }\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (iter * (end_index - start_index) \/ (1024.0 * 1024.0)) \/ duration \\\r\n << \" million read (zipfian)\/sec\" << \"\\n\";\r\n \r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func2, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (iter * key_num \/ (1024.0 * 1024.0)) \/ (elapsed_seconds \/ num_thread)\r\n << \" million read (zipfian)\/sec\" << \"\\n\";\r\n\r\n return;\r\n}\r\nChange the order of recording time usage and printing on the screen\r\n\/*\r\n * benchmark_bwtree_full.cpp - This file contains test suites for command\r\n * benchmark-bwtree-full\r\n *\/\r\n\r\n#include \"test_suite.h\"\r\n\r\n\/*\r\n * BenchmarkBwTreeRandInsert() - As name suggests\r\n *\r\n * Note that for this function we do not pass a bwtree instance for it and \r\n * instead we make and destroy the object inside the function, since we\r\n * do not use this function's result to test read (i.e. all read operations\r\n * are tested upon a sequentially populated BwTree instance)\r\n *\/\r\nvoid BenchmarkBwTreeRandInsert(int key_num, int thread_num) {\r\n \/\/ Get an empty trrr; do not print its construction message\r\n TreeType *t = GetEmptyTree(true);\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[thread_num];\r\n for(int i = 0;i < thread_num;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n \/\/ This generates a permutation on [0, key_num)\r\n Permutation perm{(size_t)key_num, 0};\r\n \r\n auto func = [key_num, \r\n &thread_time, \r\n thread_num,\r\n &perm](uint64_t thread_id, TreeType *t) {\r\n long int start_key = key_num \/ thread_num * (long)thread_id;\r\n long int end_key = start_key + key_num \/ thread_num;\r\n\r\n \/\/ Declare timer and start it immediately\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int i = start_key;i < end_key;i++) {\r\n long long int key = perm[i];\r\n \r\n t->Insert(key, key);\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (key_num \/ thread_num) \/ (1024.0 * 1024.0) \/ duration \\\r\n << \" million random insert\/sec\" << \"\\n\";\r\n\r\n \/\/ Print L3 total accesses and cache misses\r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(thread_num, func, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < thread_num;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << thread_num << \" Threads BwTree: overall \"\r\n << (key_num \/ (1024.0 * 1024.0) * thread_num) \/ elapsed_seconds\r\n << \" million random insert\/sec\" << \"\\n\";\r\n \r\n \/\/ Remove the tree instance\r\n delete t;\r\n \r\n return;\r\n}\r\n\r\n\/*\r\n * BenchmarkBwTreeSeqInsert() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeSeqInsert(TreeType *t, \r\n int key_num, \r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n\r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n\r\n auto func = [key_num, \r\n &thread_time, \r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n long int start_key = key_num \/ num_thread * (long)thread_id;\r\n long int end_key = start_key + key_num \/ num_thread;\r\n\r\n \/\/ Declare timer and start it immediately\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int i = start_key;i < end_key;i++) {\r\n t->Insert(i, i);\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n\r\n thread_time[thread_id] = duration;\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (key_num \/ num_thread) \/ (1024.0 * 1024.0) \/ duration \\\r\n << \" million insert\/sec\" << \"\\n\";\r\n \r\n \/\/ Print L3 total accesses and cache misses\r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (key_num \/ (1024.0 * 1024.0) * num_thread) \/ elapsed_seconds\r\n << \" million insert\/sec\" << \"\\n\";\r\n \r\n return;\r\n}\r\n\r\n\/*\r\n * BenchmarkBwTreeSeqRead() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeSeqRead(TreeType *t, \r\n int key_num,\r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n int iter = 1;\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n auto func = [key_num, \r\n iter, \r\n &thread_time, \r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n std::vector v{};\r\n\r\n v.reserve(1);\r\n\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int j = 0;j < iter;j++) {\r\n for(int i = 0;i < key_num;i++) {\r\n t->GetValue(i, v);\r\n\r\n v.clear();\r\n }\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (iter * key_num \/ (1024.0 * 1024.0)) \/ duration \\\r\n << \" million read\/sec\" << \"\\n\";\r\n \r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func, t);\r\n \r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (iter * key_num \/ (1024.0 * 1024.0) * num_thread * num_thread) \/ elapsed_seconds\r\n << \" million read\/sec\" << \"\\n\";\r\n\r\n return;\r\n}\r\n\r\n\/*\r\n * BenchmarkBwTreeRandRead() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeRandRead(TreeType *t, \r\n int key_num,\r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n int iter = 1;\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n auto func2 = [key_num, \r\n iter, \r\n &thread_time,\r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n std::vector v{};\r\n\r\n v.reserve(1);\r\n \r\n \/\/ This is the random number generator we use\r\n SimpleInt64Random<0, 30 * 1024 * 1024> h{};\r\n\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int j = 0;j < iter;j++) {\r\n for(int i = 0;i < key_num;i++) {\r\n \/\/int key = uniform_dist(e1);\r\n long int key = (long int)h((uint64_t)i, thread_id);\r\n\r\n t->GetValue(key, v);\r\n\r\n v.clear();\r\n }\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (iter * key_num \/ (1024.0 * 1024.0)) \/ duration \\\r\n << \" million read (random)\/sec\" << \"\\n\";\r\n \r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n \r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func2, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (iter * key_num \/ (1024.0 * 1024.0) * num_thread * num_thread) \/ elapsed_seconds\r\n << \" million read (random)\/sec\" << \"\\n\";\r\n\r\n return;\r\n}\r\n\r\n\r\n\/*\r\n * BenchmarkBwTreeZipfRead() - As name suggests\r\n *\/\r\nvoid BenchmarkBwTreeZipfRead(TreeType *t, \r\n int key_num,\r\n int thread_num) {\r\n const int num_thread = thread_num;\r\n int iter = 1;\r\n \r\n \/\/ This is used to record time taken for each individual thread\r\n double thread_time[num_thread];\r\n for(int i = 0;i < num_thread;i++) {\r\n thread_time[i] = 0.0;\r\n }\r\n \r\n \/\/ Generate zipfian distribution into this list\r\n std::vector zipfian_key_list{};\r\n zipfian_key_list.reserve(key_num);\r\n \r\n \/\/ Initialize it with time() as the random seed\r\n Zipfian zipf{(uint64_t)key_num, 0.99, (uint64_t)time(NULL)};\r\n \r\n \/\/ Populate the array with random numbers \r\n for(int i = 0;i < key_num;i++) {\r\n zipfian_key_list.push_back(zipf.Get()); \r\n }\r\n \r\n auto func2 = [key_num, \r\n iter, \r\n &thread_time,\r\n &zipfian_key_list,\r\n num_thread](uint64_t thread_id, TreeType *t) {\r\n \/\/ This is the start and end index we read into the zipfian array\r\n long int start_index = key_num \/ num_thread * (long)thread_id;\r\n long int end_index = start_index + key_num \/ num_thread;\r\n \r\n std::vector v{};\r\n\r\n v.reserve(1);\r\n\r\n Timer timer{true};\r\n CacheMeter cache{true};\r\n\r\n for(int j = 0;j < iter;j++) {\r\n for(long i = start_index;i < end_index;i++) {\r\n long int key = zipfian_key_list[i];\r\n\r\n t->GetValue(key, v);\r\n\r\n v.clear();\r\n }\r\n }\r\n\r\n cache.Stop();\r\n double duration = timer.Stop();\r\n \r\n thread_time[thread_id] = duration;\r\n\r\n std::cout << \"[Thread \" << thread_id << \" Done] @ \" \\\r\n << (iter * (end_index - start_index) \/ (1024.0 * 1024.0)) \/ duration \\\r\n << \" million read (zipfian)\/sec\" << \"\\n\";\r\n \r\n cache.PrintL3CacheUtilization();\r\n cache.PrintL1CacheUtilization();\r\n\r\n return;\r\n };\r\n\r\n LaunchParallelTestID(num_thread, func2, t);\r\n\r\n double elapsed_seconds = 0.0;\r\n for(int i = 0;i < num_thread;i++) {\r\n elapsed_seconds += thread_time[i];\r\n }\r\n\r\n std::cout << num_thread << \" Threads BwTree: overall \"\r\n << (iter * key_num \/ (1024.0 * 1024.0)) \/ (elapsed_seconds \/ num_thread)\r\n << \" million read (zipfian)\/sec\" << \"\\n\";\r\n\r\n return;\r\n}\r\n<|endoftext|>"} {"text":"\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/config.hpp\"\n\n#define CAF_SUITE streambuf\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \"caf\/streambuf.hpp\"\n\nusing namespace caf;\n\nCAF_TEST(signed_arraybuf) {\n auto data = std::string{\"The quick brown fox jumps over the lazy dog\"};\n arraybuf ab{data};\n \/\/ Let's read some.\n CAF_CHECK_EQUAL(static_cast(ab.in_avail()), data.size());\n CAF_CHECK_EQUAL(ab.sgetc(), 'T');\n std::string buf;\n buf.resize(3);\n auto got = ab.sgetn(&buf[0], 3);\n CAF_CHECK_EQUAL(got, 3);\n CAF_CHECK_EQUAL(buf, \"The\");\n CAF_CHECK_EQUAL(ab.sgetc(), ' ');\n \/\/ Exhaust the stream.\n buf.resize(data.size());\n got = ab.sgetn(&buf[0] + 3, static_cast(data.size() - 3));\n CAF_CHECK_EQUAL(static_cast(got), data.size() - 3);\n CAF_CHECK_EQUAL(data, buf);\n CAF_CHECK_EQUAL(ab.in_avail(), 0);\n \/\/ No more.\n auto c = ab.sgetc();\n CAF_CHECK_EQUAL(c, charbuf::traits_type::eof());\n \/\/ Reset the stream and write into it.\n ab.pubsetbuf(&data[0], static_cast(data.size()));\n CAF_CHECK_EQUAL(static_cast(ab.in_avail()), data.size());\n auto put = ab.sputn(\"One\", 3);\n CAF_CHECK_EQUAL(put, 3);\n CAF_CHECK(data.compare(0, 3, \"One\") == 0);\n}\n\nCAF_TEST(unsigned_arraybuf) {\n std::vector data = {0x0a, 0x0b, 0x0c, 0x0d};\n arraybuf ab{data};\n decltype(data) buf;\n std::copy(std::istreambuf_iterator{&ab},\n std::istreambuf_iterator{},\n std::back_inserter(buf));\n CAF_CHECK_EQUAL(data, buf);\n \/\/ Relative positioning.\n using pos = arraybuf::pos_type;\n CAF_CHECK_EQUAL(ab.pubseekoff(2, std::ios::beg, std::ios::in), pos{2});\n CAF_CHECK_EQUAL(ab.sbumpc(), static_cast(0x0c));\n CAF_CHECK_EQUAL(ab.sgetc(), 0x0d);\n CAF_CHECK_EQUAL(ab.pubseekoff(0, std::ios::cur, std::ios::in), pos{3});\n CAF_CHECK_EQUAL(ab.pubseekoff(-2, std::ios::cur, std::ios::in), pos{1});\n CAF_CHECK_EQUAL(ab.sgetc(), 0x0b);\n CAF_CHECK_EQUAL(ab.pubseekoff(-4, std::ios::end, std::ios::in), pos{0});\n CAF_CHECK_EQUAL(ab.sgetc(), 0x0a);\n \/\/ Absolute positioning.\n CAF_CHECK_EQUAL(ab.pubseekpos(1, std::ios::in), pos{1});\n CAF_CHECK_EQUAL(ab.sgetc(), 0x0b);\n CAF_CHECK_EQUAL(ab.pubseekpos(3, std::ios::in), pos{3});\n CAF_CHECK_EQUAL(ab.sbumpc(), 0x0d);\n CAF_CHECK_EQUAL(ab.in_avail(), 0);\n}\n\nCAF_TEST(containerbuf) {\n std::string data{\n \"Habe nun, ach! Philosophie,\\n\"\n \"Juristerei und Medizin,\\n\"\n \"Und leider auch Theologie\\n\"\n \"Durchaus studiert, mit heißem Bemühn.\\n\"\n \"Da steh ich nun, ich armer Tor!\\n\"\n \"Und bin so klug als wie zuvor\"\n };\n \/\/ Write some data.\n std::vector buf;\n vectorbuf vb{buf};\n auto put = vb.sputn(data.data(), static_cast(data.size()));\n CAF_CHECK_EQUAL(static_cast(put), data.size());\n put = vb.sputn(\";\", 1);\n CAF_CHECK_EQUAL(put, 1);\n std::string target;\n std::copy(buf.begin(), buf.end(), std::back_inserter(target));\n CAF_CHECK_EQUAL(data + ';', target);\n \/\/ Check \"overflow\" on a new stream.\n buf.clear();\n vectorbuf vb2{buf};\n auto chr = vb2.sputc('x');\n CAF_CHECK_EQUAL(chr, 'x');\n \/\/ Let's read some data into a stream.\n buf.clear();\n containerbuf scb{data};\n std::copy(std::istreambuf_iterator{&scb},\n std::istreambuf_iterator{},\n std::back_inserter(buf));\n CAF_CHECK_EQUAL(buf.size(), data.size());\n CAF_CHECK(std::equal(buf.begin(), buf.end(), data.begin() \/*, data.end() *\/));\n \/\/ We're done, nothing to see here, please move along.\n CAF_CHECK_EQUAL(scb.sgetc(), containerbuf::traits_type::eof());\n \/\/ Let's read again, but now in one big block.\n buf.clear();\n containerbuf sib2{data};\n buf.resize(data.size());\n auto got = sib2.sgetn(&buf[0], static_cast(buf.size()));\n CAF_CHECK_EQUAL(static_cast(got), data.size());\n CAF_CHECK_EQUAL(buf.size(), data.size());\n CAF_CHECK(std::equal(buf.begin(), buf.end(), data.begin() \/*, data.end() *\/));\n}\nFix sign warnings\/******************************************************************************\n * ____ _ _____ *\n * \/ ___| \/ \\ | ___| C++ *\n * | | \/ _ \\ | |_ Actor *\n * | |___ \/ ___ \\| _| Framework *\n * \\____\/_\/ \\_|_| *\n * *\n * Copyright 2011-2018 Dominik Charousset *\n * *\n * Distributed under the terms and conditions of the BSD 3-Clause License or *\n * (at your option) under the terms and conditions of the Boost Software *\n * License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *\n * *\n * If you did not receive a copy of the license files, see *\n * http:\/\/opensource.org\/licenses\/BSD-3-Clause and *\n * http:\/\/www.boost.org\/LICENSE_1_0.txt. *\n ******************************************************************************\/\n\n#include \"caf\/config.hpp\"\n\n#define CAF_SUITE streambuf\n#include \"caf\/test\/unit_test.hpp\"\n\n#include \"caf\/streambuf.hpp\"\n\nusing namespace caf;\n\nCAF_TEST(signed_arraybuf) {\n auto data = std::string{\"The quick brown fox jumps over the lazy dog\"};\n arraybuf ab{data};\n \/\/ Let's read some.\n CAF_CHECK_EQUAL(static_cast(ab.in_avail()), data.size());\n CAF_CHECK_EQUAL(ab.sgetc(), 'T');\n std::string buf;\n buf.resize(3);\n auto got = ab.sgetn(&buf[0], 3);\n CAF_CHECK_EQUAL(got, 3);\n CAF_CHECK_EQUAL(buf, \"The\");\n CAF_CHECK_EQUAL(ab.sgetc(), ' ');\n \/\/ Exhaust the stream.\n buf.resize(data.size());\n got = ab.sgetn(&buf[0] + 3, static_cast(data.size() - 3));\n CAF_CHECK_EQUAL(static_cast(got), data.size() - 3);\n CAF_CHECK_EQUAL(data, buf);\n CAF_CHECK_EQUAL(ab.in_avail(), 0);\n \/\/ No more.\n auto c = ab.sgetc();\n CAF_CHECK_EQUAL(c, charbuf::traits_type::eof());\n \/\/ Reset the stream and write into it.\n ab.pubsetbuf(&data[0], static_cast(data.size()));\n CAF_CHECK_EQUAL(static_cast(ab.in_avail()), data.size());\n auto put = ab.sputn(\"One\", 3);\n CAF_CHECK_EQUAL(put, 3);\n CAF_CHECK(data.compare(0, 3, \"One\") == 0);\n}\n\nCAF_TEST(unsigned_arraybuf) {\n using buf_type = arraybuf;\n std::vector data = {0x0a, 0x0b, 0x0c, 0x0d};\n buf_type ab{data};\n decltype(data) buf;\n std::copy(std::istreambuf_iterator{&ab},\n std::istreambuf_iterator{},\n std::back_inserter(buf));\n CAF_CHECK_EQUAL(data, buf);\n \/\/ Relative positioning.\n using pos_type = buf_type::pos_type;\n using int_type = buf_type::int_type;\n CAF_CHECK_EQUAL(ab.pubseekoff(2, std::ios::beg, std::ios::in), pos_type{2});\n CAF_CHECK_EQUAL(ab.sbumpc(), int_type{0x0c});\n CAF_CHECK_EQUAL(ab.sgetc(), int_type{0x0d});\n CAF_CHECK_EQUAL(ab.pubseekoff(0, std::ios::cur, std::ios::in), pos_type{3});\n CAF_CHECK_EQUAL(ab.pubseekoff(-2, std::ios::cur, std::ios::in), pos_type{1});\n CAF_CHECK_EQUAL(ab.sgetc(), int_type{0x0b});\n CAF_CHECK_EQUAL(ab.pubseekoff(-4, std::ios::end, std::ios::in), pos_type{0});\n CAF_CHECK_EQUAL(ab.sgetc(), int_type{0x0a});\n \/\/ Absolute positioning.\n CAF_CHECK_EQUAL(ab.pubseekpos(1, std::ios::in), pos_type{1});\n CAF_CHECK_EQUAL(ab.sgetc(), int_type{0x0b});\n CAF_CHECK_EQUAL(ab.pubseekpos(3, std::ios::in), pos_type{3});\n CAF_CHECK_EQUAL(ab.sbumpc(), int_type{0x0d});\n CAF_CHECK_EQUAL(ab.in_avail(), std::streamsize{0});\n}\n\nCAF_TEST(containerbuf) {\n std::string data{\n \"Habe nun, ach! Philosophie,\\n\"\n \"Juristerei und Medizin,\\n\"\n \"Und leider auch Theologie\\n\"\n \"Durchaus studiert, mit heißem Bemühn.\\n\"\n \"Da steh ich nun, ich armer Tor!\\n\"\n \"Und bin so klug als wie zuvor\"\n };\n \/\/ Write some data.\n std::vector buf;\n vectorbuf vb{buf};\n auto put = vb.sputn(data.data(), static_cast(data.size()));\n CAF_CHECK_EQUAL(static_cast(put), data.size());\n put = vb.sputn(\";\", 1);\n CAF_CHECK_EQUAL(put, 1);\n std::string target;\n std::copy(buf.begin(), buf.end(), std::back_inserter(target));\n CAF_CHECK_EQUAL(data + ';', target);\n \/\/ Check \"overflow\" on a new stream.\n buf.clear();\n vectorbuf vb2{buf};\n auto chr = vb2.sputc('x');\n CAF_CHECK_EQUAL(chr, 'x');\n \/\/ Let's read some data into a stream.\n buf.clear();\n containerbuf scb{data};\n std::copy(std::istreambuf_iterator{&scb},\n std::istreambuf_iterator{},\n std::back_inserter(buf));\n CAF_CHECK_EQUAL(buf.size(), data.size());\n CAF_CHECK(std::equal(buf.begin(), buf.end(), data.begin() \/*, data.end() *\/));\n \/\/ We're done, nothing to see here, please move along.\n CAF_CHECK_EQUAL(scb.sgetc(), containerbuf::traits_type::eof());\n \/\/ Let's read again, but now in one big block.\n buf.clear();\n containerbuf sib2{data};\n buf.resize(data.size());\n auto got = sib2.sgetn(&buf[0], static_cast(buf.size()));\n CAF_CHECK_EQUAL(static_cast(got), data.size());\n CAF_CHECK_EQUAL(buf.size(), data.size());\n CAF_CHECK(std::equal(buf.begin(), buf.end(), data.begin() \/*, data.end() *\/));\n}\n<|endoftext|>"} {"text":"\/\/ RUN: mkdir -p %T\/read-file-config\/\n\/\/ RUN: cp %s %T\/read-file-config\/test.cpp\n\/\/ RUN: echo 'Checks: \"-*,modernize-use-nullptr\"' > %T\/read-file-config\/.clang-tidy\n\/\/ RUN: echo '[{\"command\": \"cc -c -o test.o test.cpp\", \"directory\": \"%T\/read-file-config\", \"file\": \"%T\/read-file-config\/test.cpp\"}]' > %T\/read-file-config\/compile_commands.json\n\/\/ RUN: clang-tidy %T\/read-file-config\/test.cpp | not grep \"warning: .*\\[clang-analyzer-deadcode.DeadStores\\]$\"\n\/\/ RUN: clang-tidy -checks=\"-*,clang-analyzer-*\" %T\/read-file-config\/test.cpp | grep \"warning: .*\\[clang-analyzer-deadcode.DeadStores\\]$\"\n\nvoid f() {\n int x;\n x = 1;\n x = 2;\n}\nFix test from r330245 on Windows.\/\/ RUN: mkdir -p %T\/read-file-config\/\n\/\/ RUN: cp %s %T\/read-file-config\/test.cpp\n\/\/ RUN: echo 'Checks: \"-*,modernize-use-nullptr\"' > %T\/read-file-config\/.clang-tidy\n\/\/ RUN: echo '[{\"command\": \"cc -c -o test.o test.cpp\", \"directory\": \"%\/T\/read-file-config\", \"file\": \"%\/T\/read-file-config\/test.cpp\"}]' > %T\/read-file-config\/compile_commands.json\n\/\/ RUN: clang-tidy %T\/read-file-config\/test.cpp | not grep \"warning: .*\\[clang-analyzer-deadcode.DeadStores\\]$\"\n\/\/ RUN: clang-tidy -checks=\"-*,clang-analyzer-*\" %T\/read-file-config\/test.cpp | grep \"warning: .*\\[clang-analyzer-deadcode.DeadStores\\]$\"\n\nvoid f() {\n int x;\n x = 1;\n x = 2;\n}\n<|endoftext|>"} {"text":"\/\/\n\/\/ pLSI (probabilistic latent semantic indexing)\n\/\/\n\/\/ Copyright(C) 2009 Mizuki Fujisawa \n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; version 2 of the License.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bayon.h\"\n\n\n\/********************************************************************\n * Typedef\n *******************************************************************\/\ntypedef enum {\n OPT_NUMBER = 'n',\n OPT_ITER = 'i',\n OPT_BETA = 'b',\n} plsi_options;\n\ntypedef std::map Option;\ntypedef bayon::HashMap::type Feature;\ntypedef bayon::HashMap::type DocId2Str;\ntypedef bayon::HashMap::type VecKey2Str;\ntypedef bayon::HashMap::type Str2VecKey;\n\n\n\/********************************************************************\n * constants\n *******************************************************************\/\nconst size_t DEFAULT_NUM_ITER = 50;\nconst double DEFAULT_BETA = 0.75;\nconst unsigned int DEFAULT_SEED = 12345;\n\n\n\/********************************************************************\n * global variables\n *******************************************************************\/\nstruct option longopts[] = {\n {\"number\", required_argument, NULL, OPT_NUMBER},\n {\"iter\", required_argument, NULL, OPT_ITER },\n {\"beta\", required_argument, NULL, OPT_BETA },\n {0, 0, 0, 0}\n};\n\n\n\/********************************************************************\n * class\n *******************************************************************\/\nnamespace bayon {\n\nclass PLSI {\n private:\n size_t num_cluster_;\n size_t num_doc_;\n size_t num_word_;\n double beta_;\n unsigned int seed_;\n std::vector documents_;\n double **pdz_, **pdz_new_;\n double **pwz_, **pwz_new_;\n double *pz_, *pz_new_;\n double ***scores_;\n\n void set_random_probabilities(size_t row, size_t col, double **array) {\n for (size_t i = 0; i < row; i++) {\n array[i] = new double[col];\n double sum = 0.0;\n for (size_t j = 0; j < col; j++) {\n array[i][j] = myrand(&seed_);\n sum += array[i][j];\n }\n for (size_t j = 0; j < col; j++) {\n array[i][j] \/= sum;\n }\n }\n }\n\n void expect() {\n for (size_t id = 0; id < num_doc_; id++) {\n VecHashMap *hmap = documents_[id]->feature()->hash_map();\n for (VecHashMap::iterator it = hmap->begin(); it != hmap->end(); ++it) {\n double denominator = 0.0;\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n denominator += pz_[iz]\n * pow(pwz_[it->first][iz] * pdz_[id][iz], beta_);\n }\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n double numerator = pz_[iz]\n * pow(pwz_[it->first][iz] * pdz_[id][iz], beta_);\n scores_[id][it->first][iz] = denominator ?\n numerator \/ denominator : 0.0;\n }\n }\n }\n }\n\n void maximize() {\n double denominators[num_cluster_];\n double denom_sum = 0.0;\n\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n denominators[iz] = 0.0;\n for (size_t id = 0; id < num_doc_; id++) {\n VecHashMap *hmap = documents_[id]->feature()->hash_map();\n for (VecHashMap::iterator it = hmap->begin(); it != hmap->end(); ++it) {\n double val = it->second * scores_[id][it->first][iz];\n denominators[iz] += val;\n pdz_new_[id][iz] += val;\n pwz_new_[it->first][iz] += val;\n }\n }\n denom_sum += denominators[iz];\n\n for (size_t id = 0; id < num_doc_; id++) {\n pdz_[id][iz] = pdz_new_[id][iz] \/ denominators[iz];\n pdz_new_[id][iz] = 0.0;\n }\n for (size_t iw = 0; iw < num_word_; iw++) {\n pwz_[iw][iz] = pwz_new_[iw][iz] \/ denominators[iz];\n pwz_new_[iw][iz] = 0.0;\n }\n }\n for (size_t iz = 0; iz < num_cluster_; iz++)\n pz_[iz] = denominators[iz] \/ denom_sum;\n }\n\n public:\n PLSI(size_t num_cluster, double beta, unsigned int seed)\n : num_cluster_(num_cluster), num_doc_(0), num_word_(0),\n beta_(beta), seed_(seed) { }\n\n ~PLSI() {\n for (size_t i = 0; i < num_doc_; i ++) {\n delete pdz_[i];\n delete pdz_new_[i];\n }\n for (size_t i = 0; i < num_word_; i ++) {\n delete pwz_[i];\n delete pwz_new_[i];\n }\n delete [] pdz_;\n delete [] pwz_;\n delete [] pz_;\n delete [] pdz_new_;\n delete [] pwz_new_;\n delete [] pz_new_;\n }\n\n void init_probabilities() {\n pdz_ = new double*[num_doc_];\n set_random_probabilities(num_doc_, num_cluster_, pdz_);\n pwz_ = new double*[num_word_];\n set_random_probabilities(num_word_, num_cluster_, pwz_);\n pz_ = new double[num_cluster_];\n for (size_t i = 0; i < num_cluster_; i++) pz_[i] = 1.0 \/ num_cluster_;\n\n pdz_new_ = new double*[num_doc_];\n for (size_t id = 0; id < num_doc_; id++) {\n pdz_new_[id] = new double[num_cluster_];\n for (size_t iz = 0; iz < num_cluster_; iz++) pdz_new_[id][iz] = 0.0;\n }\n pwz_new_ = new double*[num_word_];\n for (size_t iw = 0; iw < num_word_; iw++) {\n pwz_new_[iw] = new double[num_cluster_];\n for (size_t iz = 0; iz < num_cluster_; iz++) pwz_new_[iw][iz] = 0.0;\n }\n pz_new_ = new double[num_cluster_];\n for (size_t iz = 0; iz < num_cluster_; iz++) pz_new_[iz] = 0.0;\n\n scores_ = new double**[num_doc_];\n for (size_t i = 0; i < num_doc_; i++) {\n scores_[i] = new double*[num_word_];\n for (size_t j = 0; j < num_word_; j++) {\n scores_[i][j] = new double[num_cluster_];\n }\n }\n }\n\n void add_document(Document &doc) {\n Document *ptr = new Document(doc.id(), doc.feature());\n doc.set_features(NULL);\n documents_.push_back(ptr);\n num_doc_++;\n VecHashMap *hmap = ptr->feature()->hash_map();\n for (VecHashMap::iterator it = hmap->begin();\n it != hmap->end(); ++it) {\n if ((it->first+1) > static_cast(num_word_)) num_word_ = it->first+1;\n }\n }\n\n void em(size_t num_iter) {\n for (size_t i = 0; i < num_iter; i++) {\n expect();\n maximize();\n }\n }\n\n void show_pdz() {\n for (size_t i = 0; i < num_doc_; i++) {\n for (size_t j = 0; j < num_cluster_; j++) {\n if (j != 0) std::cout << \"\\t\";\n std::cout << pdz_[i][j];\n }\n std::cout << std::endl;\n }\n }\n\n void show_pwz() {\n for (size_t i = 0; i < num_word_; i++) {\n for (size_t j = 0; j < num_cluster_; j++) {\n if (j != 0) std::cout << \"\\t\";\n std::cout << pwz_[i][j];\n }\n std::cout << std::endl;\n }\n }\n\n void show_pz() {\n for (size_t i = 0; i < num_cluster_; i++) {\n if (i != 0) std::cout << \"\\t\";\n std::cout << pz_[i];\n }\n std::cout << std::endl;\n }\n\n double **pdz() { return pdz_; }\n double **pwz() { return pwz_; }\n double *pz() { return pz_; }\n const std::vector &documents() { return documents_; }\n};\n\n} \/\/ namespace bayon\n\n\n\/********************************************************************\n * function prototypes\n *******************************************************************\/\nint main(int argc, char **argv);\nstatic void usage(std::string progname);\nstatic int parse_options(int argc, char **argv, Option &option);\nstatic size_t parse_tsv(std::string &tsv, Feature &feature);\nstatic size_t read_documents(std::ifstream &ifs, bayon::PLSI &plsi,\n bayon::VecKey &veckey, DocId2Str &docid2str,\n VecKey2Str &veckey2str, Str2VecKey &str2veckey);\n\n\/* main function *\/\nint main(int argc, char **argv) {\n std::string progname(argv[0]);\n Option option;\n int optind = parse_options(argc, argv, option);\n argc -= optind;\n argv += optind;\n if (argc != 1 || option.find(OPT_NUMBER) == option.end()) {\n usage(progname);\n return EXIT_FAILURE;\n }\n\n std::ifstream ifs_doc(argv[0]);\n if (!ifs_doc) {\n std::cerr << \"[ERROR]File not found: \" << argv[0] << std::endl;\n return EXIT_FAILURE;\n }\n\n DocId2Str docid2str;\n bayon::init_hash_map(bayon::DOC_EMPTY_KEY, docid2str);\n VecKey2Str veckey2str;\n bayon::init_hash_map(bayon::VECTOR_EMPTY_KEY, veckey2str);\n Str2VecKey str2veckey;\n bayon::init_hash_map(\"\", str2veckey);\n bayon::VecKey veckey = 0;\n\n size_t num_cluster = static_cast(atoi(option[OPT_NUMBER].c_str()));\n size_t num_iter = option.find(OPT_ITER) != option.end() ?\n static_cast(atoi(option[OPT_ITER].c_str())) : DEFAULT_NUM_ITER;\n double beta = option.find(OPT_ITER) != option.end() ?\n atof(option[OPT_BETA].c_str()) : DEFAULT_BETA;\n bayon::PLSI plsi(num_cluster, beta, DEFAULT_SEED);;\n size_t num_doc = read_documents(ifs_doc, plsi, veckey,\n docid2str, veckey2str, str2veckey);\n plsi.init_probabilities();\n plsi.em(num_iter);\n\n double **pdz = plsi.pdz();\n for (size_t i = 0; i < num_doc; i++) {\n std::cout << docid2str[plsi.documents()[i]->id()];\n for (size_t j = 0; j < num_cluster; j++) {\n std::cout << \"\\t\" << pdz[i][j];\n }\n std::cout << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n\n\/* show usage *\/\nstatic void usage(std::string progname) {\n std::cerr\n << progname << \": Clustering tool by probabilistic latent semantic indexing\"\n << std::endl\n << \"Usage:\" << std::endl\n << \" % \" << progname << \" -n num [-b beta | -i niter] file\" << std::endl\n << \" -n, --number=num number of clusters\" << std::endl\n << \" -i, --iter=num number of iteration\" << std::endl\n << \" -b, --beta=double parameter of tempered EM\" << std::endl;\n}\n\n\/* parse command line options *\/\nstatic int parse_options(int argc, char **argv, Option &option) {\n int opt;\n extern char *optarg;\n extern int optind;\n while ((opt = getopt_long(argc, argv, \"n:i:b:\", longopts, NULL))\n != -1) {\n switch (opt) {\n case OPT_NUMBER:\n option[OPT_NUMBER] = optarg;\n break;\n case OPT_ITER:\n option[OPT_ITER] = optarg;\n break;\n case OPT_BETA:\n option[OPT_BETA] = optarg;\n break;\n default:\n break;\n }\n }\n return optind;\n}\n\n\/* parse tsv format string *\/\nstatic size_t parse_tsv(std::string &tsv, Feature &feature) {\n std::string key;\n int cnt = 0;\n size_t keycnt = 0;\n\n size_t p = tsv.find(bayon::DELIMITER);\n while (true) {\n std::string s = tsv.substr(0, p);\n if (cnt % 2 == 0) {\n key = s;\n } else {\n double point = 0.0;\n point = atof(s.c_str());\n if (!key.empty() && point != 0) {\n feature[key] = point;\n keycnt++;\n }\n }\n if (p == tsv.npos) break;\n cnt++;\n tsv = tsv.substr(p + bayon::DELIMITER.size());\n p = tsv.find(bayon::DELIMITER);\n }\n return keycnt;\n}\n\n\/* read input file and add documents to PLSI object *\/\nstatic size_t read_documents(std::ifstream &ifs, bayon::PLSI &plsi,\n bayon::VecKey &veckey, DocId2Str &docid2str,\n VecKey2Str &veckey2str, Str2VecKey &str2veckey) {\n bayon::DocumentId docid = 0;\n std::string line;\n while (std::getline(ifs, line)) {\n if (!line.empty()) {\n size_t p = line.find(bayon::DELIMITER);\n std::string doc_name = line.substr(0, p);\n line = line.substr(p + bayon::DELIMITER.size());\n\n bayon::Document doc(docid);\n docid2str[docid] = doc_name;\n docid++;\n Feature feature;\n bayon::init_hash_map(\"\", feature);\n parse_tsv(line, feature);\n\n for (Feature::iterator it = feature.begin(); it != feature.end(); ++it) {\n if (str2veckey.find(it->first) == str2veckey.end()) {\n str2veckey[it->first] = veckey;\n veckey2str[veckey] = it->first;\n veckey++;\n }\n doc.add_feature(str2veckey[it->first], it->second);\n }\n plsi.add_document(doc);\n }\n }\n return docid;\n}\n\n[trunk] speed up plsi\/\/\n\/\/ pLSI (probabilistic latent semantic indexing)\n\/\/\n\/\/ Copyright(C) 2009 Mizuki Fujisawa \n\/\/\n\/\/ This program is free software; you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU General Public License as published by\n\/\/ the Free Software Foundation; version 2 of the License.\n\/\/\n\/\/ This program is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU General Public License\n\/\/ along with this program; if not, write to the Free Software\n\/\/ Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n\/\/\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \"bayon.h\"\n\n\n\/********************************************************************\n * Typedef\n *******************************************************************\/\ntypedef enum {\n OPT_NUMBER = 'n',\n OPT_ITER = 'i',\n OPT_BETA = 'b',\n} plsi_options;\n\ntypedef std::map Option;\ntypedef bayon::HashMap::type Feature;\ntypedef bayon::HashMap::type DocId2Str;\ntypedef bayon::HashMap::type VecKey2Str;\ntypedef bayon::HashMap::type Str2VecKey;\n\n\n\/********************************************************************\n * constants\n *******************************************************************\/\nconst size_t DEFAULT_NUM_ITER = 50;\nconst double DEFAULT_BETA = 0.75;\nconst unsigned int DEFAULT_SEED = 12345;\n\n\n\/********************************************************************\n * global variables\n *******************************************************************\/\nstruct option longopts[] = {\n {\"number\", required_argument, NULL, OPT_NUMBER},\n {\"iter\", required_argument, NULL, OPT_ITER },\n {\"beta\", required_argument, NULL, OPT_BETA },\n {0, 0, 0, 0}\n};\n\n\n\/********************************************************************\n * class\n *******************************************************************\/\nnamespace bayon {\n\nclass PLSI {\n private:\n size_t num_cluster_;\n size_t num_doc_;\n size_t num_word_;\n double beta_;\n double sum_weight_;\n unsigned int seed_;\n std::vector documents_;\n double **pdz_, **pdz_new_;\n double **pwz_, **pwz_new_;\n double *pz_, *pz_new_;\n\n void set_random_prob(size_t row, size_t col, double **array, double **array2) {\n for (size_t i = 0; i < row; i++) {\n array[i] = new double[col];\n array2[i] = new double[col];\n double sum = 0.0;\n for (size_t j = 0; j < col; j++) {\n array[i][j] = myrand(&seed_);\n array2[i][j] = 0.0;\n sum += array[i][j];\n }\n for (size_t j = 0; j < col; j++) {\n array[i][j] \/= sum;\n }\n }\n }\n\n void em_loop() {\n for (size_t id = 0; id < num_doc_; id++) {\n VecHashMap *hmap = documents_[id]->feature()->hash_map();\n for (VecHashMap::iterator it = hmap->begin(); it != hmap->end(); ++it) {\n double denom = 0.0;\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n denom += pz_[iz] * pow(pwz_[it->first][iz] * pdz_[id][iz], beta_);\n }\n if (!denom) continue;\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n double numer = pz_[iz] * pow(pwz_[it->first][iz] * pdz_[id][iz], beta_);\n double score = it->second * numer \/ denom;\n pdz_new_[id][iz] += score;\n pwz_new_[it->first][iz] += score;\n pz_new_[iz] += score;\n }\n }\n }\n\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n for (size_t id = 0; id < num_doc_; id++) {\n pdz_[id][iz] = pdz_new_[id][iz] \/ pz_new_[iz];\n pdz_new_[id][iz] = 0.0;\n }\n for (size_t iw = 0; iw < num_word_; iw++) {\n pwz_[iw][iz] = pwz_new_[iw][iz] \/ pz_new_[iz];\n pwz_new_[iw][iz] = 0.0;\n }\n }\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n pz_[iz] = pz_new_[iz] \/ sum_weight_;\n pz_new_[iz] = 0.0;\n }\n }\n\n public:\n PLSI(size_t num_cluster, double beta, unsigned int seed)\n : num_cluster_(num_cluster), num_doc_(0), num_word_(0),\n beta_(beta), seed_(seed) { }\n\n ~PLSI() {\n for (size_t i = 0; i < num_doc_; i ++) {\n delete pdz_[i];\n delete pdz_new_[i];\n }\n for (size_t i = 0; i < num_word_; i ++) {\n delete pwz_[i];\n delete pwz_new_[i];\n }\n delete [] pdz_;\n delete [] pwz_;\n delete [] pz_;\n delete [] pdz_new_;\n delete [] pwz_new_;\n delete [] pz_new_;\n }\n\n void init_probabilities() {\n pdz_ = new double*[num_doc_];\n pdz_new_ = new double*[num_doc_];\n set_random_prob(num_doc_, num_cluster_, pdz_, pdz_new_);\n\n pwz_ = new double*[num_word_];\n pwz_new_ = new double*[num_word_];\n set_random_prob(num_word_, num_cluster_, pwz_, pwz_new_);\n\n pz_ = new double[num_cluster_];\n pz_new_ = new double[num_cluster_];\n for (size_t iz = 0; iz < num_cluster_; iz++) {\n pz_[iz] = 1.0 \/ num_cluster_;\n pz_new_[iz] = 0.0;\n }\n }\n\n void add_document(Document &doc) {\n Document *ptr = new Document(doc.id(), doc.feature());\n doc.set_features(NULL);\n documents_.push_back(ptr);\n num_doc_++;\n VecHashMap *hmap = ptr->feature()->hash_map();\n for (VecHashMap::iterator it = hmap->begin();\n it != hmap->end(); ++it) {\n if ((it->first+1) > static_cast(num_word_)) num_word_ = it->first+1;\n sum_weight_ += it->second;\n }\n }\n\n void em(size_t num_iter) {\n for (size_t i = 0; i < num_iter; i++) em_loop();\n }\n\n void show_pdz() {\n for (size_t i = 0; i < num_doc_; i++) {\n for (size_t j = 0; j < num_cluster_; j++) {\n if (j != 0) std::cout << \"\\t\";\n std::cout << pdz_[i][j];\n }\n std::cout << std::endl;\n }\n }\n\n void show_pwz() {\n for (size_t i = 0; i < num_word_; i++) {\n for (size_t j = 0; j < num_cluster_; j++) {\n if (j != 0) std::cout << \"\\t\";\n std::cout << pwz_[i][j];\n }\n std::cout << std::endl;\n }\n }\n\n void show_pz() {\n for (size_t i = 0; i < num_cluster_; i++) {\n if (i != 0) std::cout << \"\\t\";\n std::cout << pz_[i];\n }\n std::cout << std::endl;\n }\n\n double **pdz() { return pdz_; }\n double **pwz() { return pwz_; }\n double *pz() { return pz_; }\n const std::vector &documents() { return documents_; }\n};\n\n} \/\/ namespace bayon\n\n\n\/********************************************************************\n * function prototypes\n *******************************************************************\/\nint main(int argc, char **argv);\nstatic void usage(std::string progname);\nstatic int parse_options(int argc, char **argv, Option &option);\nstatic size_t parse_tsv(std::string &tsv, Feature &feature);\nstatic size_t read_documents(std::ifstream &ifs, bayon::PLSI &plsi,\n bayon::VecKey &veckey, DocId2Str &docid2str,\n VecKey2Str &veckey2str, Str2VecKey &str2veckey);\n\n\/* main function *\/\nint main(int argc, char **argv) {\n std::string progname(argv[0]);\n Option option;\n int optind = parse_options(argc, argv, option);\n argc -= optind;\n argv += optind;\n if (argc != 1 || option.find(OPT_NUMBER) == option.end()) {\n usage(progname);\n return EXIT_FAILURE;\n }\n\n std::ifstream ifs_doc(argv[0]);\n if (!ifs_doc) {\n std::cerr << \"[ERROR]File not found: \" << argv[0] << std::endl;\n return EXIT_FAILURE;\n }\n\n DocId2Str docid2str;\n bayon::init_hash_map(bayon::DOC_EMPTY_KEY, docid2str);\n VecKey2Str veckey2str;\n bayon::init_hash_map(bayon::VECTOR_EMPTY_KEY, veckey2str);\n Str2VecKey str2veckey;\n bayon::init_hash_map(\"\", str2veckey);\n bayon::VecKey veckey = 0;\n\n size_t num_cluster = static_cast(atoi(option[OPT_NUMBER].c_str()));\n size_t num_iter = option.find(OPT_ITER) != option.end() ?\n static_cast(atoi(option[OPT_ITER].c_str())) : DEFAULT_NUM_ITER;\n double beta = option.find(OPT_BETA) != option.end() ?\n atof(option[OPT_BETA].c_str()) : DEFAULT_BETA;\n bayon::PLSI plsi(num_cluster, beta, DEFAULT_SEED);;\n size_t num_doc = read_documents(ifs_doc, plsi, veckey,\n docid2str, veckey2str, str2veckey);\n plsi.init_probabilities();\n plsi.em(num_iter);\n\n double **pdz = plsi.pdz();\n for (size_t i = 0; i < num_doc; i++) {\n std::cout << docid2str[plsi.documents()[i]->id()];\n for (size_t j = 0; j < num_cluster; j++) {\n std::cout << \"\\t\" << pdz[i][j];\n }\n std::cout << std::endl;\n }\n\n return EXIT_SUCCESS;\n}\n\n\/* show usage *\/\nstatic void usage(std::string progname) {\n std::cerr\n << progname << \": Clustering tool by probabilistic latent semantic indexing\"\n << std::endl\n << \"Usage:\" << std::endl\n << \" % \" << progname << \" -n num [-b beta | -i niter] file\" << std::endl\n << \" -n, --number=num number of clusters\" << std::endl\n << \" -i, --iter=num number of iteration\" << std::endl\n << \" -b, --beta=double parameter of tempered EM\" << std::endl;\n}\n\n\/* parse command line options *\/\nstatic int parse_options(int argc, char **argv, Option &option) {\n int opt;\n extern char *optarg;\n extern int optind;\n while ((opt = getopt_long(argc, argv, \"n:i:b:\", longopts, NULL))\n != -1) {\n switch (opt) {\n case OPT_NUMBER:\n option[OPT_NUMBER] = optarg;\n break;\n case OPT_ITER:\n option[OPT_ITER] = optarg;\n break;\n case OPT_BETA:\n option[OPT_BETA] = optarg;\n break;\n default:\n break;\n }\n }\n return optind;\n}\n\n\/* parse tsv format string *\/\nstatic size_t parse_tsv(std::string &tsv, Feature &feature) {\n std::string key;\n int cnt = 0;\n size_t keycnt = 0;\n\n size_t p = tsv.find(bayon::DELIMITER);\n while (true) {\n std::string s = tsv.substr(0, p);\n if (cnt % 2 == 0) {\n key = s;\n } else {\n double point = 0.0;\n point = atof(s.c_str());\n if (!key.empty() && point != 0) {\n feature[key] = point;\n keycnt++;\n }\n }\n if (p == tsv.npos) break;\n cnt++;\n tsv = tsv.substr(p + bayon::DELIMITER.size());\n p = tsv.find(bayon::DELIMITER);\n }\n return keycnt;\n}\n\n\/* read input file and add documents to PLSI object *\/\nstatic size_t read_documents(std::ifstream &ifs, bayon::PLSI &plsi,\n bayon::VecKey &veckey, DocId2Str &docid2str,\n VecKey2Str &veckey2str, Str2VecKey &str2veckey) {\n bayon::DocumentId docid = 0;\n std::string line;\n while (std::getline(ifs, line)) {\n if (!line.empty()) {\n size_t p = line.find(bayon::DELIMITER);\n std::string doc_name = line.substr(0, p);\n line = line.substr(p + bayon::DELIMITER.size());\n\n bayon::Document doc(docid);\n docid2str[docid] = doc_name;\n docid++;\n Feature feature;\n bayon::init_hash_map(\"\", feature);\n parse_tsv(line, feature);\n\n for (Feature::iterator it = feature.begin(); it != feature.end(); ++it) {\n if (str2veckey.find(it->first) == str2veckey.end()) {\n str2veckey[it->first] = veckey;\n veckey2str[veckey] = it->first;\n veckey++;\n }\n doc.add_feature(str2veckey[it->first], it->second);\n }\n plsi.add_document(doc);\n }\n }\n return docid;\n}\n\n<|endoftext|>"} {"text":"#include \n\n#include \n\n#include \"fly\/config\/config.h\"\n#include \"fly\/config\/config_manager.h\"\n#include \"fly\/path\/path.h\"\n#include \"fly\/path\/path_config.h\"\n#include \"fly\/task\/task_manager.h\"\n#include \"fly\/types\/string.h\"\n\n#include \"test\/util\/path_util.h\"\n#include \"test\/util\/waitable_task_runner.h\"\n\nnamespace\n{\n std::chrono::seconds s_waitTime(5);\n\n \/**\n * Subclass of the path config to decrease the poll interval for faster\n * testing.\n *\/\n class TestPathConfig : public fly::PathConfig\n {\n public:\n TestPathConfig() : fly::PathConfig()\n {\n m_defaultPollInterval = I64(10);\n }\n };\n}\n\n\/\/==============================================================================\nclass ConfigManagerTest : public ::testing::Test\n{\npublic:\n ConfigManagerTest() :\n m_path(fly::PathUtil::GenerateTempDirectory()),\n m_file(fly::String::GenerateRandomString(10) + \".txt\"),\n m_fullPath(fly::Path::Join(m_path, m_file)),\n\n m_spTaskManager(std::make_shared(1)),\n\n m_spTaskRunner(\n m_spTaskManager->CreateTaskRunner()\n ),\n\n m_spConfigManager(std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Ini,\n m_path,\n m_file\n )),\n\n m_spPathConfig(m_spConfigManager->CreateConfig())\n {\n }\n\n \/**\n * Create the file directory and start the task and config managers.\n *\/\n void SetUp() override\n {\n ASSERT_TRUE(fly::Path::MakePath(m_path));\n ASSERT_TRUE(m_spTaskManager->Start());\n ASSERT_TRUE(m_spConfigManager->Start());\n\n m_initialSize = m_spConfigManager->GetSize();\n }\n\n \/**\n * Delete the created directory and stop the task manager.\n *\/\n void TearDown() override\n {\n ASSERT_TRUE(m_spTaskManager->Stop());\n ASSERT_TRUE(fly::Path::RemovePath(m_path));\n }\n\nprotected:\n std::string m_path;\n std::string m_file;\n std::string m_fullPath;\n\n fly::TaskManagerPtr m_spTaskManager;\n fly::WaitableSequencedTaskRunnerPtr m_spTaskRunner;\n\n fly::ConfigManagerPtr m_spConfigManager;\n\n fly::PathConfigPtr m_spPathConfig;\n\n size_t m_initialSize;\n};\n\n\/\/==============================================================================\nclass BadConfig : public fly::Config\n{\n \/\/ Badly written config class which does not override the GetName() method.\n \/\/ It will have the same name as the base Config class.\n};\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, AllFileTypesTest)\n{\n {\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Ini,\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_TRUE(m_spConfigManager->Start());\n }\n {\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Json,\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_TRUE(m_spConfigManager->Start());\n }\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadFileTypeTest)\n{\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n static_cast(-1),\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_FALSE(m_spConfigManager->Start());\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, CreateConfigTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DuplicateConfigTest)\n{\n auto spConfig1 = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n\n auto spConfig2 = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DeletedConfigTest)\n{\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n {\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n }\n\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n {\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n }\n\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_FALSE(spConfig.get() == NULL);\n spConfig.reset();\n\n spConfig = m_spConfigManager->CreateConfig();\n EXPECT_FALSE(spConfig.get() == NULL);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DeletedConfigDetectedByPollerTest)\n{\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n {\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n }\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents + \"\\n\"));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadConfigTypeTest)\n{\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n\n auto spConfig2 = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n EXPECT_FALSE(spConfig2);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, InitialFileFirstTest)\n{\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n auto spConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, InitialFileSecondTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, FileChangeTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents1(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents1));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n EXPECT_EQ(spConfig->GetValue(\"age\", -1), -1);\n\n const std::string contents2(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=Jane Doe\\n\"\n \"age=27\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents2));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"Jane Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"age\", -1), 27);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DeleteFileTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n\n std::remove(m_fullPath.c_str());\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadUpdateTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadObjectTest)\n{\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Json,\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_TRUE(m_spConfigManager->Start());\n\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\"[1, 2, 3]\");\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n}\nUnused var#include \n\n#include \n\n#include \"fly\/config\/config.h\"\n#include \"fly\/config\/config_manager.h\"\n#include \"fly\/path\/path.h\"\n#include \"fly\/path\/path_config.h\"\n#include \"fly\/task\/task_manager.h\"\n#include \"fly\/types\/string.h\"\n\n#include \"test\/util\/path_util.h\"\n#include \"test\/util\/waitable_task_runner.h\"\n\nnamespace\n{\n \/**\n * Subclass of the path config to decrease the poll interval for faster\n * testing.\n *\/\n class TestPathConfig : public fly::PathConfig\n {\n public:\n TestPathConfig() : fly::PathConfig()\n {\n m_defaultPollInterval = I64(10);\n }\n };\n}\n\n\/\/==============================================================================\nclass ConfigManagerTest : public ::testing::Test\n{\npublic:\n ConfigManagerTest() :\n m_path(fly::PathUtil::GenerateTempDirectory()),\n m_file(fly::String::GenerateRandomString(10) + \".txt\"),\n m_fullPath(fly::Path::Join(m_path, m_file)),\n\n m_spTaskManager(std::make_shared(1)),\n\n m_spTaskRunner(\n m_spTaskManager->CreateTaskRunner()\n ),\n\n m_spConfigManager(std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Ini,\n m_path,\n m_file\n )),\n\n m_spPathConfig(m_spConfigManager->CreateConfig())\n {\n }\n\n \/**\n * Create the file directory and start the task and config managers.\n *\/\n void SetUp() override\n {\n ASSERT_TRUE(fly::Path::MakePath(m_path));\n ASSERT_TRUE(m_spTaskManager->Start());\n ASSERT_TRUE(m_spConfigManager->Start());\n\n m_initialSize = m_spConfigManager->GetSize();\n }\n\n \/**\n * Delete the created directory and stop the task manager.\n *\/\n void TearDown() override\n {\n ASSERT_TRUE(m_spTaskManager->Stop());\n ASSERT_TRUE(fly::Path::RemovePath(m_path));\n }\n\nprotected:\n std::string m_path;\n std::string m_file;\n std::string m_fullPath;\n\n fly::TaskManagerPtr m_spTaskManager;\n fly::WaitableSequencedTaskRunnerPtr m_spTaskRunner;\n\n fly::ConfigManagerPtr m_spConfigManager;\n\n fly::PathConfigPtr m_spPathConfig;\n\n size_t m_initialSize;\n};\n\n\/\/==============================================================================\nclass BadConfig : public fly::Config\n{\n \/\/ Badly written config class which does not override the GetName() method.\n \/\/ It will have the same name as the base Config class.\n};\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, AllFileTypesTest)\n{\n {\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Ini,\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_TRUE(m_spConfigManager->Start());\n }\n {\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Json,\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_TRUE(m_spConfigManager->Start());\n }\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadFileTypeTest)\n{\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n static_cast(-1),\n m_path,\n m_file\n );\n\n EXPECT_FALSE(m_spConfigManager->Start());\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, CreateConfigTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DuplicateConfigTest)\n{\n auto spConfig1 = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n\n auto spConfig2 = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DeletedConfigTest)\n{\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n {\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n }\n\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n {\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n }\n\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_FALSE(spConfig.get() == NULL);\n spConfig.reset();\n\n spConfig = m_spConfigManager->CreateConfig();\n EXPECT_FALSE(spConfig.get() == NULL);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DeletedConfigDetectedByPollerTest)\n{\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n {\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n }\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents + \"\\n\"));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadConfigTypeTest)\n{\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize);\n\n auto spConfig = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n\n auto spConfig2 = m_spConfigManager->CreateConfig();\n EXPECT_EQ(m_spConfigManager->GetSize(), m_initialSize + 1);\n EXPECT_FALSE(spConfig2);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, InitialFileFirstTest)\n{\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n auto spConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, InitialFileSecondTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, FileChangeTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents1(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents1));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n EXPECT_EQ(spConfig->GetValue(\"age\", -1), -1);\n\n const std::string contents2(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=Jane Doe\\n\"\n \"age=27\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents2));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"Jane Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"age\", -1), 27);\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, DeleteFileTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name=John Doe\\n\"\n \"address=USA\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"John Doe\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"USA\");\n\n std::remove(m_fullPath.c_str());\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadUpdateTest)\n{\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\n \"[\" + fly::Config::GetName() + \"]\\n\"\n \"name\"\n );\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n}\n\n\/\/==============================================================================\nTEST_F(ConfigManagerTest, BadObjectTest)\n{\n m_spConfigManager = std::make_shared(\n m_spTaskRunner,\n fly::ConfigManager::ConfigFileType::Json,\n m_path,\n m_file\n );\n m_spPathConfig = m_spConfigManager->CreateConfig();\n\n EXPECT_TRUE(m_spConfigManager->Start());\n\n auto spConfig = m_spConfigManager->CreateConfig();\n\n const std::string contents(\"[1, 2, 3]\");\n\n ASSERT_TRUE(fly::PathUtil::WriteFile(m_fullPath, contents));\n m_spTaskRunner->WaitForTaskTypeToComplete();\n m_spTaskRunner->WaitForTaskTypeToComplete();\n\n EXPECT_EQ(spConfig->GetValue(\"name\", \"\"), \"\");\n EXPECT_EQ(spConfig->GetValue(\"address\", \"\"), \"\");\n}\n<|endoftext|>"} {"text":"#include \"interpreterTest.h\"\n\n#include \n\n#include \n#include \"src\/interpreter\/interpreter.h\"\n#include \"src\/textLanguage\/robotsBlockParser.h\"\n\nusing namespace qrTest::robotsTests::interpreterCoreTests;\n\nusing namespace interpreterCore::interpreter;\nusing namespace ::testing;\n\nvoid InterpreterTest::SetUp()\n{\n\t\/\/\/ @todo: Need to rewrite this shit with 'temp' setting manager value.\n\t\/\/\/ It is used in serializer and innitialized in main window.\n\t\/\/\/ So when we run tests outside of enviroment they fail!\n\tqReal::SettingsManager::setValue(\"temp\", QCoreApplication::applicationDirPath() + \"\/unsaved\");\n\tmQrguiFacade.reset(new QrguiFacade(\"unittests\/basicTest.qrs\"));\n\tmQrguiFacade->setActiveTab(qReal::Id::loadFromString(\n\t\t\t\"qrm:\/RobotsMetamodel\/RobotsDiagram\/RobotsDiagramNode\/{f08fa823-e187-4755-87ba-e4269ae4e798}\"));\n\n\tmFakeConnectToRobotAction.reset(new QAction(nullptr));\n\n\tON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault(\n\t\t\tReturn(QList())\n\t\t\t);\n\tEXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(AtLeast(1));\n\n\t\/\/\/ @todo: Do we need this code in some common place? Why do we need to write\n\t\/\/\/ it every time when we are going to use RobotModelManager mock?\n\n\tON_CALL(mModel, name()).WillByDefault(Return(\"mockRobot\"));\n\tEXPECT_CALL(mModel, name()).Times(AtLeast(1));\n\n\tON_CALL(mModel, needsConnection()).WillByDefault(Return(false));\n\tEXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0));\n\n\tON_CALL(mModel, init()).WillByDefault(Return());\n\tEXPECT_CALL(mModel, init()).Times(AtLeast(0));\n\n\tON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock));\n\tEXPECT_CALL(mModel, configuration()).Times(AtLeast(0));\n\n\tON_CALL(mModel, connectToRobot()).WillByDefault(\n\t\t\tInvoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected)\n\t\t\t);\n\tEXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0));\n\n\tON_CALL(mModel, disconnectFromRobot()).WillByDefault(\n\t\t\tInvoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected)\n\t\t\t);\n\tEXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0));\n\n\tON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList()));\n\tEXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0));\n\n\tON_CALL(mModel, availablePorts()).WillByDefault(Return(QList()));\n\tEXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0));\n\n\tON_CALL(mModel, applyConfiguration()).WillByDefault(\n\t\t\tInvoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured)\n\t\t\t);\n\tEXPECT_CALL(mModel, applyConfiguration()).Times(1);\n\n\tON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState));\n\tEXPECT_CALL(mModel, connectionState()).Times(2);\n\n\tON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline));\n\tEXPECT_CALL(mModel, timeline()).Times(AtLeast(1));\n\n\n\tON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel));\n\tEXPECT_CALL(mModelManager, model()).Times(AtLeast(1));\n\n\tON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return());\n\tEXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0);\n\n\t\/\/\/ @todo Don't like it.\n\tinterpreterCore::textLanguage::RobotsBlockParser parser(\n\t\t\tmQrguiFacade->mainWindowInterpretersInterface().errorReporter()\n\t\t\t, mModelManager\n\t\t\t, []() { return 0; }\n\t\t\t);\n\n\tqrtext::lua::LuaToolbox luaToolbox;\n\n\tDummyBlockFactory *blocksFactory = new DummyBlockFactory;\n\tblocksFactory->configure(\n\t\t\tmQrguiFacade->graphicalModelAssistInterface()\n\t\t\t, mQrguiFacade->logicalModelAssistInterface()\n\t\t\t, mModelManager\n\t\t\t, *mQrguiFacade->mainWindowInterpretersInterface().errorReporter()\n\t\t\t, luaToolbox\n\t\t\t);\n\n\tON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault(\n\t\t\tInvoke([=] (qReal::Id const &id, interpreterBase::robotModel::RobotModelInterface const &robotModel) {\n\t\t\t\t\tQ_UNUSED(robotModel)\n\t\t\t\t\treturn blocksFactory->block(id);\n\t\t\t} )\n\t\t\t);\n\tEXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0));\n\n\tON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault(\n\t\t\tInvoke([=] (interpreterBase::robotModel::RobotModelInterface const &robotModel) {\n\t\t\t\t\tQ_UNUSED(robotModel)\n\t\t\t\t\treturn blocksFactory->providedBlocks().toSet();\n\t\t\t} )\n\t\t\t);\n\tEXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0);\n\n\tmInterpreter.reset(new Interpreter(\n\t\t\tmQrguiFacade->graphicalModelAssistInterface()\n\t\t\t, mQrguiFacade->logicalModelAssistInterface()\n\t\t\t, mQrguiFacade->mainWindowInterpretersInterface()\n\t\t\t, mQrguiFacade->projectManagementInterface()\n\t\t\t, mBlocksFactoryManager\n\t\t\t, mModelManager\n\t\t\t, luaToolbox\n\t\t\t, *mFakeConnectToRobotAction\n\t\t\t));\n}\n\nTEST_F(InterpreterTest, interpret)\n{\n\tEXPECT_CALL(mModel, stopRobot()).Times(1);\n\n\tmInterpreter->interpret();\n}\n\nTEST_F(InterpreterTest, stopRobot)\n{\n\t\/\/ It shall be called directly here and in destructor of a model.\n\tEXPECT_CALL(mModel, stopRobot()).Times(2);\n\n\tmInterpreter->interpret();\n\tmInterpreter->stopRobot();\n}\nfixed unit tests#include \"interpreterTest.h\"\n\n#include \n\n#include \n#include \"src\/interpreter\/interpreter.h\"\n#include \"src\/textLanguage\/robotsBlockParser.h\"\n\nusing namespace qrTest::robotsTests::interpreterCoreTests;\n\nusing namespace interpreterCore::interpreter;\nusing namespace ::testing;\n\nvoid InterpreterTest::SetUp()\n{\n\t\/\/\/ @todo: Need to rewrite this shit with 'temp' setting manager value.\n\t\/\/\/ It is used in serializer and innitialized in main window.\n\t\/\/\/ So when we run tests outside of enviroment they fail!\n\tqReal::SettingsManager::setValue(\"temp\", QCoreApplication::applicationDirPath() + \"\/unsaved\");\n\tmQrguiFacade.reset(new QrguiFacade(\"unittests\/basicTest.qrs\"));\n\tmQrguiFacade->setActiveTab(qReal::Id::loadFromString(\n\t\t\t\"qrm:\/RobotsMetamodel\/RobotsDiagram\/RobotsDiagramNode\/{f08fa823-e187-4755-87ba-e4269ae4e798}\"));\n\n\tmFakeConnectToRobotAction.reset(new QAction(nullptr));\n\n\tON_CALL(mConfigurationInterfaceMock, devices()).WillByDefault(\n\t\t\tReturn(QList())\n\t\t\t);\n\tEXPECT_CALL(mConfigurationInterfaceMock, devices()).Times(AtLeast(1));\n\n\t\/\/\/ @todo: Do we need this code in some common place? Why do we need to write\n\t\/\/\/ it every time when we are going to use RobotModelManager mock?\n\n\tON_CALL(mModel, name()).WillByDefault(Return(\"mockRobot\"));\n\tEXPECT_CALL(mModel, name()).Times(AtLeast(1));\n\n\tON_CALL(mModel, needsConnection()).WillByDefault(Return(false));\n\tEXPECT_CALL(mModel, needsConnection()).Times(AtLeast(0));\n\n\tON_CALL(mModel, init()).WillByDefault(Return());\n\tEXPECT_CALL(mModel, init()).Times(AtLeast(0));\n\n\tON_CALL(mModel, configuration()).WillByDefault(ReturnRef(mConfigurationInterfaceMock));\n\tEXPECT_CALL(mModel, configuration()).Times(AtLeast(0));\n\n\tON_CALL(mModel, connectToRobot()).WillByDefault(\n\t\t\tInvoke(&mModelManager, &RobotModelManagerInterfaceMock::emitConnected)\n\t\t\t);\n\tEXPECT_CALL(mModel, connectToRobot()).Times(AtLeast(0));\n\n\tON_CALL(mModel, disconnectFromRobot()).WillByDefault(\n\t\t\tInvoke(&mModelManager, &RobotModelManagerInterfaceMock::emitDisconnected)\n\t\t\t);\n\tEXPECT_CALL(mModel, disconnectFromRobot()).Times(AtLeast(0));\n\n\tON_CALL(mModel, configurablePorts()).WillByDefault(Return(QList()));\n\tEXPECT_CALL(mModel, configurablePorts()).Times(AtLeast(0));\n\n\tON_CALL(mModel, availablePorts()).WillByDefault(Return(QList()));\n\tEXPECT_CALL(mModel, availablePorts()).Times(AtLeast(0));\n\n\tON_CALL(mModel, applyConfiguration()).WillByDefault(\n\t\t\tInvoke(&mModelManager, &RobotModelManagerInterfaceMock::emitAllDevicesConfigured)\n\t\t\t);\n\tEXPECT_CALL(mModel, applyConfiguration()).Times(1);\n\n\tON_CALL(mModel, connectionState()).WillByDefault(Return(RobotModelInterfaceMock::connectedState));\n\tEXPECT_CALL(mModel, connectionState()).Times(2);\n\n\tON_CALL(mModel, timeline()).WillByDefault(ReturnRef(mTimeline));\n\tEXPECT_CALL(mModel, timeline()).Times(AtLeast(1));\n\n\n\tON_CALL(mModelManager, model()).WillByDefault(ReturnRef(mModel));\n\tEXPECT_CALL(mModelManager, model()).Times(AtLeast(1));\n\n\tON_CALL(mBlocksFactoryManager, addFactory(_, _)).WillByDefault(Return());\n\tEXPECT_CALL(mBlocksFactoryManager, addFactory(_, _)).Times(0);\n\n\tinterpreterCore::textLanguage::RobotsBlockParser parser(mModelManager, []() { return 0; });\n\n\tDummyBlockFactory *blocksFactory = new DummyBlockFactory;\n\tblocksFactory->configure(\n\t\t\tmQrguiFacade->graphicalModelAssistInterface()\n\t\t\t, mQrguiFacade->logicalModelAssistInterface()\n\t\t\t, mModelManager\n\t\t\t, *mQrguiFacade->mainWindowInterpretersInterface().errorReporter()\n\t\t\t, parser\n\t\t\t);\n\n\tON_CALL(mBlocksFactoryManager, block(_, _)).WillByDefault(\n\t\t\tInvoke([=] (qReal::Id const &id, interpreterBase::robotModel::RobotModelInterface const &robotModel) {\n\t\t\t\t\tQ_UNUSED(robotModel)\n\t\t\t\t\treturn blocksFactory->block(id);\n\t\t\t} )\n\t\t\t);\n\tEXPECT_CALL(mBlocksFactoryManager, block(_, _)).Times(AtLeast(0));\n\n\tON_CALL(mBlocksFactoryManager, enabledBlocks(_)).WillByDefault(\n\t\t\tInvoke([=] (interpreterBase::robotModel::RobotModelInterface const &robotModel) {\n\t\t\t\t\tQ_UNUSED(robotModel)\n\t\t\t\t\treturn blocksFactory->providedBlocks().toSet();\n\t\t\t} )\n\t\t\t);\n\tEXPECT_CALL(mBlocksFactoryManager, enabledBlocks(_)).Times(0);\n\n\tmInterpreter.reset(new Interpreter(\n\t\t\tmQrguiFacade->graphicalModelAssistInterface()\n\t\t\t, mQrguiFacade->logicalModelAssistInterface()\n\t\t\t, mQrguiFacade->mainWindowInterpretersInterface()\n\t\t\t, mQrguiFacade->projectManagementInterface()\n\t\t\t, mBlocksFactoryManager\n\t\t\t, mModelManager\n\t\t\t, parser\n\t\t\t, *mFakeConnectToRobotAction\n\t\t\t));\n}\n\nTEST_F(InterpreterTest, interpret)\n{\n\tEXPECT_CALL(mModel, stopRobot()).Times(1);\n\n\tmInterpreter->interpret();\n}\n\nTEST_F(InterpreterTest, stopRobot)\n{\n\t\/\/ It shall be called directly here and in destructor of a model.\n\tEXPECT_CALL(mModel, stopRobot()).Times(2);\n\n\tmInterpreter->interpret();\n\tmInterpreter->stopRobot();\n}\n<|endoftext|>"} {"text":"\/\/**********************************************************************;\n\/\/ Copyright (c) 2015, Intel Corporation\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of Intel Corporation nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n\/\/ THE POSSIBILITY OF SUCH DAMAGE.\n\/\/**********************************************************************;\n\n#ifdef _WIN32\n#include \"stdafx.h\"\n#else\n#include \n#endif\n\n#ifndef UNICODE\n#define UNICODE 1\n#endif\n\n#ifdef _WIN32\n\/\/ link with Ws2_32.lib\n#pragma comment(lib,\"Ws2_32.lib\")\n\n#include \n#include \n#else\n#define sprintf_s snprintf\n#define sscanf_s sscanf\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \"common.h\"\n\nint debugLevel = 0;\nUINT32 nvIndex = 0;\nUINT32 authHandle = TPM_RH_PLATFORM;\nUINT16 dataSize = 0;\nunsigned char nvBuffer[MAX_NV_BUFFER_SIZE];\nchar fileName[PATH_MAX];\nchar handlePasswd[sizeof(TPMU_HA)];\n\nint nvWrite()\n{\n UINT32 rval;\n TPMS_AUTH_COMMAND sessionData;\n TPMS_AUTH_RESPONSE sessionDataOut;\n TSS2_SYS_CMD_AUTHS sessionsData;\n TSS2_SYS_RSP_AUTHS sessionsDataOut;\n int i;\n TPM2B_MAX_NV_BUFFER nvWriteData;\n\n TPMS_AUTH_COMMAND *sessionDataArray[1] = { &sessionData };\n TPMS_AUTH_RESPONSE *sessionDataOutArray[1] = { &sessionDataOut };\n\n sessionsDataOut.rspAuths = &sessionDataOutArray[0];\n sessionsData.cmdAuths = &sessionDataArray[0];\n\n sessionsDataOut.rspAuthsCount = 1;\n sessionsData.cmdAuthsCount = 1;\n\n sessionData.sessionHandle = TPM_RS_PW;\n sessionData.nonce.t.size = 0;\n sessionData.hmac.t.size = 0;\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n if (strlen(handlePasswd) > 0)\n {\n sessionData.hmac.t.size = strlen(handlePasswd);\n memcpy( &sessionData.hmac.t.buffer[0], handlePasswd, sessionData.hmac.t.size );\n }\n\n nvWriteData.t.size = dataSize;\n printf(\"\\nThe data(size=%d) to be written:\\n\", dataSize);\n for( i = 0; i<(int)dataSize; i++ )\n {\n nvWriteData.t.buffer[i] = nvBuffer[i];\n printf(\"%02x\\t\", nvBuffer[i]);\n }\n printf(\"\\n\\n\");\n\n rval = Tss2_Sys_NV_Write( sysContext, authHandle, nvIndex, &sessionsData, &nvWriteData, 0, &sessionsDataOut );\n if(rval != TSS2_RC_SUCCESS)\n {\n printf( \"Failed to write NV area at index 0x%x (%d).Error:0x%x\\n\", nvIndex, nvIndex, rval );\n return -1;\n }\n printf( \"Success to write NV area at index 0x%x (%d).\\n\", nvIndex, nvIndex );\n\n return 0;\n}\n\nvoid showHelp(const char *name)\n{\n printf(\"Usage: %s [-h\/--help]\\n\"\n \" or: %s [-v\/--version]\\n\"\n \" or: %s [-x\/--index ] [-a\/--authHandle ] [-P\/--handlePasswd ] [-f\/--file ]\\n\"\n \" or: %s [-x\/--index ] [-a\/--authHandle ] [-P\/--handlePasswd ] [-f\/--file ]\\n\"\n \" [-p\/--port ] [-d\/--dbg ]\\n\"\n \"\\nwhere:\\n\\n\"\n \" -h\/--help display this help and exit.\\n\"\n \" -v\/--version display version information and exit.\\n\"\n \" -x\/--index specifies the index of the NV area.\\n\"\n \" -a\/--authHandle specifies the handle used to authorize:\\n\"\n \" 0x40000001 (TPM_RH_OWNER)\\n\"\n \" 0x4000000C (TPM_RH_PLATFORM)\\n\"\n \" {NV_INDEX_FIRST:NV_INDEX_LAST}\\n\"\n \" -P\/--handlePasswd specifies the password of authHandle.\\n\"\n \" -f\/--file specifies the nv data file.\\n\"\n \" -p\/--port specifies the port number, default:%d, optional\\n\"\n \" -d\/--dbg specifies level of debug messages, optional:\\n\"\n \" 0 (high level test results)\\n\"\n \" 1 (test app send\/receive byte streams)\\n\"\n \" 2 (resource manager send\/receive byte streams)\\n\"\n \" 3 (resource manager tables)\\n\"\n \"\\nexample:\\n\"\n \" %s -x 0x1500016 -a 0x40000001 -P passwd -f nv.data\\n\"\n , name, name, name, name, DEFAULT_RESMGR_TPM_PORT, name);\n}\n\nint main(int argc, char* argv[])\n{\n int opt;\n char type[100] = \"local\";\n char hostName[200] = DEFAULT_HOSTNAME;\n int port = DEFAULT_RESMGR_TPM_PORT;\n int returnVal = 0;\n\n struct option sOpts[] = {\n { \"index\" , required_argument, NULL, 'x' },\n { \"authHandle\" , required_argument, NULL, 'a' },\n { \"file\" , required_argument, NULL, 'f' },\n { \"handlePasswd\", required_argument, NULL, 'P' },\n { \"port\" , required_argument, NULL, 'p' },\n { \"dbg\" , required_argument, NULL, 'd' },\n { \"help\" , no_argument, NULL, 'h' },\n { \"version\" , no_argument, NULL, 'v' },\n { NULL , no_argument, NULL, 0 },\n };\n\n if(argc == 1)\n {\n showHelp(argv[0]);\n return 0;\n }\n\n if( argc > (int)(2*sizeof(sOpts)\/sizeof(struct option)) )\n {\n showArgMismatch(argv[0]);\n return -1;\n }\n\n while ( ( opt = getopt_long( argc, argv, \"x:a:f:P:p:d:hv\", sOpts, NULL ) ) != -1 )\n {\n switch ( opt ) {\n case 'h':\n case '?':\n showHelp(argv[0]);\n return 0;\n case 'v':\n showVersion(argv[0]);\n return 0;\n\n case 'x':\n if( getSizeUint32Hex(optarg, &nvIndex) != 0 )\n {\n return -2;\n }\n break;\n\n case 'a':\n if( getSizeUint32Hex(optarg, &authHandle) != 0 )\n {\n return -3;\n }\n break;\n\n case 'P':\n if( optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) )\n {\n printf(\"\\nPlease input the handle password(optional,no more than %d characters).\\n\", (int)sizeof(TPMU_HA)-1);\n return -4;\n }\n safeStrNCpy(&handlePasswd[0], optarg, sizeof(handlePasswd));\n break;\n\n case 'f':\n if( optarg == NULL )\n {\n printf(\"\\nPlease input the nv data file.\\n\");\n return -5;\n }\n safeStrNCpy(&fileName[0], optarg, sizeof(fileName));\n break;\n\n case 'p':\n if( getPort(optarg, &port) )\n {\n printf(\"Incorrect port number.\\n\");\n return -6;\n }\n break;\n case 'd':\n if( getDebugLevel(optarg, &debugLevel) )\n {\n printf(\"Incorrect debug level.\\n\");\n return -7;\n }\n break;\n\n default:\n showArgMismatch(argv[0]);\n return -8;\n }\n }\n\n if( nvIndex == 0 )\n {\n printf(\"You must provide an index (!= 0) for the NVRAM area.\\n\");\n return -9;\n }\n\n if( authHandle == 0 )\n {\n printf(\"You must provide an right auth handle for this operation.\\n\");\n return -10;\n }\n\n dataSize = MAX_NV_BUFFER_SIZE;\n if(loadDataFromFile(fileName, nvBuffer, &dataSize))\n {\n printf(\"Failed to read data from %s\\n\", fileName);\n return -11;\n }\n\n prepareTest(hostName, port, debugLevel);\n\n returnVal = nvWrite();\n\n finishTest();\n\n if(returnVal)\n return -12;\n\n return 0;\n}\ntpm2-nvwrite: fix for unable to write 1024B+ data\/\/**********************************************************************;\n\/\/ Copyright (c) 2015, Intel Corporation\n\/\/ All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions are met:\n\/\/\n\/\/ 1. Redistributions of source code must retain the above copyright notice,\n\/\/ this list of conditions and the following disclaimer.\n\/\/\n\/\/ 2. Redistributions in binary form must reproduce the above copyright notice,\n\/\/ this list of conditions and the following disclaimer in the documentation\n\/\/ and\/or other materials provided with the distribution.\n\/\/\n\/\/ 3. Neither the name of Intel Corporation nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this software without\n\/\/ specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n\/\/ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n\/\/ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n\/\/ ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n\/\/ LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n\/\/ CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n\/\/ SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n\/\/ INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n\/\/ CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n\/\/ ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF\n\/\/ THE POSSIBILITY OF SUCH DAMAGE.\n\/\/**********************************************************************;\n\n#ifdef _WIN32\n#include \"stdafx.h\"\n#else\n#include \n#endif\n\n#ifndef UNICODE\n#define UNICODE 1\n#endif\n\n#ifdef _WIN32\n\/\/ link with Ws2_32.lib\n#pragma comment(lib,\"Ws2_32.lib\")\n\n#include \n#include \n#else\n#define sprintf_s snprintf\n#define sscanf_s sscanf\n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \"common.h\"\n\nint debugLevel = 0;\nUINT32 nvIndex = 0;\nUINT32 authHandle = TPM_RH_PLATFORM;\nUINT16 dataSize = 0;\nunsigned char nvBuffer[MAX_NV_INDEX_SIZE];\nchar fileName[PATH_MAX];\nchar handlePasswd[sizeof(TPMU_HA)];\n\nint nvWrite()\n{\n UINT32 rval;\n TPMS_AUTH_COMMAND sessionData;\n TPMS_AUTH_RESPONSE sessionDataOut;\n TSS2_SYS_CMD_AUTHS sessionsData;\n TSS2_SYS_RSP_AUTHS sessionsDataOut;\n UINT16 i, offset = 0;\n TPM2B_MAX_NV_BUFFER nvWriteData;\n\n TPMS_AUTH_COMMAND *sessionDataArray[1] = { &sessionData };\n TPMS_AUTH_RESPONSE *sessionDataOutArray[1] = { &sessionDataOut };\n\n sessionsDataOut.rspAuths = &sessionDataOutArray[0];\n sessionsData.cmdAuths = &sessionDataArray[0];\n\n sessionsDataOut.rspAuthsCount = 1;\n sessionsData.cmdAuthsCount = 1;\n\n sessionData.sessionHandle = TPM_RS_PW;\n sessionData.nonce.t.size = 0;\n sessionData.hmac.t.size = 0;\n *( (UINT8 *)((void *)&sessionData.sessionAttributes ) ) = 0;\n\n if (strlen(handlePasswd) > 0)\n {\n sessionData.hmac.t.size = strlen(handlePasswd);\n memcpy( &sessionData.hmac.t.buffer[0], handlePasswd, sessionData.hmac.t.size );\n }\n\n while (dataSize > 0)\n {\n nvWriteData.t.size = dataSize > MAX_NV_BUFFER_SIZE ? MAX_NV_BUFFER_SIZE : dataSize;\n printf(\"\\nThe data(size=%d) to be written:\\n\", nvWriteData.t.size);\n for( i = 0; i<(int)nvWriteData.t.size; i++ )\n {\n nvWriteData.t.buffer[i] = nvBuffer[offset+i];\n printf(\"%02x \", nvBuffer[offset+i]);\n }\n printf(\"\\n\\n\");\n\n rval = Tss2_Sys_NV_Write( sysContext, authHandle, nvIndex, &sessionsData, &nvWriteData, offset, &sessionsDataOut );\n if(rval != TSS2_RC_SUCCESS)\n {\n printf( \"Failed to write NV area at index 0x%x (%d) offset 0x%x. Error:0x%x\\n\", nvIndex, nvIndex, offset, rval );\n return -1;\n }\n printf( \"Success to write NV area at index 0x%x (%d) offset 0x%x.\\n\", nvIndex, nvIndex, offset );\n\n dataSize -= nvWriteData.t.size;\n offset += nvWriteData.t.size; \n }\n\n return 0;\n}\n\nvoid showHelp(const char *name)\n{\n printf(\"Usage: %s [-h\/--help]\\n\"\n \" or: %s [-v\/--version]\\n\"\n \" or: %s [-x\/--index ] [-a\/--authHandle ] [-P\/--handlePasswd ] [-f\/--file ]\\n\"\n \" or: %s [-x\/--index ] [-a\/--authHandle ] [-P\/--handlePasswd ] [-f\/--file ]\\n\"\n \" [-p\/--port ] [-d\/--dbg ]\\n\"\n \"\\nwhere:\\n\\n\"\n \" -h\/--help display this help and exit.\\n\"\n \" -v\/--version display version information and exit.\\n\"\n \" -x\/--index specifies the index of the NV area.\\n\"\n \" -a\/--authHandle specifies the handle used to authorize:\\n\"\n \" 0x40000001 (TPM_RH_OWNER)\\n\"\n \" 0x4000000C (TPM_RH_PLATFORM)\\n\"\n \" {NV_INDEX_FIRST:NV_INDEX_LAST}\\n\"\n \" -P\/--handlePasswd specifies the password of authHandle.\\n\"\n \" -f\/--file specifies the nv data file.\\n\"\n \" -p\/--port specifies the port number, default:%d, optional\\n\"\n \" -d\/--dbg specifies level of debug messages, optional:\\n\"\n \" 0 (high level test results)\\n\"\n \" 1 (test app send\/receive byte streams)\\n\"\n \" 2 (resource manager send\/receive byte streams)\\n\"\n \" 3 (resource manager tables)\\n\"\n \"\\nexample:\\n\"\n \" %s -x 0x1500016 -a 0x40000001 -P passwd -f nv.data\\n\"\n , name, name, name, name, DEFAULT_RESMGR_TPM_PORT, name);\n}\n\nint main(int argc, char* argv[])\n{\n int opt;\n char type[100] = \"local\";\n char hostName[200] = DEFAULT_HOSTNAME;\n int port = DEFAULT_RESMGR_TPM_PORT;\n int returnVal = 0;\n\n struct option sOpts[] = {\n { \"index\" , required_argument, NULL, 'x' },\n { \"authHandle\" , required_argument, NULL, 'a' },\n { \"file\" , required_argument, NULL, 'f' },\n { \"handlePasswd\", required_argument, NULL, 'P' },\n { \"port\" , required_argument, NULL, 'p' },\n { \"dbg\" , required_argument, NULL, 'd' },\n { \"help\" , no_argument, NULL, 'h' },\n { \"version\" , no_argument, NULL, 'v' },\n { NULL , no_argument, NULL, 0 },\n };\n\n if(argc == 1)\n {\n showHelp(argv[0]);\n return 0;\n }\n\n if( argc > (int)(2*sizeof(sOpts)\/sizeof(struct option)) )\n {\n showArgMismatch(argv[0]);\n return -1;\n }\n\n while ( ( opt = getopt_long( argc, argv, \"x:a:f:P:p:d:hv\", sOpts, NULL ) ) != -1 )\n {\n switch ( opt ) {\n case 'h':\n case '?':\n showHelp(argv[0]);\n return 0;\n case 'v':\n showVersion(argv[0]);\n return 0;\n\n case 'x':\n if( getSizeUint32Hex(optarg, &nvIndex) != 0 )\n {\n return -2;\n }\n break;\n\n case 'a':\n if( getSizeUint32Hex(optarg, &authHandle) != 0 )\n {\n return -3;\n }\n break;\n\n case 'P':\n if( optarg == NULL || (strlen(optarg) >= sizeof(TPMU_HA)) )\n {\n printf(\"\\nPlease input the handle password(optional,no more than %d characters).\\n\", (int)sizeof(TPMU_HA)-1);\n return -4;\n }\n safeStrNCpy(&handlePasswd[0], optarg, sizeof(handlePasswd));\n break;\n\n case 'f':\n if( optarg == NULL )\n {\n printf(\"\\nPlease input the nv data file.\\n\");\n return -5;\n }\n safeStrNCpy(&fileName[0], optarg, sizeof(fileName));\n break;\n\n case 'p':\n if( getPort(optarg, &port) )\n {\n printf(\"Incorrect port number.\\n\");\n return -6;\n }\n break;\n case 'd':\n if( getDebugLevel(optarg, &debugLevel) )\n {\n printf(\"Incorrect debug level.\\n\");\n return -7;\n }\n break;\n\n default:\n showArgMismatch(argv[0]);\n return -8;\n }\n }\n\n if( nvIndex == 0 )\n {\n printf(\"You must provide an index (!= 0) for the NVRAM area.\\n\");\n return -9;\n }\n\n if( authHandle == 0 )\n {\n printf(\"You must provide an right auth handle for this operation.\\n\");\n return -10;\n }\n\n dataSize = MAX_NV_INDEX_SIZE;\n if(loadDataFromFile(fileName, nvBuffer, &dataSize))\n {\n printf(\"Failed to read data from %s\\n\", fileName);\n return -11;\n }\n\n prepareTest(hostName, port, debugLevel);\n\n returnVal = nvWrite();\n\n finishTest();\n\n if(returnVal)\n return -12;\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Ash Berlin, Aristid Breitkreuz\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/object.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/evaluate.hpp\"\n#include \"flusspferd\/io\/io.hpp\"\n#include \"test_environment.hpp\"\n\n#include \n#include \n\n#ifdef FLUSSPFERD_HAVE_IO\n\nBOOST_FIXTURE_TEST_SUITE( io, context_fixture )\n\nBOOST_AUTO_TEST_CASE( test_have_IO ) {\n flusspferd::io::load_io();\n flusspferd::root_value v;\n BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(\"IO\", __FILE__, __LINE__) );\n BOOST_CHECK(v.is_object());\n BOOST_CHECK(!v.is_null());\n\n flusspferd::gc();\n}\n\nBOOST_AUTO_TEST_CASE( test_file_read ) {\n flusspferd::io::load_io();\n const char* js = \"f = new IO.File('test\/fixtures\/file1'); f.readWhole()\";\n flusspferd::root_value v;\n BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );\n BOOST_CHECK_EQUAL(v.to_string().c_str(), \"foobar\\nbaz\\n\");\n\n js = \"f = new IO.File('test\/fixtures\/file1'); f.readWhole()\";\n BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );\n BOOST_CHECK_EQUAL(v.to_string().c_str(), \"foobar\\nbaz\\n\");\n\n flusspferd::gc();\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif\nTest: IO tests work again\/\/ vim:ts=2:sw=2:expandtab:autoindent:filetype=cpp:\n\/*\nCopyright (c) 2008 Ash Berlin, Aristid Breitkreuz\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n*\/\n\n#include \"flusspferd\/object.hpp\"\n#include \"flusspferd\/string.hpp\"\n#include \"flusspferd\/evaluate.hpp\"\n#include \"flusspferd\/security.hpp\"\n#include \"flusspferd\/io\/io.hpp\"\n#include \"test_environment.hpp\"\n\n#include \n#include \n\n#ifdef FLUSSPFERD_HAVE_IO\n\nBOOST_FIXTURE_TEST_SUITE( io, context_fixture )\n\nBOOST_AUTO_TEST_CASE( test_have_IO ) {\n flusspferd::io::load_io();\n flusspferd::root_value v;\n BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(\"IO\", __FILE__, __LINE__) );\n BOOST_CHECK(v.is_object());\n BOOST_CHECK(!v.is_null());\n\n flusspferd::gc();\n}\n\nBOOST_AUTO_TEST_CASE( test_file_read ) {\n flusspferd::io::load_io();\n flusspferd::security::create(flusspferd::global());\n\n const char* js = \"f = new IO.File('test\/fixtures\/file1'); f.readWhole()\";\n flusspferd::root_value v;\n BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );\n BOOST_CHECK_EQUAL(v.to_string().c_str(), \"foobar\\nbaz\\n\");\n\n js = \"f = new IO.File('test\/fixtures\/file1'); f.readWhole()\";\n BOOST_CHECK_NO_THROW( v = flusspferd::evaluate(js, __FILE__, __LINE__) );\n BOOST_CHECK_EQUAL(v.to_string().c_str(), \"foobar\\nbaz\\n\");\n\n flusspferd::gc();\n}\n\n\nBOOST_AUTO_TEST_SUITE_END()\n\n#endif\n<|endoftext|>"} {"text":"\/*=====================================================================\nQGroundControl Open Source Ground Control Station\n\n(c) 2009, 2010 QGROUNDCONTROL PROJECT \n\nThis file is part of the QGROUNDCONTROL project\n\n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see .\n\n======================================================================*\/\n\n#include \"PxQuadMAV.h\"\n#include \"GAudioOutput.h\"\n\nPxQuadMAV::PxQuadMAV(MAVLinkProtocol* mavlink, int id) :\n UAS(mavlink, id)\n{\n}\n\n\/**\n * This function is called by MAVLink once a complete, uncorrupted (CRC check valid)\n * mavlink packet is received.\n *\n * @param link Hardware link the message came from (e.g. \/dev\/ttyUSB0 or UDP port).\n * messages can be sent back to the system via this link\n * @param message MAVLink message, as received from the MAVLink protocol stack\n *\/\nvoid PxQuadMAV::receiveMessage(LinkInterface* link, mavlink_message_t message)\n{\n \/\/ Only compile this portion if matching MAVLink packets have been compiled\n#ifdef MAVLINK_ENABLED_PIXHAWK\n mavlink_message_t* msg = &message;\n\n if (message.sysid == uasId) {\n switch (message.msgid) {\n case MAVLINK_MSG_ID_RAW_AUX: {\n mavlink_raw_aux_t raw;\n mavlink_msg_raw_aux_decode(&message, &raw);\n quint64 time = getUnixTime(0);\n emit valueChanged(uasId, \"Pressure\", \"raw\", raw.baro, time);\n emit valueChanged(uasId, \"Temperature\", \"raw\", raw.temp, time);\n }\n break;\n case MAVLINK_MSG_ID_IMAGE_TRIGGERED: {\n \/\/ FIXME Kind of a hack to load data from disk\n mavlink_image_triggered_t img;\n mavlink_msg_image_triggered_decode(&message, &img);\n qDebug() << \"IMAGE AVAILABLE:\" << img.timestamp;\n emit imageStarted(img.timestamp);\n }\n break;\n case MAVLINK_MSG_ID_PATTERN_DETECTED: {\n mavlink_pattern_detected_t detected;\n mavlink_msg_pattern_detected_decode(&message, &detected);\n QByteArray b;\n b.resize(256);\n mavlink_msg_pattern_detected_get_file(&message, (int8_t*)b.data());\n b.append('\\0');\n QString name = QString(b);\n if (detected.type == 0)\n emit patternDetected(uasId, name, detected.confidence, detected.detected);\n else if (detected.type == 1)\n emit letterDetected(uasId, name, detected.confidence, detected.detected);\n }\n break;\n case MAVLINK_MSG_ID_WATCHDOG_HEARTBEAT: {\n mavlink_watchdog_heartbeat_t payload;\n mavlink_msg_watchdog_heartbeat_decode(msg, &payload);\n\n emit watchdogReceived(this->uasId, payload.watchdog_id, payload.process_count);\n }\n break;\n\n case MAVLINK_MSG_ID_WATCHDOG_PROCESS_INFO: {\n mavlink_watchdog_process_info_t payload;\n mavlink_msg_watchdog_process_info_decode(msg, &payload);\n\n emit processReceived(this->uasId, payload.watchdog_id, payload.process_id, QString((const char*)payload.name), QString((const char*)payload.arguments), payload.timeout);\n }\n break;\n\n case MAVLINK_MSG_ID_WATCHDOG_PROCESS_STATUS: {\n mavlink_watchdog_process_status_t payload;\n mavlink_msg_watchdog_process_status_decode(msg, &payload);\n emit processChanged(this->uasId, payload.watchdog_id, payload.process_id, payload.state, (payload.muted == 1) ? true : false, payload.crashes, payload.pid);\n }\n break;\n case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE: {\n mavlink_vision_position_estimate_t pos;\n mavlink_msg_vision_position_estimate_decode(&message, &pos);\n quint64 time = getUnixTime(pos.usec);\n \/\/emit valueChanged(uasId, \"vis. time\", pos.usec, time);\n emit valueChanged(uasId, \"vis. roll\", \"rad\", pos.roll, time);\n emit valueChanged(uasId, \"vis. pitch\", \"rad\", pos.pitch, time);\n emit valueChanged(uasId, \"vis. yaw\", \"rad\", pos.yaw, time);\n emit valueChanged(uasId, \"vis. x\", \"m\", pos.x, time);\n emit valueChanged(uasId, \"vis. y\", \"m\", pos.y, time);\n emit valueChanged(uasId, \"vis. z\", \"m\", pos.z, time);\n }\n break;\n case MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE: {\n mavlink_vicon_position_estimate_t pos;\n mavlink_msg_vicon_position_estimate_decode(&message, &pos);\n quint64 time = getUnixTime(pos.usec);\n \/\/emit valueChanged(uasId, \"vis. time\", pos.usec, time);\n emit valueChanged(uasId, \"vicon roll\", \"rad\", pos.roll, time);\n emit valueChanged(uasId, \"vicon pitch\", \"rad\", pos.pitch, time);\n emit valueChanged(uasId, \"vicon yaw\", \"rad\", pos.yaw, time);\n emit valueChanged(uasId, \"vicon x\", \"m\", pos.x, time);\n emit valueChanged(uasId, \"vicon y\", \"m\", pos.y, time);\n emit valueChanged(uasId, \"vicon z\", \"m\", pos.z, time);\n emit localPositionChanged(this, pos.x, pos.y, pos.z, time);\n }\n break;\n case MAVLINK_MSG_ID_AUX_STATUS: {\n mavlink_aux_status_t status;\n mavlink_msg_aux_status_decode(&message, &status);\n emit loadChanged(this, status.load\/10.0f);\n emit errCountChanged(uasId, \"IMU\", \"I2C0\", status.i2c0_err_count);\n emit errCountChanged(uasId, \"IMU\", \"I2C1\", status.i2c1_err_count);\n emit errCountChanged(uasId, \"IMU\", \"SPI0\", status.spi0_err_count);\n emit errCountChanged(uasId, \"IMU\", \"SPI1\", status.spi1_err_count);\n emit errCountChanged(uasId, \"IMU\", \"UART\", status.uart_total_err_count);\n emit valueChanged(uasId, \"Load\", \"%\", ((float)status.load)\/10.0f, getUnixTime());\n }\n break;\n default:\n \/\/ Let UAS handle the default message set\n UAS::receiveMessage(link, message);\n break;\n }\n }\n\n#else\n \/\/ Let UAS handle the default message set\n UAS::receiveMessage(link, message);\n Q_UNUSED(link);\n Q_UNUSED(message);\n#endif\n}\n\nvoid PxQuadMAV::sendProcessCommand(int watchdogId, int processId, unsigned int command)\n{\n#ifdef MAVLINK_ENABLED_PIXHAWK\n mavlink_watchdog_command_t payload;\n payload.target_system_id = uasId;\n payload.watchdog_id = watchdogId;\n payload.process_id = processId;\n payload.command_id = (uint8_t)command;\n\n mavlink_message_t msg;\n mavlink_msg_watchdog_command_encode(mavlink->getSystemId(), mavlink->getComponentId(), &msg, &payload);\n sendMessage(msg);\n#else\n Q_UNUSED(watchdogId);\n Q_UNUSED(processId);\n Q_UNUSED(command);\n#endif\n}\nadded vision speed estimate parsing (pixhawk specific)\/*=====================================================================\nQGroundControl Open Source Ground Control Station\n\n(c) 2009, 2010 QGROUNDCONTROL PROJECT \n\nThis file is part of the QGROUNDCONTROL project\n\n QGROUNDCONTROL is free software: you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation, either version 3 of the License, or\n (at your option) any later version.\n\n QGROUNDCONTROL is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with QGROUNDCONTROL. If not, see .\n\n======================================================================*\/\n\n#include \"PxQuadMAV.h\"\n#include \"GAudioOutput.h\"\n\nPxQuadMAV::PxQuadMAV(MAVLinkProtocol* mavlink, int id) :\n UAS(mavlink, id)\n{\n}\n\n\/**\n * This function is called by MAVLink once a complete, uncorrupted (CRC check valid)\n * mavlink packet is received.\n *\n * @param link Hardware link the message came from (e.g. \/dev\/ttyUSB0 or UDP port).\n * messages can be sent back to the system via this link\n * @param message MAVLink message, as received from the MAVLink protocol stack\n *\/\nvoid PxQuadMAV::receiveMessage(LinkInterface* link, mavlink_message_t message)\n{\n \/\/ Only compile this portion if matching MAVLink packets have been compiled\n#ifdef MAVLINK_ENABLED_PIXHAWK\n mavlink_message_t* msg = &message;\n\n if (message.sysid == uasId) {\n switch (message.msgid) {\n case MAVLINK_MSG_ID_RAW_AUX: {\n mavlink_raw_aux_t raw;\n mavlink_msg_raw_aux_decode(&message, &raw);\n quint64 time = getUnixTime(0);\n emit valueChanged(uasId, \"Pressure\", \"raw\", raw.baro, time);\n emit valueChanged(uasId, \"Temperature\", \"raw\", raw.temp, time);\n }\n break;\n case MAVLINK_MSG_ID_IMAGE_TRIGGERED: {\n \/\/ FIXME Kind of a hack to load data from disk\n mavlink_image_triggered_t img;\n mavlink_msg_image_triggered_decode(&message, &img);\n qDebug() << \"IMAGE AVAILABLE:\" << img.timestamp;\n emit imageStarted(img.timestamp);\n }\n break;\n case MAVLINK_MSG_ID_PATTERN_DETECTED: {\n mavlink_pattern_detected_t detected;\n mavlink_msg_pattern_detected_decode(&message, &detected);\n QByteArray b;\n b.resize(256);\n mavlink_msg_pattern_detected_get_file(&message, (int8_t*)b.data());\n b.append('\\0');\n QString name = QString(b);\n if (detected.type == 0)\n emit patternDetected(uasId, name, detected.confidence, detected.detected);\n else if (detected.type == 1)\n emit letterDetected(uasId, name, detected.confidence, detected.detected);\n }\n break;\n case MAVLINK_MSG_ID_WATCHDOG_HEARTBEAT: {\n mavlink_watchdog_heartbeat_t payload;\n mavlink_msg_watchdog_heartbeat_decode(msg, &payload);\n\n emit watchdogReceived(this->uasId, payload.watchdog_id, payload.process_count);\n }\n break;\n\n case MAVLINK_MSG_ID_WATCHDOG_PROCESS_INFO: {\n mavlink_watchdog_process_info_t payload;\n mavlink_msg_watchdog_process_info_decode(msg, &payload);\n\n emit processReceived(this->uasId, payload.watchdog_id, payload.process_id, QString((const char*)payload.name), QString((const char*)payload.arguments), payload.timeout);\n }\n break;\n\n case MAVLINK_MSG_ID_WATCHDOG_PROCESS_STATUS: {\n mavlink_watchdog_process_status_t payload;\n mavlink_msg_watchdog_process_status_decode(msg, &payload);\n emit processChanged(this->uasId, payload.watchdog_id, payload.process_id, payload.state, (payload.muted == 1) ? true : false, payload.crashes, payload.pid);\n }\n break;\n case MAVLINK_MSG_ID_VISION_POSITION_ESTIMATE: {\n mavlink_vision_position_estimate_t pos;\n mavlink_msg_vision_position_estimate_decode(&message, &pos);\n quint64 time = getUnixTime(pos.usec);\n \/\/emit valueChanged(uasId, \"vis. time\", pos.usec, time);\n emit valueChanged(uasId, \"vis. roll\", \"rad\", pos.roll, time);\n emit valueChanged(uasId, \"vis. pitch\", \"rad\", pos.pitch, time);\n emit valueChanged(uasId, \"vis. yaw\", \"rad\", pos.yaw, time);\n emit valueChanged(uasId, \"vis. x\", \"m\", pos.x, time);\n emit valueChanged(uasId, \"vis. y\", \"m\", pos.y, time);\n emit valueChanged(uasId, \"vis. z\", \"m\", pos.z, time);\n }\n break;\n case MAVLINK_MSG_ID_VICON_POSITION_ESTIMATE: {\n mavlink_vicon_position_estimate_t pos;\n mavlink_msg_vicon_position_estimate_decode(&message, &pos);\n quint64 time = getUnixTime(pos.usec);\n \/\/emit valueChanged(uasId, \"vis. time\", pos.usec, time);\n emit valueChanged(uasId, \"vicon roll\", \"rad\", pos.roll, time);\n emit valueChanged(uasId, \"vicon pitch\", \"rad\", pos.pitch, time);\n emit valueChanged(uasId, \"vicon yaw\", \"rad\", pos.yaw, time);\n emit valueChanged(uasId, \"vicon x\", \"m\", pos.x, time);\n emit valueChanged(uasId, \"vicon y\", \"m\", pos.y, time);\n emit valueChanged(uasId, \"vicon z\", \"m\", pos.z, time);\n \/\/emit localPositionChanged(this, pos.x, pos.y, pos.z, time);\n }\n break;\n case MAVLINK_MSG_ID_VISION_SPEED_ESTIMATE: {\n mavlink_vision_speed_estimate_t speed;\n mavlink_msg_vision_speed_estimate_decode(&message, &speed);\n quint64 time = getUnixTime(speed.usec);\n emit valueChanged(uasId, \"vis. speed x\", \"m\/s\", speed.x, time);\n emit valueChanged(uasId, \"vis. speed y\", \"m\/s\", speed.y, time);\n emit valueChanged(uasId, \"vis. speed z\", \"m\/s\", speed.z, time);\n }\n break;\n case MAVLINK_MSG_ID_AUX_STATUS: {\n mavlink_aux_status_t status;\n mavlink_msg_aux_status_decode(&message, &status);\n emit loadChanged(this, status.load\/10.0f);\n emit errCountChanged(uasId, \"IMU\", \"I2C0\", status.i2c0_err_count);\n emit errCountChanged(uasId, \"IMU\", \"I2C1\", status.i2c1_err_count);\n emit errCountChanged(uasId, \"IMU\", \"SPI0\", status.spi0_err_count);\n emit errCountChanged(uasId, \"IMU\", \"SPI1\", status.spi1_err_count);\n emit errCountChanged(uasId, \"IMU\", \"UART\", status.uart_total_err_count);\n emit valueChanged(uasId, \"Load\", \"%\", ((float)status.load)\/10.0f, getUnixTime());\n }\n break;\n default:\n \/\/ Let UAS handle the default message set\n UAS::receiveMessage(link, message);\n break;\n }\n }\n\n#else\n \/\/ Let UAS handle the default message set\n UAS::receiveMessage(link, message);\n Q_UNUSED(link);\n Q_UNUSED(message);\n#endif\n}\n\nvoid PxQuadMAV::sendProcessCommand(int watchdogId, int processId, unsigned int command)\n{\n#ifdef MAVLINK_ENABLED_PIXHAWK\n mavlink_watchdog_command_t payload;\n payload.target_system_id = uasId;\n payload.watchdog_id = watchdogId;\n payload.process_id = processId;\n payload.command_id = (uint8_t)command;\n\n mavlink_message_t msg;\n mavlink_msg_watchdog_command_encode(mavlink->getSystemId(), mavlink->getComponentId(), &msg, &payload);\n sendMessage(msg);\n#else\n Q_UNUSED(watchdogId);\n Q_UNUSED(processId);\n Q_UNUSED(command);\n#endif\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright (C) 2013 Daniel Nicoletti \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"udisksclient_p.h\"\n\n#include \"udiskspartition.h\"\n#include \"common.h\"\n\n#include \n\nQ_LOGGING_CATEGORY(UDISKSQT_CLIENT, \"udisksqt.client\")\n\nUDisksClient::UDisksClient(QObject *parent) :\n QObject(parent),\n d_ptr(new UDisksClientPrivate)\n{\n Q_D(UDisksClient);\n\n connect(&d->objectInterface, &OrgFreedesktopDBusObjectManagerInterface::InterfacesAdded,\n this, [=] (const QDBusObjectPath & objectPath, UDVariantMapMap interfacesAndProperties) {\n qCDebug(UDISKSQT_CLIENT) << \"interfaces added\" << objectPath.path();\n\n UDisksObject::Ptr object = d->objects.value(objectPath);\n if (object.isNull()) {\n UDisksObject::Ptr object(new UDisksObject(objectPath, interfacesAndProperties, this));\n d->objects.insert(objectPath, object);\n Q_EMIT objectAdded(object);\n } else {\n object->addInterfaces(interfacesAndProperties);\n Q_EMIT interfacesAdded(object);\n }\n });\n connect(&d->objectInterface, &OrgFreedesktopDBusObjectManagerInterface::InterfacesRemoved,\n this, [=] (const QDBusObjectPath & objectPath, const QStringList &interfaces) {\n qCDebug(UDISKSQT_CLIENT) << \"interfaces removed\" << objectPath.path();\n\n auto it = d->objects.find(objectPath);\n if (it != d->objects.end() && !it.value().isNull()) {\n UDisksObject::Ptr object = it.value();\n it.value()->removeInterfaces(interfaces);\n if (object->interfaces() == UDisksObject::InterfaceNone) {\n Q_EMIT objectRemoved(object);\n d->objects.erase(it);\n } else {\n Q_EMIT interfacesRemoved(object);\n }\n }\n });\n\n auto watcher = new QDBusServiceWatcher(QStringLiteral(UD2_SERVICE),\n QDBusConnection::systemBus(),\n QDBusServiceWatcher::WatchForUnregistration,\n this);\n connect(watcher, &QDBusServiceWatcher::serviceUnregistered, this, [=] {\n if (d->inited) {\n auto it = d->objects.begin();\n while (it != d->objects.end()) {\n UDisksObject::Ptr object = it.value();\n if (object) {\n Q_EMIT objectRemoved(object);\n }\n d->objects.erase(it);\n }\n\n d->inited = false;\n Q_EMIT initChanged();\n }\n });\n}\n\nUDisksClient::~UDisksClient()\n{\n delete d_ptr;\n}\n\nbool UDisksClient::inited() const\n{\n Q_D(const UDisksClient);\n return d->inited;\n}\n\nbool UDisksClient::init(bool async)\n{\n Q_D(UDisksClient);\n\n if (d->inited) {\n return true;\n }\n\n if (async) {\n QDBusPendingReply reply = d->objectInterface.GetManagedObjects();\n auto watcher = new QDBusPendingCallWatcher(reply, this);\n connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] {\n QDBusPendingReply reply = *watcher;\n if (reply.isError()) {\n qCWarning(UDISKSQT_CLIENT) << \"Failed to get objects\" << reply.error().message();\n } else {\n d->initObjects(reply.value(), this);\n }\n watcher->deleteLater();\n\n d->inited = true;\n Q_EMIT objectsAvailable();\n });\n } else {\n QDBusReply reply = d->objectInterface.GetManagedObjects();\n d->inited = true;\n\n if (!reply.isValid()) {\n qCWarning(UDISKSQT_CLIENT) << \"Failed to get managed objects:\" << reply.error().message();\n return false;\n }\n\n d->initObjects(reply.value(), this);\n }\n return true;\n}\n\nUDisksObject::List UDisksClient::getObjects(UDisksObject::Kind kind) const\n{\n Q_D(const UDisksClient);\n\n if (kind == UDisksObject::Any) {\n return d->objects.values();\n } else {\n UDisksObject::List ret;\n QHash::ConstIterator it = d->objects.constBegin();\n while (it != d->objects.end()) {\n if (kind == it.value()->kind()) {\n ret.append(it.value());\n }\n ++it;\n }\n return ret;\n }\n}\n\nUDisksObject::List UDisksClient::getObjects(const QList &objectPaths) const\n{\n Q_D(const UDisksClient);\n UDisksObject::List ret;\n for (const QDBusObjectPath &objectPath : objectPaths) {\n UDisksObject::Ptr object = d->objects.value(objectPath);\n if (object) {\n ret.append(object);\n }\n }\n return ret;\n}\n\nUDisksObject::Ptr UDisksClient::getObject(const QDBusObjectPath &objectPath) const\n{\n Q_D(const UDisksClient);\n return d->objects.value(objectPath);\n}\n\nUDisksObject::List UDisksClient::getPartitions(const QDBusObjectPath &tablePath) const\n{\n UDisksObject::List ret;\n const UDisksObject::List blockDevices = getObjects(UDisksObject::BlockDevice);\n for (const UDisksObject::Ptr &object : blockDevices) {\n if (object->partition() && object->partition()->table() == tablePath) {\n ret.append(object);\n }\n }\n return ret;\n}\n\nUDisksManager *UDisksClient::manager() const\n{\n UDisksManager *ret = nullptr;\n const UDisksObject::List managers = getObjects(UDisksObject::Manager);\n if (!managers.isEmpty()) {\n ret = managers.first()->manager();\n }\n return ret;\n}\n\nUDisksClientPrivate::UDisksClientPrivate()\n : objectInterface(QLatin1String(UD2_SERVICE),\n QLatin1String(UD2_PATH),\n QDBusConnection::systemBus())\n{\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n\n if (!objectInterface.isValid()) {\n \/\/ TODO do an async call\n QDBusMessage message;\n message = QDBusMessage::createMethodCall(QLatin1String(\"org.freedesktop.DBus\"),\n QLatin1String(\"\/org\/freedesktop\/DBus\"),\n QLatin1String(\"org.freedesktop.DBus\"),\n QLatin1String(\"ListActivatableNames\"));\n\n QDBusReply reply = QDBusConnection::systemBus().call(message);\n if (reply.isValid() && reply.value().contains(QLatin1String(UD2_SERVICE))) {\n QDBusConnection::systemBus().interface()->startService(QLatin1String(UD2_SERVICE));\n } else {\n qCWarning(UDISKSQT_CLIENT) << \"UDisk2 service is not available, check if it's properly installed\";\n }\n }\n}\n\nvoid UDisksClientPrivate::initObjects(const UDManagedObjects &managedObjects, UDisksClient *client)\n{\n UDManagedObjects::ConstIterator it = managedObjects.constBegin();\n while (it != managedObjects.constEnd()) {\n UDisksObject::Ptr object(new UDisksObject(it.key(), it.value(), client));\n objects.insert(it.key(), object);\n ++it;\n }\n}\n\n#include \"moc_udisksclient.cpp\"\nFix sending initChanged\/*\n * Copyright (C) 2013 Daniel Nicoletti \n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Library General Public\n * License as published by the Free Software Foundation; either\n * version 2 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Library General Public License for more details.\n *\n * You should have received a copy of the GNU Library General Public License\n * along with this library; see the file COPYING.LIB. If not, write to\n * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,\n * Boston, MA 02110-1301, USA.\n *\/\n\n#include \"udisksclient_p.h\"\n\n#include \"udiskspartition.h\"\n#include \"common.h\"\n\n#include \n\nQ_LOGGING_CATEGORY(UDISKSQT_CLIENT, \"udisksqt.client\")\n\nUDisksClient::UDisksClient(QObject *parent) :\n QObject(parent),\n d_ptr(new UDisksClientPrivate)\n{\n Q_D(UDisksClient);\n\n connect(&d->objectInterface, &OrgFreedesktopDBusObjectManagerInterface::InterfacesAdded,\n this, [=] (const QDBusObjectPath & objectPath, UDVariantMapMap interfacesAndProperties) {\n qCDebug(UDISKSQT_CLIENT) << \"interfaces added\" << objectPath.path();\n\n UDisksObject::Ptr object = d->objects.value(objectPath);\n if (object.isNull()) {\n UDisksObject::Ptr object(new UDisksObject(objectPath, interfacesAndProperties, this));\n d->objects.insert(objectPath, object);\n Q_EMIT objectAdded(object);\n } else {\n object->addInterfaces(interfacesAndProperties);\n Q_EMIT interfacesAdded(object);\n }\n });\n connect(&d->objectInterface, &OrgFreedesktopDBusObjectManagerInterface::InterfacesRemoved,\n this, [=] (const QDBusObjectPath & objectPath, const QStringList &interfaces) {\n qCDebug(UDISKSQT_CLIENT) << \"interfaces removed\" << objectPath.path();\n\n auto it = d->objects.find(objectPath);\n if (it != d->objects.end() && !it.value().isNull()) {\n UDisksObject::Ptr object = it.value();\n it.value()->removeInterfaces(interfaces);\n if (object->interfaces() == UDisksObject::InterfaceNone) {\n Q_EMIT objectRemoved(object);\n d->objects.erase(it);\n } else {\n Q_EMIT interfacesRemoved(object);\n }\n }\n });\n\n auto watcher = new QDBusServiceWatcher(QStringLiteral(UD2_SERVICE),\n QDBusConnection::systemBus(),\n QDBusServiceWatcher::WatchForUnregistration,\n this);\n connect(watcher, &QDBusServiceWatcher::serviceUnregistered, this, [=] {\n if (d->inited) {\n auto it = d->objects.begin();\n while (it != d->objects.end()) {\n UDisksObject::Ptr object = it.value();\n if (object) {\n Q_EMIT objectRemoved(object);\n }\n d->objects.erase(it);\n }\n\n d->inited = false;\n Q_EMIT initChanged();\n }\n });\n}\n\nUDisksClient::~UDisksClient()\n{\n delete d_ptr;\n}\n\nbool UDisksClient::inited() const\n{\n Q_D(const UDisksClient);\n return d->inited;\n}\n\nbool UDisksClient::init(bool async)\n{\n Q_D(UDisksClient);\n\n if (d->inited) {\n return true;\n }\n\n if (async) {\n QDBusPendingReply reply = d->objectInterface.GetManagedObjects();\n auto watcher = new QDBusPendingCallWatcher(reply, this);\n connect(watcher, &QDBusPendingCallWatcher::finished, this, [=] {\n QDBusPendingReply reply = *watcher;\n if (reply.isError()) {\n qCWarning(UDISKSQT_CLIENT) << \"Failed to get objects\" << reply.error().message();\n } else {\n d->initObjects(reply.value(), this);\n }\n watcher->deleteLater();\n\n d->inited = true;\n Q_EMIT initChanged();\n Q_EMIT objectsAvailable();\n });\n } else {\n QDBusReply reply = d->objectInterface.GetManagedObjects();\n d->inited = true;\n Q_EMIT initChanged();\n\n if (!reply.isValid()) {\n qCWarning(UDISKSQT_CLIENT) << \"Failed to get managed objects:\" << reply.error().message();\n return false;\n }\n\n d->initObjects(reply.value(), this);\n }\n return true;\n}\n\nUDisksObject::List UDisksClient::getObjects(UDisksObject::Kind kind) const\n{\n Q_D(const UDisksClient);\n\n if (kind == UDisksObject::Any) {\n return d->objects.values();\n } else {\n UDisksObject::List ret;\n QHash::ConstIterator it = d->objects.constBegin();\n while (it != d->objects.end()) {\n if (kind == it.value()->kind()) {\n ret.append(it.value());\n }\n ++it;\n }\n return ret;\n }\n}\n\nUDisksObject::List UDisksClient::getObjects(const QList &objectPaths) const\n{\n Q_D(const UDisksClient);\n UDisksObject::List ret;\n for (const QDBusObjectPath &objectPath : objectPaths) {\n UDisksObject::Ptr object = d->objects.value(objectPath);\n if (object) {\n ret.append(object);\n }\n }\n return ret;\n}\n\nUDisksObject::Ptr UDisksClient::getObject(const QDBusObjectPath &objectPath) const\n{\n Q_D(const UDisksClient);\n return d->objects.value(objectPath);\n}\n\nUDisksObject::List UDisksClient::getPartitions(const QDBusObjectPath &tablePath) const\n{\n UDisksObject::List ret;\n const UDisksObject::List blockDevices = getObjects(UDisksObject::BlockDevice);\n for (const UDisksObject::Ptr &object : blockDevices) {\n if (object->partition() && object->partition()->table() == tablePath) {\n ret.append(object);\n }\n }\n return ret;\n}\n\nUDisksManager *UDisksClient::manager() const\n{\n UDisksManager *ret = nullptr;\n const UDisksObject::List managers = getObjects(UDisksObject::Manager);\n if (!managers.isEmpty()) {\n ret = managers.first()->manager();\n }\n return ret;\n}\n\nUDisksClientPrivate::UDisksClientPrivate()\n : objectInterface(QLatin1String(UD2_SERVICE),\n QLatin1String(UD2_PATH),\n QDBusConnection::systemBus())\n{\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n qDBusRegisterMetaType();\n\n if (!objectInterface.isValid()) {\n \/\/ TODO do an async call\n QDBusMessage message;\n message = QDBusMessage::createMethodCall(QLatin1String(\"org.freedesktop.DBus\"),\n QLatin1String(\"\/org\/freedesktop\/DBus\"),\n QLatin1String(\"org.freedesktop.DBus\"),\n QLatin1String(\"ListActivatableNames\"));\n\n QDBusReply reply = QDBusConnection::systemBus().call(message);\n if (reply.isValid() && reply.value().contains(QLatin1String(UD2_SERVICE))) {\n QDBusConnection::systemBus().interface()->startService(QLatin1String(UD2_SERVICE));\n } else {\n qCWarning(UDISKSQT_CLIENT) << \"UDisk2 service is not available, check if it's properly installed\";\n }\n }\n}\n\nvoid UDisksClientPrivate::initObjects(const UDManagedObjects &managedObjects, UDisksClient *client)\n{\n UDManagedObjects::ConstIterator it = managedObjects.constBegin();\n while (it != managedObjects.constEnd()) {\n UDisksObject::Ptr object(new UDisksObject(it.key(), it.value(), client));\n objects.insert(it.key(), object);\n ++it;\n }\n}\n\n#include \"moc_udisksclient.cpp\"\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ OpenGL Mathematics (glm.g-truc.net)\n\/\/\/\n\/\/\/ Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/ \n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/ \n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\/\/\/ @ref gtx_matrix_transform_2d\n\/\/\/ @file glm\/gtc\/gtx_matrix_transform_2d.inl\n\/\/\/ @date 2014-02-20\n\/\/\/ @author Miguel Ángel Pérez Martínez\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n\nnamespace glm\n{\n\t\n\ttemplate \n\tGLM_FUNC_QUALIFIER detail::tmat3x3 translate(\n\t\tdetail::tmat3x3 const & m,\n\t\tdetail::tvec2 const & v)\n\t{\n\t\tdetail::tmat3x3 Result(m);\n\t\tResult[2] = m[0] * v[0] + m[1] * v[1] + m[2];\n\t\treturn Result;\n\t}\n\n\n\ttemplate \n \tGLM_FUNC_QUALIFIER detail::tmat3x3 rotate(\n\t\tdetail::tmat3x3 const & m,\n\t\tT const & angle)\n\t{\n\t#ifdef GLM_FORCE_RADIANS\n\t\tT a = angle;\n\t#else\n\t\tT a = radians(angle);\t\t\n\t#endif\n\t\tT c = cos(a);\n\t\tT s = sin(a);\n\n detail::tmat3x3 Result(detail::tmat3x3::_null);\n\t\tResult[0] = m[0] * c + m[1] * s;\n\t\tResult[1] = m[0] * -s + m[1] * c;\n\t\tResult[2] = m[2];\n\t\treturn Result;\n\t}\n\n\ttemplate \n\tGLM_FUNC_QUALIFIER detail::tmat3x3 scale(\n\t\tdetail::tmat3x3 const & m,\n\t\tdetail::tvec2 const & v)\n\t{\n detail::tmat3x3 Result(detail::tmat3x3::_null);\n\t\tResult[0] = m[0] * v[0];\n\t\tResult[1] = m[1] * v[1];\n Result[2] = m[2];\n\t\treturn Result;\n\t}\n\n\ttemplate \n \tGLM_FUNC_QUALIFIER detail::tmat3x3 shearX(\n\t\tdetail::tmat3x3 const & m,\n\t\tT const & y)\n\t{\n\t\tdetail::tmat3x3 Result();\n\t\tResult[0][1] = y;\n\t\treturn m * Result;\n\t}\n\n\ttemplate \n \tGLM_FUNC_QUALIFIER detail::tmat3x3 shearY(\n\t\tdetail::tmat3x3 const & m,\n\t\tT const & x)\n\t{\n\t\tdetail::tmat3x3 Result();\n\t\tResult[1][0] = x;\n\t\treturn m * Result;\n\t}\n\n}\/\/namespace glm\nAdded trigonometric.hpp dep to matrix_transform_2d.inl\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/ OpenGL Mathematics (glm.g-truc.net)\n\/\/\/\n\/\/\/ Copyright (c) 2005 - 2014 G-Truc Creation (www.g-truc.net)\n\/\/\/ Permission is hereby granted, free of charge, to any person obtaining a copy\n\/\/\/ of this software and associated documentation files (the \"Software\"), to deal\n\/\/\/ in the Software without restriction, including without limitation the rights\n\/\/\/ to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n\/\/\/ copies of the Software, and to permit persons to whom the Software is\n\/\/\/ furnished to do so, subject to the following conditions:\n\/\/\/ \n\/\/\/ The above copyright notice and this permission notice shall be included in\n\/\/\/ all copies or substantial portions of the Software.\n\/\/\/ \n\/\/\/ THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n\/\/\/ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n\/\/\/ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n\/\/\/ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n\/\/\/ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n\/\/\/ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n\/\/\/ THE SOFTWARE.\n\/\/\/\n\/\/\/ @ref gtx_matrix_transform_2d\n\/\/\/ @file glm\/gtc\/matrix_transform_2d.inl\n\/\/\/ @date 2014-02-20\n\/\/\/ @author Miguel Ángel Pérez Martínez\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"..\/trigonometric.hpp\"\n\nnamespace glm\n{\n\t\n\ttemplate \n\tGLM_FUNC_QUALIFIER detail::tmat3x3 translate(\n\t\tdetail::tmat3x3 const & m,\n\t\tdetail::tvec2 const & v)\n\t{\n\t\tdetail::tmat3x3 Result(m);\n\t\tResult[2] = m[0] * v[0] + m[1] * v[1] + m[2];\n\t\treturn Result;\n\t}\n\n\n\ttemplate \n \tGLM_FUNC_QUALIFIER detail::tmat3x3 rotate(\n\t\tdetail::tmat3x3 const & m,\n\t\tT const & angle)\n\t{\n\t#ifdef GLM_FORCE_RADIANS\n\t\tT a = angle;\n\t#else\n\t\tT a = radians(angle);\t\t\n\t#endif\n\t\tT c = cos(a);\n\t\tT s = sin(a);\n\n detail::tmat3x3 Result(detail::tmat3x3::_null);\n\t\tResult[0] = m[0] * c + m[1] * s;\n\t\tResult[1] = m[0] * -s + m[1] * c;\n\t\tResult[2] = m[2];\n\t\treturn Result;\n\t}\n\n\ttemplate \n\tGLM_FUNC_QUALIFIER detail::tmat3x3 scale(\n\t\tdetail::tmat3x3 const & m,\n\t\tdetail::tvec2 const & v)\n\t{\n detail::tmat3x3 Result(detail::tmat3x3::_null);\n\t\tResult[0] = m[0] * v[0];\n\t\tResult[1] = m[1] * v[1];\n Result[2] = m[2];\n\t\treturn Result;\n\t}\n\n\ttemplate \n \tGLM_FUNC_QUALIFIER detail::tmat3x3 shearX(\n\t\tdetail::tmat3x3 const & m,\n\t\tT const & y)\n\t{\n\t\tdetail::tmat3x3 Result();\n\t\tResult[0][1] = y;\n\t\treturn m * Result;\n\t}\n\n\ttemplate \n \tGLM_FUNC_QUALIFIER detail::tmat3x3 shearY(\n\t\tdetail::tmat3x3 const & m,\n\t\tT const & x)\n\t{\n\t\tdetail::tmat3x3 Result();\n\t\tResult[1][0] = x;\n\t\treturn m * Result;\n\t}\n\n}\/\/namespace glm\n<|endoftext|>"} {"text":"\/* \n* Copyright 2013 Matthias Fuchs\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"stromx\/runtime\/test\/ServerTest.h\"\n\n#include \n\n#include \n#include \n\n#include \"stromx\/runtime\/OperatorTester.h\"\n#include \"stromx\/runtime\/Server.h\"\n\nCPPUNIT_TEST_SUITE_REGISTRATION (stromx::runtime::ServerTest);\n\nnamespace \n{\n}\n\nnamespace stromx\n{\n namespace runtime\n {\n namespace \n {\n void startServer(Operator* op)\n {\n DataContainer data(new UInt32(2));\n op->setInputData(Server::INPUT, data);\n }\n }\n \n void ServerTest::setUp()\n {\n m_operator = new OperatorTester(new Server());\n \n DataContainer data(new UInt32(1));\n m_operator->initialize();\n m_operator->activate();\n m_operator->setInputData(Server::INPUT, data);\n }\n\n void ServerTest::testTransmit()\n {\n boost::thread t(startServer, m_operator);\n boost::this_thread::sleep(boost::posix_time::microsec(300));\n \n using namespace boost::asio;\n \n io_service io_service;\n ip::tcp::resolver resolver(io_service);\n ip::tcp::resolver::query query(\"localhost\", \"49152\");\n ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n \n ip::tcp::socket socket(io_service);\n connect(socket, endpoint_iterator);\n \n boost::array buf;\n size_t len = socket.read_some(boost::asio::buffer(buf));\n t.join();\n \n CPPUNIT_ASSERT_EQUAL(size_t(38), len);\n }\n\n void ServerTest::tearDown()\n {\n delete m_operator;\n }\n }\n}\nSuppress server operator test\/* \n* Copyright 2013 Matthias Fuchs\n*\n* Licensed under the Apache License, Version 2.0 (the \"License\");\n* you may not use this file except in compliance with the License.\n* You may obtain a copy of the License at\n*\n* http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n*\n* Unless required by applicable law or agreed to in writing, software\n* distributed under the License is distributed on an \"AS IS\" BASIS,\n* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n* See the License for the specific language governing permissions and\n* limitations under the License.\n*\/\n\n#include \"stromx\/runtime\/test\/ServerTest.h\"\n\n#include \n\n#include \n#include \n\n#include \"stromx\/runtime\/OperatorTester.h\"\n#include \"stromx\/runtime\/Server.h\"\n\nCPPUNIT_TEST_SUITE_REGISTRATION (stromx::runtime::ServerTest);\n\nnamespace \n{\n}\n\nnamespace stromx\n{\n namespace runtime\n {\n namespace \n {\n void startServer(Operator* op)\n {\n DataContainer data(new UInt32(2));\n op->setInputData(Server::INPUT, data);\n }\n }\n \n void ServerTest::setUp()\n {\n m_operator = new OperatorTester(new Server());\n \n DataContainer data(new UInt32(1));\n m_operator->initialize();\n m_operator->activate();\n m_operator->setInputData(Server::INPUT, data);\n }\n\n void ServerTest::testTransmit()\n {\n boost::thread t(startServer, m_operator);\n boost::this_thread::sleep(boost::posix_time::microsec(300));\n \n using namespace boost::asio;\n \n io_service io_service;\n ip::tcp::resolver resolver(io_service);\n ip::tcp::resolver::query query(\"localhost\", \"49152\");\n ip::tcp::resolver::iterator endpoint_iterator = resolver.resolve(query);\n \n ip::tcp::socket socket(io_service);\n connect(socket, endpoint_iterator);\n \n boost::array buf;\n size_t len = socket.read_some(boost::asio::buffer(buf));\n t.join();\n \n\/\/ CPPUNIT_ASSERT_EQUAL(size_t(38), len);\n }\n\n void ServerTest::tearDown()\n {\n delete m_operator;\n }\n }\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n\n#include \n\nnamespace parser{\n\n \tclass Sign_{\n std::string name_;\n bool isTerm_;\n public:\n Sign_(std::string n, bool t){\n name_ = n;\n isTerm_ = t;\n }\n\t\tSign_(std::string n){\n\t\t\tname_ = n;\n\t\t isTerm_ = true;\t\n\t\t}\n\t\tSign_(){\n\t\t\tname_ =\"\";\n\t\t\tisTerm_ = true;\n\t\t}\n bool isTerm(){\n return isTerm_;\n }\n std::string name(){\n return name_;\n }\n\t\toperator std::string() const{\n \t\treturn name_;\n\t\t}\n\t};\n\n\t\n\tusing Sign = std::shared_ptr;\n \n\tclass Item{\n\t public:\n Sign left;\n std::vector rights;\n int pos;\n Item(Sign l, std::initializer_list const & r){\n\t\t\tpos = 0;\n left = l;\n rights.insert(rights.end(),r.begin(), r.end());\n }\n Sign nextSign(){\n \treturn rights[pos];\n }\n void next(){\n\t\t\tif(rights.size() > pos+1)\n \tpos++;\n }\n\t\tbool isLast(){\n\t\t\treturn pos == rights.size()-1;\n\t\t}\n\t\tfriend std::ostream& operator<<(std::ostream &out, const Item &i){\n\t\t\tout << std::string(*i.left) <<\" => \";\n\t\t\tif(i.pos == 0){\n\t\t\t\tout<< \" . \";\n\t\t\t}\n\t\t\tfor(int j=0;j rules;\n\n\tstd::vector getItems(Sign s){\n\t\t\/\/std::cout << std::string(*s) << std::endl;\n\t\tstd::vector res;\n\t\tfor(auto& i : rules){\n\t\t\tif(i.left->name() == s->name()){\n\t\t\t\tres.push_back(i);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n std::vector first(Sign sign){\n if(sign->isTerm()){\n return {sign};\n }\n std::vector res; \n\t\tauto items = getItems( sign );\n\t\tif(items.size() == 0)\n\t\t\treturn res;\n\n for(auto& i : items){\n\t\t\t\/\/std::cout << std::string( *i.left ) << \" \" << i.rights.size() <= 2){\n auto nxt = first(i.rights[1]);\n res.insert(res.end(), nxt.begin(), nxt.end());\n }else{\n res.push_back( Eps);\n }\n }else{\n \tres.insert(res.end(), ext.begin(), ext.end());\n\t\t\t}\n\t\t}\n return res;\n }\n\n std::vector first(std::initializer_list& l){\n if(l.size() == 0)\n return {Eps};\n\n std::vector res;\n \n auto it = l.begin();\n if(*it == Eps) return {Eps};\n if((*it)->isTerm()) return {*it};\n\n auto ext = first(*it); \n if(find(ext.begin(), ext.end(), Eps) != ext.end()){\n ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());\n res.insert(res.end(), ext.begin(), ext.end()); \n if(l.size() >= 2 ){\n it++;\n auto next = first(*it);\n res.insert(res.end(), next.begin(), next.end());\n }else{\n\t\t\t\tres.push_back(Eps);\n\t\t\t}\n }\n return ext;\n }\n\n std::vector follow(Sign& s){\n\t\tstd::cout<< std::string(*s) << std::endl;\n std::vector res;\n \n if(s == E){\n res.push_back(Fin);\n }\n\n for(auto rit = rules.cbegin(); rit != rules.cend(); ++rit){\n auto ls = rit->left; \n if(ls == s) continue;\n\n\t\t\tauto rs = rit->rights;\n for(size_t i = 1; i < rs.size(); i++){\n \tif(rs[i] == s){\n \tif(i + 1 < rs.size()){ \n \tauto ext = first(rs[i+1]);\n if(find(ext.begin(), ext.end(), Eps) != ext.end()){\n \t \tauto left = follow(ls);\n res.insert(res.end(), left.begin(), left.end());\n }\n ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());\n \tres.insert(res.end(), ext.begin(), ext.end());\n }else{\n auto left = follow(ls);\n res.insert(res.end(), left.begin(), left.end());\n }\n }\n }\n }\n return res;\n }\n\n\tvoid closure(std::vector& I){\n\t\tint size = I.size();\n\t\tstd::vector alreadys;\n\t\tdo{\n\t\t\tsize = I.size();\n\t\t\tstd::cout<<\"LOOP\\n\";\n\t\t\tfor(auto i : I){\n\t\t\t\t\/\/std::cout<< i << std::endl;\n\t\t\t\tauto X = getItems( i.nextSign() );\n\n\t\t\t\tstd::cout<< \"SIZE:\"< Goto(std::vector I,Sign X){\n\t\tstd::vector J;\n\t\t\/*\n\t\tstd::cout << \"Goto argv b--------\\n\";\n\t\tfor(auto i : I) std::cout<< i;\n\t\tstd::cout<< std::string(*X)<> T;\n\t\tstd::vector> Tt;\n\t\tstd::vector f({ Item( mS(\"S\"),{ E, Fin}) });\n\t\tclosure(f);\n\t\tT.push_back(f);\n\t\tint size = T.size();\n\t\tint count = 0;\n\t\tstd::cout<< f[0];\n\t\tstd::cout<<\"++++++++++++++++\\n\";\n\t\tTt = T;\n\t\tstd::vector alreadys;\n\t\twhile( count < 5){\n\t\t\tcount++;\n\t\t\tfor(auto t : T){\n\t\t\t\tfor(auto i : t){\n\t\t\t\t\tstd::cout<< \"i loop start\\n\"<< i;\n\t\t\t\t\tif(find(alreadys.begin(), alreadys.end(), i.nextSign()) != alreadys.end())\n\t\t\t\t\t\tcontinue;\n\t\t\t\t\talreadys.push_back(i.nextSign());\n\t\t\t\t\tauto J = Goto( t, i.nextSign());\n\t\t\t\t\tstd::cout << \"***************************\\n\";\n\t\t\t\t\tstd::cout << \"I:\"<< std::string(*i.nextSign()) << std::endl;\n\t\t\t\t\tfor(auto j : J)\n\t\t\t\t\t\tstd::cout << j;\n\t\t\t\t\tstd::cout << \"***************************\\n\";\n\t\t\t\t\tT.push_back(J);\n\t\t\t\t\tstd::cout<<\"i loop end\\n\";\n\t\t\t\t}\n\t\t\t\tstd::cout<<\"t loop end\\n\";\n\t\t\t}\n\t\t\tstd::cout<< size << \" \" << T.size() << std::endl; \n\t\t\tif( size != T.size()){\n\t\t\t\tsize = T.size();\n\t\t\t}else{\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t\tstd::cout<<\"####################\\n\";\n\t\tfor(auto t : T){\n\t\t\tstd::cout<<\"~~~~~~~~~~~~~~~\\n\";\n\t\t\tfor(auto i : t){\n\t\t\t\tstd::cout<< i;\n\t\t\t}\n\t\t}\n\t}\n\tvoid setup(){\n\n rules.push_back(Item( E,\n { T, Eq }\n ));\n\n rules.push_back(Item( Eq,\n {mtS(\"+\"), T, Eq }\n ));\n rules.push_back(Item( Eq,\n { Eps }\n ));\n \n\t\trules.push_back(Item( T,\n { F, Tq}\n ));\n \n\t\trules.push_back(Item( Tq,\n { mtS(\"*\"), F, Tq }\n ));\n rules.push_back(Item( Tq,\n { Eps }\n ));\n\n rules.push_back(Item( F,\n { mtS(\"(\"), E, mtS(\")\")}\n ));\n rules.push_back(Item( F,\n { mtS(\"i\")}\n\t\t));\n } \n\n\tusing namespace std;\n \n void test(Sign S){\n std::cout << \"==== \"< items = { Item( mS(\"S\"), { E, Fin}) };\n closure(items);\n\t\tstd::cout<<\"~~~~~~~~~~~~~~~\\n\";\n for(auto i : items)\n\t\t\tstd::cout << i;\n\t\t*\/\n\t\tDFA();\n\t\n \/\/delete items;\n \n \/\/create_dfa();\n \/\/for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){\n \/\/ if(rit->second)\n \/\/ rit->second.reset();\n \/\/}\n }\n}\n\n\nint main(){\n parser::parser();\n return 0;\n}\n\/*\n * ==== T ===\n * (\n * i\n * ===\n * FIN\n * )\n * +\n * ==== Tq ===\n * *\n * Epsilon\n * ===\n * FIN\n * )\n * +\n * ==== F ===\n * (\n * i\n * ===\n * FIN\n * )\n * +\n * *\n * ===\n *\/\n\n[WIP] LR v0.0.1#include \n#include \n#include \n#include \n#include \n#include \n\n\n#include \n\n#include \n\nnamespace parser{\n\n\tusing namespace std;\n\n \tstruct Sign{\n\n std::string name;\n bool isTerm;\n\n Sign(std::string n, bool t):\n\t name(move(n)),\n\t isTerm(move(t))\n {}\n\n\t\tSign(std::string n):\n\t\t\tname(move(n)),\n\t\t isTerm(true)\n\t {}\n\n\t\tSign():\n\t\t\tname(\"\"),\n\t\t\tisTerm(true)\n\t\t{}\n\n\t\toperator std::string() const{\n \t\treturn name;\n\t\t}\n \n\t\tbool operator==(const Sign& rhs) const{\n\t\t\treturn name == rhs.name;\n\t\t};\n\t\n\t\tinline bool operator!=(const Sign& rhs) const{\n\t\t\treturn !(*this == rhs);\n\t\t}\n\t};\n\n class HashSign {\n\t\tpublic:\n\t size_t operator()(const Sign& s) const {\n\t const int C = 9873967;\n\t size_t t = 0;\n\t for(int i = 0; i != s.name.size(); ++i) {\n\t t = t * C + (char)s.name[i];\n\t }\n\t return t;\n\t }\n\t};\n\n\tstruct Item{\n Sign left;\n std::vector rights;\n int pos;\n\n Item(Sign l, vector r):\n pos(0),\n left(move(l)),\n rights(move(r))\n {}\n\n Sign nextSign(){\n \tif(isLast())\n \t\treturn Sign();\n \treturn rights.at(pos);\n }\n\n void next(){\n \tpos++;\n }\n\n\t\tbool isLast(){\n\t\t\treturn pos == rights.size();\n\t\t}\n\n\t\tfriend std::ostream& operator<<(std::ostream &out, const Item &i){\n\t\t\tout << std::string(i.left) <<\" => \";\n\n\t\t\tif(i.pos == 0){\n\t\t\t\tout<< \" . \";\n\t\t\t}\n\t\t\tfor(int j=0;j items;\n\t\tunordered_map transitions;\n\t\tState():\n\t\t\tid(-1)\n\t\t{}\n\n\t\tState(int id):\n\t\t\tid(id)\n\t\t{}\n\n\t\tvoid append(vector newItems){\n\t\t\titems.insert(items.end(), move(newItems).begin(), move(newItems).end());\n\t\t}\n\n\t\tfriend std::ostream& operator<<(std::ostream &out, const State &s){\n\t\t\tout <<\"- Q\"<< std::to_string(s.id) <<\" -\\n\";\n\t\t\tfor(auto item : s.items){\n\t\t\t\tcout <<\" \"<< item;\n\t\t\t}\n\t\t\tout << \"\\n\";\n\t\t\treturn out;\n\t\t}\n\t};\n\n\tSign mS(std::string name){\n\t\treturn Sign(name,false);\n\t}\n\tSign mtS(std::string name){\n\t\treturn Sign(name);\n\t}\n\n auto E = mS(\"E\");\n auto Eq = mS(\"Eq\");\n auto T = mS(\"T\");\n auto Tq = mS(\"Tq\");\n auto F = mS(\"F\");\n\n\tauto Eps = mtS(\"Epsilon\");\n\tauto Fin = mtS(\"Fin\");\n\n\tstd::vector grammar;\n\n\tstd::vector getItems(Sign s){\n\t\tstd::vector res;\n\t\tfor(auto& i : grammar){\n\t\t\tif(i.left.name == s.name){\n\t\t\t\tres.push_back(i);\n\t\t\t}\n\t\t}\n\t\treturn res;\n\t}\n\n std::vector first(Sign sign){\n if(sign.isTerm){\n return {sign};\n }\n std::vector res; \n\t\tauto items = getItems( sign );\n\t\tif(items.size() == 0)\n\t\t\treturn res;\n\n for(auto& i : items){\n \tauto ext = first(i.rights[0]);\n if(find(ext.begin(), ext.end(), Eps) != ext.end()){\n\t\t\t\text.erase(remove(ext.begin(), ext.end(), Eps), ext.end());\n \tres.insert(res.end(), ext.begin(), ext.end());\n if(i.rights.size() >= 2){\n auto nxt = first(i.rights[1]);\n res.insert(res.end(), nxt.begin(), nxt.end());\n }else{\n res.push_back( Eps);\n }\n }else{\n \tres.insert(res.end(), ext.begin(), ext.end());\n\t\t\t}\n\t\t}\n return res;\n }\n\n std::vector first(vector& l){\n if(l.size() == 0)\n return {Eps};\n\n std::vector res;\n \n auto it = l.begin();\n if(*it == Eps) return {Eps};\n if((*it).isTerm) return {*it};\n\n auto ext = first(*it); \n if(find(ext.begin(), ext.end(), Eps) != ext.end()){\n ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());\n res.insert(res.end(), ext.begin(), ext.end()); \n if(l.size() >= 2 ){\n it++;\n auto next = first(*it);\n res.insert(res.end(), next.begin(), next.end());\n }else{\n\t\t\t\tres.push_back(Eps);\n\t\t\t}\n }\n return ext;\n }\n\n std::vector follow(Sign s){\n std::vector res;\n \n if(s == E){\n res.push_back(Fin);\n }\n\n for(auto rit = grammar.cbegin(); rit != grammar.cend(); ++rit){\n auto ls = (*rit).left; \n if(ls == s) continue;\n\n\t\t\tauto rs = (*rit).rights;\n for(size_t i = 1; i < rs.size(); i++){\n \tif(rs[i] == s){\n \tif(i + 1 < rs.size()){ \n \tauto ext = first(rs[i+1]);\n if(find(ext.begin(), ext.end(), Eps) != ext.end()){\n \t \tauto left = follow(ls);\n res.insert(res.end(), left.begin(), left.end());\n }\n ext.erase(remove(ext.begin(), ext.end(), Eps), ext.end());\n \tres.insert(res.end(), ext.begin(), ext.end());\n }else{\n auto left = follow(ls);\n res.insert(res.end(), left.begin(), left.end());\n }\n }\n }\n }\n return res;\n }\n\n unordered_map, HashSign> follows;\n\tvector> DFAutomaton;\n\t\n\tvoid generateDFAutomaton(int st){\n\t\tcout<< \"generateDFAutomaton(\"< newStateNumbers;\n\t\tauto state = DFAutomaton.at(st);\n\n\t\tfor(auto item : state->items){\n\t\t\tif(!item.isLast()){\n\t\t\t\tauto first = item.nextSign();\n\n\t\t\t\tif(!first.isTerm){\n\t\t\t\t\tstate->append(getItems(first));\n\t\t\t\t}\n\n\t\t\t\tif(state->transitions.find(first) == state->transitions.end()){\n\t\t\t\t\tDFAutomaton.push_back(make_shared(st+1));\n\t\t\t\t\tstate->transitions[first] = DFAutomaton.size() - 1;\n\t\t\t\t\tnewStateNumbers.push_back(DFAutomaton.size() - 1);\n\t\t\t\t}\n\t\t\t\titem.next();\n\t\t\t\tDFAutomaton.at(DFAutomaton.size() - 1)->append({item});\n\t\t\t}\n\t\t}\n\n\t\tcout << DFAutomaton.at(DFAutomaton.size() - 1)->items.size() << \" \" <(0);\n\t\tQ0->append(getItems(E));\n\t\tDFAutomaton.push_back(Q0);\n\n\t\tgenerateDFAutomaton(0);\n\n\t\tfor(int i=0;i items = { Item( mS(\"S\"), { E, Fin}) };\n closure(items);\n\t\tstd::cout<<\"~~~~~~~~~~~~~~~\\n\";\n for(auto i : items)\n\t\t\tstd::cout << i;\n\t\n \/\/delete items;\n \n \/\/create_dfa();\n \/\/for(auto rit = rule_table.begin(); rit != rule_table.end(); ++rit){\n \/\/ if(rit.second)\n \/\/ rit.second.reset();\n \/\/}\n*\/ \n }\n}\n\n\nint main(){\n parser::parser();\n return 0;\n}\n\/*\n * ==== T ===\n * (\n * i\n * ===\n * FIN\n * )\n * +\n * ==== Tq ===\n * *\n * Epsilon\n * ===\n * FIN\n * )\n * +\n * ==== F ===\n * (\n * i\n * ===\n * FIN\n * )\n * +\n * *\n * ===\n *\/\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \"sass_context.h\"\n#include \"emscripten_wrapper.hpp\"\n\nchar *sass_compile_emscripten(\n char *source_string,\n int output_style,\n int precision,\n bool source_comments,\n bool is_indented_syntax_src,\n bool source_map_contents,\n bool source_map_embed,\n bool omit_source_map_url,\n char *source_map_root,\n char *source_map_file,\n char *input_path,\n char *output_path,\n char *indent,\n char *linefeed,\n char *include_paths,\n char **source_map_string,\n char **included_files,\n char **error_message,\n char **error_json\n) {\n char *output_string;\n\n \/\/ I suck at C and I'm probably doing this way wrong\n Sass_Output_Style sass_output_style;\n switch (output_style) {\n case 3:\n sass_output_style = SASS_STYLE_COMPRESSED;\n break;\n\n case 2:\n sass_output_style = SASS_STYLE_COMPACT;\n break;\n\n case 1:\n sass_output_style = SASS_STYLE_EXPANDED;\n break;\n\n case 0:\n default:\n sass_output_style = SASS_STYLE_NESTED;\n break;\n }\n\n \/\/ initialize context\n struct Sass_Data_Context* data_ctx = sass_make_data_context(strdup(source_string));\n struct Sass_Context* ctx = sass_data_context_get_context(data_ctx);\n struct Sass_Options* ctx_opt = sass_context_get_options(ctx);\n\n \/\/ configure context\n sass_option_set_precision(ctx_opt, precision);\n sass_option_set_output_style(ctx_opt, sass_output_style);\n sass_option_set_source_comments(ctx_opt, source_comments);\n sass_option_set_source_map_embed(ctx_opt, source_map_embed);\n sass_option_set_source_map_contents(ctx_opt, source_map_contents);\n sass_option_set_omit_source_map_url(ctx_opt, omit_source_map_url);\n sass_option_set_is_indented_syntax_src(ctx_opt, is_indented_syntax_src);\n sass_option_set_indent(ctx_opt, indent);\n sass_option_set_linefeed(ctx_opt, linefeed);\n sass_option_set_input_path(ctx_opt, input_path);\n sass_option_set_output_path(ctx_opt, output_path);\n \/\/ void sass_option_set_plugin_path (struct Sass_Options* options, const char* plugin_path);\n sass_option_set_include_path(ctx_opt, include_paths);\n sass_option_set_source_map_file(ctx_opt, source_map_file);\n sass_option_set_source_map_root(ctx_opt, source_map_root);\n \/\/ void sass_option_set_c_functions (struct Sass_Options* options, Sass_C_Function_List c_functions);\n \/\/ void sass_option_set_importer (struct Sass_Options* options, Sass_C_Import_Callback importer);\n\n \/\/ compile\n int status = sass_compile_data_context(data_ctx);\n\n \/\/ extract results\n *included_files = NULL;\n *source_map_string = NULL;\n *error_message = NULL;\n *error_json = NULL;\n if (status == 0) {\n \/\/ NOTE: taking memory ownership causes the thing to explode on second iteration\n \/\/output_string = sass_context_take_output_string(ctx);\n output_string = strdup(sass_context_get_output_string(ctx));\n\n \/\/*source_map_string = sass_context_take_source_map_string(ctx);\n const char* _source_map_string = sass_context_get_source_map_string(ctx);\n if (_source_map_string) {\n *source_map_string = strdup(_source_map_string);\n }\n\n \/\/ TODO: figure out how C-string-arrays work\n char** _included_files = sass_context_get_included_files(ctx);\n if (_included_files && *_included_files) {\n *included_files = strdup(*_included_files);\n }\n } else {\n output_string = NULL;\n \/\/*error_message = sass_context_take_error_message(ctx);\n *error_message = strdup(sass_context_get_error_message(ctx));\n \/\/*error_json = sass_context_take_error_json(ctx);\n *error_json = strdup(sass_context_get_error_json(ctx));\n }\n\n \/\/ clean up\n sass_delete_data_context(data_ctx);\n\n return output_string;\n}\n\nfeature(libsass): yes, a typecast beats a switch, moron!#include \n#include \n#include \"sass_context.h\"\n#include \"emscripten_wrapper.hpp\"\n\nchar *sass_compile_emscripten(\n char *source_string,\n int output_style,\n int precision,\n bool source_comments,\n bool is_indented_syntax_src,\n bool source_map_contents,\n bool source_map_embed,\n bool omit_source_map_url,\n char *source_map_root,\n char *source_map_file,\n char *input_path,\n char *output_path,\n char *indent,\n char *linefeed,\n char *include_paths,\n char **source_map_string,\n char **included_files,\n char **error_message,\n char **error_json\n) {\n char *output_string;\n\n Sass_Output_Style sass_output_style = (Sass_Output_Style)output_style;\n\n \/\/ initialize context\n struct Sass_Data_Context* data_ctx = sass_make_data_context(strdup(source_string));\n struct Sass_Context* ctx = sass_data_context_get_context(data_ctx);\n struct Sass_Options* ctx_opt = sass_context_get_options(ctx);\n\n \/\/ configure context\n sass_option_set_precision(ctx_opt, precision);\n sass_option_set_output_style(ctx_opt, sass_output_style);\n sass_option_set_source_comments(ctx_opt, source_comments);\n sass_option_set_source_map_embed(ctx_opt, source_map_embed);\n sass_option_set_source_map_contents(ctx_opt, source_map_contents);\n sass_option_set_omit_source_map_url(ctx_opt, omit_source_map_url);\n sass_option_set_is_indented_syntax_src(ctx_opt, is_indented_syntax_src);\n sass_option_set_indent(ctx_opt, indent);\n sass_option_set_linefeed(ctx_opt, linefeed);\n sass_option_set_input_path(ctx_opt, input_path);\n sass_option_set_output_path(ctx_opt, output_path);\n \/\/ void sass_option_set_plugin_path (struct Sass_Options* options, const char* plugin_path);\n sass_option_set_include_path(ctx_opt, include_paths);\n sass_option_set_source_map_file(ctx_opt, source_map_file);\n sass_option_set_source_map_root(ctx_opt, source_map_root);\n \/\/ void sass_option_set_c_functions (struct Sass_Options* options, Sass_C_Function_List c_functions);\n \/\/ void sass_option_set_importer (struct Sass_Options* options, Sass_C_Import_Callback importer);\n\n \/\/ compile\n int status = sass_compile_data_context(data_ctx);\n\n \/\/ extract results\n *included_files = NULL;\n *source_map_string = NULL;\n *error_message = NULL;\n *error_json = NULL;\n if (status == 0) {\n \/\/ NOTE: taking memory ownership causes the thing to explode on second iteration\n \/\/output_string = sass_context_take_output_string(ctx);\n output_string = strdup(sass_context_get_output_string(ctx));\n\n \/\/*source_map_string = sass_context_take_source_map_string(ctx);\n const char* _source_map_string = sass_context_get_source_map_string(ctx);\n if (_source_map_string) {\n *source_map_string = strdup(_source_map_string);\n }\n\n \/\/ TODO: figure out how C-string-arrays work\n char** _included_files = sass_context_get_included_files(ctx);\n if (_included_files && *_included_files) {\n *included_files = strdup(*_included_files);\n }\n } else {\n output_string = NULL;\n \/\/*error_message = sass_context_take_error_message(ctx);\n *error_message = strdup(sass_context_get_error_message(ctx));\n \/\/*error_json = sass_context_take_error_json(ctx);\n *error_json = strdup(sass_context_get_error_json(ctx));\n }\n\n \/\/ clean up\n sass_delete_data_context(data_ctx);\n\n return output_string;\n}\n\n<|endoftext|>"} {"text":"\/\/ @(#)root\/eve:$Id$\n\/\/ Author: Matevz Tadel 2007\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TEveGeoShape.h\"\n#include \"TEveTrans.h\"\n#include \"TEveManager.h\"\n#include \"TEvePolygonSetProjected.h\"\n\n#include \"TEveGeoShapeExtract.h\"\n#include \"TEvePad.h\"\n#include \"TEveGeoPolyShape.h\"\n#include \"TGLScenePad.h\"\n#include \"TGLFaceSet.h\"\n\n#include \"TROOT.h\"\n#include \"TPad.h\"\n#include \"TBuffer3D.h\"\n#include \"TVirtualViewer3D.h\"\n#include \"TColor.h\"\n#include \"TFile.h\"\n\n#include \"TGeoShape.h\"\n#include \"TGeoVolume.h\"\n#include \"TGeoNode.h\"\n#include \"TGeoShapeAssembly.h\"\n#include \"TGeoCompositeShape.h\"\n#include \"TGeoManager.h\"\n#include \"TGeoMatrix.h\"\n#include \"TVirtualGeoPainter.h\"\n\nnamespace\n{\nTGeoManager* init_geo_mangeur()\n{\n \/\/ Create a phony geo manager that can be used for storing free\n \/\/ shapes. Otherwise shapes register themselves to current\n \/\/ geo-manager (or even create one).\n\n TGeoManager* old = gGeoManager;\n gGeoManager = 0;\n TGeoManager* mgr = new TGeoManager();\n mgr->SetNameTitle(\"TEveGeoShape::fgGeoMangeur\",\n \"Static geo manager used for wrapped TGeoShapes.\");\n gGeoManager = old;\n return mgr;\n}\n}\n\n\/\/==============================================================================\n\/\/==============================================================================\n\/\/ TEveGeoShape\n\/\/==============================================================================\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ Wrapper for TGeoShape with absolute positioning and color\n\/\/ attributes allowing display of extracted TGeoShape's (without an\n\/\/ active TGeoManager) and simplified geometries (needed for NLT\n\/\/ projections).\n\/\/\n\/\/ TGeoCompositeShapes and TGeoAssemblies are supported.\n\nClassImp(TEveGeoShape);\n\nTGeoManager* TEveGeoShape::fgGeoMangeur = init_geo_mangeur();\n\n\/\/______________________________________________________________________________\nTGeoManager* TEveGeoShape::GetGeoMangeur()\n{\n \/\/ Return static geo-manager that is used intenally to make shapes\n \/\/ lead a happy life.\n \/\/ Set gGeoManager to this object when creating TGeoShapes to be\n \/\/ passed into TEveGeoShapes.\n\n return fgGeoMangeur;\n}\n\n\/\/______________________________________________________________________________\nTEveGeoShape::TEveGeoShape(const char* name, const char* title) :\n TEveElement (fColor),\n TNamed (name, title),\n fColor (0),\n fNSegments (0),\n fShape (0)\n{\n \/\/ Constructor.\n\n InitMainTrans();\n}\n\n\/\/______________________________________________________________________________\nTEveGeoShape::~TEveGeoShape()\n{\n \/\/ Destructor.\n\n SetShape(0);\n}\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::SetShape(TGeoShape* s)\n{\n \/\/ Set TGeoShape shown by this object.\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur);\n\n if (fShape) {\n fShape->SetUniqueID(fShape->GetUniqueID() - 1);\n if (fShape->GetUniqueID() == 0)\n delete fShape;\n }\n fShape = s;\n if (fShape) {\n fShape->SetUniqueID(fShape->GetUniqueID() + 1);\n }\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::Paint(Option_t* \/*option*\/)\n{\n \/\/ Paint object.\n\n static const TEveException eh(\"TEveGeoShape::Paint \");\n\n if (fShape == 0)\n return;\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur, fNSegments);\n\n TBuffer3D& buff = (TBuffer3D&) fShape->GetBuffer3D\n (TBuffer3D::kCore, kFALSE);\n\n buff.fID = this;\n buff.fColor = GetMainColor();\n buff.fTransparency = GetMainTransparency();\n RefMainTrans().SetBuffer3D(buff);\n buff.fLocalFrame = kTRUE; \/\/ Always enforce local frame (no geo manager).\n\n Int_t sections = TBuffer3D::kBoundingBox | TBuffer3D::kShapeSpecific;\n if (fNSegments > 2)\n sections |= TBuffer3D::kRawSizes | TBuffer3D::kRaw;\n fShape->GetBuffer3D(sections, kTRUE);\n\n Int_t reqSec = gPad->GetViewer3D()->AddObject(buff);\n\n if (reqSec != TBuffer3D::kNone) {\n \/\/ This shouldn't happen, but I suspect it does sometimes.\n if (reqSec & TBuffer3D::kCore)\n Warning(eh, \"Core section required again for shape='%s'. This shouldn't happen.\", GetName());\n fShape->GetBuffer3D(reqSec, kTRUE);\n reqSec = gPad->GetViewer3D()->AddObject(buff);\n }\n\n if (reqSec != TBuffer3D::kNone)\n Warning(eh, \"Extra section required: reqSec=%d, shape=%s.\", reqSec, GetName());\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::Save(const char* file, const char* name)\n{\n \/\/ Save the shape tree as TEveGeoShapeExtract.\n \/\/ File is always recreated.\n \/\/ This function is obsolete, use SaveExtractInstead().\n\n Warning(\"Save()\", \"This function is deprecated, use SaveExtract() instead.\");\n SaveExtract(file, name);\n}\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::SaveExtract(const char* file, const char* name)\n{\n \/\/ Save the shape tree as TEveGeoShapeExtract.\n \/\/ File is always recreated.\n\n TEveGeoShapeExtract* gse = DumpShapeTree(this, 0);\n\n TFile f(file, \"RECREATE\");\n gse->Write(name);\n f.Close();\n}\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::WriteExtract(const char* name)\n{\n \/\/ Write the shape tree as TEveGeoShapeExtract to current directory.\n\n TEveGeoShapeExtract* gse = DumpShapeTree(this, 0);\n gse->Write(name);\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nTEveGeoShapeExtract* TEveGeoShape::DumpShapeTree(TEveGeoShape* gsre,\n TEveGeoShapeExtract* parent)\n{\n \/\/ Export this shape and its descendants into a geoshape-extract.\n\n TEveGeoShapeExtract* she = new TEveGeoShapeExtract(gsre->GetName(), gsre->GetTitle());\n she->SetTrans(gsre->RefMainTrans().Array());\n Int_t ci = gsre->GetColor();\n TColor* c = gROOT->GetColor(ci);\n Float_t rgba[4] = {1, 0, 0, 1 - gsre->GetMainTransparency()\/100.};\n if (c)\n {\n rgba[0] = c->GetRed();\n rgba[1] = c->GetGreen();\n rgba[2] = c->GetBlue();\n }\n she->SetRGBA(rgba);\n she->SetRnrSelf(gsre->GetRnrSelf());\n she->SetRnrElements(gsre->GetRnrChildren());\n she->SetShape(gsre->GetShape());\n if (gsre->HasChildren())\n {\n TList* ele = new TList();\n she->SetElements(ele);\n she->GetElements()->SetOwner(true);\n TEveElement::List_i i = gsre->BeginChildren();\n while (i != gsre->EndChildren()) {\n TEveGeoShape* l = dynamic_cast(*i);\n DumpShapeTree(l, she);\n i++;\n }\n }\n if (parent)\n parent->GetElements()->Add(she);\n\n return she;\n}\n\n\/\/______________________________________________________________________________\nTEveGeoShape* TEveGeoShape::ImportShapeExtract(TEveGeoShapeExtract* gse,\n TEveElement* parent)\n{\n \/\/ Import a shape extract 'gse' under element 'parent'.\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur);\n TEveManager::TRedrawDisabler redrawOff(gEve);\n TEveGeoShape* gsre = SubImportShapeExtract(gse, parent);\n gsre->ElementChanged();\n return gsre;\n}\n\n\n\/\/______________________________________________________________________________\nTEveGeoShape* TEveGeoShape::SubImportShapeExtract(TEveGeoShapeExtract* gse,\n TEveElement* parent)\n{\n \/\/ Recursive version for importing a shape extract tree.\n\n TEveGeoShape* gsre = new TEveGeoShape(gse->GetName(), gse->GetTitle());\n gsre->RefMainTrans().SetFromArray(gse->GetTrans());\n const Float_t* rgba = gse->GetRGBA();\n gsre->SetMainColorRGB(rgba[0], rgba[1], rgba[2]);\n gsre->SetMainAlpha(rgba[3]);\n gsre->SetRnrSelf(gse->GetRnrSelf());\n gsre->SetRnrChildren(gse->GetRnrElements());\n gsre->SetShape(gse->GetShape());\n\n if (parent)\n parent->AddElement(gsre);\n\n if (gse->HasElements())\n {\n TIter next(gse->GetElements());\n TEveGeoShapeExtract* chld;\n while ((chld = (TEveGeoShapeExtract*) next()) != 0)\n SubImportShapeExtract(chld, gsre);\n }\n\n return gsre;\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nTClass* TEveGeoShape::ProjectedClass() const\n{\n \/\/ Return class for projected objects, TEvePolygonSetProjected.\n \/\/ Virtual from TEveProjectable.\n\n return TEvePolygonSetProjected::Class();\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nTBuffer3D* TEveGeoShape::MakeBuffer3D()\n{\n \/\/ Create a TBuffer3D suitable for presentation of the shape.\n \/\/ Transformation matrix is also applied.\n\n if (fShape == 0) return 0;\n\n if (dynamic_cast(fShape)) {\n \/\/ !!!! TGeoShapeAssembly makes a bad TBuffer3D\n return 0;\n }\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur, fNSegments);\n\n TBuffer3D* buff = fShape->MakeBuffer3D();\n TEveTrans& mx = RefMainTrans();\n if (mx.GetUseTrans())\n {\n Int_t n = buff->NbPnts();\n Double_t* pnts = buff->fPnts;\n for(Int_t k = 0; k < n; ++k)\n {\n mx.MultiplyIP(&pnts[3*k]);\n }\n }\n return buff;\n}\nExtend class docs.\/\/ @(#)root\/eve:$Id$\n\/\/ Author: Matevz Tadel 2007\n\n\/*************************************************************************\n * Copyright (C) 1995-2007, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TEveGeoShape.h\"\n#include \"TEveTrans.h\"\n#include \"TEveManager.h\"\n#include \"TEvePolygonSetProjected.h\"\n\n#include \"TEveGeoShapeExtract.h\"\n#include \"TEvePad.h\"\n#include \"TEveGeoPolyShape.h\"\n#include \"TGLScenePad.h\"\n#include \"TGLFaceSet.h\"\n\n#include \"TROOT.h\"\n#include \"TPad.h\"\n#include \"TBuffer3D.h\"\n#include \"TVirtualViewer3D.h\"\n#include \"TColor.h\"\n#include \"TFile.h\"\n\n#include \"TGeoShape.h\"\n#include \"TGeoVolume.h\"\n#include \"TGeoNode.h\"\n#include \"TGeoShapeAssembly.h\"\n#include \"TGeoCompositeShape.h\"\n#include \"TGeoManager.h\"\n#include \"TGeoMatrix.h\"\n#include \"TVirtualGeoPainter.h\"\n\nnamespace\n{\nTGeoManager* init_geo_mangeur()\n{\n \/\/ Create a phony geo manager that can be used for storing free\n \/\/ shapes. Otherwise shapes register themselves to current\n \/\/ geo-manager (or even create one).\n\n TGeoManager* old = gGeoManager;\n gGeoManager = 0;\n TGeoManager* mgr = new TGeoManager();\n mgr->SetNameTitle(\"TEveGeoShape::fgGeoMangeur\",\n \"Static geo manager used for wrapped TGeoShapes.\");\n gGeoManager = old;\n return mgr;\n}\n}\n\n\/\/==============================================================================\n\/\/==============================================================================\n\/\/ TEveGeoShape\n\/\/==============================================================================\n\n\/\/______________________________________________________________________________\n\/\/\n\/\/ Wrapper for TGeoShape with absolute positioning and color\n\/\/ attributes allowing display of extracted TGeoShape's (without an\n\/\/ active TGeoManager) and simplified geometries (needed for non-linear\n\/\/ projections).\n\/\/\n\/\/ TGeoCompositeShapes and TGeoAssemblies are supported.\n\/\/\n\/\/ If fNSegments data-member is < 2 (0 by default), the default number of\n\/\/ segments is used for tesselation and special GL objects are\n\/\/ instantiated for selected shapes (spheres, tubes). If fNSegments is > 2,\n\/\/ it gets forwarded to geo-manager and this tesselation detail is\n\/\/ used when creating the buffer passed to GL.\n\nClassImp(TEveGeoShape);\n\nTGeoManager* TEveGeoShape::fgGeoMangeur = init_geo_mangeur();\n\n\/\/______________________________________________________________________________\nTGeoManager* TEveGeoShape::GetGeoMangeur()\n{\n \/\/ Return static geo-manager that is used intenally to make shapes\n \/\/ lead a happy life.\n \/\/ Set gGeoManager to this object when creating TGeoShapes to be\n \/\/ passed into TEveGeoShapes.\n\n return fgGeoMangeur;\n}\n\n\/\/______________________________________________________________________________\nTEveGeoShape::TEveGeoShape(const char* name, const char* title) :\n TEveElement (fColor),\n TNamed (name, title),\n fColor (0),\n fNSegments (0),\n fShape (0)\n{\n \/\/ Constructor.\n\n InitMainTrans();\n}\n\n\/\/______________________________________________________________________________\nTEveGeoShape::~TEveGeoShape()\n{\n \/\/ Destructor.\n\n SetShape(0);\n}\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::SetShape(TGeoShape* s)\n{\n \/\/ Set TGeoShape shown by this object.\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur);\n\n if (fShape) {\n fShape->SetUniqueID(fShape->GetUniqueID() - 1);\n if (fShape->GetUniqueID() == 0)\n delete fShape;\n }\n fShape = s;\n if (fShape) {\n fShape->SetUniqueID(fShape->GetUniqueID() + 1);\n }\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::Paint(Option_t* \/*option*\/)\n{\n \/\/ Paint object.\n\n static const TEveException eh(\"TEveGeoShape::Paint \");\n\n if (fShape == 0)\n return;\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur, fNSegments);\n\n TBuffer3D& buff = (TBuffer3D&) fShape->GetBuffer3D\n (TBuffer3D::kCore, kFALSE);\n\n buff.fID = this;\n buff.fColor = GetMainColor();\n buff.fTransparency = GetMainTransparency();\n RefMainTrans().SetBuffer3D(buff);\n buff.fLocalFrame = kTRUE; \/\/ Always enforce local frame (no geo manager).\n\n Int_t sections = TBuffer3D::kBoundingBox | TBuffer3D::kShapeSpecific;\n if (fNSegments > 2)\n sections |= TBuffer3D::kRawSizes | TBuffer3D::kRaw;\n fShape->GetBuffer3D(sections, kTRUE);\n\n Int_t reqSec = gPad->GetViewer3D()->AddObject(buff);\n\n if (reqSec != TBuffer3D::kNone) {\n \/\/ This shouldn't happen, but I suspect it does sometimes.\n if (reqSec & TBuffer3D::kCore)\n Warning(eh, \"Core section required again for shape='%s'. This shouldn't happen.\", GetName());\n fShape->GetBuffer3D(reqSec, kTRUE);\n reqSec = gPad->GetViewer3D()->AddObject(buff);\n }\n\n if (reqSec != TBuffer3D::kNone)\n Warning(eh, \"Extra section required: reqSec=%d, shape=%s.\", reqSec, GetName());\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::Save(const char* file, const char* name)\n{\n \/\/ Save the shape tree as TEveGeoShapeExtract.\n \/\/ File is always recreated.\n \/\/ This function is obsolete, use SaveExtractInstead().\n\n Warning(\"Save()\", \"This function is deprecated, use SaveExtract() instead.\");\n SaveExtract(file, name);\n}\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::SaveExtract(const char* file, const char* name)\n{\n \/\/ Save the shape tree as TEveGeoShapeExtract.\n \/\/ File is always recreated.\n\n TEveGeoShapeExtract* gse = DumpShapeTree(this, 0);\n\n TFile f(file, \"RECREATE\");\n gse->Write(name);\n f.Close();\n}\n\n\/\/______________________________________________________________________________\nvoid TEveGeoShape::WriteExtract(const char* name)\n{\n \/\/ Write the shape tree as TEveGeoShapeExtract to current directory.\n\n TEveGeoShapeExtract* gse = DumpShapeTree(this, 0);\n gse->Write(name);\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nTEveGeoShapeExtract* TEveGeoShape::DumpShapeTree(TEveGeoShape* gsre,\n TEveGeoShapeExtract* parent)\n{\n \/\/ Export this shape and its descendants into a geoshape-extract.\n\n TEveGeoShapeExtract* she = new TEveGeoShapeExtract(gsre->GetName(), gsre->GetTitle());\n she->SetTrans(gsre->RefMainTrans().Array());\n Int_t ci = gsre->GetColor();\n TColor* c = gROOT->GetColor(ci);\n Float_t rgba[4] = {1, 0, 0, 1 - gsre->GetMainTransparency()\/100.};\n if (c)\n {\n rgba[0] = c->GetRed();\n rgba[1] = c->GetGreen();\n rgba[2] = c->GetBlue();\n }\n she->SetRGBA(rgba);\n she->SetRnrSelf(gsre->GetRnrSelf());\n she->SetRnrElements(gsre->GetRnrChildren());\n she->SetShape(gsre->GetShape());\n if (gsre->HasChildren())\n {\n TList* ele = new TList();\n she->SetElements(ele);\n she->GetElements()->SetOwner(true);\n TEveElement::List_i i = gsre->BeginChildren();\n while (i != gsre->EndChildren()) {\n TEveGeoShape* l = dynamic_cast(*i);\n DumpShapeTree(l, she);\n i++;\n }\n }\n if (parent)\n parent->GetElements()->Add(she);\n\n return she;\n}\n\n\/\/______________________________________________________________________________\nTEveGeoShape* TEveGeoShape::ImportShapeExtract(TEveGeoShapeExtract* gse,\n TEveElement* parent)\n{\n \/\/ Import a shape extract 'gse' under element 'parent'.\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur);\n TEveManager::TRedrawDisabler redrawOff(gEve);\n TEveGeoShape* gsre = SubImportShapeExtract(gse, parent);\n gsre->ElementChanged();\n return gsre;\n}\n\n\n\/\/______________________________________________________________________________\nTEveGeoShape* TEveGeoShape::SubImportShapeExtract(TEveGeoShapeExtract* gse,\n TEveElement* parent)\n{\n \/\/ Recursive version for importing a shape extract tree.\n\n TEveGeoShape* gsre = new TEveGeoShape(gse->GetName(), gse->GetTitle());\n gsre->RefMainTrans().SetFromArray(gse->GetTrans());\n const Float_t* rgba = gse->GetRGBA();\n gsre->SetMainColorRGB(rgba[0], rgba[1], rgba[2]);\n gsre->SetMainAlpha(rgba[3]);\n gsre->SetRnrSelf(gse->GetRnrSelf());\n gsre->SetRnrChildren(gse->GetRnrElements());\n gsre->SetShape(gse->GetShape());\n\n if (parent)\n parent->AddElement(gsre);\n\n if (gse->HasElements())\n {\n TIter next(gse->GetElements());\n TEveGeoShapeExtract* chld;\n while ((chld = (TEveGeoShapeExtract*) next()) != 0)\n SubImportShapeExtract(chld, gsre);\n }\n\n return gsre;\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nTClass* TEveGeoShape::ProjectedClass() const\n{\n \/\/ Return class for projected objects, TEvePolygonSetProjected.\n \/\/ Virtual from TEveProjectable.\n\n return TEvePolygonSetProjected::Class();\n}\n\n\/******************************************************************************\/\n\n\/\/______________________________________________________________________________\nTBuffer3D* TEveGeoShape::MakeBuffer3D()\n{\n \/\/ Create a TBuffer3D suitable for presentation of the shape.\n \/\/ Transformation matrix is also applied.\n\n if (fShape == 0) return 0;\n\n if (dynamic_cast(fShape)) {\n \/\/ !!!! TGeoShapeAssembly makes a bad TBuffer3D\n return 0;\n }\n\n TEveGeoManagerHolder gmgr(fgGeoMangeur, fNSegments);\n\n TBuffer3D* buff = fShape->MakeBuffer3D();\n TEveTrans& mx = RefMainTrans();\n if (mx.GetUseTrans())\n {\n Int_t n = buff->NbPnts();\n Double_t* pnts = buff->fPnts;\n for(Int_t k = 0; k < n; ++k)\n {\n mx.MultiplyIP(&pnts[3*k]);\n }\n }\n return buff;\n}\n<|endoftext|>"} {"text":"#ifndef __Z2H_PARSER__\n#define __Z2H_PARSER__ = 1\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"token.hpp\"\n#include \"symbol.hpp\"\n#include \"binder.hpp\"\n\nusing namespace std::placeholders;\n\nnamespace z2h {\n\n template \n class Token;\n\n template \n class Symbol;\n\n template \n class Grammar;\n\n class ParserException : public std::exception {\n const char *_file;\n size_t _line;\n const std::string _message;\n std::string _what;\n public:\n ParserException(const char *file, size_t line, const std::string &message)\n : _file(file)\n , _line(line)\n , _message(message) {\n std::ostringstream out;\n out << _file << \":\" << _line << \" \" << _message << std::endl;\n _what = out.str();\n }\n virtual const char * what() const throw() {\n return _what.c_str();\n }\n };\n\n template \n struct Parser : public Binder {\n\n std::string source;\n size_t position;\n std::vector *> tokens;\n size_t index;\n\n ~Parser() {\n while (!tokens.empty())\n delete tokens.back(), tokens.pop_back();\n }\n\n Parser()\n : source(\"\")\n , position(0)\n , tokens({})\n , index(0) {\n }\n\n \/\/ Symbols must be defined by the inheriting parser\n virtual std::vector *> Symbols() = 0;\n\n Token * Scan() {\n\n auto eof = Symbols()[0];\n Symbol *match = nullptr;\n if (position < source.length()) {\n size_t end = position;\n bool skip = false;\n for (auto symbol : Symbols()) {\n long length = symbol->Scan(symbol, source.substr(position, source.length() - position), position);\n if (position + abs(length) > end || (match != nullptr && symbol->lbp > match->lbp && position + abs(length) == end)) {\n match = symbol;\n end = position + abs(length);\n skip = length < 0;\n }\n }\n if (position == end) {\n throw ParserException(__FILE__, __LINE__, \"Parser::Scan: invalid symbol\");\n }\n return new Token(match, source, position, end - position, skip);\n }\n return new Token(eof, source, position, 0, false); \/\/eof\n }\n\n Token * LookAhead(size_t distance, bool skips = false) {\n Token *token = nullptr;\n auto i = index;\n while (distance) {\n if (i < tokens.size()) {\n token = tokens[i];\n }\n else {\n token = Scan();\n position += token->length;\n tokens.push_back(token);\n }\n if (skips || !token->skip)\n --distance;\n ++i;\n }\n return token;\n }\n\n Token * Consume(Symbol *expected = nullptr, const std::string &message = \"\") {\n auto token = LookAhead(1);\n while (token->position != tokens[index++]->position);\n if (nullptr != expected && *expected != *token->symbol)\n throw ParserException(__FILE__, __LINE__, message);\n return token;\n }\n\n std::vector *> Tokenize() {\n auto eof = Symbols()[0];\n auto token = Consume();\n while (*eof != *token->symbol) {\n token = Consume();\n }\n return tokens;\n }\n\n std::string Load(const std::string &filename) {\n struct stat buffer;\n if (stat (filename.c_str(), &buffer) != 0)\n ParserException(__FILE__, __LINE__, filename + \" doesn't exist or is unreadable\");\n std::ifstream file(filename);\n std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n return text;\n }\n\n TAst ParseFile(const std::string &filename) {\n auto source = Load(filename);\n return Parse(source);\n }\n\n TAst Parse(std::string source) {\n this->source = source;\n return Expression();\n }\n\n TAst Expression(size_t rbp = 0) {\n\n auto *curr = Consume();\n if (nullptr == curr->symbol->Nud) {\n std::ostringstream out;\n out << \"unexpected: nullptr==Nud curr=\" << *curr;\n throw ParserException(__FILE__, __LINE__, out.str());\n }\n\n TAst left = curr->symbol->Nud(curr);\n\n auto *next = LookAhead(1);\n while (rbp < next->symbol->lbp) {\n next = Consume();\n left = next->symbol->Led(left, next);\n }\n\n return left;\n }\n\n TAst Statement() {\n auto *la1 = LookAhead(1);\n if (la1->symbol->Std) {\n Consume();\n return la1->symbol->Std();\n }\n auto ast = Expression();\n Consume(1, \"EndOfStatement expected!\");\n return ast;\n }\n\n size_t Line() {\n return 0;\n }\n\n size_t Column() {\n return 0;\n }\n \n };\n\n}\n\n#endif \/*__Z2H_PARSER__*\/\npassing distance by ref so that When 'Consuming' we can advance by how many tokens were actually advanced... -sai#ifndef __Z2H_PARSER__\n#define __Z2H_PARSER__ = 1\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"token.hpp\"\n#include \"symbol.hpp\"\n#include \"binder.hpp\"\n\nusing namespace std::placeholders;\n\nnamespace z2h {\n\n template \n class Token;\n\n template \n class Symbol;\n\n class ParserException : public std::exception {\n const char *_file;\n size_t _line;\n const std::string _message;\n std::string _what;\n public:\n ParserException(const char *file, size_t line, const std::string &message)\n : _file(file)\n , _line(line)\n , _message(message) {\n std::ostringstream out;\n out << _file << \":\" << _line << \" \" << _message << std::endl;\n _what = out.str();\n }\n virtual const char * what() const throw() {\n return _what.c_str();\n }\n };\n\n template \n struct Parser : public Binder {\n\n std::string source;\n size_t position;\n std::vector *> tokens;\n size_t index;\n\n ~Parser() {\n while (!tokens.empty())\n delete tokens.back(), tokens.pop_back();\n }\n\n Parser()\n : source(\"\")\n , position(0)\n , tokens({})\n , index(0) {\n }\n\n \/\/ Symbols must be defined by the inheriting parser\n virtual std::vector *> Symbols() = 0;\n\n Token * Scan() {\n\n auto eof = Symbols()[0];\n Symbol *match = nullptr;\n if (position < source.length()) {\n size_t end = position;\n bool skip = false;\n for (auto symbol : Symbols()) {\n long length = symbol->Scan(symbol, source.substr(position, source.length() - position), position);\n if (position + abs(length) > end || (match != nullptr && symbol->lbp > match->lbp && position + abs(length) == end)) {\n match = symbol;\n end = position + abs(length);\n skip = length < 0;\n }\n }\n if (position == end) {\n throw ParserException(__FILE__, __LINE__, \"Parser::Scan: invalid symbol\");\n }\n return new Token(match, source, position, end - position, skip);\n }\n return new Token(eof, source, position, 0, false); \/\/eof\n }\n\n Token * LookAhead(size_t &distance, bool skips = false) {\n Token *token = nullptr;\n auto i = index;\n while (distance) {\n if (i < tokens.size()) {\n token = tokens[i];\n }\n else {\n token = Scan();\n position += token->length;\n tokens.push_back(token);\n }\n if (skips || !token->skip)\n --distance;\n ++i;\n }\n distance = i - index;\n return token;\n }\n\n Token * Consume(Symbol *expected = nullptr, const std::string &message = \"\") {\n size_t distance = 1;\n auto token = LookAhead(distance);\n index += distance;\n if (nullptr != expected && *expected != *token->symbol)\n throw ParserException(__FILE__, __LINE__, message);\n return token;\n }\n\n std::vector *> Tokenize() {\n auto eof = Symbols()[0];\n auto token = Consume();\n while (*eof != *token->symbol) {\n token = Consume();\n }\n return tokens;\n }\n\n std::string Load(const std::string &filename) {\n struct stat buffer;\n if (stat (filename.c_str(), &buffer) != 0)\n ParserException(__FILE__, __LINE__, filename + \" doesn't exist or is unreadable\");\n std::ifstream file(filename);\n std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n return text;\n }\n\n TAst ParseFile(const std::string &filename) {\n auto source = Load(filename);\n return Parse(source);\n }\n\n TAst Parse(std::string source) {\n this->source = source;\n return Expression();\n }\n\n TAst Expression(size_t rbp = 0) {\n\n auto *curr = Consume();\n if (nullptr == curr->symbol->Nud) {\n std::ostringstream out;\n out << \"unexpected: nullptr==Nud curr=\" << *curr;\n throw ParserException(__FILE__, __LINE__, out.str());\n }\n\n TAst left = curr->symbol->Nud(curr);\n\n size_t distance = 1;\n auto *next = LookAhead(distance);\n while (rbp < next->symbol->lbp) {\n next = Consume();\n left = next->symbol->Led(left, next);\n }\n\n return left;\n }\n\n TAst Statement() {\n size_t distance = 1;\n auto *la1 = LookAhead(distance);\n if (la1->symbol->Std) {\n Consume();\n return la1->symbol->Std();\n }\n auto ast = Expression();\n Consume(1, \"EndOfStatement expected!\");\n return ast;\n }\n\n size_t Line() {\n return 0;\n }\n\n size_t Column() {\n return 0;\n }\n \n };\n\n}\n\n#endif \/*__Z2H_PARSER__*\/\n<|endoftext|>"} {"text":"#ifndef __Z2H_PARSER__\n#define __Z2H_PARSER__ = 1\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"token.hpp\"\n#include \"symbol.hpp\"\n#include \"binder.hpp\"\n\nusing namespace std::placeholders;\n\nnamespace z2h {\n\n template \n class Token;\n\n template \n class Symbol;\n\n class ParserException : public std::exception {\n const char *_file;\n size_t _line;\n const std::string _message;\n std::string _what;\n public:\n ParserException(const char *file, size_t line, const std::string &message)\n : _file(file)\n , _line(line)\n , _message(message) {\n std::ostringstream out;\n out << _file << \":\" << _line << \" \" << _message << std::endl;\n _what = out.str();\n }\n virtual const char * what() const throw() {\n return _what.c_str();\n }\n };\n\n template \n struct Parser : public Binder {\n\n std::string source;\n size_t position;\n std::vector *> tokens;\n size_t index;\n\n ~Parser() {\n while (!tokens.empty())\n delete tokens.back(), tokens.pop_back();\n }\n\n Parser()\n : source(\"\")\n , position(0)\n , tokens({})\n , index(0) {\n }\n\n \/\/ Symbols must be defined by the inheriting parser\n virtual std::vector *> Symbols() = 0;\n\n Token * Scan() {\n\n auto eof = Symbols()[0];\n Symbol *match = nullptr;\n if (position < source.length()) {\n size_t end = position;\n bool skip = false;\n for (auto symbol : Symbols()) {\n long length = symbol->Scan(symbol, source.substr(position, source.length() - position), position);\n if (position + abs(length) > end || (match != nullptr && symbol->lbp > match->lbp && position + abs(length) == end)) {\n match = symbol;\n end = position + abs(length);\n skip = length < 0;\n }\n }\n if (position == end) {\n throw ParserException(__FILE__, __LINE__, \"Parser::Scan: invalid symbol\");\n }\n return new Token(match, source, position, end - position, skip);\n }\n return new Token(eof, source, position, 0, false); \/\/eof\n }\n\n Token * LookAhead(size_t &distance, bool skips = false) {\n Token *token = nullptr;\n auto i = index;\n while (distance) {\n if (i < tokens.size()) {\n token = tokens[i];\n }\n else {\n token = Scan();\n position += token->length;\n tokens.push_back(token);\n }\n if (skips || !token->skip)\n --distance;\n ++i;\n }\n distance = i - index;\n return token;\n }\n\n Token * Consume(Symbol *expected = nullptr, const std::string &message = \"\") {\n size_t distance = 1;\n auto token = LookAhead(distance);\n index += distance;\n if (nullptr != expected && *expected != *token->symbol)\n throw ParserException(__FILE__, __LINE__, message);\n return token;\n }\n\n std::string Load(const std::string &filename) {\n struct stat buffer;\n if (stat(filename.c_str(), &buffer) != 0)\n ParserException(__FILE__, __LINE__, filename + \" doesn't exist or is unreadable\");\n std::ifstream file(filename);\n std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n source = text;\n return text;\n }\n\n std::vector *> TokenizeFile(const std::string &filename) {\n Load(filename);\n return Tokenize(source);\n }\n\n std::vector *> Tokenize(std::string source) {\n this->index = 0;\n this->source = source;\n auto eof = Symbols()[0];\n auto token = Consume();\n while (*eof != *token->symbol) {\n token = Consume();\n }\n return tokens;\n }\n\n TAst ParseFile(const std::string &filename) {\n \/\/auto source = Load(filename);\n Load(filename);\n return Parse(source);\n }\n\n TAst Parse(std::string source) {\n this->index = 0;\n this->source = source;\n return Expression();\n }\n\n TAst Expression(size_t rbp = 0) {\n\n auto *curr = Consume();\n if (nullptr == curr->symbol->Nud) {\n std::ostringstream out;\n out << \"unexpected: nullptr==Nud curr=\" << *curr;\n throw ParserException(__FILE__, __LINE__, out.str());\n }\n\n TAst left = curr->symbol->Nud(curr);\n\n size_t distance = 1;\n auto *next = LookAhead(distance);\n while (rbp < next->symbol->lbp) {\n next = Consume();\n left = next->symbol->Led(left, next);\n }\n\n return left;\n }\n\n TAst Statement() {\n size_t distance = 1;\n auto *la1 = LookAhead(distance);\n if (la1->symbol->Std) {\n Consume();\n return la1->symbol->Std();\n }\n auto ast = Expression();\n Consume(1, \"EndOfStatement expected!\");\n return ast;\n }\n\n size_t Line() {\n return 0;\n }\n\n size_t Column() {\n return 0;\n }\n \n };\n\n}\n\n#endif \/*__Z2H_PARSER__*\/\nrenamed Load -> Open ... -sai#ifndef __Z2H_PARSER__\n#define __Z2H_PARSER__ = 1\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"token.hpp\"\n#include \"symbol.hpp\"\n#include \"binder.hpp\"\n\nusing namespace std::placeholders;\n\nnamespace z2h {\n\n template \n class Token;\n\n template \n class Symbol;\n\n class ParserException : public std::exception {\n const char *_file;\n size_t _line;\n const std::string _message;\n std::string _what;\n public:\n ParserException(const char *file, size_t line, const std::string &message)\n : _file(file)\n , _line(line)\n , _message(message) {\n std::ostringstream out;\n out << _file << \":\" << _line << \" \" << _message << std::endl;\n _what = out.str();\n }\n virtual const char * what() const throw() {\n return _what.c_str();\n }\n };\n\n template \n struct Parser : public Binder {\n\n std::string source;\n size_t position;\n std::vector *> tokens;\n size_t index;\n\n ~Parser() {\n while (!tokens.empty())\n delete tokens.back(), tokens.pop_back();\n }\n\n Parser()\n : source(\"\")\n , position(0)\n , tokens({})\n , index(0) {\n }\n\n \/\/ Symbols must be defined by the inheriting parser\n virtual std::vector *> Symbols() = 0;\n\n std::string Open(const std::string &filename) {\n struct stat buffer;\n if (stat(filename.c_str(), &buffer) != 0)\n ParserException(__FILE__, __LINE__, filename + \" doesn't exist or is unreadable\");\n std::ifstream file(filename);\n std::string text((std::istreambuf_iterator(file)), std::istreambuf_iterator());\n return text;\n }\n\n Token * Scan() {\n\n auto eof = Symbols()[0];\n Symbol *match = nullptr;\n if (position < source.length()) {\n size_t end = position;\n bool skip = false;\n for (auto symbol : Symbols()) {\n long length = symbol->Scan(symbol, source.substr(position, source.length() - position), position);\n if (position + abs(length) > end || (match != nullptr && symbol->lbp > match->lbp && position + abs(length) == end)) {\n match = symbol;\n end = position + abs(length);\n skip = length < 0;\n }\n }\n if (position == end) {\n throw ParserException(__FILE__, __LINE__, \"Parser::Scan: invalid symbol\");\n }\n return new Token(match, source, position, end - position, skip);\n }\n return new Token(eof, source, position, 0, false); \/\/eof\n }\n\n Token * LookAhead(size_t &distance, bool skips = false) {\n Token *token = nullptr;\n auto i = index;\n while (distance) {\n if (i < tokens.size()) {\n token = tokens[i];\n }\n else {\n token = Scan();\n position += token->length;\n tokens.push_back(token);\n }\n if (skips || !token->skip)\n --distance;\n ++i;\n }\n distance = i - index;\n return token;\n }\n\n Token * Consume(Symbol *expected = nullptr, const std::string &message = \"\") {\n size_t distance = 1;\n auto token = LookAhead(distance);\n index += distance;\n if (nullptr != expected && *expected != *token->symbol)\n throw ParserException(__FILE__, __LINE__, message);\n return token;\n }\n\n std::vector *> TokenizeFile(const std::string &filename) {\n auto source = Open(filename);\n return Tokenize(source);\n }\n\n std::vector *> Tokenize(std::string source) {\n this->index = 0;\n this->source = source;\n auto eof = Symbols()[0];\n auto token = Consume();\n while (*eof != *token->symbol) {\n token = Consume();\n }\n return tokens;\n }\n\n TAst ParseFile(const std::string &filename) {\n auto source = Open(filename);\n return Parse(source);\n }\n\n TAst Parse(std::string source) {\n this->index = 0;\n this->source = source;\n return Expression();\n }\n\n TAst Expression(size_t rbp = 0) {\n\n auto *curr = Consume();\n if (nullptr == curr->symbol->Nud) {\n std::ostringstream out;\n out << \"unexpected: nullptr==Nud curr=\" << *curr;\n throw ParserException(__FILE__, __LINE__, out.str());\n }\n\n TAst left = curr->symbol->Nud(curr);\n\n size_t distance = 1;\n auto *next = LookAhead(distance);\n while (rbp < next->symbol->lbp) {\n next = Consume();\n left = next->symbol->Led(left, next);\n }\n\n return left;\n }\n\n TAst Statement() {\n size_t distance = 1;\n auto *la1 = LookAhead(distance);\n if (la1->symbol->Std) {\n Consume();\n return la1->symbol->Std();\n }\n auto ast = Expression();\n Consume(1, \"EndOfStatement expected!\");\n return ast;\n }\n\n size_t Line() {\n return 0;\n }\n\n size_t Column() {\n return 0;\n }\n \n };\n\n}\n\n#endif \/*__Z2H_PARSER__*\/\n<|endoftext|>"} {"text":"\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkElevationFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkElevationFilter.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkFloatArray.h\"\n\n\n\/\/------------------------------------------------------------------------------\nvtkElevationFilter* vtkElevationFilter::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkElevationFilter\");\n if(ret)\n {\n return (vtkElevationFilter*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkElevationFilter;\n}\n\n\n\n\n\/\/ Construct object with LowPoint=(0,0,0) and HighPoint=(0,0,1). Scalar\n\/\/ range is (0,1).\nvtkElevationFilter::vtkElevationFilter()\n{\n this->LowPoint[0] = 0.0;\n this->LowPoint[1] = 0.0;\n this->LowPoint[2] = 0.0;\n \n this->HighPoint[0] = 0.0;\n this->HighPoint[1] = 0.0;\n this->HighPoint[2] = 1.0;\n\n this->ScalarRange[0] = 0.0;\n this->ScalarRange[1] = 1.0;\n}\n\n\/\/\n\/\/ Convert position along ray into scalar value. Example use includes \n\/\/ coloring terrain by elevation.\n\/\/\nvoid vtkElevationFilter::Execute()\n{\n vtkIdType numPts, i;\n int j;\n vtkFloatArray *newScalars;\n float l, *x, s, v[3];\n float diffVector[3], diffScalar;\n vtkDataSet *input = this->GetInput();\n\n \/\/ Initialize\n \/\/\n vtkDebugMacro(<<\"Generating elevation scalars!\");\n\n \/\/ First, copy the input to the output as a starting point\n this->GetOutput()->CopyStructure( input );\n\n if ( ((numPts=input->GetNumberOfPoints()) < 1) )\n {\n \/\/vtkErrorMacro(<< \"No input!\");\n return;\n }\n\n \/\/ Allocate\n \/\/\n newScalars = vtkFloatArray::New();\n newScalars->SetNumberOfTuples(numPts);\n\n \/\/ Set up 1D parametric system\n \/\/\n for (i=0; i<3; i++)\n {\n diffVector[i] = this->HighPoint[i] - this->LowPoint[i];\n }\n if ( (l = vtkMath::Dot(diffVector,diffVector)) == 0.0)\n {\n vtkErrorMacro(<< this << \": Bad vector, using (0,0,1)\\n\");\n diffVector[0] = diffVector[1] = 0.0; diffVector[2] = 1.0;\n l = 1.0;\n }\n\n \/\/ Compute parametric coordinate and map into scalar range\n \/\/\n diffScalar = this->ScalarRange[1] - this->ScalarRange[0];\n for (i=0; iUpdateProgress ((float)i\/numPts);\n if (this->GetAbortExecute())\n\t{\n\tbreak;\n\t}\n }\n\n x = input->GetPoint(i);\n for (j=0; j<3; j++)\n {\n v[j] = x[j] - this->LowPoint[j];\n }\n s = vtkMath::Dot(v,diffVector) \/ l;\n s = (s < 0.0 ? 0.0 : s > 1.0 ? 1.0 : s);\n newScalars->SetValue(i,this->ScalarRange[0]+s*diffScalar);\n }\n\n \/\/ Update self\n \/\/\n this->GetOutput()->GetPointData()->CopyScalarsOff();\n this->GetOutput()->GetPointData()->PassData(input->GetPointData());\n\n this->GetOutput()->GetCellData()->PassData(input->GetCellData());\n\n newScalars->SetName(\"Elevation\");\n this->GetOutput()->GetPointData()->SetScalars(newScalars);\n newScalars->Delete();\n}\n\nvoid vtkElevationFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToDataSetFilter::PrintSelf(os,indent);\n\n os << indent << \"Low Point: (\" << this->LowPoint[0] << \", \"\n << this->LowPoint[1] << \", \"\n << this->LowPoint[2] << \")\\n\";\n os << indent << \"High Point: (\" << this->HighPoint[0] << \", \"\n << this->HighPoint[1] << \", \"\n << this->HighPoint[2] << \")\\n\";\n os << indent << \"Scalar Range: (\" << this->ScalarRange[0] << \", \"\n << this->ScalarRange[1] << \")\\n\";\n}\nENH:Saner progress reporting\/*=========================================================================\n\n Program: Visualization Toolkit\n Module: vtkElevationFilter.cxx\n Language: C++\n Date: $Date$\n Version: $Revision$\n\n\nCopyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen \nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice,\n this list of conditions and the following disclaimer.\n\n * Redistributions in binary form must reproduce the above copyright notice,\n this list of conditions and the following disclaimer in the documentation\n and\/or other materials provided with the distribution.\n\n * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names\n of any contributors may be used to endorse or promote products derived\n from this software without specific prior written permission.\n\n * Modified source versions must be plainly marked as such, and must not be\n misrepresented as being the original software.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''\nAND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\nIMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\nARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n=========================================================================*\/\n#include \"vtkElevationFilter.h\"\n#include \"vtkMath.h\"\n#include \"vtkObjectFactory.h\"\n#include \"vtkFloatArray.h\"\n\n\n\/\/------------------------------------------------------------------------------\nvtkElevationFilter* vtkElevationFilter::New()\n{\n \/\/ First try to create the object from the vtkObjectFactory\n vtkObject* ret = vtkObjectFactory::CreateInstance(\"vtkElevationFilter\");\n if(ret)\n {\n return (vtkElevationFilter*)ret;\n }\n \/\/ If the factory was unable to create the object, then create it here.\n return new vtkElevationFilter;\n}\n\n\n\n\n\/\/ Construct object with LowPoint=(0,0,0) and HighPoint=(0,0,1). Scalar\n\/\/ range is (0,1).\nvtkElevationFilter::vtkElevationFilter()\n{\n this->LowPoint[0] = 0.0;\n this->LowPoint[1] = 0.0;\n this->LowPoint[2] = 0.0;\n \n this->HighPoint[0] = 0.0;\n this->HighPoint[1] = 0.0;\n this->HighPoint[2] = 1.0;\n\n this->ScalarRange[0] = 0.0;\n this->ScalarRange[1] = 1.0;\n}\n\n\/\/\n\/\/ Convert position along ray into scalar value. Example use includes \n\/\/ coloring terrain by elevation.\n\/\/\nvoid vtkElevationFilter::Execute()\n{\n vtkIdType numPts, i;\n int j;\n vtkFloatArray *newScalars;\n float l, *x, s, v[3];\n float diffVector[3], diffScalar;\n vtkDataSet *input = this->GetInput();\n int abort=0;\n\n \/\/ Initialize\n \/\/\n vtkDebugMacro(<<\"Generating elevation scalars!\");\n\n \/\/ First, copy the input to the output as a starting point\n this->GetOutput()->CopyStructure( input );\n\n if ( ((numPts=input->GetNumberOfPoints()) < 1) )\n {\n \/\/vtkErrorMacro(<< \"No input!\");\n return;\n }\n\n \/\/ Allocate\n \/\/\n newScalars = vtkFloatArray::New();\n newScalars->SetNumberOfTuples(numPts);\n\n \/\/ Set up 1D parametric system\n \/\/\n for (i=0; i<3; i++)\n {\n diffVector[i] = this->HighPoint[i] - this->LowPoint[i];\n }\n if ( (l = vtkMath::Dot(diffVector,diffVector)) == 0.0)\n {\n vtkErrorMacro(<< this << \": Bad vector, using (0,0,1)\\n\");\n diffVector[0] = diffVector[1] = 0.0; diffVector[2] = 1.0;\n l = 1.0;\n }\n\n \/\/ Compute parametric coordinate and map into scalar range\n \/\/\n int tenth = numPts\/10 + 1;\n diffScalar = this->ScalarRange[1] - this->ScalarRange[0];\n for (i=0; iUpdateProgress ((float)i\/numPts);\n abort = this->GetAbortExecute();\n }\n\n x = input->GetPoint(i);\n for (j=0; j<3; j++)\n {\n v[j] = x[j] - this->LowPoint[j];\n }\n s = vtkMath::Dot(v,diffVector) \/ l;\n s = (s < 0.0 ? 0.0 : s > 1.0 ? 1.0 : s);\n newScalars->SetValue(i,this->ScalarRange[0]+s*diffScalar);\n }\n\n \/\/ Update self\n \/\/\n this->GetOutput()->GetPointData()->CopyScalarsOff();\n this->GetOutput()->GetPointData()->PassData(input->GetPointData());\n\n this->GetOutput()->GetCellData()->PassData(input->GetCellData());\n\n newScalars->SetName(\"Elevation\");\n this->GetOutput()->GetPointData()->SetScalars(newScalars);\n newScalars->Delete();\n}\n\nvoid vtkElevationFilter::PrintSelf(ostream& os, vtkIndent indent)\n{\n vtkDataSetToDataSetFilter::PrintSelf(os,indent);\n\n os << indent << \"Low Point: (\" << this->LowPoint[0] << \", \"\n << this->LowPoint[1] << \", \"\n << this->LowPoint[2] << \")\\n\";\n os << indent << \"High Point: (\" << this->HighPoint[0] << \", \"\n << this->HighPoint[1] << \", \"\n << this->HighPoint[2] << \")\\n\";\n os << indent << \"Scalar Range: (\" << this->ScalarRange[0] << \", \"\n << this->ScalarRange[1] << \")\\n\";\n}\n<|endoftext|>"} {"text":"#include \n\n#include \"routing\/osrm_routed_wrapper.h\"\n#include \"structures\/vroom\/input\/input.h\"\n#include \"structures\/vroom\/job.h\"\n#include \"structures\/vroom\/vehicle.h\"\n#include \"utils\/exception.h\"\n\nvoid log_solution(const vroom::Solution& sol, bool geometry) {\n std::cout << \"Total cost: \" << sol.summary.cost << std::endl;\n std::cout << \"Unassigned: \" << sol.summary.unassigned << std::endl;\n\n \/\/ Log unassigned jobs if any.\n std::cout << \"Unassigned job ids: \";\n for (const auto& j : sol.unassigned) {\n std::cout << j.id << \", \";\n }\n std::cout << std::endl;\n\n \/\/ Describe routes in solution.\n for (const auto& route : sol.routes) {\n std::cout << \"Steps for vehicle \" << route.vehicle\n << \" (cost: \" << route.cost;\n std::cout << \" - duration: \" << route.duration;\n std::cout << \" - service: \" << route.service;\n if (geometry) {\n std::cout << \" - distance: \" << route.distance;\n }\n\n std::cout << \")\" << std::endl;\n\n \/\/ Describe all route steps.\n for (const auto& step : route.steps) {\n std::string type;\n switch (step.step_type) {\n case vroom::STEP_TYPE::START:\n type = \"Start\";\n break;\n case vroom::STEP_TYPE::END:\n type = \"End\";\n break;\n case vroom::STEP_TYPE::BREAK:\n type = \"Break\";\n break;\n case vroom::STEP_TYPE::JOB:\n switch (step.job_type) {\n case vroom::JOB_TYPE::SINGLE:\n type = \"Job\";\n break;\n case vroom::JOB_TYPE::PICKUP:\n type = \"Pickup\";\n break;\n case vroom::JOB_TYPE::DELIVERY:\n type = \"Delivery\";\n break;\n }\n break;\n }\n std::cout << type;\n\n \/\/ Add job\/pickup\/delivery\/break ids.\n if (step.step_type != vroom::STEP_TYPE::START and\n step.step_type != vroom::STEP_TYPE::END) {\n std::cout << \" \" << step.id;\n }\n\n \/\/ Add location if known.\n if (step.location.has_coordinates()) {\n std::cout << \" - \" << step.location.lon() << \";\" << step.location.lat();\n }\n\n std::cout << \" - arrival: \" << step.arrival;\n std::cout << \" - duration: \" << step.duration;\n std::cout << \" - service: \" << step.service;\n\n \/\/ Add extra step info if geometry is required.\n if (geometry) {\n std::cout << \" - distance: \" << step.distance;\n }\n std::cout << std::endl;\n }\n }\n}\n\nvoid run_example_with_osrm() {\n bool GEOMETRY = true;\n unsigned amount_dimension = 1;\n\n \/\/ Set OSRM host and port for \"car\" profile.\n vroom::io::Servers servers;\n servers[\"car\"] = vroom::Server(\"localhost\", \"5000\");\n\n vroom::Input problem_instance(amount_dimension, servers, vroom::ROUTER::OSRM);\n\n problem_instance.set_geometry(GEOMETRY); \/\/ Query for route geometry\n \/\/ after solving.\n\n \/\/ Create one-dimension capacity restrictions to model the situation\n \/\/ where one vehicle can handle 4 jobs with deliveries.\n vroom::Amount vehicle_capacity(1);\n vroom::TimeWindow vehicle_tw(28800, 43200); \/\/ Working hours.\n \/\/ Default \"zero\" amount data structures with relevant dimension.\n vroom::Amount job_delivery(amount_dimension);\n vroom::Amount job_empty_delivery(amount_dimension);\n job_delivery[0] = 1;\n\n vroom::Amount job_pickup(amount_dimension);\n vroom::Amount job_empty_pickup(amount_dimension);\n job_pickup[0] = 1;\n\n vroom::Duration service = 5 * 60; \/\/ 5 minutes\n vehicle_capacity[0] = 4;\n\n \/\/ Define vehicle breaks.\n vroom::Break break_1(1, {vroom::TimeWindow(32400, 34200)}, 300);\n vroom::Break break_2(2, {vroom::TimeWindow(34200, 36000)}, 300);\n\n \/\/ Define vehicles (use std::nullopt for no start or no end).\n vroom::Location depot(vroom::Coordinates({{2.35044, 48.71764}}));\n vroom::Vehicle v1(1, \/\/ id\n depot, \/\/ start\n depot, \/\/ end\n \"car\", \/\/ profile\n vehicle_capacity, \/\/ capacity\n {1, 14}, \/\/ skills\n vehicle_tw, \/\/ time window\n {break_1}); \/\/ breaks\n problem_instance.add_vehicle(v1);\n\n vroom::Vehicle v2(2, \/\/ id\n depot, \/\/ start\n depot, \/\/ end\n \"car\", \/\/ profile\n vehicle_capacity, \/\/ capacity\n {2, 14}, \/\/ skills\n vehicle_tw, \/\/ time window\n {break_2}); \/\/ breaks\n\n problem_instance.add_vehicle(v2);\n\n \/\/ Job to be done between 9 and 10 AM.\n std::vector job_1_tws({{32400, 36000}});\n\n \/\/ Set jobs id, location, service time, amount, required skills,\n \/\/ priority and time windows. Constraints that are not required can\n \/\/ be omitted.\n std::vector jobs;\n jobs.push_back(vroom::Job(1,\n vroom::Coordinates({{1.98935, 48.701}}),\n service,\n job_delivery,\n job_empty_pickup,\n {1}, \/\/ skills\n 0, \/\/ default priority\n job_1_tws));\n jobs.push_back(vroom::Job(2,\n vroom::Coordinates({{2.03655, 48.61128}}),\n service,\n job_empty_delivery,\n job_pickup,\n {1}));\n jobs.push_back(vroom::Job(5,\n vroom::Coordinates({{2.28325, 48.5958}}),\n service,\n job_delivery,\n job_empty_pickup,\n {14}));\n jobs.push_back(vroom::Job(6,\n vroom::Coordinates({{2.89357, 48.90736}}),\n service,\n job_delivery,\n job_empty_pickup,\n {14}));\n\n for (const auto& j : jobs) {\n problem_instance.add_job(j);\n }\n\n \/\/ Define a shipment.\n vroom::Skills pd_skills({2});\n vroom::Amount pd_amount(amount_dimension);\n pd_amount[0] = 1;\n\n vroom::Job pickup(4,\n vroom::JOB_TYPE::PICKUP,\n vroom::Coordinates({{2.41808, 49.22619}}),\n service,\n pd_amount,\n pd_skills);\n\n vroom::Job delivery(3,\n vroom::JOB_TYPE::DELIVERY,\n vroom::Coordinates({{2.39719, 49.07611}}),\n service,\n pd_amount,\n pd_skills);\n problem_instance.add_shipment(pickup, delivery);\n\n \/\/ Skills definitions set the following constraints:\n \/\/ - jobs 1 and 2 can only be served by vehicle 1\n \/\/ - jobs 3 and 4 can only be served by vehicle 2\n \/\/ - jobs 5 and 6 can be served by either one of the vehicles\n\n \/\/ Solve!\n auto sol = problem_instance.solve(5, \/\/ Exploration level.\n 4); \/\/ Use 4 threads.\n\n log_solution(sol, GEOMETRY);\n}\n\nvoid run_example_with_custom_matrix() {\n bool GEOMETRY = false;\n unsigned amount_dimension = 0; \/\/ No capacity constraint.\n\n vroom::Input problem_instance(amount_dimension);\n\n \/\/ Define custom matrix and bypass OSRM call.\n vroom::Matrix matrix_input({{0, 2104, 197, 1299},\n {2103, 0, 2255, 3152},\n {197, 2256, 0, 1102},\n {1299, 3153, 1102, 0}});\n problem_instance.set_matrix(std::move(matrix_input));\n\n \/\/ Define vehicles (use std::nullopt for no start or no end).\n vroom::Location v_start(0); \/\/ index in the provided matrix.\n vroom::Location v_end(3); \/\/ index in the provided matrix.\n\n vroom::Vehicle v(0, \/\/ id\n v_start, \/\/ start\n v_end); \/\/ end\n problem_instance.add_vehicle(v);\n\n \/\/ Define jobs with id and index of location in the matrix\n \/\/ (coordinates are optional). Constraints that are not required can\n \/\/ be omitted.\n std::vector jobs;\n jobs.push_back(vroom::Job(1414, 1));\n jobs.push_back(vroom::Job(1515, 2));\n\n for (const auto& j : jobs) {\n problem_instance.add_job(j);\n }\n\n \/\/ Solve!\n auto sol = problem_instance.solve(5, \/\/ Exploration level.\n 4); \/\/ Use 4 threads.\n\n log_solution(sol, GEOMETRY);\n}\n\nint main() {\n try {\n run_example_with_osrm();\n \/\/ run_example_with_custom_matrix();\n } catch (const vroom::Exception& e) {\n std::cerr << \"[Error] \" << e.message << std::endl;\n }\n return 0;\n}\nFix set_matrix call in libvroom example.#include \n\n#include \"routing\/osrm_routed_wrapper.h\"\n#include \"structures\/vroom\/input\/input.h\"\n#include \"structures\/vroom\/job.h\"\n#include \"structures\/vroom\/vehicle.h\"\n#include \"utils\/exception.h\"\n\nvoid log_solution(const vroom::Solution& sol, bool geometry) {\n std::cout << \"Total cost: \" << sol.summary.cost << std::endl;\n std::cout << \"Unassigned: \" << sol.summary.unassigned << std::endl;\n\n \/\/ Log unassigned jobs if any.\n std::cout << \"Unassigned job ids: \";\n for (const auto& j : sol.unassigned) {\n std::cout << j.id << \", \";\n }\n std::cout << std::endl;\n\n \/\/ Describe routes in solution.\n for (const auto& route : sol.routes) {\n std::cout << \"Steps for vehicle \" << route.vehicle\n << \" (cost: \" << route.cost;\n std::cout << \" - duration: \" << route.duration;\n std::cout << \" - service: \" << route.service;\n if (geometry) {\n std::cout << \" - distance: \" << route.distance;\n }\n\n std::cout << \")\" << std::endl;\n\n \/\/ Describe all route steps.\n for (const auto& step : route.steps) {\n std::string type;\n switch (step.step_type) {\n case vroom::STEP_TYPE::START:\n type = \"Start\";\n break;\n case vroom::STEP_TYPE::END:\n type = \"End\";\n break;\n case vroom::STEP_TYPE::BREAK:\n type = \"Break\";\n break;\n case vroom::STEP_TYPE::JOB:\n switch (step.job_type) {\n case vroom::JOB_TYPE::SINGLE:\n type = \"Job\";\n break;\n case vroom::JOB_TYPE::PICKUP:\n type = \"Pickup\";\n break;\n case vroom::JOB_TYPE::DELIVERY:\n type = \"Delivery\";\n break;\n }\n break;\n }\n std::cout << type;\n\n \/\/ Add job\/pickup\/delivery\/break ids.\n if (step.step_type != vroom::STEP_TYPE::START and\n step.step_type != vroom::STEP_TYPE::END) {\n std::cout << \" \" << step.id;\n }\n\n \/\/ Add location if known.\n if (step.location.has_coordinates()) {\n std::cout << \" - \" << step.location.lon() << \";\" << step.location.lat();\n }\n\n std::cout << \" - arrival: \" << step.arrival;\n std::cout << \" - duration: \" << step.duration;\n std::cout << \" - service: \" << step.service;\n\n \/\/ Add extra step info if geometry is required.\n if (geometry) {\n std::cout << \" - distance: \" << step.distance;\n }\n std::cout << std::endl;\n }\n }\n}\n\nvoid run_example_with_osrm() {\n bool GEOMETRY = true;\n unsigned amount_dimension = 1;\n\n \/\/ Set OSRM host and port for \"car\" profile.\n vroom::io::Servers servers;\n servers[\"car\"] = vroom::Server(\"localhost\", \"5000\");\n\n vroom::Input problem_instance(amount_dimension, servers, vroom::ROUTER::OSRM);\n\n problem_instance.set_geometry(GEOMETRY); \/\/ Query for route geometry\n \/\/ after solving.\n\n \/\/ Create one-dimension capacity restrictions to model the situation\n \/\/ where one vehicle can handle 4 jobs with deliveries.\n vroom::Amount vehicle_capacity(1);\n vroom::TimeWindow vehicle_tw(28800, 43200); \/\/ Working hours.\n \/\/ Default \"zero\" amount data structures with relevant dimension.\n vroom::Amount job_delivery(amount_dimension);\n vroom::Amount job_empty_delivery(amount_dimension);\n job_delivery[0] = 1;\n\n vroom::Amount job_pickup(amount_dimension);\n vroom::Amount job_empty_pickup(amount_dimension);\n job_pickup[0] = 1;\n\n vroom::Duration service = 5 * 60; \/\/ 5 minutes\n vehicle_capacity[0] = 4;\n\n \/\/ Define vehicle breaks.\n vroom::Break break_1(1, {vroom::TimeWindow(32400, 34200)}, 300);\n vroom::Break break_2(2, {vroom::TimeWindow(34200, 36000)}, 300);\n\n \/\/ Define vehicles (use std::nullopt for no start or no end).\n vroom::Location depot(vroom::Coordinates({{2.35044, 48.71764}}));\n vroom::Vehicle v1(1, \/\/ id\n depot, \/\/ start\n depot, \/\/ end\n \"car\", \/\/ profile\n vehicle_capacity, \/\/ capacity\n {1, 14}, \/\/ skills\n vehicle_tw, \/\/ time window\n {break_1}); \/\/ breaks\n problem_instance.add_vehicle(v1);\n\n vroom::Vehicle v2(2, \/\/ id\n depot, \/\/ start\n depot, \/\/ end\n \"car\", \/\/ profile\n vehicle_capacity, \/\/ capacity\n {2, 14}, \/\/ skills\n vehicle_tw, \/\/ time window\n {break_2}); \/\/ breaks\n\n problem_instance.add_vehicle(v2);\n\n \/\/ Job to be done between 9 and 10 AM.\n std::vector job_1_tws({{32400, 36000}});\n\n \/\/ Set jobs id, location, service time, amount, required skills,\n \/\/ priority and time windows. Constraints that are not required can\n \/\/ be omitted.\n std::vector jobs;\n jobs.push_back(vroom::Job(1,\n vroom::Coordinates({{1.98935, 48.701}}),\n service,\n job_delivery,\n job_empty_pickup,\n {1}, \/\/ skills\n 0, \/\/ default priority\n job_1_tws));\n jobs.push_back(vroom::Job(2,\n vroom::Coordinates({{2.03655, 48.61128}}),\n service,\n job_empty_delivery,\n job_pickup,\n {1}));\n jobs.push_back(vroom::Job(5,\n vroom::Coordinates({{2.28325, 48.5958}}),\n service,\n job_delivery,\n job_empty_pickup,\n {14}));\n jobs.push_back(vroom::Job(6,\n vroom::Coordinates({{2.89357, 48.90736}}),\n service,\n job_delivery,\n job_empty_pickup,\n {14}));\n\n for (const auto& j : jobs) {\n problem_instance.add_job(j);\n }\n\n \/\/ Define a shipment.\n vroom::Skills pd_skills({2});\n vroom::Amount pd_amount(amount_dimension);\n pd_amount[0] = 1;\n\n vroom::Job pickup(4,\n vroom::JOB_TYPE::PICKUP,\n vroom::Coordinates({{2.41808, 49.22619}}),\n service,\n pd_amount,\n pd_skills);\n\n vroom::Job delivery(3,\n vroom::JOB_TYPE::DELIVERY,\n vroom::Coordinates({{2.39719, 49.07611}}),\n service,\n pd_amount,\n pd_skills);\n problem_instance.add_shipment(pickup, delivery);\n\n \/\/ Skills definitions set the following constraints:\n \/\/ - jobs 1 and 2 can only be served by vehicle 1\n \/\/ - jobs 3 and 4 can only be served by vehicle 2\n \/\/ - jobs 5 and 6 can be served by either one of the vehicles\n\n \/\/ Solve!\n auto sol = problem_instance.solve(5, \/\/ Exploration level.\n 4); \/\/ Use 4 threads.\n\n log_solution(sol, GEOMETRY);\n}\n\nvoid run_example_with_custom_matrix() {\n bool GEOMETRY = false;\n unsigned amount_dimension = 0; \/\/ No capacity constraint.\n\n vroom::Input problem_instance(amount_dimension);\n\n \/\/ Define custom matrix and bypass OSRM call.\n vroom::Matrix matrix_input({{0, 2104, 197, 1299},\n {2103, 0, 2255, 3152},\n {197, 2256, 0, 1102},\n {1299, 3153, 1102, 0}});\n problem_instance.set_matrix(\"car\", std::move(matrix_input));\n\n \/\/ Define vehicles (use std::nullopt for no start or no end).\n vroom::Location v_start(0); \/\/ index in the provided matrix.\n vroom::Location v_end(3); \/\/ index in the provided matrix.\n\n vroom::Vehicle v(0, \/\/ id\n v_start, \/\/ start\n v_end); \/\/ end\n problem_instance.add_vehicle(v);\n\n \/\/ Define jobs with id and index of location in the matrix\n \/\/ (coordinates are optional). Constraints that are not required can\n \/\/ be omitted.\n std::vector jobs;\n jobs.push_back(vroom::Job(1414, 1));\n jobs.push_back(vroom::Job(1515, 2));\n\n for (const auto& j : jobs) {\n problem_instance.add_job(j);\n }\n\n \/\/ Solve!\n auto sol = problem_instance.solve(5, \/\/ Exploration level.\n 4); \/\/ Use 4 threads.\n\n log_solution(sol, GEOMETRY);\n}\n\nint main() {\n try {\n run_example_with_osrm();\n \/\/ run_example_with_custom_matrix();\n } catch (const vroom::Exception& e) {\n std::cerr << \"[Error] \" << e.message << std::endl;\n }\n return 0;\n}\n<|endoftext|>"} {"text":"\/**\n * This file is part of Slideshow.\n * Copyright (C) 2008 David Sveningsson \n *\n * Slideshow is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Slideshow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Slideshow. If not, see .\n *\/\n\n#include \"config.h\"\n#include \"Exceptions.h\"\n#include \"Graphics.h\"\n#include \"Kernel.h\"\n#include \"OS.h\"\n#include \"Log.h\"\n#include \"Transition.h\"\n#include \n#include \n\n#include \n#include \n\nstatic void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) {\n\tconst char* format = fif != FIF_UNKNOWN ? FreeImage_GetFormatFromFIF(fif) : \"Unknown\";\n\tLog::message(Log::Verbose, \"FreeImage: An error occured while loading an image\\n\");\n Log::message(Log::Debug, \"FreeImage: Format: %s Message: %s\\n\", format, message);\n}\n\nstatic FIBITMAP* GenericLoader(const char* lpszPathName, int flag = 0) {\n FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName, 0);\n\n if ( fif == FIF_UNKNOWN ) {\n \tfif = FreeImage_GetFIFFromFilename(lpszPathName);\n\t}\n\n if ( fif == FIF_UNKNOWN ) {\n \tthrow GraphicsException(\"FreeImage: unknown format, or FreeImage does not handle it.\");\n }\n\n if ( !FreeImage_FIFSupportsReading(fif) ){\n \tthrow GraphicsException(\"FreeImage: cannot read this format.\");\n }\n\n return FreeImage_Load(fif, lpszPathName, flag);\n}\nGraphics::Graphics(int width, int height, bool fullscreen):\n\t_transition(NULL),\n\ttexture_0(0),\n\ttexture_1(0){\n\n\tOS::init_view(width, height, fullscreen);\n\tLog::message(Log::Verbose, \"Graphics: Using resoultion %dx%d\\n\", width, height);\n\n\tfreeimage_init();\n\tgl_setup();\n\tgl_set_matrices();\n\tgl_init_textures();\n}\n\nGraphics::~Graphics(){\n\tgl_cleanup_textures();\n\tfreeimage_cleanup();\n\n\tif ( _transition && _transition->cleanup ){\n\t\t_transition->cleanup();\n\t}\n\n\tfree(_transition);\n\n\tOS::cleanup();\n}\n\nvoid Graphics::freeimage_init(){\n\tFreeImage_Initialise();\n\tFreeImage_SetOutputMessage(FreeImageErrorHandler);\n}\n\nvoid Graphics::freeimage_cleanup(){\n\tFreeImage_DeInitialise();\n}\n\nvoid Graphics::gl_setup(){\n\tglShadeModel( GL_FLAT );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );\n\tglClearColor(0, 0, 0, 1);\n\tglColor4f(1, 1, 1, 1);\n\n\tglDisable( GL_DEPTH_TEST );\n\tglDisable( GL_LIGHTING );\n\tglDisable(GL_ALPHA_TEST);\n\n\tglEnable( GL_TEXTURE_2D );\n\tglEnable(GL_BLEND);\n\tglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tglClear( GL_COLOR_BUFFER_BIT );\n}\n\nvoid Graphics::gl_set_matrices(){\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglOrtho(0, 1, 0, 1, -1.0, 1.0);\n\tglScalef(1, -1, 1);\n\tglTranslated(0, -1, 0);\n\n\tglEnable(GL_CULL_FACE);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid Graphics::gl_init_textures(){\n\tglGenTextures(1, &texture_0);\n\tglGenTextures(1, &texture_1);\n}\n\nvoid Graphics::gl_cleanup_textures(){\n\tglDeleteTextures(1, &texture_0);\n\tglDeleteTextures(1, &texture_1);\n}\n\nvoid Graphics::render(float state){\n\ttransition_context_t context;\n\n\tcontext.texture[0] = texture_0;\n\tcontext.texture[1] = texture_1;\n\tcontext.state = state;\n\n\t_transition->render(&context);\n\n\tOS::swap_gl_buffers();\n}\n\nvoid Graphics::load_image(const char* name){\n\tswap_textures();\n\n\tBYTE black[] = {\n\t\t0, 0, 0\n\t};\n\tBYTE *pixels = black;\n\tFIBITMAP* dib_resized = NULL;\n\n\tint width = 1;\n\tint height = 1;\n\n\tglBindTexture(GL_TEXTURE_2D, texture_0);\n\n\tif ( name ){\n\t\tchar* path = Kernel::real_path(name);\n\n\t\tFIBITMAP* dib = GenericLoader(path);\n\n\t\tif( !dib ){\n\t\t\tthrow GraphicsException(\"Failed to load image '%s'\", path);\n\t\t}\n\n\t\tfree(path);\n\n\t\tFreeImage_FlipVertical(dib);\n\n\t\tFIBITMAP* dib32 = FreeImage_ConvertTo24Bits(dib);\n\n\t\twidth = 1024;\n\t\theight = 1024;\n\n\t\tdib_resized = FreeImage_Rescale(dib32, width, height, FILTER_BILINEAR);\n\n\t\tpixels = (BYTE*)FreeImage_GetBits(dib_resized);\n\n\t\tFreeImage_Unload(dib);\n\t\tFreeImage_Unload(dib32);\n\t}\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pixels);\n\n if ( name ){\n \tFreeImage_Unload(dib_resized);\n }\n}\n\nvoid Graphics::swap_textures(){\n\tunsigned int tmp = texture_0;\n\ttexture_0 = texture_1;\n\ttexture_1 = tmp;\n}\n\nvoid Graphics::set_transition(transition_module_t* module){\n\tif ( _transition && _transition->cleanup ){\n\t\t_transition->cleanup();\n\t}\n\n\t_transition = module;\n\n\tif ( _transition && _transition->init ){\n\t\t_transition->init();\n\t}\n}\nMemoryleak if an image could not be loaded\/**\n * This file is part of Slideshow.\n * Copyright (C) 2008 David Sveningsson \n *\n * Slideshow is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Affero General Public License as\n * published by the Free Software Foundation, either version 3 of the\n * License, or (at your option) any later version.\n *\n * Slideshow is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Affero General Public License for more details.\n *\n * You should have received a copy of the GNU Affero General Public License\n * along with Slideshow. If not, see .\n *\/\n\n#include \"config.h\"\n#include \"Exceptions.h\"\n#include \"Graphics.h\"\n#include \"Kernel.h\"\n#include \"OS.h\"\n#include \"Log.h\"\n#include \"Transition.h\"\n#include \n#include \n\n#include \n#include \n\nstatic void FreeImageErrorHandler(FREE_IMAGE_FORMAT fif, const char *message) {\n\tconst char* format = fif != FIF_UNKNOWN ? FreeImage_GetFormatFromFIF(fif) : \"Unknown\";\n\tLog::message(Log::Verbose, \"FreeImage: An error occured while loading an image\\n\");\n Log::message(Log::Debug, \"FreeImage: Format: %s Message: %s\\n\", format, message);\n}\n\nstatic FIBITMAP* GenericLoader(const char* lpszPathName, int flag = 0) {\n FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(lpszPathName, 0);\n\n if ( fif == FIF_UNKNOWN ) {\n \tfif = FreeImage_GetFIFFromFilename(lpszPathName);\n\t}\n\n if ( fif == FIF_UNKNOWN ) {\n \tthrow GraphicsException(\"FreeImage: unknown format, or FreeImage does not handle it.\");\n }\n\n if ( !FreeImage_FIFSupportsReading(fif) ){\n \tthrow GraphicsException(\"FreeImage: cannot read this format.\");\n }\n\n return FreeImage_Load(fif, lpszPathName, flag);\n}\nGraphics::Graphics(int width, int height, bool fullscreen):\n\t_transition(NULL),\n\ttexture_0(0),\n\ttexture_1(0){\n\n\tOS::init_view(width, height, fullscreen);\n\tLog::message(Log::Verbose, \"Graphics: Using resoultion %dx%d\\n\", width, height);\n\n\tfreeimage_init();\n\tgl_setup();\n\tgl_set_matrices();\n\tgl_init_textures();\n}\n\nGraphics::~Graphics(){\n\tgl_cleanup_textures();\n\tfreeimage_cleanup();\n\n\tif ( _transition && _transition->cleanup ){\n\t\t_transition->cleanup();\n\t}\n\n\tfree(_transition);\n\n\tOS::cleanup();\n}\n\nvoid Graphics::freeimage_init(){\n\tFreeImage_Initialise();\n\tFreeImage_SetOutputMessage(FreeImageErrorHandler);\n}\n\nvoid Graphics::freeimage_cleanup(){\n\tFreeImage_DeInitialise();\n}\n\nvoid Graphics::gl_setup(){\n\tglShadeModel( GL_FLAT );\n\tglHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST );\n\tglClearColor(0, 0, 0, 1);\n\tglColor4f(1, 1, 1, 1);\n\n\tglDisable( GL_DEPTH_TEST );\n\tglDisable( GL_LIGHTING );\n\tglDisable(GL_ALPHA_TEST);\n\n\tglEnable( GL_TEXTURE_2D );\n\tglEnable(GL_BLEND);\n\tglBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n\tglClear( GL_COLOR_BUFFER_BIT );\n}\n\nvoid Graphics::gl_set_matrices(){\n\tglMatrixMode(GL_PROJECTION);\n\tglLoadIdentity();\n\n\tglOrtho(0, 1, 0, 1, -1.0, 1.0);\n\tglScalef(1, -1, 1);\n\tglTranslated(0, -1, 0);\n\n\tglEnable(GL_CULL_FACE);\n\n\tglMatrixMode(GL_MODELVIEW);\n\tglLoadIdentity();\n}\n\nvoid Graphics::gl_init_textures(){\n\tglGenTextures(1, &texture_0);\n\tglGenTextures(1, &texture_1);\n}\n\nvoid Graphics::gl_cleanup_textures(){\n\tglDeleteTextures(1, &texture_0);\n\tglDeleteTextures(1, &texture_1);\n}\n\nvoid Graphics::render(float state){\n\ttransition_context_t context;\n\n\tcontext.texture[0] = texture_0;\n\tcontext.texture[1] = texture_1;\n\tcontext.state = state;\n\n\t_transition->render(&context);\n\n\tOS::swap_gl_buffers();\n}\n\nvoid Graphics::load_image(const char* name){\n\tswap_textures();\n\n\tBYTE black[] = {\n\t\t0, 0, 0\n\t};\n\tBYTE *pixels = black;\n\tFIBITMAP* dib_resized = NULL;\n\n\tint width = 1;\n\tint height = 1;\n\n\tglBindTexture(GL_TEXTURE_2D, texture_0);\n\n\tif ( name ){\n\t\tchar* path = Kernel::real_path(name);\n\n\t\tFIBITMAP* dib = GenericLoader(path);\n\n\t\tif( !dib ){\n\t\t\tfree(path);\n\t\t\tthrow GraphicsException(\"Failed to load image '%s'\", path);\n\t\t}\n\n\t\tfree(path);\n\n\t\tFreeImage_FlipVertical(dib);\n\n\t\tFIBITMAP* dib32 = FreeImage_ConvertTo24Bits(dib);\n\n\t\twidth = 1024;\n\t\theight = 1024;\n\n\t\tdib_resized = FreeImage_Rescale(dib32, width, height, FILTER_BILINEAR);\n\n\t\tpixels = (BYTE*)FreeImage_GetBits(dib_resized);\n\n\t\tFreeImage_Unload(dib);\n\t\tFreeImage_Unload(dib32);\n\t}\n\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_BGR_EXT, GL_UNSIGNED_BYTE, pixels);\n\n if ( name ){\n \tFreeImage_Unload(dib_resized);\n }\n}\n\nvoid Graphics::swap_textures(){\n\tunsigned int tmp = texture_0;\n\ttexture_0 = texture_1;\n\ttexture_1 = tmp;\n}\n\nvoid Graphics::set_transition(transition_module_t* module){\n\tif ( _transition && _transition->cleanup ){\n\t\t_transition->cleanup();\n\t}\n\n\t_transition = module;\n\n\tif ( _transition && _transition->init ){\n\t\t_transition->init();\n\t}\n}\n<|endoftext|>"} {"text":"\/\/===- unittests\/AST\/PostOrderASTVisitor.cpp - Declaration printer tests --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains tests for the post-order traversing functionality\n\/\/ of RecursiveASTVisitor.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace clang;\n\nnamespace {\n\n class RecordingVisitor\n : public RecursiveASTVisitor {\n\n bool VisitPostOrder;\n public:\n explicit RecordingVisitor(bool VisitPostOrder)\n : VisitPostOrder(VisitPostOrder) {\n }\n\n \/\/ List of visited nodes during traversal.\n std::vector VisitedNodes;\n\n bool shouldTraversePostOrder() const { return VisitPostOrder; }\n\n bool VisitUnaryOperator(UnaryOperator *Op) {\n VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));\n return true;\n }\n\n bool VisitBinaryOperator(BinaryOperator *Op) {\n VisitedNodes.push_back(Op->getOpcodeStr());\n return true;\n }\n\n bool VisitIntegerLiteral(IntegerLiteral *Lit) {\n VisitedNodes.push_back(Lit->getValue().toString(10, false));\n return true;\n }\n\n bool VisitVarDecl(VarDecl* D) {\n VisitedNodes.push_back(D->getNameAsString());\n return true;\n }\n\n bool VisitCXXMethodDecl(CXXMethodDecl *D) {\n VisitedNodes.push_back(D->getQualifiedNameAsString());\n return true;\n }\n\n bool VisitReturnStmt(ReturnStmt *S) {\n VisitedNodes.push_back(\"return\");\n return true;\n }\n\n bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {\n VisitedNodes.push_back(Declaration->getQualifiedNameAsString());\n return true;\n }\n\n bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {\n VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());\n return true;\n }\n };\n\n}\n\nTEST(RecursiveASTVisitor, PostOrderTraversal) {\n auto ASTUnit = tooling::buildASTFromCode(\n \"class A {\"\n \" class B {\"\n \" int foo() { while(4) { int i = 9; int j = -i; } return (1 + 3) + 2; }\"\n \" };\"\n \"};\"\n );\n auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();\n \/\/ We traverse the translation unit and store all\n \/\/ visited nodes.\n RecordingVisitor Visitor(true);\n Visitor.TraverseTranslationUnitDecl(TU);\n\n std::vector expected = {\n \"4\", \"9\", \"i\", \"-\", \"j\", \"1\", \"3\", \"+\", \"2\", \"+\", \"return\", \"A::B::foo\", \"A::B\", \"A\"\n };\n \/\/ Compare the list of actually visited nodes\n \/\/ with the expected list of visited nodes.\n ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());\n for (std::size_t I = 0; I < expected.size(); I++) {\n ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);\n }\n}\n\nTEST(RecursiveASTVisitor, NoPostOrderTraversal) {\n auto ASTUnit = tooling::buildASTFromCode(\n \"class A {\"\n \" class B {\"\n \" int foo() { return 1 + 2; }\"\n \" };\"\n \"};\"\n );\n auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();\n \/\/ We traverse the translation unit and store all\n \/\/ visited nodes.\n RecordingVisitor Visitor(false);\n Visitor.TraverseTranslationUnitDecl(TU);\n\n std::vector expected = {\n \"A\", \"A::B\", \"A::B::foo\", \"return\", \"+\", \"1\", \"2\"\n };\n \/\/ Compare the list of actually visited nodes\n \/\/ with the expected list of visited nodes.\n ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());\n for (std::size_t I = 0; I < expected.size(); I++) {\n ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);\n }\n}\n[RecursiveASTVisitor] Improve post-order traversal unit test\/\/===- unittests\/AST\/PostOrderASTVisitor.cpp - Declaration printer tests --===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\/\/\n\/\/ This file contains tests for the post-order traversing functionality\n\/\/ of RecursiveASTVisitor.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"clang\/AST\/RecursiveASTVisitor.h\"\n#include \"clang\/Tooling\/Tooling.h\"\n#include \"gtest\/gtest.h\"\n\nusing namespace clang;\n\nnamespace {\n\n class RecordingVisitor\n : public RecursiveASTVisitor {\n\n bool VisitPostOrder;\n public:\n explicit RecordingVisitor(bool VisitPostOrder)\n : VisitPostOrder(VisitPostOrder) {\n }\n\n \/\/ List of visited nodes during traversal.\n std::vector VisitedNodes;\n\n bool shouldTraversePostOrder() const { return VisitPostOrder; }\n\n bool VisitUnaryOperator(UnaryOperator *Op) {\n VisitedNodes.push_back(Op->getOpcodeStr(Op->getOpcode()));\n return true;\n }\n\n bool VisitBinaryOperator(BinaryOperator *Op) {\n VisitedNodes.push_back(Op->getOpcodeStr());\n return true;\n }\n\n bool VisitIntegerLiteral(IntegerLiteral *Lit) {\n VisitedNodes.push_back(Lit->getValue().toString(10, false));\n return true;\n }\n\n bool VisitVarDecl(VarDecl* D) {\n VisitedNodes.push_back(D->getNameAsString());\n return true;\n }\n\n bool VisitCXXMethodDecl(CXXMethodDecl *D) {\n VisitedNodes.push_back(D->getQualifiedNameAsString());\n return true;\n }\n\n bool VisitReturnStmt(ReturnStmt *S) {\n VisitedNodes.push_back(\"return\");\n return true;\n }\n\n bool VisitCXXRecordDecl(CXXRecordDecl *Declaration) {\n VisitedNodes.push_back(Declaration->getQualifiedNameAsString());\n return true;\n }\n\n bool VisitTemplateTypeParmType(TemplateTypeParmType *T) {\n VisitedNodes.push_back(T->getDecl()->getQualifiedNameAsString());\n return true;\n }\n };\n\n}\n\nTEST(RecursiveASTVisitor, PostOrderTraversal) {\n auto ASTUnit = tooling::buildASTFromCode(\n \"class A {\"\n \" class B {\"\n \" int foo() { while(4) { int i = 9; int j = -5; } return (1 + 3) + 2; }\"\n \" };\"\n \"};\"\n );\n auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();\n \/\/ We traverse the translation unit and store all\n \/\/ visited nodes.\n RecordingVisitor Visitor(true);\n Visitor.TraverseTranslationUnitDecl(TU);\n\n std::vector expected = {\"4\", \"9\", \"i\", \"5\", \"-\",\n \"j\", \"1\", \"3\", \"+\", \"2\",\n \"+\", \"return\", \"A::B::foo\", \"A::B\", \"A\"};\n \/\/ Compare the list of actually visited nodes\n \/\/ with the expected list of visited nodes.\n ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());\n for (std::size_t I = 0; I < expected.size(); I++) {\n ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);\n }\n}\n\nTEST(RecursiveASTVisitor, NoPostOrderTraversal) {\n auto ASTUnit = tooling::buildASTFromCode(\n \"class A {\"\n \" class B {\"\n \" int foo() { return 1 + 2; }\"\n \" };\"\n \"};\"\n );\n auto TU = ASTUnit->getASTContext().getTranslationUnitDecl();\n \/\/ We traverse the translation unit and store all\n \/\/ visited nodes.\n RecordingVisitor Visitor(false);\n Visitor.TraverseTranslationUnitDecl(TU);\n\n std::vector expected = {\n \"A\", \"A::B\", \"A::B::foo\", \"return\", \"+\", \"1\", \"2\"\n };\n \/\/ Compare the list of actually visited nodes\n \/\/ with the expected list of visited nodes.\n ASSERT_EQ(expected.size(), Visitor.VisitedNodes.size());\n for (std::size_t I = 0; I < expected.size(); I++) {\n ASSERT_EQ(expected[I], Visitor.VisitedNodes[I]);\n }\n}\n<|endoftext|>"} {"text":"\/\/===- llvm\/unittest\/VMCore\/InstructionsTest.cpp - Instructions unit tests ===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace llvm {\nnamespace {\n\nTEST(InstructionsTest, ReturnInst) {\n LLVMContext &C(getGlobalContext());\n\n \/\/ test for PR6589\n const ReturnInst* r0 = ReturnInst::Create(C);\n EXPECT_EQ(r0->op_begin(), r0->op_end());\n\n const IntegerType* Int1 = IntegerType::get(C, 1);\n Constant* One = ConstantInt::get(Int1, 1, true);\n const ReturnInst* r1 = ReturnInst::Create(C, One);\n User::const_op_iterator b(r1->op_begin());\n EXPECT_NE(b, r1->op_end());\n EXPECT_EQ(*b, One);\n EXPECT_EQ(r1->getOperand(0), One);\n ++b;\n EXPECT_EQ(b, r1->op_end());\n\n \/\/ clean up\n delete r0;\n delete r1;\n}\n\n} \/\/ end anonymous namespace\n} \/\/ end namespace llvm\nadd BranchInst tests\/\/===- llvm\/unittest\/VMCore\/InstructionsTest.cpp - Instructions unit tests ===\/\/\n\/\/\n\/\/ The LLVM Compiler Infrastructure\n\/\/\n\/\/ This file is distributed under the University of Illinois Open Source\n\/\/ License. See LICENSE.TXT for details.\n\/\/\n\/\/===----------------------------------------------------------------------===\/\/\n\n#include \"llvm\/Instructions.h\"\n#include \"llvm\/BasicBlock.h\"\n#include \"llvm\/DerivedTypes.h\"\n#include \"llvm\/LLVMContext.h\"\n#include \"gtest\/gtest.h\"\n\nnamespace llvm {\nnamespace {\n\nTEST(InstructionsTest, ReturnInst) {\n LLVMContext &C(getGlobalContext());\n\n \/\/ test for PR6589\n const ReturnInst* r0 = ReturnInst::Create(C);\n EXPECT_EQ(r0->getNumOperands(), 0U);\n EXPECT_EQ(r0->op_begin(), r0->op_end());\n\n const IntegerType* Int1 = IntegerType::get(C, 1);\n Constant* One = ConstantInt::get(Int1, 1, true);\n const ReturnInst* r1 = ReturnInst::Create(C, One);\n EXPECT_EQ(r1->getNumOperands(), 1U);\n User::const_op_iterator b(r1->op_begin());\n EXPECT_NE(b, r1->op_end());\n EXPECT_EQ(*b, One);\n EXPECT_EQ(r1->getOperand(0), One);\n ++b;\n EXPECT_EQ(b, r1->op_end());\n\n \/\/ clean up\n delete r0;\n delete r1;\n}\n\nTEST(InstructionsTest, BranchInst) {\n LLVMContext &C(getGlobalContext());\n\n \/\/ Make a BasicBlocks\n BasicBlock* bb0 = BasicBlock::Create(C);\n BasicBlock* bb1 = BasicBlock::Create(C);\n\n \/\/ Mandatory BranchInst\n const BranchInst* b0 = BranchInst::Create(bb0);\n\n \/\/ check num operands\n EXPECT_EQ(b0->getNumOperands(), 1U);\n\n EXPECT_NE(b0->op_begin(), b0->op_end());\n\n const IntegerType* Int1 = IntegerType::get(C, 1);\n Constant* One = ConstantInt::get(Int1, 1, true);\n\n \/\/ Conditional BranchInst\n BranchInst* b1 = BranchInst::Create(bb0, bb1, One);\n\n \/\/ check num operands\n EXPECT_EQ(b1->getNumOperands(), 3U);\n\n User::const_op_iterator b(b1->op_begin());\n\n \/\/ check COND\n EXPECT_NE(b, b1->op_end());\n EXPECT_EQ(*b, One);\n EXPECT_EQ(b1->getOperand(0), One);\n ++b;\n\n \/\/ check ELSE\n EXPECT_EQ(*b, bb1);\n EXPECT_EQ(b1->getOperand(1), bb1);\n ++b;\n\n \/\/ check THEN\n EXPECT_EQ(*b, bb0);\n EXPECT_EQ(b1->getOperand(2), bb0);\n ++b;\n\n EXPECT_EQ(b, b1->op_end());\n\n \/\/ shrink it\n b1->setUnconditionalDest(bb1);\n\n \/\/ check num operands\n EXPECT_EQ(b1->getNumOperands(), 1U);\n\n User::const_op_iterator c(b1->op_begin());\n EXPECT_NE(c, b1->op_end());\n\n \/\/ check THEN\n EXPECT_EQ(*c, bb1);\n EXPECT_EQ(b1->getOperand(0), bb1);\n ++c;\n\n EXPECT_EQ(c, b1->op_end());\n\n \/\/ clean up\n delete b0;\n delete b1;\n\n delete bb0;\n delete bb1;\n}\n\n} \/\/ end anonymous namespace\n} \/\/ end namespace llvm\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\nnamespace lvtk {\nnamespace demo {\n\nclass Box : public lvtk::Widget {\npublic:\n Box() = default;\n virtual ~Box() = default;\n\n void paint (Graphics& g) override {\n g.set_color (color);\n g.fill_rect (bounds().at (0, 0));\n }\n\n bool obstructed (int x, int y) override { return true; }\n\n void motion (InputEvent ev) override {\n \/\/ std::clog << __name << \" motion: \"\n \/\/ << ev.pos.str() << std::endl;\n }\n\n void pressed (InputEvent ev) override {\n std::clog << __name << \" down: \"\n << ev.pos.str() << \" bounds: \"\n << bounds().str() << std::endl;\n }\n\n void released (InputEvent ev) override {\n std::clog << __name << \" up: \"\n << ev.pos.str() << std::endl;\n }\n\n Color color { 0xff0000ff };\n};\n\nclass Container : public Widget {\npublic:\n Container() {\n add (button1);\n button1.set_visible (true);\n button1.__name = \"button1\";\n button1.color = Color (0x444444ff);\n add (button2);\n button2.__name = \"button2\";\n button2.color = button1.color;\n button2.set_visible (true);\n }\n\n void resized() override {\n auto r1 = bounds().at (0, 0);\n \/\/ std::clog << \"container resized: \" << r1.str() << std::endl;\n r1.width \/= 2;\n auto r2 = r1;\n r2.x = r1.width;\n const int padding = 12;\n r1.x += padding;\n r1.y += padding;\n r1.width -= (padding * 2);\n r1.height -= (padding * 2);\n r2.x += padding;\n r2.y += padding;\n r2.width -= (padding * 2);\n r2.height -= (padding * 2);\n\n button1.set_bounds (r1);\n button2.set_bounds (r2);\n }\n\n void paint (Graphics& g) override {\n g.set_color (0x777777FF);\n g.fill_rect (bounds().at (0, 0));\n }\n\n Box button1, button2;\n};\n\nclass Content : public Widget {\npublic:\n Content() {\n __name = \"Content\";\n add (buttons);\n buttons.set_visible (true);\n set_size (360, 240);\n set_visible (true);\n }\n\n ~Content() {\n }\n\n void motion (InputEvent ev) override {\n \/\/ std::clog << \"content motion\\n\";\n }\n\n void resized() override {\n auto r = bounds().at (0, 0);\n r.x = 20;\n r.y = 20;\n r.width -= (r.x * 2);\n r.height -= (r.y * 2);\n buttons.set_bounds (r);\n }\n\n void paint (Graphics& g) override {\n g.set_color (Color (0x545454ff));\n g.fill_rect (bounds().at (0, 0).as());\n }\n\nprivate:\n Container buttons;\n};\n\nstatic int run (lvtk::Main& context, int argc, char** argv) {\n auto content = std::make_unique();\n content->set_size (640, 360);\n content->set_visible (true);\n\n try {\n context.elevate (*content, 0);\n bool quit = false;\n while (! quit) {\n context.loop (-1.0);\n quit = context.__quit_flag;\n }\n } catch (...) {\n std::clog << \"fatal error in main loop\\n\";\n \/\/ std::clog << e.what() << std::endl;\n return 1;\n }\n\n content.reset();\n return 0;\n}\n\n} \/\/ namespace demo\n} \/\/ namespace lvtk\ndemo: run any widget with c++ template func#pragma once\n\n#include \n#include \n#include \n\nnamespace lvtk {\nnamespace demo {\n\nclass Box : public lvtk::Widget {\npublic:\n Box() = default;\n virtual ~Box() = default;\n\n void paint (Graphics& g) override {\n g.set_color (color);\n g.fill_rect (bounds().at (0, 0));\n }\n\n bool obstructed (int x, int y) override { return true; }\n\n void motion (InputEvent ev) override {\n \/\/ std::clog << __name << \" motion: \"\n \/\/ << ev.pos.str() << std::endl;\n }\n\n void pressed (InputEvent ev) override {\n std::clog << __name << \" down: \"\n << ev.pos.str() << \" bounds: \"\n << bounds().str() << std::endl;\n }\n\n void released (InputEvent ev) override {\n std::clog << __name << \" up: \"\n << ev.pos.str() << std::endl;\n }\n\n Color color { 0xff0000ff };\n};\n\nclass Container : public Widget {\npublic:\n Container() {\n add (button1);\n button1.set_visible (true);\n button1.__name = \"button1\";\n button1.color = Color (0x444444ff);\n add (button2);\n button2.__name = \"button2\";\n button2.color = button1.color;\n button2.set_visible (true);\n }\n\n void resized() override {\n auto r1 = bounds().at (0, 0);\n \/\/ std::clog << \"container resized: \" << r1.str() << std::endl;\n r1.width \/= 2;\n auto r2 = r1;\n r2.x = r1.width;\n const int padding = 12;\n r1.x += padding;\n r1.y += padding;\n r1.width -= (padding * 2);\n r1.height -= (padding * 2);\n r2.x += padding;\n r2.y += padding;\n r2.width -= (padding * 2);\n r2.height -= (padding * 2);\n\n button1.set_bounds (r1);\n button2.set_bounds (r2);\n }\n\n void paint (Graphics& g) override {\n g.set_color (0x777777FF);\n g.fill_rect (bounds().at (0, 0));\n }\n\n Box button1, button2;\n};\n\nclass Content : public Widget {\npublic:\n Content() {\n __name = \"Content\";\n add (buttons);\n buttons.set_visible (true);\n set_size (360, 240);\n set_visible (true);\n }\n\n ~Content() {\n }\n\n void motion (InputEvent ev) override {\n \/\/ std::clog << \"content motion\\n\";\n }\n\n void resized() override {\n auto r = bounds().at (0, 0);\n r.x = 20;\n r.y = 20;\n r.width -= (r.x * 2);\n r.height -= (r.y * 2);\n buttons.set_bounds (r);\n }\n\n void paint (Graphics& g) override {\n g.set_color (Color (0x545454ff));\n g.fill_rect (bounds().at (0, 0).as());\n }\n\nprivate:\n Container buttons;\n};\n\n\ntemplate \nstatic int run (lvtk::Main& context) {\n auto content = std::make_unique();\n content->set_size (640, 360);\n content->set_visible (true);\n\n try {\n context.elevate (*content, 0);\n bool quit = false;\n while (! quit) {\n context.loop (-1.0);\n quit = context.__quit_flag;\n }\n } catch (...) {\n std::clog << \"fatal error in main loop\\n\";\n \/\/ std::clog << e.what() << std::endl;\n return 1;\n }\n\n content.reset();\n return 0;\n}\n\nstatic int run (lvtk::Main& context, int, char**) {\n return run (context);\n}\n\n} \/\/ namespace demo\n} \/\/ namespace lvtk\n<|endoftext|>"} {"text":"\/*\n\tThis program tests class LinkedList\n*\/\n\n#include\n#include\n#include \"linkedlist.h\"\n\n\/\/ tests insertion\n\nvoid testInsert(){\n\n\tstd::cout<<\"Test Insert\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {6,5,4,3,2,1};\n\n\t\/\/ create linked list\n\tLinkedList ll;\n\n\t\/\/ insert values into linked list (always at beginning i.e. index 0)\n\tfor(auto x: values){\n\t\tll.insertFirst(x);\n\t}\n\n\t\/\/ display linked list\n\tll.print();\n\n\t\/\/ insert 100 at end\n\tll.insertLast(100);\n\n\t\/\/ display linked list\n\tll.print();\n\n\t\/\/ insert in between\n\tll.insert_node(3,5000);\n\n\t\/\/ display linked list\n\tll.print();\n\n\tll.valueAt(-500);\n\n}\n\n\n\/\/ tests valueAt() and getLength()\n\nvoid testB(){\n\n\tstd::cout<<\"Test B\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {6,5,4,3,2,1};\n\n\t\/\/ create linked list\n\tLinkedList ll;\n\n\t\/\/ insert values into linked list (always at beginning i.e. index 0)\n\tfor(auto x: values){\n\t\tll.insertFirst(x);\n\t}\n\n\t\/\/ insert 100 at end\n\tll.insertLast(1000);\n\n\t\/\/ insert in between\n\tll.insert_node(3,5000);\n\n\t\/\/ display linked list\n\tll.print();\t\n\n\tstd::cout<<\"Length: \"< values = {20,18,16,15,14,12,10,8,6,4,1,2,0};\n\n\t\/\/ Create linked list\n\tLinkedList ll;\n\n\tfor(auto x: values){\n\n\t\tll.insertFirst(x);\n\t}\t\n\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index: 9\\n\";\n\tll.delete_node(9);\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index : 2\\n\";\n\tll.delete_node(2);\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index: 0\\n\";\n\tll.delete_node(0);\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index: 9\\n\";\n\tll.delete_node(9);\n\tll.print();\n\n}\n\n\n\/\/ tests reverse\nvoid testReverse(){\n\n\tstd::cout<<\"Test Reverse\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {10,9,8,7,6,5,4,3,2,1};\n\n\t\/\/ Create linked list\n\tLinkedList ll;\n\n\tfor(auto x: values){\n\n\t\tll.insertFirst(x);\n\t}\t\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tfor(int i=0;i<7;i++)\n\t\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\n}\n\n\n\/\/ tests pairwiseReverse\nvoid testpairwiseReverse(){\n\n\tstd::cout<<\"Test Pairwise Reverse\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {10,9,8,7,6,5,4,3,2,1};\n\n\t\/\/ Create linked list\n\tLinkedList ll;\n\n\tfor(auto x: values){\n\n\t\tll.insertFirst(x);\n\t}\t\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tfor(int i=0;i<6;i++)\n\t\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\t\n\tll.print();\n\n\n}\n\n\n\/\/ tests hasLoop\n\nvoid testHasLoop(){\n\n\tLinkedList l1(1);\n\n\tif(l1.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl1 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl1 does not have loop\";\n\n\tLinkedList l2;\n\tfor(int i=1;i<=5;i++)\n\t\tl2.insertLast(i);\n\n\tif(l2.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl2 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl2 does not have loop\";\n\n\n\tLinkedList l3(2);\n\n\tif(l3.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl3 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl3 does not have loop\";\n\n\n\tLinkedList l4(3);\n\n\tif(l4.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl4 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl4 does not have loop\";\n}\n\n\nint main(){\n\n\t\/\/ test insert\n\ttestInsert();\n\n\t\/\/ test B\n\ttestB();\n\n\t\/\/ test delete\n\ttestDelete();\n\n\t\/\/ test reverse\n\ttestReverse();\n\n\t\/\/ test pairwise reverse\n\ttestpairwiseReverse();\n\n\t\/\/ test hasLoop\n\ttestHasLoop();\n\n\treturn 0;\n}\nAdd test cases for loop removal\/*\n\tThis program tests class LinkedList\n*\/\n\n#include\n#include\n#include \"linkedlist.h\"\n\n\/\/ tests insertion\n\nvoid testInsert(){\n\n\tstd::cout<<\"Test Insert\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {6,5,4,3,2,1};\n\n\t\/\/ create linked list\n\tLinkedList ll;\n\n\t\/\/ insert values into linked list (always at beginning i.e. index 0)\n\tfor(auto x: values){\n\t\tll.insertFirst(x);\n\t}\n\n\t\/\/ display linked list\n\tll.print();\n\n\t\/\/ insert 100 at end\n\tll.insertLast(100);\n\n\t\/\/ display linked list\n\tll.print();\n\n\t\/\/ insert in between\n\tll.insert_node(3,5000);\n\n\t\/\/ display linked list\n\tll.print();\n\n\tll.valueAt(-500);\n\n}\n\n\n\/\/ tests valueAt() and getLength()\n\nvoid testB(){\n\n\tstd::cout<<\"Test B\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {6,5,4,3,2,1};\n\n\t\/\/ create linked list\n\tLinkedList ll;\n\n\t\/\/ insert values into linked list (always at beginning i.e. index 0)\n\tfor(auto x: values){\n\t\tll.insertFirst(x);\n\t}\n\n\t\/\/ insert 100 at end\n\tll.insertLast(1000);\n\n\t\/\/ insert in between\n\tll.insert_node(3,5000);\n\n\t\/\/ display linked list\n\tll.print();\t\n\n\tstd::cout<<\"Length: \"< values = {20,18,16,15,14,12,10,8,6,4,1,2,0};\n\n\t\/\/ Create linked list\n\tLinkedList ll;\n\n\tfor(auto x: values){\n\n\t\tll.insertFirst(x);\n\t}\t\n\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index: 9\\n\";\n\tll.delete_node(9);\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index : 2\\n\";\n\tll.delete_node(2);\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index: 0\\n\";\n\tll.delete_node(0);\n\tll.print();\n\n\tstd::cout<<\"\\nDelete index: 9\\n\";\n\tll.delete_node(9);\n\tll.print();\n\n}\n\n\n\/\/ tests reverse\nvoid testReverse(){\n\n\tstd::cout<<\"Test Reverse\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {10,9,8,7,6,5,4,3,2,1};\n\n\t\/\/ Create linked list\n\tLinkedList ll;\n\n\tfor(auto x: values){\n\n\t\tll.insertFirst(x);\n\t}\t\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tfor(int i=0;i<7;i++)\n\t\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.reverse();\n\n\tll.print();\n\n\n}\n\n\n\/\/ tests pairwiseReverse\nvoid testpairwiseReverse(){\n\n\tstd::cout<<\"Test Pairwise Reverse\\n\";\n\n\t\/\/ define vector of values\n\tstd::vector values = {10,9,8,7,6,5,4,3,2,1};\n\n\t\/\/ Create linked list\n\tLinkedList ll;\n\n\tfor(auto x: values){\n\n\t\tll.insertFirst(x);\n\t}\t\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tfor(int i=0;i<6;i++)\n\t\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\n\tll.print();\n\n\tll.delete_node(0);\n\n\tll.print();\n\n\tll.pairwiseReverse();\n\t\n\tll.print();\n\n\n}\n\n\n\/\/ tests hasLoop\n\nvoid testHasLoop(){\n\n\tLinkedList l1(1);\n\n\tif(l1.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl1 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl1 does not have loop\";\n\n\tLinkedList l2;\n\tfor(int i=1;i<=5;i++)\n\t\tl2.insertLast(i);\n\n\tif(l2.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl2 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl2 does not have loop\";\n\n\n\tLinkedList l3(2);\n\n\tif(l3.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl3 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl3 does not have loop\";\n\n\n\tLinkedList l4(3);\n\n\tif(l4.hasLoop()!=nullptr)\n\t\tstd::cout<<\"\\nl4 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl4 does not have loop\";\n}\n\n\n\/\/tests remove loop\n\nvoid testRemoveLoop(){\n\n\tLinkedList l1(1);\n\n\tNode * loopnode1 = l1.hasLoop();\n\n\tif(loopnode1!=nullptr)\n\t\tstd::cout<<\"\\nl1 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl1 does not have loop\";\n\n\tl1.removeLoop(loopnode1);\n\n\tloopnode1 = l1.hasLoop();\n\n\tif(loopnode1!=nullptr)\n\t\tstd::cout<<\"\\nl1 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl1 does not have loop\";\n\n\tl1.print();\n\n\n\tLinkedList l3(2);\n\n\tNode * loopnode3 = l3.hasLoop();\n\n\tif(loopnode3!=nullptr)\n\t\tstd::cout<<\"\\nl3 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl3 does not have loop\";\n\n\tl3.removeLoop(loopnode3);\n\n\tloopnode3 = l3.hasLoop();\n\n\tif(loopnode3!=nullptr)\n\t\tstd::cout<<\"\\nl3 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl3 does not have loop\";\n\t\n\tl3.print();\n\n\t\n\tLinkedList l4(3);\n\n\tNode *loopnode4 = l4.hasLoop();\n\n\tif(loopnode4!=nullptr)\n\t\tstd::cout<<\"\\nl4 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl4 does not have loop\";\n\n\tl4.removeLoop(loopnode4);\n\n\tloopnode4 = l4.hasLoop();\n\n\tif(loopnode4!=nullptr)\n\t\tstd::cout<<\"\\nl4 has loop\";\n\telse\n\t\tstd::cout<<\"\\nl4 does not have loop\";\t\n\n\tl4.print();\n\n}\n\nint main(){\n\n\t\/\/ test insert\n\ttestInsert();\n\n\t\/\/ test B\n\ttestB();\n\n\t\/\/ test delete\n\ttestDelete();\n\n\t\/\/ test reverse\n\ttestReverse();\n\n\t\/\/ test pairwise reverse\n\ttestpairwiseReverse();\n\n\t\/\/ test hasLoop\n\ttestHasLoop();\n\n\t\/\/ test remove loop\n\ttestRemoveLoop();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \"io_interface.h\"\n\n#include \"matrix_config.h\"\n#include \"mem_worker_thread.h\"\n#include \"EM_object.h\"\n#include \"local_mem_buffer.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\n#ifdef USE_HWLOC\nstd::vector get_cpus(int node_id)\n{\n\tstd::vector io_cpus = safs::get_io_cpus();\n\tstd::vector logical_units = cpus.get_node(node_id).get_logical_units();\n\tstd::set cpu_set(logical_units.begin(), logical_units.end());\n\t\/\/ Remove the logical units where I\/O threads run.\n\tfor (size_t j = 0; j < io_cpus.size(); j++)\n\t\tcpu_set.erase(io_cpus[j]);\n\treturn std::vector(cpu_set.begin(), cpu_set.end());\n}\n#endif\n\nmem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node)\n{\n\ttot_num_tasks = 0;\n\tthreads.resize(num_nodes);\n\tfor (int i = 0; i < num_nodes; i++) {\n\t\t\/\/ Get the CPU cores that are in node i.\n#ifdef USE_HWLOC\n\t\tstd::vector cpus = get_cpus(i);\n#endif\n\t\tthreads[i].resize(nthreads_per_node);\n\t\tfor (int j = 0; j < nthreads_per_node; j++) {\n\t\t\tstd::string name\n\t\t\t\t= std::string(\"mem-worker-\") + itoa(i) + \"-\" + itoa(j);\n#ifdef USE_HWLOC\n\t\t\tif (safs::get_io_cpus().empty())\n\t\t\t\tthreads[i][j] = std::shared_ptr(\n\t\t\t\t\t\tnew pool_task_thread(i * nthreads_per_node + j, name, i));\n\t\t\telse\n\t\t\t\tthreads[i][j] = std::shared_ptr(\n\t\t\t\t\t\tnew pool_task_thread(i * nthreads_per_node + j, name,\n\t\t\t\t\t\t\tcpus, i));\n#else\n\t\t\tthreads[i][j] = std::shared_ptr(\n\t\t\t\t\tnew pool_task_thread(i * nthreads_per_node + j, name, i));\n#endif\n\t\t\tthreads[i][j]->start();\n\t\t}\n\t}\n\tntasks_per_node.resize(num_nodes);\n}\n\n\/*\n * This method dispatches tasks in a round-robin fashion.\n *\/\nvoid mem_thread_pool::process_task(int node_id, thread_task *task)\n{\n\tif (node_id < 0)\n\t\tnode_id = tot_num_tasks % get_num_nodes();\n\n\tassert((size_t) node_id < threads.size());\n\tsize_t idx = ntasks_per_node[node_id] % threads[node_id].size();\n\tthreads[node_id][idx]->add_task(task);\n\tntasks_per_node[node_id]++;\n\ttot_num_tasks++;\n}\n\nvoid mem_thread_pool::wait4complete()\n{\n\tfor (size_t i = 0; i < threads.size(); i++) {\n\t\tsize_t nthreads = threads[i].size();\n\t\tfor (size_t j = 0; j < nthreads; j++)\n\t\t\tthreads[i][j]->wait4complete();\n\t}\n\n\t\/\/ After all workers complete, we should try to clear the memory buffers\n\t\/\/ in each worker thread to reduce memory consumption.\n\t\/\/ We might want to keep the memory buffer for I\/O on dense matrices.\n\tif (matrix_conf.is_keep_mem_buf())\n\t\tdetail::local_mem_buffer::clear_bufs(\n\t\t\t\tdetail::local_mem_buffer::MAT_PORTION);\n\telse\n\t\tdetail::local_mem_buffer::clear_bufs();\n}\n\nsize_t mem_thread_pool::get_num_pending() const\n{\n\tsize_t ret = 0;\n\tfor (size_t i = 0; i < threads.size(); i++) {\n\t\tsize_t nthreads = threads[i].size();\n\t\tfor (size_t j = 0; j < nthreads; j++)\n\t\t\tret += threads[i][j]->get_num_pending();\n\t}\n\treturn ret;\n}\n\nstatic mem_thread_pool::ptr global_threads;\nenum thread_pool_state {\n\tUNINIT,\n\tACTIVE,\n\tINACTIVE,\n};\nstatic thread_pool_state pool_state = thread_pool_state::UNINIT;\n\n\/*\n * When we disable thread pool, we use the main thread to perform\n * computation.\n *\/\nbool mem_thread_pool::disable_thread_pool()\n{\n\tpool_state = thread_pool_state::INACTIVE;\n\treturn true;\n}\n\nbool mem_thread_pool::enable_thread_pool()\n{\n\tpool_state = thread_pool_state::ACTIVE;\n\treturn true;\n}\n\nmem_thread_pool::ptr mem_thread_pool::get_global_mem_threads()\n{\n\tassert(pool_state != thread_pool_state::INACTIVE);\n\tif (global_threads == NULL) {\n\t\tint nthreads_per_node\n\t\t\t= matrix_conf.get_num_DM_threads() \/ matrix_conf.get_num_nodes();\n\t\tassert(nthreads_per_node > 0);\n\t\tglobal_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(),\n\t\t\t\tnthreads_per_node);\n\t\tenable_thread_pool();\n\t}\n\treturn global_threads;\n}\n\nsize_t mem_thread_pool::get_global_num_threads()\n{\n\t\/\/ When we disable the thread pool, we use the main thread for computation.\n\t\/\/ So the number of threads is 1.\n\tif (pool_state == thread_pool_state::INACTIVE)\n\t\treturn 1;\n\telse\n\t\treturn get_global_mem_threads()->get_num_threads();\n}\n\nint mem_thread_pool::get_curr_thread_id()\n{\n\t\/\/ When we disable the thread pool, we use the main thread for computation.\n\t\/\/ And we use 0 as the thread id of the main thread.\n\tif (pool_state == thread_pool_state::INACTIVE)\n\t\treturn 0;\n\telse {\n\t\tdetail::pool_task_thread *curr\n\t\t\t= dynamic_cast(thread::get_curr_thread());\n\t\tassert(curr);\n\t\treturn curr->get_pool_thread_id();\n\t}\n}\n\nvoid mem_thread_pool::init_global_mem_threads(int num_nodes,\n\t\tint nthreads_per_node)\n{\n\tif (global_threads == NULL) {\n\t\tglobal_threads = mem_thread_pool::create(num_nodes, nthreads_per_node);\n\t\tenable_thread_pool();\n\t}\n}\n\nvoid mem_thread_pool::destroy()\n{\n\tglobal_threads = NULL;\n}\n\nstatic size_t wait4ios(safs::io_select::ptr select, size_t max_pending_ios)\n{\n\tsize_t num_pending;\n\tdo {\n\t\tnum_pending = select->num_pending_ios();\n\n\t\t\/\/ Figure out how many I\/O requests we have to wait for in\n\t\t\/\/ this iteration.\n\t\tint num_to_process;\n\t\tif (num_pending > max_pending_ios)\n\t\t\tnum_to_process = num_pending - max_pending_ios;\n\t\telse\n\t\t\tnum_to_process = 0;\n\t\tselect->wait4complete(num_to_process);\n\n\t\t\/\/ Test if all I\/O instances have pending I\/O requests left.\n\t\t\/\/ When a portion of a matrix is ready in memory and being processed,\n\t\t\/\/ it may result in writing data to another matrix. Therefore, we\n\t\t\/\/ need to process all completed I\/O requests (portions with data\n\t\t\/\/ in memory) first and then count the number of new pending I\/Os.\n\t\tnum_pending = select->num_pending_ios();\n\t} while (num_pending > max_pending_ios);\n\treturn num_pending;\n}\n\nvoid io_worker_task::run()\n{\n\tstd::vector ios;\n\tpthread_spin_lock(&lock);\n\tfor (auto it = EM_objs.begin(); it != EM_objs.end(); it++) {\n\t\tstd::vector tmp = (*it)->create_ios();\n\t\tios.insert(ios.end(), tmp.begin(), tmp.end());\n\t}\n\tpthread_spin_unlock(&lock);\n\tsafs::io_select::ptr select = safs::create_io_select(ios);\n\n\t\/\/ The task runs until there are no tasks left in the queue.\n\twhile (dispatch->issue_task())\n\t\twait4ios(select, max_pending_ios);\n\t\/\/ Test if all I\/O instances have processed all requests.\n\tsize_t num_pending = wait4ios(select, 0);\n\tassert(num_pending == 0);\n\n\tpthread_spin_lock(&lock);\n\tEM_objs.clear();\n\tpthread_spin_unlock(&lock);\n\n\tfor (size_t i = 0; i < ios.size(); i++) {\n\t\tportion_callback &cb = static_cast(\n\t\t\t\tios[i]->get_callback());\n\t\tassert(!cb.has_callback());\n\t}\n}\n\nglobal_counter::global_counter()\n{\n\tcounts.resize(mem_thread_pool::get_global_num_threads());\n\treset();\n}\n\nvoid global_counter::inc(size_t val)\n{\n\tint id = mem_thread_pool::get_curr_thread_id();\n\tcounts[id].count += val;\n}\n\nvoid global_counter::reset()\n{\n\tfor (size_t i = 0; i < counts.size(); i++)\n\t\tcounts[i].count = 0;\n}\n\nsize_t global_counter::get() const\n{\n\tsize_t tot = 0;\n\tfor (size_t i = 0; i < counts.size(); i++)\n\t\ttot += counts[i].count;\n\treturn tot;\n}\n\n}\n\n}\n[Matrix]: del wait4ios.\/*\n * Copyright 2014 Open Connectome Project (http:\/\/openconnecto.me)\n * Written by Da Zheng (zhengda1936@gmail.com)\n *\n * This file is part of FlashMatrix.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#include \n\n#include \"io_interface.h\"\n\n#include \"matrix_config.h\"\n#include \"mem_worker_thread.h\"\n#include \"EM_object.h\"\n#include \"local_mem_buffer.h\"\n\nnamespace fm\n{\n\nnamespace detail\n{\n\n#ifdef USE_HWLOC\nstd::vector get_cpus(int node_id)\n{\n\tstd::vector io_cpus = safs::get_io_cpus();\n\tstd::vector logical_units = cpus.get_node(node_id).get_logical_units();\n\tstd::set cpu_set(logical_units.begin(), logical_units.end());\n\t\/\/ Remove the logical units where I\/O threads run.\n\tfor (size_t j = 0; j < io_cpus.size(); j++)\n\t\tcpu_set.erase(io_cpus[j]);\n\treturn std::vector(cpu_set.begin(), cpu_set.end());\n}\n#endif\n\nmem_thread_pool::mem_thread_pool(int num_nodes, int nthreads_per_node)\n{\n\ttot_num_tasks = 0;\n\tthreads.resize(num_nodes);\n\tfor (int i = 0; i < num_nodes; i++) {\n\t\t\/\/ Get the CPU cores that are in node i.\n#ifdef USE_HWLOC\n\t\tstd::vector cpus = get_cpus(i);\n#endif\n\t\tthreads[i].resize(nthreads_per_node);\n\t\tfor (int j = 0; j < nthreads_per_node; j++) {\n\t\t\tstd::string name\n\t\t\t\t= std::string(\"mem-worker-\") + itoa(i) + \"-\" + itoa(j);\n#ifdef USE_HWLOC\n\t\t\tif (safs::get_io_cpus().empty())\n\t\t\t\tthreads[i][j] = std::shared_ptr(\n\t\t\t\t\t\tnew pool_task_thread(i * nthreads_per_node + j, name, i));\n\t\t\telse\n\t\t\t\tthreads[i][j] = std::shared_ptr(\n\t\t\t\t\t\tnew pool_task_thread(i * nthreads_per_node + j, name,\n\t\t\t\t\t\t\tcpus, i));\n#else\n\t\t\tthreads[i][j] = std::shared_ptr(\n\t\t\t\t\tnew pool_task_thread(i * nthreads_per_node + j, name, i));\n#endif\n\t\t\tthreads[i][j]->start();\n\t\t}\n\t}\n\tntasks_per_node.resize(num_nodes);\n}\n\n\/*\n * This method dispatches tasks in a round-robin fashion.\n *\/\nvoid mem_thread_pool::process_task(int node_id, thread_task *task)\n{\n\tif (node_id < 0)\n\t\tnode_id = tot_num_tasks % get_num_nodes();\n\n\tassert((size_t) node_id < threads.size());\n\tsize_t idx = ntasks_per_node[node_id] % threads[node_id].size();\n\tthreads[node_id][idx]->add_task(task);\n\tntasks_per_node[node_id]++;\n\ttot_num_tasks++;\n}\n\nvoid mem_thread_pool::wait4complete()\n{\n\tfor (size_t i = 0; i < threads.size(); i++) {\n\t\tsize_t nthreads = threads[i].size();\n\t\tfor (size_t j = 0; j < nthreads; j++)\n\t\t\tthreads[i][j]->wait4complete();\n\t}\n\n\t\/\/ After all workers complete, we should try to clear the memory buffers\n\t\/\/ in each worker thread to reduce memory consumption.\n\t\/\/ We might want to keep the memory buffer for I\/O on dense matrices.\n\tif (matrix_conf.is_keep_mem_buf())\n\t\tdetail::local_mem_buffer::clear_bufs(\n\t\t\t\tdetail::local_mem_buffer::MAT_PORTION);\n\telse\n\t\tdetail::local_mem_buffer::clear_bufs();\n}\n\nsize_t mem_thread_pool::get_num_pending() const\n{\n\tsize_t ret = 0;\n\tfor (size_t i = 0; i < threads.size(); i++) {\n\t\tsize_t nthreads = threads[i].size();\n\t\tfor (size_t j = 0; j < nthreads; j++)\n\t\t\tret += threads[i][j]->get_num_pending();\n\t}\n\treturn ret;\n}\n\nstatic mem_thread_pool::ptr global_threads;\nenum thread_pool_state {\n\tUNINIT,\n\tACTIVE,\n\tINACTIVE,\n};\nstatic thread_pool_state pool_state = thread_pool_state::UNINIT;\n\n\/*\n * When we disable thread pool, we use the main thread to perform\n * computation.\n *\/\nbool mem_thread_pool::disable_thread_pool()\n{\n\tpool_state = thread_pool_state::INACTIVE;\n\treturn true;\n}\n\nbool mem_thread_pool::enable_thread_pool()\n{\n\tpool_state = thread_pool_state::ACTIVE;\n\treturn true;\n}\n\nmem_thread_pool::ptr mem_thread_pool::get_global_mem_threads()\n{\n\tassert(pool_state != thread_pool_state::INACTIVE);\n\tif (global_threads == NULL) {\n\t\tint nthreads_per_node\n\t\t\t= matrix_conf.get_num_DM_threads() \/ matrix_conf.get_num_nodes();\n\t\tassert(nthreads_per_node > 0);\n\t\tglobal_threads = mem_thread_pool::create(matrix_conf.get_num_nodes(),\n\t\t\t\tnthreads_per_node);\n\t\tenable_thread_pool();\n\t}\n\treturn global_threads;\n}\n\nsize_t mem_thread_pool::get_global_num_threads()\n{\n\t\/\/ When we disable the thread pool, we use the main thread for computation.\n\t\/\/ So the number of threads is 1.\n\tif (pool_state == thread_pool_state::INACTIVE)\n\t\treturn 1;\n\telse\n\t\treturn get_global_mem_threads()->get_num_threads();\n}\n\nint mem_thread_pool::get_curr_thread_id()\n{\n\t\/\/ When we disable the thread pool, we use the main thread for computation.\n\t\/\/ And we use 0 as the thread id of the main thread.\n\tif (pool_state == thread_pool_state::INACTIVE)\n\t\treturn 0;\n\telse {\n\t\tdetail::pool_task_thread *curr\n\t\t\t= dynamic_cast(thread::get_curr_thread());\n\t\tassert(curr);\n\t\treturn curr->get_pool_thread_id();\n\t}\n}\n\nvoid mem_thread_pool::init_global_mem_threads(int num_nodes,\n\t\tint nthreads_per_node)\n{\n\tif (global_threads == NULL) {\n\t\tglobal_threads = mem_thread_pool::create(num_nodes, nthreads_per_node);\n\t\tenable_thread_pool();\n\t}\n}\n\nvoid mem_thread_pool::destroy()\n{\n\tglobal_threads = NULL;\n}\n\nvoid io_worker_task::run()\n{\n\tstd::vector ios;\n\tpthread_spin_lock(&lock);\n\tfor (auto it = EM_objs.begin(); it != EM_objs.end(); it++) {\n\t\tstd::vector tmp = (*it)->create_ios();\n\t\tios.insert(ios.end(), tmp.begin(), tmp.end());\n\t}\n\tpthread_spin_unlock(&lock);\n\tsafs::io_select::ptr select = safs::create_io_select(ios);\n\n\t\/\/ The task runs until there are no tasks left in the queue.\n\twhile (dispatch->issue_task())\n\t\tsafs::wait4ios(select, max_pending_ios);\n\t\/\/ Test if all I\/O instances have processed all requests.\n\tsize_t num_pending = safs::wait4ios(select, 0);\n\tassert(num_pending == 0);\n\n\tpthread_spin_lock(&lock);\n\tEM_objs.clear();\n\tpthread_spin_unlock(&lock);\n\n\tfor (size_t i = 0; i < ios.size(); i++) {\n\t\tportion_callback &cb = static_cast(\n\t\t\t\tios[i]->get_callback());\n\t\tassert(!cb.has_callback());\n\t}\n}\n\nglobal_counter::global_counter()\n{\n\tcounts.resize(mem_thread_pool::get_global_num_threads());\n\treset();\n}\n\nvoid global_counter::inc(size_t val)\n{\n\tint id = mem_thread_pool::get_curr_thread_id();\n\tcounts[id].count += val;\n}\n\nvoid global_counter::reset()\n{\n\tfor (size_t i = 0; i < counts.size(); i++)\n\t\tcounts[i].count = 0;\n}\n\nsize_t global_counter::get() const\n{\n\tsize_t tot = 0;\n\tfor (size_t i = 0; i < counts.size(); i++)\n\t\ttot += counts[i].count;\n\treturn tot;\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"#ifndef UNITTEST11_UTILITY_TOSTRING_HPP\r\n#define UNITTEST11_UTILITY_TOSTRING_HPP\r\n\r\n#include \"Meta\/IsIterableContainer.hpp\"\r\n#include \"Meta\/IfElseTypes.hpp\"\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace ut11\r\n{\r\n\tnamespace utility\r\n\t{\r\n\t\ttemplate inline std::string ToString(const V& value);\r\n\r\n\t\tnamespace detail\r\n\t\t{\r\n\t\t\ttemplate\r\n\t\t\tclass IsStreamWritable\r\n\t\t\t{\r\n\t\t\t\ttemplate\r\n\t\t\t\tstatic auto test(int) -> decltype(std::declval() << std::declval(), std::true_type());\r\n\r\n\t\t\t\ttemplate static auto test(...) -> std::false_type;\r\n\r\n\t\t\tpublic:\r\n\t\t\t\ttypedef decltype(test(0)) Result;\r\n\t\t\t};\r\n\r\n\t\t\ttemplate struct ParseNonIterableToString\r\n\t\t\t{\r\n\t\t\t\tinline std::string operator()(const V& value) const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn ToString(value, IsStreamWritable::Result());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tinline std::string ToString(const V& value, std::true_type) const\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::stringstream stream;\r\n\t\t\t\t\tstream << value;\r\n\t\t\t\t\treturn stream.str();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tinline std::string ToString(const V& value, std::false_type) const\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::stringstream stream;\r\n\t\t\t\t\tstream << \"[\" << typeid(V).name() << \"]\";\r\n\t\t\t\t\treturn stream.str();\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\ttemplate struct ParseIterableToString\r\n\t\t\t{\r\n\t\t\t\tinline std::string operator()(const V& value) const\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::stringstream stream;\r\n\t\t\t\t\tstream << \"{ \";\r\n\t\t\t\t\tfor (const auto& arg : value)\r\n\t\t\t\t\t\tstream << ToString(arg) << \" \";\r\n\t\t\t\t\tstream << \"}\";\r\n\t\t\t\t\treturn stream.str();\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t\/*! \\brief Can be partially specialised to parse non-streamables to strings without making the type streamable *\/\r\n\t\ttemplate struct ParseToString\r\n\t\t{\r\n\t\t\tinline std::string operator()(const V& value) const\r\n\t\t\t{\r\n\t\t\t\treturn typename Meta::IfElseTypes< Meta::IsIterableContainer::value, detail::ParseIterableToString, detail::ParseNonIterableToString >::type()(value);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate<> struct ParseToString\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::string& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\r\n\t\ttemplate<> struct ParseToString< void* >\r\n\t\t{\r\n\t\t\tinline std::string operator()(void* value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"void_pointer:\") + detail::ParseNonIterableToString()(value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\t\ttemplate struct ParseToString< T* >\r\n\t\t{\r\n\t\t\tinline std::string operator()(T* value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"pointer:\") + ParseToString()(*value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate struct ParseToString< std::unique_ptr >\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::unique_ptr& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"unique_ptr:\") + ParseToString()(*value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate<> struct ParseToString< std::shared_ptr >\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::shared_ptr& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"shared_ptr:\") + detail::ParseNonIterableToString()(value.get()) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\t\ttemplate struct ParseToString< std::shared_ptr >\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::shared_ptr& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"shared_ptr:\") + ParseToString()(*value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate inline std::string ToString(const V& value)\r\n\t\t{\r\n\t\t\treturn ParseToString()(value);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif \/\/ UNITTEST11_UTILITY_TOSTRING_HPP\r\nFixed in gcc#ifndef UNITTEST11_UTILITY_TOSTRING_HPP\r\n#define UNITTEST11_UTILITY_TOSTRING_HPP\r\n\r\n#include \"Meta\/IsIterableContainer.hpp\"\r\n#include \"Meta\/IfElseTypes.hpp\"\r\n\r\n#include \r\n#include \r\n#include \r\n\r\nnamespace ut11\r\n{\r\n\tnamespace utility\r\n\t{\r\n\t\ttemplate inline std::string ToString(const V& value);\r\n\r\n\t\tnamespace detail\r\n\t\t{\r\n\t\t\ttemplate\r\n\t\t\tclass IsStreamWritable\r\n\t\t\t{\r\n\t\t\t\ttemplate\r\n\t\t\t\tstatic auto test(int) -> decltype(std::declval() << std::declval(), std::true_type());\r\n\r\n\t\t\t\ttemplate static auto test(...) -> std::false_type;\r\n\r\n\t\t\tpublic:\r\n\t\t\t\ttypedef decltype(test(0)) Result;\r\n\t\t\t};\r\n\r\n\t\t\ttemplate struct ParseNonIterableToString\r\n\t\t\t{\r\n\t\t\t\tinline std::string operator()(const V& value) const\r\n\t\t\t\t{\r\n\t\t\t\t\treturn ToString(value, typename IsStreamWritable::Result());\r\n\t\t\t\t}\r\n\r\n\t\t\t\tinline std::string ToString(const V& value, std::true_type) const\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::stringstream stream;\r\n\t\t\t\t\tstream << value;\r\n\t\t\t\t\treturn stream.str();\r\n\t\t\t\t}\r\n\r\n\t\t\t\tinline std::string ToString(const V& value, std::false_type) const\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::stringstream stream;\r\n\t\t\t\t\tstream << \"[\" << typeid(V).name() << \"]\";\r\n\t\t\t\t\treturn stream.str();\r\n\t\t\t\t}\r\n\t\t\t};\r\n\r\n\t\t\ttemplate struct ParseIterableToString\r\n\t\t\t{\r\n\t\t\t\tinline std::string operator()(const V& value) const\r\n\t\t\t\t{\r\n\t\t\t\t\tstd::stringstream stream;\r\n\t\t\t\t\tstream << \"{ \";\r\n\t\t\t\t\tfor (const auto& arg : value)\r\n\t\t\t\t\t\tstream << ToString(arg) << \" \";\r\n\t\t\t\t\tstream << \"}\";\r\n\t\t\t\t\treturn stream.str();\r\n\t\t\t\t}\r\n\t\t\t};\r\n\t\t}\r\n\r\n\t\t\/*! \\brief Can be partially specialised to parse non-streamables to strings without making the type streamable *\/\r\n\t\ttemplate struct ParseToString\r\n\t\t{\r\n\t\t\tinline std::string operator()(const V& value) const\r\n\t\t\t{\r\n\t\t\t\treturn typename Meta::IfElseTypes< Meta::IsIterableContainer::value, detail::ParseIterableToString, detail::ParseNonIterableToString >::type()(value);\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate<> struct ParseToString\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::string& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value;\r\n\t\t\t}\r\n\t\t};\r\n\r\n\r\n\t\ttemplate<> struct ParseToString< void* >\r\n\t\t{\r\n\t\t\tinline std::string operator()(void* value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"void_pointer:\") + detail::ParseNonIterableToString()(value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\t\ttemplate struct ParseToString< T* >\r\n\t\t{\r\n\t\t\tinline std::string operator()(T* value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"pointer:\") + ParseToString()(*value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate struct ParseToString< std::unique_ptr >\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::unique_ptr& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"unique_ptr:\") + ParseToString()(*value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate<> struct ParseToString< std::shared_ptr >\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::shared_ptr& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"shared_ptr:\") + detail::ParseNonIterableToString()(value.get()) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\t\ttemplate struct ParseToString< std::shared_ptr >\r\n\t\t{\r\n\t\t\tinline std::string operator()(const std::shared_ptr& value) const\r\n\t\t\t{\r\n\t\t\t\treturn value ? std::string(\"shared_ptr:\") + ParseToString()(*value) : \"nullptr\";\r\n\t\t\t}\r\n\t\t};\r\n\r\n\t\ttemplate inline std::string ToString(const V& value)\r\n\t\t{\r\n\t\t\treturn ParseToString()(value);\r\n\t\t}\r\n\t}\r\n}\r\n\r\n#endif \/\/ UNITTEST11_UTILITY_TOSTRING_HPP\r\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Nektar;\n\nint main(int argc, char *argv[])\n{\n if(argc != 2)\n {\n cerr << \"Usage: XmlToVtk meshfile\" << endl;\n exit(1);\n } \n \n LibUtilities::SessionReaderSharedPtr vSession\n = LibUtilities::SessionReader::CreateInstance(argc, argv);\n\n \/\/----------------------------------------------\n \/\/ Read in mesh from input file\n string meshfile(argv[argc-1]);\n SpatialDomains::MeshGraphSharedPtr graphShPt = \n SpatialDomains::MeshGraph::Read(meshfile);\n \/\/----------------------------------------------\n\n \/\/----------------------------------------------\n \/\/ Set up Expansion information\n SpatialDomains::ExpansionMap emap = graphShPt->GetExpansions();\n SpatialDomains::ExpansionMapIter it;\n \n for (it = emap.begin(); it != emap.end(); ++it)\n {\n for (int i = 0; i < it->second->m_basisKeyVector.size(); ++i)\n {\n LibUtilities::BasisKey tmp1 = it->second->m_basisKeyVector[i];\n LibUtilities::PointsKey tmp2 = tmp1.GetPointsKey();\n it->second->m_basisKeyVector[i] = LibUtilities::BasisKey(\n tmp1.GetBasisType(), tmp1.GetNumModes(),\n LibUtilities::PointsKey(tmp2.GetNumPoints(),\n LibUtilities::eGaussLobattoLegendre));\n }\n }\n \/\/----------------------------------------------\n \n \/\/----------------------------------------------\n \/\/ Define Expansion\n int expdim = graphShPt->GetMeshDimension();\n Array Exp(1);\n\n switch(expdim)\n {\n case 1:\n {\n MultiRegions::ExpList1DSharedPtr Exp1D;\n Exp1D = MemoryManager\n ::AllocateSharedPtr(vSession,graphShPt);\n Exp[0] = Exp1D;\n break;\n }\n case 2:\n {\n MultiRegions::ExpList2DSharedPtr Exp2D;\n Exp2D = MemoryManager\n ::AllocateSharedPtr(vSession,graphShPt);\n Exp[0] = Exp2D;\n break;\n }\n case 3:\n {\n MultiRegions::ExpList3DSharedPtr Exp3D;\n Exp3D = MemoryManager\n ::AllocateSharedPtr(vSession,graphShPt);\n Exp[0] = Exp3D;\n break;\n }\n default:\n {\n ASSERTL0(false,\"Expansion dimension not recognised\");\n break;\n }\n }\n \/\/----------------------------------------------\n \n \/\/----------------------------------------------\n \/\/ Write out VTK file.\n string outname(strtok(argv[argc-1],\".\"));\n outname += \".vtu\";\n ofstream outfile(outname.c_str());\n\n Exp[0]->WriteVtkHeader(outfile);\n \/\/ For each field write header and footer, since there is no field data.\n for(int i = 0; i < Exp[0]->GetExpSize(); ++i)\n {\n Exp[0]->WriteVtkPieceHeader(outfile,i);\n Exp[0]->WriteVtkPieceFooter(outfile,i);\n }\n Exp[0]->WriteVtkFooter(outfile);\n \/\/----------------------------------------------\n \n return 0;\n}\n\nChanged XmlToVtk points distribution to PolyEvenlySpaced, same number of quadrature points in each spatial direction.#include \n#include \n\n#include \n#include \n#include \n#include \n\nusing namespace Nektar;\n\nint main(int argc, char *argv[])\n{\n if(argc != 2)\n {\n cerr << \"Usage: XmlToVtk meshfile\" << endl;\n exit(1);\n } \n \n LibUtilities::SessionReaderSharedPtr vSession\n = LibUtilities::SessionReader::CreateInstance(argc, argv);\n\n \/\/----------------------------------------------\n \/\/ Read in mesh from input file\n string meshfile(argv[argc-1]);\n SpatialDomains::MeshGraphSharedPtr graphShPt = \n SpatialDomains::MeshGraph::Read(meshfile);\n \/\/----------------------------------------------\n\n \/\/----------------------------------------------\n \/\/ Set up Expansion information\n SpatialDomains::ExpansionMap emap = graphShPt->GetExpansions();\n SpatialDomains::ExpansionMapIter it;\n \n for (it = emap.begin(); it != emap.end(); ++it)\n {\n for (int i = 0; i < it->second->m_basisKeyVector.size(); ++i)\n {\n LibUtilities::BasisKey tmp1 = it->second->m_basisKeyVector[i];\n LibUtilities::PointsKey tmp2 = tmp1.GetPointsKey();\n it->second->m_basisKeyVector[i] = LibUtilities::BasisKey(\n tmp1.GetBasisType(), tmp1.GetNumModes(),\n LibUtilities::PointsKey(tmp1.GetNumModes(),\n LibUtilities::ePolyEvenlySpaced));\n }\n }\n \/\/----------------------------------------------\n \n \/\/----------------------------------------------\n \/\/ Define Expansion\n int expdim = graphShPt->GetMeshDimension();\n Array Exp(1);\n\n switch(expdim)\n {\n case 1:\n {\n MultiRegions::ExpList1DSharedPtr Exp1D;\n Exp1D = MemoryManager\n ::AllocateSharedPtr(vSession,graphShPt);\n Exp[0] = Exp1D;\n break;\n }\n case 2:\n {\n MultiRegions::ExpList2DSharedPtr Exp2D;\n Exp2D = MemoryManager\n ::AllocateSharedPtr(vSession,graphShPt);\n Exp[0] = Exp2D;\n break;\n }\n case 3:\n {\n MultiRegions::ExpList3DSharedPtr Exp3D;\n Exp3D = MemoryManager\n ::AllocateSharedPtr(vSession,graphShPt);\n Exp[0] = Exp3D;\n break;\n }\n default:\n {\n ASSERTL0(false,\"Expansion dimension not recognised\");\n break;\n }\n }\n \/\/----------------------------------------------\n \n \/\/----------------------------------------------\n \/\/ Write out VTK file.\n string outname(strtok(argv[argc-1],\".\"));\n outname += \".vtu\";\n ofstream outfile(outname.c_str());\n\n Exp[0]->WriteVtkHeader(outfile);\n \/\/ For each field write header and footer, since there is no field data.\n for(int i = 0; i < Exp[0]->GetExpSize(); ++i)\n {\n Exp[0]->WriteVtkPieceHeader(outfile,i);\n Exp[0]->WriteVtkPieceFooter(outfile,i);\n }\n Exp[0]->WriteVtkFooter(outfile);\n \/\/----------------------------------------------\n \n return 0;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \"grid.h\"\n#include \"cell.h\"\n#include \n#include \n\n\nusing namespace sf;\n\nint main()\n{\n\t\/\/Calling grid here\n\t\/\/this will be 1027 \/ 32 which is defend in grid.cpp \n\tint gridWidth = grid::windowWidth \/ grid::x;\n\t\/\/this will be 720 \/ 32 which also defend in grid.cpp\n\tint gridHeight = grid::windowHeight \/ grid::y;\n\t\/\/Calling cell setup \n\tcell::Setup(gridWidth, gridHeight);\n\tint drawingCells[32][32];\n\t\/\/starting with the window \n\tsf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), \"Welcome to Mohanad's Game Of Life\");\n\tbool Gamestart;\n\n\twhile (window.isOpen())\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (event.type == Event::KeyPressed) {\n\t\t\t\tswitch (event.key.code) {\n\t\t\t\tcase Keyboard::Escape:\n\t\t\t\t\tprintf(\"Bye Bye and see you next time \\n\");\n\t\t\t\t\texit(0);\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (event.type == sf::Event::MouseButtonPressed) {\n\n\t\t\t\tint clickX = (event.mouseButton.x \/ grid::x);\n\t\t\t\tint clickY = (event.mouseButton.y \/ grid::y);\n\t\t\t\tdrawingCells[clickY][clickX] = drawingCells[clickY][clickX] == 1 ? 0.5 : 1;\n\n\t\t\t\t\/\/checking is the mouse clicked or not\n\t\t\t\tprintf(\"mouse clicked \\n\");\n\t\t\t}\n\t\t\t\/\/this will run the game \n\t\t\tif (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)\n\t\t\t{\n\n\t\t\t\tif (Gamestart = true) {\n\t\t\t\t\tfor (size_t row = 0; row < gridHeight; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t(Gamestart = false);\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\n\t\t\t\t\t\t\/\/\tgrid::logicOfCurrentGeneration(drawingCells);\n\t\t\t\t\t\tprintf(\"Game has start enjoy \\n\");\n\t\t\t\t\t}\n\n\n\t\t\t\t\twindow.clear();\n\n\t\t\t\t\tfor (size_t row = 0; row < grid::x; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t column = 0; column < grid::y; column++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint state = drawingCells[row][column];\n\t\t\t\t\t\t\tif (state == 1) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::White);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (state == 0) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::Blue);\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcell::Setposition((column * gridWidth), (row * gridHeight));\n\t\t\t\t\t\t\twindow.draw(cell::target);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\twindow.display();\n\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t}\n\t}\n}Commit#include \n#include \"grid.h\"\n#include \"cell.h\"\n#include \n#include \n\n\nusing namespace sf;\n\nint main()\n{\n\t\/\/Calling grid here\n\t\/\/this will be 1027 \/ 32 which is defend in grid.cpp \n\tint gridWidth = grid::windowWidth \/ grid::x;\n\t\/\/this will be 720 \/ 32 which also defend in grid.cpp\n\tint gridHeight = grid::windowHeight \/ grid::y;\n\t\/\/Calling cell setup \n\tcell::Setup(gridWidth, gridHeight);\n\tint drawingCells[32][32];\n\t\/\/starting with the window \n\tsf::RenderWindow window(sf::VideoMode(grid::windowWidth, grid::windowHeight), \"Welcome to Mohanad's Game Of Life\");\n\tbool Gamestart;\n\n\twhile (window.isOpen())\n\t{\n\t\tsf::Event event;\n\t\twhile (window.pollEvent(event))\n\t\t{\n\t\t\tif (event.type == sf::Event::Closed)\n\t\t\t\twindow.close();\n\t\t\tif (event.type == Event::KeyPressed) {\n\t\t\t\tswitch (event.key.code) {\n\t\t\t\tcase Keyboard::Escape:\n\t\t\t\t\tprintf(\"Bye Bye and see you next time \\n\");\n\t\t\t\t\texit(0);\n\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (event.type == sf::Event::MouseButtonPressed) {\n\n\t\t\t\tint clickX = (event.mouseButton.x \/ grid::x);\n\t\t\t\tint clickY = (event.mouseButton.y \/ grid::y);\n\t\t\t\tdrawingCells[clickY][clickX] = drawingCells[clickY][clickX] == 1 ? 0.5 : 1;\n\n\t\t\t\t\/\/checking is the mouse clicked or not\n\t\t\t\tprintf(\"mouse clicked \\n\");\n\t\t\t}\n\t\t\t\/\/this will run the game \n\t\t\tif (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::R)\n\t\t\t{\n\n\t\t\t\tif (Gamestart = true) {\n\t\t\t\t\tfor (size_t row = 0; row < gridHeight; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tint count = 0;\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 - 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 + 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32 + 1]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif (drawingCells[32 - 1][32]) {\n\t\t\t\t\t\t\t++count;\n\t\t\t\t\t\t}\n\t\t\t\t\t\telse {\n\t\t\t\t\t\t\t(Gamestart = false);\n\t\t\t\t\t\t\n\t\t\t\t\t\t}\n\t\t\t\t\t\t\n\n\t\t\t\t\t\tprintf(\"Start \\n\");\n\t\t\t\t\t}\n\n\n\t\t\t\t\twindow.clear();\n\n\t\t\t\t\tfor (size_t row = 0; row < grid::x; row++)\n\t\t\t\t\t{\n\t\t\t\t\t\tfor (size_t column = 0; column < grid::y; column++)\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tint state = drawingCells[row][column];\n\t\t\t\t\t\t\tif (state == 1) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::White);\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse if (state == 0) {\n\t\t\t\t\t\t\t\tcell::Setcolor(Color::Blue);\n\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\tcell::Setposition((column * gridWidth), (row * gridHeight));\n\t\t\t\t\t\t\twindow.draw(cell::target);\n\n\t\t\t\t\t\t}\n\n\t\t\t\t\t}\n\t\t\t\t\twindow.display();\n\n\t\t\t\t}\n\n\n\t\t\t}\n\n\t\t}\n\t}\n}<|endoftext|>"} {"text":"\/**\n * @file nullable_attribute.cc\n *\n * @section LICENSE\n *\n * The MIT License\n *\n * @copyright Copyright (c) 2020-2021 TileDB, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * When run, this program will create a simple 2D dense array with one fixed\n * nullable attribute and one var-sized nullable attribute, write some data\n * to it, and read the data back on both attributes.\n *\/\n\n#include \n#include \n\nusing namespace tiledb;\n\n\/\/ Name of array.\nstd::string array_name(\"nullable_attributes_array\");\n\nvoid create_array() {\n \/\/ Create a TileDB context\n Context ctx;\n\n \/\/ The array will be 2x2 with dimensions \"rows\" and \"cols\", with domain [1,2]\n Domain domain(ctx);\n domain.add_dimension(Dimension::create(ctx, \"rows\", {{1, 2}}, 2))\n .add_dimension(Dimension::create(ctx, \"cols\", {{1, 2}}, 2));\n\n \/\/ The array will be dense\n ArraySchema schema(ctx, TILEDB_DENSE);\n schema.set_domain(domain).set_order({{TILEDB_ROW_MAJOR, TILEDB_ROW_MAJOR}});\n\n \/\/ Create two attributes \"a1\" and \"a2\", the first fixed and the second\n \/\/ variable-sized.\n Attribute a1 = Attribute::create(ctx, \"a1\");\n Attribute a2 = Attribute::create>(ctx, \"a2\");\n\n \/\/ Set both attributes as nullable\n a1.set_nullable(true);\n a2.set_nullable(true);\n\n schema.add_attribute(a1);\n schema.add_attribute(a2);\n\n \/\/ Create the (empty) array on disk.\n Array::create(array_name, schema);\n}\n\nvoid write_array() {\n Context ctx;\n\n \/\/ Prepare some data for the array\n std::vector a1_data = {100, 200, 300, 400};\n std::vector a2_data = {10, 10, 20, 30, 30, 30, 40, 40};\n std::vector a2_el_off = {0, 2, 3, 6};\n std::vector a2_off;\n for (auto e : a2_el_off)\n a2_off.push_back(e * sizeof(int));\n\n \/\/ Open the array for writing and create the query\n Array array(ctx, array_name, TILEDB_WRITE);\n Query query(ctx, array);\n query.set_layout(TILEDB_ROW_MAJOR);\n\n \/\/ Specify the validity buffer for each attribute\n std::vector a1_validity_buf = {1, 0, 0, 1};\n std::vector a2_validity_buf = {0, 1, 1, 0};\n\n \/\/ Set the query buffers specifying the validity for each data\n query.set_buffer_nullable(\"a1\", a1_data, a1_validity_buf)\n .set_buffer_nullable(\"a2\", a2_off, a2_data, a2_validity_buf);\n\n \/\/ Perform the write and close the array.\n query.submit();\n array.close();\n}\n\nvoid read_array() {\n Context ctx;\n\n \/\/ Prepare the array for reading\n Array array(ctx, array_name, TILEDB_READ);\n\n \/\/ Prepare the vectors that will hold the results\n std::vector a1_data(4);\n std::vector a1_validity_buf(a1_data.size());\n\n std::vector a2_data(8);\n std::vector a2_off(4);\n std::vector a2_validity_buf(a2_off.size());\n\n \/\/ Prepare and submit the query, and close the array\n Query query(ctx, array);\n query.set_layout(TILEDB_ROW_MAJOR);\n\n \/\/ Read the full array\n const std::vector subarray_full = {1, 2, 1, 2};\n query.set_subarray(subarray_full);\n\n \/\/ Set the query buffers specifying the validity for each data\n query.set_buffer_nullable(\"a1\", a1_data, a1_validity_buf)\n .set_buffer_nullable(\"a2\", a2_off, a2_data, a2_validity_buf);\n query.submit();\n array.close();\n\n \/\/ Print out the data we read for each nullable atttribute\n unsigned long i = 0;\n std::cout << \"a1: \" << std::endl;\n for (i = 0; i < 4; ++i) {\n std::cout << (a1_validity_buf[i] > 0 ? std::to_string(a1_data[i]) : \"NULL\");\n std::cout << \" \";\n }\n std::cout << std::endl;\n\n std::cout << \"a2: \" << std::endl;\n for (i = 0; i < 4; ++i) {\n if (a2_validity_buf[i] > 0) {\n std::cout << \"{ \";\n std::cout << std::to_string(a2_data[i * 2]);\n std::cout << \", \";\n std::cout << std::to_string(a2_data[i * 2 + 1]);\n std::cout << \" }\";\n } else {\n std::cout << \"{ NULL }\";\n }\n std::cout << \" \";\n }\n std::cout << std::endl;\n}\n\nint main() {\n Context ctx;\n if (Object::object(ctx, array_name).type() == Object::Type::Array) {\n tiledb::Object::remove(ctx, array_name);\n }\n create_array();\n write_array();\n read_array();\n\n return 0;\n}\nAdd nullable string to nullable attribute example\/**\n * @file nullable_attribute.cc\n *\n * @section LICENSE\n *\n * The MIT License\n *\n * @copyright Copyright (c) 2020-2021 TileDB, Inc.\n *\n * Permission is hereby granted, free of charge, to any person obtaining a copy\n * of this software and associated documentation files (the \"Software\"), to deal\n * in the Software without restriction, including without limitation the rights\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\n * copies of the Software, and to permit persons to whom the Software is\n * furnished to do so, subject to the following conditions:\n *\n * The above copyright notice and this permission notice shall be included in\n * all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n * THE SOFTWARE.\n *\n * @section DESCRIPTION\n *\n * When run, this program will create a simple 2D dense array with one fixed\n * nullable attribute and one var-sized nullable attribute, write some data\n * to it, and read the data back on both attributes.\n *\/\n\n#include \n#include \n\nusing namespace tiledb;\n\n\/\/ Name of array.\nstd::string array_name(\"nullable_attributes_array\");\n\nvoid create_array() {\n \/\/ Create a TileDB context\n Context ctx;\n\n \/\/ The array will be 2x2 with dimensions \"rows\" and \"cols\", with domain [1,2]\n Domain domain(ctx);\n domain.add_dimension(Dimension::create(ctx, \"rows\", {{1, 2}}, 2))\n .add_dimension(Dimension::create(ctx, \"cols\", {{1, 2}}, 2));\n\n \/\/ The array will be dense\n ArraySchema schema(ctx, TILEDB_DENSE);\n schema.set_domain(domain).set_order({{TILEDB_ROW_MAJOR, TILEDB_ROW_MAJOR}});\n\n \/\/ Create two attributes \"a1\" and \"a2\", the first fixed and the second\n \/\/ variable-sized.\n Attribute a1 = Attribute::create(ctx, \"a1\");\n Attribute a2 = Attribute::create>(ctx, \"a2\");\n auto a3 = Attribute(ctx, \"a3\", TILEDB_STRING_UTF8);\n a3.set_cell_val_num(TILEDB_VAR_NUM);\n\n \/\/ Set both attributes as nullable\n a1.set_nullable(true);\n a2.set_nullable(true);\n a3.set_nullable(true);\n\n schema.add_attribute(a1);\n schema.add_attribute(a2);\n schema.add_attribute(a3);\n\n \/\/ Create the (empty) array on disk.\n Array::create(array_name, schema);\n}\n\nvoid write_array() {\n Context ctx;\n\n \/\/ Prepare some data for the array\n std::vector a1_data = {100, 200, 300, 400};\n std::vector a2_data = {10, 10, 20, 30, 30, 30, 40, 40};\n std::vector a2_el_off = {0, 2, 3, 6};\n std::vector a2_off;\n for (auto e : a2_el_off)\n a2_off.push_back(e * sizeof(int));\n\n const char a3_data_char[] = \"abcdewxyz\";\n std::vector a3_data(a3_data_char, a3_data_char + 9);\n std::vector a3_el_off = {0, 3, 4, 5};\n std::vector a3_off;\n for (auto e : a3_el_off)\n a3_off.push_back(e * sizeof(char));\n\n \/\/ Open the array for writing and create the query\n Array array(ctx, array_name, TILEDB_WRITE);\n Query query(ctx, array);\n query.set_layout(TILEDB_ROW_MAJOR);\n\n \/\/ Specify the validity buffer for each attribute\n std::vector a1_validity_buf = {1, 0, 0, 1};\n std::vector a2_validity_buf = {0, 1, 1, 0};\n std::vector a3_validity_buf = {1, 0, 0, 1};\n\n \/\/ Set the query buffers specifying the validity for each data\n query.set_buffer_nullable(\"a1\", a1_data, a1_validity_buf)\n .set_buffer_nullable(\"a2\", a2_off, a2_data, a2_validity_buf)\n .set_buffer_nullable(\"a3\", a3_off, a3_data, a3_validity_buf);\n\n \/\/ Perform the write and close the array.\n query.submit();\n array.close();\n}\n\nvoid read_array() {\n Context ctx;\n\n \/\/ Prepare the array for reading\n Array array(ctx, array_name, TILEDB_READ);\n\n \/\/ Prepare the vectors that will hold the results\n std::vector a1_data(4);\n std::vector a1_validity_buf(a1_data.size());\n\n std::vector a2_data(8);\n std::vector a2_off(4);\n std::vector a2_validity_buf(a2_off.size());\n\n std::vector a3_data(1000);\n std::vector a3_off(10);\n std::vector a3_validity_buf(a3_off.size());\n\n \/\/ Prepare and submit the query, and close the array\n Query query(ctx, array);\n query.set_layout(TILEDB_ROW_MAJOR);\n\n \/\/ Read the full array\n const std::vector subarray_full = {1, 2, 1, 2};\n query.set_subarray(subarray_full);\n\n \/\/ Set the query buffers specifying the validity for each data\n query.set_buffer_nullable(\"a1\", a1_data, a1_validity_buf)\n .set_buffer_nullable(\"a2\", a2_off, a2_data, a2_validity_buf)\n .set_buffer_nullable(\"a3\", a3_off, a3_data, a3_validity_buf);\n query.submit();\n\n if (query.query_status() == tiledb::Query::Status::INCOMPLETE) {\n std::cerr << \"** Query did not complete! **\" << std::endl;\n }\n\n auto result_elements = query.result_buffer_elements();\n array.close();\n\n \/\/ Unpack a3 result to a vector of strings\n std::vector a3_results;\n auto a3_result_elements = result_elements[\"a3\"];\n uint64_t a3_offsets_num = a3_result_elements.first;\n uint64_t a3_data_num = a3_result_elements.second;\n\n uint64_t start = 0;\n uint64_t end = 0;\n\n for (size_t i = 0; i < a3_offsets_num; i++) {\n start = a3_off[i];\n end = (i == a3_offsets_num - 1) ? a3_data_num : a3_off[i + 1];\n a3_results.push_back(\n std::string(a3_data.data() + start, a3_data.data() + end));\n }\n\n \/\/ Print out the data we read for each nullable atttribute\n unsigned long i = 0;\n std::cout << \"a1: \" << std::endl;\n for (i = 0; i < 4; ++i) {\n std::cout << (a1_validity_buf[i] > 0 ? std::to_string(a1_data[i]) : \"NULL\");\n std::cout << \" \";\n }\n std::cout << std::endl;\n\n std::cout << \"a2: \" << std::endl;\n for (i = 0; i < 4; ++i) {\n if (a2_validity_buf[i] > 0) {\n std::cout << \"{ \";\n std::cout << std::to_string(a2_data[i * 2]);\n std::cout << \", \";\n std::cout << std::to_string(a2_data[i * 2 + 1]);\n std::cout << \" }\";\n } else {\n std::cout << \"{ NULL }\";\n }\n std::cout << \" \";\n }\n\n std::cout << std::endl << \"a3: \" << std::endl;\n for (i = 0; i < 4; ++i) {\n if (a3_validity_buf[i] > 0)\n std::cout << \" \" << a3_results[i] << std::endl;\n else\n std::cout << \" \"\n << \"NULL\" << std::endl;\n }\n\n std::cout << std::endl;\n}\n\nint main() {\n Context ctx;\n if (Object::object(ctx, array_name).type() == Object::Type::Array) {\n tiledb::Object::remove(ctx, array_name);\n }\n create_array();\n write_array();\n read_array();\n\n return 0;\n}\n<|endoftext|>"} {"text":"\n#include \"UnionLowestLevelSimpleScanOperator.h\"\n\nnamespace srch2 {\nnamespace instantsearch {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ merge when lists are sorted by ID Only top K\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nUnionLowestLevelSimpleScanOperator::UnionLowestLevelSimpleScanOperator() {\n\tqueryEvaluator = NULL;\n}\n\nUnionLowestLevelSimpleScanOperator::~UnionLowestLevelSimpleScanOperator(){\n\t\/\/TODO\n}\nbool UnionLowestLevelSimpleScanOperator::open(QueryEvaluatorInternal * queryEvaluator, PhysicalPlanExecutionParameters & params){\n\t\/\/ first save the pointer to QueryEvaluator\n\tthis->queryEvaluator = queryEvaluator;\n\n\t\/\/ 1. get the pointer to logical plan node\n\tLogicalPlanNode * logicalPlanNode = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode();\n\t\/\/ 2. Get the Term object\n\tTerm * term = NULL;\n\tif(params.isFuzzy){\n\t\tterm = logicalPlanNode->fuzzyTerm;\n\t}else{\n\t\tterm = logicalPlanNode->exactTerm;\n\t}\n\t\/\/ 3. Get the ActiveNodeSet from the logical plan\n\tPrefixActiveNodeSet * activeNodeSet = logicalPlanNode->stats->getActiveNodeSetForEstimation(params.isFuzzy);\n\n\t\/\/ 4. Create the iterator and save it as a member of the class for future calls to getNext\n\tif (term->getTermType() == TERM_TYPE_PREFIX) { \/\/ prefix term\n for (LeafNodeSetIterator iter (activeNodeSet, term->getThreshold()); !iter.isDone(); iter.next()) {\n TrieNodePointer leafNode;\n TrieNodePointer prefixNode;\n unsigned distance;\n iter.getItem(prefixNode, leafNode, distance);\n \/\/ get inverted list pointer and save it\n shared_ptr > invertedListReadView;\n this->queryEvaluator->getInvertedIndex()->\n \t\tgetInvertedListReadView(leafNode->getInvertedListOffset() , invertedListReadView);\n this->invertedLists.push_back(invertedListReadView);\n this->invertedListPrefixes.push_back(prefixNode);\n this->invertedListLeafNodes.push_back(leafNode);\n this->invertedListDistances.push_back(distance);\n this->invertedListIDs.push_back(leafNode->getInvertedListOffset());\n }\n\t}else{ \/\/ complete term\n for (ActiveNodeSetIterator iter(activeNodeSet, term->getThreshold()); !iter.isDone(); iter.next()) {\n TrieNodePointer trieNode;\n unsigned distance;\n iter.getItem(trieNode, distance);\n distance = activeNodeSet->getEditdistanceofPrefix(trieNode);\n depthInitializeSimpleScanOperator(trieNode, trieNode, distance, term->getThreshold());\n }\n\t}\n\tthis->invertedListOffset = 0;\n\tthis->cursorOnInvertedList = 0;\n\n}\nPhysicalPlanRecordItem * UnionLowestLevelSimpleScanOperator::getNext(const PhysicalPlanExecutionParameters & params) {\n\n\tif(this->invertedListOffset >= this->invertedLists.size()){\n\t\treturn NULL;\n\t}\n\t\/\/ we dont have any list with size zero\n\tASSERT(this->cursorOnInvertedList < this->invertedLists.at(this->invertedListOffset)->size());\n\n\t\/\/ 1. get the pointer to logical plan node\n\tLogicalPlanNode * logicalPlanNode = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode();\n\t\/\/ 2. Get the Term object\n\tTerm * term = NULL;\n\tif(params.isFuzzy){\n\t\tterm = logicalPlanNode->fuzzyTerm;\n\t}else{\n\t\tterm = logicalPlanNode->exactTerm;\n\t}\n\n\t\/\/ find the next record and check the its validity\n\tunsigned recordID = this->invertedLists.at(this->invertedListOffset)->at(this->cursorOnInvertedList);\n\n\tunsigned recordOffset =\n\t\t\tthis->queryEvaluator->getInvertedIndex()->getKeywordOffset(recordID, this->invertedListIDs.at(this->invertedListOffset));\n\n bool foundValidHit = 0;\n float termRecordStaticScore = 0;\n unsigned termAttributeBitmap = 0;\n while (1) {\n if (this->queryEvaluator->getInvertedIndex()->isValidTermPositionHit(recordID, recordOffset,\n term->getAttributeToFilterTermHits(), termAttributeBitmap,\n termRecordStaticScore) ) {\n foundValidHit = 1;\n break;\n }\n this->cursorOnInvertedList ++;\n if (this->cursorOnInvertedList < this->invertedLists.at(this->invertedListOffset)->size()) {\n \trecordID = this->invertedLists.at(this->invertedListOffset)->at(this->cursorOnInvertedList);\n \/\/ calculate record offset online\n \trecordOffset =\n \t\t\t\tthis->queryEvaluator->getInvertedIndex()->getKeywordOffset(recordID, this->invertedListIDs.at(this->invertedListOffset));\n } else {\n \tthis->invertedListOffset ++;\n\t\t\tthis->cursorOnInvertedList = 0;\n \tif(this->invertedListOffset < this->invertedLists.size()){\n \t\trecordID = this->invertedLists.at(this->invertedListOffset)->at(this->cursorOnInvertedList);\n\t\t\t\t\/\/ calculate record offset online\n\t\t\t\trecordOffset =\n\t\t\t\t\t\t\tthis->queryEvaluator->getInvertedIndex()->getKeywordOffset(recordID, this->invertedListIDs.at(this->invertedListOffset));\n \t}else{\n \t\treturn NULL;\n \t}\n }\n }\n\n if(foundValidHit == 0){\n \treturn NULL;\n }\n\n\t\/\/ return the item.\n\tPhysicalPlanRecordItem * newItem = this->queryEvaluator->getPhysicalPlanRecordItemFactory()->createRecordItem();\n\t\/\/ record id\n\tnewItem->setRecordId(recordID);\n\t\/\/ edit distance\n\tvector editDistances;\n\teditDistances.push_back(this->invertedListDistances.at(this->cursorOnInvertedList));\n\tnewItem->setRecordMatchEditDistances(editDistances);\n\t\/\/ matching prefix\n\tvector matchingPrefixes;\n\tmatchingPrefixes.push_back(this->invertedListLeafNodes.at(this->cursorOnInvertedList)); \/\/ TODO this might be wrong\n\tnewItem->setRecordMatchingPrefixes(matchingPrefixes);\n\t\/\/ runtime score\n\tbool isPrefixMatch = this->invertedListPrefixes.at(this->invertedListOffset) ==\n\t\t\tthis->invertedListLeafNodes.at(this->invertedListOffset);\n\t\/\/\/\/\/\/ TODO ???????????????????????????? RANKER\n\tnewItem->setRecordRuntimeScore(\tDefaultTopKRanker::computeTermRecordRuntimeScore(termRecordStaticScore,\n this->invertedListDistances.at(this->invertedListOffset),\n term->getKeyword()->size(),\n isPrefixMatch,\n params.prefixMatchPenalty , term->getSimilarityBoost()));\n\t\/\/ static score\n\tnewItem->setRecordStaticScore(termRecordStaticScore);\n\t\/\/ attributeBitmap\n\tvector attributeBitmaps;\n\tattributeBitmaps.push_back(termAttributeBitmap);\n\tnewItem->setRecordMatchAttributeBitmaps(attributeBitmaps);\n\t\/\/ !!!! runtime score is not set here !!!! (we don't have it here and we don't need it here)\n\n\n\n\n\t\/\/ prepare for next call\n\tthis->cursorOnInvertedList ++;\n\tif(this->cursorOnInvertedList > this->invertedLists.at(this->invertedListOffset)->size()){\n\t\tthis->invertedListOffset ++;\n\t\tthis->cursorOnInvertedList = 0;\n\t}\n\n\n\treturn newItem;\n}\nbool UnionLowestLevelSimpleScanOperator::close(PhysicalPlanExecutionParameters & params){\n\n\tthis->invertedLists.clear();\n\tthis->invertedListDistances.clear();\n\tthis->invertedListLeafNodes.clear();\n\tthis->invertedListPrefixes.clear();\n\tthis->invertedListIDs.clear();\n\tthis->cursorOnInvertedList = 0;\n\tthis->invertedListOffset = 0;\n\tqueryEvaluator = NULL;\n\n}\nbool UnionLowestLevelSimpleScanOperator::verifyByRandomAccess(PhysicalPlanRandomAccessVerificationParameters & parameters) {\n\t\/\/TODO\n}\n\n\nvoid UnionLowestLevelSimpleScanOperator::depthInitializeSimpleScanOperator(\n\t\tconst TrieNode* trieNode, const TrieNode* prefixNode, unsigned distance, unsigned bound){\n if (trieNode->isTerminalNode())\n \/\/ get inverted list pointer and save it\n shared_ptr > invertedListReadView;\n this->queryEvaluator->getInvertedIndex()->\n \t\tgetInvertedListReadView(trieNode->getInvertedListOffset() , invertedListReadView);\n this->invertedLists.push_back(invertedListReadView);\n this->invertedListPrefixes.push_back(prefixNode);\n this->invertedListLeafNodes.push_back(trieNode);\n this->invertedListDistances.push_back(distance);\n this->invertedListIDs.push_back(trieNode->getInvertedListOffset() );\n if (distance < bound) {\n for (unsigned int childIterator = 0; childIterator < trieNode->getChildrenCount(); childIterator++) {\n const TrieNode *child = trieNode->getChild(childIterator);\n depthInitializeSimpleScanOperator(child, trieNode, distance+1, bound);\n }\n }\n}\n\n\/\/ The cost of open of a child is considered only once in the cost computation\n\/\/ of parent open function.\nunsigned UnionLowestLevelSimpleScanOptimizationOperator::getCostOfOpen(const PhysicalPlanExecutionParameters & params){\n\t\/\/TODO\n}\n\/\/ The cost of getNext of a child is multiplied by the estimated number of calls to this function\n\/\/ when the cost of parent is being calculated.\nunsigned UnionLowestLevelSimpleScanOptimizationOperator::getCostOfGetNext(const PhysicalPlanExecutionParameters & params) {\n\t\/\/TODO\n}\n\/\/ the cost of close of a child is only considered once since each node's close function is only called once.\nunsigned UnionLowestLevelSimpleScanOptimizationOperator::getCostOfClose(const PhysicalPlanExecutionParameters & params) {\n\t\/\/TODO\n}\nvoid UnionLowestLevelSimpleScanOptimizationOperator::getOutputProperties(IteratorProperties & prop){\n\t\/\/ no output property\n}\nvoid UnionLowestLevelSimpleScanOptimizationOperator::getRequiredInputProperties(IteratorProperties & prop){\n\t\/\/ the only requirement for input is to be directly connected to inverted index,\n\t\/\/ so since no operator outputs PhysicalPlanIteratorProperty_LowestLevel TVL will be pushed down to lowest level\n\tprop.addProperty(PhysicalPlanIteratorProperty_LowestLevel);\n}\nPhysicalPlanNodeType UnionLowestLevelSimpleScanOptimizationOperator::getType() {\n\treturn PhysicalPlanNode_UnionLowestLevelSimpleScanOperator;\n}\nbool UnionLowestLevelSimpleScanOptimizationOperator::validateChildren(){\n\tif(getChildrenCount() > 0){ \/\/ this operator cannot have any children\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n}\n}\nSimple Scan operator.\n#include \"UnionLowestLevelSimpleScanOperator.h\"\n#include \"operation\/QueryEvaluatorInternal.h\"\n\nnamespace srch2 {\nnamespace instantsearch {\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/ merge when lists are sorted by ID Only top K\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nUnionLowestLevelSimpleScanOperator::UnionLowestLevelSimpleScanOperator() {\n\tqueryEvaluator = NULL;\n}\n\nUnionLowestLevelSimpleScanOperator::~UnionLowestLevelSimpleScanOperator(){\n\t\/\/TODO\n}\nbool UnionLowestLevelSimpleScanOperator::open(QueryEvaluatorInternal * queryEvaluator, PhysicalPlanExecutionParameters & params){\n\t\/\/ first save the pointer to QueryEvaluator\n\tthis->queryEvaluator = queryEvaluator;\n\n\t\/\/ 1. get the pointer to logical plan node\n\tLogicalPlanNode * logicalPlanNode = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode();\n\t\/\/ 2. Get the Term object\n\tTerm * term = NULL;\n\tif(params.isFuzzy){\n\t\tterm = logicalPlanNode->fuzzyTerm;\n\t}else{\n\t\tterm = logicalPlanNode->exactTerm;\n\t}\n\t\/\/ 3. Get the ActiveNodeSet from the logical plan\n\tPrefixActiveNodeSet * activeNodeSet = logicalPlanNode->stats->getActiveNodeSetForEstimation(params.isFuzzy);\n\n\t\/\/ 4. Create the iterator and save it as a member of the class for future calls to getNext\n\tif (term->getTermType() == TERM_TYPE_PREFIX) { \/\/ prefix term\n for (LeafNodeSetIterator iter (activeNodeSet, term->getThreshold()); !iter.isDone(); iter.next()) {\n TrieNodePointer leafNode;\n TrieNodePointer prefixNode;\n unsigned distance;\n iter.getItem(prefixNode, leafNode, distance);\n \/\/ get inverted list pointer and save it\n shared_ptr > invertedListReadView;\n this->queryEvaluator->getInvertedIndex()->\n \t\tgetInvertedListReadView(leafNode->getInvertedListOffset() , invertedListReadView);\n this->invertedLists.push_back(invertedListReadView);\n this->invertedListPrefixes.push_back(prefixNode);\n this->invertedListLeafNodes.push_back(leafNode);\n this->invertedListDistances.push_back(distance);\n this->invertedListIDs.push_back(leafNode->getInvertedListOffset());\n }\n\t}else{ \/\/ complete term\n for (ActiveNodeSetIterator iter(activeNodeSet, term->getThreshold()); !iter.isDone(); iter.next()) {\n TrieNodePointer trieNode;\n unsigned distance;\n iter.getItem(trieNode, distance);\n distance = activeNodeSet->getEditdistanceofPrefix(trieNode);\n depthInitializeSimpleScanOperator(trieNode, trieNode, distance, term->getThreshold());\n }\n\t}\n\tthis->invertedListOffset = 0;\n\tthis->cursorOnInvertedList = 0;\n\n}\nPhysicalPlanRecordItem * UnionLowestLevelSimpleScanOperator::getNext(const PhysicalPlanExecutionParameters & params) {\n\n\tif(this->invertedListOffset >= this->invertedLists.size()){\n\t\treturn NULL;\n\t}\n\t\/\/ we dont have any list with size zero\n\tASSERT(this->cursorOnInvertedList < this->invertedLists.at(this->invertedListOffset)->size());\n\n\t\/\/ 1. get the pointer to logical plan node\n\tLogicalPlanNode * logicalPlanNode = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode();\n\t\/\/ 2. Get the Term object\n\tTerm * term = NULL;\n\tif(params.isFuzzy){\n\t\tterm = logicalPlanNode->fuzzyTerm;\n\t}else{\n\t\tterm = logicalPlanNode->exactTerm;\n\t}\n\n\t\/\/ find the next record and check the its validity\n\tunsigned recordID = this->invertedLists.at(this->invertedListOffset)->at(this->cursorOnInvertedList);\n\n\tunsigned recordOffset =\n\t\t\tthis->queryEvaluator->getInvertedIndex()->getKeywordOffset(recordID, this->invertedListIDs.at(this->invertedListOffset));\n\n bool foundValidHit = 0;\n float termRecordStaticScore = 0;\n unsigned termAttributeBitmap = 0;\n while (1) {\n if (this->queryEvaluator->getInvertedIndex()->isValidTermPositionHit(recordID, recordOffset,\n term->getAttributeToFilterTermHits(), termAttributeBitmap,\n termRecordStaticScore) ) {\n foundValidHit = 1;\n break;\n }\n this->cursorOnInvertedList ++;\n if (this->cursorOnInvertedList < this->invertedLists.at(this->invertedListOffset)->size()) {\n \trecordID = this->invertedLists.at(this->invertedListOffset)->at(this->cursorOnInvertedList);\n \/\/ calculate record offset online\n \trecordOffset =\n \t\t\t\tthis->queryEvaluator->getInvertedIndex()->getKeywordOffset(recordID, this->invertedListIDs.at(this->invertedListOffset));\n } else {\n \tthis->invertedListOffset ++;\n\t\t\tthis->cursorOnInvertedList = 0;\n \tif(this->invertedListOffset < this->invertedLists.size()){\n \t\trecordID = this->invertedLists.at(this->invertedListOffset)->at(this->cursorOnInvertedList);\n\t\t\t\t\/\/ calculate record offset online\n\t\t\t\trecordOffset =\n\t\t\t\t\t\t\tthis->queryEvaluator->getInvertedIndex()->getKeywordOffset(recordID, this->invertedListIDs.at(this->invertedListOffset));\n \t}else{\n \t\treturn NULL;\n \t}\n }\n }\n\n if(foundValidHit == 0){\n \treturn NULL;\n }\n\n\t\/\/ return the item.\n\tPhysicalPlanRecordItem * newItem = this->queryEvaluator->getPhysicalPlanRecordItemFactory()->createRecordItem();\n\t\/\/ record id\n\tnewItem->setRecordId(recordID);\n\t\/\/ edit distance\n\tvector editDistances;\n\teditDistances.push_back(this->invertedListDistances.at(this->cursorOnInvertedList));\n\tnewItem->setRecordMatchEditDistances(editDistances);\n\t\/\/ matching prefix\n\tvector matchingPrefixes;\n\tmatchingPrefixes.push_back(this->invertedListLeafNodes.at(this->cursorOnInvertedList)); \/\/ TODO this might be wrong\n\tnewItem->setRecordMatchingPrefixes(matchingPrefixes);\n\t\/\/ runtime score\n\tbool isPrefixMatch = this->invertedListPrefixes.at(this->invertedListOffset) ==\n\t\t\tthis->invertedListLeafNodes.at(this->invertedListOffset);\n\t\/\/\/\/\/\/ TODO ???????????????????????????? RANKER\n\tnewItem->setRecordRuntimeScore(\tDefaultTopKRanker::computeTermRecordRuntimeScore(termRecordStaticScore,\n this->invertedListDistances.at(this->invertedListOffset),\n term->getKeyword()->size(),\n isPrefixMatch,\n params.prefixMatchPenalty , term->getSimilarityBoost()));\n\t\/\/ static score\n\tnewItem->setRecordStaticScore(termRecordStaticScore);\n\t\/\/ attributeBitmap\n\tvector attributeBitmaps;\n\tattributeBitmaps.push_back(termAttributeBitmap);\n\tnewItem->setRecordMatchAttributeBitmaps(attributeBitmaps);\n\t\/\/ !!!! runtime score is not set here !!!! (we don't have it here and we don't need it here)\n\n\n\n\n\t\/\/ prepare for next call\n\tthis->cursorOnInvertedList ++;\n\tif(this->cursorOnInvertedList > this->invertedLists.at(this->invertedListOffset)->size()){\n\t\tthis->invertedListOffset ++;\n\t\tthis->cursorOnInvertedList = 0;\n\t}\n\n\n\treturn newItem;\n}\nbool UnionLowestLevelSimpleScanOperator::close(PhysicalPlanExecutionParameters & params){\n\n\tthis->invertedLists.clear();\n\tthis->invertedListDistances.clear();\n\tthis->invertedListLeafNodes.clear();\n\tthis->invertedListPrefixes.clear();\n\tthis->invertedListIDs.clear();\n\tthis->cursorOnInvertedList = 0;\n\tthis->invertedListOffset = 0;\n\tqueryEvaluator = NULL;\n\n}\nbool UnionLowestLevelSimpleScanOperator::verifyByRandomAccess(PhysicalPlanRandomAccessVerificationParameters & parameters) {\n\t \/\/do the verification\n\tPrefixActiveNodeSet *prefixActiveNodeSet =\n\t\t\tthis->getPhysicalPlanOptimizationNode()->getLogicalPlanNode()->stats->getActiveNodeSetForEstimation(parameters.isFuzzy);\n\n\tTerm * term = this->getPhysicalPlanOptimizationNode()->getLogicalPlanNode()->exactTerm;\n\n\tunsigned termSearchableAttributeIdToFilterTermHits = term->getAttributeToFilterTermHits();\n\t\/\/ assume the iterator returns the ActiveNodes in the increasing order based on edit distance\n\tfor (ActiveNodeSetIterator iter(prefixActiveNodeSet, term->getThreshold());\n\t\t\t!iter.isDone(); iter.next()) {\n\t\tconst TrieNode *trieNode;\n\t\tunsigned distance;\n\t\titer.getItem(trieNode, distance);\n\n\t\tunsigned minId = trieNode->getMinId();\n\t\tunsigned maxId = trieNode->getMaxId();\n\t\tif (term->getTermType() == srch2::instantsearch::TERM_TYPE_COMPLETE) {\n\t\t\tif (trieNode->isTerminalNode())\n\t\t\t\tmaxId = minId;\n\t\t\telse\n\t\t\t\tcontinue; \/\/ ignore non-terminal nodes\n\t\t}\n\n\t\tunsigned matchingKeywordId;\n\t\tfloat termRecordStaticScore;\n\t\tunsigned termAttributeBitmap;\n\t\tif (this->queryEvaluator->getForwardIndex()->haveWordInRange(parameters.recordToVerify->getRecordId(), minId, maxId,\n\t\t\t\ttermSearchableAttributeIdToFilterTermHits,\n\t\t\t\tmatchingKeywordId, termAttributeBitmap, termRecordStaticScore)) {\n\t\t\tparameters.termRecordMatchingPrefixes.push_back(trieNode);\n\t\t\tparameters.attributeBitmaps.push_back(termAttributeBitmap);\n\t\t\tparameters.prefixEditDistances.push_back(distance);\n\t\t\tbool isPrefixMatch = ( (!trieNode->isTerminalNode()) || (minId != matchingKeywordId) );\n\t\t\tparameters.runTimeTermRecordScores.push_back(DefaultTopKRanker::computeTermRecordRuntimeScore(termRecordStaticScore, distance,\n\t\t\t\t\t\tterm->getKeyword()->size(),\n\t\t\t\t\t\tisPrefixMatch,\n\t\t\t\t\t\tparameters.prefixMatchPenalty , term->getSimilarityBoost() ) );\n\t\t\tparameters.staticTermRecordScores.push_back(termRecordStaticScore);\n\t\t\t\/\/ parameters.positionIndexOffsets ????\n\t\t\treturn true;\n\t\t}\n\t}\n\treturn false;\n}\n\n\nvoid UnionLowestLevelSimpleScanOperator::depthInitializeSimpleScanOperator(\n\t\tconst TrieNode* trieNode, const TrieNode* prefixNode, unsigned distance, unsigned bound){\n if (trieNode->isTerminalNode()){\n \/\/ get inverted list pointer and save it\n shared_ptr > invertedListReadView;\n this->queryEvaluator->getInvertedIndex()->\n \t\tgetInvertedListReadView(trieNode->getInvertedListOffset() , invertedListReadView);\n this->invertedLists.push_back(invertedListReadView);\n this->invertedListPrefixes.push_back(prefixNode);\n this->invertedListLeafNodes.push_back(trieNode);\n this->invertedListDistances.push_back(distance);\n this->invertedListIDs.push_back(trieNode->getInvertedListOffset() );\n }\n if (distance < bound) {\n for (unsigned int childIterator = 0; childIterator < trieNode->getChildrenCount(); childIterator++) {\n const TrieNode *child = trieNode->getChild(childIterator);\n depthInitializeSimpleScanOperator(child, trieNode, distance+1, bound);\n }\n }\n}\n\n\/\/ The cost of open of a child is considered only once in the cost computation\n\/\/ of parent open function.\nunsigned UnionLowestLevelSimpleScanOptimizationOperator::getCostOfOpen(const PhysicalPlanExecutionParameters & params){\n\t\/\/TODO\n}\n\/\/ The cost of getNext of a child is multiplied by the estimated number of calls to this function\n\/\/ when the cost of parent is being calculated.\nunsigned UnionLowestLevelSimpleScanOptimizationOperator::getCostOfGetNext(const PhysicalPlanExecutionParameters & params) {\n\t\/\/TODO\n}\n\/\/ the cost of close of a child is only considered once since each node's close function is only called once.\nunsigned UnionLowestLevelSimpleScanOptimizationOperator::getCostOfClose(const PhysicalPlanExecutionParameters & params) {\n\t\/\/TODO\n}\nvoid UnionLowestLevelSimpleScanOptimizationOperator::getOutputProperties(IteratorProperties & prop){\n\t\/\/ no output property\n}\nvoid UnionLowestLevelSimpleScanOptimizationOperator::getRequiredInputProperties(IteratorProperties & prop){\n\t\/\/ the only requirement for input is to be directly connected to inverted index,\n\t\/\/ so since no operator outputs PhysicalPlanIteratorProperty_LowestLevel TVL will be pushed down to lowest level\n\tprop.addProperty(PhysicalPlanIteratorProperty_LowestLevel);\n}\nPhysicalPlanNodeType UnionLowestLevelSimpleScanOptimizationOperator::getType() {\n\treturn PhysicalPlanNode_UnionLowestLevelSimpleScanOperator;\n}\nbool UnionLowestLevelSimpleScanOptimizationOperator::validateChildren(){\n\tif(getChildrenCount() > 0){ \/\/ this operator cannot have any children\n\t\treturn false;\n\t}\n\treturn true;\n}\n\n}\n}\n<|endoftext|>"} {"text":"\/\/ Copyright 2016-2017 Jean-Francois Poilpret\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n\n#if defined(ARDUINO_UNO)\n#define HARDWARE_UART 1\n#include \nstatic constexpr const board::USART UART = board::USART::USART0;\nstatic constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;\n\/\/ Define vectors we need in the example\nREGISTER_UATX_ISR(0)\n#elif defined(BREADBOARD_ATTINYX4)\n#define HARDWARE_UART 0\n#include \nstatic constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;\nstatic constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;\n#else\n#error \"Current target is not yet supported!\"\n#endif\n\n\/\/ UART for traces\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\n#if HARDWARE_UART\nstatic serial::hard::UATX uart{output_buffer};\n#else\nstatic serial::soft::UATX uart{output_buffer};\n#endif\nstatic streams::FormattedOutput out = uart.fout();\n\nusing devices::magneto::MPU6050;\nusing devices::magneto::AllSensors;\n\nusing streams::dec;\nusing streams::hex;\nusing streams::flush;\n\nvoid trace_i2c_status(uint8_t expected_status, uint8_t actual_status)\n{\n\tif (expected_status != actual_status)\n\t\tout << F(\"status expected = \") << expected_status << F(\", actual = \") << actual_status << '\\n' << flush;\n}\n\nusing ACCELEROMETER = MPU6050;\n\nint main() __attribute__((OS_main));\nint main()\n{\n\tboard::init();\n\tsei();\n#if HARDWARE_UART\n\tuart.register_handler();\n#endif\n\tuart.begin(115200);\n\tout.width(2);\n\tout << F(\"Start\\n\") << flush;\n\n\tACCELEROMETER::MANAGER manager;\n\tmanager.begin();\n\tout << F(\"I2C interface started\\n\") << flush;\n\n\tACCELEROMETER mpu{manager};\n\t\n\tbool ok = mpu.begin();\n\tout << dec << F(\"begin() \") << ok << '\\n' << flush;\n\twhile (true)\n\t{\n\t\tAllSensors sensors;\n\t\tok = mpu.all_measures(sensors);\n\t\tout << dec << F(\"all_measures() \") << ok << '\\n' << flush;\n\t\tif (ok)\n\t\t{\n\t\t\tout\t<< dec \n\t\t\t\t<< F(\"Gyro x = \") << sensors.gyro.x \n\t\t\t\t<< F(\", y = \") << sensors.gyro.y \n\t\t\t\t<< F(\", z = \") << sensors.gyro.z << '\\n' << flush;\n\t\t\tout\t<< dec \n\t\t\t\t<< F(\"Accel x = \") << sensors.accel.x \n\t\t\t\t<< F(\", y = \") << sensors.accel.y \n\t\t\t\t<< F(\", z = \") << sensors.accel.z << '\\n' << flush;\n\t\t\t\/\/TODO methods to convert data: accel, gyro, temperature\n\t\t\t\/\/ Also check the temperature precision as per datasheet\n\t\t\tout << dec << F(\"Temp = \") << mpu.convert_temp_to_centi_degrees(sensors.temperature) << F(\" centi-C\\n\") << flush;\n\t\t}\n\t\ttime::delay_ms(1000);\n\t}\n\t\n\t\/\/ Stop TWI interface\n\t\/\/===================\n\tmanager.end();\n\tout << F(\"End\\n\") << flush;\n}\nImprove MPU6050 example to convert accelerometer\/gyroscope raw values to physical values.\/\/ Copyright 2016-2017 Jean-Francois Poilpret\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n\n#if defined(ARDUINO_UNO)\n#define HARDWARE_UART 1\n#include \nstatic constexpr const board::USART UART = board::USART::USART0;\nstatic constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;\n\/\/ Define vectors we need in the example\nREGISTER_UATX_ISR(0)\n#elif defined(BREADBOARD_ATTINYX4)\n#define HARDWARE_UART 0\n#include \nstatic constexpr const board::DigitalPin TX = board::DigitalPin::D8_PB0;\nstatic constexpr const uint8_t OUTPUT_BUFFER_SIZE = 64;\n#else\n#error \"Current target is not yet supported!\"\n#endif\n\n\/\/ UART for traces\nstatic char output_buffer[OUTPUT_BUFFER_SIZE];\n#if HARDWARE_UART\nstatic serial::hard::UATX uart{output_buffer};\n#else\nstatic serial::soft::UATX uart{output_buffer};\n#endif\nstatic streams::FormattedOutput out = uart.fout();\n\nusing utils::UnitPrefix;\nusing utils::map;\nusing devices::magneto::MPU6050;\nusing devices::magneto::AllSensors;\nusing devices::magneto::AccelRange;\nusing devices::magneto::GyroRange;\nusing devices::magneto::ACCEL_RANGE_G;\nusing devices::magneto::GYRO_RANGE_DPS;\n\nusing streams::dec;\nusing streams::hex;\nusing streams::flush;\n\nstatic constexpr const GyroRange GYRO_RANGE = GyroRange::RANGE_250;\nstatic constexpr const AccelRange ACCEL_RANGE = AccelRange::RANGE_2G;\n\ninline int16_t gyro(int16_t value)\n{\n\treturn map(value, UnitPrefix::CENTI, GYRO_RANGE_DPS(GYRO_RANGE), 15);\n}\ninline int16_t accel(int16_t value)\n{\n\treturn map(value, UnitPrefix::MILLI, ACCEL_RANGE_G(ACCEL_RANGE), 15);\n}\n\nvoid trace_i2c_status(uint8_t expected_status, uint8_t actual_status)\n{\n\tif (expected_status != actual_status)\n\t\tout << F(\"status expected = \") << expected_status << F(\", actual = \") << actual_status << '\\n' << flush;\n}\n\nusing ACCELEROMETER = MPU6050;\n\nint main() __attribute__((OS_main));\nint main()\n{\n\tboard::init();\n\tsei();\n#if HARDWARE_UART\n\tuart.register_handler();\n#endif\n\tuart.begin(115200);\n\tout.width(2);\n\tout << F(\"Start\\n\") << flush;\n\n\tACCELEROMETER::MANAGER manager;\n\tmanager.begin();\n\tout << F(\"I2C interface started\\n\") << flush;\n\n\tACCELEROMETER mpu{manager};\n\t\n\tbool ok = mpu.begin(GyroRange::RANGE_250, AccelRange::RANGE_2G);\n\tout << dec << F(\"begin() \") << ok << '\\n' << flush;\n\twhile (true)\n\t{\n\t\tAllSensors sensors;\n\t\tok = mpu.all_measures(sensors);\n\t\tout << dec << F(\"all_measures() \") << ok << '\\n' << flush;\n\t\tif (ok)\n\t\t{\n\t\t\tout\t<< dec \n\t\t\t\t<< F(\"raw Gyro x = \") << sensors.gyro.x \n\t\t\t\t<< F(\", y = \") << sensors.gyro.y \n\t\t\t\t<< F(\", z = \") << sensors.gyro.z << '\\n' << flush;\n\t\t\tout\t<< dec \n\t\t\t\t<< F(\"cdps Gyro x = \") << gyro(sensors.gyro.x)\n\t\t\t\t<< F(\", y = \") << gyro(sensors.gyro.y) \n\t\t\t\t<< F(\", z = \") << gyro(sensors.gyro.z) << '\\n' << flush;\n\t\t\tout\t<< dec \n\t\t\t\t<< F(\"raw Accel x = \") << sensors.accel.x \n\t\t\t\t<< F(\", y = \") << sensors.accel.y \n\t\t\t\t<< F(\", z = \") << sensors.accel.z << '\\n' << flush;\n\t\t\tout\t<< dec \n\t\t\t\t<< F(\"mG Accel x = \") << accel(sensors.accel.x) \n\t\t\t\t<< F(\", y = \") << accel(sensors.accel.y) \n\t\t\t\t<< F(\", z = \") << accel(sensors.accel.z) << '\\n' << flush;\n\t\t\t\/\/ Also check the temperature precision as per datasheet\n\t\t\tout << dec << F(\"Temp = \") << mpu.convert_temp_to_centi_degrees(sensors.temperature) << F(\" centi-C\\n\") << flush;\n\t\t}\n\t\ttime::delay_ms(1000);\n\t}\n\t\n\t\/\/ Stop TWI interface\n\t\/\/===================\n\tmanager.end();\n\tout << F(\"End\\n\") << flush;\n}\n<|endoftext|>"} {"text":"\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"gallerymodel.h\"\n\n#include \"qgalleryitemlist.h\"\n\nGalleryModel::GalleryModel(QObject *parent)\n : QAbstractItemModel(parent)\n , mediaList(0)\n , columnNames(1)\n , displayKeys(1, -1)\n , displayFields(1)\n , decorationKeys(1, -1)\n , decorationFields(1)\n{\n}\n\nGalleryModel::~GalleryModel()\n{\n}\n\nQVariant GalleryModel::data(const QModelIndex &index, int role) const\n{\n if (index.isValid()) {\n int key = -1;\n\n if (role == Qt::DisplayRole || role == Qt::EditRole)\n key = displayKeys.at(index.column());\n else if (role == Qt::DecorationRole)\n key = decorationKeys.at(index.column());\n else if (role >= Qt::UserRole)\n key = userKeys.at(role - Qt::UserRole);\n\n if (key >= 0)\n return mediaList->metaData(index.row(), key);\n }\n return QVariant();\n}\n\nbool GalleryModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if (index.isValid() && role == Qt::EditRole) {\n int key = displayKeys.at(index.column());\n\n if (key >= 0) {\n mediaList->setMetaData(index.row(), key, value);\n\n return true;\n }\n }\n return false;\n}\n\nQt::ItemFlags GalleryModel::flags(const QModelIndex &index) const\n{\n Qt::ItemFlags flags = Qt::ItemIsEnabled;\n\n if (index.isValid()) {\n int key = displayKeys.at(index.column());\n\n if (key >= 0 && mediaList->propertyAttributes(key) & QGalleryProperty::CanWrite)\n flags |= Qt::ItemIsEditable;\n }\n\n return flags;\n}\n\nQModelIndex GalleryModel::index(int row, int column, const QModelIndex &parent) const\n{\n if (!parent.isValid() && mediaList\n && row >= 0 && row < mediaList->count()\n && column >= 0 && column < displayFields.count()) {\n\n \/\/ Ideally we'd use the scroll position of the view to set the cursor position\n if (row > 0 && row < mediaList->count() - 1) {\n const_cast(mediaList)->setCursorPosition(row);\n }\n\n return createIndex(row, column);\n }\n return QModelIndex();\n}\n\nQModelIndex GalleryModel::parent(const QModelIndex &) const\n{\n return QModelIndex();\n}\n\nQVariant GalleryModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n return orientation == Qt::Horizontal && role == Qt::DisplayRole\n ? columnNames.value(section)\n : QVariant();\n}\n\nint GalleryModel::rowCount(const QModelIndex &parent) const\n{\n return !parent.isValid() && mediaList\n ? mediaList->count()\n : 0;\n}\n\nint GalleryModel::columnCount(const QModelIndex &parent) const\n{\n return !parent.isValid() ? displayFields.count() : 0;\n}\n\nvoid GalleryModel::setColumnCount(int count)\n{\n if (displayFields.count() > count) {\n beginRemoveColumns(QModelIndex(), count, displayFields.count() - 1);\n\n columnNames.resize(count);\n displayFields.resize(count);\n displayKeys.resize(count);\n decorationFields.resize(count);\n decorationKeys.resize(count);\n\n endRemoveColumns();\n } else if (displayFields.count() < count) {\n int index = displayFields.count();\n\n beginInsertColumns(QModelIndex(), index, count - 1);\n\n columnNames.resize(count);\n displayFields.resize(count);\n displayKeys.fill(-1, count);\n decorationFields.resize(count);\n decorationKeys.fill(-1, count);\n\n endInsertColumns();\n }\n}\n\nQGalleryItemList *GalleryModel::list() const\n{\n return mediaList;\n}\n\nvoid GalleryModel::setList(QGalleryItemList *list)\n{\n beginResetModel();\n\n if (mediaList) {\n disconnect(mediaList, SIGNAL(inserted(int,int)), this, SLOT(inserted(int,int)));\n disconnect(mediaList, SIGNAL(removed(int,int)), this, SLOT(removed(int,int)));\n disconnect(mediaList, SIGNAL(moved(int,int,int)), this, SLOT(moved(int,int,int)));\n disconnect(mediaList, SIGNAL(metaDataChanged(int,int,QList)),\n this, SLOT(metaDataChanged(int,int,QList)));\n\n displayKeys.fill(-1);\n decorationKeys.fill(-1);\n userKeys.fill(-1);\n }\n\n mediaList = list;\n\n if (mediaList) {\n for (int i = 0; i < displayFields.count(); ++i)\n displayKeys[i] = mediaList->propertyKey(displayFields.at(i));\n\n for (int i = 0; i < decorationFields.count(); ++i)\n decorationKeys[i] = mediaList->propertyKey(decorationFields.at(i));\n\n for (int i = 0; i < userFields.count(); ++i)\n userKeys[i] = mediaList->propertyKey(userFields.at(i));\n\n connect(mediaList, SIGNAL(inserted(int,int)), this, SLOT(inserted(int,int)));\n connect(mediaList, SIGNAL(removed(int,int)), this, SLOT(removed(int,int)));\n connect(mediaList, SIGNAL(moved(int,int,int)), this, SLOT(moved(int,int,int)));\n connect(mediaList, SIGNAL(metaDataChanged(int,int,QList)),\n this, SLOT(metaDataChanged(int,int,QList)));\n }\n endResetModel();\n}\n\nQString GalleryModel::columnName(int column) const\n{\n return columnNames.at(column);\n}\n\nvoid GalleryModel::setColumnName(int column, const QString &name)\n{\n columnNames[column] = name;\n\n emit headerDataChanged(Qt::Horizontal, column, column);\n}\n\nQString GalleryModel::displayFieldForColumn(int column) const\n{\n return displayFields.at(column);\n}\n\nvoid GalleryModel::setDisplayFieldForColumn(int column, const QString &field)\n{\n displayFields[column] = field;\n\n if (mediaList) {\n displayKeys[column] = mediaList->propertyKey(field);\n\n emit dataChanged(createIndex(0, column), createIndex(mediaList->count() - 1, column));\n }\n}\n\nQString GalleryModel::decorationFieldForColumn(int column) const\n{\n return decorationFields.at(column);\n}\n\nvoid GalleryModel::setDecorationFieldForColumn(int column, const QString &field)\n{\n decorationFields[column] = field;\n\n if (mediaList) {\n decorationKeys[column] = mediaList->propertyKey(field);\n\n emit dataChanged(createIndex(0, column), createIndex(mediaList->count() - 1, column));\n }\n}\n\nQVector GalleryModel::userRoleFields() const\n{\n return userFields;\n}\n\nvoid GalleryModel::setUserRoleFields(const QVector &fields)\n{\n userFields = fields;\n userKeys.fill(-1, userFields.count());\n\n if (mediaList) {\n for (int i = 0; i < userFields.count(); ++i)\n userKeys[i] = mediaList->propertyKey(userFields.at(i));\n\n emit dataChanged(\n createIndex(0, 0),\n createIndex(mediaList->count() - 1, displayFields.count()));\n }\n}\n\nvoid GalleryModel::removed(int index, int count)\n{\n beginRemoveRows(QModelIndex(), index, index + count - 1);\n endRemoveRows();\n}\n\nvoid GalleryModel::inserted(int index, int count)\n{\n beginInsertRows(QModelIndex(), index, index + count - 1);\n endInsertRows();\n}\n\nvoid GalleryModel::moved(int from, int to, int count)\n{\n beginMoveRows(QModelIndex(), from, from + count - 1, QModelIndex(), to);\n}\n\nvoid GalleryModel::metaDataChanged(int index, int count, const QList &)\n{\n emit dataChanged(\n createIndex(index, 0),\n createIndex(index + count -1, displayFields.count() - 1));\n}\n\nReduce noise in calls to setCursorPosition.\/****************************************************************************\n**\n** Copyright (C) 2009 Nokia Corporation and\/or its subsidiary(-ies).\n** All rights reserved.\n** Contact: Nokia Corporation (qt-info@nokia.com)\n**\n** This file is part of the Qt Mobility Components.\n**\n** $QT_BEGIN_LICENSE:LGPL$\n** No Commercial Usage\n** This file contains pre-release code and may not be distributed.\n** You may use this file in accordance with the terms and conditions\n** contained in the Technology Preview License Agreement accompanying\n** this package.\n**\n** GNU Lesser General Public License Usage\n** Alternatively, this file may be used under the terms of the GNU Lesser\n** General Public License version 2.1 as published by the Free Software\n** Foundation and appearing in the file LICENSE.LGPL included in the\n** packaging of this file. Please review the following information to\n** ensure the GNU Lesser General Public License version 2.1 requirements\n** will be met: http:\/\/www.gnu.org\/licenses\/old-licenses\/lgpl-2.1.html.\n**\n** In addition, as a special exception, Nokia gives you certain additional\n** rights. These rights are described in the Nokia Qt LGPL Exception\n** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.\n**\n** If you have questions regarding the use of this file, please contact\n** Nokia at qt-info@nokia.com.\n**\n**\n**\n**\n**\n**\n**\n**\n** $QT_END_LICENSE$\n**\n****************************************************************************\/\n\n#include \"gallerymodel.h\"\n\n#include \"qgalleryitemlist.h\"\n\nGalleryModel::GalleryModel(QObject *parent)\n : QAbstractItemModel(parent)\n , mediaList(0)\n , columnNames(1)\n , displayKeys(1, -1)\n , displayFields(1)\n , decorationKeys(1, -1)\n , decorationFields(1)\n{\n}\n\nGalleryModel::~GalleryModel()\n{\n}\n\nQVariant GalleryModel::data(const QModelIndex &index, int role) const\n{\n if (index.isValid()) {\n int key = -1;\n\n if (role == Qt::DisplayRole || role == Qt::EditRole)\n key = displayKeys.at(index.column());\n else if (role == Qt::DecorationRole)\n key = decorationKeys.at(index.column());\n else if (role >= Qt::UserRole)\n key = userKeys.at(role - Qt::UserRole);\n\n if (key >= 0)\n return mediaList->metaData(index.row(), key);\n }\n return QVariant();\n}\n\nbool GalleryModel::setData(const QModelIndex &index, const QVariant &value, int role)\n{\n if (index.isValid() && role == Qt::EditRole) {\n int key = displayKeys.at(index.column());\n\n if (key >= 0) {\n mediaList->setMetaData(index.row(), key, value);\n\n return true;\n }\n }\n return false;\n}\n\nQt::ItemFlags GalleryModel::flags(const QModelIndex &index) const\n{\n Qt::ItemFlags flags = Qt::ItemIsEnabled;\n\n if (index.isValid()) {\n int key = displayKeys.at(index.column());\n\n if (key >= 0 && mediaList->propertyAttributes(key) & QGalleryProperty::CanWrite)\n flags |= Qt::ItemIsEditable;\n }\n\n return flags;\n}\n\nQModelIndex GalleryModel::index(int row, int column, const QModelIndex &parent) const\n{\n if (!parent.isValid() && mediaList\n && row >= 0 && row < mediaList->count()\n && column >= 0 && column < displayFields.count()) {\n\n \/\/ Ideally we'd use the scroll position of the view to set the cursor position\n if (row < mediaList->count() - 1) {\n const int position = mediaList->cursorPosition();\n const int pageSize = mediaList->minimumPagedItems();\n\n if (row - 16 < position && position > 0)\n mediaList->setCursorPosition(qMax(0, row - 16));\n else if (row + 16 > position + pageSize)\n mediaList->setCursorPosition(qMax(0, row + 16 - pageSize));\n }\n\n return createIndex(row, column);\n }\n return QModelIndex();\n}\n\nQModelIndex GalleryModel::parent(const QModelIndex &) const\n{\n return QModelIndex();\n}\n\nQVariant GalleryModel::headerData(int section, Qt::Orientation orientation, int role) const\n{\n return orientation == Qt::Horizontal && role == Qt::DisplayRole\n ? columnNames.value(section)\n : QVariant();\n}\n\nint GalleryModel::rowCount(const QModelIndex &parent) const\n{\n return !parent.isValid() && mediaList\n ? mediaList->count()\n : 0;\n}\n\nint GalleryModel::columnCount(const QModelIndex &parent) const\n{\n return !parent.isValid() ? displayFields.count() : 0;\n}\n\nvoid GalleryModel::setColumnCount(int count)\n{\n if (displayFields.count() > count) {\n beginRemoveColumns(QModelIndex(), count, displayFields.count() - 1);\n\n columnNames.resize(count);\n displayFields.resize(count);\n displayKeys.resize(count);\n decorationFields.resize(count);\n decorationKeys.resize(count);\n\n endRemoveColumns();\n } else if (displayFields.count() < count) {\n int index = displayFields.count();\n\n beginInsertColumns(QModelIndex(), index, count - 1);\n\n columnNames.resize(count);\n displayFields.resize(count);\n displayKeys.fill(-1, count);\n decorationFields.resize(count);\n decorationKeys.fill(-1, count);\n\n endInsertColumns();\n }\n}\n\nQGalleryItemList *GalleryModel::list() const\n{\n return mediaList;\n}\n\nvoid GalleryModel::setList(QGalleryItemList *list)\n{\n beginResetModel();\n\n if (mediaList) {\n disconnect(mediaList, SIGNAL(inserted(int,int)), this, SLOT(inserted(int,int)));\n disconnect(mediaList, SIGNAL(removed(int,int)), this, SLOT(removed(int,int)));\n disconnect(mediaList, SIGNAL(moved(int,int,int)), this, SLOT(moved(int,int,int)));\n disconnect(mediaList, SIGNAL(metaDataChanged(int,int,QList)),\n this, SLOT(metaDataChanged(int,int,QList)));\n\n displayKeys.fill(-1);\n decorationKeys.fill(-1);\n userKeys.fill(-1);\n }\n\n mediaList = list;\n\n if (mediaList) {\n for (int i = 0; i < displayFields.count(); ++i)\n displayKeys[i] = mediaList->propertyKey(displayFields.at(i));\n\n for (int i = 0; i < decorationFields.count(); ++i)\n decorationKeys[i] = mediaList->propertyKey(decorationFields.at(i));\n\n for (int i = 0; i < userFields.count(); ++i)\n userKeys[i] = mediaList->propertyKey(userFields.at(i));\n\n connect(mediaList, SIGNAL(inserted(int,int)), this, SLOT(inserted(int,int)));\n connect(mediaList, SIGNAL(removed(int,int)), this, SLOT(removed(int,int)));\n connect(mediaList, SIGNAL(moved(int,int,int)), this, SLOT(moved(int,int,int)));\n connect(mediaList, SIGNAL(metaDataChanged(int,int,QList)),\n this, SLOT(metaDataChanged(int,int,QList)));\n }\n endResetModel();\n}\n\nQString GalleryModel::columnName(int column) const\n{\n return columnNames.at(column);\n}\n\nvoid GalleryModel::setColumnName(int column, const QString &name)\n{\n columnNames[column] = name;\n\n emit headerDataChanged(Qt::Horizontal, column, column);\n}\n\nQString GalleryModel::displayFieldForColumn(int column) const\n{\n return displayFields.at(column);\n}\n\nvoid GalleryModel::setDisplayFieldForColumn(int column, const QString &field)\n{\n displayFields[column] = field;\n\n if (mediaList) {\n displayKeys[column] = mediaList->propertyKey(field);\n\n emit dataChanged(createIndex(0, column), createIndex(mediaList->count() - 1, column));\n }\n}\n\nQString GalleryModel::decorationFieldForColumn(int column) const\n{\n return decorationFields.at(column);\n}\n\nvoid GalleryModel::setDecorationFieldForColumn(int column, const QString &field)\n{\n decorationFields[column] = field;\n\n if (mediaList) {\n decorationKeys[column] = mediaList->propertyKey(field);\n\n emit dataChanged(createIndex(0, column), createIndex(mediaList->count() - 1, column));\n }\n}\n\nQVector GalleryModel::userRoleFields() const\n{\n return userFields;\n}\n\nvoid GalleryModel::setUserRoleFields(const QVector &fields)\n{\n userFields = fields;\n userKeys.fill(-1, userFields.count());\n\n if (mediaList) {\n for (int i = 0; i < userFields.count(); ++i)\n userKeys[i] = mediaList->propertyKey(userFields.at(i));\n\n emit dataChanged(\n createIndex(0, 0),\n createIndex(mediaList->count() - 1, displayFields.count()));\n }\n}\n\nvoid GalleryModel::removed(int index, int count)\n{\n beginRemoveRows(QModelIndex(), index, index + count - 1);\n endRemoveRows();\n}\n\nvoid GalleryModel::inserted(int index, int count)\n{\n beginInsertRows(QModelIndex(), index, index + count - 1);\n endInsertRows();\n}\n\nvoid GalleryModel::moved(int from, int to, int count)\n{\n beginMoveRows(QModelIndex(), from, from + count - 1, QModelIndex(), to);\n}\n\nvoid GalleryModel::metaDataChanged(int index, int count, const QList &)\n{\n emit dataChanged(\n createIndex(index, 0),\n createIndex(index + count -1, displayFields.count() - 1));\n}\n\n<|endoftext|>"} {"text":"#include \n\n#include \"events-impl.h\"\n\n#include \"protocol\/stress.pb.h\"\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n\n#include \"vtrc-client-base\/vtrc-client.h\"\n\n#include \"vtrc-common\/vtrc-closure-holder.h\"\n#include \"vtrc-common\/vtrc-call-context.h\"\n\n\n#include \"vtrc-chrono.h\"\n#include \"vtrc-thread.h\"\n\n\nnamespace stress {\n\n using namespace vtrc;\n namespace gpb = google::protobuf;\n\nnamespace {\n\n typedef vtrc::chrono::high_resolution_clock high_resolution_clock;\n typedef high_resolution_clock::time_point time_point;\n\n size_t get_micro( const time_point &f, const time_point &l )\n {\n return chrono::duration_cast( l - f ).count( );\n }\n\n class events_impl: public vtrc_example::stress_events {\n\n client::vtrc_client_wptr client_;\n\n time_point last_event_point_;\n\n public:\n events_impl( vtrc::shared_ptr c )\n :client_(c)\n ,last_event_point_(high_resolution_clock::now( ))\n { }\n private:\n\n void event(::google::protobuf::RpcController* controller,\n const ::vtrc_example::event_req* request,\n ::vtrc_example::event_res* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder holder( done );\n\n time_point this_event_point = high_resolution_clock::now( );\n\n std::string name( request->is_event( ) ? \"Event\" : \"Callback\" );\n\n std::cout << name << \" id '\" << request->id( ) << \"'\"\n << \"; \";\n if( request->id( ) > 0 ) {\n std::cout\n << \"previous: \"\n << get_micro( last_event_point_, this_event_point )\n << \" microseconds ago\"\n << \"; thread \" << this_thread::get_id( );\n }\n std::cout << \"\\n\";\n\n last_event_point_ = this_event_point;\n }\n\n std::string get_stack( )\n {\n client::vtrc_client_sptr locked( client_.lock( ) );\n\n if( locked ) { \/\/\/ just on case;\n\n const common::call_context *cc(locked->get_call_context( ));\n size_t depth = cc->depth( );\n std::ostringstream oss;\n\n size_t from_server = 0;\n size_t from_client = 0;\n\n bool is_server = true;\n while( cc ) {\n\n from_server += is_server ? 1 : 0;\n from_client += is_server ? 0 : 1;\n\n is_server = !is_server;\n cc = cc->next( );\n }\n oss << \"depth: \" << depth << \"; \"\n << \"client depth: \" << from_client << \"; \"\n << \"server depth: \" << from_server;\n return oss.str( );\n }\n\n return \"<>failed<>?\";\n }\n\n std::string get_stack1( )\n {\n client::vtrc_client_sptr locked( client_.lock( ) );\n\n if( locked ) { \/\/\/ just on case;\n\n const common::call_context *cc(locked->get_call_context( ));\n std::ostringstream oss;\n bool from_server = true;\n while( cc ) {\n oss << (from_server ? \">\" : \"<\");\n from_server = !from_server;\n cc = cc->next( );\n }\n return oss.str( );\n }\n\n return \"<>failed<>?\";\n }\n\n std::string get_stack2( )\n {\n client::vtrc_client_sptr locked( client_.lock( ) );\n\n if( locked ) { \/\/\/ just on case;\n\n const common::call_context *cc(locked->get_call_context( ));\n std::ostringstream oss;\n bool from_server = true;\n while( cc ) {\n oss << (from_server ? \"S>\" : \"C<\") << \":\"\n << cc->get_lowlevel_message( )->call( ).service_id( )\n << \"::\"\n << cc->get_lowlevel_message( )->call( ).method_id( );\n cc = cc->next( );\n from_server = !from_server;\n if( cc ) {\n oss << \"->\";\n }\n }\n return oss.str( );\n }\n\n return \"<>failed<>?\";\n }\n\n void recursive_callback(::google::protobuf::RpcController* controller,\n const ::vtrc_example::recursive_call_req* request,\n ::vtrc_example::recursive_call_res* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder holder( done );\n\n std::string stack(get_stack( ));\n\n if( request->balance( ) == 0 ) {\n std::cout << \"Last recursive_callback\\n\";\n std::cout << \"last stack: \" << stack\n << \"\\n\";\n } else {\n std::cout << \"[IN ] balance: \" << request->balance( )\n << \"; stack: \" << stack\n << \"\\n\";\n client::vtrc_client_sptr locked(client_.lock( ));\n if( locked ) {\n vtrc::shared_ptr impl(\n create_stress_client(locked,\n common::rpc_channel::USE_CONTEXT_CALL));\n impl->recursive_call( request->balance( ) - 1 );\n }\n std::cout << \"[OUT] balance: \" << request->balance( )\n << \"; stack: \" << stack\n << \"\\n\";\n }\n }\n\n\n };\n}\n\n gpb::Service *create_events( vtrc::shared_ptr c )\n {\n return new events_impl( c );\n }\n\n}\nexamples#include \n\n#include \"events-impl.h\"\n\n#include \"protocol\/stress.pb.h\"\n#include \"protocol\/vtrc-rpc-lowlevel.pb.h\"\n\n#include \"vtrc-client-base\/vtrc-client.h\"\n\n#include \"vtrc-common\/vtrc-closure-holder.h\"\n#include \"vtrc-common\/vtrc-call-context.h\"\n\n\n#include \"vtrc-chrono.h\"\n#include \"vtrc-thread.h\"\n\n\nnamespace stress {\n\n using namespace vtrc;\n namespace gpb = google::protobuf;\n\nnamespace {\n\n typedef vtrc::chrono::high_resolution_clock high_resolution_clock;\n typedef high_resolution_clock::time_point time_point;\n\n size_t get_micro( const time_point &f, const time_point &l )\n {\n return chrono::duration_cast( l - f ).count( );\n }\n\n class events_impl: public vtrc_example::stress_events {\n\n client::vtrc_client_wptr client_;\n\n time_point last_event_point_;\n\n public:\n events_impl( vtrc::shared_ptr c )\n :client_(c)\n ,last_event_point_(high_resolution_clock::now( ))\n { }\n private:\n\n void event(::google::protobuf::RpcController* controller,\n const ::vtrc_example::event_req* request,\n ::vtrc_example::event_res* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder holder( done );\n\n time_point this_event_point = high_resolution_clock::now( );\n\n std::string name( request->is_event( ) ? \"Event\" : \"Callback\" );\n\n std::cout << name << \" id '\" << request->id( ) << \"'\"\n << \"; \";\n if( request->id( ) > 0 ) {\n std::cout\n << \"previous: \"\n << get_micro( last_event_point_, this_event_point )\n << \" microseconds ago\"\n << \"; thread \" << this_thread::get_id( );\n }\n std::cout << \"\\n\";\n\n last_event_point_ = this_event_point;\n }\n\n std::string get_stack( )\n {\n client::vtrc_client_sptr locked( client_.lock( ) );\n\n if( locked ) { \/\/\/ just on case;\n\n const common::call_context *cc(locked->get_call_context( ));\n size_t depth = cc->depth( );\n std::ostringstream oss;\n\n size_t from_server = 0;\n size_t from_client = 0;\n\n bool is_server = true;\n while( cc ) {\n\n from_server += is_server ? 1 : 0;\n from_client += is_server ? 0 : 1;\n\n is_server = !is_server;\n cc = cc->next( );\n }\n oss << \"depth: \" << depth << \"; \"\n << \"client depth: \" << from_client << \"; \"\n << \"server depth: \" << from_server;\n return oss.str( );\n }\n\n return \"<>failed<>?\";\n }\n\n std::string get_stack1( )\n {\n client::vtrc_client_sptr locked( client_.lock( ) );\n\n if( locked ) { \/\/\/ just on case;\n\n const common::call_context *cc(locked->get_call_context( ));\n std::ostringstream oss;\n bool from_server = true;\n while( cc ) {\n oss << (from_server ? \">\" : \"<\");\n from_server = !from_server;\n cc = cc->next( );\n }\n return oss.str( );\n }\n\n return \"<>failed<>?\";\n }\n\n std::string get_stack2( )\n {\n client::vtrc_client_sptr locked( client_.lock( ) );\n\n if( locked ) { \/\/\/ just on case;\n\n const common::call_context *cc(locked->get_call_context( ));\n std::ostringstream oss;\n bool from_server = true;\n while( cc ) {\n oss << (from_server ? \"S>\" : \"C<\") << \":\"\n << cc->get_lowlevel_message( )->call( ).service_id( )\n << \"::\"\n << cc->get_lowlevel_message( )->call( ).method_id( );\n cc = cc->next( );\n from_server = !from_server;\n if( cc ) {\n oss << \"->\";\n }\n }\n return oss.str( );\n }\n\n return \"<>failed<>?\";\n }\n\n void recursive_callback(::google::protobuf::RpcController* controller,\n const ::vtrc_example::recursive_call_req* request,\n ::vtrc_example::recursive_call_res* response,\n ::google::protobuf::Closure* done)\n {\n common::closure_holder holder( done );\n\n std::string stack(get_stack( ));\n\n std::cout << \"[IN ] balance: \" << request->balance( )\n << \"; stack: \" << stack\n << \"\\n\";\n\n client::vtrc_client_sptr locked(client_.lock( ));\n\n if( locked ) {\n vtrc::shared_ptr impl(\n create_stress_client(locked,\n common::rpc_channel::USE_CONTEXT_CALL));\n impl->recursive_call( request->balance( ) - 1 );\n }\n if( request->balance( ) == 1 ) {\n std::cout << \"============= EXIT =============\\n\";\n }\n std::cout << \"[OUT] balance: \" << request->balance( )\n << \"; stack: \" << stack\n << \"\\n\";\n }\n\n\n };\n}\n\n gpb::Service *create_events( vtrc::shared_ptr c )\n {\n return new events_impl( c );\n }\n\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \"zerocash\/ZerocashParams.h\"\n#include \"coins.h\"\n#include \"util.h\"\n#include \"init.h\"\n#include \"primitives\/transaction.h\"\n#include \"crypto\/equihash.h\"\n#include \"chainparams.h\"\n#include \"pow.h\"\n\n#include \"zcbenchmarks.h\"\n\nstruct timeval tv_start;\n\nvoid timer_start()\n{\n gettimeofday(&tv_start, 0);\n}\n\ndouble timer_stop()\n{\n double elapsed;\n struct timeval tv_end;\n gettimeofday(&tv_end, 0);\n elapsed = double(tv_end.tv_sec-tv_start.tv_sec) +\n (tv_end.tv_usec-tv_start.tv_usec)\/double(1000000);\n return elapsed;\n}\n\ndouble benchmark_sleep()\n{\n timer_start();\n sleep(1);\n return timer_stop();\n}\n\ndouble benchmark_parameter_loading()\n{\n \/\/ FIXME: this is duplicated with the actual loading code\n boost::filesystem::path pk_path = ZC_GetParamsDir() \/ \"zc-testnet-public-alpha-proving.key\";\n boost::filesystem::path vk_path = ZC_GetParamsDir() \/ \"zc-testnet-public-alpha-verification.key\";\n\n timer_start();\n auto vk_loaded = libzerocash::ZerocashParams::LoadVerificationKeyFromFile(\n vk_path.string(),\n INCREMENTAL_MERKLE_TREE_DEPTH\n );\n auto pk_loaded = libzerocash::ZerocashParams::LoadProvingKeyFromFile(\n pk_path.string(),\n INCREMENTAL_MERKLE_TREE_DEPTH\n );\n libzerocash::ZerocashParams zerocashParams = libzerocash::ZerocashParams(\n INCREMENTAL_MERKLE_TREE_DEPTH,\n &pk_loaded,\n &vk_loaded\n );\n return timer_stop();\n}\n\ndouble benchmark_create_joinsplit()\n{\n CScript scriptPubKey;\n\n std::vector vpourin;\n std::vector vpourout;\n\n while (vpourin.size() < NUM_POUR_INPUTS) {\n vpourin.push_back(PourInput(INCREMENTAL_MERKLE_TREE_DEPTH));\n }\n\n while (vpourout.size() < NUM_POUR_OUTPUTS) {\n vpourout.push_back(PourOutput(0));\n }\n\n \/* Get the anchor of an empty commitment tree. *\/\n IncrementalMerkleTree blank_tree(INCREMENTAL_MERKLE_TREE_DEPTH);\n std::vector newrt_v(32);\n blank_tree.getRootValue(newrt_v);\n uint256 anchor = uint256(newrt_v);\n\n timer_start();\n CPourTx pourtx(*pzerocashParams,\n scriptPubKey,\n anchor,\n {vpourin[0], vpourin[1]},\n {vpourout[0], vpourout[1]},\n 0,\n 0);\n double ret = timer_stop();\n assert(pourtx.Verify(*pzerocashParams));\n return ret;\n}\n\ndouble benchmark_verify_joinsplit(const CPourTx &joinsplit)\n{\n timer_start();\n joinsplit.Verify(*pzerocashParams);\n return timer_stop();\n}\n\ndouble benchmark_solve_equihash()\n{\n const char *testing = \"testing\";\n Equihash eh {Params(CBaseChainParams::MAIN).EquihashN(), Params(CBaseChainParams::MAIN).EquihashK()};\n crypto_generichash_blake2b_state eh_state;\n eh.InitialiseState(eh_state);\n crypto_generichash_blake2b_update(&eh_state, (const unsigned char*)testing, strlen(testing));\n timer_start();\n eh.BasicSolve(eh_state);\n return timer_stop();\n}\n\ndouble benchmark_verify_equihash()\n{\n CChainParams params = Params(CBaseChainParams::MAIN);\n CBlock genesis = Params(CBaseChainParams::MAIN).GenesisBlock();\n CBlockHeader genesis_header = genesis.GetBlockHeader();\n timer_start();\n CheckEquihashSolution(&genesis_header, params);\n return timer_stop();\n}\n\nBenchmark a random equihash input.#include \n#include \n#include \"zerocash\/ZerocashParams.h\"\n#include \"coins.h\"\n#include \"util.h\"\n#include \"init.h\"\n#include \"primitives\/transaction.h\"\n#include \"crypto\/equihash.h\"\n#include \"chainparams.h\"\n#include \"pow.h\"\n#include \"sodium.h\"\n#include \"streams.h\"\n\n#include \"zcbenchmarks.h\"\n\nstruct timeval tv_start;\n\nvoid timer_start()\n{\n gettimeofday(&tv_start, 0);\n}\n\ndouble timer_stop()\n{\n double elapsed;\n struct timeval tv_end;\n gettimeofday(&tv_end, 0);\n elapsed = double(tv_end.tv_sec-tv_start.tv_sec) +\n (tv_end.tv_usec-tv_start.tv_usec)\/double(1000000);\n return elapsed;\n}\n\ndouble benchmark_sleep()\n{\n timer_start();\n sleep(1);\n return timer_stop();\n}\n\ndouble benchmark_parameter_loading()\n{\n \/\/ FIXME: this is duplicated with the actual loading code\n boost::filesystem::path pk_path = ZC_GetParamsDir() \/ \"zc-testnet-public-alpha-proving.key\";\n boost::filesystem::path vk_path = ZC_GetParamsDir() \/ \"zc-testnet-public-alpha-verification.key\";\n\n timer_start();\n auto vk_loaded = libzerocash::ZerocashParams::LoadVerificationKeyFromFile(\n vk_path.string(),\n INCREMENTAL_MERKLE_TREE_DEPTH\n );\n auto pk_loaded = libzerocash::ZerocashParams::LoadProvingKeyFromFile(\n pk_path.string(),\n INCREMENTAL_MERKLE_TREE_DEPTH\n );\n libzerocash::ZerocashParams zerocashParams = libzerocash::ZerocashParams(\n INCREMENTAL_MERKLE_TREE_DEPTH,\n &pk_loaded,\n &vk_loaded\n );\n return timer_stop();\n}\n\ndouble benchmark_create_joinsplit()\n{\n CScript scriptPubKey;\n\n std::vector vpourin;\n std::vector vpourout;\n\n while (vpourin.size() < NUM_POUR_INPUTS) {\n vpourin.push_back(PourInput(INCREMENTAL_MERKLE_TREE_DEPTH));\n }\n\n while (vpourout.size() < NUM_POUR_OUTPUTS) {\n vpourout.push_back(PourOutput(0));\n }\n\n \/* Get the anchor of an empty commitment tree. *\/\n IncrementalMerkleTree blank_tree(INCREMENTAL_MERKLE_TREE_DEPTH);\n std::vector newrt_v(32);\n blank_tree.getRootValue(newrt_v);\n uint256 anchor = uint256(newrt_v);\n\n timer_start();\n CPourTx pourtx(*pzerocashParams,\n scriptPubKey,\n anchor,\n {vpourin[0], vpourin[1]},\n {vpourout[0], vpourout[1]},\n 0,\n 0);\n double ret = timer_stop();\n assert(pourtx.Verify(*pzerocashParams));\n return ret;\n}\n\ndouble benchmark_verify_joinsplit(const CPourTx &joinsplit)\n{\n timer_start();\n joinsplit.Verify(*pzerocashParams);\n return timer_stop();\n}\n\ndouble benchmark_solve_equihash()\n{\n CBlock pblock;\n CEquihashInput I{pblock};\n CDataStream ss(SER_NETWORK, PROTOCOL_VERSION);\n ss << I;\n\n Equihash eh {Params(CBaseChainParams::MAIN).EquihashN(), Params(CBaseChainParams::MAIN).EquihashK()};\n crypto_generichash_blake2b_state eh_state;\n eh.InitialiseState(eh_state);\n crypto_generichash_blake2b_update(&eh_state, (unsigned char*)&ss[0], ss.size());\n\n uint256 nonce;\n randombytes_buf(nonce.begin(), 32);\n crypto_generichash_blake2b_update(&eh_state,\n nonce.begin(),\n nonce.size());\n\n timer_start();\n eh.BasicSolve(eh_state);\n return timer_stop();\n}\n\ndouble benchmark_verify_equihash()\n{\n CChainParams params = Params(CBaseChainParams::MAIN);\n CBlock genesis = Params(CBaseChainParams::MAIN).GenesisBlock();\n CBlockHeader genesis_header = genesis.GetBlockHeader();\n timer_start();\n CheckEquihashSolution(&genesis_header, params);\n return timer_stop();\n}\n\n<|endoftext|>"} {"text":"\/\/\n\/\/ ClockDeferrer.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 23\/08\/2018.\n\/\/ Copyright © 2018 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef ClockDeferrer_h\n#define ClockDeferrer_h\n\n#include \n\n\/*!\n\tA ClockDeferrer maintains a list of ordered actions and the times at which\n\tthey should happen, and divides a total execution period up into the portions\n\tthat occur between those actions, triggering each action when it is reached.\n\n\t@c Class should be a class that implements @c advance(TimeUnit), to advance\n\tthat amount of time.\n*\/\ntemplate class ClockDeferrer {\n\tpublic:\n\t\t\/\/\/ Constructs a ClockDeferrer that will call target.advance in between deferred actions.\n\t\tClockDeferrer(std::function &&target) : target_(std::move(target)) {}\n\n\t\t\/*!\n\t\t\tSchedules @c action to occur in @c delay units of time.\n\n\t\t\tActions must be scheduled in the order they will occur. It is undefined behaviour\n\t\t\tto schedule them out of order.\n\t\t*\/\n\t\tvoid defer(TimeUnit delay, const std::function &action) {\n\t\t\tpending_actions_.emplace_back(delay, action);\n\t\t}\n\n\t\t\/*!\n\t\t\tRuns for @c length units of time.\n\n\t\t\tThe target's @c advance will be called with one or more periods that add up to @c length;\n\t\t\tany scheduled actions will be called between periods.\n\t\t*\/\n\t\tvoid run_for(TimeUnit length) {\n\t\t\t\/\/ If there are no pending actions, just run for the entire length.\n\t\t\t\/\/ This should be the normal branch.\n\t\t\tif(pending_actions_.empty()) {\n\t\t\t\ttarget_(length);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Divide the time to run according to the pending actions.\n\t\t\twhile(length > TimeUnit(0)) {\n\t\t\t\tTimeUnit next_period = pending_actions_.empty() ? length : std::min(length, pending_actions_[0].delay);\n\t\t\t\ttarget_(next_period);\n\t\t\t\tlength -= next_period;\n\n\t\t\t\toff_t performances = 0;\n\t\t\t\tfor(auto &action: pending_actions_) {\n\t\t\t\t\taction.delay -= next_period;\n\t\t\t\t\tif(!action.delay) {\n\t\t\t\t\t\taction.action();\n\t\t\t\t\t\t++performances;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(performances) {\n\t\t\t\t\tpending_actions_.erase(pending_actions_.begin(), pending_actions_.begin() + performances);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tstd::function target_;\n\n\t\t\/\/ The list of deferred actions.\n\t\tstruct DeferredAction {\n\t\t\tTimeUnit delay;\n\t\t\tstd::function action;\n\n\t\t\tDeferredAction(TimeUnit delay, const std::function &action) : delay(delay), action(std::move(action)) {}\n\t\t};\n\t\tstd::vector pending_actions_;\n};\n\n#endif \/* ClockDeferrer_h *\/\nCorrects documentation.\/\/\n\/\/ ClockDeferrer.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 23\/08\/2018.\n\/\/ Copyright © 2018 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef ClockDeferrer_h\n#define ClockDeferrer_h\n\n#include \n\n\/*!\n\tA ClockDeferrer maintains a list of ordered actions and the times at which\n\tthey should happen, and divides a total execution period up into the portions\n\tthat occur between those actions, triggering each action when it is reached.\n*\/\ntemplate class ClockDeferrer {\n\tpublic:\n\t\t\/\/\/ Constructs a ClockDeferrer that will call target(period) in between deferred actions.\n\t\tClockDeferrer(std::function &&target) : target_(std::move(target)) {}\n\n\t\t\/*!\n\t\t\tSchedules @c action to occur in @c delay units of time.\n\n\t\t\tActions must be scheduled in the order they will occur. It is undefined behaviour\n\t\t\tto schedule them out of order.\n\t\t*\/\n\t\tvoid defer(TimeUnit delay, const std::function &action) {\n\t\t\tpending_actions_.emplace_back(delay, action);\n\t\t}\n\n\t\t\/*!\n\t\t\tRuns for @c length units of time.\n\n\t\t\tThe constructor-supplied target will be called with one or more periods that add up to @c length;\n\t\t\tany scheduled actions will be called between periods.\n\t\t*\/\n\t\tvoid run_for(TimeUnit length) {\n\t\t\t\/\/ If there are no pending actions, just run for the entire length.\n\t\t\t\/\/ This should be the normal branch.\n\t\t\tif(pending_actions_.empty()) {\n\t\t\t\ttarget_(length);\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\t\/\/ Divide the time to run according to the pending actions.\n\t\t\twhile(length > TimeUnit(0)) {\n\t\t\t\tTimeUnit next_period = pending_actions_.empty() ? length : std::min(length, pending_actions_[0].delay);\n\t\t\t\ttarget_(next_period);\n\t\t\t\tlength -= next_period;\n\n\t\t\t\toff_t performances = 0;\n\t\t\t\tfor(auto &action: pending_actions_) {\n\t\t\t\t\taction.delay -= next_period;\n\t\t\t\t\tif(!action.delay) {\n\t\t\t\t\t\taction.action();\n\t\t\t\t\t\t++performances;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif(performances) {\n\t\t\t\t\tpending_actions_.erase(pending_actions_.begin(), pending_actions_.begin() + performances);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tprivate:\n\t\tstd::function target_;\n\n\t\t\/\/ The list of deferred actions.\n\t\tstruct DeferredAction {\n\t\t\tTimeUnit delay;\n\t\t\tstd::function action;\n\n\t\t\tDeferredAction(TimeUnit delay, const std::function &action) : delay(delay), action(std::move(action)) {}\n\t\t};\n\t\tstd::vector pending_actions_;\n};\n\n#endif \/* ClockDeferrer_h *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ ClockReceiver.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 22\/07\/2017.\n\/\/ Copyright 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef ClockReceiver_hpp\n#define ClockReceiver_hpp\n\n#include \"ForceInline.hpp\"\n#include \n\n\/*\n\tInformal pattern for all classes that run from a clock cycle:\n\n\t\tEach will implement either or both of run_for(Cycles) and run_for(HalfCycles), as\n\t\tis appropriate.\n\n\t\tCallers that are accumulating HalfCycles but want to talk to receivers that implement\n\t\tonly run_for(Cycles) can use HalfCycle.flush_cycles if they have appropriate storage, or\n\t\tcan wrap the receiver in HalfClockReceiver in order automatically to bind half-cycle\n\t\tstorage to it.\n\n\tAlignment rule:\n\n\t\trun_for(Cycles) may be called only after an even number of half cycles. E.g. the following\n\t\tsequence will have undefined results:\n\n\t\t\trun_for(HalfCycles(1))\n\t\t\trun_for(Cycles(1))\n\n\t\tAn easy way to ensure this as a caller is to pick only one of run_for(Cycles) and\n\t\trun_for(HalfCycles) to use.\n\n\tReasoning:\n\n\t\tUsers of this template may with to implement run_for(Cycles) and run_for(HalfCycles)\n\t\twhere there is a need to implement at half-cycle precision but a faster execution\n\t\tpath can be offered for full-cycle precision. Those users are permitted to assume\n\t\tphase in run_for(Cycles) and should do so to be compatible with callers that use\n\t\tonly run_for(Cycles).\n\n\tCorollary:\n\n\t\tStarting from nothing, the first run_for(HalfCycles(1)) will do the **first** half\n\t\tof a full cycle. The second will do the second half. Etc.\n\n*\/\n\n\/*!\n\tProvides a class that wraps a plain int, providing most of the basic arithmetic and\n\tBoolean operators, but forcing callers and receivers to be explicit as to usage.\n*\/\ntemplate class WrappedInt {\n\tpublic:\n\t\tusing IntType = int64_t;\n\n\t\tforceinline constexpr WrappedInt(IntType l) noexcept : length_(l) {}\n\t\tforceinline constexpr WrappedInt() noexcept : length_(0) {}\n\n\t\tforceinline T &operator =(const T &rhs) {\n\t\t\tlength_ = rhs.length_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tforceinline T &operator +=(const T &rhs) {\n\t\t\tlength_ += rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator -=(const T &rhs) {\n\t\t\tlength_ -= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator ++() {\n\t\t\t++ length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator ++(int) {\n\t\t\tlength_ ++;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator --() {\n\t\t\t-- length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator --(int) {\n\t\t\tlength_ --;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator *=(const T &rhs) {\n\t\t\tlength_ *= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator \/=(const T &rhs) {\n\t\t\tlength_ \/= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator %=(const T &rhs) {\n\t\t\tlength_ %= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator &=(const T &rhs) {\n\t\t\tlength_ &= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline constexpr T operator +(const T &rhs) const\t\t\t{\treturn T(length_ + rhs.length_);\t}\n\t\tforceinline constexpr T operator -(const T &rhs) const\t\t\t{\treturn T(length_ - rhs.length_);\t}\n\n\t\tforceinline constexpr T operator *(const T &rhs) const\t\t\t{\treturn T(length_ * rhs.length_);\t}\n\t\tforceinline constexpr T operator \/(const T &rhs) const\t\t\t{\treturn T(length_ \/ rhs.length_);\t}\n\n\t\tforceinline constexpr T operator %(const T &rhs) const\t\t\t{\treturn T(length_ % rhs.length_);\t}\n\t\tforceinline constexpr T operator &(const T &rhs) const\t\t\t{\treturn T(length_ & rhs.length_);\t}\n\n\t\tforceinline constexpr T operator -() const\t\t\t\t\t\t{\treturn T(- length_);\t\t\t\t}\n\n\t\tforceinline constexpr bool operator <(const T &rhs) const\t\t{\treturn length_ < rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator >(const T &rhs) const\t\t{\treturn length_ > rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator <=(const T &rhs) const\t\t{\treturn length_ <= rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator >=(const T &rhs) const\t\t{\treturn length_ >= rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator ==(const T &rhs) const\t\t{\treturn length_ == rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator !=(const T &rhs) const\t\t{\treturn length_ != rhs.length_;\t\t}\n\n\t\tforceinline constexpr bool operator !() const\t\t\t\t\t{\treturn !length_;\t\t\t\t\t}\n\t\t\/\/ bool operator () is not supported because it offers an implicit cast to int, which is prone silently to permit misuse\n\n\t\t\/\/\/ @returns The underlying int, cast to an integral type of your choosing.\n\t\ttemplate forceinline constexpr Type as() { return Type(length_); }\n\n\t\t\/\/\/ @returns The underlying int, in its native form.\n\t\tforceinline constexpr IntType as_integral() const { return length_; }\n\n\t\t\/*!\n\t\t\tSevers from @c this the effect of dividing by @c divisor; @c this will end up with\n\t\t\tthe value of @c this modulo @c divisor and @c divided by @c divisor is returned.\n\t\t*\/\n\t\ttemplate forceinline Result divide(const T &divisor) {\n\t\t\tResult r;\n\t\t\tstatic_cast(this)->fill(r, divisor);\n\t\t\treturn r;\n\t\t}\n\n\t\t\/*!\n\t\t\tFlushes the value in @c this. The current value is returned, and the internal value\n\t\t\tis reset to zero.\n\t\t*\/\n\t\ttemplate Result flush() {\n\t\t\t\/\/ Jiggery pokery here; switching to function overloading avoids\n\t\t\t\/\/ the namespace-level requirement for template specialisation.\n\t\t\tResult r;\n\t\t\tstatic_cast(this)->fill(r);\n\t\t\treturn r;\n\t\t}\n\n\t\t\/\/ operator int() is deliberately not provided, to avoid accidental subtitution of\n\t\t\/\/ classes that use this template.\n\n\tprotected:\n\t\tIntType length_;\n};\n\n\/\/\/ Describes an integer number of whole cycles: pairs of clock signal transitions.\nclass Cycles: public WrappedInt {\n\tpublic:\n\t\tforceinline constexpr Cycles(IntType l) noexcept : WrappedInt(l) {}\n\t\tforceinline constexpr Cycles() noexcept : WrappedInt() {}\n\t\tforceinline constexpr Cycles(const Cycles &cycles) noexcept : WrappedInt(cycles.length_) {}\n\n\tprivate:\n\t\tfriend WrappedInt;\n\t\tvoid fill(Cycles &result) {\n\t\t\tresult.length_ = length_;\n\t\t\tlength_ = 0;\n\t\t}\n\n\t\tvoid fill(Cycles &result, const Cycles &divisor) {\n\t\t\tresult.length_ = length_ \/ divisor.length_;\n\t\t\tlength_ %= divisor.length_;\n\t\t}\n};\n\n\/\/\/ Describes an integer number of half cycles: single clock signal transitions.\nclass HalfCycles: public WrappedInt {\n\tpublic:\n\t\tforceinline constexpr HalfCycles(IntType l) noexcept : WrappedInt(l) {}\n\t\tforceinline constexpr HalfCycles() noexcept : WrappedInt() {}\n\n\t\tforceinline constexpr HalfCycles(const Cycles &cycles) noexcept : WrappedInt(cycles.as_integral() * 2) {}\n\t\tforceinline constexpr HalfCycles(const HalfCycles &half_cycles) noexcept : WrappedInt(half_cycles.length_) {}\n\n\t\t\/\/\/ @returns The number of whole cycles completely covered by this span of half cycles.\n\t\tforceinline constexpr Cycles cycles() const {\n\t\t\treturn Cycles(length_ >> 1);\n\t\t}\n\n\t\t\/*!\n\t\t\tSevers from @c this the effect of dividing by @c divisor; @c this will end up with\n\t\t\tthe value of @c this modulo @c divisor and @c divided by @c divisor is returned.\n\t\t*\/\n\t\tforceinline Cycles divide_cycles(const Cycles &divisor) {\n\t\t\tconst HalfCycles half_divisor = HalfCycles(divisor);\n\t\t\tconst Cycles result(length_ \/ half_divisor.length_);\n\t\t\tlength_ %= half_divisor.length_;\n\t\t\treturn result;\n\t\t}\n\n\tprivate:\n\t\tfriend WrappedInt;\n\t\tvoid fill(Cycles &result) {\n\t\t\tresult = Cycles(length_ >> 1);\n\t\t\tlength_ &= 1;\n\t\t}\n\n\t\tvoid fill(HalfCycles &result) {\n\t\t\tresult.length_ = length_;\n\t\t\tlength_ = 0;\n\t\t}\n\n\t\tvoid fill(Cycles &result, const HalfCycles &divisor) {\n\t\t\tresult = Cycles(length_ \/ (divisor.length_ << 1));\n\t\t\tlength_ %= (divisor.length_ << 1);\n\t\t}\n\n\t\tvoid fill(HalfCycles &result, const HalfCycles &divisor) {\n\t\t\tresult.length_ = length_ \/ divisor.length_;\n\t\t\tlength_ %= divisor.length_;\n\t\t}\n};\n\n\/\/ Create a specialisation of WrappedInt::flush for converting HalfCycles to Cycles\n\/\/ without losing the fractional part.\n\n\/*!\n\tIf a component implements only run_for(Cycles), an owner can wrap it in HalfClockReceiver\n\tautomatically to gain run_for(HalfCycles).\n*\/\ntemplate class HalfClockReceiver: public T {\n\tpublic:\n\t\tusing T::T;\n\n\t\tforceinline void run_for(const HalfCycles half_cycles) {\n\t\t\thalf_cycles_ += half_cycles;\n\t\t\tT::run_for(half_cycles_.flush());\n\t\t}\n\n\tprivate:\n\t\tHalfCycles half_cycles_;\n};\n\n#endif \/* ClockReceiver_hpp *\/\nCorrects lack of `const`.\/\/\n\/\/ ClockReceiver.hpp\n\/\/ Clock Signal\n\/\/\n\/\/ Created by Thomas Harte on 22\/07\/2017.\n\/\/ Copyright 2017 Thomas Harte. All rights reserved.\n\/\/\n\n#ifndef ClockReceiver_hpp\n#define ClockReceiver_hpp\n\n#include \"ForceInline.hpp\"\n#include \n\n\/*\n\tInformal pattern for all classes that run from a clock cycle:\n\n\t\tEach will implement either or both of run_for(Cycles) and run_for(HalfCycles), as\n\t\tis appropriate.\n\n\t\tCallers that are accumulating HalfCycles but want to talk to receivers that implement\n\t\tonly run_for(Cycles) can use HalfCycle.flush_cycles if they have appropriate storage, or\n\t\tcan wrap the receiver in HalfClockReceiver in order automatically to bind half-cycle\n\t\tstorage to it.\n\n\tAlignment rule:\n\n\t\trun_for(Cycles) may be called only after an even number of half cycles. E.g. the following\n\t\tsequence will have undefined results:\n\n\t\t\trun_for(HalfCycles(1))\n\t\t\trun_for(Cycles(1))\n\n\t\tAn easy way to ensure this as a caller is to pick only one of run_for(Cycles) and\n\t\trun_for(HalfCycles) to use.\n\n\tReasoning:\n\n\t\tUsers of this template may with to implement run_for(Cycles) and run_for(HalfCycles)\n\t\twhere there is a need to implement at half-cycle precision but a faster execution\n\t\tpath can be offered for full-cycle precision. Those users are permitted to assume\n\t\tphase in run_for(Cycles) and should do so to be compatible with callers that use\n\t\tonly run_for(Cycles).\n\n\tCorollary:\n\n\t\tStarting from nothing, the first run_for(HalfCycles(1)) will do the **first** half\n\t\tof a full cycle. The second will do the second half. Etc.\n\n*\/\n\n\/*!\n\tProvides a class that wraps a plain int, providing most of the basic arithmetic and\n\tBoolean operators, but forcing callers and receivers to be explicit as to usage.\n*\/\ntemplate class WrappedInt {\n\tpublic:\n\t\tusing IntType = int64_t;\n\n\t\tforceinline constexpr WrappedInt(IntType l) noexcept : length_(l) {}\n\t\tforceinline constexpr WrappedInt() noexcept : length_(0) {}\n\n\t\tforceinline T &operator =(const T &rhs) {\n\t\t\tlength_ = rhs.length_;\n\t\t\treturn *this;\n\t\t}\n\n\t\tforceinline T &operator +=(const T &rhs) {\n\t\t\tlength_ += rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator -=(const T &rhs) {\n\t\t\tlength_ -= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator ++() {\n\t\t\t++ length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator ++(int) {\n\t\t\tlength_ ++;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator --() {\n\t\t\t-- length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator --(int) {\n\t\t\tlength_ --;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator *=(const T &rhs) {\n\t\t\tlength_ *= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator \/=(const T &rhs) {\n\t\t\tlength_ \/= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator %=(const T &rhs) {\n\t\t\tlength_ %= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline T &operator &=(const T &rhs) {\n\t\t\tlength_ &= rhs.length_;\n\t\t\treturn *static_cast(this);\n\t\t}\n\n\t\tforceinline constexpr T operator +(const T &rhs) const\t\t\t{\treturn T(length_ + rhs.length_);\t}\n\t\tforceinline constexpr T operator -(const T &rhs) const\t\t\t{\treturn T(length_ - rhs.length_);\t}\n\n\t\tforceinline constexpr T operator *(const T &rhs) const\t\t\t{\treturn T(length_ * rhs.length_);\t}\n\t\tforceinline constexpr T operator \/(const T &rhs) const\t\t\t{\treturn T(length_ \/ rhs.length_);\t}\n\n\t\tforceinline constexpr T operator %(const T &rhs) const\t\t\t{\treturn T(length_ % rhs.length_);\t}\n\t\tforceinline constexpr T operator &(const T &rhs) const\t\t\t{\treturn T(length_ & rhs.length_);\t}\n\n\t\tforceinline constexpr T operator -() const\t\t\t\t\t\t{\treturn T(- length_);\t\t\t\t}\n\n\t\tforceinline constexpr bool operator <(const T &rhs) const\t\t{\treturn length_ < rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator >(const T &rhs) const\t\t{\treturn length_ > rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator <=(const T &rhs) const\t\t{\treturn length_ <= rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator >=(const T &rhs) const\t\t{\treturn length_ >= rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator ==(const T &rhs) const\t\t{\treturn length_ == rhs.length_;\t\t}\n\t\tforceinline constexpr bool operator !=(const T &rhs) const\t\t{\treturn length_ != rhs.length_;\t\t}\n\n\t\tforceinline constexpr bool operator !() const\t\t\t\t\t{\treturn !length_;\t\t\t\t\t}\n\t\t\/\/ bool operator () is not supported because it offers an implicit cast to int, which is prone silently to permit misuse\n\n\t\t\/\/\/ @returns The underlying int, cast to an integral type of your choosing.\n\t\ttemplate forceinline constexpr Type as() const { return Type(length_); }\n\n\t\t\/\/\/ @returns The underlying int, in its native form.\n\t\tforceinline constexpr IntType as_integral() const { return length_; }\n\n\t\t\/*!\n\t\t\tSevers from @c this the effect of dividing by @c divisor; @c this will end up with\n\t\t\tthe value of @c this modulo @c divisor and @c divided by @c divisor is returned.\n\t\t*\/\n\t\ttemplate forceinline Result divide(const T &divisor) {\n\t\t\tResult r;\n\t\t\tstatic_cast(this)->fill(r, divisor);\n\t\t\treturn r;\n\t\t}\n\n\t\t\/*!\n\t\t\tFlushes the value in @c this. The current value is returned, and the internal value\n\t\t\tis reset to zero.\n\t\t*\/\n\t\ttemplate Result flush() {\n\t\t\t\/\/ Jiggery pokery here; switching to function overloading avoids\n\t\t\t\/\/ the namespace-level requirement for template specialisation.\n\t\t\tResult r;\n\t\t\tstatic_cast(this)->fill(r);\n\t\t\treturn r;\n\t\t}\n\n\t\t\/\/ operator int() is deliberately not provided, to avoid accidental subtitution of\n\t\t\/\/ classes that use this template.\n\n\tprotected:\n\t\tIntType length_;\n};\n\n\/\/\/ Describes an integer number of whole cycles: pairs of clock signal transitions.\nclass Cycles: public WrappedInt {\n\tpublic:\n\t\tforceinline constexpr Cycles(IntType l) noexcept : WrappedInt(l) {}\n\t\tforceinline constexpr Cycles() noexcept : WrappedInt() {}\n\t\tforceinline constexpr Cycles(const Cycles &cycles) noexcept : WrappedInt(cycles.length_) {}\n\n\tprivate:\n\t\tfriend WrappedInt;\n\t\tvoid fill(Cycles &result) {\n\t\t\tresult.length_ = length_;\n\t\t\tlength_ = 0;\n\t\t}\n\n\t\tvoid fill(Cycles &result, const Cycles &divisor) {\n\t\t\tresult.length_ = length_ \/ divisor.length_;\n\t\t\tlength_ %= divisor.length_;\n\t\t}\n};\n\n\/\/\/ Describes an integer number of half cycles: single clock signal transitions.\nclass HalfCycles: public WrappedInt {\n\tpublic:\n\t\tforceinline constexpr HalfCycles(IntType l) noexcept : WrappedInt(l) {}\n\t\tforceinline constexpr HalfCycles() noexcept : WrappedInt() {}\n\n\t\tforceinline constexpr HalfCycles(const Cycles &cycles) noexcept : WrappedInt(cycles.as_integral() * 2) {}\n\t\tforceinline constexpr HalfCycles(const HalfCycles &half_cycles) noexcept : WrappedInt(half_cycles.length_) {}\n\n\t\t\/\/\/ @returns The number of whole cycles completely covered by this span of half cycles.\n\t\tforceinline constexpr Cycles cycles() const {\n\t\t\treturn Cycles(length_ >> 1);\n\t\t}\n\n\t\t\/*!\n\t\t\tSevers from @c this the effect of dividing by @c divisor; @c this will end up with\n\t\t\tthe value of @c this modulo @c divisor and @c divided by @c divisor is returned.\n\t\t*\/\n\t\tforceinline Cycles divide_cycles(const Cycles &divisor) {\n\t\t\tconst HalfCycles half_divisor = HalfCycles(divisor);\n\t\t\tconst Cycles result(length_ \/ half_divisor.length_);\n\t\t\tlength_ %= half_divisor.length_;\n\t\t\treturn result;\n\t\t}\n\n\tprivate:\n\t\tfriend WrappedInt;\n\t\tvoid fill(Cycles &result) {\n\t\t\tresult = Cycles(length_ >> 1);\n\t\t\tlength_ &= 1;\n\t\t}\n\n\t\tvoid fill(HalfCycles &result) {\n\t\t\tresult.length_ = length_;\n\t\t\tlength_ = 0;\n\t\t}\n\n\t\tvoid fill(Cycles &result, const HalfCycles &divisor) {\n\t\t\tresult = Cycles(length_ \/ (divisor.length_ << 1));\n\t\t\tlength_ %= (divisor.length_ << 1);\n\t\t}\n\n\t\tvoid fill(HalfCycles &result, const HalfCycles &divisor) {\n\t\t\tresult.length_ = length_ \/ divisor.length_;\n\t\t\tlength_ %= divisor.length_;\n\t\t}\n};\n\n\/\/ Create a specialisation of WrappedInt::flush for converting HalfCycles to Cycles\n\/\/ without losing the fractional part.\n\n\/*!\n\tIf a component implements only run_for(Cycles), an owner can wrap it in HalfClockReceiver\n\tautomatically to gain run_for(HalfCycles).\n*\/\ntemplate class HalfClockReceiver: public T {\n\tpublic:\n\t\tusing T::T;\n\n\t\tforceinline void run_for(const HalfCycles half_cycles) {\n\t\t\thalf_cycles_ += half_cycles;\n\t\t\tT::run_for(half_cycles_.flush());\n\t\t}\n\n\tprivate:\n\t\tHalfCycles half_cycles_;\n};\n\n#endif \/* ClockReceiver_hpp *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ Ensure that gtest is the first header otherwise Windows raises an error\n#include \n\/\/ Keep this comment to keep gtest.h above. (clang-format off\/on is not working here!)\n\n#include \"agent_test_helper.hpp\"\n#include \"pipeline\/shdr_token_mapper.hpp\"\n#include \"pipeline\/duplicate_filter.hpp\"\n#include \"pipeline\/delta_filter.hpp\"\n#include \"pipeline\/deliver.hpp\"\n#include \"pipeline\/pipeline.hpp\"\n#include \"observation\/observation.hpp\"\n#include \"adapter\/adapter.hpp\"\n#include \n\nusing namespace mtconnect;\nusing namespace mtconnect::adapter;\nusing namespace mtconnect::pipeline;\nusing namespace mtconnect::observation;\nusing namespace std;\nusing namespace std::literals;\nusing namespace std::chrono_literals;\n\nclass PipelineDeliverTest : public testing::Test\n{\n protected:\n void SetUp() override\n { \/\/ Create an agent with only 16 slots and 8 data items.\n m_agentTestHelper = make_unique();\n m_agentTestHelper->createAgent(\"\/samples\/SimpleDevlce.xml\",\n 8, 4, \"1.7\", 25);\n m_agentId = to_string(getCurrentTimeInSec());\n m_device = m_agentTestHelper->m_agent->getDeviceByName(\"LinuxCNC\");\n }\n\n void TearDown() override\n {\n m_agentTestHelper.reset();\n }\n\n std::unique_ptr m_agentTestHelper;\n std::string m_agentId;\n Device *m_device{nullptr};\n};\n\nTEST_F(PipelineDeliverTest, test_simple_flow)\n{\n m_agentTestHelper->addAdapter();\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"Xpos\", obs->getDataItem()->getName());\n ASSERT_EQ(100.0, obs->getValue());\n ASSERT_EQ(\"2021-01-22T12:33:45.123Z\", format(obs->getTimestamp()));\n}\n\nTEST_F(PipelineDeliverTest, filter_duplicates)\n{\n ConfigOptions options{{configuration::FilterDuplicates, true}};\n m_agentTestHelper->addAdapter(options);\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n \n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"Xpos\", obs->getDataItem()->getName());\n ASSERT_EQ(100.0, obs->getValue());\n \n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|101.0\");\n ASSERT_EQ(seq + 2, m_agentTestHelper->m_agent->getSequence());\n auto obs2 = m_agentTestHelper->m_agent->getFromBuffer(seq + 1);\n ASSERT_EQ(101.0, obs2->getValue());\n}\n\n\/\/a01c7f30\nTEST_F(PipelineDeliverTest, filter_upcase)\n{\n ConfigOptions options{{configuration::UpcaseDataItemValue, true}};\n m_agentTestHelper->addAdapter(options);\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|a01c7f30|active\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n \n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"a01c7f30\", obs->getDataItem()->getId());\n ASSERT_EQ(\"ACTIVE\", obs->getValue());\n \n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|101.0\");\n ASSERT_EQ(seq + 2, m_agentTestHelper->m_agent->getSequence());\n auto obs2 = m_agentTestHelper->m_agent->getFromBuffer(seq + 1);\n ASSERT_EQ(101.0, obs2->getValue());\n}\n\nAdded tests for unit conversion and sample duration\/\/\n\/\/ Copyright Copyright 2009-2021, AMT – The Association For Manufacturing Technology (“AMT”)\n\/\/ All rights reserved.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\/\/\n\n\/\/ Ensure that gtest is the first header otherwise Windows raises an error\n#include \n\/\/ Keep this comment to keep gtest.h above. (clang-format off\/on is not working here!)\n\n#include \"agent_test_helper.hpp\"\n#include \"pipeline\/shdr_token_mapper.hpp\"\n#include \"pipeline\/duplicate_filter.hpp\"\n#include \"pipeline\/delta_filter.hpp\"\n#include \"pipeline\/deliver.hpp\"\n#include \"pipeline\/pipeline.hpp\"\n#include \"observation\/observation.hpp\"\n#include \"adapter\/adapter.hpp\"\n#include \n\nusing namespace mtconnect;\nusing namespace mtconnect::adapter;\nusing namespace mtconnect::pipeline;\nusing namespace mtconnect::observation;\nusing namespace std;\nusing namespace std::literals;\nusing namespace std::chrono_literals;\n\nclass PipelineDeliverTest : public testing::Test\n{\n protected:\n void SetUp() override\n { \/\/ Create an agent with only 16 slots and 8 data items.\n m_agentTestHelper = make_unique();\n m_agentTestHelper->createAgent(\"\/samples\/SimpleDevlce.xml\",\n 8, 4, \"1.7\", 25);\n m_agentId = to_string(getCurrentTimeInSec());\n m_device = m_agentTestHelper->m_agent->getDeviceByName(\"LinuxCNC\");\n }\n\n void TearDown() override\n {\n m_agentTestHelper.reset();\n }\n\n std::unique_ptr m_agentTestHelper;\n std::string m_agentId;\n Device *m_device{nullptr};\n};\n\nTEST_F(PipelineDeliverTest, test_simple_flow)\n{\n m_agentTestHelper->addAdapter();\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"Xpos\", obs->getDataItem()->getName());\n ASSERT_EQ(100.0, obs->getValue());\n ASSERT_EQ(\"2021-01-22T12:33:45.123Z\", format(obs->getTimestamp()));\n}\n\nTEST_F(PipelineDeliverTest, filter_duplicates)\n{\n ConfigOptions options{{configuration::FilterDuplicates, true}};\n m_agentTestHelper->addAdapter(options);\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n \n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"Xpos\", obs->getDataItem()->getName());\n ASSERT_EQ(100.0, obs->getValue());\n \n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|101.0\");\n ASSERT_EQ(seq + 2, m_agentTestHelper->m_agent->getSequence());\n auto obs2 = m_agentTestHelper->m_agent->getFromBuffer(seq + 1);\n ASSERT_EQ(101.0, obs2->getValue());\n}\n\n\/\/a01c7f30\nTEST_F(PipelineDeliverTest, filter_upcase)\n{\n ConfigOptions options{{configuration::UpcaseDataItemValue, true}};\n m_agentTestHelper->addAdapter(options);\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|a01c7f30|active\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n \n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"a01c7f30\", obs->getDataItem()->getId());\n ASSERT_EQ(\"ACTIVE\", obs->getValue());\n \n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z|Xpos|101.0\");\n ASSERT_EQ(seq + 2, m_agentTestHelper->m_agent->getSequence());\n auto obs2 = m_agentTestHelper->m_agent->getFromBuffer(seq + 1);\n ASSERT_EQ(101.0, obs2->getValue());\n}\n\nTEST_F(PipelineDeliverTest, extract_duration) \n{\n m_agentTestHelper->addAdapter();\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:45.123Z@200.1232|Xpos|100.0\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"Xpos\", obs->getDataItem()->getName());\n ASSERT_EQ(100.0, obs->getValue());\n ASSERT_EQ(\"2021-01-22T12:33:45.123Z\", format(obs->getTimestamp()));\n ASSERT_EQ(200.1232, obs->get(\"duration\"));\n}\n\nTEST_F(PipelineDeliverTest, unit_conversion)\n{\n m_agentTestHelper->addAdapter(ConfigOptions{{configuration::ConversionRequired, true}});\n auto seq = m_agentTestHelper->m_agent->getSequence();\n m_agentTestHelper->m_adapter->processData(\"2021-01-22T12:33:48.123Z|amp|10.1\");\n ASSERT_EQ(seq + 1, m_agentTestHelper->m_agent->getSequence());\n auto obs = m_agentTestHelper->m_agent->getFromBuffer(seq);\n ASSERT_TRUE(obs);\n ASSERT_EQ(\"amp\", obs->getDataItem()->getName());\n ASSERT_EQ(\"KILOAMPERE\", obs->getDataItem()->getNativeUnits());\n std::cout << obs->get(\"VALUE\");\n ASSERT_EQ(10100.0, obs->getValue());\n}<|endoftext|>"} {"text":"\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"osl\/module.h\"\n#include \"osl\/process.h\"\n\n#include \"rtl\/ustrbuf.hxx\"\n\n#include \"salinst.hxx\"\n#include \"generic\/gensys.h\"\n#include \"generic\/gendata.hxx\"\n#include \"unx\/desktops.hxx\"\n#include \"vcl\/printerinfomanager.hxx\"\n\n#include \n#include \n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\nextern \"C\" {\ntypedef SalInstance*(*salFactoryProc)( oslModule pModule);\n}\n\nstatic oslModule pCloseModule = NULL;\n\nstatic SalInstance* tryInstance( const OUString& rModuleBase )\n{\n SalInstance* pInst = NULL;\n\n \/\/ Disable gtk3 plugin load except in experimental mode for now.\n if( rModuleBase.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( \"gtk3\" ) ) &&\n !SalGenericSystem::enableExperimentalFeatures() )\n return NULL;\n\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"vclplug_\" );\n aModName.append( rModuleBase );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n if( aMod )\n {\n salFactoryProc aProc = (salFactoryProc)osl_getAsciiFunctionSymbol( aMod, \"create_SalInstance\" );\n if( aProc )\n {\n pInst = aProc( aMod );\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"sal plugin %s produced instance %p\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(),\n pInst );\n#endif\n if( pInst )\n {\n pCloseModule = aMod;\n\n#ifndef ANDROID\n \/*\n * Recent GTK+ versions load their modules with RTLD_LOCAL, so we can\n * not access the 'gnome_accessibility_module_shutdown' anymore.\n * So make sure libgtk+ & co are still mapped into memory when\n * atk-bridge's atexit handler gets called.\n *\/\n if( rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"gtk\")) ||\n rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"gtk3\")) )\n {\n pCloseModule = NULL;\n }\n \/*\n * #i109007# KDE3 seems to have the same problem; an atexit cleanup\n * handler, which cannot be resolved anymore if the plugin is already unloaded.\n *\/\n else if( rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"kde\")) )\n {\n pCloseModule = NULL;\n }\n#endif\n GetSalData()->m_pPlugin = aMod;\n }\n else\n osl_unloadModule( aMod );\n }\n else\n {\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"could not load symbol %s from shared object %s\\n\",\n \"create_SalInstance\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n osl_unloadModule( aMod );\n }\n }\n#if OSL_DEBUG_LEVEL > 1\n else\n std::fprintf( stderr, \"could not load shared object %s\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n\n return pInst;\n}\n\n#ifndef ANDROID\n\nstatic DesktopType get_desktop_environment()\n{\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"desktop_detector\" );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n DesktopType ret = DESKTOP_UNKNOWN;\n if( aMod )\n {\n DesktopType (*pSym)() = (DesktopType(*)())\n osl_getAsciiFunctionSymbol( aMod, \"get_desktop_environment\" );\n if( pSym )\n ret = pSym();\n }\n osl_unloadModule( aMod );\n return ret;\n}\n\n#else\n\n#define get_desktop_environment() DESKTOP_NONE \/\/ For now...\n\n#endif\n\nstatic SalInstance* autodetect_plugin()\n{\n static const char* pKDEFallbackList[] =\n {\n \"kde4\", \"kde\", \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pStandardFallbackList[] =\n {\n \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pHeadlessFallbackList[] =\n {\n \"svp\", 0\n };\n\n DesktopType desktop = get_desktop_environment();\n const char ** pList = pStandardFallbackList;\n int nListEntry = 0;\n\n \/\/ no server at all: dummy plugin\n if ( desktop == DESKTOP_NONE )\n pList = pHeadlessFallbackList;\n else if ( desktop == DESKTOP_GNOME )\n pList = pStandardFallbackList;\n else if( desktop == DESKTOP_KDE )\n {\n pList = pKDEFallbackList;\n nListEntry = 1;\n }\n else if( desktop == DESKTOP_KDE4 )\n pList = pKDEFallbackList;\n\n SalInstance* pInst = NULL;\n while( pList[nListEntry] && pInst == NULL )\n {\n rtl::OUString aTry( rtl::OUString::createFromAscii( pList[nListEntry] ) );\n pInst = tryInstance( aTry );\n #if OSL_DEBUG_LEVEL > 1\n if( pInst )\n std::fprintf( stderr, \"plugin autodetection: %s\\n\", pList[nListEntry] );\n #endif\n nListEntry++;\n }\n\n return pInst;\n}\n\nstatic SalInstance* check_headless_plugin()\n{\n int nParams = osl_getCommandArgCount();\n OUString aParam;\n for( int i = 0; i < nParams; i++ )\n {\n osl_getCommandArg( i, &aParam.pData );\n if( aParam.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"-headless\")) ||\n aParam.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"--headless\")) )\n {\n return tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( \"svp\" ) ) );\n }\n }\n return NULL;\n}\n\nSalInstance *CreateSalInstance()\n{\n SalInstance* pInst = NULL;\n\n static const char* pUsePlugin = getenv( \"SAL_USE_VCLPLUGIN\" );\n\n pInst = check_headless_plugin();\n\n if( !pInst && pUsePlugin && *pUsePlugin )\n pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) );\n\n if( ! pInst )\n pInst = autodetect_plugin();\n\n \/\/ fallback, try everything\n const char* pPlugin[] = { \"gtk3\", \"gtk\", \"kde4\", \"kde\", \"gen\", 0 };\n\n for ( int i = 0; !pInst && pPlugin[ i ]; ++i )\n pInst = tryInstance( OUString::createFromAscii( pPlugin[ i ] ) );\n\n if( ! pInst )\n {\n std::fprintf( stderr, \"no suitable windowing system found, exiting.\\n\" );\n _exit( 1 );\n }\n\n \/\/ acquire SolarMutex\n pInst->AcquireYieldMutex( 1 );\n\n return pInst;\n}\n\nvoid DestroySalInstance( SalInstance *pInst )\n{\n \/\/ release SolarMutex\n pInst->ReleaseYieldMutex();\n\n delete pInst;\n if( pCloseModule )\n osl_unloadModule( pCloseModule );\n}\n\nvoid InitSalData()\n{\n}\n\nvoid DeInitSalData()\n{\n}\n\nvoid InitSalMain()\n{\n}\n\nvoid DeInitSalMain()\n{\n}\n\nvoid SalAbort( const rtl::OUString& rErrorText, bool bDumpCore )\n{\n if( rErrorText.isEmpty() )\n std::fprintf( stderr, \"Application Error\\n\" );\n else\n std::fprintf( stderr, \"%s\\n\", rtl::OUStringToOString(rErrorText, osl_getThreadTextEncoding()).getStr() );\n if( bDumpCore )\n abort();\n else\n _exit(1);\n}\n\nstatic const char * desktop_strings[] = { \"none\", \"unknown\", \"GNOME\", \"KDE\", \"KDE4\" };\n\nconst OUString& SalGetDesktopEnvironment()\n{\n static rtl::OUString aRet;\n if( aRet.isEmpty())\n {\n rtl::OUStringBuffer buf( 8 );\n buf.appendAscii( desktop_strings[ get_desktop_environment() ] );\n aRet = buf.makeStringAndClear();\n }\n return aRet;\n}\n\nSalData::SalData() :\n m_pInstance(NULL),\n m_pPlugin(NULL),\n m_pPIManager(NULL)\n{\n}\n\nSalData::~SalData()\n{\n psp::PrinterInfoManager::release();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\nThe \"generic\" thing is X11-specific\/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- *\/\n\/*************************************************************************\n *\n * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.\n *\n * Copyright 2000, 2010 Oracle and\/or its affiliates.\n *\n * OpenOffice.org - a multi-platform office productivity suite\n *\n * This file is part of OpenOffice.org.\n *\n * OpenOffice.org is free software: you can redistribute it and\/or modify\n * it under the terms of the GNU Lesser General Public License version 3\n * only, as published by the Free Software Foundation.\n *\n * OpenOffice.org is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n * GNU Lesser General Public License version 3 for more details\n * (a copy is included in the LICENSE file that accompanied this code).\n *\n * You should have received a copy of the GNU Lesser General Public License\n * version 3 along with OpenOffice.org. If not, see\n * \n * for a copy of the LGPLv3 License.\n *\n ************************************************************************\/\n\n\n#include \"osl\/module.h\"\n#include \"osl\/process.h\"\n\n#include \"rtl\/ustrbuf.hxx\"\n\n#include \"salinst.hxx\"\n#include \"generic\/gensys.h\"\n#include \"generic\/gendata.hxx\"\n#include \"unx\/desktops.hxx\"\n#include \"vcl\/printerinfomanager.hxx\"\n\n#include \n#include \n\nusing ::rtl::OUString;\nusing ::rtl::OUStringBuffer;\nextern \"C\" {\ntypedef SalInstance*(*salFactoryProc)( oslModule pModule);\n}\n\nstatic oslModule pCloseModule = NULL;\n\nstatic SalInstance* tryInstance( const OUString& rModuleBase )\n{\n SalInstance* pInst = NULL;\n#ifndef ANDROID\n \/\/ Disable gtk3 plugin load except in experimental mode for now.\n if( rModuleBase.equalsAsciiL( RTL_CONSTASCII_STRINGPARAM( \"gtk3\" ) ) &&\n !SalGenericSystem::enableExperimentalFeatures() )\n return NULL;\n#endif\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"vclplug_\" );\n aModName.append( rModuleBase );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n if( aMod )\n {\n salFactoryProc aProc = (salFactoryProc)osl_getAsciiFunctionSymbol( aMod, \"create_SalInstance\" );\n if( aProc )\n {\n pInst = aProc( aMod );\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"sal plugin %s produced instance %p\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr(),\n pInst );\n#endif\n if( pInst )\n {\n pCloseModule = aMod;\n\n#ifndef ANDROID\n \/*\n * Recent GTK+ versions load their modules with RTLD_LOCAL, so we can\n * not access the 'gnome_accessibility_module_shutdown' anymore.\n * So make sure libgtk+ & co are still mapped into memory when\n * atk-bridge's atexit handler gets called.\n *\/\n if( rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"gtk\")) ||\n rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"gtk3\")) )\n {\n pCloseModule = NULL;\n }\n \/*\n * #i109007# KDE3 seems to have the same problem; an atexit cleanup\n * handler, which cannot be resolved anymore if the plugin is already unloaded.\n *\/\n else if( rModuleBase.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"kde\")) )\n {\n pCloseModule = NULL;\n }\n#endif\n GetSalData()->m_pPlugin = aMod;\n }\n else\n osl_unloadModule( aMod );\n }\n else\n {\n#if OSL_DEBUG_LEVEL > 1\n std::fprintf( stderr, \"could not load symbol %s from shared object %s\\n\",\n \"create_SalInstance\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n osl_unloadModule( aMod );\n }\n }\n#if OSL_DEBUG_LEVEL > 1\n else\n std::fprintf( stderr, \"could not load shared object %s\\n\",\n OUStringToOString( aModule, RTL_TEXTENCODING_ASCII_US ).getStr() );\n#endif\n\n return pInst;\n}\n\n#ifndef ANDROID\n\nstatic DesktopType get_desktop_environment()\n{\n OUStringBuffer aModName( 128 );\n aModName.appendAscii( SAL_DLLPREFIX\"desktop_detector\" );\n aModName.appendAscii( SAL_DLLPOSTFIX );\n OUString aModule = aModName.makeStringAndClear();\n\n oslModule aMod = osl_loadModuleRelative(\n reinterpret_cast< oslGenericFunction >( &tryInstance ), aModule.pData,\n SAL_LOADMODULE_DEFAULT );\n DesktopType ret = DESKTOP_UNKNOWN;\n if( aMod )\n {\n DesktopType (*pSym)() = (DesktopType(*)())\n osl_getAsciiFunctionSymbol( aMod, \"get_desktop_environment\" );\n if( pSym )\n ret = pSym();\n }\n osl_unloadModule( aMod );\n return ret;\n}\n\n#else\n\n#define get_desktop_environment() DESKTOP_NONE \/\/ For now...\n\n#endif\n\nstatic SalInstance* autodetect_plugin()\n{\n static const char* pKDEFallbackList[] =\n {\n \"kde4\", \"kde\", \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pStandardFallbackList[] =\n {\n \"gtk3\", \"gtk\", \"gen\", 0\n };\n\n static const char* pHeadlessFallbackList[] =\n {\n \"svp\", 0\n };\n\n DesktopType desktop = get_desktop_environment();\n const char ** pList = pStandardFallbackList;\n int nListEntry = 0;\n\n \/\/ no server at all: dummy plugin\n if ( desktop == DESKTOP_NONE )\n pList = pHeadlessFallbackList;\n else if ( desktop == DESKTOP_GNOME )\n pList = pStandardFallbackList;\n else if( desktop == DESKTOP_KDE )\n {\n pList = pKDEFallbackList;\n nListEntry = 1;\n }\n else if( desktop == DESKTOP_KDE4 )\n pList = pKDEFallbackList;\n\n SalInstance* pInst = NULL;\n while( pList[nListEntry] && pInst == NULL )\n {\n rtl::OUString aTry( rtl::OUString::createFromAscii( pList[nListEntry] ) );\n pInst = tryInstance( aTry );\n #if OSL_DEBUG_LEVEL > 1\n if( pInst )\n std::fprintf( stderr, \"plugin autodetection: %s\\n\", pList[nListEntry] );\n #endif\n nListEntry++;\n }\n\n return pInst;\n}\n\nstatic SalInstance* check_headless_plugin()\n{\n int nParams = osl_getCommandArgCount();\n OUString aParam;\n for( int i = 0; i < nParams; i++ )\n {\n osl_getCommandArg( i, &aParam.pData );\n if( aParam.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"-headless\")) ||\n aParam.equalsAsciiL(RTL_CONSTASCII_STRINGPARAM(\"--headless\")) )\n {\n return tryInstance( OUString( RTL_CONSTASCII_USTRINGPARAM( \"svp\" ) ) );\n }\n }\n return NULL;\n}\n\nSalInstance *CreateSalInstance()\n{\n SalInstance* pInst = NULL;\n\n static const char* pUsePlugin = getenv( \"SAL_USE_VCLPLUGIN\" );\n\n pInst = check_headless_plugin();\n\n if( !pInst && pUsePlugin && *pUsePlugin )\n pInst = tryInstance( OUString::createFromAscii( pUsePlugin ) );\n\n if( ! pInst )\n pInst = autodetect_plugin();\n\n \/\/ fallback, try everything\n const char* pPlugin[] = { \"gtk3\", \"gtk\", \"kde4\", \"kde\", \"gen\", 0 };\n\n for ( int i = 0; !pInst && pPlugin[ i ]; ++i )\n pInst = tryInstance( OUString::createFromAscii( pPlugin[ i ] ) );\n\n if( ! pInst )\n {\n std::fprintf( stderr, \"no suitable windowing system found, exiting.\\n\" );\n _exit( 1 );\n }\n\n \/\/ acquire SolarMutex\n pInst->AcquireYieldMutex( 1 );\n\n return pInst;\n}\n\nvoid DestroySalInstance( SalInstance *pInst )\n{\n \/\/ release SolarMutex\n pInst->ReleaseYieldMutex();\n\n delete pInst;\n if( pCloseModule )\n osl_unloadModule( pCloseModule );\n}\n\nvoid InitSalData()\n{\n}\n\nvoid DeInitSalData()\n{\n}\n\nvoid InitSalMain()\n{\n}\n\nvoid DeInitSalMain()\n{\n}\n\nvoid SalAbort( const rtl::OUString& rErrorText, bool bDumpCore )\n{\n if( rErrorText.isEmpty() )\n std::fprintf( stderr, \"Application Error\\n\" );\n else\n std::fprintf( stderr, \"%s\\n\", rtl::OUStringToOString(rErrorText, osl_getThreadTextEncoding()).getStr() );\n if( bDumpCore )\n abort();\n else\n _exit(1);\n}\n\nstatic const char * desktop_strings[] = { \"none\", \"unknown\", \"GNOME\", \"KDE\", \"KDE4\" };\n\nconst OUString& SalGetDesktopEnvironment()\n{\n static rtl::OUString aRet;\n if( aRet.isEmpty())\n {\n rtl::OUStringBuffer buf( 8 );\n buf.appendAscii( desktop_strings[ get_desktop_environment() ] );\n aRet = buf.makeStringAndClear();\n }\n return aRet;\n}\n\nSalData::SalData() :\n m_pInstance(NULL),\n m_pPlugin(NULL),\n m_pPIManager(NULL)\n{\n}\n\nSalData::~SalData()\n{\n psp::PrinterInfoManager::release();\n}\n\n\/* vim:set shiftwidth=4 softtabstop=4 expandtab: *\/\n<|endoftext|>"} {"text":"#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Main\n#include \"test_common.h\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nclass BenchCallback : public dariadb::IReadCallback {\npublic:\n BenchCallback() { count = 0; }\n void call(const dariadb::Meas &) { count++; }\n size_t count;\n};\n\nBOOST_AUTO_TEST_CASE(Engine_common_test) {\n const std::string storage_path = \"testStorage\";\n const size_t chunk_size = 256;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n using namespace dariadb;\n using namespace dariadb::storage;\n {\n std::cout << \"Engine_common_test.\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->wal_cache_size.setValue(100);\n settings->wal_file_size.setValue(settings->wal_cache_size.value() * 5);\n settings->chunk_size.setValue(chunk_size);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, true, false);\n\n auto pages_count = ms->description().pages_count;\n BOOST_CHECK_GE(pages_count, size_t(2));\n BOOST_CHECK(ms->settings() != nullptr);\n BOOST_CHECK(ms->settings()->storage_path.value() == storage_path);\n }\n {\n std::cout << \"reopen closed storage\\n\";\n \n\tauto ms = dariadb::open_storage(storage_path);\n\tauto settings = ms->settings();\n \n auto index_files = dariadb::utils::fs::ls(settings->raw_path.value(), \".pagei\");\n BOOST_CHECK(!index_files.empty());\n for (auto &f : index_files) {\n dariadb::utils::fs::rm(f);\n }\n index_files = dariadb::utils::fs::ls(settings->raw_path.value(), \".pagei\");\n BOOST_CHECK(index_files.empty());\n\n ms->fsck();\n\n ms->wait_all_asyncs();\n\n \/\/ check first id, because that Id placed in compressed pages.\n auto values = ms->readInterval(QueryInterval({dariadb::Id(0)}, 0, from, to));\n BOOST_CHECK_EQUAL(values.size(), dariadb_test::copies_count);\n\n auto current = ms->currentValue(dariadb::IdArray{}, 0);\n BOOST_CHECK(current.size() != size_t(0));\n\n std::cout << \"erase old files\" << std::endl;\n ms->settings()->max_store_period.setValue(1);\n while (true) {\n index_files = dariadb::utils::fs::ls(settings->raw_path.value(), \".pagei\");\n if (index_files.empty()) {\n break;\n }\n std::cout << \"file left:\" << std::endl;\n for (auto i : index_files) {\n std::cout << i << std::endl;\n }\n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n }\n std::cout << \"end\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_compress_all_test) {\n const std::string storage_path = \"testStorage\";\n const size_t chunk_size = 256;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 50;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_compress_all_test\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->wal_cache_size.setValue(100);\n settings->wal_file_size.setValue(settings->wal_cache_size.value() * 2);\n settings->chunk_size.setValue(chunk_size);\n settings->strategy.setValue(dariadb::STRATEGY::WAL);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb::IdSet all_ids;\n dariadb::Time maxWritedTime;\n dariadb_test::fill_storage_for_test(ms.get(), from, to, step, &all_ids,\n &maxWritedTime, false);\n\n ms->compress_all();\n while (true) {\n auto wals_count = ms->description().wal_count;\n if (wals_count == 0) {\n break;\n }\n dariadb::utils::sleep_mls(500);\n }\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Subscribe) {\n const std::string storage_path = \"testStorage\";\n\n {\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n\n dariadb::IEngine_Ptr ms = std::make_shared(settings);\n\n dariadb_test::subscribe_test(ms.get());\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_MemStorage_common_test) {\n const std::string storage_path = \"testStorage\";\n const size_t chunk_size = 128;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_MemStorage_common_test\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->strategy.setValue(STRATEGY::MEMORY);\n settings->chunk_size.setValue(chunk_size);\n settings->max_chunks_per_page.setValue(5);\n settings->memory_limit.setValue(50 * 1024);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, false, false);\n\n auto pages_count = ms->description().pages_count;\n BOOST_CHECK_GE(pages_count, size_t(2));\n ms->settings()->max_store_period.setValue(1);\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_MemOnlyStorage_common_test) {\n const size_t chunk_size = 128;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_MemOnlyStorage_common_test\\n\";\n\n auto settings = dariadb::storage::Settings::create();\n settings->chunk_size.setValue(chunk_size);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, false, false);\n\n auto pages_count = ms->description().pages_count;\n BOOST_CHECK_EQUAL(pages_count, size_t(0));\n ms->settings()->max_store_period.setValue(1);\n while (true) {\n dariadb::QueryInterval qi({dariadb::Id(0)}, dariadb::Flag(), from, to);\n auto values = ms->readInterval(qi);\n if (values.empty()) {\n break;\n } else {\n std::cout << \"values !empty() \" << values.size() << std::endl;\n dariadb::utils::sleep_mls(500);\n }\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_Cache_common_test) {\n const std::string storage_path = \"testStorage\";\n\n const size_t chunk_size = 128;\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_Cache_common_test\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->strategy.setValue(STRATEGY::CACHE);\n settings->chunk_size.setValue(chunk_size);\n settings->memory_limit.setValue(50 * 1024);\n settings->wal_file_size.setValue(2000);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, true, false);\n\n auto descr = ms->description();\n BOOST_CHECK_GT(descr.pages_count, size_t(0));\n ms->settings()->max_store_period.setValue(1);\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\nengine_test: refact.#define BOOST_TEST_DYN_LINK\n#define BOOST_TEST_MODULE Main\n#include \"test_common.h\"\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\nclass BenchCallback : public dariadb::IReadCallback {\npublic:\n BenchCallback() { count = 0; }\n void call(const dariadb::Meas &) { count++; }\n size_t count;\n};\n\nBOOST_AUTO_TEST_CASE(Engine_common_test) {\n const std::string storage_path = \"testStorage\";\n const size_t chunk_size = 256;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n using namespace dariadb;\n using namespace dariadb::storage;\n {\n std::cout << \"Engine_common_test.\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->wal_cache_size.setValue(100);\n settings->wal_file_size.setValue(settings->wal_cache_size.value() * 5);\n settings->chunk_size.setValue(chunk_size);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, true, false);\n\n auto pages_count = ms->description().pages_count;\n BOOST_CHECK_GE(pages_count, size_t(2));\n BOOST_CHECK(ms->settings() != nullptr);\n BOOST_CHECK(ms->settings()->storage_path.value() == storage_path);\n }\n {\n std::cout << \"reopen closed storage\\n\";\n\t{\/\/ bad idea remove files from working storage.\n\t\tauto ms = dariadb::open_storage(storage_path);\n\t\tauto settings = ms->settings();\n\n\t\tauto path_to_raw = settings->raw_path.value();\n\t\tsettings = nullptr;\n\t\tms->stop();\n\n\t\tms = nullptr;\n\t\tauto index_files = dariadb::utils::fs::ls(path_to_raw, \".pagei\");\n\t\tBOOST_CHECK(!index_files.empty());\n\t\tfor (auto &f : index_files) {\n\t\t\tdariadb::utils::fs::rm(f);\n\t\t}\n\t\tindex_files = dariadb::utils::fs::ls(path_to_raw, \".pagei\");\n\t\tBOOST_CHECK(index_files.empty());\n\t}\n\t\n\tauto ms = dariadb::open_storage(storage_path);\n\tauto settings = ms->settings();\n\n ms->fsck();\n\n ms->wait_all_asyncs();\n\n \/\/ check first id, because that Id placed in compressed pages.\n auto values = ms->readInterval(QueryInterval({dariadb::Id(0)}, 0, from, to));\n BOOST_CHECK_EQUAL(values.size(), dariadb_test::copies_count);\n\n auto current = ms->currentValue(dariadb::IdArray{}, 0);\n BOOST_CHECK(current.size() != size_t(0));\n\n std::cout << \"erase old files\" << std::endl;\n ms->settings()->max_store_period.setValue(1);\n while (true) {\n auto index_files = dariadb::utils::fs::ls(settings->raw_path.value(), \".pagei\");\n if (index_files.empty()) {\n break;\n }\n std::cout << \"file left:\" << std::endl;\n for (auto i : index_files) {\n std::cout << i << std::endl;\n }\n std::this_thread::sleep_for(std::chrono::seconds(1));\n }\n }\n std::cout << \"end\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_compress_all_test) {\n const std::string storage_path = \"testStorage\";\n const size_t chunk_size = 256;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 50;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_compress_all_test\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->wal_cache_size.setValue(100);\n settings->wal_file_size.setValue(settings->wal_cache_size.value() * 2);\n settings->chunk_size.setValue(chunk_size);\n settings->strategy.setValue(dariadb::STRATEGY::WAL);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb::IdSet all_ids;\n dariadb::Time maxWritedTime;\n dariadb_test::fill_storage_for_test(ms.get(), from, to, step, &all_ids,\n &maxWritedTime, false);\n\n ms->compress_all();\n while (true) {\n auto wals_count = ms->description().wal_count;\n if (wals_count == 0) {\n break;\n }\n dariadb::utils::sleep_mls(500);\n }\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Subscribe) {\n const std::string storage_path = \"testStorage\";\n\n {\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n\n dariadb::IEngine_Ptr ms = std::make_shared(settings);\n\n dariadb_test::subscribe_test(ms.get());\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_MemStorage_common_test) {\n const std::string storage_path = \"testStorage\";\n const size_t chunk_size = 128;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_MemStorage_common_test\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->strategy.setValue(STRATEGY::MEMORY);\n settings->chunk_size.setValue(chunk_size);\n settings->max_chunks_per_page.setValue(5);\n settings->memory_limit.setValue(50 * 1024);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, false, false);\n\n auto pages_count = ms->description().pages_count;\n BOOST_CHECK_GE(pages_count, size_t(2));\n ms->settings()->max_store_period.setValue(1);\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_MemOnlyStorage_common_test) {\n const size_t chunk_size = 128;\n\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_MemOnlyStorage_common_test\\n\";\n\n auto settings = dariadb::storage::Settings::create();\n settings->chunk_size.setValue(chunk_size);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, false, false);\n\n auto pages_count = ms->description().pages_count;\n BOOST_CHECK_EQUAL(pages_count, size_t(0));\n ms->settings()->max_store_period.setValue(1);\n while (true) {\n dariadb::QueryInterval qi({dariadb::Id(0)}, dariadb::Flag(), from, to);\n auto values = ms->readInterval(qi);\n if (values.empty()) {\n break;\n } else {\n std::cout << \"values !empty() \" << values.size() << std::endl;\n dariadb::utils::sleep_mls(500);\n }\n }\n }\n}\n\nBOOST_AUTO_TEST_CASE(Engine_Cache_common_test) {\n const std::string storage_path = \"testStorage\";\n\n const size_t chunk_size = 128;\n const dariadb::Time from = 0;\n const dariadb::Time to = from + 1000;\n const dariadb::Time step = 10;\n\n using namespace dariadb;\n using namespace dariadb::storage;\n\n {\n std::cout << \"Engine_Cache_common_test\\n\";\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n\n auto settings = dariadb::storage::Settings::create(storage_path);\n settings->strategy.setValue(STRATEGY::CACHE);\n settings->chunk_size.setValue(chunk_size);\n settings->memory_limit.setValue(50 * 1024);\n settings->wal_file_size.setValue(2000);\n std::unique_ptr ms{new Engine(settings)};\n\n dariadb_test::storage_test_check(ms.get(), from, to, step, true, true, false);\n\n auto descr = ms->description();\n BOOST_CHECK_GT(descr.pages_count, size_t(0));\n ms->settings()->max_store_period.setValue(1);\n }\n if (dariadb::utils::fs::path_exists(storage_path)) {\n dariadb::utils::fs::rm(storage_path);\n }\n}\n<|endoftext|>"} {"text":"\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ I grabbed these CRC routines from the following source:\n\/\/ http:\/\/www.landfield.com\/faqs\/compression-faq\/part1\/section-25.html\n\/\/\n\/\/ These routines are very useful, so I'm including them in bochs.\n\/\/ They are not covered by the license, as they are not my doing.\n\/\/ My gratitude to the author for offering them on the 'net.\n\/\/\n\/\/ I only changed the u_long to Bit32u, and u_char to Bit8u, and gave\n\/\/ the functions prototypes.\n\/\/\n\/\/ -Kevin\n\/\/\n\/\/ **************************************************************************\n\/\/ The following C code (by Rob Warnock ) does CRC-32 in\n\/\/ BigEndian\/BigEndian byte\/bit order. That is, the data is sent most\n\/\/ significant byte first, and each of the bits within a byte is sent most\n\/\/ significant bit first, as in FDDI. You will need to twiddle with it to do\n\/\/ Ethernet CRC, i.e., BigEndian\/LittleEndian byte\/bit order. [Left as an\n\/\/ exercise for the reader.]\n\/\/\n\/\/ The CRCs this code generates agree with the vendor-supplied Verilog models\n\/\/ of several of the popular FDDI \"MAC\" chips.\n\/\/ **************************************************************************\n\n#include \"config.h\"\n\n\/* Initialized first time \"crc32()\" is called. If you prefer, you can\n * statically initialize it at compile time. [Another exercise.]\n *\/\nstatic Bit32u crc32_table[256];\n\n\/*\n * Build auxiliary table for parallel byte-at-a-time CRC-32.\n *\/\n#define CRC32_POLY 0x04c11db7 \/* AUTODIN II, Ethernet, & FDDI *\/\n\nstatic void init_crc32(void)\n{\n int i, j;\n Bit32u c;\n\n for (i = 0; i < 256; ++i) {\n for (c = i << 24, j = 8; j > 0; --j)\n c = c & 0x80000000 ? (c << 1) ^ CRC32_POLY : (c << 1);\n crc32_table[i] = c;\n }\n}\n\nBit32u crc32(const Bit8u *buf, int len)\n{\n const Bit8u *p;\n Bit32u crc;\n\n if (!crc32_table[1]) \/* if not already done, *\/\n init_crc32(); \/* build table *\/\n\n crc = 0xffffffff; \/* preload shift register, per CRC-32 spec *\/\n for (p = buf; len > 0; ++p, --len)\n crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *p];\n return ~crc; \/* transmit complement, per CRC-32 spec *\/\n}\nIndent changes\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ $Id$\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/\n\/\/ I grabbed these CRC routines from the following source:\n\/\/ http:\/\/www.landfield.com\/faqs\/compression-faq\/part1\/section-25.html\n\/\/\n\/\/ These routines are very useful, so I'm including them in bochs.\n\/\/ They are not covered by the license, as they are not my doing.\n\/\/ My gratitude to the author for offering them on the 'net.\n\/\/\n\/\/ I only changed the u_long to Bit32u, and u_char to Bit8u, and gave\n\/\/ the functions prototypes.\n\/\/\n\/\/ -Kevin\n\/\/\n\/\/ **************************************************************************\n\/\/ The following C code (by Rob Warnock ) does CRC-32 in\n\/\/ BigEndian\/BigEndian byte\/bit order. That is, the data is sent most\n\/\/ significant byte first, and each of the bits within a byte is sent most\n\/\/ significant bit first, as in FDDI. You will need to twiddle with it to do\n\/\/ Ethernet CRC, i.e., BigEndian\/LittleEndian byte\/bit order. [Left as an\n\/\/ exercise for the reader.]\n\/\/\n\/\/ The CRCs this code generates agree with the vendor-supplied Verilog models\n\/\/ of several of the popular FDDI \"MAC\" chips.\n\/\/ **************************************************************************\n\n#include \"config.h\"\n\n\/* Initialized first time \"crc32()\" is called. If you prefer, you can\n * statically initialize it at compile time. [Another exercise.]\n *\/\nstatic Bit32u crc32_table[256];\n\n\/*\n * Build auxiliary table for parallel byte-at-a-time CRC-32.\n *\/\n#define CRC32_POLY 0x04c11db7 \/* AUTODIN II, Ethernet, & FDDI *\/\n\nstatic void init_crc32(void)\n{\n int i, j;\n Bit32u c;\n\n for (i = 0; i < 256; ++i) {\n for (c = i << 24, j = 8; j > 0; --j)\n c = c & 0x80000000 ? (c << 1) ^ CRC32_POLY : (c << 1);\n crc32_table[i] = c;\n }\n}\n\nBit32u crc32(const Bit8u *buf, int len)\n{\n const Bit8u *p;\n Bit32u crc;\n\n if (!crc32_table[1]) \/* if not already done, *\/\n init_crc32(); \/* build table *\/\n\n crc = 0xffffffff; \/* preload shift register, per CRC-32 spec *\/\n for (p = buf; len > 0; ++p, --len)\n crc = (crc << 8) ^ crc32_table[(crc >> 24) ^ *p];\n return ~crc; \/* transmit complement, per CRC-32 spec *\/\n}\n<|endoftext|>"} {"text":"#include \"ItemUtils.h\"\n#include \n#include \n#include \n#include \n\nnamespace DEM::RPG\n{\n\nGame::HEntity AddItemsIntoContainer(Game::CGameWorld& World, Game::HEntity Container, Game::HEntity ItemStackEntity, bool Merge)\n{\n\tauto pItemStack = World.FindComponent(ItemStackEntity);\n\tif (!pItemStack) return {};\n\n\tauto pItem = FindItemComponent(World, ItemStackEntity, *pItemStack);\n\tif (!pItem) return {};\n\n\tauto pContainer = World.FindComponent(Container);\n\tif (!pContainer) return {};\n\n\t\/\/ Fail if this item can't be placed into the container\n\t\/\/ TODO: split stack, fill available container space!\n\t\/\/ bool flag in args to enable this? return actually added count \/ remaining stack ID?\n\tCContainerStats Stats;\n\tCalcContainerStats(World, *pContainer, Stats);\n\tif (Stats.FreeWeight < pItemStack->Count * pItem->Weight) return {};\n\tif (Stats.FreeVolume < pItemStack->Count * pItem->Volume) return {};\n\n\t\/\/ Try to merge new items into existing stack\n\tif (Merge && !pItemStack->Modified)\n\t{\n\t\tfor (auto MergeAcceptorID : pContainer->Items)\n\t\t{\n\t\t\tauto pMergeTo = World.FindComponent(MergeAcceptorID);\n\t\t\tif (pMergeTo && pMergeTo->Prototype == pItemStack->Prototype && !pMergeTo->Modified)\n\t\t\t{\n\t\t\t\tpMergeTo->Count += pItemStack->Count;\n\t\t\t\tWorld.DeleteEntity(ItemStackEntity);\n\t\t\t\treturn MergeAcceptorID;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If not merged, transfer a stack into the container\n\n\tWorld.RemoveComponent(ItemStackEntity);\n\tWorld.RemoveComponent(ItemStackEntity);\n\n\t\/\/ TODO: allow inserting into specified index!\n\tpContainer->Items.push_back(ItemStackEntity);\n\n\treturn ItemStackEntity;\n}\n\/\/---------------------------------------------------------------------\n\n\/\/!!!check dropping near another item stack or pile (temporary container)! bool flag 'allow merging'?\nbool DropItemsToLocation(Game::CGameWorld& World, Game::HEntity ItemStackEntity, const Math::CTransformSRT& Tfm)\n{\n\tauto pItemStack = World.FindComponent(ItemStackEntity);\n\tif (!pItemStack) return false;\n\n\tconst CItemComponent* pItem = FindItemComponent(World, ItemStackEntity, *pItemStack);\n\tif (!pItem) return false;\n\n\t\/\/ TODO:\n\t\/\/ If merging enabled, query item stacks and tmp item containers in accessible range, not owned by someone else\n\t\/\/ If tmp item containers are found, add the stack to the closest one (take lookat dir into account?)\n\t\/\/ Else if stacks are found, try to merge into the closest one (take lookat dir into account?)\n\t\/\/ If not merged, create tmp item container and add found stack and our stack to it\n\t\/\/ If nothing found, drop a new item object into location (create scene and RB)\n\n\tif (pItem->WorldModelID)\n\t{\n\t\tauto pSceneComponent = World.AddComponent(ItemStackEntity);\n\t\tpSceneComponent->RootNode->RemoveFromParent();\n\t\tpSceneComponent->AssetID = pItem->WorldModelID;\n\t\tpSceneComponent->SetLocalTransform(Tfm);\n\t}\n\n\tif (pItem->WorldPhysicsID)\n\t{\n\t\tauto pPhysicsComponent = World.AddComponent(ItemStackEntity);\n\t\tpPhysicsComponent->ShapeAssetID = pItem->WorldPhysicsID;\n\t\tpPhysicsComponent->Mass = pItemStack->Count * pItem->Weight;\n\t\tpPhysicsComponent->CollisionGroupID = CStrID(\"PhysicalDynamic|Interactable\");\n\t\t\/\/ TODO: physics material?\n\t}\n\n\treturn true;\n}\n\/\/---------------------------------------------------------------------\n\n\/\/ TODO: use container as an std::optional hint? or handle this in user API and call RemoveItemsFromContainer only when needed?\nvoid RemoveItemsFromContainer(Game::CGameWorld& World, Game::HEntity ItemStackEntity, Game::HEntity Container)\n{\n\tauto pContainer = World.FindComponent(Container);\n\tif (!pContainer) return;\n\n\tpContainer->Items.erase(std::remove(pContainer->Items.begin(), pContainer->Items.end(), ItemStackEntity));\n}\n\/\/---------------------------------------------------------------------\n\nvoid CalcContainerStats(Game::CGameWorld& World, const CItemContainerComponent& Container, CContainerStats& OutStats)\n{\n\tOutStats.UsedWeight = 0.f;\n\tOutStats.UsedVolume = 0.f;\n\tOutStats.Price = 0;\n\tfor (auto ItemEntityID : Container.Items)\n\t{\n\t\tauto pStack = World.FindComponent(ItemEntityID);\n\t\tif (!pStack) continue;\n\n\t\tif (auto pItem = FindItemComponent(World, ItemEntityID, *pStack))\n\t\t{\n\t\t\tOutStats.UsedWeight += pStack->Count * pItem->Weight;\n\t\t\tOutStats.UsedVolume += pStack->Count * pItem->Volume;\n\t\t\tOutStats.Price += pStack->Count * pItem->Price; \/\/???what to count? only valuable or money-like items?\n\t\t}\n\t}\n\n\tOutStats.FreeWeight = (Container.MaxWeight <= 0.f) ? FLT_MAX : (Container.MaxWeight - OutStats.UsedWeight);\n\tOutStats.FreeVolume = (Container.MaxVolume <= 0.f) ? FLT_MAX : (Container.MaxVolume - OutStats.UsedVolume);\n}\n\/\/---------------------------------------------------------------------\n\n}\nProtect from re-adding the same item stack to the container#include \"ItemUtils.h\"\n#include \n#include \n#include \n#include \n\nnamespace DEM::RPG\n{\n\nGame::HEntity AddItemsIntoContainer(Game::CGameWorld& World, Game::HEntity Container, Game::HEntity StackID, bool Merge)\n{\n\tauto pItemStack = World.FindComponent(StackID);\n\tif (!pItemStack) return {};\n\n\tauto pItem = FindItemComponent(World, StackID, *pItemStack);\n\tif (!pItem) return {};\n\n\tauto pContainer = World.FindComponent(Container);\n\tif (!pContainer) return {};\n\n\t\/\/ Check that we don't insert already contained stack, and find a merge stack if posible\n\tif (std::find(pContainer->Items.cbegin(), pContainer->Items.cend(), StackID) != pContainer->Items.cend())\n\t\treturn {};\n\n\t\/\/ Fail if this item can't be placed into the container\n\t\/\/ TODO: split stack, fill available container space!\n\t\/\/ bool flag in args to enable this? return actually added count \/ remaining stack ID?\n\tCContainerStats Stats;\n\tCalcContainerStats(World, *pContainer, Stats);\n\tif (Stats.FreeWeight < pItemStack->Count * pItem->Weight) return {};\n\tif (Stats.FreeVolume < pItemStack->Count * pItem->Volume) return {};\n\n\t\/\/ Try to merge new items into existing stack\n\tif (Merge && !pItemStack->Modified)\n\t{\n\t\tfor (auto MergeAcceptorID : pContainer->Items)\n\t\t{\n\t\t\tauto pMergeTo = World.FindComponent(MergeAcceptorID);\n\t\t\tif (pMergeTo && pMergeTo->Prototype == pItemStack->Prototype && !pMergeTo->Modified)\n\t\t\t{\n\t\t\t\tpMergeTo->Count += pItemStack->Count;\n\t\t\t\tWorld.DeleteEntity(StackID);\n\t\t\t\treturn MergeAcceptorID;\n\t\t\t}\n\t\t}\n\t}\n\n\t\/\/ If not merged, transfer a stack into the container\n\n\tWorld.RemoveComponent(StackID);\n\tWorld.RemoveComponent(StackID);\n\n\t\/\/ TODO: allow inserting into specified index!\n\tpContainer->Items.push_back(StackID);\n\n\treturn StackID;\n}\n\/\/---------------------------------------------------------------------\n\n\/\/!!!check dropping near another item stack or pile (temporary container)! bool flag 'allow merging'?\nbool DropItemsToLocation(Game::CGameWorld& World, Game::HEntity ItemStackEntity, const Math::CTransformSRT& Tfm)\n{\n\tauto pItemStack = World.FindComponent(ItemStackEntity);\n\tif (!pItemStack) return false;\n\n\tconst CItemComponent* pItem = FindItemComponent(World, ItemStackEntity, *pItemStack);\n\tif (!pItem) return false;\n\n\t\/\/ TODO:\n\t\/\/ If merging enabled, query item stacks and tmp item containers in accessible range, not owned by someone else\n\t\/\/ If tmp item containers are found, add the stack to the closest one (take lookat dir into account?)\n\t\/\/ Else if stacks are found, try to merge into the closest one (take lookat dir into account?)\n\t\/\/ If not merged, create tmp item container and add found stack and our stack to it\n\t\/\/ If nothing found, drop a new item object into location (create scene and RB)\n\n\tif (pItem->WorldModelID)\n\t{\n\t\tauto pSceneComponent = World.AddComponent(ItemStackEntity);\n\t\tpSceneComponent->RootNode->RemoveFromParent();\n\t\tpSceneComponent->AssetID = pItem->WorldModelID;\n\t\tpSceneComponent->SetLocalTransform(Tfm);\n\t}\n\n\tif (pItem->WorldPhysicsID)\n\t{\n\t\tauto pPhysicsComponent = World.AddComponent(ItemStackEntity);\n\t\tpPhysicsComponent->ShapeAssetID = pItem->WorldPhysicsID;\n\t\tpPhysicsComponent->Mass = pItemStack->Count * pItem->Weight;\n\t\tpPhysicsComponent->CollisionGroupID = CStrID(\"PhysicalDynamic|Interactable\");\n\t\t\/\/ TODO: physics material?\n\t}\n\n\treturn true;\n}\n\/\/---------------------------------------------------------------------\n\n\/\/ TODO: use container as an std::optional hint? or handle this in user API and call RemoveItemsFromContainer only when needed?\nvoid RemoveItemsFromContainer(Game::CGameWorld& World, Game::HEntity ItemStackEntity, Game::HEntity Container)\n{\n\tauto pContainer = World.FindComponent(Container);\n\tif (!pContainer) return;\n\n\tpContainer->Items.erase(std::remove(pContainer->Items.begin(), pContainer->Items.end(), ItemStackEntity));\n}\n\/\/---------------------------------------------------------------------\n\nvoid CalcContainerStats(Game::CGameWorld& World, const CItemContainerComponent& Container, CContainerStats& OutStats)\n{\n\tOutStats.UsedWeight = 0.f;\n\tOutStats.UsedVolume = 0.f;\n\tOutStats.Price = 0;\n\tfor (auto ItemEntityID : Container.Items)\n\t{\n\t\tauto pStack = World.FindComponent(ItemEntityID);\n\t\tif (!pStack) continue;\n\n\t\tif (auto pItem = FindItemComponent(World, ItemEntityID, *pStack))\n\t\t{\n\t\t\tOutStats.UsedWeight += pStack->Count * pItem->Weight;\n\t\t\tOutStats.UsedVolume += pStack->Count * pItem->Volume;\n\t\t\tOutStats.Price += pStack->Count * pItem->Price; \/\/???what to count? only valuable or money-like items?\n\t\t}\n\t}\n\n\tOutStats.FreeWeight = (Container.MaxWeight <= 0.f) ? FLT_MAX : (Container.MaxWeight - OutStats.UsedWeight);\n\tOutStats.FreeVolume = (Container.MaxVolume <= 0.f) ? FLT_MAX : (Container.MaxVolume - OutStats.UsedVolume);\n}\n\/\/---------------------------------------------------------------------\n\n}\n<|endoftext|>"} {"text":"Libport.Hash: fixes.<|endoftext|>"} {"text":"#include \"views\/SystemView.h\"\n#include \"SystemData.h\"\n#include \"Renderer.h\"\n#include \"Log.h\"\n#include \"Window.h\"\n#include \"views\/ViewController.h\"\n#include \"animations\/LambdaAnimation.h\"\n#include \"SystemData.h\"\n#include \"Settings.h\"\n#include \"Util.h\"\n\n#define SELECTED_SCALE 1.5f\n#define LOGO_PADDING ((logoSize().x() * (SELECTED_SCALE - 1)\/2) + (mSize.x() * 0.06f))\n#define BAND_HEIGHT (logoSize().y() * SELECTED_SCALE)\n\nSystemView::SystemView(Window* window) : IList(window, LIST_SCROLL_STYLE_SLOW, LIST_ALWAYS_LOOP),\n\tmSystemInfo(window, \"SYSTEM INFO\", Font::get(FONT_SIZE_SMALL), 0x33333300, ALIGN_CENTER)\n{\n\tmCamOffset = 0;\n\tmExtrasCamOffset = 0;\n\tmExtrasFadeOpacity = 0.0f;\n\n\tsetSize((float)Renderer::getScreenWidth(), (float)Renderer::getScreenHeight());\n\n\tmSystemInfo.setSize(mSize.x(), mSystemInfo.getSize().y() * 1.333f);\n\tmSystemInfo.setPosition(0, (mSize.y() + BAND_HEIGHT) \/ 2);\n\n\tpopulate();\n}\n\nvoid SystemView::populate()\n{\n\tmEntries.clear();\n\n\tfor(auto it = SystemData::sSystemVector.begin(); it != SystemData::sSystemVector.end(); it++)\n\t{\n\t\tconst std::shared_ptr& theme = (*it)->getTheme();\n\n\t\tEntry e;\n\t\te.name = (*it)->getName();\n\t\te.object = *it;\n\n\t\t\/\/ make logo\n\t\tif(theme->getElement(\"system\", \"logo\", \"image\"))\n\t\t{\n\t\t\tImageComponent* logo = new ImageComponent(mWindow);\n\t\t\tlogo->setMaxSize(Eigen::Vector2f(logoSize().x(), logoSize().y()));\n\t\t\tlogo->applyTheme((*it)->getTheme(), \"system\", \"logo\", ThemeFlags::PATH);\n\t\t\tlogo->setPosition((logoSize().x() - logo->getSize().x()) \/ 2, (logoSize().y() - logo->getSize().y()) \/ 2); \/\/ center\n\t\t\te.data.logo = std::shared_ptr(logo);\n\n\t\t\tImageComponent* logoSelected = new ImageComponent(mWindow);\n\t\t\tlogoSelected->setMaxSize(Eigen::Vector2f(logoSize().x() * SELECTED_SCALE, logoSize().y() * SELECTED_SCALE * 0.70f));\n\t\t\tlogoSelected->applyTheme((*it)->getTheme(), \"system\", \"logo\", ThemeFlags::PATH);\n\t\t\tlogoSelected->setPosition((logoSize().x() - logoSelected->getSize().x()) \/ 2, \n\t\t\t\t(logoSize().y() - logoSelected->getSize().y()) \/ 2); \/\/ center\n\t\t\te.data.logoSelected = std::shared_ptr(logoSelected);\n\t\t}else{\n\t\t\t\/\/ no logo in theme; use text\n\t\t\tTextComponent* text = new TextComponent(mWindow, \n\t\t\t\t(*it)->getName(), \n\t\t\t\tFont::get(FONT_SIZE_LARGE), \n\t\t\t\t0x000000FF, \n\t\t\t\tALIGN_CENTER);\n\t\t\ttext->setSize(logoSize());\n\t\t\te.data.logo = std::shared_ptr(text);\n\n\t\t\tTextComponent* textSelected = new TextComponent(mWindow, \n\t\t\t\t(*it)->getName(), \n\t\t\t\tFont::get((int)(FONT_SIZE_LARGE * SELECTED_SCALE)), \n\t\t\t\t0x000000FF, \n\t\t\t\tALIGN_CENTER);\n\t\t\ttextSelected->setSize(logoSize());\n\t\t\te.data.logoSelected = std::shared_ptr(textSelected);\n\t\t}\n\n\t\t\/\/ make background extras\n\t\te.data.backgroundExtras = std::shared_ptr(new ThemeExtras(mWindow));\n\t\te.data.backgroundExtras->setExtras(ThemeData::makeExtras((*it)->getTheme(), \"system\", mWindow));\n\n\t\tthis->add(e);\n\t}\n}\n\nvoid SystemView::goToSystem(SystemData* system, bool animate)\n{\n\tsetCursor(system);\n\n\tif(!animate)\n\t\tfinishAnimation(0);\n}\n\nbool SystemView::input(InputConfig* config, Input input)\n{\n\tif(input.value != 0)\n\t{\n\t\tif(config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_r && SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool(\"Debug\"))\n\t\t{\n\t\t\tLOG(LogInfo) << \" Reloading SystemList view\";\n\n\t\t\t\/\/ reload themes\n\t\t\tfor(auto it = mEntries.begin(); it != mEntries.end(); it++)\n\t\t\t\tit->object->loadTheme();\n\n\t\t\tpopulate();\n\t\t\tupdateHelpPrompts();\n\t\t\treturn true;\n\t\t}\n\t\tif(config->isMappedTo(\"left\", input))\n\t\t{\n\t\t\tlistInput(-1);\n\t\t\treturn true;\n\t\t}\n\t\tif(config->isMappedTo(\"right\", input))\n\t\t{\n\t\t\tlistInput(1);\n\t\t\treturn true;\n\t\t}\n\t\tif(config->isMappedTo(\"a\", input))\n\t\t{\n\t\t\tstopScrolling();\n\t\t\tViewController::get()->goToGameList(getSelected());\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\tif(config->isMappedTo(\"left\", input) || config->isMappedTo(\"right\", input))\n\t\t\tlistInput(0);\n\t}\n\n\treturn GuiComponent::input(config, input);\n}\n\nvoid SystemView::update(int deltaTime)\n{\n\tlistUpdate(deltaTime);\n\tGuiComponent::update(deltaTime);\n}\n\nvoid SystemView::onCursorChanged(const CursorState& state)\n{\n\t\/\/ update help style\n\tupdateHelpPrompts();\n\n\tfloat startPos = mCamOffset;\n\n\tfloat posMax = (float)mEntries.size();\n\tfloat target = (float)mCursor;\n\n\t\/\/ what's the shortest way to get to our target?\n\t\/\/ it's one of these...\n\n\tfloat endPos = target; \/\/ directly\n\tfloat dist = abs(endPos - startPos);\n\t\n\tif(abs(target + posMax - startPos) < dist)\n\t\tendPos = target + posMax; \/\/ loop around the end (0 -> max)\n\tif(abs(target - posMax - startPos) < dist)\n\t\tendPos = target - posMax; \/\/ loop around the start (max - 1 -> -1)\n\n\t\n\t\/\/ animate mSystemInfo's opacity (fade out, wait, fade back in)\n\n\tcancelAnimation(1);\n\tcancelAnimation(2);\n\n\tconst float infoStartOpacity = mSystemInfo.getOpacity() \/ 255.f;\n\n\tAnimation* infoFadeOut = new LambdaAnimation(\n\t\t[infoStartOpacity, this] (float t)\n\t{\n\t\tmSystemInfo.setOpacity((unsigned char)(lerp(infoStartOpacity, 0.f, t) * 255));\n\t}, (int)(infoStartOpacity * 150));\n\n\tunsigned int gameCount = getSelected()->getGameCount();\n\n\t\/\/ also change the text after we've fully faded out\n\tsetAnimation(infoFadeOut, 0, [this, gameCount] {\n\t\tstd::stringstream ss;\n\t\t\n\t\t\/\/ only display a game count if there are at least 2 games\n\t\tif(gameCount > 1)\n\t\t\tss << gameCount << \" GAMES AVAILABLE\";\n\n\t\tmSystemInfo.setText(ss.str()); \n\t}, false, 1);\n\n\t\/\/ only display a game count if there are at least 2 games\n\tif(gameCount > 1)\n\t{\n\t\tAnimation* infoFadeIn = new LambdaAnimation(\n\t\t\t[this](float t)\n\t\t{\n\t\t\tmSystemInfo.setOpacity((unsigned char)(lerp(0.f, 1.f, t) * 255));\n\t\t}, 300);\n\n\t\t\/\/ wait 600ms to fade in\n\t\tsetAnimation(infoFadeIn, 2000, nullptr, false, 2);\n\t}\n\n\t\/\/ no need to animate transition, we're not going anywhere (probably mEntries.size() == 1)\n\tif(endPos == mCamOffset && endPos == mExtrasCamOffset)\n\t\treturn;\n\n\tAnimation* anim;\n\tif(Settings::getInstance()->getString(\"TransitionStyle\") == \"fade\")\n\t{\n\t\tfloat startExtrasFade = mExtrasFadeOpacity;\n\t\tanim = new LambdaAnimation(\n\t\t\t[startExtrasFade, startPos, endPos, posMax, this](float t)\n\t\t{\n\t\t\tt -= 1;\n\t\t\tfloat f = lerp(startPos, endPos, t*t*t + 1);\n\t\t\tif(f < 0)\n\t\t\t\tf += posMax;\n\t\t\tif(f >= posMax)\n\t\t\t\tf -= posMax;\n\n\t\t\tthis->mCamOffset = f;\n\n\t\t\tt += 1;\n\t\t\tif(t < 0.3f)\n\t\t\t\tthis->mExtrasFadeOpacity = lerp(0.0f, 1.0f, t \/ 0.3f + startExtrasFade);\n\t\t\telse if(t < 0.7f)\n\t\t\t\tthis->mExtrasFadeOpacity = 1.0f;\n\t\t\telse\n\t\t\t\tthis->mExtrasFadeOpacity = lerp(1.0f, 0.0f, (t - 0.7f) \/ 0.3f);\n\n\t\t\tif(t > 0.5f)\n\t\t\t\tthis->mExtrasCamOffset = endPos;\n\n\t\t}, 500);\n\t}\n\telse{ \/\/ slide\n\t\tanim = new LambdaAnimation(\n\t\t\t[startPos, endPos, posMax, this](float t)\n\t\t{\n\t\t\tt -= 1;\n\t\t\tfloat f = lerp(startPos, endPos, t*t*t + 1);\n\t\t\tif(f < 0)\n\t\t\t\tf += posMax;\n\t\t\tif(f >= posMax)\n\t\t\t\tf -= posMax;\n\n\t\t\tthis->mCamOffset = f;\n\t\t\tthis->mExtrasCamOffset = f;\n\t\t}, 500);\n\t}\n\n\tsetAnimation(anim, 0, nullptr, false, 0);\n}\n\nvoid SystemView::render(const Eigen::Affine3f& parentTrans)\n{\n\tif(size() == 0)\n\t\treturn;\n\n\tEigen::Affine3f trans = getTransform() * parentTrans;\n\t\n\t\/\/ draw the list elements (titles, backgrounds, logos)\n\tconst float logoSizeX = logoSize().x() + LOGO_PADDING;\n\n\tint logoCount = (int)(mSize.x() \/ logoSizeX) + 2; \/\/ how many logos we need to draw\n\tint center = (int)(mCamOffset);\n\n\tif(mEntries.size() == 1)\n\t\tlogoCount = 1;\n\n\t\/\/ draw background extras\n\tEigen::Affine3f extrasTrans = trans;\n\tint extrasCenter = (int)mExtrasCamOffset;\n\tfor(int i = extrasCenter - 1; i < extrasCenter + 2; i++)\n\t{\n\t\tint index = i;\n\t\twhile(index < 0)\n\t\t\tindex += mEntries.size();\n\t\twhile(index >= (int)mEntries.size())\n\t\t\tindex -= mEntries.size();\n\n\t\textrasTrans.translation() = trans.translation() + Eigen::Vector3f((i - mExtrasCamOffset) * mSize.x(), 0, 0);\n\n\t\tEigen::Vector2i clipRect = Eigen::Vector2i((int)((i - mExtrasCamOffset) * mSize.x()), 0);\n\t\tRenderer::pushClipRect(clipRect, mSize.cast());\n\t\tmEntries.at(index).data.backgroundExtras->render(extrasTrans);\n\t\tRenderer::popClipRect();\n\t}\n\n\t\/\/ fade extras if necessary\n\tif(mExtrasFadeOpacity)\n\t{\n\t\tRenderer::setMatrix(trans);\n\t\tRenderer::drawRect(0.0f, 0.0f, mSize.x(), mSize.y(), 0x00000000 | (unsigned char)(mExtrasFadeOpacity * 255));\n\t}\n\n\t\/\/ draw logos\n\tfloat xOff = (mSize.x() - logoSize().x())\/2 - (mCamOffset * logoSizeX);\n\tfloat yOff = (mSize.y() - logoSize().y())\/2;\n\n\t\/\/ background behind the logos\n\tRenderer::setMatrix(trans);\n\tRenderer::drawRect(0.f, (mSize.y() - BAND_HEIGHT) \/ 2, mSize.x(), BAND_HEIGHT, 0xFFFFFFD8);\n\n\tEigen::Affine3f logoTrans = trans;\n\tfor(int i = center - logoCount\/2; i < center + logoCount\/2 + 1; i++)\n\t{\n\t\tint index = i;\n\t\twhile(index < 0)\n\t\t\tindex += mEntries.size();\n\t\twhile(index >= (int)mEntries.size())\n\t\t\tindex -= mEntries.size();\n\n\t\tlogoTrans.translation() = trans.translation() + Eigen::Vector3f(i * logoSizeX + xOff, yOff, 0);\n\n\t\tif(index == mCursor) \/\/scale our selection up\n\t\t{\n\t\t\t\/\/ selected\n\t\t\tconst std::shared_ptr& comp = mEntries.at(index).data.logoSelected;\n\t\t\tcomp->setOpacity(0xFF);\n\t\t\tcomp->render(logoTrans);\n\t\t}else{\n\t\t\t\/\/ not selected\n\t\t\tconst std::shared_ptr& comp = mEntries.at(index).data.logo;\n\t\t\tcomp->setOpacity(0x80);\n\t\t\tcomp->render(logoTrans);\n\t\t}\n\t}\n\n\tRenderer::setMatrix(trans);\n\tRenderer::drawRect(mSystemInfo.getPosition().x(), mSystemInfo.getPosition().y() - 1, mSize.x(), mSystemInfo.getSize().y(), 0xDDDDDD00 | (unsigned char)(mSystemInfo.getOpacity() \/ 255.f * 0xD8));\n\tmSystemInfo.render(trans);\n}\n\nstd::vector SystemView::getHelpPrompts()\n{\n\tstd::vector prompts;\n\tprompts.push_back(HelpPrompt(\"left\/right\", \"choose\"));\n\tprompts.push_back(HelpPrompt(\"a\", \"select\"));\n\treturn prompts;\n}\n\nHelpStyle SystemView::getHelpStyle()\n{\n\tHelpStyle style;\n\tstyle.applyTheme(mEntries.at(mCursor).object->getTheme(), \"system\");\n\treturn style;\n}\nUpdate SystemView.cpp#include \"views\/SystemView.h\"\n#include \"SystemData.h\"\n#include \"Renderer.h\"\n#include \"Log.h\"\n#include \"Window.h\"\n#include \"views\/ViewController.h\"\n#include \"animations\/LambdaAnimation.h\"\n#include \"SystemData.h\"\n#include \"Settings.h\"\n#include \"Util.h\"\n#include \"ThemeData.h\"\n#include \"Music.h\"\n\n#define SELECTED_SCALE 1.5f\n#define LOGO_PADDING ((logoSize().x() * (SELECTED_SCALE - 1)\/2) + (mSize.x() * 0.06f))\n#define BAND_HEIGHT (logoSize().y() * SELECTED_SCALE)\n\nSystemView::SystemView(Window* window) : IList(window, LIST_SCROLL_STYLE_SLOW, LIST_ALWAYS_LOOP),\n\tmSystemInfo(window, \"SYSTEM INFO\", Font::get(FONT_SIZE_SMALL), 0x33333300, ALIGN_CENTER)\n{\n\tmCamOffset = 0;\n\tmExtrasCamOffset = 0;\n\tmExtrasFadeOpacity = 0.0f;\n\n\tsetSize((float)Renderer::getScreenWidth(), (float)Renderer::getScreenHeight());\n\n\tmSystemInfo.setSize(mSize.x(), mSystemInfo.getSize().y() * 1.333f);\n\tmSystemInfo.setPosition(0, (mSize.y() + BAND_HEIGHT) \/ 2);\n\n\tpopulate();\n}\n\nvoid SystemView::populate()\n{\n\tmEntries.clear();\n\n\tfor(auto it = SystemData::sSystemVector.begin(); it != SystemData::sSystemVector.end(); it++)\n\t{\n\t\tconst std::shared_ptr& theme = (*it)->getTheme();\n\n\t\tEntry e;\n\t\te.name = (*it)->getName();\n\t\te.object = *it;\n\n\t\t\/\/ make logo\n\t\tif(theme->getElement(\"system\", \"logo\", \"image\"))\n\t\t{\n\t\t\tImageComponent* logo = new ImageComponent(mWindow);\n\t\t\tlogo->setMaxSize(Eigen::Vector2f(logoSize().x(), logoSize().y()));\n\t\t\tlogo->applyTheme((*it)->getTheme(), \"system\", \"logo\", ThemeFlags::PATH);\n\t\t\tlogo->setPosition((logoSize().x() - logo->getSize().x()) \/ 2, (logoSize().y() - logo->getSize().y()) \/ 2); \/\/ center\n\t\t\te.data.logo = std::shared_ptr(logo);\n\n\t\t\tImageComponent* logoSelected = new ImageComponent(mWindow);\n\t\t\tlogoSelected->setMaxSize(Eigen::Vector2f(logoSize().x() * SELECTED_SCALE, logoSize().y() * SELECTED_SCALE * 0.70f));\n\t\t\tlogoSelected->applyTheme((*it)->getTheme(), \"system\", \"logo\", ThemeFlags::PATH);\n\t\t\tlogoSelected->setPosition((logoSize().x() - logoSelected->getSize().x()) \/ 2, \n\t\t\t\t(logoSize().y() - logoSelected->getSize().y()) \/ 2); \/\/ center\n\t\t\te.data.logoSelected = std::shared_ptr(logoSelected);\n\t\t}else{\n\t\t\t\/\/ no logo in theme; use text\n\t\t\tTextComponent* text = new TextComponent(mWindow, \n\t\t\t\t(*it)->getName(), \n\t\t\t\tFont::get(FONT_SIZE_LARGE), \n\t\t\t\t0x000000FF, \n\t\t\t\tALIGN_CENTER);\n\t\t\ttext->setSize(logoSize());\n\t\t\te.data.logo = std::shared_ptr(text);\n\n\t\t\tTextComponent* textSelected = new TextComponent(mWindow, \n\t\t\t\t(*it)->getName(), \n\t\t\t\tFont::get((int)(FONT_SIZE_LARGE * SELECTED_SCALE)), \n\t\t\t\t0x000000FF, \n\t\t\t\tALIGN_CENTER);\n\t\t\ttextSelected->setSize(logoSize());\n\t\t\te.data.logoSelected = std::shared_ptr(textSelected);\n\t\t}\n\n\t\t\/\/ make background extras\n\t\te.data.backgroundExtras = std::shared_ptr(new ThemeExtras(mWindow));\n\t\te.data.backgroundExtras->setExtras(ThemeData::makeExtras((*it)->getTheme(), \"system\", mWindow));\n\n\t\tthis->add(e);\n\t}\n}\n\nvoid SystemView::goToSystem(SystemData* system, bool animate)\n{\n\tsetCursor(system);\n\n\tif(!animate)\n\t\tfinishAnimation(0);\n}\n\nbool SystemView::input(InputConfig* config, Input input)\n{\n\tif(input.value != 0)\n\t{\n\t\tif(config->getDeviceId() == DEVICE_KEYBOARD && input.value && input.id == SDLK_r && SDL_GetModState() & KMOD_LCTRL && Settings::getInstance()->getBool(\"Debug\"))\n\t\t{\n\t\t\tLOG(LogInfo) << \" Reloading SystemList view\";\n\n\t\t\t\/\/ reload themes\n\t\t\tfor(auto it = mEntries.begin(); it != mEntries.end(); it++)\n\t\t\t\tit->object->loadTheme();\n\n\t\t\tpopulate();\n\t\t\tupdateHelpPrompts();\n\t\t\treturn true;\n\t\t}\n\t\tif(config->isMappedTo(\"left\", input))\n\t\t{\n\t\t\tlistInput(-1);\n\t\t\treturn true;\n\t\t}\n\t\tif(config->isMappedTo(\"right\", input))\n\t\t{\n\t\t\tlistInput(1);\n\t\t\treturn true;\n\t\t}\n\t\tif(config->isMappedTo(\"a\", input))\n\t\t{\n\t\t\tstopScrolling();\n\t\t\tViewController::get()->goToGameList(getSelected());\n\t\t\treturn true;\n\t\t}\n\t}else{\n\t\tif(config->isMappedTo(\"left\", input) || config->isMappedTo(\"right\", input))\n\t\t\tlistInput(0);\n\t}\n\n\treturn GuiComponent::input(config, input);\n}\n\nvoid SystemView::update(int deltaTime)\n{\n\tlistUpdate(deltaTime);\n\tGuiComponent::update(deltaTime);\n}\n\nvoid SystemView::onCursorChanged(const CursorState& state)\n{\n\n\tif(lastSystem != getSelected()){\n\t\tlastSystem = getSelected();\n\t\tMusic::startMusic(getSelected()->getTheme());\n\t}\n\t\/\/ update help style\n\tupdateHelpPrompts();\n\n\tfloat startPos = mCamOffset;\n\n\tfloat posMax = (float)mEntries.size();\n\tfloat target = (float)mCursor;\n\n\t\/\/ what's the shortest way to get to our target?\n\t\/\/ it's one of these...\n\n\tfloat endPos = target; \/\/ directly\n\tfloat dist = abs(endPos - startPos);\n\t\n\tif(abs(target + posMax - startPos) < dist)\n\t\tendPos = target + posMax; \/\/ loop around the end (0 -> max)\n\tif(abs(target - posMax - startPos) < dist)\n\t\tendPos = target - posMax; \/\/ loop around the start (max - 1 -> -1)\n\n\t\n\t\/\/ animate mSystemInfo's opacity (fade out, wait, fade back in)\n\n\tcancelAnimation(1);\n\tcancelAnimation(2);\n\n\tconst float infoStartOpacity = mSystemInfo.getOpacity() \/ 255.f;\n\n\tAnimation* infoFadeOut = new LambdaAnimation(\n\t\t[infoStartOpacity, this] (float t)\n\t{\n\t\tmSystemInfo.setOpacity((unsigned char)(lerp(infoStartOpacity, 0.f, t) * 255));\n\t}, (int)(infoStartOpacity * 150));\n\n\tunsigned int gameCount = getSelected()->getGameCount();\n\n\t\/\/ also change the text after we've fully faded out\n\tsetAnimation(infoFadeOut, 0, [this, gameCount] {\n\t\tstd::stringstream ss;\n\t\t\n\t\t\/\/ only display a game count if there are at least 2 games\n\t\tif(gameCount > 1)\n\t\t\tss << gameCount << \" GAMES AVAILABLE\";\n\n\t\tmSystemInfo.setText(ss.str()); \n\t}, false, 1);\n\n\t\/\/ only display a game count if there are at least 2 games\n\tif(gameCount > 1)\n\t{\n\t\tAnimation* infoFadeIn = new LambdaAnimation(\n\t\t\t[this](float t)\n\t\t{\n\t\t\tmSystemInfo.setOpacity((unsigned char)(lerp(0.f, 1.f, t) * 255));\n\t\t}, 300);\n\n\t\t\/\/ wait 600ms to fade in\n\t\tsetAnimation(infoFadeIn, 2000, nullptr, false, 2);\n\t}\n\n\t\/\/ no need to animate transition, we're not going anywhere (probably mEntries.size() == 1)\n\tif(endPos == mCamOffset && endPos == mExtrasCamOffset)\n\t\treturn;\n\n\tAnimation* anim;\n\tif(Settings::getInstance()->getString(\"TransitionStyle\") == \"fade\")\n\t{\n\t\tfloat startExtrasFade = mExtrasFadeOpacity;\n\t\tanim = new LambdaAnimation(\n\t\t\t[startExtrasFade, startPos, endPos, posMax, this](float t)\n\t\t{\n\t\t\tt -= 1;\n\t\t\tfloat f = lerp(startPos, endPos, t*t*t + 1);\n\t\t\tif(f < 0)\n\t\t\t\tf += posMax;\n\t\t\tif(f >= posMax)\n\t\t\t\tf -= posMax;\n\n\t\t\tthis->mCamOffset = f;\n\n\t\t\tt += 1;\n\t\t\tif(t < 0.3f)\n\t\t\t\tthis->mExtrasFadeOpacity = lerp(0.0f, 1.0f, t \/ 0.3f + startExtrasFade);\n\t\t\telse if(t < 0.7f)\n\t\t\t\tthis->mExtrasFadeOpacity = 1.0f;\n\t\t\telse\n\t\t\t\tthis->mExtrasFadeOpacity = lerp(1.0f, 0.0f, (t - 0.7f) \/ 0.3f);\n\n\t\t\tif(t > 0.5f)\n\t\t\t\tthis->mExtrasCamOffset = endPos;\n\n\t\t}, 500);\n\t}\n\telse{ \/\/ slide\n\t\tanim = new LambdaAnimation(\n\t\t\t[startPos, endPos, posMax, this](float t)\n\t\t{\n\t\t\tt -= 1;\n\t\t\tfloat f = lerp(startPos, endPos, t*t*t + 1);\n\t\t\tif(f < 0)\n\t\t\t\tf += posMax;\n\t\t\tif(f >= posMax)\n\t\t\t\tf -= posMax;\n\n\t\t\tthis->mCamOffset = f;\n\t\t\tthis->mExtrasCamOffset = f;\n\t\t}, 500);\n\t}\n\n\tsetAnimation(anim, 0, nullptr, false, 0);\n}\n\nvoid SystemView::render(const Eigen::Affine3f& parentTrans)\n{\n\tif(size() == 0)\n\t\treturn;\n\n\tEigen::Affine3f trans = getTransform() * parentTrans;\n\t\n\t\/\/ draw the list elements (titles, backgrounds, logos)\n\tconst float logoSizeX = logoSize().x() + LOGO_PADDING;\n\n\tint logoCount = (int)(mSize.x() \/ logoSizeX) + 2; \/\/ how many logos we need to draw\n\tint center = (int)(mCamOffset);\n\n\tif(mEntries.size() == 1)\n\t\tlogoCount = 1;\n\n\t\/\/ draw background extras\n\tEigen::Affine3f extrasTrans = trans;\n\tint extrasCenter = (int)mExtrasCamOffset;\n\tfor(int i = extrasCenter - 1; i < extrasCenter + 2; i++)\n\t{\n\t\tint index = i;\n\t\twhile(index < 0)\n\t\t\tindex += mEntries.size();\n\t\twhile(index >= (int)mEntries.size())\n\t\t\tindex -= mEntries.size();\n\n\t\textrasTrans.translation() = trans.translation() + Eigen::Vector3f((i - mExtrasCamOffset) * mSize.x(), 0, 0);\n\n\t\tEigen::Vector2i clipRect = Eigen::Vector2i((int)((i - mExtrasCamOffset) * mSize.x()), 0);\n\t\tRenderer::pushClipRect(clipRect, mSize.cast());\n\t\tmEntries.at(index).data.backgroundExtras->render(extrasTrans);\n\t\tRenderer::popClipRect();\n\t}\n\n\t\/\/ fade extras if necessary\n\tif(mExtrasFadeOpacity)\n\t{\n\t\tRenderer::setMatrix(trans);\n\t\tRenderer::drawRect(0.0f, 0.0f, mSize.x(), mSize.y(), 0x00000000 | (unsigned char)(mExtrasFadeOpacity * 255));\n\t}\n\n\t\/\/ draw logos\n\tfloat xOff = (mSize.x() - logoSize().x())\/2 - (mCamOffset * logoSizeX);\n\tfloat yOff = (mSize.y() - logoSize().y())\/2;\n\n\t\/\/ background behind the logos\n\tRenderer::setMatrix(trans);\n\tRenderer::drawRect(0.f, (mSize.y() - BAND_HEIGHT) \/ 2, mSize.x(), BAND_HEIGHT, 0xFFFFFFD8);\n\n\tEigen::Affine3f logoTrans = trans;\n\tfor(int i = center - logoCount\/2; i < center + logoCount\/2 + 1; i++)\n\t{\n\t\tint index = i;\n\t\twhile(index < 0)\n\t\t\tindex += mEntries.size();\n\t\twhile(index >= (int)mEntries.size())\n\t\t\tindex -= mEntries.size();\n\n\t\tlogoTrans.translation() = trans.translation() + Eigen::Vector3f(i * logoSizeX + xOff, yOff, 0);\n\n\t\tif(index == mCursor) \/\/scale our selection up\n\t\t{\n\t\t\t\/\/ selected\n\t\t\tconst std::shared_ptr& comp = mEntries.at(index).data.logoSelected;\n\t\t\tcomp->setOpacity(0xFF);\n\t\t\tcomp->render(logoTrans);\n\t\t}else{\n\t\t\t\/\/ not selected\n\t\t\tconst std::shared_ptr& comp = mEntries.at(index).data.logo;\n\t\t\tcomp->setOpacity(0x80);\n\t\t\tcomp->render(logoTrans);\n\t\t}\n\t}\n\n\tRenderer::setMatrix(trans);\n\tRenderer::drawRect(mSystemInfo.getPosition().x(), mSystemInfo.getPosition().y() - 1, mSize.x(), mSystemInfo.getSize().y(), 0xDDDDDD00 | (unsigned char)(mSystemInfo.getOpacity() \/ 255.f * 0xD8));\n\tmSystemInfo.render(trans);\n}\n\nstd::vector SystemView::getHelpPrompts()\n{\n\tstd::vector prompts;\n\tprompts.push_back(HelpPrompt(\"left\/right\", \"choose\"));\n\tprompts.push_back(HelpPrompt(\"a\", \"select\"));\n\treturn prompts;\n}\n\nHelpStyle SystemView::getHelpStyle()\n{\n\tHelpStyle style;\n\tstyle.applyTheme(mEntries.at(mCursor).object->getTheme(), \"system\");\n\treturn style;\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/gui:$Name: $:$Id: TRootEmbeddedCanvas.cxx,v 1.3 2001\/02\/14 15:39:35 rdm Exp $\n\/\/ Author: Fons Rademakers 15\/07\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootEmbeddedCanvas \/\/\n\/\/ \/\/\n\/\/ This class creates a TGCanvas in which a TCanvas is created. Use \/\/\n\/\/ GetCanvas() to get a pointer to the TCanvas. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TRootEmbeddedCanvas.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootEmbeddedContainer \/\/\n\/\/ \/\/\n\/\/ Utility class used by TRootEmbeddedCanvas. The TRootEmbeddedContainer\/\/\n\/\/ is the frame embedded in the TGCanvas widget. The ROOT graphics goes \/\/\n\/\/ into this frame. This class is used to enable input events on this \/\/\n\/\/ graphics frame and forward the events to the TRootEmbeddedCanvas \/\/\n\/\/ handlers. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass TRootEmbeddedContainer : public TGCompositeFrame {\nprivate:\n TRootEmbeddedCanvas *fCanvas; \/\/ pointer back to embedded canvas\npublic:\n TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id, const TGWindow *parent);\n\n Bool_t HandleButton(Event_t *ev)\n { return fCanvas->HandleContainerButton(ev); }\n Bool_t HandleDoubleClick(Event_t *ev)\n { return fCanvas->HandleContainerDoubleClick(ev); }\n Bool_t HandleConfigureNotify(Event_t *ev)\n { TGFrame::HandleConfigureNotify(ev);\n return fCanvas->HandleContainerConfigure(ev); }\n Bool_t HandleKey(Event_t *ev)\n { return fCanvas->HandleContainerKey(ev); }\n Bool_t HandleMotion(Event_t *ev)\n { return fCanvas->HandleContainerMotion(ev); }\n Bool_t HandleExpose(Event_t *ev)\n { return fCanvas->HandleContainerExpose(ev); }\n Bool_t HandleCrossing(Event_t *ev)\n { return fCanvas->HandleContainerCrossing(ev); }\n};\n\n\/\/______________________________________________________________________________\nTRootEmbeddedContainer::TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id,\n const TGWindow *p) : TGCompositeFrame(gClient, id, p)\n{\n \/\/ Create a canvas container.\n\n fCanvas = c;\n\n gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,\n kButtonPressMask | kButtonReleaseMask,\n kNone, kNone);\n\n AddInput(kKeyPressMask | kKeyReleaseMask | kPointerMotionMask |\n kExposureMask | kStructureNotifyMask | kLeaveWindowMask);\n}\n\n\n\n\nClassImp(TRootEmbeddedCanvas)\n\n\/\/______________________________________________________________________________\nTRootEmbeddedCanvas::TRootEmbeddedCanvas(const char *name, const TGWindow *p,\n UInt_t w, UInt_t h, UInt_t options, ULong_t back)\n : TGCanvas(p, w, h, options, back)\n{\n \/\/ Create an TCanvas embedded in a TGFrame. A pointer to the TCanvas can\n \/\/ be obtained via the GetCanvas() member function. To embed a canvas\n \/\/ derived from a TCanvas do the following:\n \/\/ TRootEmbeddedCanvas *embedded = new TRootEmbeddedCanvas(0, p, w, h);\n \/\/ [note name must be 0, not null string \"\"]\n \/\/ Int_t wid = embedded->GetCanvasWindowId();\n \/\/ TMyCanvas *myc = new TMyCanvas(\"myname\", 10, 10, wid);\n \/\/ embedded->AdoptCanvas(myc);\n \/\/ [ the MyCanvas is adopted by the embedded canvas and will be\n \/\/ destroyed by it ]\n\n fButton = 0;\n fAutoFit = kTRUE;\n\n fCWinId = gVirtualX->InitWindow((ULong_t)GetViewPort()->GetId());\n Window_t win = gVirtualX->GetWindowID(fCWinId);\n fCanvasContainer = new TRootEmbeddedContainer(this, win, GetViewPort());\n SetContainer(fCanvasContainer);\n\n if (name)\n fCanvas = new TCanvas(name, 10, 10, fCWinId);\n}\n\n\/\/______________________________________________________________________________\nTRootEmbeddedCanvas::~TRootEmbeddedCanvas()\n{\n \/\/ Delete embedded ROOT canvas.\n\n delete fCanvas;\n delete fCanvasContainer;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerButton(Event_t *event)\n{\n \/\/ Handle mouse button events in the canvas container.\n\n Int_t button = event->fCode;\n Int_t x = event->fX;\n Int_t y = event->fY;\n\n if (event->fType == kButtonPress) {\n fButton = button;\n if (button == kButton1)\n fCanvas->HandleInput(kButton1Down, x, y);\n if (button == kButton2)\n fCanvas->HandleInput(kButton2Down, x, y);\n if (button == kButton3) {\n fCanvas->HandleInput(kButton3Down, x, y);\n fButton = 0; \/\/ button up is consumed by TContextMenu\n }\n\n } else if (event->fType == kButtonRelease) {\n if (button == kButton1)\n fCanvas->HandleInput(kButton1Up, x, y);\n if (button == kButton2)\n fCanvas->HandleInput(kButton2Up, x, y);\n if (button == kButton3)\n fCanvas->HandleInput(kButton3Up, x, y);\n\n fButton = 0;\n }\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerDoubleClick(Event_t *event)\n{\n \/\/ Handle mouse button double click events in the canvas container.\n\n Int_t button = event->fCode;\n Int_t x = event->fX;\n Int_t y = event->fY;\n\n if (button == kButton1)\n fCanvas->HandleInput(kButton1Double, x, y);\n if (button == kButton2)\n fCanvas->HandleInput(kButton2Double, x, y);\n if (button == kButton3)\n fCanvas->HandleInput(kButton3Double, x, y);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerConfigure(Event_t *)\n{\n \/\/ Handle configure (i.e. resize) event.\n\n if (fAutoFit) {\n fCanvas->Resize();\n fCanvas->Update();\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerKey(Event_t *event)\n{\n \/\/ Handle keyboard events in the canvas container.\n\n if (event->fType == kGKeyPress) {\n fButton = event->fCode;\n UInt_t keysym;\n char str[2];\n gVirtualX->LookupString(event, str, sizeof(str), keysym);\n if (str[0] == 3) \/\/ ctrl-c sets the interrupt flag\n gROOT->SetInterrupt();\n fCanvas->HandleInput(kKeyPress, str[0], keysym);\n } else if (event->fType == kKeyRelease)\n fButton = 0;\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerMotion(Event_t *event)\n{\n \/\/ Handle mouse motion event in the canvas container.\n\n Int_t x = event->fX;\n Int_t y = event->fY;\n\n if (fButton == 0)\n fCanvas->HandleInput(kMouseMotion, x, y);\n if (fButton == kButton1)\n fCanvas->HandleInput(kButton1Motion, x, y);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerExpose(Event_t *event)\n{\n \/\/ Handle expose events.\n\n if (event->fCount == 0)\n fCanvas->Flush();\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerCrossing(Event_t *event)\n{\n \/\/ Handle enter\/leave events. Only leave is activated at the moment.\n\n if (event->fType == kLeaveNotify)\n fCanvas->HandleInput(kMouseLeave, 0, 0);\n\n return kTRUE;\n}\nfCanvas was not initialzed to 0 and add protection in methods against fCanvas possibly being 0.\/\/ @(#)root\/gui:$Name: $:$Id: TRootEmbeddedCanvas.cxx,v 1.4 2001\/04\/04 13:38:38 rdm Exp $\n\/\/ Author: Fons Rademakers 15\/07\/98\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootEmbeddedCanvas \/\/\n\/\/ \/\/\n\/\/ This class creates a TGCanvas in which a TCanvas is created. Use \/\/\n\/\/ GetCanvas() to get a pointer to the TCanvas. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TRootEmbeddedCanvas.h\"\n#include \"TCanvas.h\"\n#include \"TROOT.h\"\n\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TRootEmbeddedContainer \/\/\n\/\/ \/\/\n\/\/ Utility class used by TRootEmbeddedCanvas. The TRootEmbeddedContainer\/\/\n\/\/ is the frame embedded in the TGCanvas widget. The ROOT graphics goes \/\/\n\/\/ into this frame. This class is used to enable input events on this \/\/\n\/\/ graphics frame and forward the events to the TRootEmbeddedCanvas \/\/\n\/\/ handlers. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\nclass TRootEmbeddedContainer : public TGCompositeFrame {\nprivate:\n TRootEmbeddedCanvas *fCanvas; \/\/ pointer back to embedded canvas\npublic:\n TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id, const TGWindow *parent);\n\n Bool_t HandleButton(Event_t *ev)\n { return fCanvas->HandleContainerButton(ev); }\n Bool_t HandleDoubleClick(Event_t *ev)\n { return fCanvas->HandleContainerDoubleClick(ev); }\n Bool_t HandleConfigureNotify(Event_t *ev)\n { TGFrame::HandleConfigureNotify(ev);\n return fCanvas->HandleContainerConfigure(ev); }\n Bool_t HandleKey(Event_t *ev)\n { return fCanvas->HandleContainerKey(ev); }\n Bool_t HandleMotion(Event_t *ev)\n { return fCanvas->HandleContainerMotion(ev); }\n Bool_t HandleExpose(Event_t *ev)\n { return fCanvas->HandleContainerExpose(ev); }\n Bool_t HandleCrossing(Event_t *ev)\n { return fCanvas->HandleContainerCrossing(ev); }\n};\n\n\/\/______________________________________________________________________________\nTRootEmbeddedContainer::TRootEmbeddedContainer(TRootEmbeddedCanvas *c, Window_t id,\n const TGWindow *p) : TGCompositeFrame(gClient, id, p)\n{\n \/\/ Create a canvas container.\n\n fCanvas = c;\n\n gVirtualX->GrabButton(fId, kAnyButton, kAnyModifier,\n kButtonPressMask | kButtonReleaseMask,\n kNone, kNone);\n\n AddInput(kKeyPressMask | kKeyReleaseMask | kPointerMotionMask |\n kExposureMask | kStructureNotifyMask | kLeaveWindowMask);\n}\n\n\n\n\nClassImp(TRootEmbeddedCanvas)\n\n\/\/______________________________________________________________________________\nTRootEmbeddedCanvas::TRootEmbeddedCanvas(const char *name, const TGWindow *p,\n UInt_t w, UInt_t h, UInt_t options, ULong_t back)\n : TGCanvas(p, w, h, options, back)\n{\n \/\/ Create an TCanvas embedded in a TGFrame. A pointer to the TCanvas can\n \/\/ be obtained via the GetCanvas() member function. To embed a canvas\n \/\/ derived from a TCanvas do the following:\n \/\/ TRootEmbeddedCanvas *embedded = new TRootEmbeddedCanvas(0, p, w, h);\n \/\/ [note name must be 0, not null string \"\"]\n \/\/ Int_t wid = embedded->GetCanvasWindowId();\n \/\/ TMyCanvas *myc = new TMyCanvas(\"myname\", 10, 10, wid);\n \/\/ embedded->AdoptCanvas(myc);\n \/\/ [ the MyCanvas is adopted by the embedded canvas and will be\n \/\/ destroyed by it ]\n\n fCanvas = 0;\n fButton = 0;\n fAutoFit = kTRUE;\n\n fCWinId = gVirtualX->InitWindow((ULong_t)GetViewPort()->GetId());\n Window_t win = gVirtualX->GetWindowID(fCWinId);\n fCanvasContainer = new TRootEmbeddedContainer(this, win, GetViewPort());\n SetContainer(fCanvasContainer);\n\n if (name)\n fCanvas = new TCanvas(name, 10, 10, fCWinId);\n}\n\n\/\/______________________________________________________________________________\nTRootEmbeddedCanvas::~TRootEmbeddedCanvas()\n{\n \/\/ Delete embedded ROOT canvas.\n\n delete fCanvas;\n delete fCanvasContainer;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerButton(Event_t *event)\n{\n \/\/ Handle mouse button events in the canvas container.\n\n if (!fCanvas) return kTRUE;\n\n Int_t button = event->fCode;\n Int_t x = event->fX;\n Int_t y = event->fY;\n\n if (event->fType == kButtonPress) {\n fButton = button;\n if (button == kButton1)\n fCanvas->HandleInput(kButton1Down, x, y);\n if (button == kButton2)\n fCanvas->HandleInput(kButton2Down, x, y);\n if (button == kButton3) {\n fCanvas->HandleInput(kButton3Down, x, y);\n fButton = 0; \/\/ button up is consumed by TContextMenu\n }\n\n } else if (event->fType == kButtonRelease) {\n if (button == kButton1)\n fCanvas->HandleInput(kButton1Up, x, y);\n if (button == kButton2)\n fCanvas->HandleInput(kButton2Up, x, y);\n if (button == kButton3)\n fCanvas->HandleInput(kButton3Up, x, y);\n\n fButton = 0;\n }\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerDoubleClick(Event_t *event)\n{\n \/\/ Handle mouse button double click events in the canvas container.\n\n if (!fCanvas) return kTRUE;\n\n Int_t button = event->fCode;\n Int_t x = event->fX;\n Int_t y = event->fY;\n\n if (button == kButton1)\n fCanvas->HandleInput(kButton1Double, x, y);\n if (button == kButton2)\n fCanvas->HandleInput(kButton2Double, x, y);\n if (button == kButton3)\n fCanvas->HandleInput(kButton3Double, x, y);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerConfigure(Event_t *)\n{\n \/\/ Handle configure (i.e. resize) event.\n\n if (fAutoFit && fCanvas) {\n fCanvas->Resize();\n fCanvas->Update();\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerKey(Event_t *event)\n{\n \/\/ Handle keyboard events in the canvas container.\n\n if (!fCanvas) return kTRUE;\n\n if (event->fType == kGKeyPress) {\n fButton = event->fCode;\n UInt_t keysym;\n char str[2];\n gVirtualX->LookupString(event, str, sizeof(str), keysym);\n if (str[0] == 3) \/\/ ctrl-c sets the interrupt flag\n gROOT->SetInterrupt();\n fCanvas->HandleInput(kKeyPress, str[0], keysym);\n } else if (event->fType == kKeyRelease)\n fButton = 0;\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerMotion(Event_t *event)\n{\n \/\/ Handle mouse motion event in the canvas container.\n\n if (!fCanvas) return kTRUE;\n\n Int_t x = event->fX;\n Int_t y = event->fY;\n\n if (fButton == 0)\n fCanvas->HandleInput(kMouseMotion, x, y);\n if (fButton == kButton1)\n fCanvas->HandleInput(kButton1Motion, x, y);\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerExpose(Event_t *event)\n{\n \/\/ Handle expose events.\n\n if (!fCanvas) return kTRUE;\n\n if (event->fCount == 0)\n fCanvas->Flush();\n\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nBool_t TRootEmbeddedCanvas::HandleContainerCrossing(Event_t *event)\n{\n \/\/ Handle enter\/leave events. Only leave is activated at the moment.\n\n if (!fCanvas) return kTRUE;\n\n if (event->fType == kLeaveNotify)\n fCanvas->HandleInput(kMouseLeave, 0, 0);\n\n return kTRUE;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"build\/build_config.h\"\n#include \"base\/debug_util.h\"\n\n#if defined(OS_LINUX)\n#include \n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_piece.h\"\n\n\/\/ static\nbool DebugUtil::SpawnDebuggerOnProcess(unsigned \/* process_id *\/) {\n NOTIMPLEMENTED();\n return false;\n}\n\n#if defined(OS_MACOSX)\n\n\/\/ Based on Apple's recommended method as described in\n\/\/ http:\/\/developer.apple.com\/qa\/qa2004\/qa1361.html\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n \/\/ Initialize mib, which tells sysctl what info we want. In this case,\n \/\/ we're looking for information about a specific process ID.\n int mib[] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid()\n };\n\n \/\/ Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and\n \/\/ binary interfaces may change.\n struct kinfo_proc info;\n size_t info_size = sizeof(info);\n\n int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);\n DCHECK(sysctl_result == 0);\n if (sysctl_result != 0)\n return false;\n\n \/\/ This process is being debugged if the P_TRACED flag is set.\n return (info.kp_proc.p_flag & P_TRACED) != 0;\n}\n\n#elif defined(OS_LINUX)\n\n\/\/ We can look in \/proc\/self\/status for TracerPid. We are likely used in crash\n\/\/ handling, so we are careful not to use the heap or have side effects.\n\/\/ Another option that is common is to try to ptrace yourself, but then we\n\/\/ can't detach without forking(), and that's not so great.\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n int status_fd = open(\"\/proc\/self\/status\", O_RDONLY);\n if (status_fd == -1)\n return false;\n\n \/\/ We assume our line will be in the first 1024 characters and that we can\n \/\/ read this much all at once. In practice this will generally be true.\n \/\/ This simplifies and speeds up things considerably.\n char buf[1024];\n\n ssize_t num_read = read(status_fd, buf, sizeof(buf));\n close(status_fd);\n\n if (num_read <= 0)\n return false;\n\n StringPiece status(buf, num_read);\n StringPiece tracer(\"TracerPid:\\t\");\n\n StringPiece::size_type pid_index = status.find(tracer);\n if (pid_index == StringPiece::npos)\n return false;\n\n \/\/ Our pid is 0 without a debugger, assume this for any pid starting with 0.\n pid_index += tracer.size();\n return pid_index < status.size() && status[pid_index] != '0';\n}\n\n#endif \/\/ OS_LINUX\n\n\/\/ static\nvoid DebugUtil::BreakDebugger() {\n asm (\"int3\");\n}\n\n#if defined(OS_LINUX)\n\nStackTrace::StackTrace() {\n static const unsigned kMaxCallers = 256;\n\n void* callers[kMaxCallers];\n int count = backtrace(callers, kMaxCallers);\n trace_.resize(count);\n memcpy(&trace_[0], callers, sizeof(void*) * count);\n}\n\nvoid StackTrace::PrintBacktrace() {\n fflush(stderr);\n backtrace_symbols_fd(&trace_[0], trace_.size(), STDERR_FILENO);\n}\n\n#elif defined(OS_MACOSX)\n\n\/\/ TODO(port): complete this code\nStackTrace::StackTrace() { }\n\nStackTrace::PrintBacktrace() {\n NOTIMPLEMENTED();\n}\n\n#endif \/\/ defined(OS_MACOSX)\n\nconst void *const *StackTrace::Addresses(size_t* count) {\n *count = trace_.size();\n if (trace_.size())\n return &trace_[0];\n return NULL;\n}\nMac build fix\/\/ Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"build\/build_config.h\"\n#include \"base\/debug_util.h\"\n\n#if defined(OS_LINUX)\n#include \n#include \n#endif\n\n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \"base\/basictypes.h\"\n#include \"base\/logging.h\"\n#include \"base\/string_piece.h\"\n\n\/\/ static\nbool DebugUtil::SpawnDebuggerOnProcess(unsigned \/* process_id *\/) {\n NOTIMPLEMENTED();\n return false;\n}\n\n#if defined(OS_MACOSX)\n\n\/\/ Based on Apple's recommended method as described in\n\/\/ http:\/\/developer.apple.com\/qa\/qa2004\/qa1361.html\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n \/\/ Initialize mib, which tells sysctl what info we want. In this case,\n \/\/ we're looking for information about a specific process ID.\n int mib[] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid()\n };\n\n \/\/ Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and\n \/\/ binary interfaces may change.\n struct kinfo_proc info;\n size_t info_size = sizeof(info);\n\n int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);\n DCHECK(sysctl_result == 0);\n if (sysctl_result != 0)\n return false;\n\n \/\/ This process is being debugged if the P_TRACED flag is set.\n return (info.kp_proc.p_flag & P_TRACED) != 0;\n}\n\n#elif defined(OS_LINUX)\n\n\/\/ We can look in \/proc\/self\/status for TracerPid. We are likely used in crash\n\/\/ handling, so we are careful not to use the heap or have side effects.\n\/\/ Another option that is common is to try to ptrace yourself, but then we\n\/\/ can't detach without forking(), and that's not so great.\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n int status_fd = open(\"\/proc\/self\/status\", O_RDONLY);\n if (status_fd == -1)\n return false;\n\n \/\/ We assume our line will be in the first 1024 characters and that we can\n \/\/ read this much all at once. In practice this will generally be true.\n \/\/ This simplifies and speeds up things considerably.\n char buf[1024];\n\n ssize_t num_read = read(status_fd, buf, sizeof(buf));\n close(status_fd);\n\n if (num_read <= 0)\n return false;\n\n StringPiece status(buf, num_read);\n StringPiece tracer(\"TracerPid:\\t\");\n\n StringPiece::size_type pid_index = status.find(tracer);\n if (pid_index == StringPiece::npos)\n return false;\n\n \/\/ Our pid is 0 without a debugger, assume this for any pid starting with 0.\n pid_index += tracer.size();\n return pid_index < status.size() && status[pid_index] != '0';\n}\n\n#endif \/\/ OS_LINUX\n\n\/\/ static\nvoid DebugUtil::BreakDebugger() {\n asm (\"int3\");\n}\n\n#if defined(OS_LINUX)\n\nStackTrace::StackTrace() {\n static const unsigned kMaxCallers = 256;\n\n void* callers[kMaxCallers];\n int count = backtrace(callers, kMaxCallers);\n trace_.resize(count);\n memcpy(&trace_[0], callers, sizeof(void*) * count);\n}\n\nvoid StackTrace::PrintBacktrace() {\n fflush(stderr);\n backtrace_symbols_fd(&trace_[0], trace_.size(), STDERR_FILENO);\n}\n\n#elif defined(OS_MACOSX)\n\n\/\/ TODO(port): complete this code\nStackTrace::StackTrace() { }\n\nvoid StackTrace::PrintBacktrace() {\n NOTIMPLEMENTED();\n}\n\n#endif \/\/ defined(OS_MACOSX)\n\nconst void *const *StackTrace::Addresses(size_t* count) {\n *count = trace_.size();\n if (trace_.size())\n return &trace_[0];\n return NULL;\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"build\/build_config.h\"\n#include \"base\/debug_util.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(OS_MACOSX)\n#include \n#endif\n\n#include \"base\/basictypes.h\"\n#include \"base\/compat_execinfo.h\"\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_piece.h\"\n\n\/\/ static\nbool DebugUtil::SpawnDebuggerOnProcess(unsigned \/* process_id *\/) {\n NOTIMPLEMENTED();\n return false;\n}\n\n#if defined(OS_MACOSX)\n\n\/\/ Based on Apple's recommended method as described in\n\/\/ http:\/\/developer.apple.com\/qa\/qa2004\/qa1361.html\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n \/\/ If the process is sandboxed then we can't use the sysctl, so cache the\n \/\/ value.\n static bool is_set = false;\n static bool being_debugged = false;\n\n if (is_set) {\n return being_debugged;\n }\n\n \/\/ Initialize mib, which tells sysctl what info we want. In this case,\n \/\/ we're looking for information about a specific process ID.\n int mib[] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid()\n };\n\n \/\/ Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and\n \/\/ binary interfaces may change.\n struct kinfo_proc info;\n size_t info_size = sizeof(info);\n\n int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);\n DCHECK(sysctl_result == 0);\n if (sysctl_result != 0) {\n is_set = true;\n being_debugged = false;\n return being_debugged;\n }\n\n \/\/ This process is being debugged if the P_TRACED flag is set.\n is_set = true;\n being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;\n return being_debugged;\n}\n\n#elif defined(OS_LINUX)\n\n\/\/ We can look in \/proc\/self\/status for TracerPid. We are likely used in crash\n\/\/ handling, so we are careful not to use the heap or have side effects.\n\/\/ Another option that is common is to try to ptrace yourself, but then we\n\/\/ can't detach without forking(), and that's not so great.\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n int status_fd = open(\"\/proc\/self\/status\", O_RDONLY);\n if (status_fd == -1)\n return false;\n\n \/\/ We assume our line will be in the first 1024 characters and that we can\n \/\/ read this much all at once. In practice this will generally be true.\n \/\/ This simplifies and speeds up things considerably.\n char buf[1024];\n\n ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));\n HANDLE_EINTR(close(status_fd));\n\n if (num_read <= 0)\n return false;\n\n base::StringPiece status(buf, num_read);\n base::StringPiece tracer(\"TracerPid:\\t\");\n\n base::StringPiece::size_type pid_index = status.find(tracer);\n if (pid_index == base::StringPiece::npos)\n return false;\n\n \/\/ Our pid is 0 without a debugger, assume this for any pid starting with 0.\n pid_index += tracer.size();\n return pid_index < status.size() && status[pid_index] != '0';\n}\n\n#endif \/\/ OS_LINUX\n\n\/\/ static\nvoid DebugUtil::BreakDebugger() {\n#if defined(ARCH_CPU_ARM_FAMILY)\n asm(\"bkpt 0\");\n#else\n asm(\"int3\");\n#endif\n}\n\nStackTrace::StackTrace() {\n#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5\n if (!backtrace) {\n count_ = 0;\n return;\n }\n#endif\n \/\/ Though the backtrace API man page does not list any possible negative\n \/\/ return values, we take no chance.\n count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);\n}\n\nvoid StackTrace::PrintBacktrace() {\n#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5\n if (!backtrace_symbols_fd)\n return;\n#endif\n fflush(stderr);\n backtrace_symbols_fd(trace_, count_, STDERR_FILENO);\n}\n\nvoid StackTrace::OutputToStream(std::ostream* os) {\n#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5\n if (!backtrace_symbols)\n return;\n#endif\n scoped_ptr_malloc trace_symbols(backtrace_symbols(trace_, count_));\n\n \/\/ If we can't retrieve the symbols, print an error and just dump the raw\n \/\/ addresses.\n if (trace_symbols.get() == NULL) {\n (*os) << \"Unable get symbols for backtrace (\" << strerror(errno)\n << \"). Dumping raw addresses in trace:\\n\";\n for (int i = 0; i < count_; ++i) {\n (*os) << \"\\t\" << trace_[i] << \"\\n\";\n }\n } else {\n (*os) << \"Backtrace:\\n\";\n for (int i = 0; i < count_; ++i) {\n (*os) << \"\\t\" << trace_symbols.get()[i] << \"\\n\";\n }\n }\n}\nExplicitly compare to NULL when looking for weak_import symbols.\/\/ Copyright (c) 2006-2009 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"build\/build_config.h\"\n#include \"base\/debug_util.h\"\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#if defined(OS_MACOSX)\n#include \n#endif\n\n#include \"base\/basictypes.h\"\n#include \"base\/compat_execinfo.h\"\n#include \"base\/eintr_wrapper.h\"\n#include \"base\/logging.h\"\n#include \"base\/scoped_ptr.h\"\n#include \"base\/string_piece.h\"\n\n\/\/ static\nbool DebugUtil::SpawnDebuggerOnProcess(unsigned \/* process_id *\/) {\n NOTIMPLEMENTED();\n return false;\n}\n\n#if defined(OS_MACOSX)\n\n\/\/ Based on Apple's recommended method as described in\n\/\/ http:\/\/developer.apple.com\/qa\/qa2004\/qa1361.html\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n \/\/ If the process is sandboxed then we can't use the sysctl, so cache the\n \/\/ value.\n static bool is_set = false;\n static bool being_debugged = false;\n\n if (is_set) {\n return being_debugged;\n }\n\n \/\/ Initialize mib, which tells sysctl what info we want. In this case,\n \/\/ we're looking for information about a specific process ID.\n int mib[] = {\n CTL_KERN,\n KERN_PROC,\n KERN_PROC_PID,\n getpid()\n };\n\n \/\/ Caution: struct kinfo_proc is marked __APPLE_API_UNSTABLE. The source and\n \/\/ binary interfaces may change.\n struct kinfo_proc info;\n size_t info_size = sizeof(info);\n\n int sysctl_result = sysctl(mib, arraysize(mib), &info, &info_size, NULL, 0);\n DCHECK(sysctl_result == 0);\n if (sysctl_result != 0) {\n is_set = true;\n being_debugged = false;\n return being_debugged;\n }\n\n \/\/ This process is being debugged if the P_TRACED flag is set.\n is_set = true;\n being_debugged = (info.kp_proc.p_flag & P_TRACED) != 0;\n return being_debugged;\n}\n\n#elif defined(OS_LINUX)\n\n\/\/ We can look in \/proc\/self\/status for TracerPid. We are likely used in crash\n\/\/ handling, so we are careful not to use the heap or have side effects.\n\/\/ Another option that is common is to try to ptrace yourself, but then we\n\/\/ can't detach without forking(), and that's not so great.\n\/\/ static\nbool DebugUtil::BeingDebugged() {\n int status_fd = open(\"\/proc\/self\/status\", O_RDONLY);\n if (status_fd == -1)\n return false;\n\n \/\/ We assume our line will be in the first 1024 characters and that we can\n \/\/ read this much all at once. In practice this will generally be true.\n \/\/ This simplifies and speeds up things considerably.\n char buf[1024];\n\n ssize_t num_read = HANDLE_EINTR(read(status_fd, buf, sizeof(buf)));\n HANDLE_EINTR(close(status_fd));\n\n if (num_read <= 0)\n return false;\n\n base::StringPiece status(buf, num_read);\n base::StringPiece tracer(\"TracerPid:\\t\");\n\n base::StringPiece::size_type pid_index = status.find(tracer);\n if (pid_index == base::StringPiece::npos)\n return false;\n\n \/\/ Our pid is 0 without a debugger, assume this for any pid starting with 0.\n pid_index += tracer.size();\n return pid_index < status.size() && status[pid_index] != '0';\n}\n\n#endif \/\/ OS_LINUX\n\n\/\/ static\nvoid DebugUtil::BreakDebugger() {\n#if defined(ARCH_CPU_ARM_FAMILY)\n asm(\"bkpt 0\");\n#else\n asm(\"int3\");\n#endif\n}\n\nStackTrace::StackTrace() {\n#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5\n if (backtrace == NULL) {\n count_ = 0;\n return;\n }\n#endif\n \/\/ Though the backtrace API man page does not list any possible negative\n \/\/ return values, we take no chance.\n count_ = std::max(backtrace(trace_, arraysize(trace_)), 0);\n}\n\nvoid StackTrace::PrintBacktrace() {\n#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5\n if (backtrace_symbols_fd == NULL)\n return;\n#endif\n fflush(stderr);\n backtrace_symbols_fd(trace_, count_, STDERR_FILENO);\n}\n\nvoid StackTrace::OutputToStream(std::ostream* os) {\n#if defined(OS_MACOSX) && MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5\n if (backtrace_symbols == NULL)\n return;\n#endif\n scoped_ptr_malloc trace_symbols(backtrace_symbols(trace_, count_));\n\n \/\/ If we can't retrieve the symbols, print an error and just dump the raw\n \/\/ addresses.\n if (trace_symbols.get() == NULL) {\n (*os) << \"Unable get symbols for backtrace (\" << strerror(errno)\n << \"). Dumping raw addresses in trace:\\n\";\n for (int i = 0; i < count_; ++i) {\n (*os) << \"\\t\" << trace_[i] << \"\\n\";\n }\n } else {\n (*os) << \"Backtrace:\\n\";\n for (int i = 0; i < count_; ++i) {\n (*os) << \"\\t\" << trace_symbols.get()[i] << \"\\n\";\n }\n }\n}\n<|endoftext|>"} {"text":"\/*\n * Copyright 2015 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ This is heavily inspired by the signal handler from google-glog\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace folly { namespace symbolizer {\n\nnamespace {\n\n\/**\n * Fatal signal handler registry.\n *\/\nclass FatalSignalCallbackRegistry {\n public:\n FatalSignalCallbackRegistry();\n\n void add(SignalCallback func);\n void markInstalled();\n void run();\n\n private:\n std::atomic installed_;\n std::mutex mutex_;\n std::vector handlers_;\n};\n\nFatalSignalCallbackRegistry::FatalSignalCallbackRegistry()\n : installed_(false) {\n}\n\nvoid FatalSignalCallbackRegistry::add(SignalCallback func) {\n std::lock_guard lock(mutex_);\n CHECK(!installed_)\n << \"FatalSignalCallbackRegistry::add may not be used \"\n \"after installing the signal handlers.\";\n handlers_.push_back(func);\n}\n\nvoid FatalSignalCallbackRegistry::markInstalled() {\n std::lock_guard lock(mutex_);\n CHECK(!installed_.exchange(true))\n << \"FatalSignalCallbackRegistry::markInstalled must be called \"\n << \"at most once\";\n}\n\nvoid FatalSignalCallbackRegistry::run() {\n if (!installed_) {\n return;\n }\n\n for (auto& fn : handlers_) {\n fn();\n }\n}\n\n\/\/ Leak it so we don't have to worry about destruction order\nFatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =\n new FatalSignalCallbackRegistry;\n\nstruct {\n int number;\n const char* name;\n struct sigaction oldAction;\n} kFatalSignals[] = {\n { SIGSEGV, \"SIGSEGV\" },\n { SIGILL, \"SIGILL\" },\n { SIGFPE, \"SIGFPE\" },\n { SIGABRT, \"SIGABRT\" },\n { SIGBUS, \"SIGBUS\" },\n { SIGTERM, \"SIGTERM\" },\n { 0, nullptr }\n};\n\nvoid callPreviousSignalHandler(int signum) {\n \/\/ Restore disposition to old disposition, then kill ourselves with the same\n \/\/ signal. The signal will be blocked until we return from our handler,\n \/\/ then it will invoke the default handler and abort.\n for (auto p = kFatalSignals; p->name; ++p) {\n if (p->number == signum) {\n sigaction(signum, &p->oldAction, nullptr);\n raise(signum);\n return;\n }\n }\n\n \/\/ Not one of the signals we know about. Oh well. Reset to default.\n struct sigaction sa;\n memset(&sa, 0, sizeof(sa));\n sa.sa_handler = SIG_DFL;\n sigaction(signum, &sa, nullptr);\n raise(signum);\n}\n\nconstexpr size_t kDefaultCapacity = 500;\n\n\/\/ Note: not thread-safe, but that's okay, as we only let one thread\n\/\/ in our signal handler at a time.\n\/\/\n\/\/ Leak it so we don't have to worry about destruction order\nauto gSignalSafeElfCache = new SignalSafeElfCache(kDefaultCapacity);\n\n\/\/ Buffered writer (using a fixed-size buffer). We try to write only once\n\/\/ to prevent interleaving with messages written from other threads.\n\/\/\n\/\/ Leak it so we don't have to worry about destruction order.\nauto gPrinter = new FDSymbolizePrinter(STDERR_FILENO,\n SymbolizePrinter::COLOR_IF_TTY,\n size_t(64) << 10); \/\/ 64KiB\n\n\/\/ Flush gPrinter, also fsync, in case we're about to crash again...\nvoid flush() {\n gPrinter->flush();\n fsyncNoInt(STDERR_FILENO);\n}\n\nvoid printDec(uint64_t val) {\n char buf[20];\n uint32_t n = uint64ToBufferUnsafe(val, buf);\n gPrinter->print(StringPiece(buf, n));\n}\n\nconst char kHexChars[] = \"0123456789abcdef\";\nvoid printHex(uint64_t val) {\n \/\/ TODO(tudorb): Add this to folly\/Conv.h\n char buf[2 + 2 * sizeof(uint64_t)]; \/\/ \"0x\" prefix, 2 digits for each byte\n\n char* end = buf + sizeof(buf);\n char* p = end;\n do {\n *--p = kHexChars[val & 0x0f];\n val >>= 4;\n } while (val != 0);\n *--p = 'x';\n *--p = '0';\n\n gPrinter->print(StringPiece(p, end));\n}\n\nvoid print(StringPiece sp) {\n gPrinter->print(sp);\n}\n\nvoid dumpTimeInfo() {\n SCOPE_EXIT { flush(); };\n time_t now = time(nullptr);\n print(\"*** Aborted at \");\n printDec(now);\n print(\" (Unix time, try 'date -d @\");\n printDec(now);\n print(\"') ***\\n\");\n}\n\nvoid dumpSignalInfo(int signum, siginfo_t* siginfo) {\n SCOPE_EXIT { flush(); };\n \/\/ Get the signal name, if possible.\n const char* name = nullptr;\n for (auto p = kFatalSignals; p->name; ++p) {\n if (p->number == signum) {\n name = p->name;\n break;\n }\n }\n\n print(\"*** Signal \");\n printDec(signum);\n if (name) {\n print(\" (\");\n print(name);\n print(\")\");\n }\n\n print(\" (\");\n printHex(reinterpret_cast(siginfo->si_addr));\n print(\") received by PID \");\n printDec(getpid());\n print(\" (pthread TID \");\n printHex((uint64_t)pthread_self());\n print(\") (linux TID \");\n printDec(syscall(__NR_gettid));\n print(\"), stack trace: ***\\n\");\n}\n\nFOLLY_NOINLINE void dumpStackTrace(bool symbolize);\n\nvoid dumpStackTrace(bool symbolize) {\n SCOPE_EXIT { flush(); };\n \/\/ Get and symbolize stack trace\n constexpr size_t kMaxStackTraceDepth = 100;\n FrameArray addresses;\n\n \/\/ Skip the getStackTrace frame\n if (!getStackTraceSafe(addresses)) {\n print(\"(error retrieving stack trace)\\n\");\n } else if (symbolize) {\n Symbolizer symbolizer(gSignalSafeElfCache);\n symbolizer.symbolize(addresses);\n\n \/\/ Skip the top 2 frames:\n \/\/ getStackTraceSafe\n \/\/ dumpStackTrace (here)\n \/\/\n \/\/ Leaving signalHandler on the stack for clarity, I think.\n gPrinter->println(addresses, 2);\n } else {\n print(\"(safe mode, symbolizer not available)\\n\");\n AddressFormatter formatter;\n for (size_t i = 0; i < addresses.frameCount; ++i) {\n print(formatter.format(addresses.addresses[i]));\n print(\"\\n\");\n }\n }\n}\n\n\/\/ On Linux, pthread_t is a pointer, so 0 is an invalid value, which we\n\/\/ take to indicate \"no thread in the signal handler\".\n\/\/\n\/\/ POSIX defines PTHREAD_NULL for this purpose, but that's not available.\nconstexpr pthread_t kInvalidThreadId = 0;\n\nstd::atomic gSignalThread(kInvalidThreadId);\nstd::atomic gInRecursiveSignalHandler(false);\n\n\/\/ Here be dragons.\nvoid innerSignalHandler(int signum, siginfo_t* info, void* uctx) {\n \/\/ First, let's only let one thread in here at a time.\n pthread_t myId = pthread_self();\n\n pthread_t prevSignalThread = kInvalidThreadId;\n while (!gSignalThread.compare_exchange_strong(prevSignalThread, myId)) {\n if (pthread_equal(prevSignalThread, myId)) {\n \/\/ First time here. Try to dump the stack trace without symbolization.\n \/\/ If we still fail, well, we're mightily screwed, so we do nothing the\n \/\/ next time around.\n if (!gInRecursiveSignalHandler.exchange(true)) {\n print(\"Entered fatal signal handler recursively. We're in trouble.\\n\");\n dumpStackTrace(false); \/\/ no symbolization\n }\n return;\n }\n\n \/\/ Wait a while, try again.\n timespec ts;\n ts.tv_sec = 0;\n ts.tv_nsec = 100L * 1000 * 1000; \/\/ 100ms\n nanosleep(&ts, nullptr);\n\n prevSignalThread = kInvalidThreadId;\n }\n\n dumpTimeInfo();\n dumpSignalInfo(signum, info);\n dumpStackTrace(true); \/\/ with symbolization\n\n \/\/ Run user callbacks\n gFatalSignalCallbackRegistry->run();\n}\n\nvoid signalHandler(int signum, siginfo_t* info, void* uctx) {\n SCOPE_EXIT { flush(); };\n innerSignalHandler(signum, info, uctx);\n\n gSignalThread = kInvalidThreadId;\n \/\/ Kill ourselves with the previous handler.\n callPreviousSignalHandler(signum);\n}\n\n} \/\/ namespace\n\nvoid addFatalSignalCallback(SignalCallback cb) {\n gFatalSignalCallbackRegistry->add(cb);\n}\n\nvoid installFatalSignalCallbacks() {\n gFatalSignalCallbackRegistry->markInstalled();\n}\n\nnamespace {\n\nstd::atomic gAlreadyInstalled;\n\n} \/\/ namespace\n\nvoid installFatalSignalHandler() {\n if (gAlreadyInstalled.exchange(true)) {\n \/\/ Already done.\n return;\n }\n\n struct sigaction sa;\n memset(&sa, 0, sizeof(sa));\n sigemptyset(&sa.sa_mask);\n \/\/ By default signal handlers are run on the signaled thread's stack.\n \/\/ In case of stack overflow running the SIGSEGV signal handler on\n \/\/ the same stack leads to another SIGSEGV and crashes the program.\n \/\/ Use SA_ONSTACK, so alternate stack is used (only if configured via\n \/\/ sigaltstack).\n sa.sa_flags |= SA_SIGINFO | SA_ONSTACK;\n sa.sa_sigaction = &signalHandler;\n\n for (auto p = kFatalSignals; p->name; ++p) {\n CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));\n }\n}\n\n}} \/\/ namespaces\nLog pid\/uid of sending process in signal handler, too\/*\n * Copyright 2015 Facebook, Inc.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n\/\/ This is heavily inspired by the signal handler from google-glog\n\n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n#include \n#include \n#include \n#include \n#include \n\nnamespace folly { namespace symbolizer {\n\nnamespace {\n\n\/**\n * Fatal signal handler registry.\n *\/\nclass FatalSignalCallbackRegistry {\n public:\n FatalSignalCallbackRegistry();\n\n void add(SignalCallback func);\n void markInstalled();\n void run();\n\n private:\n std::atomic installed_;\n std::mutex mutex_;\n std::vector handlers_;\n};\n\nFatalSignalCallbackRegistry::FatalSignalCallbackRegistry()\n : installed_(false) {\n}\n\nvoid FatalSignalCallbackRegistry::add(SignalCallback func) {\n std::lock_guard lock(mutex_);\n CHECK(!installed_)\n << \"FatalSignalCallbackRegistry::add may not be used \"\n \"after installing the signal handlers.\";\n handlers_.push_back(func);\n}\n\nvoid FatalSignalCallbackRegistry::markInstalled() {\n std::lock_guard lock(mutex_);\n CHECK(!installed_.exchange(true))\n << \"FatalSignalCallbackRegistry::markInstalled must be called \"\n << \"at most once\";\n}\n\nvoid FatalSignalCallbackRegistry::run() {\n if (!installed_) {\n return;\n }\n\n for (auto& fn : handlers_) {\n fn();\n }\n}\n\n\/\/ Leak it so we don't have to worry about destruction order\nFatalSignalCallbackRegistry* gFatalSignalCallbackRegistry =\n new FatalSignalCallbackRegistry;\n\nstruct {\n int number;\n const char* name;\n struct sigaction oldAction;\n} kFatalSignals[] = {\n { SIGSEGV, \"SIGSEGV\" },\n { SIGILL, \"SIGILL\" },\n { SIGFPE, \"SIGFPE\" },\n { SIGABRT, \"SIGABRT\" },\n { SIGBUS, \"SIGBUS\" },\n { SIGTERM, \"SIGTERM\" },\n { 0, nullptr }\n};\n\nvoid callPreviousSignalHandler(int signum) {\n \/\/ Restore disposition to old disposition, then kill ourselves with the same\n \/\/ signal. The signal will be blocked until we return from our handler,\n \/\/ then it will invoke the default handler and abort.\n for (auto p = kFatalSignals; p->name; ++p) {\n if (p->number == signum) {\n sigaction(signum, &p->oldAction, nullptr);\n raise(signum);\n return;\n }\n }\n\n \/\/ Not one of the signals we know about. Oh well. Reset to default.\n struct sigaction sa;\n memset(&sa, 0, sizeof(sa));\n sa.sa_handler = SIG_DFL;\n sigaction(signum, &sa, nullptr);\n raise(signum);\n}\n\nconstexpr size_t kDefaultCapacity = 500;\n\n\/\/ Note: not thread-safe, but that's okay, as we only let one thread\n\/\/ in our signal handler at a time.\n\/\/\n\/\/ Leak it so we don't have to worry about destruction order\nauto gSignalSafeElfCache = new SignalSafeElfCache(kDefaultCapacity);\n\n\/\/ Buffered writer (using a fixed-size buffer). We try to write only once\n\/\/ to prevent interleaving with messages written from other threads.\n\/\/\n\/\/ Leak it so we don't have to worry about destruction order.\nauto gPrinter = new FDSymbolizePrinter(STDERR_FILENO,\n SymbolizePrinter::COLOR_IF_TTY,\n size_t(64) << 10); \/\/ 64KiB\n\n\/\/ Flush gPrinter, also fsync, in case we're about to crash again...\nvoid flush() {\n gPrinter->flush();\n fsyncNoInt(STDERR_FILENO);\n}\n\nvoid printDec(uint64_t val) {\n char buf[20];\n uint32_t n = uint64ToBufferUnsafe(val, buf);\n gPrinter->print(StringPiece(buf, n));\n}\n\nconst char kHexChars[] = \"0123456789abcdef\";\nvoid printHex(uint64_t val) {\n \/\/ TODO(tudorb): Add this to folly\/Conv.h\n char buf[2 + 2 * sizeof(uint64_t)]; \/\/ \"0x\" prefix, 2 digits for each byte\n\n char* end = buf + sizeof(buf);\n char* p = end;\n do {\n *--p = kHexChars[val & 0x0f];\n val >>= 4;\n } while (val != 0);\n *--p = 'x';\n *--p = '0';\n\n gPrinter->print(StringPiece(p, end));\n}\n\nvoid print(StringPiece sp) {\n gPrinter->print(sp);\n}\n\nvoid dumpTimeInfo() {\n SCOPE_EXIT { flush(); };\n time_t now = time(nullptr);\n print(\"*** Aborted at \");\n printDec(now);\n print(\" (Unix time, try 'date -d @\");\n printDec(now);\n print(\"') ***\\n\");\n}\n\nconst char* sigill_reason(int si_code) {\n switch (si_code) {\n case ILL_ILLOPC:\n return \"illegal opcode\";\n case ILL_ILLOPN:\n return \"illegal operand\";\n case ILL_ILLADR:\n return \"illegal addressing mode\";\n case ILL_ILLTRP:\n return \"illegal trap\";\n case ILL_PRVOPC:\n return \"privileged opcode\";\n case ILL_PRVREG:\n return \"privileged register\";\n case ILL_COPROC:\n return \"coprocessor error\";\n case ILL_BADSTK:\n return \"internal stack error\";\n\n default:\n return nullptr;\n }\n}\n\nconst char* sigfpe_reason(int si_code) {\n switch (si_code) {\n case FPE_INTDIV:\n return \"integer divide by zero\";\n case FPE_INTOVF:\n return \"integer overflow\";\n case FPE_FLTDIV:\n return \"floating-point divide by zero\";\n case FPE_FLTOVF:\n return \"floating-point overflow\";\n case FPE_FLTUND:\n return \"floating-point underflow\";\n case FPE_FLTRES:\n return \"floating-point inexact result\";\n case FPE_FLTINV:\n return \"floating-point invalid operation\";\n case FPE_FLTSUB:\n return \"subscript out of range\";\n\n default:\n return nullptr;\n }\n}\n\nconst char* sigsegv_reason(int si_code) {\n switch (si_code) {\n case SEGV_MAPERR:\n return \"address not mapped to object\";\n case SEGV_ACCERR:\n return \"invalid permissions for mapped object\";\n\n default:\n return nullptr;\n }\n}\n\nconst char* sigbus_reason(int si_code) {\n switch (si_code) {\n case BUS_ADRALN:\n return \"invalid address alignment\";\n case BUS_ADRERR:\n return \"nonexistent physical address\";\n case BUS_OBJERR:\n return \"object-specific hardware error\";\n\n \/\/ MCEERR_AR and MCEERR_AO: in sigaction(2) but not in headers.\n\n default:\n return nullptr;\n }\n}\n\nconst char* sigtrap_reason(int si_code) {\n switch (si_code) {\n case TRAP_BRKPT:\n return \"process breakpoint\";\n case TRAP_TRACE:\n return \"process trace trap\";\n\n \/\/ TRAP_BRANCH and TRAP_HWBKPT: in sigaction(2) but not in headers.\n\n default:\n return nullptr;\n }\n}\n\nconst char* sigchld_reason(int si_code) {\n switch (si_code) {\n case CLD_EXITED:\n return \"child has exited\";\n case CLD_KILLED:\n return \"child was killed\";\n case CLD_DUMPED:\n return \"child terminated abnormally\";\n case CLD_TRAPPED:\n return \"traced child has trapped\";\n case CLD_STOPPED:\n return \"child has stopped\";\n case CLD_CONTINUED:\n return \"stopped child has continued\";\n\n default:\n return nullptr;\n }\n}\n\nconst char* sigio_reason(int si_code) {\n switch (si_code) {\n case POLL_IN:\n return \"data input available\";\n case POLL_OUT:\n return \"output buffers available\";\n case POLL_MSG:\n return \"input message available\";\n case POLL_ERR:\n return \"I\/O error\";\n case POLL_PRI:\n return \"high priority input available\";\n case POLL_HUP:\n return \"device disconnected\";\n\n default:\n return nullptr;\n }\n}\n\nconst char* signal_reason(int signum, int si_code) {\n switch (signum) {\n case SIGILL:\n return sigill_reason(si_code);\n case SIGFPE:\n return sigfpe_reason(si_code);\n case SIGSEGV:\n return sigsegv_reason(si_code);\n case SIGBUS:\n return sigbus_reason(si_code);\n case SIGTRAP:\n return sigtrap_reason(si_code);\n case SIGCHLD:\n return sigchld_reason(si_code);\n case SIGIO:\n return sigio_reason(si_code); \/\/ aka SIGPOLL\n\n default:\n return nullptr;\n }\n}\n\nvoid dumpSignalInfo(int signum, siginfo_t* siginfo) {\n SCOPE_EXIT { flush(); };\n \/\/ Get the signal name, if possible.\n const char* name = nullptr;\n for (auto p = kFatalSignals; p->name; ++p) {\n if (p->number == signum) {\n name = p->name;\n break;\n }\n }\n\n print(\"*** Signal \");\n printDec(signum);\n if (name) {\n print(\" (\");\n print(name);\n print(\")\");\n }\n\n print(\" (\");\n printHex(reinterpret_cast(siginfo->si_addr));\n print(\") received by PID \");\n printDec(getpid());\n print(\" (pthread TID \");\n printHex((uint64_t)pthread_self());\n print(\") (linux TID \");\n printDec(syscall(__NR_gettid));\n\n \/\/ Kernel-sourced signals don't give us useful info for pid\/uid.\n if (siginfo->si_code != SI_KERNEL) {\n print(\") (maybe from PID \");\n printDec(siginfo->si_pid);\n print(\", UID \");\n printDec(siginfo->si_uid);\n }\n\n auto reason = signal_reason(signum, siginfo->si_code);\n\n if (reason != nullptr) {\n print(\") (code: \");\n print(reason);\n }\n\n print(\"), stack trace: ***\\n\");\n}\n\nFOLLY_NOINLINE void dumpStackTrace(bool symbolize);\n\nvoid dumpStackTrace(bool symbolize) {\n SCOPE_EXIT { flush(); };\n \/\/ Get and symbolize stack trace\n constexpr size_t kMaxStackTraceDepth = 100;\n FrameArray addresses;\n\n \/\/ Skip the getStackTrace frame\n if (!getStackTraceSafe(addresses)) {\n print(\"(error retrieving stack trace)\\n\");\n } else if (symbolize) {\n Symbolizer symbolizer(gSignalSafeElfCache);\n symbolizer.symbolize(addresses);\n\n \/\/ Skip the top 2 frames:\n \/\/ getStackTraceSafe\n \/\/ dumpStackTrace (here)\n \/\/\n \/\/ Leaving signalHandler on the stack for clarity, I think.\n gPrinter->println(addresses, 2);\n } else {\n print(\"(safe mode, symbolizer not available)\\n\");\n AddressFormatter formatter;\n for (size_t i = 0; i < addresses.frameCount; ++i) {\n print(formatter.format(addresses.addresses[i]));\n print(\"\\n\");\n }\n }\n}\n\n\/\/ On Linux, pthread_t is a pointer, so 0 is an invalid value, which we\n\/\/ take to indicate \"no thread in the signal handler\".\n\/\/\n\/\/ POSIX defines PTHREAD_NULL for this purpose, but that's not available.\nconstexpr pthread_t kInvalidThreadId = 0;\n\nstd::atomic gSignalThread(kInvalidThreadId);\nstd::atomic gInRecursiveSignalHandler(false);\n\n\/\/ Here be dragons.\nvoid innerSignalHandler(int signum, siginfo_t* info, void* uctx) {\n \/\/ First, let's only let one thread in here at a time.\n pthread_t myId = pthread_self();\n\n pthread_t prevSignalThread = kInvalidThreadId;\n while (!gSignalThread.compare_exchange_strong(prevSignalThread, myId)) {\n if (pthread_equal(prevSignalThread, myId)) {\n \/\/ First time here. Try to dump the stack trace without symbolization.\n \/\/ If we still fail, well, we're mightily screwed, so we do nothing the\n \/\/ next time around.\n if (!gInRecursiveSignalHandler.exchange(true)) {\n print(\"Entered fatal signal handler recursively. We're in trouble.\\n\");\n dumpStackTrace(false); \/\/ no symbolization\n }\n return;\n }\n\n \/\/ Wait a while, try again.\n timespec ts;\n ts.tv_sec = 0;\n ts.tv_nsec = 100L * 1000 * 1000; \/\/ 100ms\n nanosleep(&ts, nullptr);\n\n prevSignalThread = kInvalidThreadId;\n }\n\n dumpTimeInfo();\n dumpSignalInfo(signum, info);\n dumpStackTrace(true); \/\/ with symbolization\n\n \/\/ Run user callbacks\n gFatalSignalCallbackRegistry->run();\n}\n\nvoid signalHandler(int signum, siginfo_t* info, void* uctx) {\n SCOPE_EXIT { flush(); };\n innerSignalHandler(signum, info, uctx);\n\n gSignalThread = kInvalidThreadId;\n \/\/ Kill ourselves with the previous handler.\n callPreviousSignalHandler(signum);\n}\n\n} \/\/ namespace\n\nvoid addFatalSignalCallback(SignalCallback cb) {\n gFatalSignalCallbackRegistry->add(cb);\n}\n\nvoid installFatalSignalCallbacks() {\n gFatalSignalCallbackRegistry->markInstalled();\n}\n\nnamespace {\n\nstd::atomic gAlreadyInstalled;\n\n} \/\/ namespace\n\nvoid installFatalSignalHandler() {\n if (gAlreadyInstalled.exchange(true)) {\n \/\/ Already done.\n return;\n }\n\n struct sigaction sa;\n memset(&sa, 0, sizeof(sa));\n sigemptyset(&sa.sa_mask);\n \/\/ By default signal handlers are run on the signaled thread's stack.\n \/\/ In case of stack overflow running the SIGSEGV signal handler on\n \/\/ the same stack leads to another SIGSEGV and crashes the program.\n \/\/ Use SA_ONSTACK, so alternate stack is used (only if configured via\n \/\/ sigaltstack).\n sa.sa_flags |= SA_SIGINFO | SA_ONSTACK;\n sa.sa_sigaction = &signalHandler;\n\n for (auto p = kFatalSignals; p->name; ++p) {\n CHECK_ERR(sigaction(p->number, &sa, &p->oldAction));\n }\n}\n\n}} \/\/ namespaces\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n\nstatic llvm::LLVMContext &Context = llvm::getGlobalContext();\nstatic llvm::Module *ModuleOb = new llvm::Module(\"my compiler\", Context);\n\nllvm::Function *createFunc(llvm::IRBuilder<> &Builder, std::string Name)\n{\n llvm::FunctionType *funcTy = llvm::FunctionType::get(Builder.getInt32Ty(), false);\n llvm::Function *fooFunc = llvm::Function::Create(\n funcTy, llvm::Function::ExternalLinkage, Name, ModuleOb);\n return fooFunc;\n}\n\nllvm::GlobalVariable *createGlob(llvm::IRBuilder<> &Builder, std::string Name) {\n ModuleOb->getOrInsertGlobal(Name, Builder.getInt32Ty());\n llvm::GlobalVariable *gVar = ModuleOb->getNamedGlobal(Name);\n gVar->setLinkage(llvm::GlobalValue::CommonLinkage);\n gVar->setAlignment(4);\n return gVar;\n}\n\nllvm::BasicBlock *createBB(llvm::Function *fooFunc, std::string Name)\n{\n return llvm::BasicBlock::Create(Context, Name, fooFunc);\n}\n\n\nint main(int argc, char *argv[]) {\n static llvm::IRBuilder<> Builder(Context);\n\n llvm::GlobalVariable *gVar = createGlob(Builder, \"x\");\n\n llvm::Function *fooFunc = createFunc(Builder, \"foo\");\n\n llvm::BasicBlock* entry = createBB(fooFunc, \"entry\");\n Builder.SetInsertPoint(entry);\n\n llvm::verifyFunction(*fooFunc);\n ModuleOb->dump();\n return 0;\n}\nemit return#include \n#include \n#include \n#include \n#include \n#include \n\nstatic llvm::LLVMContext &Context = llvm::getGlobalContext();\nstatic llvm::Module *ModuleOb = new llvm::Module(\"my compiler\", Context);\n\nllvm::Function *createFunc(llvm::IRBuilder<> &Builder, std::string Name)\n{\n llvm::FunctionType *funcTy = llvm::FunctionType::get(Builder.getInt32Ty(), false);\n llvm::Function *fooFunc = llvm::Function::Create(\n funcTy, llvm::Function::ExternalLinkage, Name, ModuleOb);\n return fooFunc;\n}\n\nllvm::GlobalVariable *createGlob(llvm::IRBuilder<> &Builder, std::string Name) {\n ModuleOb->getOrInsertGlobal(Name, Builder.getInt32Ty());\n llvm::GlobalVariable *gVar = ModuleOb->getNamedGlobal(Name);\n gVar->setLinkage(llvm::GlobalValue::CommonLinkage);\n gVar->setAlignment(4);\n return gVar;\n}\n\nllvm::BasicBlock *createBB(llvm::Function *fooFunc, std::string Name)\n{\n return llvm::BasicBlock::Create(Context, Name, fooFunc);\n}\n\n\nint main(int argc, char *argv[]) {\n static llvm::IRBuilder<> Builder(Context);\n\n llvm::GlobalVariable *gVar = createGlob(Builder, \"x\");\n\n llvm::Function *fooFunc = createFunc(Builder, \"foo\");\n\n llvm::BasicBlock* entry = createBB(fooFunc, \"entry\");\n Builder.SetInsertPoint(entry);\n\n \/\/Builder.CreateRet(Builder.getInt32(0));\n Builder.CreateRet(gVar);\n\n llvm::verifyFunction(*fooFunc);\n ModuleOb->dump();\n return 0;\n}\n<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n#include \n\nnamespace multi_iter {\n#ifdef __cpp_concepts\ntemplate \nconcept bool ForwardIterator = requires(T it) {\n {*it};\n {++it};\n {it == it}\n};\n\ntemplate \nconcept bool ForwardIterable = ForwardIterator()))>\n && ForwardIterator()))>;\n\n#define IS_ITERABLE(T) ForwardIterable T\n\n#else\n \/\/TODO do some enable_if\n#define IS_ITERABLE(T) typename T\n#endif\n\ntemplate \nclass multi_iterator {\n\ttemplate \n\tusing start_iterator = decltype (std::begin(std::declval()));\n\n\ttemplate \n\tusing end_iterator = decltype (std::end(std::declval()));\n\n\ttemplate \n\tusing iterator_pair = std::pair, end_iterator>;\n\npublic:\n\tusing iterators = std::tuple...>;\n\n template \n explicit multi_iterator(T&& t)\n :_data{std::forward(t)}\n {\n }\n bool is_done() const noexcept {\n return std::get<0>(this->_data).first == std::get<0>(this->_data).second;\n }\n\n auto& operator++() {\n this->increment(std::make_index_sequence());\n return *this;\n }\n auto operator*() {\n return this->deref(std::make_index_sequence());\n }\n\n friend bool operator != (const multi_iterator& pthis, const multi_iterator& \/*sentinel*\/) noexcept {\n return !pthis.is_done();\n }\nprivate:\n template \n void increment(std::index_sequence) {\n std::initializer_list{(++std::get(this->_data).first, 0) ...};\n }\n\n template \n auto deref(std::index_sequence) {\n return std::make_tuple(std::ref(*std::get(this->_data).first) ...);\n }\n template \n auto deref(std::index_sequence) const {\n return std::make_tuple(std::cref(*std::get(this->_data).first) ...);\n }\n\nprivate:\n iterators _data;\n};\n\ntemplate <>\nclass multi_iterator {\n};\n\ntemplate \nclass multi_adapter {\npublic:\n template \n explicit multi_adapter(T&& ... t)\n :_data{{std::begin(t), std::end(t)} ...}\n {\n }\n auto begin() {\n return multi_iterator(this->_data);\n }\n auto end() {\n return multi_iterator();\n }\nprivate:\n typename multi_iterator::iterators _data;\n};\n\ntemplate \nauto get_size(C&& c, Args&& ...) {\n return std::size(c);\n}\n\n\/**\n TODO:\n - allow different container sizes with user-defined fallback values\n*\/\ntemplate \nauto iterate(Args && ... args) {\n const auto size = get_size(std::forward(args) ...);\n if (((get_size(args) != size) || ...)) {\n throw std::runtime_error(\"cannot multi-iterate containers of different sizes\");\n }\n return multi_adapter(std::forward(args)...);\n}\n\n} \/\/ namespace\n\nspecify return types for iterator ops#pragma once\n\n#include \n#include \n#include \n\nnamespace multi_iter {\n#ifdef __cpp_concepts\ntemplate \nconcept bool ForwardIterator = requires(T it) {\n {*it};\n {++it} -> T;\n {it == it} -> bool\n};\n\ntemplate \nconcept bool ForwardIterable = ForwardIterator()))>\n && ForwardIterator()))>;\n\n#define IS_ITERABLE(T) ForwardIterable T\n\n#else\n \/\/TODO do some enable_if\n#define IS_ITERABLE(T) typename T\n#endif\n\ntemplate \nclass multi_iterator {\n\ttemplate \n\tusing start_iterator = decltype (std::begin(std::declval()));\n\n\ttemplate \n\tusing end_iterator = decltype (std::end(std::declval()));\n\n\ttemplate \n\tusing iterator_pair = std::pair, end_iterator>;\n\npublic:\n\tusing iterators = std::tuple...>;\n\n template \n explicit multi_iterator(T&& t)\n :_data{std::forward(t)}\n {\n }\n bool is_done() const noexcept {\n return std::get<0>(this->_data).first == std::get<0>(this->_data).second;\n }\n\n auto& operator++() {\n this->increment(std::make_index_sequence());\n return *this;\n }\n auto operator*() {\n return this->deref(std::make_index_sequence());\n }\n\n friend bool operator != (const multi_iterator& pthis, const multi_iterator& \/*sentinel*\/) noexcept {\n return !pthis.is_done();\n }\nprivate:\n template \n void increment(std::index_sequence) {\n std::initializer_list{(++std::get(this->_data).first, 0) ...};\n }\n\n template \n auto deref(std::index_sequence) {\n return std::make_tuple(std::ref(*std::get(this->_data).first) ...);\n }\n template \n auto deref(std::index_sequence) const {\n return std::make_tuple(std::cref(*std::get(this->_data).first) ...);\n }\n\nprivate:\n iterators _data;\n};\n\ntemplate <>\nclass multi_iterator {\n};\n\ntemplate \nclass multi_adapter {\npublic:\n template \n explicit multi_adapter(T&& ... t)\n :_data{{std::begin(t), std::end(t)} ...}\n {\n }\n auto begin() {\n return multi_iterator(this->_data);\n }\n auto end() {\n return multi_iterator();\n }\nprivate:\n typename multi_iterator::iterators _data;\n};\n\ntemplate \nauto get_size(C&& c, Args&& ...) {\n return std::size(c);\n}\n\n\/**\n TODO:\n - allow different container sizes with user-defined fallback values\n*\/\ntemplate \nauto iterate(Args && ... args) {\n const auto size = get_size(std::forward(args) ...);\n if (((get_size(args) != size) || ...)) {\n throw std::runtime_error(\"cannot multi-iterate containers of different sizes\");\n }\n return multi_adapter(std::forward(args)...);\n}\n\n} \/\/ namespace\n\n<|endoftext|>"} {"text":"\/\/ stack solution by hxdone\n\nclass Solution {\npublic:\n\tint romanToInt(string s) {\n\t\tmap sym_table;\n\t\tsym_table['I'] = 1;\n\t\tsym_table['V'] = 5;\n\t\tsym_table['X'] = 10;\n\t\tsym_table['L'] = 50;\n\t\tsym_table['C'] = 100;\n\t\tsym_table['D'] = 500;\n\t\tsym_table['M'] = 1000;\n\t\tstack v_stack;\n\t\tfor (int i = 0; i < s.length(); ++i) {\n\t\t\tint v = sym_table[s[i]];\n\t\t\twhile (!v_stack.empty() && v > v_stack.top()) {\n\t\t\t\tv = v-v_stack.top();\n\t\t\t\tv_stack.pop();\n\t\t\t}\n\t\t\tv_stack.push(v);\n\t\t}\n\t\tint ret = 0;\n\t\twhile (!v_stack.empty()) {\n\t\t\tret += v_stack.top();\n\t\t\tv_stack.pop();\n\t\t}\n\t\treturn ret;\n\t}\n}; \nimprove solution for leetcode\/Algorithms\/RomanToInteger\/\/ char-array hashmap and backward-summing solution by hxdone\n\nclass Solution {\npublic:\n Solution() {\n sym_table['I'] = 1;\n sym_table['V'] = 5;\n sym_table['X'] = 10;\n sym_table['L'] = 50;\n sym_table['C'] = 100;\n sym_table['D'] = 500;\n sym_table['M'] = 1000;\n }\n int romanToInt(string s) {\n int ret = 0;\n int last = 0;\n for (int i = s.length()-1; i >= 0; --i) {\n int v = sym_table[s[i]];\n if (v >= last) {\n ret += v;\n last = v;\n }\n else\n ret -= v;\n }\n return ret;\n }\nprivate:\n int sym_table[256];\n};\n<|endoftext|>"} {"text":"\/*\r\n * Copyright (c) 2015-2017 Alex Spataru \r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n * THE SOFTWARE.\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/**\r\n * Holds a generic mapping to be applied to joysticks that have not been mapped\r\n * by the SDL project or by the database.\r\n *\r\n * This mapping is different on each supported operating system.\r\n *\/\r\nstatic QString GENERIC_MAPPINGS;\r\n\r\n\/**\r\n * Load a different generic\/backup mapping for each operating system.\r\n *\/\r\n#ifdef SDL_SUPPORTED\r\n #if defined Q_OS_WIN\r\n #define GENERIC_MAPPINGS_PATH \":\/QJoysticks\/SDL\/GenericMappings\/Windows.txt\"\r\n #elif defined Q_OS_MAC\r\n #define GENERIC_MAPPINGS_PATH \":\/QJoysticks\/SDL\/GenericMappings\/OSX.txt\"\r\n #elif defined Q_OS_LINUX && !defined Q_OS_ANDROID\r\n #define GENERIC_MAPPINGS_PATH \":\/QJoysticks\/SDL\/GenericMappings\/Linux.txt\"\r\n #endif\r\n#endif\r\n\r\nSDL_Joysticks::SDL_Joysticks (QObject* parent) : QObject (parent)\r\n{\r\n m_tracker = -1;\r\n\r\n#ifdef SDL_SUPPORTED\r\n if (SDL_Init (SDL_INIT_HAPTIC | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER)) {\r\n qDebug() << \"Cannot initialize SDL:\" << SDL_GetError();\r\n qApp->quit();\r\n }\r\n\r\n QFile database (\":\/QJoysticks\/SDL\/Database.txt\");\r\n if (database.open (QFile::ReadOnly)) {\r\n while (!database.atEnd()) {\r\n QString line = QString::fromUtf8 (database.readLine());\r\n SDL_GameControllerAddMapping (line.toStdString().c_str());\r\n }\r\n\r\n database.close();\r\n }\r\n\r\n QFile genericMappings (GENERIC_MAPPINGS_PATH);\r\n if (genericMappings.open (QFile::ReadOnly)) {\r\n GENERIC_MAPPINGS = QString::fromUtf8 (genericMappings.readAll());\r\n genericMappings.close();\r\n }\r\n\r\n QTimer::singleShot (100, Qt::PreciseTimer, this, &SDL_Joysticks::update);\r\n#endif\r\n}\r\n\r\nSDL_Joysticks::~SDL_Joysticks()\r\n{\r\n#ifdef SDL_SUPPORTED\r\n SDL_Quit();\r\n#endif\r\n}\r\n\r\n\/**\r\n * Returns a list with all the registered joystick devices\r\n *\/\r\nQList SDL_Joysticks::joysticks()\r\n{\r\n QList list;\r\n\r\n#ifdef SDL_SUPPORTED\r\n for (int i = 0; i < SDL_NumJoysticks(); ++i)\r\n list.append (getJoystick (i));\r\n#endif\r\n\r\n return list;\r\n}\r\n\r\n\/**\r\n * Based on the data contained in the \\a request, this function will instruct\r\n * the appropriate joystick to rumble for\r\n *\/\r\nvoid SDL_Joysticks::rumble (const QJoystickRumble& request)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n SDL_Haptic* haptic = SDL_HapticOpen (request.joystick->id);\r\n\r\n if (haptic) {\r\n SDL_HapticRumbleInit (haptic);\r\n SDL_HapticRumblePlay (haptic, request.strength, request.length);\r\n }\r\n#else\r\n Q_UNUSED (request);\r\n#endif\r\n}\r\n\r\n\/**\r\n * Polls for new SDL events and reacts to each event accordingly.\r\n *\/\r\nvoid SDL_Joysticks::update()\r\n{\r\n#ifdef SDL_SUPPORTED\r\n SDL_Event event;\r\n\r\n while (SDL_PollEvent (&event)) {\r\n switch (event.type) {\r\n case SDL_JOYDEVICEADDED:\r\n configureJoystick (&event);\r\n break;\r\n case SDL_JOYDEVICEREMOVED:\r\n SDL_JoystickClose (SDL_JoystickOpen (event.jdevice.which));\r\n SDL_GameControllerClose (SDL_GameControllerOpen (event.cdevice.which));\r\n emit countChanged();\r\n break;\r\n case SDL_CONTROLLERAXISMOTION:\r\n emit axisEvent (getAxisEvent (&event));\r\n break;\r\n case SDL_JOYBUTTONUP:\r\n emit buttonEvent (getButtonEvent (&event));\r\n break;\r\n case SDL_JOYBUTTONDOWN:\r\n emit buttonEvent (getButtonEvent (&event));\r\n break;\r\n case SDL_JOYHATMOTION:\r\n emit POVEvent (getPOVEvent (&event));\r\n break;\r\n }\r\n }\r\n\r\n QTimer::singleShot (10, Qt::PreciseTimer, this, &SDL_Joysticks::update);\r\n#endif\r\n}\r\n\r\n\/**\r\n * Checks if the joystick referenced by the \\a event can be initialized.\r\n * If not, the function will apply a generic mapping to the joystick and\r\n * attempt to initialize the joystick again.\r\n *\/\r\nvoid SDL_Joysticks::configureJoystick (const SDL_Event* event)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n if (!SDL_IsGameController (event->cdevice.which)) {\r\n SDL_Joystick* js = SDL_JoystickOpen (event->jdevice.which);\r\n\r\n if (js) {\r\n char guid [1024];\r\n SDL_JoystickGetGUIDString (SDL_JoystickGetGUID (js), guid, sizeof (guid));\r\n\r\n QString mapping = QString (\"%1,%2,%3\")\r\n .arg (guid)\r\n .arg (SDL_JoystickName (js))\r\n .arg (GENERIC_MAPPINGS);\r\n\r\n SDL_GameControllerAddMapping (mapping.toStdString().c_str());\r\n SDL_JoystickClose (js);\r\n }\r\n }\r\n\r\n SDL_GameControllerOpen (event->cdevice.which);\r\n\r\n ++m_tracker;\r\n emit countChanged();\r\n#else\r\n Q_UNUSED (event);\r\n#endif\r\n}\r\n\r\n\/**\r\n * Returns a joystick ID compatible with the \\c QJoysticks system.\r\n * SDL assigns an ID to each joystick based on the order that they are attached,\r\n * but it does not decrease the ID counter when a joystick is removed.\r\n *\r\n * As noted earlier, the \\c QJoysticks maintains an ID system similar to the\r\n * one used by a \\c QList, since it eases the operation with most Qt classes\r\n * and widgets.\r\n *\/\r\nint SDL_Joysticks::getDynamicID (int id)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n id = abs (m_tracker - (id + 1));\r\n\r\n if (id >= SDL_NumJoysticks())\r\n id -= 1;\r\n\r\n#endif\r\n\r\n return id;\r\n}\r\n\r\n\/**\r\n * Returns the josytick device registered with the given \\a id.\r\n * If no joystick with the given \\a id is found, then the function will warn\r\n * the user through the console.\r\n *\/\r\nQJoystickDevice* SDL_Joysticks::getJoystick (int id)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n QJoystickDevice* joystick = new QJoystickDevice;\r\n SDL_Joystick* sdl_joystick = SDL_JoystickOpen (id);\r\n joystick->id = getDynamicID (id);\r\n\r\n if (sdl_joystick) {\r\n joystick->blacklisted = false;\r\n joystick->name = SDL_JoystickName (sdl_joystick);\r\n\r\n \/* Get joystick properties *\/\r\n int povs = SDL_JoystickNumHats (sdl_joystick);\r\n int axes = SDL_JoystickNumAxes (sdl_joystick);\r\n int buttons = SDL_JoystickNumButtons (sdl_joystick);\r\n\r\n \/* Initialize POVs *\/\r\n for (int i = 0; i < povs; ++i)\r\n joystick->povs.append (0);\r\n\r\n \/* Initialize axes *\/\r\n for (int i = 0; i < axes; ++i)\r\n joystick->axes.append (0);\r\n\r\n \/* Initialize buttons *\/\r\n for (int i = 0; i < buttons; ++i)\r\n joystick->buttons.append (false);\r\n }\r\n\r\n else\r\n qWarning() << Q_FUNC_INFO << \"Cannot find joystick with id:\" << id;\r\n\r\n return joystick;\r\n#else\r\n Q_UNUSED (id);\r\n return NULL;\r\n#endif\r\n}\r\n\r\n\/**\r\n * Reads the contents of the given \\a event and constructs a new\r\n * \\c QJoystickPOVEvent to be used with the \\c QJoysticks system.\r\n *\/\r\nQJoystickPOVEvent SDL_Joysticks::getPOVEvent (const SDL_Event* sdl_event)\r\n{\r\n QJoystickPOVEvent event;\r\n\r\n#ifdef SDL_SUPPORTED\r\n event.pov = sdl_event->jhat.hat;\r\n event.joystick = getJoystick (sdl_event->jdevice.which);\r\n\r\n switch (sdl_event->jhat.value) {\r\n case SDL_HAT_RIGHTUP:\r\n event.angle = 45;\r\n break;\r\n case SDL_HAT_RIGHTDOWN:\r\n event.angle = 135;\r\n break;\r\n case SDL_HAT_LEFTDOWN:\r\n event.angle = 225;\r\n break;\r\n case SDL_HAT_LEFTUP:\r\n event.angle = 315;\r\n break;\r\n case SDL_HAT_UP:\r\n event.angle = 0;\r\n break;\r\n case SDL_HAT_RIGHT:\r\n event.angle = 90;\r\n break;\r\n case SDL_HAT_DOWN:\r\n event.angle = 180;\r\n break;\r\n case SDL_HAT_LEFT:\r\n event.angle = 270;\r\n break;\r\n default:\r\n event.angle = -1;\r\n break;\r\n }\r\n#else\r\n Q_UNUSED (sdl_event);\r\n#endif\r\n\r\n return event;\r\n}\r\n\r\n\/**\r\n * Reads the contents of the given \\a event and constructs a new\r\n * \\c QJoystickAxisEvent to be used with the \\c QJoysticks system.\r\n *\/\r\nQJoystickAxisEvent SDL_Joysticks::getAxisEvent (const SDL_Event* sdl_event)\r\n{\r\n QJoystickAxisEvent event;\r\n\r\n#ifdef SDL_SUPPORTED\r\n event.axis = sdl_event->caxis.axis;\r\n event.value = static_cast (sdl_event->caxis.value) \/ 32767;\r\n event.joystick = getJoystick (sdl_event->cdevice.which);\r\n#else\r\n Q_UNUSED (sdl_event);\r\n#endif\r\n\r\n return event;\r\n}\r\n\r\n\/**\r\n * Reads the contents of the given \\a event and constructs a new\r\n * \\c QJoystickButtonEvent to be used with the \\c QJoysticks system.\r\n *\/\r\nQJoystickButtonEvent SDL_Joysticks::getButtonEvent (const SDL_Event*\r\n sdl_event)\r\n{\r\n QJoystickButtonEvent event;\r\n\r\n#ifdef SDL_SUPPORTED\r\n event.button = sdl_event->jbutton.button;\r\n event.pressed = sdl_event->jbutton.state == SDL_PRESSED;\r\n event.joystick = getJoystick (sdl_event->jdevice.which);\r\n#else\r\n Q_UNUSED (sdl_event);\r\n#endif\r\n\r\n return event;\r\n}\r\nUpdate SDL_Joysticks.cpp\/*\r\n * Copyright (c) 2015-2017 Alex Spataru \r\n *\r\n * Permission is hereby granted, free of charge, to any person obtaining a copy\r\n * of this software and associated documentation files (the \"Software\"), to deal\r\n * in the Software without restriction, including without limitation the rights\r\n * to use, copy, modify, merge, publish, distribute, sublicense, and\/or sell\r\n * copies of the Software, and to permit persons to whom the Software is\r\n * furnished to do so, subject to the following conditions:\r\n *\r\n * The above copyright notice and this permission notice shall be included in\r\n * all copies or substantial portions of the Software.\r\n *\r\n * THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\n * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\n * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\n * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\n * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\n * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\r\n * THE SOFTWARE.\r\n *\/\r\n\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\n\/**\r\n * Holds a generic mapping to be applied to joysticks that have not been mapped\r\n * by the SDL project or by the database.\r\n *\r\n * This mapping is different on each supported operating system.\r\n *\/\r\nstatic QString GENERIC_MAPPINGS;\r\n\r\n\/**\r\n * Load a different generic\/backup mapping for each operating system.\r\n *\/\r\n#ifdef SDL_SUPPORTED\r\n #if defined Q_OS_WIN\r\n #define GENERIC_MAPPINGS_PATH \":\/QJoysticks\/SDL\/GenericMappings\/Windows.txt\"\r\n #elif defined Q_OS_MAC\r\n #define GENERIC_MAPPINGS_PATH \":\/QJoysticks\/SDL\/GenericMappings\/OSX.txt\"\r\n #elif defined Q_OS_LINUX && !defined Q_OS_ANDROID\r\n #define GENERIC_MAPPINGS_PATH \":\/QJoysticks\/SDL\/GenericMappings\/Linux.txt\"\r\n #endif\r\n#endif\r\n\r\nSDL_Joysticks::SDL_Joysticks (QObject* parent) : QObject (parent)\r\n{\r\n m_tracker = -1;\r\n\r\n#ifdef SDL_SUPPORTED\r\n if (SDL_Init (SDL_INIT_HAPTIC | SDL_INIT_AUDIO | SDL_INIT_GAMECONTROLLER)) {\r\n qDebug() << \"Cannot initialize SDL:\" << SDL_GetError();\r\n qApp->quit();\r\n }\r\n\r\n QFile database (\":\/QJoysticks\/SDL\/Database.txt\");\r\n if (database.open (QFile::ReadOnly)) {\r\n while (!database.atEnd()) {\r\n QString line = QString::fromUtf8 (database.readLine());\r\n SDL_GameControllerAddMapping (line.toStdString().c_str());\r\n }\r\n\r\n database.close();\r\n }\r\n\r\n QFile genericMappings (GENERIC_MAPPINGS_PATH);\r\n if (genericMappings.open (QFile::ReadOnly)) {\r\n GENERIC_MAPPINGS = QString::fromUtf8 (genericMappings.readAll());\r\n genericMappings.close();\r\n }\r\n\r\n QTimer::singleShot (100, Qt::PreciseTimer, this, SLOT (update()));\r\n#endif\r\n}\r\n\r\nSDL_Joysticks::~SDL_Joysticks()\r\n{\r\n#ifdef SDL_SUPPORTED\r\n SDL_Quit();\r\n#endif\r\n}\r\n\r\n\/**\r\n * Returns a list with all the registered joystick devices\r\n *\/\r\nQList SDL_Joysticks::joysticks()\r\n{\r\n QList list;\r\n\r\n#ifdef SDL_SUPPORTED\r\n for (int i = 0; i < SDL_NumJoysticks(); ++i)\r\n list.append (getJoystick (i));\r\n#endif\r\n\r\n return list;\r\n}\r\n\r\n\/**\r\n * Based on the data contained in the \\a request, this function will instruct\r\n * the appropriate joystick to rumble for\r\n *\/\r\nvoid SDL_Joysticks::rumble (const QJoystickRumble& request)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n SDL_Haptic* haptic = SDL_HapticOpen (request.joystick->id);\r\n\r\n if (haptic) {\r\n SDL_HapticRumbleInit (haptic);\r\n SDL_HapticRumblePlay (haptic, request.strength, request.length);\r\n }\r\n#else\r\n Q_UNUSED (request);\r\n#endif\r\n}\r\n\r\n\/**\r\n * Polls for new SDL events and reacts to each event accordingly.\r\n *\/\r\nvoid SDL_Joysticks::update()\r\n{\r\n#ifdef SDL_SUPPORTED\r\n SDL_Event event;\r\n\r\n while (SDL_PollEvent (&event)) {\r\n switch (event.type) {\r\n case SDL_JOYDEVICEADDED:\r\n configureJoystick (&event);\r\n break;\r\n case SDL_JOYDEVICEREMOVED:\r\n SDL_JoystickClose (SDL_JoystickOpen (event.jdevice.which));\r\n SDL_GameControllerClose (SDL_GameControllerOpen (event.cdevice.which));\r\n emit countChanged();\r\n break;\r\n case SDL_CONTROLLERAXISMOTION:\r\n emit axisEvent (getAxisEvent (&event));\r\n break;\r\n case SDL_JOYBUTTONUP:\r\n emit buttonEvent (getButtonEvent (&event));\r\n break;\r\n case SDL_JOYBUTTONDOWN:\r\n emit buttonEvent (getButtonEvent (&event));\r\n break;\r\n case SDL_JOYHATMOTION:\r\n emit POVEvent (getPOVEvent (&event));\r\n break;\r\n }\r\n }\r\n\r\n QTimer::singleShot (10, Qt::PreciseTimer, this, &SDL_Joysticks::update);\r\n#endif\r\n}\r\n\r\n\/**\r\n * Checks if the joystick referenced by the \\a event can be initialized.\r\n * If not, the function will apply a generic mapping to the joystick and\r\n * attempt to initialize the joystick again.\r\n *\/\r\nvoid SDL_Joysticks::configureJoystick (const SDL_Event* event)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n if (!SDL_IsGameController (event->cdevice.which)) {\r\n SDL_Joystick* js = SDL_JoystickOpen (event->jdevice.which);\r\n\r\n if (js) {\r\n char guid [1024];\r\n SDL_JoystickGetGUIDString (SDL_JoystickGetGUID (js), guid, sizeof (guid));\r\n\r\n QString mapping = QString (\"%1,%2,%3\")\r\n .arg (guid)\r\n .arg (SDL_JoystickName (js))\r\n .arg (GENERIC_MAPPINGS);\r\n\r\n SDL_GameControllerAddMapping (mapping.toStdString().c_str());\r\n SDL_JoystickClose (js);\r\n }\r\n }\r\n\r\n SDL_GameControllerOpen (event->cdevice.which);\r\n\r\n ++m_tracker;\r\n emit countChanged();\r\n#else\r\n Q_UNUSED (event);\r\n#endif\r\n}\r\n\r\n\/**\r\n * Returns a joystick ID compatible with the \\c QJoysticks system.\r\n * SDL assigns an ID to each joystick based on the order that they are attached,\r\n * but it does not decrease the ID counter when a joystick is removed.\r\n *\r\n * As noted earlier, the \\c QJoysticks maintains an ID system similar to the\r\n * one used by a \\c QList, since it eases the operation with most Qt classes\r\n * and widgets.\r\n *\/\r\nint SDL_Joysticks::getDynamicID (int id)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n id = abs (m_tracker - (id + 1));\r\n\r\n if (id >= SDL_NumJoysticks())\r\n id -= 1;\r\n\r\n#endif\r\n\r\n return id;\r\n}\r\n\r\n\/**\r\n * Returns the josytick device registered with the given \\a id.\r\n * If no joystick with the given \\a id is found, then the function will warn\r\n * the user through the console.\r\n *\/\r\nQJoystickDevice* SDL_Joysticks::getJoystick (int id)\r\n{\r\n#ifdef SDL_SUPPORTED\r\n QJoystickDevice* joystick = new QJoystickDevice;\r\n SDL_Joystick* sdl_joystick = SDL_JoystickOpen (id);\r\n joystick->id = getDynamicID (id);\r\n\r\n if (sdl_joystick) {\r\n joystick->blacklisted = false;\r\n joystick->name = SDL_JoystickName (sdl_joystick);\r\n\r\n \/* Get joystick properties *\/\r\n int povs = SDL_JoystickNumHats (sdl_joystick);\r\n int axes = SDL_JoystickNumAxes (sdl_joystick);\r\n int buttons = SDL_JoystickNumButtons (sdl_joystick);\r\n\r\n \/* Initialize POVs *\/\r\n for (int i = 0; i < povs; ++i)\r\n joystick->povs.append (0);\r\n\r\n \/* Initialize axes *\/\r\n for (int i = 0; i < axes; ++i)\r\n joystick->axes.append (0);\r\n\r\n \/* Initialize buttons *\/\r\n for (int i = 0; i < buttons; ++i)\r\n joystick->buttons.append (false);\r\n }\r\n\r\n else\r\n qWarning() << Q_FUNC_INFO << \"Cannot find joystick with id:\" << id;\r\n\r\n return joystick;\r\n#else\r\n Q_UNUSED (id);\r\n return NULL;\r\n#endif\r\n}\r\n\r\n\/**\r\n * Reads the contents of the given \\a event and constructs a new\r\n * \\c QJoystickPOVEvent to be used with the \\c QJoysticks system.\r\n *\/\r\nQJoystickPOVEvent SDL_Joysticks::getPOVEvent (const SDL_Event* sdl_event)\r\n{\r\n QJoystickPOVEvent event;\r\n\r\n#ifdef SDL_SUPPORTED\r\n event.pov = sdl_event->jhat.hat;\r\n event.joystick = getJoystick (sdl_event->jdevice.which);\r\n\r\n switch (sdl_event->jhat.value) {\r\n case SDL_HAT_RIGHTUP:\r\n event.angle = 45;\r\n break;\r\n case SDL_HAT_RIGHTDOWN:\r\n event.angle = 135;\r\n break;\r\n case SDL_HAT_LEFTDOWN:\r\n event.angle = 225;\r\n break;\r\n case SDL_HAT_LEFTUP:\r\n event.angle = 315;\r\n break;\r\n case SDL_HAT_UP:\r\n event.angle = 0;\r\n break;\r\n case SDL_HAT_RIGHT:\r\n event.angle = 90;\r\n break;\r\n case SDL_HAT_DOWN:\r\n event.angle = 180;\r\n break;\r\n case SDL_HAT_LEFT:\r\n event.angle = 270;\r\n break;\r\n default:\r\n event.angle = -1;\r\n break;\r\n }\r\n#else\r\n Q_UNUSED (sdl_event);\r\n#endif\r\n\r\n return event;\r\n}\r\n\r\n\/**\r\n * Reads the contents of the given \\a event and constructs a new\r\n * \\c QJoystickAxisEvent to be used with the \\c QJoysticks system.\r\n *\/\r\nQJoystickAxisEvent SDL_Joysticks::getAxisEvent (const SDL_Event* sdl_event)\r\n{\r\n QJoystickAxisEvent event;\r\n\r\n#ifdef SDL_SUPPORTED\r\n event.axis = sdl_event->caxis.axis;\r\n event.value = static_cast (sdl_event->caxis.value) \/ 32767;\r\n event.joystick = getJoystick (sdl_event->cdevice.which);\r\n#else\r\n Q_UNUSED (sdl_event);\r\n#endif\r\n\r\n return event;\r\n}\r\n\r\n\/**\r\n * Reads the contents of the given \\a event and constructs a new\r\n * \\c QJoystickButtonEvent to be used with the \\c QJoysticks system.\r\n *\/\r\nQJoystickButtonEvent SDL_Joysticks::getButtonEvent (const SDL_Event*\r\n sdl_event)\r\n{\r\n QJoystickButtonEvent event;\r\n\r\n#ifdef SDL_SUPPORTED\r\n event.button = sdl_event->jbutton.button;\r\n event.pressed = sdl_event->jbutton.state == SDL_PRESSED;\r\n event.joystick = getJoystick (sdl_event->jdevice.which);\r\n#else\r\n Q_UNUSED (sdl_event);\r\n#endif\r\n\r\n return event;\r\n}\r\n<|endoftext|>"} {"text":"#pragma once\n\n#include \"eigen.hh\"\n\n#include \"numerics\/optimization\/error_function.hh\"\n\n#include \n\nnamespace numerics {\n\ntemplate \nstruct MinimizationResult {\n VecNd solution = VecNd::Zero();\n VecNd terminal_jti = VecNd::Zero();\n VecNd terminal_error = VecNd::Zero();\n\n bool success = false;\n};\n\nstruct OptimizationConfiguration {\n int max_iterations = 5;\n double levenberg_mu = 1e-3;\n};\n\ntemplate \nMinimizationResult gauss_newton_minimize(\n const std::vector> &funcs,\n const VecNd &initialization,\n const OptimizationConfiguration &opt_cfg) {\n using OutVec = VecNd;\n using InVec = VecNd;\n using Information = MatNd;\n using ErrorJacobian = MatNd;\n\n MinimizationResult result;\n InVec x = initialization;\n\n for (int k = 0; k < opt_cfg.max_iterations; ++k) {\n Information jtj = Information::Zero();\n InVec jti = InVec::Zero();\n\n result.terminal_error.setZero();\n ErrorJacobian jac;\n for (const auto &func : funcs) {\n jac.setZero();\n const OutVec innovation = func(x, &jac);\n jtj += jac.transpose() * jac;\n jti += jac.transpose() * innovation;\n result.terminal_error += innovation;\n }\n\n const Eigen::LLT llt_jtj(opt_cfg.levenberg_mu * Information::Identity() +\n jtj);\n if (llt_jtj.info() != Eigen::Success) {\n result.success = false;\n break;\n }\n\n const InVec update = llt_jtj.solve(jti);\n\n x -= update;\n\n result.solution = x;\n result.terminal_jti = jti;\n result.success = true;\n }\n\n return result;\n}\n\ntemplate \nMinimizationResult gauss_newton_minimize(\n const ErrorFunction &func,\n const VecNd &initialization,\n const OptimizationConfiguration &opt_cfg = {}) {\n const std::vector> fncs = {\n wrap_numerical_diff(func)};\n const auto result = gauss_newton_minimize(fncs, initialization, opt_cfg);\n return result;\n}\n\n} \/\/ namespace numerics\nExperiment with permitting dynamic-sized matrices in GN#pragma once\n\n#include \"eigen.hh\"\n\n#include \"numerics\/optimization\/error_function.hh\"\n\n#include \n\nnamespace numerics {\n\ntemplate \nstruct MinimizationResult {\n VecNd solution = VecNd::Zero();\n VecNd terminal_jti = VecNd::Zero();\n VecNd terminal_error = VecNd::Zero();\n\n bool success = false;\n};\n\nstruct OptimizationConfiguration {\n int max_iterations = 5;\n double levenberg_mu = 1e-3;\n};\n\ntemplate \nMinimizationResult gauss_newton_minimize(\n const std::vector> &funcs,\n const VecNd &initialization,\n const OptimizationConfiguration &opt_cfg) {\n using OutVec = VecNd;\n using InVec = VecNd;\n using Information = MatNd;\n using ErrorJacobian = MatNd;\n\n MinimizationResult result;\n InVec x = initialization;\n\n Information jtj;\n InVec jti;\n for (int k = 0; k < opt_cfg.max_iterations; ++k) {\n jtj.setZero();\n jti.setZero();\n\n result.terminal_error.setZero();\n ErrorJacobian jac;\n for (const auto &func : funcs) {\n jac.setZero();\n const OutVec innovation = func(x, &jac);\n jtj += jac.transpose() * jac;\n jti += jac.transpose() * innovation;\n result.terminal_error += innovation;\n }\n\n const Eigen::LLT llt_jtj(opt_cfg.levenberg_mu * Information::Identity() +\n jtj);\n if (llt_jtj.info() != Eigen::Success) {\n result.success = false;\n break;\n }\n\n const InVec update = llt_jtj.solve(jti);\n\n x -= update;\n\n result.solution = x;\n result.terminal_jti = jti;\n result.success = true;\n }\n\n return result;\n}\n\ntemplate \nMinimizationResult gauss_newton_minimize(\n const ErrorFunction &func,\n const VecNd &initialization,\n const OptimizationConfiguration &opt_cfg = {}) {\n const std::vector> fncs = {\n wrap_numerical_diff(func)};\n const auto result = gauss_newton_minimize(fncs, initialization, opt_cfg);\n return result;\n}\n\n} \/\/ namespace numerics\n<|endoftext|>"} {"text":"\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n\n#include \"mlir\/IR\/Builders.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Module.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/UseDefLists.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/Pass.h\" \/\/ from @llvm-project\n#include \"mlir\/Support\/LLVM.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_ops.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_saved_model.h\"\n\nnamespace mlir {\nnamespace tf_saved_model {\nnamespace {\n\n\/\/ This pass will replace a func's bound inputs which are bound to\n\/\/ tf.ReadVariable ops global tensors with tf.Const ops inside the func's body.\n\/\/ If this pass runs successfully, the resultant IR will be guaranteed to:\n\/\/\n\/\/ 1. Not contain any tf_saved_model.global_tensor ops\n\/\/ 2. Not contain any tf_saved_model.bound_input arg attrs on tf_saved_model\n\/\/ exported functions\n\/\/ Else, the pass fails.\n\/\/\n\/\/ The reason this pass has this contract is so that once this succeeds, we know\n\/\/ the IR is in correct form for inference backends (like lite) that do not\n\/\/ support resources\/variables . Further, this contract also ensures that this\n\/\/ pass lowers from saved model to pure TF. Hence it fails, if it cannot lower.\nstruct FreezeGlobalTensorsPass\n : public PassWrapper> {\n void runOnOperation() override;\n};\n\nvoid FreezeGlobalTensorsPass::runOnOperation() {\n auto module = getOperation();\n SymbolTable symbol_table(module);\n DenseSet frozen_global_tensors;\n\n for (auto func : module.getOps()) {\n SmallVector args_to_erase;\n OpBuilder builder(func.getBody());\n\n for (int i = 0, e = func.getNumArguments(); i < e; ++i) {\n SmallVector read_variable_ops_to_erase;\n auto global_tensor = LookupBoundInput(func, i, symbol_table);\n\n if (!global_tensor) continue;\n frozen_global_tensors.insert(global_tensor);\n\n \/\/ This pass assumes that all global tensors as immutable (e.g. by a\n \/\/ previous optimize global tensors pass). If not, this pass has to fail\n \/\/ since it cannot perform one of its goals.\n if (global_tensor.is_mutable()) {\n global_tensor.emitError() << \"is not immutable\";\n return signalPassFailure();\n }\n\n auto arg = func.getArgument(i);\n for (auto user : arg.getUsers()) {\n if (auto read_op = llvm::dyn_cast(user)) {\n \/\/ Collect all read variable ops so that all its uses can be replaced\n \/\/ with the tf.constant corresponding to the global tensor op.\n read_variable_ops_to_erase.push_back(read_op);\n } else {\n \/\/ Current assumption is all users are tf.ReadVariableOp. Need to\n \/\/ expand this to handle control flow and call ops.\n user->emitError() << \"could not rewrite use of immutable bound input\";\n return signalPassFailure();\n }\n }\n\n \/\/ Replace the arg with a tf.Const op in the function body.\n builder.setInsertionPointToStart(&func.getBody().front());\n auto const_op = builder.create(global_tensor.getLoc(),\n global_tensor.value());\n args_to_erase.push_back(i);\n for (auto read_op : read_variable_ops_to_erase) {\n read_op.getResult().replaceAllUsesWith(const_op.getResult());\n read_op.erase();\n }\n }\n func.eraseArguments(args_to_erase);\n }\n \/\/ Erase all global tensors that were frozen.\n for (auto global_tensor : frozen_global_tensors) {\n global_tensor->erase();\n }\n\n if (!module.getOps().empty()) {\n module.emitError() << \"could not freeze all global tensors in the module\";\n return signalPassFailure();\n }\n}\n\n} \/\/ namespace\n\n\/\/ For \"opt\" to pick up this pass.\nstatic PassRegistration pass(\n \"tf-saved-model-freeze-global-tensors\",\n \"Freeze tf_saved_model.global_tensor's in func bodies.\");\n\nstd::unique_ptr> CreateFreezeGlobalTensorsPass() {\n return std::make_unique();\n}\n\n} \/\/ namespace tf_saved_model\n} \/\/ namespace mlir\nImprove diagnostic when a mutable global tensor is found\/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n==============================================================================*\/\n\n#include \n#include \n\n#include \"mlir\/IR\/Builders.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/Module.h\" \/\/ from @llvm-project\n#include \"mlir\/IR\/UseDefLists.h\" \/\/ from @llvm-project\n#include \"mlir\/Pass\/Pass.h\" \/\/ from @llvm-project\n#include \"mlir\/Support\/LLVM.h\" \/\/ from @llvm-project\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_ops.h\"\n#include \"tensorflow\/compiler\/mlir\/tensorflow\/ir\/tf_saved_model.h\"\n\nnamespace mlir {\nnamespace tf_saved_model {\nnamespace {\n\n\/\/ This pass will replace a func's bound inputs which are bound to\n\/\/ tf.ReadVariable ops global tensors with tf.Const ops inside the func's body.\n\/\/ If this pass runs successfully, the resultant IR will be guaranteed to:\n\/\/\n\/\/ 1. Not contain any tf_saved_model.global_tensor ops\n\/\/ 2. Not contain any tf_saved_model.bound_input arg attrs on tf_saved_model\n\/\/ exported functions\n\/\/ Else, the pass fails.\n\/\/\n\/\/ The reason this pass has this contract is so that once this succeeds, we know\n\/\/ the IR is in correct form for inference backends (like lite) that do not\n\/\/ support resources\/variables . Further, this contract also ensures that this\n\/\/ pass lowers from saved model to pure TF. Hence it fails, if it cannot lower.\nstruct FreezeGlobalTensorsPass\n : public PassWrapper> {\n void runOnOperation() override;\n};\n\nvoid FreezeGlobalTensorsPass::runOnOperation() {\n auto module = getOperation();\n SymbolTable symbol_table(module);\n DenseSet frozen_global_tensors;\n\n for (auto func : module.getOps()) {\n SmallVector args_to_erase;\n OpBuilder builder(func.getBody());\n\n for (int i = 0, e = func.getNumArguments(); i < e; ++i) {\n SmallVector read_variable_ops_to_erase;\n auto global_tensor = LookupBoundInput(func, i, symbol_table);\n\n if (!global_tensor) continue;\n frozen_global_tensors.insert(global_tensor);\n\n \/\/ This pass assumes that all global tensors as immutable (e.g. by a\n \/\/ previous optimize global tensors pass). If not, this pass has to fail\n \/\/ since it cannot perform one of its goals.\n if (global_tensor.is_mutable()) {\n global_tensor.emitError() << \"is not immutable, try running \"\n \"tf-saved-model-optimize-global-tensors \"\n \"to prove tensors are immutable\";\n return signalPassFailure();\n }\n\n auto arg = func.getArgument(i);\n for (auto user : arg.getUsers()) {\n if (auto read_op = llvm::dyn_cast(user)) {\n \/\/ Collect all read variable ops so that all its uses can be replaced\n \/\/ with the tf.constant corresponding to the global tensor op.\n read_variable_ops_to_erase.push_back(read_op);\n } else {\n \/\/ Current assumption is all users are tf.ReadVariableOp. Need to\n \/\/ expand this to handle control flow and call ops.\n user->emitError() << \"could not rewrite use of immutable bound input\";\n return signalPassFailure();\n }\n }\n\n \/\/ Replace the arg with a tf.Const op in the function body.\n builder.setInsertionPointToStart(&func.getBody().front());\n auto const_op = builder.create(global_tensor.getLoc(),\n global_tensor.value());\n args_to_erase.push_back(i);\n for (auto read_op : read_variable_ops_to_erase) {\n read_op.getResult().replaceAllUsesWith(const_op.getResult());\n read_op.erase();\n }\n }\n func.eraseArguments(args_to_erase);\n }\n \/\/ Erase all global tensors that were frozen.\n for (auto global_tensor : frozen_global_tensors) {\n global_tensor->erase();\n }\n\n if (!module.getOps().empty()) {\n module.emitError() << \"could not freeze all global tensors in the module\";\n return signalPassFailure();\n }\n}\n\n} \/\/ namespace\n\n\/\/ For \"opt\" to pick up this pass.\nstatic PassRegistration pass(\n \"tf-saved-model-freeze-global-tensors\",\n \"Freeze tf_saved_model.global_tensor's in func bodies.\");\n\nstd::unique_ptr> CreateFreezeGlobalTensorsPass() {\n return std::make_unique();\n}\n\n} \/\/ namespace tf_saved_model\n} \/\/ namespace mlir\n<|endoftext|>"} {"text":"#include \"asylo\/util\/logging.h\"\n\n#include \"oak\/server\/oak_server.h\"\n\n#include \"src\/binary-reader.h\"\n#include \"src\/error-formatter.h\"\n#include \"src\/error.h\"\n#include \"src\/interp\/binary-reader-interp.h\"\n#include \"src\/interp\/interp.h\"\n\nnamespace oak {\nnamespace grpc_server {\n\n\/\/ From https:\/\/github.com\/WebAssembly\/wabt\/blob\/master\/src\/tools\/wasm-interp.cc .\n\nstatic wabt::Features s_features;\nstatic std::unique_ptr s_log_stream;\nstatic std::unique_ptr s_stdout_stream;\n\nstatic wabt::interp::Result PrintCallback(const wabt::interp::HostFunc* func,\n const wabt::interp::FuncSignature* sig,\n const wabt::interp::TypedValues& args,\n wabt::interp::TypedValues& results) {\n LOG(INFO) << \"Called host\";\n return wabt::interp::Result::Ok;\n}\n\nstatic wabt::Index UnknownFuncHandler(wabt::interp::Environment* env,\n wabt::interp::HostModule* host_module, wabt::string_view name,\n wabt::Index sig_index) {\n LOG(INFO) << \"Unknown func export\";\n std::pair pair =\n host_module->AppendFuncExport(name, sig_index, PrintCallback);\n return pair.second;\n}\n\nstatic void InitEnvironment(wabt::interp::Environment* env) {\n wabt::interp::HostModule* go_module = env->AppendHostModule(\"go\");\n go_module->on_unknown_func_export = UnknownFuncHandler;\n\n wabt::interp::HostModule* oak_module = env->AppendHostModule(\"oak\");\n oak_module->on_unknown_func_export = UnknownFuncHandler;\n}\n\nstatic wabt::Result ReadModule(std::string module_bytes, wabt::interp::Environment* env,\n wabt::Errors* errors, wabt::interp::DefinedModule** out_module) {\n LOG(INFO) << \"Reading module\";\n wabt::Result result;\n\n *out_module = nullptr;\n\n const bool kReadDebugNames = true;\n const bool kStopOnFirstError = true;\n const bool kFailOnCustomSectionError = true;\n wabt::ReadBinaryOptions options(s_features, s_log_stream.get(), kReadDebugNames,\n kStopOnFirstError, kFailOnCustomSectionError);\n\n LOG(INFO) << \"xxx\";\n result = wabt::ReadBinaryInterp(env, module_bytes.data(), module_bytes.size(), options, errors,\n out_module);\n LOG(INFO) << \"yyy\";\n\n if (Succeeded(result)) {\n env->DisassembleModule(s_stdout_stream.get(), *out_module);\n }\n\n LOG(INFO) << \"Read module\";\n return result;\n}\n\nOakServer::OakServer() : Service() {}\n\n::grpc::Status OakServer::InitiateComputation(::grpc::ServerContext* context,\n const ::oak::InitiateComputationRequest* request,\n ::oak::InitiateComputationResponse* response) {\n LOG(INFO) << \"Initate Computation: \" << request->DebugString();\n\n s_stdout_stream = wabt::FileStream::CreateStdout();\n\n wabt::Result result;\n wabt::interp::Environment env;\n InitEnvironment(&env);\n\n wabt::Errors errors;\n wabt::interp::DefinedModule* module = nullptr;\n result = ReadModule(request->business_logic(), &env, &errors, &module);\n if (wabt::Succeeded(result)) {\n LOG(INFO) << \"Success\";\n } else {\n LOG(INFO) << \"Failure: \" << result;\n LOG(INFO) << \"Errors: \" << wabt::FormatErrorsToString(errors, wabt::Location::Type::Binary);\n }\n\n \/\/ int token_cnt = 3;\n \/\/ char *tokens[] = {(char *)\"mul\", (char *)\"11\", (char *)\"22\"};\n\n \/\/ int res = 0;\n LOG(INFO) << \"Invoking function\";\n \/\/ res = invoke(m, tokens[0], token_cnt - 1, tokens + 1);\n LOG(INFO) << \"Function invoked\";\n \/\/ if (res) {\n \/\/ char *value = value_repr(&m->stack[m->sp]);\n \/\/ LOG(INFO) << \"value: \" << value;\n \/\/ response->set_value(value);\n \/\/} else {\n \/\/ fprintf(stderr, \"error\");\n \/\/ LOG(INFO) << \"error\";\n \/\/ response->set_value(\"error\");\n \/\/}\n\n return ::grpc::Status::OK;\n}\n\n} \/\/ namespace grpc_server\n} \/\/ namespace oak\nPrint func exports#include \"asylo\/util\/logging.h\"\n\n#include \"oak\/server\/oak_server.h\"\n\n#include \"src\/binary-reader.h\"\n#include \"src\/error-formatter.h\"\n#include \"src\/error.h\"\n#include \"src\/interp\/binary-reader-interp.h\"\n#include \"src\/interp\/interp.h\"\n\nnamespace oak {\nnamespace grpc_server {\n\n\/\/ From https:\/\/github.com\/WebAssembly\/wabt\/blob\/master\/src\/tools\/wasm-interp.cc .\n\nstatic wabt::Features s_features;\nstatic std::unique_ptr s_log_stream;\nstatic std::unique_ptr s_stdout_stream;\n\nstatic wabt::interp::Result PrintCallback(const wabt::interp::HostFunc* func,\n const wabt::interp::FuncSignature* sig,\n const wabt::interp::TypedValues& args,\n wabt::interp::TypedValues& results) {\n LOG(INFO) << \"Called host\";\n return wabt::interp::Result::Ok;\n}\n\nstatic wabt::Index UnknownFuncHandler(wabt::interp::Environment* env,\n wabt::interp::HostModule* host_module, wabt::string_view name,\n wabt::Index sig_index) {\n LOG(INFO) << \"Unknown func export: \" << name.to_string();\n std::pair pair =\n host_module->AppendFuncExport(name, sig_index, PrintCallback);\n return pair.second;\n}\n\nstatic void InitEnvironment(wabt::interp::Environment* env) {\n wabt::interp::HostModule* go_module = env->AppendHostModule(\"go\");\n go_module->on_unknown_func_export = UnknownFuncHandler;\n\n wabt::interp::HostModule* oak_module = env->AppendHostModule(\"oak\");\n oak_module->on_unknown_func_export = UnknownFuncHandler;\n}\n\nstatic wabt::Result ReadModule(std::string module_bytes, wabt::interp::Environment* env,\n wabt::Errors* errors, wabt::interp::DefinedModule** out_module) {\n LOG(INFO) << \"Reading module\";\n wabt::Result result;\n\n *out_module = nullptr;\n\n const bool kReadDebugNames = true;\n const bool kStopOnFirstError = true;\n const bool kFailOnCustomSectionError = true;\n wabt::ReadBinaryOptions options(s_features, s_log_stream.get(), kReadDebugNames,\n kStopOnFirstError, kFailOnCustomSectionError);\n\n LOG(INFO) << \"xxx\";\n result = wabt::ReadBinaryInterp(env, module_bytes.data(), module_bytes.size(), options, errors,\n out_module);\n LOG(INFO) << \"yyy\";\n\n if (Succeeded(result)) {\n \/\/ env->DisassembleModule(s_stdout_stream.get(), *out_module);\n }\n\n LOG(INFO) << \"Read module\";\n return result;\n}\n\nOakServer::OakServer() : Service() {}\n\n::grpc::Status OakServer::InitiateComputation(::grpc::ServerContext* context,\n const ::oak::InitiateComputationRequest* request,\n ::oak::InitiateComputationResponse* response) {\n LOG(INFO) << \"Initate Computation: \" << request->DebugString();\n\n s_stdout_stream = wabt::FileStream::CreateStdout();\n\n wabt::Result result;\n wabt::interp::Environment env;\n InitEnvironment(&env);\n\n wabt::Errors errors;\n wabt::interp::DefinedModule* module = nullptr;\n result = ReadModule(request->business_logic(), &env, &errors, &module);\n if (wabt::Succeeded(result)) {\n LOG(INFO) << \"Success\";\n } else {\n LOG(INFO) << \"Failure: \" << result;\n LOG(INFO) << \"Errors: \" << wabt::FormatErrorsToString(errors, wabt::Location::Type::Binary);\n }\n\n \/\/ int token_cnt = 3;\n \/\/ char *tokens[] = {(char *)\"mul\", (char *)\"11\", (char *)\"22\"};\n\n \/\/ int res = 0;\n LOG(INFO) << \"Invoking function\";\n \/\/ res = invoke(m, tokens[0], token_cnt - 1, tokens + 1);\n LOG(INFO) << \"Function invoked\";\n \/\/ if (res) {\n \/\/ char *value = value_repr(&m->stack[m->sp]);\n \/\/ LOG(INFO) << \"value: \" << value;\n \/\/ response->set_value(value);\n \/\/} else {\n \/\/ fprintf(stderr, \"error\");\n \/\/ LOG(INFO) << \"error\";\n \/\/ response->set_value(\"error\");\n \/\/}\n\n return ::grpc::Status::OK;\n}\n\n} \/\/ namespace grpc_server\n} \/\/ namespace oak\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Browser test for basic Chrome OS file manager functionality:\n\/\/ - The file list is updated when a file is added externally to the Downloads\n\/\/ folder.\n\/\/ - Selecting a file and copy-pasting it with the keyboard copies the file.\n\/\/ - Selecting a file and pressing delete deletes it.\n\n#include \n#include \n\n#include \"base\/callback.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_path_watcher.h\"\n#include \"base\/platform_file.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/component_loader.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/browser_context.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"net\/base\/escape.h\"\n#include \"webkit\/fileapi\/external_mount_points.h\"\n\nnamespace {\n\nconst char kFileManagerExtensionId[] = \"hhaomjibdihmijegdhdafkllkbggdgoj\";\n\nconst char kKeyboardTestFileName[] = \"world.mpeg\";\nconst int kKeyboardTestFileSize = 1000;\nconst char kKeyboardTestFileCopyName[] = \"world (1).mpeg\";\n\n\/\/ The base test class. Used by FileManagerBrowserLocalTest and\n\/\/ FileManagerBrowserDriveTest.\n\/\/ TODO(satorux): Add the latter: crbug.com\/224534.\nclass FileManagerBrowserTestBase : public ExtensionApiTest {\n protected:\n \/\/ Loads the file manager extension, navigating it to |directory_path| for\n \/\/ testing, and waits for it to finish initializing. This is invoked at the\n \/\/ start of each test (it crashes if run in SetUp).\n void StartFileManager(const std::string& directory_path);\n\n \/\/ Loads our testing extension and sends it a string identifying the current\n \/\/ test.\n void StartTest(const std::string& test_name);\n};\n\nvoid FileManagerBrowserTestBase::StartFileManager(\n const std::string& directory_path) {\n std::string file_manager_url =\n (std::string(\"chrome-extension:\/\/\") +\n kFileManagerExtensionId +\n \"\/main.html#\" +\n net::EscapeQueryParamValue(directory_path, false \/* use_plus *\/));\n\n ui_test_utils::NavigateToURL(browser(), GURL(file_manager_url));\n\n \/\/ This is sent by the file manager when it's finished initializing.\n ExtensionTestMessageListener listener(\"worker-initialized\", false);\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n}\n\nvoid FileManagerBrowserTestBase::StartTest(const std::string& test_name) {\n base::FilePath path = test_data_dir_.AppendASCII(\"file_manager_browsertest\");\n const extensions::Extension* extension = LoadExtensionAsComponent(path);\n ASSERT_TRUE(extension);\n\n ExtensionTestMessageListener listener(\"which test\", true);\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n listener.Reply(test_name);\n}\n\n\/\/ The boolean parameter, retrieved by GetParam(), is true if testing in the\n\/\/ guest mode. See SetUpCommandLine() below for details.\nclass FileManagerBrowserLocalTest : public FileManagerBrowserTestBase,\n public ::testing::WithParamInterface {\n public:\n virtual void SetUp() OVERRIDE {\n extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();\n\n ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());\n downloads_path_ = tmp_dir_.path().Append(\"Downloads\");\n ASSERT_TRUE(file_util::CreateDirectory(downloads_path_));\n\n CreateTestFile(\"hello.txt\", 123, \"4 Sep 1998 12:34:56\");\n CreateTestFile(\"My Desktop Background.png\", 1024, \"18 Jan 2038 01:02:03\");\n CreateTestFile(kKeyboardTestFileName, kKeyboardTestFileSize,\n \"4 July 2012 10:35:00\");\n CreateTestDirectory(\"photos\", \"1 Jan 1980 23:59:59\");\n \/\/ Files starting with . are filtered out in\n \/\/ file_manager\/js\/directory_contents.js, so this should not be shown.\n CreateTestDirectory(\".warez\", \"26 Oct 1985 13:39\");\n\n ExtensionApiTest::SetUp();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n bool in_guest_mode = GetParam();\n if (in_guest_mode) {\n command_line->AppendSwitch(switches::kGuestSession);\n command_line->AppendSwitch(switches::kIncognito);\n }\n ExtensionApiTest::SetUpCommandLine(command_line);\n }\n\n protected:\n \/\/ Creates a file with the given |name|, |length|, and |modification_time|.\n void CreateTestFile(const std::string& name,\n int length,\n const std::string& modification_time);\n\n \/\/ Creates an empty directory with the given |name| and |modification_time|.\n void CreateTestDirectory(const std::string& name,\n const std::string& modification_time);\n\n \/\/ Add a mount point to the fake Downloads directory. Should be called\n \/\/ before StartFileManager().\n void AddMountPointToFakeDownloads();\n\n \/\/ Path to the fake Downloads directory used in the test.\n base::FilePath downloads_path_;\n\n private:\n base::ScopedTempDir tmp_dir_;\n};\n\nINSTANTIATE_TEST_CASE_P(InGuestMode,\n FileManagerBrowserLocalTest,\n ::testing::Values(true));\n\nINSTANTIATE_TEST_CASE_P(InNonGuestMode,\n FileManagerBrowserLocalTest,\n ::testing::Values(false));\n\nvoid FileManagerBrowserLocalTest::CreateTestFile(\n const std::string& name,\n int length,\n const std::string& modification_time) {\n ASSERT_GE(length, 0);\n base::FilePath path = downloads_path_.AppendASCII(name);\n int flags = base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_WRITE;\n bool created = false;\n base::PlatformFileError error = base::PLATFORM_FILE_ERROR_FAILED;\n base::PlatformFile file = base::CreatePlatformFile(path, flags,\n &created, &error);\n ASSERT_TRUE(created);\n ASSERT_FALSE(error) << error;\n ASSERT_TRUE(base::TruncatePlatformFile(file, length));\n ASSERT_TRUE(base::ClosePlatformFile(file));\n base::Time time;\n ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time));\n ASSERT_TRUE(file_util::SetLastModifiedTime(path, time));\n}\n\nvoid FileManagerBrowserLocalTest::CreateTestDirectory(\n const std::string& name,\n const std::string& modification_time) {\n base::FilePath path = downloads_path_.AppendASCII(name);\n ASSERT_TRUE(file_util::CreateDirectory(path));\n base::Time time;\n ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time));\n ASSERT_TRUE(file_util::SetLastModifiedTime(path, time));\n}\n\nvoid FileManagerBrowserLocalTest::AddMountPointToFakeDownloads() {\n \/\/ Install our fake Downloads mount point first.\n fileapi::ExternalMountPoints* mount_points =\n content::BrowserContext::GetMountPoints(profile());\n ASSERT_TRUE(mount_points->RevokeFileSystem(\"Downloads\"));\n ASSERT_TRUE(mount_points->RegisterFileSystem(\n \"Downloads\", fileapi::kFileSystemTypeNativeLocal, downloads_path_));\n}\n\n\/\/ Monitors changes to a single file until the supplied condition callback\n\/\/ returns true. Usage:\n\/\/ TestFilePathWatcher watcher(path_to_file, MyConditionCallback);\n\/\/ watcher.StartAndWaitUntilReady();\n\/\/ ... trigger filesystem modification ...\n\/\/ watcher.RunMessageLoopUntilConditionSatisfied();\nclass TestFilePathWatcher {\n public:\n typedef base::Callback\n ConditionCallback;\n\n \/\/ Stores the supplied |path| and |condition| for later use (no side effects).\n TestFilePathWatcher(const base::FilePath& path,\n const ConditionCallback& condition);\n\n \/\/ Starts the FilePathWatcher and returns once it's watching for changes.\n void StartAndWaitUntilReady();\n\n \/\/ Waits (running a message pump) until the callback returns true or\n \/\/ FilePathWatcher reports an error. Return true on success.\n bool RunMessageLoopUntilConditionSatisfied();\n\n private:\n \/\/ FILE thread callback to start the FilePathWatcher.\n void StartWatching();\n\n \/\/ FilePathWatcher callback (on the FILE thread). Posts Done() to the UI\n \/\/ thread when the condition is satisfied or there is an error.\n void FilePathWatcherCallback(const base::FilePath& path, bool error);\n\n \/\/ Sets done_ and stops the message pump if running.\n void Done();\n\n const base::FilePath path_;\n ConditionCallback condition_;\n scoped_ptr watcher_;\n base::Closure quit_closure_;\n bool done_;\n bool error_;\n};\n\nTestFilePathWatcher::TestFilePathWatcher(const base::FilePath& path,\n const ConditionCallback& condition)\n : path_(path),\n condition_(condition),\n done_(false),\n error_(false) {\n}\n\nvoid TestFilePathWatcher::StartAndWaitUntilReady() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n base::RunLoop run_loop;\n content::BrowserThread::PostTaskAndReply(\n content::BrowserThread::FILE,\n FROM_HERE,\n base::Bind(&TestFilePathWatcher::StartWatching,\n base::Unretained(this)),\n run_loop.QuitClosure());\n run_loop.Run();\n}\n\nvoid TestFilePathWatcher::StartWatching() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));\n watcher_.reset(new base::FilePathWatcher);\n bool ok = watcher_->Watch(\n path_, false \/*recursive*\/,\n base::Bind(&TestFilePathWatcher::FilePathWatcherCallback,\n base::Unretained(this)));\n ASSERT_TRUE(ok);\n}\n\nvoid TestFilePathWatcher::FilePathWatcherCallback(const base::FilePath& path,\n bool error) {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));\n ASSERT_EQ(path_, path);\n if (error || condition_.Run(path)) {\n error_ = error;\n watcher_.reset();\n content::BrowserThread::PostTask(\n content::BrowserThread::UI,\n FROM_HERE,\n base::Bind(&TestFilePathWatcher::Done, base::Unretained(this)));\n }\n}\n\nvoid TestFilePathWatcher::Done() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n done_ = true;\n if (!quit_closure_.is_null())\n quit_closure_.Run();\n}\n\nbool TestFilePathWatcher::RunMessageLoopUntilConditionSatisfied() {\n if (done_)\n return !error_;\n base::RunLoop message_loop_runner;\n quit_closure_ = message_loop_runner.QuitClosure();\n message_loop_runner.Run();\n quit_closure_ = base::Closure();\n return !error_;\n}\n\nbool CopiedFilePresent(const base::FilePath& path) {\n int64 copy_size = 0;\n \/\/ If the file doesn't exist yet this will fail and we'll keep waiting.\n if (!file_util::GetFileSize(path, ©_size))\n return false;\n return (copy_size == kKeyboardTestFileSize);\n}\n\nbool DeletedFileGone(const base::FilePath& path) {\n return !file_util::PathExists(path);\n};\n\nIN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestFileDisplay) {\n AddMountPointToFakeDownloads();\n StartFileManager(\"\/Downloads\");\n\n ResultCatcher catcher;\n\n StartTest(\"file display\");\n\n ExtensionTestMessageListener listener(\"initial check done\", true);\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n CreateTestFile(\"newly added file.mp3\", 2000, \"4 Sep 1998 00:00:00\");\n listener.Reply(\"file added\");\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestKeyboardCopy) {\n AddMountPointToFakeDownloads();\n StartFileManager(\"\/Downloads\");\n\n base::FilePath copy_path =\n downloads_path_.AppendASCII(kKeyboardTestFileCopyName);\n ASSERT_FALSE(file_util::PathExists(copy_path));\n TestFilePathWatcher watcher(copy_path, base::Bind(CopiedFilePresent));\n watcher.StartAndWaitUntilReady();\n\n ResultCatcher catcher;\n StartTest(\"keyboard copy\");\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n\n ASSERT_TRUE(watcher.RunMessageLoopUntilConditionSatisfied());\n\n \/\/ Check that it was a copy, not a move.\n base::FilePath source_path =\n downloads_path_.AppendASCII(kKeyboardTestFileName);\n ASSERT_TRUE(file_util::PathExists(source_path));\n}\n\nIN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestKeyboardDelete) {\n AddMountPointToFakeDownloads();\n StartFileManager(\"\/Downloads\");\n\n base::FilePath delete_path =\n downloads_path_.AppendASCII(kKeyboardTestFileName);\n ASSERT_TRUE(file_util::PathExists(delete_path));\n TestFilePathWatcher watcher(delete_path, base::Bind(DeletedFileGone));\n watcher.StartAndWaitUntilReady();\n\n ResultCatcher catcher;\n StartTest(\"keyboard delete\");\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n\n ASSERT_TRUE(watcher.RunMessageLoopUntilConditionSatisfied());\n}\n\n} \/\/ namespace\ndrive: Simplify TestFilePathWatcher in file_manager_browsertest.cc\/\/ Copyright (c) 2013 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n\/\/ Browser test for basic Chrome OS file manager functionality:\n\/\/ - The file list is updated when a file is added externally to the Downloads\n\/\/ folder.\n\/\/ - Selecting a file and copy-pasting it with the keyboard copies the file.\n\/\/ - Selecting a file and pressing delete deletes it.\n\n#include \n#include \n\n#include \"base\/callback.h\"\n#include \"base\/file_util.h\"\n#include \"base\/files\/file_path.h\"\n#include \"base\/files\/file_path_watcher.h\"\n#include \"base\/platform_file.h\"\n#include \"base\/threading\/platform_thread.h\"\n#include \"base\/time.h\"\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/extensions\/component_loader.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_service.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/profiles\/profile.h\"\n#include \"chrome\/browser\/ui\/browser_window.h\"\n#include \"chrome\/browser\/ui\/tabs\/tab_strip_model.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/common\/extensions\/extension.h\"\n#include \"chrome\/test\/base\/ui_test_utils.h\"\n#include \"content\/public\/browser\/browser_context.h\"\n#include \"content\/public\/browser\/render_view_host.h\"\n#include \"net\/base\/escape.h\"\n#include \"webkit\/fileapi\/external_mount_points.h\"\n\nnamespace {\n\nconst char kFileManagerExtensionId[] = \"hhaomjibdihmijegdhdafkllkbggdgoj\";\n\nconst char kKeyboardTestFileName[] = \"world.mpeg\";\nconst int64 kKeyboardTestFileSize = 1000;\nconst char kKeyboardTestFileCopyName[] = \"world (1).mpeg\";\n\n\/\/ The base test class. Used by FileManagerBrowserLocalTest and\n\/\/ FileManagerBrowserDriveTest.\n\/\/ TODO(satorux): Add the latter: crbug.com\/224534.\nclass FileManagerBrowserTestBase : public ExtensionApiTest {\n protected:\n \/\/ Loads the file manager extension, navigating it to |directory_path| for\n \/\/ testing, and waits for it to finish initializing. This is invoked at the\n \/\/ start of each test (it crashes if run in SetUp).\n void StartFileManager(const std::string& directory_path);\n\n \/\/ Loads our testing extension and sends it a string identifying the current\n \/\/ test.\n void StartTest(const std::string& test_name);\n};\n\nvoid FileManagerBrowserTestBase::StartFileManager(\n const std::string& directory_path) {\n std::string file_manager_url =\n (std::string(\"chrome-extension:\/\/\") +\n kFileManagerExtensionId +\n \"\/main.html#\" +\n net::EscapeQueryParamValue(directory_path, false \/* use_plus *\/));\n\n ui_test_utils::NavigateToURL(browser(), GURL(file_manager_url));\n\n \/\/ This is sent by the file manager when it's finished initializing.\n ExtensionTestMessageListener listener(\"worker-initialized\", false);\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n}\n\nvoid FileManagerBrowserTestBase::StartTest(const std::string& test_name) {\n base::FilePath path = test_data_dir_.AppendASCII(\"file_manager_browsertest\");\n const extensions::Extension* extension = LoadExtensionAsComponent(path);\n ASSERT_TRUE(extension);\n\n ExtensionTestMessageListener listener(\"which test\", true);\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n listener.Reply(test_name);\n}\n\n\/\/ The boolean parameter, retrieved by GetParam(), is true if testing in the\n\/\/ guest mode. See SetUpCommandLine() below for details.\nclass FileManagerBrowserLocalTest : public FileManagerBrowserTestBase,\n public ::testing::WithParamInterface {\n public:\n virtual void SetUp() OVERRIDE {\n extensions::ComponentLoader::EnableBackgroundExtensionsForTesting();\n\n ASSERT_TRUE(tmp_dir_.CreateUniqueTempDir());\n downloads_path_ = tmp_dir_.path().Append(\"Downloads\");\n ASSERT_TRUE(file_util::CreateDirectory(downloads_path_));\n\n CreateTestFile(\"hello.txt\", 123, \"4 Sep 1998 12:34:56\");\n CreateTestFile(\"My Desktop Background.png\", 1024, \"18 Jan 2038 01:02:03\");\n CreateTestFile(kKeyboardTestFileName, kKeyboardTestFileSize,\n \"4 July 2012 10:35:00\");\n CreateTestDirectory(\"photos\", \"1 Jan 1980 23:59:59\");\n \/\/ Files starting with . are filtered out in\n \/\/ file_manager\/js\/directory_contents.js, so this should not be shown.\n CreateTestDirectory(\".warez\", \"26 Oct 1985 13:39\");\n\n ExtensionApiTest::SetUp();\n }\n\n virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {\n bool in_guest_mode = GetParam();\n if (in_guest_mode) {\n command_line->AppendSwitch(switches::kGuestSession);\n command_line->AppendSwitch(switches::kIncognito);\n }\n ExtensionApiTest::SetUpCommandLine(command_line);\n }\n\n protected:\n \/\/ Creates a file with the given |name|, |length|, and |modification_time|.\n void CreateTestFile(const std::string& name,\n int length,\n const std::string& modification_time);\n\n \/\/ Creates an empty directory with the given |name| and |modification_time|.\n void CreateTestDirectory(const std::string& name,\n const std::string& modification_time);\n\n \/\/ Add a mount point to the fake Downloads directory. Should be called\n \/\/ before StartFileManager().\n void AddMountPointToFakeDownloads();\n\n \/\/ Path to the fake Downloads directory used in the test.\n base::FilePath downloads_path_;\n\n private:\n base::ScopedTempDir tmp_dir_;\n};\n\nINSTANTIATE_TEST_CASE_P(InGuestMode,\n FileManagerBrowserLocalTest,\n ::testing::Values(true));\n\nINSTANTIATE_TEST_CASE_P(InNonGuestMode,\n FileManagerBrowserLocalTest,\n ::testing::Values(false));\n\nvoid FileManagerBrowserLocalTest::CreateTestFile(\n const std::string& name,\n int length,\n const std::string& modification_time) {\n ASSERT_GE(length, 0);\n base::FilePath path = downloads_path_.AppendASCII(name);\n int flags = base::PLATFORM_FILE_CREATE | base::PLATFORM_FILE_WRITE;\n bool created = false;\n base::PlatformFileError error = base::PLATFORM_FILE_ERROR_FAILED;\n base::PlatformFile file = base::CreatePlatformFile(path, flags,\n &created, &error);\n ASSERT_TRUE(created);\n ASSERT_FALSE(error) << error;\n ASSERT_TRUE(base::TruncatePlatformFile(file, length));\n ASSERT_TRUE(base::ClosePlatformFile(file));\n base::Time time;\n ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time));\n ASSERT_TRUE(file_util::SetLastModifiedTime(path, time));\n}\n\nvoid FileManagerBrowserLocalTest::CreateTestDirectory(\n const std::string& name,\n const std::string& modification_time) {\n base::FilePath path = downloads_path_.AppendASCII(name);\n ASSERT_TRUE(file_util::CreateDirectory(path));\n base::Time time;\n ASSERT_TRUE(base::Time::FromString(modification_time.c_str(), &time));\n ASSERT_TRUE(file_util::SetLastModifiedTime(path, time));\n}\n\nvoid FileManagerBrowserLocalTest::AddMountPointToFakeDownloads() {\n \/\/ Install our fake Downloads mount point first.\n fileapi::ExternalMountPoints* mount_points =\n content::BrowserContext::GetMountPoints(profile());\n ASSERT_TRUE(mount_points->RevokeFileSystem(\"Downloads\"));\n ASSERT_TRUE(mount_points->RegisterFileSystem(\n \"Downloads\", fileapi::kFileSystemTypeNativeLocal, downloads_path_));\n}\n\n\/\/ Monitors changes to a single file until the supplied condition callback\n\/\/ returns true. Usage:\n\/\/ TestFilePathWatcher watcher(path_to_file, MyConditionCallback);\n\/\/ watcher.StartAndWaitUntilReady();\n\/\/ ... trigger filesystem modification ...\n\/\/ watcher.RunMessageLoopUntilConditionSatisfied();\nclass TestFilePathWatcher {\n public:\n typedef base::Callback\n ConditionCallback;\n\n \/\/ Stores the supplied |path| and |condition| for later use (no side effects).\n TestFilePathWatcher(const base::FilePath& path,\n const ConditionCallback& condition);\n\n \/\/ Waits (running a message pump) until the callback returns true or\n \/\/ FilePathWatcher reports an error. Return true on success.\n bool RunMessageLoopUntilConditionSatisfied();\n\n private:\n \/\/ Starts the FilePathWatcher to watch the target file. Also check if the\n \/\/ condition is already met.\n void StartWatching();\n\n \/\/ FilePathWatcher callback (on the FILE thread). Posts Done() to the UI\n \/\/ thread when the condition is satisfied or there is an error.\n void FilePathWatcherCallback(const base::FilePath& path, bool error);\n\n const base::FilePath path_;\n ConditionCallback condition_;\n scoped_ptr watcher_;\n base::RunLoop run_loop_;\n base::Closure quit_closure_;\n bool failed_;\n};\n\nTestFilePathWatcher::TestFilePathWatcher(const base::FilePath& path,\n const ConditionCallback& condition)\n : path_(path),\n condition_(condition),\n quit_closure_(run_loop_.QuitClosure()),\n failed_(false) {\n}\n\nvoid TestFilePathWatcher::StartWatching() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));\n\n watcher_.reset(new base::FilePathWatcher);\n bool ok = watcher_->Watch(\n path_, false \/*recursive*\/,\n base::Bind(&TestFilePathWatcher::FilePathWatcherCallback,\n base::Unretained(this)));\n DCHECK(ok);\n\n \/\/ If the condition was already met before FilePathWatcher was launched,\n \/\/ FilePathWatcher won't be able to detect a change, so check the condition\n \/\/ here.\n if (condition_.Run(path_)) {\n watcher_.reset();\n content::BrowserThread::PostTask(content::BrowserThread::UI,\n FROM_HERE,\n quit_closure_);\n return;\n }\n}\n\nvoid TestFilePathWatcher::FilePathWatcherCallback(const base::FilePath& path,\n bool failed) {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::FILE));\n DCHECK_EQ(path_.value(), path.value());\n\n if (failed || condition_.Run(path)) {\n failed_ = failed;\n watcher_.reset();\n content::BrowserThread::PostTask(content::BrowserThread::UI,\n FROM_HERE,\n quit_closure_);\n }\n}\n\nbool TestFilePathWatcher::RunMessageLoopUntilConditionSatisfied() {\n DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));\n\n content::BrowserThread::PostTask(\n content::BrowserThread::FILE,\n FROM_HERE,\n base::Bind(&TestFilePathWatcher::StartWatching,\n base::Unretained(this)));\n\n \/\/ Wait until the condition is met.\n run_loop_.Run();\n return !failed_;\n}\n\n\/\/ Returns true if a file with the given size is present at |path|.\nbool FilePresentWithSize(const int64 file_size,\n const base::FilePath& path) {\n int64 copy_size = 0;\n \/\/ If the file doesn't exist yet this will fail and we'll keep waiting.\n if (!file_util::GetFileSize(path, ©_size))\n return false;\n return (copy_size == file_size);\n}\n\n\/\/ Returns true if a file is not present at |path|.\nbool FileNotPresent(const base::FilePath& path) {\n return !file_util::PathExists(path);\n};\n\nIN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestFileDisplay) {\n AddMountPointToFakeDownloads();\n StartFileManager(\"\/Downloads\");\n\n ResultCatcher catcher;\n\n StartTest(\"file display\");\n\n ExtensionTestMessageListener listener(\"initial check done\", true);\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n CreateTestFile(\"newly added file.mp3\", 2000, \"4 Sep 1998 00:00:00\");\n listener.Reply(\"file added\");\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n}\n\nIN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestKeyboardCopy) {\n AddMountPointToFakeDownloads();\n StartFileManager(\"\/Downloads\");\n\n base::FilePath copy_path =\n downloads_path_.AppendASCII(kKeyboardTestFileCopyName);\n ASSERT_FALSE(file_util::PathExists(copy_path));\n\n ResultCatcher catcher;\n StartTest(\"keyboard copy\");\n\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n\n TestFilePathWatcher watcher(\n copy_path,\n base::Bind(FilePresentWithSize, kKeyboardTestFileSize));\n ASSERT_TRUE(watcher.RunMessageLoopUntilConditionSatisfied());\n\n \/\/ Check that it was a copy, not a move.\n base::FilePath source_path =\n downloads_path_.AppendASCII(kKeyboardTestFileName);\n ASSERT_TRUE(file_util::PathExists(source_path));\n}\n\nIN_PROC_BROWSER_TEST_P(FileManagerBrowserLocalTest, TestKeyboardDelete) {\n AddMountPointToFakeDownloads();\n StartFileManager(\"\/Downloads\");\n\n base::FilePath delete_path =\n downloads_path_.AppendASCII(kKeyboardTestFileName);\n ASSERT_TRUE(file_util::PathExists(delete_path));\n\n ResultCatcher catcher;\n StartTest(\"keyboard delete\");\n ASSERT_TRUE(catcher.GetNextResult()) << catcher.message();\n\n TestFilePathWatcher watcher(delete_path,\n base::Bind(FileNotPresent));\n ASSERT_TRUE(watcher.RunMessageLoopUntilConditionSatisfied());\n}\n\n} \/\/ namespace\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/run_loop.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/platform_app_browsertest_util.h\"\n#include \"chrome\/browser\/extensions\/shell_window_registry.h\"\n#include \"chrome\/browser\/ui\/base_window.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/extensions\/native_app_window.h\"\n#include \"chrome\/browser\/ui\/extensions\/shell_window.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"ui\/gfx\/rect.h\"\n\n#ifdef TOOLKIT_GTK\n#include \"content\/public\/test\/test_utils.h\"\n#endif\n\nnamespace {\n\nclass TestShellWindowRegistryObserver\n : public extensions::ShellWindowRegistry::Observer {\n public:\n explicit TestShellWindowRegistryObserver(Profile* profile)\n : profile_(profile),\n icon_updates_(0) {\n extensions::ShellWindowRegistry::Get(profile_)->AddObserver(this);\n }\n virtual ~TestShellWindowRegistryObserver() {\n extensions::ShellWindowRegistry::Get(profile_)->RemoveObserver(this);\n }\n\n \/\/ Overridden from ShellWindowRegistry::Observer:\n virtual void OnShellWindowAdded(ShellWindow* shell_window) OVERRIDE {}\n virtual void OnShellWindowIconChanged(ShellWindow* shell_window) OVERRIDE {\n ++icon_updates_;\n }\n virtual void OnShellWindowRemoved(ShellWindow* shell_window) OVERRIDE {\n }\n\n int icon_updates() { return icon_updates_; }\n\n private:\n Profile* profile_;\n int icon_updates_;\n\n DISALLOW_COPY_AND_ASSIGN(TestShellWindowRegistryObserver);\n};\n\n} \/\/ namespace\n\nnamespace extensions {\n\n\/\/ Flaky, http:\/\/crbug.com\/164735 .\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DISABLED_WindowsApiBounds) {\n ExtensionTestMessageListener background_listener(\"background_ok\", false);\n ExtensionTestMessageListener ready_listener(\"ready\", true \/* will_reply *\/);\n ExtensionTestMessageListener success_listener(\"success\", false);\n\n LoadAndLaunchPlatformApp(\"windows_api_bounds\");\n ASSERT_TRUE(background_listener.WaitUntilSatisfied());\n ASSERT_TRUE(ready_listener.WaitUntilSatisfied());\n ShellWindow* window = GetFirstShellWindow();\n\n gfx::Rect new_bounds(100, 200, 300, 400);\n new_bounds.Inset(-window->GetBaseWindow()->GetFrameInsets());\n window->GetBaseWindow()->SetBounds(new_bounds);\n\n \/\/ TODO(jeremya\/asargent) figure out why in GTK the window doesn't end up\n \/\/ with exactly the bounds we set. Is it a bug in our shell window\n \/\/ implementation? crbug.com\/160252\n#ifdef TOOLKIT_GTK\n int slop = 50;\n#else\n int slop = 0;\n#endif \/\/ !TOOLKIT_GTK\n\n ready_listener.Reply(base::IntToString(slop));\n\n#ifdef TOOLKIT_GTK\n \/\/ TODO(asargent)- this is here to help track down the root cause of\n \/\/ crbug.com\/164735.\n {\n gfx::Rect last_bounds;\n while (!success_listener.was_satisfied()) {\n gfx::Rect current_bounds = window->GetBaseWindow()->GetBounds();\n if (current_bounds != last_bounds) {\n LOG(INFO) << \"new bounds: \" << current_bounds.ToString();\n }\n last_bounds = current_bounds;\n content::RunAllPendingInMessageLoop();\n }\n }\n#endif\n\n ASSERT_TRUE(success_listener.WaitUntilSatisfied());\n}\n\n\/\/ Tests chrome.app.window.setIcon.\nIN_PROC_BROWSER_TEST_F(ExperimentalPlatformAppBrowserTest, WindowsApiSetIcon) {\n scoped_ptr test_observer(\n new TestShellWindowRegistryObserver(browser()->profile()));\n ExtensionTestMessageListener listener(\"IconSet\", false);\n LoadAndLaunchPlatformApp(\"windows_api_set_icon\");\n EXPECT_EQ(0, test_observer->icon_updates());\n \/\/ Wait until the icon load has been requested.\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n \/\/ Now wait until the WebContent has decoded the icon and chrome has\n \/\/ processed it. This needs to be in a loop since the renderer runs in a\n \/\/ different process.\n while (test_observer->icon_updates() < 1) {\n base::RunLoop run_loop;\n run_loop.RunUntilIdle();\n }\n ShellWindow* shell_window = GetFirstShellWindow();\n ASSERT_TRUE(shell_window);\n EXPECT_NE(std::string::npos,\n shell_window->app_icon_url().spec().find(\"icon.png\"));\n EXPECT_EQ(1, test_observer->icon_updates());\n}\n\n\/\/ TODO(asargent) - Figure out what to do about the fact that minimize events\n\/\/ don't work under ubuntu unity.\n\/\/ (crbug.com\/162794 and https:\/\/bugs.launchpad.net\/unity\/+bug\/998073).\n\/\/ TODO(linux_aura) http:\/\/crbug.com\/163931\n#if (defined(TOOLKIT_VIEWS) || defined(OS_MACOSX)) && !(defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA))\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, WindowsApiProperties) {\n EXPECT_TRUE(\n RunExtensionTest(\"platform_apps\/windows_api_properties\")) << message_;\n}\n\n#endif \/\/ defined(TOOLKIT_VIEWS)\n\n} \/\/ namespace extensions\nDisable PlatformAppBrowserTest.WindowsApiProperties on mac\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/run_loop.h\"\n#include \"base\/strings\/string_number_conversions.h\"\n#include \"chrome\/browser\/extensions\/extension_test_message_listener.h\"\n#include \"chrome\/browser\/extensions\/platform_app_browsertest_util.h\"\n#include \"chrome\/browser\/extensions\/shell_window_registry.h\"\n#include \"chrome\/browser\/ui\/base_window.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/extensions\/native_app_window.h\"\n#include \"chrome\/browser\/ui\/extensions\/shell_window.h\"\n#include \"chrome\/test\/base\/testing_profile.h\"\n#include \"ui\/gfx\/rect.h\"\n\n#ifdef TOOLKIT_GTK\n#include \"content\/public\/test\/test_utils.h\"\n#endif\n\nnamespace {\n\nclass TestShellWindowRegistryObserver\n : public extensions::ShellWindowRegistry::Observer {\n public:\n explicit TestShellWindowRegistryObserver(Profile* profile)\n : profile_(profile),\n icon_updates_(0) {\n extensions::ShellWindowRegistry::Get(profile_)->AddObserver(this);\n }\n virtual ~TestShellWindowRegistryObserver() {\n extensions::ShellWindowRegistry::Get(profile_)->RemoveObserver(this);\n }\n\n \/\/ Overridden from ShellWindowRegistry::Observer:\n virtual void OnShellWindowAdded(ShellWindow* shell_window) OVERRIDE {}\n virtual void OnShellWindowIconChanged(ShellWindow* shell_window) OVERRIDE {\n ++icon_updates_;\n }\n virtual void OnShellWindowRemoved(ShellWindow* shell_window) OVERRIDE {\n }\n\n int icon_updates() { return icon_updates_; }\n\n private:\n Profile* profile_;\n int icon_updates_;\n\n DISALLOW_COPY_AND_ASSIGN(TestShellWindowRegistryObserver);\n};\n\n} \/\/ namespace\n\nnamespace extensions {\n\n\/\/ Flaky, http:\/\/crbug.com\/164735 .\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DISABLED_WindowsApiBounds) {\n ExtensionTestMessageListener background_listener(\"background_ok\", false);\n ExtensionTestMessageListener ready_listener(\"ready\", true \/* will_reply *\/);\n ExtensionTestMessageListener success_listener(\"success\", false);\n\n LoadAndLaunchPlatformApp(\"windows_api_bounds\");\n ASSERT_TRUE(background_listener.WaitUntilSatisfied());\n ASSERT_TRUE(ready_listener.WaitUntilSatisfied());\n ShellWindow* window = GetFirstShellWindow();\n\n gfx::Rect new_bounds(100, 200, 300, 400);\n new_bounds.Inset(-window->GetBaseWindow()->GetFrameInsets());\n window->GetBaseWindow()->SetBounds(new_bounds);\n\n \/\/ TODO(jeremya\/asargent) figure out why in GTK the window doesn't end up\n \/\/ with exactly the bounds we set. Is it a bug in our shell window\n \/\/ implementation? crbug.com\/160252\n#ifdef TOOLKIT_GTK\n int slop = 50;\n#else\n int slop = 0;\n#endif \/\/ !TOOLKIT_GTK\n\n ready_listener.Reply(base::IntToString(slop));\n\n#ifdef TOOLKIT_GTK\n \/\/ TODO(asargent)- this is here to help track down the root cause of\n \/\/ crbug.com\/164735.\n {\n gfx::Rect last_bounds;\n while (!success_listener.was_satisfied()) {\n gfx::Rect current_bounds = window->GetBaseWindow()->GetBounds();\n if (current_bounds != last_bounds) {\n LOG(INFO) << \"new bounds: \" << current_bounds.ToString();\n }\n last_bounds = current_bounds;\n content::RunAllPendingInMessageLoop();\n }\n }\n#endif\n\n ASSERT_TRUE(success_listener.WaitUntilSatisfied());\n}\n\n\/\/ Tests chrome.app.window.setIcon.\nIN_PROC_BROWSER_TEST_F(ExperimentalPlatformAppBrowserTest, WindowsApiSetIcon) {\n scoped_ptr test_observer(\n new TestShellWindowRegistryObserver(browser()->profile()));\n ExtensionTestMessageListener listener(\"IconSet\", false);\n LoadAndLaunchPlatformApp(\"windows_api_set_icon\");\n EXPECT_EQ(0, test_observer->icon_updates());\n \/\/ Wait until the icon load has been requested.\n ASSERT_TRUE(listener.WaitUntilSatisfied());\n \/\/ Now wait until the WebContent has decoded the icon and chrome has\n \/\/ processed it. This needs to be in a loop since the renderer runs in a\n \/\/ different process.\n while (test_observer->icon_updates() < 1) {\n base::RunLoop run_loop;\n run_loop.RunUntilIdle();\n }\n ShellWindow* shell_window = GetFirstShellWindow();\n ASSERT_TRUE(shell_window);\n EXPECT_NE(std::string::npos,\n shell_window->app_icon_url().spec().find(\"icon.png\"));\n EXPECT_EQ(1, test_observer->icon_updates());\n}\n\n\/\/ TODO(asargent) - Figure out what to do about the fact that minimize events\n\/\/ don't work under ubuntu unity.\n\/\/ (crbug.com\/162794 and https:\/\/bugs.launchpad.net\/unity\/+bug\/998073).\n\/\/ TODO(linux_aura) http:\/\/crbug.com\/163931\n#if defined(TOOLKIT_VIEWS) && !(defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA))\n\nIN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, WindowsApiProperties) {\n EXPECT_TRUE(\n RunExtensionTest(\"platform_apps\/windows_api_properties\")) << message_;\n}\n\n#endif \/\/ defined(TOOLKIT_VIEWS)\n\n} \/\/ namespace extensions\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_webstore_private_api.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nclass ExtensionGalleryInstallApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryURL,\n \"http:\/\/www.example.com\");\n }\n\n bool RunInstallTest(const std::string& page) {\n std::string base_url = base::StringPrintf(\n \"http:\/\/www.example.com:%u\/files\/extensions\/\",\n test_server()->host_port_pair().port());\n\n std::string testing_install_base_url = base_url;\n testing_install_base_url += \"good.crx\";\n CompleteInstallFunction::SetTestingInstallBaseUrl(\n testing_install_base_url.c_str());\n\n std::string page_url = base_url;\n page_url += \"api_test\/extension_gallery_install\/\" + page;\n\n return RunPageTest(page_url.c_str());\n }\n};\n\n\/\/ http:\/\/crbug.com\/55642 - failing on XP.\n#if defined (OS_WIN)\n#define MAYBE_InstallAndUninstall FLAKY_InstallAndUninstall\n#else\n#define MAYBE_InstallAndUninstall InstallAndUninstall\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,\n MAYBE_InstallAndUninstall) {\n host_resolver()->AddRule(\"www.example.com\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n BeginInstallFunction::SetIgnoreUserGestureForTests(true);\n ASSERT_TRUE(RunInstallTest(\"test.html\"));\n ASSERT_TRUE(RunInstallTest(\"complete_without_begin.html\"));\n ASSERT_TRUE(RunInstallTest(\"invalid_begin.html\"));\n\n BeginInstallFunction::SetIgnoreUserGestureForTests(false);\n ASSERT_TRUE(RunInstallTest(\"no_user_gesture.html\"));\n}\nRe-disable ExtensionGalleryInstallApiTest.InstallAndUninstall on windows.\/\/ Copyright (c) 2010 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"base\/stringprintf.h\"\n#include \"chrome\/browser\/extensions\/extension_apitest.h\"\n#include \"chrome\/browser\/extensions\/extension_webstore_private_api.h\"\n#include \"chrome\/common\/chrome_switches.h\"\n#include \"chrome\/test\/ui_test_utils.h\"\n#include \"net\/base\/mock_host_resolver.h\"\n\nclass ExtensionGalleryInstallApiTest : public ExtensionApiTest {\n public:\n void SetUpCommandLine(CommandLine* command_line) {\n ExtensionApiTest::SetUpCommandLine(command_line);\n command_line->AppendSwitchASCII(switches::kAppsGalleryURL,\n \"http:\/\/www.example.com\");\n }\n\n bool RunInstallTest(const std::string& page) {\n std::string base_url = base::StringPrintf(\n \"http:\/\/www.example.com:%u\/files\/extensions\/\",\n test_server()->host_port_pair().port());\n\n std::string testing_install_base_url = base_url;\n testing_install_base_url += \"good.crx\";\n CompleteInstallFunction::SetTestingInstallBaseUrl(\n testing_install_base_url.c_str());\n\n std::string page_url = base_url;\n page_url += \"api_test\/extension_gallery_install\/\" + page;\n\n return RunPageTest(page_url.c_str());\n }\n};\n\n\/\/ http:\/\/crbug.com\/55642 - failing on XP.\n#if defined (OS_WIN)\n#define MAYBE_InstallAndUninstall DISABLED_InstallAndUninstall\n#else\n#define MAYBE_InstallAndUninstall InstallAndUninstall\n#endif\nIN_PROC_BROWSER_TEST_F(ExtensionGalleryInstallApiTest,\n MAYBE_InstallAndUninstall) {\n host_resolver()->AddRule(\"www.example.com\", \"127.0.0.1\");\n ASSERT_TRUE(test_server()->Start());\n\n BeginInstallFunction::SetIgnoreUserGestureForTests(true);\n ASSERT_TRUE(RunInstallTest(\"test.html\"));\n ASSERT_TRUE(RunInstallTest(\"complete_without_begin.html\"));\n ASSERT_TRUE(RunInstallTest(\"invalid_begin.html\"));\n\n BeginInstallFunction::SetIgnoreUserGestureForTests(false);\n ASSERT_TRUE(RunInstallTest(\"no_user_gesture.html\"));\n}\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/location_bar\/action_box_button_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/toolbar\/action_box_menu_model.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/action_box_menu.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\nnamespace {\n\n\/\/ Colors used for button backgrounds.\nconst SkColor kNormalBackgroundColor = SkColorSetRGB(255, 255, 255);\nconst SkColor kHotBackgroundColor = SkColorSetRGB(239, 239, 239);\nconst SkColor kPushedBackgroundColor = SkColorSetRGB(207, 207, 207);\n\nconst SkColor kNormalBorderColor = SkColorSetRGB(255, 255, 255);\nconst SkColor kHotBorderColor = SkColorSetRGB(223, 223, 223);\nconst SkColor kPushedBorderColor = SkColorSetRGB(191, 191, 191);\n\n} \/\/ namespace\n\n\nActionBoxButtonView::ActionBoxButtonView(Browser* browser)\n : views::MenuButton(NULL, string16(), this, false),\n browser_(browser) {\n set_id(VIEW_ID_ACTION_BOX_BUTTON);\n SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_ACTION_BOX_BUTTON));\n SetIcon(*ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(\n IDR_ACTION_BOX_BUTTON));\n set_accessibility_focusable(true);\n set_border(NULL);\n}\n\nActionBoxButtonView::~ActionBoxButtonView() {\n}\n\nSkColor ActionBoxButtonView::GetBackgroundColor() {\n switch (state()) {\n case BS_PUSHED:\n return kPushedBackgroundColor;\n case BS_HOT:\n return kHotBackgroundColor;\n default:\n return kNormalBackgroundColor;\n }\n}\n\nSkColor ActionBoxButtonView::GetBorderColor() {\n switch (state()) {\n case BS_PUSHED:\n return kPushedBorderColor;\n case BS_HOT:\n return kHotBorderColor;\n default:\n return kNormalBorderColor;\n }\n}\n\nvoid ActionBoxButtonView::GetAccessibleState(ui::AccessibleViewState* state) {\n MenuButton::GetAccessibleState(state);\n state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_ACTION_BOX_BUTTON);\n}\n\nvoid ActionBoxButtonView::OnMenuButtonClicked(View* source,\n const gfx::Point& point) {\n ActionBoxMenuModel model(browser_);\n ActionBoxMenu action_box_menu(browser_, &model);\n action_box_menu.Init();\n action_box_menu.RunMenu(this);\n}\nReplaced hardcoded background color in action box button with location bar background. May fix 146874 as well, I cannot verify\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"chrome\/browser\/ui\/views\/location_bar\/action_box_button_view.h\"\n\n#include \"base\/utf_string_conversions.h\"\n#include \"chrome\/browser\/ui\/browser.h\"\n#include \"chrome\/browser\/ui\/toolbar\/action_box_menu_model.h\"\n#include \"chrome\/browser\/ui\/view_ids.h\"\n#include \"chrome\/browser\/ui\/views\/action_box_menu.h\"\n#include \"chrome\/browser\/ui\/views\/location_bar\/location_bar_view.h\"\n#include \"grit\/generated_resources.h\"\n#include \"grit\/theme_resources.h\"\n#include \"ui\/base\/accessibility\/accessible_view_state.h\"\n#include \"ui\/base\/l10n\/l10n_util.h\"\n#include \"ui\/base\/resource\/resource_bundle.h\"\n\nnamespace {\n\n\/\/ Colors used for button backgrounds and border.\nconst SkColor kHotBackgroundColor = SkColorSetRGB(239, 239, 239);\nconst SkColor kPushedBackgroundColor = SkColorSetRGB(207, 207, 207);\n\nconst SkColor kHotBorderColor = SkColorSetRGB(223, 223, 223);\nconst SkColor kPushedBorderColor = SkColorSetRGB(191, 191, 191);\n\n} \/\/ namespace\n\n\nActionBoxButtonView::ActionBoxButtonView(Browser* browser)\n : views::MenuButton(NULL, string16(), this, false),\n browser_(browser) {\n set_id(VIEW_ID_ACTION_BOX_BUTTON);\n SetTooltipText(l10n_util::GetStringUTF16(IDS_TOOLTIP_ACTION_BOX_BUTTON));\n SetIcon(*ui::ResourceBundle::GetSharedInstance().GetImageSkiaNamed(\n IDR_ACTION_BOX_BUTTON));\n set_accessibility_focusable(true);\n set_border(NULL);\n}\n\nActionBoxButtonView::~ActionBoxButtonView() {\n}\n\nSkColor ActionBoxButtonView::GetBackgroundColor() {\n switch (state()) {\n case BS_PUSHED:\n return kPushedBackgroundColor;\n case BS_HOT:\n return kHotBackgroundColor;\n default:\n return LocationBarView::GetColor(ToolbarModel::NONE,\n LocationBarView::BACKGROUND);\n }\n}\n\nSkColor ActionBoxButtonView::GetBorderColor() {\n switch (state()) {\n case BS_PUSHED:\n return kPushedBorderColor;\n case BS_HOT:\n return kHotBorderColor;\n default:\n return GetBackgroundColor();\n }\n}\n\nvoid ActionBoxButtonView::GetAccessibleState(ui::AccessibleViewState* state) {\n MenuButton::GetAccessibleState(state);\n state->name = l10n_util::GetStringUTF16(IDS_ACCNAME_ACTION_BOX_BUTTON);\n}\n\nvoid ActionBoxButtonView::OnMenuButtonClicked(View* source,\n const gfx::Point& point) {\n ActionBoxMenuModel model(browser_);\n ActionBoxMenu action_box_menu(browser_, &model);\n action_box_menu.Init();\n action_box_menu.RunMenu(this);\n}\n<|endoftext|>"} {"text":"\/*\nCopyright 2014 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL-ast-CPP.hpp\"\n\n#ifndef _REQL_HPP\n#define _REQL_HPP\n\nclass ReQLConnection {\n};\n\nclass ReQL : ReQL_ast {\n};\n\n#endif\nAdd c++ connect and close methods.\/*\nCopyright 2014 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL-ast-CPP.hpp\"\n\n#ifndef _REQL_HPP\n#define _REQL_HPP\n\nclass ReQLConnection {\npublic:\n ReQLConnection();\n ReQLConnection(std::string);\n ReQLConnection(std::string, std::string);\n ReQLConnection(std::string, std::string, std::string);\n\n int close();\n};\n\nReQLConnection connect();\nReQLConnection connect(std::string);\nReQLConnection connect(std::string, std::string);\nReQLConnection connect(std::string, std::string, std::string);\n\nclass ReQL : public ReQL_ast {\n};\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost;\n\nstatic void write(int fd, const char *str)\n{\n\tsize_t len = strlen(str);\n\tssize_t written = write(fd, str, len);\n\tif (written < 0 || (size_t)written != len) {\n\t\tstd::cerr << \"Error writing pipe.\" << std::endl;\n\t\texit(1);\n\t}\n}\n\nint main(int argc, const char ** argv)\n{\n\tstatic const regex regex_ip(\"\\\\d{1,3}.\\\\d{1,3}.\\\\d{1,3}.\\\\d{1,3}\");\n\tstatic const regex regex_user(\"[a-zA-Z]+\");\n\t\n\t\n\tif (argc != 5) {\n\t\tstd::cerr << \"Usage: \" << argv[0] << \" \" << std::endl;\n\t\treturn 1;\n\t}\n\t\n\t\/* Obtain and validate inpit *\/\n\tstd::string user = argv[1];\n\tstd::string password = argv[2];\n\tstd::string domain = argv[3];\n\tstd::string ip = argv[4];\n\t\n\tif (!regex_match(ip, regex_ip)) {\n\t\tstd::cerr << \"Invalid IP address \" << ip << \".\" << std::endl;\n\t\texit(1);\n\t}\n\tif (!regex_match(user, regex_user)) {\n\t\tstd::cerr << \"Invalid username \" << user << \".\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t\/* read configuration *\/\n\tproperty_tree::ptree config;\n\tproperty_tree::ini_parser::read_ini(CONFIG_FILE, config);\n\tstd::string nsupdate = config.get(\"nsupdate\");\n\tstd::string keyfile = config.get(\"key\");\n\t\n\t\/* Check username, password, domain *\/\n\toptional correct_password = config.get_optional(user+\".password\");\n\tif (!correct_password || *correct_password != password) {\n\t\tstd::cerr << \"Username or password incorrect.\" << std::endl;\n\t\texit(1);\n\t}\n\tif (config.get(user+\".domain\") != domain) {\n\t\tstd::cerr << \"Domain incorrect.\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t\/* preapre the pipe *\/\n\tint pipe_ends[] = {0,0};\n\tpipe(pipe_ends);\n\n\t\/* Launch nsupdate *\/\n\tpid_t child_pid = fork();\n\tif (child_pid < 0) {\n\t\tstd::cerr << \"Error while forking.\" << std::endl;\n\t\texit(1);\n\t}\n\tif (child_pid == 0) {\n\t\t\/* We're in the child *\/\n\t\t\/* Close write end, use read and as stdin *\/\n\t\tclose(pipe_ends[1]);\n\t\tdup2(pipe_ends[0], fileno(stdin));\n\t\t\/* exec nsupdate *\/\n\t\texecl(nsupdate.c_str(), nsupdate.c_str(), \"-k\", keyfile.c_str(), NULL);\n\t\t\/* There was an error *\/\n\t\tstd::cerr << \"There was an error executing nsupdate.\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t\/* Send it the command *\/\n\twrite(pipe_ends[1], \"server localhost\\n\");\n\t\n\twrite(pipe_ends[1], \"update delete \");\n\twrite(pipe_ends[1], domain.c_str());\n\twrite(pipe_ends[1], \".\\n\");\n\t\n\twrite(pipe_ends[1], \"update add \");\n\twrite(pipe_ends[1], domain.c_str());\n\twrite(pipe_ends[1], \". 60 A \");\n\twrite(pipe_ends[1], ip.c_str());\n\twrite(pipe_ends[1], \"\\n\");\n\t\n\twrite(pipe_ends[1], \"send\\n\");\n\t\n\t\/* Close both ends *\/\n\tclose(pipe_ends[0]);\n\tclose(pipe_ends[1]);\n\t\n\t\/* Wait for child to be gone *\/\n\tint child_status;\n\twaitpid(child_pid, &child_status, 0);\n\tif (child_status != 0) {\n\t\tstd::cerr << \"There was an error in the child.\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\treturn 0;\n}\ncast last argument of execl; check for errors in dup2#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n\nusing namespace boost;\n\nstatic void write(int fd, const char *str)\n{\n\tsize_t len = strlen(str);\n\tssize_t written = write(fd, str, len);\n\tif (written < 0 || (size_t)written != len) {\n\t\tstd::cerr << \"Error writing pipe.\" << std::endl;\n\t\texit(1);\n\t}\n}\n\nint main(int argc, const char ** argv)\n{\n\tstatic const regex regex_ip(\"\\\\d{1,3}.\\\\d{1,3}.\\\\d{1,3}.\\\\d{1,3}\");\n\tstatic const regex regex_user(\"[a-zA-Z]+\");\n\t\n\t\n\tif (argc != 5) {\n\t\tstd::cerr << \"Usage: \" << argv[0] << \" \" << std::endl;\n\t\treturn 1;\n\t}\n\t\n\t\/* Obtain and validate inpit *\/\n\tstd::string user = argv[1];\n\tstd::string password = argv[2];\n\tstd::string domain = argv[3];\n\tstd::string ip = argv[4];\n\t\n\tif (!regex_match(ip, regex_ip)) {\n\t\tstd::cerr << \"Invalid IP address \" << ip << \".\" << std::endl;\n\t\texit(1);\n\t}\n\tif (!regex_match(user, regex_user)) {\n\t\tstd::cerr << \"Invalid username \" << user << \".\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t\/* read configuration *\/\n\tproperty_tree::ptree config;\n\tproperty_tree::ini_parser::read_ini(CONFIG_FILE, config);\n\tstd::string nsupdate = config.get(\"nsupdate\");\n\tstd::string keyfile = config.get(\"key\");\n\t\n\t\/* Check username, password, domain *\/\n\toptional correct_password = config.get_optional(user+\".password\");\n\tif (!correct_password || *correct_password != password) {\n\t\tstd::cerr << \"Username or password incorrect.\" << std::endl;\n\t\texit(1);\n\t}\n\tif (config.get(user+\".domain\") != domain) {\n\t\tstd::cerr << \"Domain incorrect.\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t\/* preapre the pipe *\/\n\tint pipe_ends[] = {0,0};\n\tpipe(pipe_ends);\n\n\t\/* Launch nsupdate *\/\n\tpid_t child_pid = fork();\n\tif (child_pid < 0) {\n\t\tstd::cerr << \"Error while forking.\" << std::endl;\n\t\texit(1);\n\t}\n\tif (child_pid == 0) {\n\t\t\/* We're in the child *\/\n\t\t\/* Close write end, use read and as stdin *\/\n\t\tclose(pipe_ends[1]);\n\t\tif (dup2(pipe_ends[0], fileno(stdin)) < 0) {\n\t\t\tstd::cerr << \"There was an error redirecting stdin.\" << std::endl;\n\t\t\texit(1);\n\t\t}\n\t\t\/* exec nsupdate *\/\n\t\texecl(nsupdate.c_str(), nsupdate.c_str(), \"-k\", keyfile.c_str(), (char *)NULL);\n\t\t\/* There was an error *\/\n\t\tstd::cerr << \"There was an error executing nsupdate.\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\t\/* Send it the command *\/\n\twrite(pipe_ends[1], \"server localhost\\n\");\n\t\n\twrite(pipe_ends[1], \"update delete \");\n\twrite(pipe_ends[1], domain.c_str());\n\twrite(pipe_ends[1], \".\\n\");\n\t\n\twrite(pipe_ends[1], \"update add \");\n\twrite(pipe_ends[1], domain.c_str());\n\twrite(pipe_ends[1], \". 60 A \");\n\twrite(pipe_ends[1], ip.c_str());\n\twrite(pipe_ends[1], \"\\n\");\n\t\n\twrite(pipe_ends[1], \"send\\n\");\n\t\n\t\/* Close both ends *\/\n\tclose(pipe_ends[0]);\n\tclose(pipe_ends[1]);\n\t\n\t\/* Wait for child to be gone *\/\n\tint child_status;\n\twaitpid(child_pid, &child_status, 0);\n\tif (child_status != 0) {\n\t\tstd::cerr << \"There was an error in the child.\" << std::endl;\n\t\texit(1);\n\t}\n\t\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n *\n * $RCSfile: flyincnt.cxx,v $\n *\n * $Revision: 1.8 $\n *\n * last change: $Author: kz $ $Date: 2004-05-18 14:50:46 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"cntfrm.hxx\"\n#include \"doc.hxx\"\n#include \"flyfrm.hxx\"\n#include \"frmtool.hxx\"\n#include \"frmfmt.hxx\"\n#include \"hints.hxx\"\n\n#ifndef _FMTORNT_HXX \/\/autogen\n#include \n#endif\n#ifndef _FMTFSIZE_HXX \/\/autogen\n#include \n#endif\n#include \"txtfrm.hxx\" \/\/fuer IsLocked()\n#include \"flyfrms.hxx\"\n\/\/ OD 2004-01-19 #110582#\n#ifndef _DFLYOBJ_HXX\n#include \n#endif\n\n\/\/aus FlyCnt.cxx\nvoid DeepCalc( const SwFrm *pFrm );\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()\n|*\n|* Ersterstellung MA 01. Dec. 92\n|* Letzte Aenderung MA 09. Apr. 99\n|*\n|*************************************************************************\/\nSwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :\n SwFlyFrm( pFmt, pAnch )\n{\n bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;\n SwTwips nRel = pFmt->GetVertOrient().GetPos();\n#ifdef VERTICAL_LAYOUT\n if( pAnch && pAnch->IsVertical() )\n aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;\n else\n#endif\n aRelPos.Y() = nRel;\n}\n\nSwFlyInCntFrm::~SwFlyInCntFrm()\n{\n \/\/und Tschuess.\n if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchor() )\n {\n SwRect aTmp( AddSpacesToFrm() );\n SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );\n }\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::SetRefPoint(),\n|*\n|* Ersterstellung MA 01. Dec. 92\n|* Letzte Aenderung MA 06. Aug. 95\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::SetRefPoint( const Point& rPoint, const Point& rRelAttr,\n const Point& rRelPos )\n{\n ASSERT( rPoint != aRef || rRelAttr != aRelPos, \"SetRefPoint: no change\" );\n SwFlyNotify *pNotify = NULL;\n \/\/ No notify at a locked fly frame, if a fly frame is locked, there's\n \/\/ already a SwFlyNotify object on the stack (MakeAll).\n if( !IsLocked() )\n pNotify = new SwFlyNotify( this );\n aRef = rPoint;\n aRelPos = rRelAttr;\n#ifdef VERTICAL_LAYOUT\n SWRECTFN( GetAnchor() )\n (Frm().*fnRect->fnSetPos)( rPoint + rRelPos );\n#else\n Frm().Pos( rPoint + rRelPos );\n#endif\n\/*\n \/\/Kein InvalidatePos hier, denn das wuerde dem Cntnt ein Prepare\n \/\/senden - dieser hat uns aber gerade gerufen.\n \/\/Da der Frm aber durchaus sein Position wechseln kann, muss hier\n \/\/der von ihm abdeckte Window-Bereich invalidiert werden damit keine\n \/\/Reste stehenbleiben.\n \/\/Fix: Nicht fuer PreView-Shells, dort ist es nicht notwendig und\n \/\/fuehrt zu fiesen Problemen (Der Absatz wird nur formatiert weil\n \/\/er gepaintet wird und der Cache uebergelaufen ist, beim Paint durch\n \/\/das Invalidate wird der Absatz formatiert weil...)\n if ( Frm().HasArea() && GetShell()->ISA(SwCrsrShell) )\n GetShell()->InvalidateWindows( Frm() );\n*\/\n if( pNotify )\n {\n InvalidatePage();\n bValidPos = FALSE;\n bInvalid = TRUE;\n Calc();\n delete pNotify;\n }\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::Modify()\n|*\n|* Ersterstellung MA 16. Dec. 92\n|* Letzte Aenderung MA 02. Sep. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )\n{\n BOOL bCallPrepare = FALSE;\n USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;\n if( RES_ATTRSET_CHG == nWhich )\n {\n if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n GetItemState( RES_SURROUND, FALSE ) ||\n SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n GetItemState( RES_FRMMACRO, FALSE ) )\n {\n SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );\n SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );\n\n aOld.ClearItem( RES_SURROUND );\n aNew.ClearItem( RES_SURROUND );\n aOld.ClearItem( RES_FRMMACRO );\n aNew.ClearItem( RES_FRMMACRO );\n if( aNew.Count() )\n {\n SwFlyFrm::Modify( &aOld, &aNew );\n bCallPrepare = TRUE;\n }\n }\n else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())\n {\n SwFlyFrm::Modify( pOld, pNew );\n bCallPrepare = TRUE;\n }\n }\n else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )\n {\n SwFlyFrm::Modify( pOld, pNew );\n bCallPrepare = TRUE;\n }\n\n if ( bCallPrepare && GetAnchor() )\n GetAnchor()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );\n}\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::Format()\n|*\n|* Beschreibung: Hier wird der Inhalt initial mit Formatiert.\n|* Ersterstellung MA 16. Dec. 92\n|* Letzte Aenderung MA 19. May. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )\n{\n if ( !Frm().Height() )\n {\n Lock(); \/\/nicht hintenherum den Anker formatieren.\n SwCntntFrm *pCntnt = ContainsCntnt();\n while ( pCntnt )\n { pCntnt->Calc();\n pCntnt = pCntnt->GetNextCntntFrm();\n }\n Unlock();\n }\n SwFlyFrm::Format( pAttrs );\n}\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::MakeFlyPos()\n|*\n|* Beschreibung Im Unterschied zu anderen Frms wird hier nur die\n|* die RelPos berechnet. Die absolute Position wird ausschliesslich\n|* per SetAbsPos errechnet.\n|* Ersterstellung MA 03. Dec. 92\n|* Letzte Aenderung MA 12. Apr. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeFlyPos()\n{\n if ( !bValidPos )\n {\n if ( !GetAnchor()->IsTxtFrm() || !((SwTxtFrm*)GetAnchor())->IsLocked() )\n ::DeepCalc( GetAnchor() );\n if( GetAnchor()->IsTxtFrm() )\n ((SwTxtFrm*)GetAnchor())->GetFormatted();\n bValidPos = TRUE;\n SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();\n const SwFmtVertOrient &rVert = pFmt->GetVertOrient();\n \/\/Und ggf. noch die aktuellen Werte im Format updaten, dabei darf\n \/\/zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.\n#ifdef VERTICAL_LAYOUT\n SWRECTFN( GetAnchor() )\n SwTwips nOld = rVert.GetPos();\n SwTwips nAct = bVert ? -aRelPos.X() : aRelPos.Y();\n if( bRev )\n nAct = -nAct;\n if( nAct != nOld )\n {\n SwFmtVertOrient aVert( rVert );\n aVert.SetPos( nAct );\n#else\n if ( rVert.GetPos() != aRelPos.Y() )\n {\n SwFmtVertOrient aVert( rVert );\n aVert.SetPos( aRelPos.Y() );\n#endif\n pFmt->LockModify();\n pFmt->SetAttr( aVert );\n pFmt->UnlockModify();\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::NotifyBackground()\n|*\n|* Ersterstellung MA 03. Dec. 92\n|* Letzte Aenderung MA 26. Aug. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,\n PrepareHint eHint)\n{\n if ( eHint == PREP_FLY_ATTR_CHG )\n GetAnchor()->Prepare( PREP_FLY_ATTR_CHG );\n else\n GetAnchor()->Prepare( eHint, (void*)&rRect );\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::GetRelPos()\n|*\n|* Ersterstellung MA 04. Dec. 92\n|* Letzte Aenderung MA 04. Dec. 92\n|*\n|*************************************************************************\/\nconst Point &SwFlyInCntFrm::GetRelPos() const\n{\n Calc();\n return GetCurRelPos();\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::RegistFlys()\n|*\n|* Ersterstellung MA 26. Nov. 93\n|* Letzte Aenderung MA 26. Nov. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::RegistFlys()\n{\n \/\/ vgl. SwRowFrm::RegistFlys()\n SwPageFrm *pPage = FindPageFrm();\n ASSERT( pPage, \"Flys ohne Seite anmelden?\" );\n ::RegistFlys( pPage, this );\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::MakeAll()\n|*\n|* Ersterstellung MA 18. Feb. 94\n|* Letzte Aenderung MA 13. Jun. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeAll()\n{\n \/\/ OD 2004-01-19 #110582#\n if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )\n {\n return;\n }\n\n if ( !GetAnchor() || IsLocked() || IsColLocked() || !FindPageFrm() )\n return;\n\n Lock(); \/\/Der Vorhang faellt\n\n \/\/uebernimmt im DTor die Benachrichtigung\n const SwFlyNotify aNotify( this );\n SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );\n const SwBorderAttrs &rAttrs = *aAccess.Get();\n const Size &rSz = rAttrs.GetSize();\n const SwFmtFrmSize &rFrmSz = GetFmt()->GetFrmSize();\n\n if ( IsClipped() )\n bValidSize = bHeightClipped = bWidthClipped = FALSE;\n\n while ( !bValidPos || !bValidSize || !bValidPrtArea )\n {\n \/\/Nur einstellen wenn das Flag gesetzt ist!!\n if ( !bValidSize )\n {\n bValidPrtArea = FALSE;\n\/*\n \/\/ This is also done in the Format function, so I think\n \/\/ this code is not necessary anymore:\n long nOldWidth = aFrm.Width();\n const Size aRelSize( CalcRel( rFrmSz ) );\n aFrm.Width( aRelSize.Width() );\n\n if ( aFrm.Width() > nOldWidth )\n \/\/Damit sich der Inhalt anpasst\n aFrm.Height( aRelSize.Height() );\n*\/\n }\n\n if ( !bValidPrtArea )\n MakePrtArea( rAttrs );\n\n if ( !bValidSize )\n Format( &rAttrs );\n\n if ( !bValidPos )\n MakeFlyPos();\n\n\/* #111909# objects anchored as characters may exceed right margin!\n if ( bValidPos && bValidSize )\n {\n SwFrm *pFrm = GetAnchor();\n if (\n\/\/MA 03. Apr. 96 fix(26652), Das trifft uns bestimmt nocheinmal\n\/\/ !pFrm->IsMoveable() &&\n Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&\n Frm().Width() > pFrm->Prt().Width() )\n {\n Frm().Width( pFrm->Prt().Width() );\n bValidPrtArea = FALSE;\n bWidthClipped = TRUE;\n }\n }\n *\/\n }\n Unlock();\n}\n\nINTEGRATION: CWS swdrawpositioning (1.6.36); FILE MERGED 2004\/06\/01 12:08:48 od 1.6.36.3: #i26791# - removed member 2004\/04\/08 09:20:30 od 1.6.36.2: RESYNC: (1.6-1.7); FILE MERGED 2004\/04\/07 12:07:08 od 1.6.36.1: #i26791# - adjustments for the unification of the positioning of \t Writer fly frames and drawing objects\/*************************************************************************\n *\n * $RCSfile: flyincnt.cxx,v $\n *\n * $Revision: 1.9 $\n *\n * last change: $Author: hjs $ $Date: 2004-06-28 13:39:27 $\n *\n * The Contents of this file are made available subject to the terms of\n * either of the following licenses\n *\n * - GNU Lesser General Public License Version 2.1\n * - Sun Industry Standards Source License Version 1.1\n *\n * Sun Microsystems Inc., October, 2000\n *\n * GNU Lesser General Public License Version 2.1\n * =============================================\n * Copyright 2000 by Sun Microsystems, Inc.\n * 901 San Antonio Road, Palo Alto, CA 94303, USA\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License version 2.1, as published by the Free Software Foundation.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n * MA 02111-1307 USA\n *\n *\n * Sun Industry Standards Source License Version 1.1\n * =================================================\n * The contents of this file are subject to the Sun Industry Standards\n * Source License Version 1.1 (the \"License\"); You may not use this file\n * except in compliance with the License. You may obtain a copy of the\n * License at http:\/\/www.openoffice.org\/license.html.\n *\n * Software provided under this License is provided on an \"AS IS\" basis,\n * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,\n * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,\n * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.\n * See the License for the specific provisions governing your rights and\n * obligations concerning the Software.\n *\n * The Initial Developer of the Original Code is: Sun Microsystems, Inc.\n *\n * Copyright: 2000 by Sun Microsystems, Inc.\n *\n * All Rights Reserved.\n *\n * Contributor(s): _______________________________________\n *\n *\n ************************************************************************\/\n\n\n#pragma hdrstop\n\n#include \"cntfrm.hxx\"\n#include \"doc.hxx\"\n#include \"flyfrm.hxx\"\n#include \"frmtool.hxx\"\n#include \"frmfmt.hxx\"\n#include \"hints.hxx\"\n\n#ifndef _FMTORNT_HXX \/\/autogen\n#include \n#endif\n#ifndef _FMTFSIZE_HXX \/\/autogen\n#include \n#endif\n#include \"txtfrm.hxx\" \/\/fuer IsLocked()\n#include \"flyfrms.hxx\"\n\/\/ OD 2004-01-19 #110582#\n#ifndef _DFLYOBJ_HXX\n#include \n#endif\n\n\/\/aus FlyCnt.cxx\nvoid DeepCalc( const SwFrm *pFrm );\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::SwFlyInCntFrm(), ~SwFlyInCntFrm()\n|*\n|* Ersterstellung MA 01. Dec. 92\n|* Letzte Aenderung MA 09. Apr. 99\n|*\n|*************************************************************************\/\nSwFlyInCntFrm::SwFlyInCntFrm( SwFlyFrmFmt *pFmt, SwFrm *pAnch ) :\n SwFlyFrm( pFmt, pAnch )\n{\n bInCnt = bInvalidLayout = bInvalidCntnt = TRUE;\n SwTwips nRel = pFmt->GetVertOrient().GetPos();\n \/\/ OD 2004-05-27 #i26791# - member moved to \n Point aRelPos;\n if( pAnch && pAnch->IsVertical() )\n aRelPos.X() = pAnch->IsReverse() ? nRel : -nRel;\n else\n aRelPos.Y() = nRel;\n SetCurrRelPos( aRelPos );\n}\n\nSwFlyInCntFrm::~SwFlyInCntFrm()\n{\n \/\/und Tschuess.\n if ( !GetFmt()->GetDoc()->IsInDtor() && GetAnchorFrm() )\n {\n SwRect aTmp( AddSpacesToFrm() );\n SwFlyInCntFrm::NotifyBackground( FindPageFrm(), aTmp, PREP_FLY_LEAVE );\n }\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::SetRefPoint(),\n|*\n|* Ersterstellung MA 01. Dec. 92\n|* Letzte Aenderung MA 06. Aug. 95\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::SetRefPoint( const Point& rPoint,\n const Point& rRelAttr,\n const Point& rRelPos )\n{\n \/\/ OD 2004-05-27 #i26791# - member moved to \n ASSERT( rPoint != aRef || rRelAttr != GetCurrRelPos(), \"SetRefPoint: no change\" );\n SwFlyNotify *pNotify = NULL;\n \/\/ No notify at a locked fly frame, if a fly frame is locked, there's\n \/\/ already a SwFlyNotify object on the stack (MakeAll).\n if( !IsLocked() )\n pNotify = new SwFlyNotify( this );\n aRef = rPoint;\n SetCurrRelPos( rRelAttr );\n SWRECTFN( GetAnchorFrm() )\n (Frm().*fnRect->fnSetPos)( rPoint + rRelPos );\n if( pNotify )\n {\n InvalidatePage();\n bValidPos = FALSE;\n bInvalid = TRUE;\n Calc();\n delete pNotify;\n }\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::Modify()\n|*\n|* Ersterstellung MA 16. Dec. 92\n|* Letzte Aenderung MA 02. Sep. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Modify( SfxPoolItem *pOld, SfxPoolItem *pNew )\n{\n BOOL bCallPrepare = FALSE;\n USHORT nWhich = pOld ? pOld->Which() : pNew ? pNew->Which() : 0;\n if( RES_ATTRSET_CHG == nWhich )\n {\n if( SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n GetItemState( RES_SURROUND, FALSE ) ||\n SFX_ITEM_SET == ((SwAttrSetChg*)pNew)->GetChgSet()->\n GetItemState( RES_FRMMACRO, FALSE ) )\n {\n SwAttrSetChg aOld( *(SwAttrSetChg*)pOld );\n SwAttrSetChg aNew( *(SwAttrSetChg*)pNew );\n\n aOld.ClearItem( RES_SURROUND );\n aNew.ClearItem( RES_SURROUND );\n aOld.ClearItem( RES_FRMMACRO );\n aNew.ClearItem( RES_FRMMACRO );\n if( aNew.Count() )\n {\n SwFlyFrm::Modify( &aOld, &aNew );\n bCallPrepare = TRUE;\n }\n }\n else if( ((SwAttrSetChg*)pNew)->GetChgSet()->Count())\n {\n SwFlyFrm::Modify( pOld, pNew );\n bCallPrepare = TRUE;\n }\n }\n else if( nWhich != RES_SURROUND && RES_FRMMACRO != nWhich )\n {\n SwFlyFrm::Modify( pOld, pNew );\n bCallPrepare = TRUE;\n }\n\n if ( bCallPrepare && GetAnchorFrm() )\n AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG, GetFmt() );\n}\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::Format()\n|*\n|* Beschreibung: Hier wird der Inhalt initial mit Formatiert.\n|* Ersterstellung MA 16. Dec. 92\n|* Letzte Aenderung MA 19. May. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::Format( const SwBorderAttrs *pAttrs )\n{\n if ( !Frm().Height() )\n {\n Lock(); \/\/nicht hintenherum den Anker formatieren.\n SwCntntFrm *pCntnt = ContainsCntnt();\n while ( pCntnt )\n { pCntnt->Calc();\n pCntnt = pCntnt->GetNextCntntFrm();\n }\n Unlock();\n }\n SwFlyFrm::Format( pAttrs );\n}\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::MakeFlyPos()\n|*\n|* Beschreibung Im Unterschied zu anderen Frms wird hier nur die\n|* die RelPos berechnet. Die absolute Position wird ausschliesslich\n|* per SetAbsPos errechnet.\n|* Ersterstellung MA 03. Dec. 92\n|* Letzte Aenderung MA 12. Apr. 96\n|*\n|*************************************************************************\/\n\/\/ OD 2004-03-23 #i26791#\n\/\/void SwFlyInCntFrm::MakeFlyPos()\nvoid SwFlyInCntFrm::MakeObjPos()\n{\n if ( !bValidPos )\n {\n if ( !GetAnchorFrm()->IsTxtFrm() || !((SwTxtFrm*)GetAnchorFrm())->IsLocked() )\n ::DeepCalc( GetAnchorFrm() );\n if( GetAnchorFrm()->IsTxtFrm() )\n ((SwTxtFrm*)GetAnchorFrm())->GetFormatted();\n bValidPos = TRUE;\n SwFlyFrmFmt *pFmt = (SwFlyFrmFmt*)GetFmt();\n const SwFmtVertOrient &rVert = pFmt->GetVertOrient();\n \/\/Und ggf. noch die aktuellen Werte im Format updaten, dabei darf\n \/\/zu diesem Zeitpunkt natuerlich kein Modify verschickt werden.\n SWRECTFN( GetAnchorFrm() )\n SwTwips nOld = rVert.GetPos();\n SwTwips nAct = bVert ? -GetCurrRelPos().X() : GetCurrRelPos().Y();\n if( bRev )\n nAct = -nAct;\n if( nAct != nOld )\n {\n SwFmtVertOrient aVert( rVert );\n aVert.SetPos( nAct );\n pFmt->LockModify();\n pFmt->SetAttr( aVert );\n pFmt->UnlockModify();\n }\n }\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::NotifyBackground()\n|*\n|* Ersterstellung MA 03. Dec. 92\n|* Letzte Aenderung MA 26. Aug. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::NotifyBackground( SwPageFrm *, const SwRect& rRect,\n PrepareHint eHint)\n{\n if ( eHint == PREP_FLY_ATTR_CHG )\n AnchorFrm()->Prepare( PREP_FLY_ATTR_CHG );\n else\n AnchorFrm()->Prepare( eHint, (void*)&rRect );\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::GetRelPos()\n|*\n|* Ersterstellung MA 04. Dec. 92\n|* Letzte Aenderung MA 04. Dec. 92\n|*\n|*************************************************************************\/\nconst Point SwFlyInCntFrm::GetRelPos() const\n{\n Calc();\n return GetCurrRelPos();\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::RegistFlys()\n|*\n|* Ersterstellung MA 26. Nov. 93\n|* Letzte Aenderung MA 26. Nov. 93\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::RegistFlys()\n{\n \/\/ vgl. SwRowFrm::RegistFlys()\n SwPageFrm *pPage = FindPageFrm();\n ASSERT( pPage, \"Flys ohne Seite anmelden?\" );\n ::RegistFlys( pPage, this );\n}\n\n\/*************************************************************************\n|*\n|* SwFlyInCntFrm::MakeAll()\n|*\n|* Ersterstellung MA 18. Feb. 94\n|* Letzte Aenderung MA 13. Jun. 96\n|*\n|*************************************************************************\/\nvoid SwFlyInCntFrm::MakeAll()\n{\n \/\/ OD 2004-01-19 #110582#\n if ( !GetFmt()->GetDoc()->IsVisibleLayerId( GetVirtDrawObj()->GetLayer() ) )\n {\n return;\n }\n\n if ( !GetAnchorFrm() || IsLocked() || IsColLocked() || !FindPageFrm() )\n return;\n\n Lock(); \/\/Der Vorhang faellt\n\n \/\/uebernimmt im DTor die Benachrichtigung\n const SwFlyNotify aNotify( this );\n SwBorderAttrAccess aAccess( SwFrm::GetCache(), this );\n const SwBorderAttrs &rAttrs = *aAccess.Get();\n const Size &rSz = rAttrs.GetSize();\n const SwFmtFrmSize &rFrmSz = GetFmt()->GetFrmSize();\n\n if ( IsClipped() )\n bValidSize = bHeightClipped = bWidthClipped = FALSE;\n\n while ( !bValidPos || !bValidSize || !bValidPrtArea )\n {\n \/\/Nur einstellen wenn das Flag gesetzt ist!!\n if ( !bValidSize )\n {\n bValidPrtArea = FALSE;\n\/*\n \/\/ This is also done in the Format function, so I think\n \/\/ this code is not necessary anymore:\n long nOldWidth = aFrm.Width();\n const Size aRelSize( CalcRel( rFrmSz ) );\n aFrm.Width( aRelSize.Width() );\n\n if ( aFrm.Width() > nOldWidth )\n \/\/Damit sich der Inhalt anpasst\n aFrm.Height( aRelSize.Height() );\n*\/\n }\n\n if ( !bValidPrtArea )\n MakePrtArea( rAttrs );\n\n if ( !bValidSize )\n Format( &rAttrs );\n\n if ( !bValidPos )\n {\n \/\/ OD 2004-03-23 #i26791#\n \/\/MakeFlyPos();\n MakeObjPos();\n }\n\n\/* #111909# objects anchored as characters may exceed right margin!\n if ( bValidPos && bValidSize )\n {\n SwFrm* pFrm = AnchorFrm();\n if ( Frm().Left() == (pFrm->Frm().Left()+pFrm->Prt().Left()) &&\n Frm().Width() > pFrm->Prt().Width() )\n {\n Frm().Width( pFrm->Prt().Width() );\n bValidPrtArea = FALSE;\n bWidthClipped = TRUE;\n }\n }\n *\/\n }\n Unlock();\n}\n<|endoftext|>"} {"text":"#ifndef STANDARD_TYPES_HPP\n#define STANDARD_TYPES_HPP\n\n#include \n\n#if 0\n\t#ifndef __AVR_LIBC_VERSION_STRING__\n\t\ttypedef char int8;\n\t\ttypedef unsigned char uint8;\n\n\t\ttypedef short int16;\n\t\ttypedef unsigned short uint16;\n\n\t\ttypedef int int32;\n\t\ttypedef unsigned int uint32;\n\t#else\n\t\ttypedef char int8;\n\t\ttypedef unsigned char uint8;\n\n\t\ttypedef int int16;\n\t\ttypedef unsigned int uint16;\n\n\t\ttypedef long int32;\n\t\ttypedef unsigned long uint32;\n\t#endif\n#else\n\ttypedef int8_t int8;\n\ttypedef uint8_t uint8;\n\n\ttypedef int16_t int16;\n\ttypedef uint16_t uint16;\n\n\ttypedef int32_t int32;\n\ttypedef uint32_t uint32;\n#endif\n#endif\nsaner defs#ifndef STANDARD_TYPES_HPP\n#define STANDARD_TYPES_HPP\n\n#include \n\ntypedef int8_t int8;\ntypedef uint8_t uint8;\n\ntypedef int16_t int16;\ntypedef uint16_t uint16;\n\ntypedef int32_t int32;\ntypedef uint32_t uint32;\n\n#endif\n<|endoftext|>"} {"text":"#include \n#include \n\nTEST(socket, create_destroy)\n{\n zmq::context_t context;\n zmq::socket_t socket(context, ZMQ_ROUTER);\n}\n\n#ifdef ZMQ_CPP11\nTEST(socket, create_by_enum_destroy)\n{\n zmq::context_t context;\n zmq::socket_t socket(context, zmq::socket_type::router);\n}\n#endif\nProblem: no test case for previously existing send functionality#include \n#include \n\nTEST(socket, create_destroy)\n{\n zmq::context_t context;\n zmq::socket_t socket(context, ZMQ_ROUTER);\n}\n\n#ifdef ZMQ_CPP11\nTEST(socket, create_by_enum_destroy)\n{\n zmq::context_t context;\n zmq::socket_t socket(context, zmq::socket_type::router);\n}\n#endif\n\nTEST(socket, send_receive_const_buffer)\n{\n zmq::context_t context;\n zmq::socket_t sender(context, ZMQ_PAIR);\n zmq::socket_t receiver(context, ZMQ_PAIR);\n receiver.bind(\"inproc:\/\/test\");\n sender.connect(\"inproc:\/\/test\");\n ASSERT_EQ(2, sender.send(\"Hi\", 2));\n char buf[2];\n ASSERT_EQ(2, receiver.recv(buf, 2));\n ASSERT_EQ(0, memcmp(buf, \"Hi\", 2));\n}\n<|endoftext|>"} {"text":"fix texImage2D call to use desc.internalFormat. Remove border from unresolved shaders to simplify shader code and look like normal texture arrays.<|endoftext|>"} {"text":"\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2343\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\nP4 to Git Change 1364840 by johtaylo@johtaylo-jtincrementor-increment on 2017\/01\/23 03:00:29\/\/\n\/\/ Copyright (c) 2010 Advanced Micro Devices, Inc. All rights reserved.\n\/\/\n\n#ifndef VERSIONS_HPP_\n#define VERSIONS_HPP_\n\n#include \"utils\/macros.hpp\"\n\n#ifndef AMD_PLATFORM_NAME\n# define AMD_PLATFORM_NAME \"AMD Accelerated Parallel Processing\"\n#endif \/\/ AMD_PLATFORM_NAME\n\n#ifndef AMD_PLATFORM_BUILD_NUMBER\n# define AMD_PLATFORM_BUILD_NUMBER 2344\n#endif \/\/ AMD_PLATFORM_BUILD_NUMBER\n\n#ifndef AMD_PLATFORM_REVISION_NUMBER\n# define AMD_PLATFORM_REVISION_NUMBER 0\n#endif \/\/ AMD_PLATFORM_REVISION_NUMBER\n\n#ifndef AMD_PLATFORM_RELEASE_INFO\n# define AMD_PLATFORM_RELEASE_INFO\n#endif \/\/ AMD_PLATFORM_RELEASE_INFO\n\n#define AMD_BUILD_STRING XSTR(AMD_PLATFORM_BUILD_NUMBER) \\\n \".\" XSTR(AMD_PLATFORM_REVISION_NUMBER)\n\n#ifndef AMD_PLATFORM_INFO\n# define AMD_PLATFORM_INFO \"AMD-APP\" AMD_PLATFORM_RELEASE_INFO \\\n DEBUG_ONLY(\".\" IF(IS_OPTIMIZED,\"opt\",\"dbg\")) \" (\" AMD_BUILD_STRING \")\"\n#endif \/\/ ATI_PLATFORM_INFO\n\n#endif \/\/ VERSIONS_HPP_\n<|endoftext|>"} {"text":"P4 to Git Change 1447247 by johtaylo@johtaylo-jtincrementor-increment on 2017\/08\/15 03:00:04<|endoftext|>"} {"text":"P4 to Git Change 1451630 by johtaylo@johtaylo-jtincrementor-increment on 2017\/08\/25 03:00:06<|endoftext|>"} {"text":"P4 to Git Change 1584378 by chui@ocl-promo-incrementor on 2018\/07\/24 02:56:41<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \"MainScene.h\"\n#include \"TWScene.h\"\n\nScene* TWScene::createScene()\n{\n\tauto scene = Scene::create();\n\n\tauto layer = TWScene::create();\n\n\tscene->addChild(layer);\n\n\treturn scene;\n}\n\nbool TWScene::init()\n{\n\tif (!CCLayerColor::initWithColor(Color4B::BLUE))\n\t{\n\t\treturn false;\n\t}\n\n\n\t\/\/1ȸ ͵\n\tauto mainTitle = Label::createWithTTF(\"Main Title\\n fuck!!!!\", \"fonts\/NanumGothic.ttf\", 34);\n\tmainTitle->setPosition(Point(160, 240));\n\tmainTitle->setName(\"MainTitle\");\n\n\tSize winSize = Director::getInstance()->getVisibleSize();\n\tfloat labelWidth = mainTitle->getContentSize().width;\n\tfloat labelHeight = mainTitle->getContentSize().height;\n\tauto action1 = MoveTo::create(10.0 \/ labelHeight, Point(labelWidth \/ 2, winSize.height - labelHeight \/ 2));\n\tauto action2 = MoveTo::create(10.0 \/ labelWidth, Point(winSize.width - labelWidth \/ 2, winSize.height - labelHeight \/ 2));\n\tauto action3 = MoveTo::create(10.0 \/ labelHeight, Point(winSize.width - labelWidth \/ 2, labelHeight \/ 2));\n\tauto action4 = MoveTo::create(10.0 \/ labelWidth, Point(labelWidth \/ 2, labelHeight \/ 2));\n\tauto sequence_action = Sequence::create(action1, action2, action3, action4, NULL);\n\tauto forever_repeat_action = RepeatForever::create(sequence_action);\n\n\tmainTitle->runAction(forever_repeat_action);\n\t\/\/mainTitle->stopAction(forever_repeat_action);\n\tthis->addChild(mainTitle);\n\n\tauto listener = EventListenerMouse::create();\n\tlistener->onMouseUp = CC_CALLBACK_1(TWScene::onMouseUP, this); \n\t_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);\n\n\n\t\/\/2ȸ ͵\n\tSprite* character = Sprite::create();\n\tthis->addChild(character);\n\tcharacter->setPosition(Point(winSize.width \/ 2, winSize.height \/ 2));\n\tVector animFrames;\n\tanimFrames.reserve(4);\n\tfor (int i = 0; i < 4; i++)\n\t\tanimFrames.pushBack(SpriteFrame::create(\"res\/lisa.png\", Rect(0, 48 * i, 27, 48)));\n\n\t\/\/ create the animation out of the frame\n\tAnimation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f);\n\tAnimate* animate = Animate::create(animation);\n\n\t\/\/ run it and repeat it forever\n\tRepeatForever *action = RepeatForever::create(animate);\n\t\n\tcharacter->runAction(action);\n\n\tthis->schedule(schedule_selector(TWScene::ChangeBackground), 1.0);\n\n\tLayer* bgLayer = Layer::create();\n\tthis->addChild(bgLayer, 1);\n\n\tauto spr_0 = Sprite::create(\"res\/mc.jpg\");\n\tspr_0->setScaleX(winSize.width);\n\tspr_0->setScaleY(winSize.height);\n\tspr_0->setAnchorPoint(Point::ZERO);\n\tspr_0->setPosition(Point::ZERO);\n\tbgLayer->addChild(spr_0);\n\n\tauto action_0 = MoveBy::create(10.0, Point(-2000, 0));\n\tauto action_1 = Place::create(Point::ZERO);\n\tauto action_2 = Sequence::create(action_0, action_1, NULL);\n\tauto action_3 = RepeatForever::create(action_2);\n\tbgLayer->runAction(action_3);\n\n\treturn true;\n}\n\nvoid TWScene::ChangeBackground(float deltaTIme)\n{\n\tColor3B color;\n\tint rand = random() % 5;\n\tswitch (rand){\n\tcase 0: \n\t\tcolor = Color3B::YELLOW;\n\t\tbreak;\n\tcase 1:\n\t\tcolor = Color3B::BLUE;\n\t\tbreak;\n\tcase 2:\n\t\tcolor = Color3B::GREEN;\n\t\tbreak;\n\tcase 3:\n\t\tcolor = Color3B::RED;\n\t\tbreak;\n\tcase 4:\n\t\tcolor = Color3B::MAGENTA;\n\t\tbreak;\n\tcase 5:\n\t\tcolor = Color3B::BLACK;\n\t\tbreak;\n\tcase 6:\n\t\tcolor = Color3B::ORANGE;\n\t\tbreak;\n\tcase 7:\n\t\tcolor = Color3B::GRAY;\n\t\tbreak;\n\t}\n\tthis->setColor(color);\n}\n\nvoid TWScene::ChangeToMainScene(Ref* pSender)\n{\n\tDirector::getInstance()->replaceScene(MainScene::createScene());\n}\n\nvoid TWScene::onMouseUP(cocos2d::Event* event)\n{\n\tauto mainTitle = this->getChildByName(\"MainTitle\");\n\tif (!mainTitle->isVisible())\n\t\tmainTitle->setVisible(true);\n\telse\n\t\tmainTitle->setVisible(false);\n}\nUnsolved#include \"stdafx.h\"\n#include \"MainScene.h\"\n#include \"TWScene.h\"\n\nScene* TWScene::createScene()\n{\n\tauto scene = Scene::create();\n\n\tauto layer = TWScene::create();\n\n\tscene->addChild(layer);\n\n\treturn scene;\n}\n\nbool TWScene::init()\n{\n\tif (!CCLayerColor::initWithColor(Color4B::BLUE))\n\t{\n\t\treturn false;\n\t}\n\n\n\t\/\/1ȸ ͵\n\tauto mainTitle = Label::createWithTTF(\"Main Title\\n fuck!!!!\", \"fonts\/NanumGothic.ttf\", 34);\n\tmainTitle->setPosition(Point(160, 240));\n\tmainTitle->setName(\"MainTitle\");\n\n\tSize winSize = Director::getInstance()->getVisibleSize();\n\tfloat labelWidth = mainTitle->getContentSize().width;\n\tfloat labelHeight = mainTitle->getContentSize().height;\n\tauto action1 = MoveTo::create(10.0 \/ labelHeight, Point(labelWidth \/ 2, winSize.height - labelHeight \/ 2));\n\tauto action2 = MoveTo::create(10.0 \/ labelWidth, Point(winSize.width - labelWidth \/ 2, winSize.height - labelHeight \/ 2));\n\tauto action3 = MoveTo::create(10.0 \/ labelHeight, Point(winSize.width - labelWidth \/ 2, labelHeight \/ 2));\n\tauto action4 = MoveTo::create(10.0 \/ labelWidth, Point(labelWidth \/ 2, labelHeight \/ 2));\n\tauto sequence_action = Sequence::create(action1, action2, action3, action4, NULL);\n\tauto forever_repeat_action = RepeatForever::create(sequence_action);\n\n\tmainTitle->runAction(forever_repeat_action);\n\t\/\/mainTitle->stopAction(forever_repeat_action);\n\tthis->addChild(mainTitle);\n\n\tauto listener = EventListenerMouse::create();\n\tlistener->onMouseUp = CC_CALLBACK_1(TWScene::onMouseUP, this); \n\t_eventDispatcher->addEventListenerWithSceneGraphPriority(listener, this);\n\n\n\t\/\/2ȸ ͵\n\tSprite* character = Sprite::create();\n\tthis->addChild(character);\n\tcharacter->setPosition(Point(winSize.width \/ 2, winSize.height \/ 2));\n\tVector animFrames;\n\tanimFrames.reserve(4);\n\tfor (int i = 0; i < 4; i++)\n\t\tanimFrames.pushBack(SpriteFrame::create(\"res\/lisa.png\", Rect(0, 48 * i, 27, 48)));\n\n\t\/\/ create the animation out of the frame\n\tAnimation* animation = Animation::createWithSpriteFrames(animFrames, 0.1f);\n\tAnimate* animate = Animate::create(animation);\n\n\t\/\/ run it and repeat it forever\n\tRepeatForever *action = RepeatForever::create(animate);\n\t\n\tcharacter->runAction(action);\n\n\tthis->schedule(schedule_selector(TWScene::ChangeBackground), 1.0);\n\n\tLayer* bgLayer = Layer::create();\n\tthis->addChild(bgLayer, 1);\n\n\tauto spr_0 = Sprite::create(\"res\/mc.jpg\");\n\tspr_0->setScaleX(winSize.width \/ spr_0->getContentSize().width);\n\tspr_0->setScaleY(winSize.height \/ spr_0->getContentSize().height);\n\tspr_0->setAnchorPoint(Point::ZERO);\n\tspr_0->setPosition(Point::ZERO);\n\tbgLayer->addChild(spr_0);\n\n\tauto spr_1 = Sprite::create(\"res\/mc.jpg\");\n\tspr_1->setScaleX(winSize.width \/ spr_1->getContentSize().width);\n\tspr_1->setScaleY(winSize.height \/ spr_1->getContentSize().height);\n\tspr_1->setAnchorPoint(Point::ZERO);\n\tspr_1->setPosition(Point(winSize.width, 0));\n\tbgLayer->addChild(spr_1);\n\t\n\tauto action_0 = MoveBy::create(10.0, Point(-2000, 0));\n\tauto action_1 = Place::create(Point::ZERO);\n\tauto action_2 = Sequence::create(action_0, action_1, NULL);\n\tauto action_3 = RepeatForever::create(action_2);\n\tbgLayer->runAction(action_3);\n\n\treturn true;\n}\n\nvoid TWScene::ChangeBackground(float deltaTIme)\n{\n\tColor3B color;\n\tint rand = random() % 5;\n\tswitch (rand){\n\tcase 0: \n\t\tcolor = Color3B::YELLOW;\n\t\tbreak;\n\tcase 1:\n\t\tcolor = Color3B::BLUE;\n\t\tbreak;\n\tcase 2:\n\t\tcolor = Color3B::GREEN;\n\t\tbreak;\n\tcase 3:\n\t\tcolor = Color3B::RED;\n\t\tbreak;\n\tcase 4:\n\t\tcolor = Color3B::MAGENTA;\n\t\tbreak;\n\tcase 5:\n\t\tcolor = Color3B::BLACK;\n\t\tbreak;\n\tcase 6:\n\t\tcolor = Color3B::ORANGE;\n\t\tbreak;\n\tcase 7:\n\t\tcolor = Color3B::GRAY;\n\t\tbreak;\n\t}\n\tthis->setColor(color);\n}\n\nvoid TWScene::ChangeToMainScene(Ref* pSender)\n{\n\tDirector::getInstance()->replaceScene(MainScene::createScene());\n}\n\nvoid TWScene::onMouseUP(cocos2d::Event* event)\n{\n\tauto mainTitle = this->getChildByName(\"MainTitle\");\n\tif (!mainTitle->isVisible())\n\t\tmainTitle->setVisible(true);\n\telse\n\t\tmainTitle->setVisible(false);\n}\n<|endoftext|>"} {"text":"\/\/ @(#)root\/hist:$Id$\n\/\/ Author: David Gonzalez Maline 12\/11\/09\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TFitResultPtr.h\"\n#include \"TFitResult.h\"\n#include \"TError.h\"\n\n\/**\nTFitResultPtr provides an indirection to the TFitResult class and with a semantics\nidentical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult. \nIn addition it provides an automatic comversion to an integer. In this way it can be \nreturned from the TH1::Fit method and the change in TH1::Fit be backward compatible. \nThe class \n\n *\/\n\nClassImp(TFitResultPtr)\n\nTFitResultPtr::TFitResultPtr(TFitResult * p) : \n fStatus(-1), \n fPointer(p) \n{\n \/\/ constructor from a TFitResult pointer\n if (fPointer != 0) fStatus = fPointer->Status(); \n}\n\nTFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) : \n fStatus(rhs.fStatus), fPointer(0)\n{\n \/\/ copy constructor - create a new TFitResult if needed\n if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);\n}\n\nTFitResultPtr::~TFitResultPtr()\n{\n \/\/ destructor - delete the contained TFitResult pointer if needed\n if ( fPointer != 0)\n delete fPointer;\n}\n\n\nTFitResult& TFitResultPtr::operator*() const\n{\n \/\/ impelment the de-reference operator to make the class acts as a pointer to a TFitResult\n \/\/ assert in case the class does not contain a pointer to TFitResult\n if (fPointer == 0) { \n Error(\"TFitResultPtr\",\"TFitResult is empty - use the fit option S\");\n return *(new TFitResult() );\n }\n return *fPointer;\n}\n\nTFitResult* TFitResultPtr::operator->() const\n{\n \/\/ implement the -> operator to make the class acts as a pointer to a TFitResult\n \/\/ assert in case the class does not contain a pointer to TFitResult\n if (fPointer == 0) { \n Error(\"TFitResultPtr\",\"TFitResult is empty - use the fit option S\");\n return new TFitResult();\n }\n return fPointer;\n}\n\n\nTFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs) \n{ \n \/\/ assignment operator\n \/\/ if needed copy the TFitResult object and delete previous one if existing\n if ( &rhs == this) return *this; \/\/ self assignment\n fStatus = rhs.fStatus; \n if ( fPointer ) delete fPointer;\n fPointer = 0;\n if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);\n return *this;\n}\n\nfix minor typo\/\/ @(#)root\/hist:$Id$\n\/\/ Author: David Gonzalez Maline 12\/11\/09\n\n\/*************************************************************************\n * Copyright (C) 1995-2000, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n#include \"TFitResultPtr.h\"\n#include \"TFitResult.h\"\n#include \"TError.h\"\n\n\/**\nTFitResultPtr provides an indirection to the TFitResult class and with a semantics\nidentical to a TFitResult pointer, i.e. it is like a smart pointer to a TFitResult. \nIn addition it provides an automatic comversion to an integer. In this way it can be \nreturned from the TH1::Fit method and the change in TH1::Fit be backward compatible. \nThe class \n\n *\/\n\nClassImp(TFitResultPtr)\n\nTFitResultPtr::TFitResultPtr(TFitResult * p) : \n fStatus(-1), \n fPointer(p) \n{\n \/\/ constructor from a TFitResult pointer\n if (fPointer != 0) fStatus = fPointer->Status(); \n}\n\nTFitResultPtr::TFitResultPtr(const TFitResultPtr& rhs) : \n fStatus(rhs.fStatus), fPointer(0)\n{\n \/\/ copy constructor - create a new TFitResult if needed\n if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);\n}\n\nTFitResultPtr::~TFitResultPtr()\n{\n \/\/ destructor - delete the contained TFitResult pointer if needed\n if ( fPointer != 0)\n delete fPointer;\n}\n\n\nTFitResult& TFitResultPtr::operator*() const\n{\n \/\/ implement the de-reference operator to make the class acts as a pointer to a TFitResult\n \/\/ assert in case the class does not contain a pointer to TFitResult\n if (fPointer == 0) { \n Error(\"TFitResultPtr\",\"TFitResult is empty - use the fit option S\");\n return *(new TFitResult() );\n }\n return *fPointer;\n}\n\nTFitResult* TFitResultPtr::operator->() const\n{\n \/\/ implement the -> operator to make the class acts as a pointer to a TFitResult\n \/\/ assert in case the class does not contain a pointer to TFitResult\n if (fPointer == 0) { \n Error(\"TFitResultPtr\",\"TFitResult is empty - use the fit option S\");\n return new TFitResult();\n }\n return fPointer;\n}\n\n\nTFitResultPtr & TFitResultPtr::operator=(const TFitResultPtr& rhs) \n{ \n \/\/ assignment operator\n \/\/ if needed copy the TFitResult object and delete previous one if existing\n if ( &rhs == this) return *this; \/\/ self assignment\n fStatus = rhs.fStatus; \n if ( fPointer ) delete fPointer;\n fPointer = 0;\n if (rhs.fPointer != 0) fPointer = new TFitResult(*rhs);\n return *this;\n}\n\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"AdaBoost.h\"\n#include \"VectorData.h\"\n#include \"MatData.h\"\n#include \"WeakVectorClassifierFactory.h\"\n#include \"WeakHaarClassifierFactory.h\"\n#include \"AdaBoostEdgeDetector.h\"\n\nconst double PI = 3.14159265;\n\nvoid test2DPoints()\n{\n\t\/\/Mat img = imread(\"sky.jpg\");\n\t\/\/Mat gray;\n\t\/\/cv::cvtColor(img, gray, CV_BGR2GRAY);\n\n\t\/\/imshow(\"Colored Image\", img);\n\t\/\/imshow(\"Gray Image\", gray);\n\n\t\/\/waitKey();\n\t\n\t\/\/ generate the data\n\tstd::vector data;\n\tint i = 0;\n\tcv::Mat img = cv::Mat::zeros(1100, 1100, CV_32FC3);\n\tfor (double r = 0.1 * 1000; r <= 0.51 * 1000; r += 0.05 * 1000)\n\t{\n\t\tfor (double theta = 0; theta <= 1.81 * PI; theta += (PI \/ 5),i++)\n\t\t{\n\t\t\tstd::vector d = std::vector(2, 0);\n\t\t\td[0] = 0.5f + r * std::cos(theta);\n\t\t\td[1] = 0.5f + (r - 0.05) * std::sin(theta);\n\n\t\t\tdata.push_back(new VectorData(d));\n\t\t}\n\t}\n\t\/\/ test\n\t\/\/data.clear();\n\t\/\/label.clear();\n\t\/\/for (int i = 0; i < 3; i++)\n\t\/\/{\n\t\/\/\tdata.push_back(std::vector(2, 0));\n\t\/\/\tdata[i][0] = i;\n\t\/\/\tdata[i][1] = rand() % 10;\n\t\/\/}\n\t\/\/for (int i = 3; i < 6; i++)\n\t\/\/{\n\t\/\/\tdata.push_back(std::vector(2, 0));\n\t\/\/\tdata[i][0] = i;\n\t\/\/\tdata[i][1] = rand() % 20;\n\t\/\/}\n\t\/\/\n\tstd::cout << data.size() << std::endl;\n\tint shift = 510;\n\tstd::vector label(30,1); \n\tlabel.resize(data.size(), -1);\n\tfor (int i = 0; i < data.size(); i++)\n\t{\n\t\tcv::circle(img, cv::Point(data[i]->getVectorData()[0] + shift, data[i]->getVectorData()[1] + shift), \n\t\t\t2, cv::Scalar(((label[i] - 1) \/ -2) * 255, 0, ((label[i] + 1)\/2) * 255), -1);\n\t}\n\t\/\/freopen(\"result.csv\", \"w\", stdout);\n\tWeakClassifierFactory * factory = new WeakVectorClassifierFactory();\n\tfor (int i = 1; i < 30; i+=2)\n\t{\n\t\tAdaBoost adaboost(i, factory);\n\t\tstd::vector outLabels;\n\t\tdouble accuracy = adaboost.train(data, label, outLabels);\n\t\tstd::cout << i << \", \" << accuracy << std::endl;\n\t\t\/\/system(\"PAUSE\");\n\t}\n\tcv::imshow(\"img\", img);\n\tcv::waitKey();\n}\n\nvoid displayIntegralImage(cv::Mat Iimg)\n{\n\tdouble min, max;\n\tcv::minMaxLoc(Iimg, &min, &max);\n\tIimg -= min;\n\tIimg \/= (max - min);\n\tcv::imshow(\"image\", Iimg);\n\tcv::waitKey();\n}\n\/*\nvoid testMatData()\n{\n\tcv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1);\n\tm(cv::Rect(0, 0, 200, 200)) = 50;\n\tm(cv::Rect(0, 200, 200, 200)) = 200;\n\tm(cv::Rect(200, 0, 200, 200)) = 150;\n\tm(cv::Rect(200, 200, 200, 200)) = 100;\n\tcv::Mat Iimg, I2img;\n\tcv::integral(m, Iimg, I2img, CV_32FC1);\n\t\/\/ display\n\t\/\/displayIntegralImage(Iimg);\n\tcv::Mat edges = AdaBoostEdgeDetector::cannyEdgeDetection(m);\n\n\t\/\/ prepare data vector\n\tstd::vector trainData;\n\tstd::vector labels;\n\tcv::Mat show;\n\tcv::cvtColor(m, show, CV_GRAY2BGR);\n\t\/\/ make patches 10x10 with step 5\n\tfor (int r = 0; r <= 390; r += 5)\n\t{\n\t\tfor (int c = 0; c <= 390; c += 5)\n\t\t{\n\t\t\tcv::Rect win = cv::Rect(c, r, 10, 10);\n\t\t\ttrainData.push_back(new MatData(Iimg, win));\n\t\t\t\/\/MatData testData(m, win);\n\t\t\t\/\/cv::imshow(\"window\", testData.getMatData());\n\t\t\t\/\/cv::waitKey();\n\t\t\tif (cv::sum(edges(win)).val[0] > 1)\n\t\t\t{\n\t\t\t\t\/\/ edge\n\t\t\t\tlabels.push_back(1);\n\t\t\t\tcv::rectangle(show, win, cv::Scalar(255, 0, 0));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ non edge\n\t\t\t\tlabels.push_back(-1);\n\t\t\t}\n\t\t}\n\t}\n\n\tcv::imshow(\"my edges\", show);\n\tcv::waitKey(50);\n\n\t\/\/ prepare the Haar Classifier Factory\n\tstd::vector > > shapes;\n\tint arr[] = { -1,1 };\n\tstd::vector > shape1(2,std::vector(1,1));\n\tshape1[0][0] = -1;\n\tstd::vector > shape2(2, std::vector(2, 1));\n\tshape2[0][0] = shape2[1][1] = -1;\n\n\n\tshapes.push_back(std::vector >(1, std::vector(arr, arr + 2)));\n\tshapes.push_back(shape1);\n\t\/\/shapes.push_back(shape2);\n\t\n\tstd::vector locs(1, cv::Point(0, 0));\n\tstd::vector sizes;\n\tsizes.push_back(cv::Size(5, 10));\n\tsizes.push_back(cv::Size(10, 5));\n\t\/\/sizes.push_back(cv::Size(5, 5));\n\n\t\n\tfor (int i = 1; i < 30; i ++)\n\t{\n\t\tWeakClassifierFactory * factory = new WeakHaarClassifierFactory(shapes, sizes, locs);\n\n\t\tAdaBoost adaboost(i, factory);\n\t\tstd::vector y;\n\t\tdouble accuracy = adaboost.train(trainData, labels, y);\n\t\tstd::cout << i << \", \" << accuracy << std::endl;\n\t\tcv::Mat show1;\n\t\tshow.copyTo(show1);\n\t\tfor (int j = 0; j < y.size(); j++)\n\t\t{\n\t\t\tif (y[j] == 1)\n\t\t\t{\n\t\t\t\tif (labels[j] == 1)\n\t\t\t\t{\n\t\t\t\t\tcv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 255, 0));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 0, 255));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcv::imshow(\"my edges\", show1);\n\t\tcv::waitKey(0);\n\t\t\/\/system(\"PAUSE\");\n\t}\n}\n*\/\nvoid testAdaBoostEdgeDetection()\n{\n\tcv::Mat testImg = cv::imread(\"test.png\", 0);\n\n\tcv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1);\n\tm(cv::Rect(0, 0, 200, 200)) = 50;\n\tm(cv::Rect(0, 200, 200, 200)) = 200;\n\tm(cv::Rect(200, 0, 200, 200)) = 150;\n\tm(cv::Rect(200, 200, 200, 200)) = 100;\n\tcv::imwrite(\"orig.png\", m);\n\tstd::vector images;\n\timages.push_back(m);\n\n\tstd::vector > > shapes;\n\tint arr[] = { -1,1 };\n\tstd::vector > shape1(2, std::vector(1, 1));\n\tshape1[0][0] = -1;\n\tstd::vector > shape2(2, std::vector(2, 1));\n\tshape2[0][0] = shape2[1][1] = -1;\n\n\n\tshapes.push_back(std::vector >(1, std::vector(arr, arr + 2)));\n\tshapes.push_back(shape1);\n\t\/\/shapes.push_back(shape2);\n\n\n\n\tfor (int t = 1; t < 20; t++)\n\t{\n\t\tAdaBoostEdgeDetector adaBoostEdgeDetector(t, shapes, cv::Size(4,4), 2);\n\t\tadaBoostEdgeDetector.train(images, true);\n\t\tadaBoostEdgeDetector.test(testImg, true);\n\t}\n\t\n}\n\nint main()\n{\n\t\/\/test2DPoints();\n\t\/\/testMatData();\n\ttestAdaBoostEdgeDetection();\n\treturn 0;\n}final test before class#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \"AdaBoost.h\"\n#include \"VectorData.h\"\n#include \"MatData.h\"\n#include \"WeakVectorClassifierFactory.h\"\n#include \"WeakHaarClassifierFactory.h\"\n#include \"AdaBoostEdgeDetector.h\"\n\nconst double PI = 3.14159265;\n\nvoid test2DPoints()\n{\n\t\/\/Mat img = imread(\"sky.jpg\");\n\t\/\/Mat gray;\n\t\/\/cv::cvtColor(img, gray, CV_BGR2GRAY);\n\n\t\/\/imshow(\"Colored Image\", img);\n\t\/\/imshow(\"Gray Image\", gray);\n\n\t\/\/waitKey();\n\t\n\t\/\/ generate the data\n\tstd::vector data;\n\tint i = 0;\n\tcv::Mat img = cv::Mat::zeros(1100, 1100, CV_32FC3);\n\tfor (double r = 0.1 * 1000; r <= 0.51 * 1000; r += 0.05 * 1000)\n\t{\n\t\tfor (double theta = 0; theta <= 1.81 * PI; theta += (PI \/ 5),i++)\n\t\t{\n\t\t\tstd::vector d = std::vector(2, 0);\n\t\t\td[0] = 0.5f + r * std::cos(theta);\n\t\t\td[1] = 0.5f + (r - 0.05) * std::sin(theta);\n\n\t\t\tdata.push_back(new VectorData(d));\n\t\t}\n\t}\n\t\/\/ test\n\t\/\/data.clear();\n\t\/\/label.clear();\n\t\/\/for (int i = 0; i < 3; i++)\n\t\/\/{\n\t\/\/\tdata.push_back(std::vector(2, 0));\n\t\/\/\tdata[i][0] = i;\n\t\/\/\tdata[i][1] = rand() % 10;\n\t\/\/}\n\t\/\/for (int i = 3; i < 6; i++)\n\t\/\/{\n\t\/\/\tdata.push_back(std::vector(2, 0));\n\t\/\/\tdata[i][0] = i;\n\t\/\/\tdata[i][1] = rand() % 20;\n\t\/\/}\n\t\/\/\n\tstd::cout << data.size() << std::endl;\n\tint shift = 510;\n\tstd::vector label(30,1); \n\tlabel.resize(data.size(), -1);\n\tfor (int i = 0; i < data.size(); i++)\n\t{\n\t\tcv::circle(img, cv::Point(data[i]->getVectorData()[0] + shift, data[i]->getVectorData()[1] + shift), \n\t\t\t2, cv::Scalar(((label[i] - 1) \/ -2) * 255, 0, ((label[i] + 1)\/2) * 255), -1);\n\t}\n\t\/\/freopen(\"result.csv\", \"w\", stdout);\n\tWeakClassifierFactory * factory = new WeakVectorClassifierFactory();\n\tfor (int i = 1; i < 30; i+=2)\n\t{\n\t\tAdaBoost adaboost(i, factory);\n\t\tstd::vector outLabels;\n\t\tdouble accuracy = adaboost.train(data, label, outLabels);\n\t\tstd::cout << i << \", \" << accuracy << std::endl;\n\t\t\/\/system(\"PAUSE\");\n\t}\n\tcv::imshow(\"img\", img);\n\tcv::waitKey();\n}\n\nvoid displayIntegralImage(cv::Mat Iimg)\n{\n\tdouble min, max;\n\tcv::minMaxLoc(Iimg, &min, &max);\n\tIimg -= min;\n\tIimg \/= (max - min);\n\tcv::imshow(\"image\", Iimg);\n\tcv::waitKey();\n}\n\/*\nvoid testMatData()\n{\n\tcv::Mat m = cv::Mat::zeros(cv::Size(400, 400), CV_8UC1);\n\tm(cv::Rect(0, 0, 200, 200)) = 50;\n\tm(cv::Rect(0, 200, 200, 200)) = 200;\n\tm(cv::Rect(200, 0, 200, 200)) = 150;\n\tm(cv::Rect(200, 200, 200, 200)) = 100;\n\tcv::Mat Iimg, I2img;\n\tcv::integral(m, Iimg, I2img, CV_32FC1);\n\t\/\/ display\n\t\/\/displayIntegralImage(Iimg);\n\tcv::Mat edges = AdaBoostEdgeDetector::cannyEdgeDetection(m);\n\n\t\/\/ prepare data vector\n\tstd::vector trainData;\n\tstd::vector labels;\n\tcv::Mat show;\n\tcv::cvtColor(m, show, CV_GRAY2BGR);\n\t\/\/ make patches 10x10 with step 5\n\tfor (int r = 0; r <= 390; r += 5)\n\t{\n\t\tfor (int c = 0; c <= 390; c += 5)\n\t\t{\n\t\t\tcv::Rect win = cv::Rect(c, r, 10, 10);\n\t\t\ttrainData.push_back(new MatData(Iimg, win));\n\t\t\t\/\/MatData testData(m, win);\n\t\t\t\/\/cv::imshow(\"window\", testData.getMatData());\n\t\t\t\/\/cv::waitKey();\n\t\t\tif (cv::sum(edges(win)).val[0] > 1)\n\t\t\t{\n\t\t\t\t\/\/ edge\n\t\t\t\tlabels.push_back(1);\n\t\t\t\tcv::rectangle(show, win, cv::Scalar(255, 0, 0));\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t\/\/ non edge\n\t\t\t\tlabels.push_back(-1);\n\t\t\t}\n\t\t}\n\t}\n\n\tcv::imshow(\"my edges\", show);\n\tcv::waitKey(50);\n\n\t\/\/ prepare the Haar Classifier Factory\n\tstd::vector > > shapes;\n\tint arr[] = { -1,1 };\n\tstd::vector > shape1(2,std::vector(1,1));\n\tshape1[0][0] = -1;\n\tstd::vector > shape2(2, std::vector(2, 1));\n\tshape2[0][0] = shape2[1][1] = -1;\n\n\n\tshapes.push_back(std::vector >(1, std::vector(arr, arr + 2)));\n\tshapes.push_back(shape1);\n\t\/\/shapes.push_back(shape2);\n\t\n\tstd::vector locs(1, cv::Point(0, 0));\n\tstd::vector sizes;\n\tsizes.push_back(cv::Size(5, 10));\n\tsizes.push_back(cv::Size(10, 5));\n\t\/\/sizes.push_back(cv::Size(5, 5));\n\n\t\n\tfor (int i = 1; i < 30; i ++)\n\t{\n\t\tWeakClassifierFactory * factory = new WeakHaarClassifierFactory(shapes, sizes, locs);\n\n\t\tAdaBoost adaboost(i, factory);\n\t\tstd::vector y;\n\t\tdouble accuracy = adaboost.train(trainData, labels, y);\n\t\tstd::cout << i << \", \" << accuracy << std::endl;\n\t\tcv::Mat show1;\n\t\tshow.copyTo(show1);\n\t\tfor (int j = 0; j < y.size(); j++)\n\t\t{\n\t\t\tif (y[j] == 1)\n\t\t\t{\n\t\t\t\tif (labels[j] == 1)\n\t\t\t\t{\n\t\t\t\t\tcv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 255, 0));\n\t\t\t\t}\n\t\t\t\telse\n\t\t\t\t{\n\t\t\t\t\tcv::rectangle(show1, ((MatData*)trainData[j])->getROI(), cv::Scalar(0, 0, 255));\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tcv::imshow(\"my edges\", show1);\n\t\tcv::waitKey(0);\n\t\t\/\/system(\"PAUSE\");\n\t}\n}\n*\/\nvoid testAdaBoostEdgeDetection(int horizontal = 1, int vertical = 1, int t = 6, std::string trainImg = \"orig.png\",std::string testImage = \"test.png\")\n{\n\tcv::Mat testImg = cv::imread(testImage, 0);\n\n\tcv::Mat m = cv::imread(trainImg, 0);\n\tstd::vector images;\n\timages.push_back(m);\n\n\tstd::vector > > shapes;\n\tint arr[] = { -1,1 };\n\tstd::vector > shape1(2, std::vector(1, 1));\n\tshape1[0][0] = -1;\n\tstd::vector > shape2(2, std::vector(2, 1));\n\tshape2[0][0] = shape2[1][1] = -1;\n\n\tif (horizontal)\n\t{\n\t\tshapes.push_back(std::vector >(1, std::vector(arr, arr + 2)));\n\t}\n\tif (vertical)\n\t{\n\t\tshapes.push_back(shape1);\n\t}\n\t\/\/shapes.push_back(shape2);\n\n\n\n\t\/\/for (int t = 1; t < 20; t++)\n\t{\n\t\tAdaBoostEdgeDetector adaBoostEdgeDetector(t, shapes, cv::Size(4,4), 2);\n\t\tadaBoostEdgeDetector.train(images, true);\n\t\tadaBoostEdgeDetector.test(testImg, true);\n\t}\n\t\n}\n\nint main(int argc, char*argv[])\n{\n\tint horizontal = 1;\n\tint vertical = 1;\n\tint t = 6;\n\tstd::string trainImg = \"orig.png\";\n\tstd::string testImage = \"test.png\";\n\tfor (int i = 0; i < argc; i++)\n\t{\n\t\tif (std::string(argv[i]) == \"-h\")\n\t\t{\n\t\t\thorizontal = std::stoi(argv[i + 1]);\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-v\")\n\t\t{\n\t\t\tvertical = std::stoi(argv[i + 1]);\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-t\")\n\t\t{\n\t\t\tt = std::stoi(argv[i + 1]);\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-i\")\n\t\t{\n\t\t\ttrainImg = argv[i + 1];\n\t\t}\n\t\telse if (std::string(argv[i]) == \"-o\")\n\t\t{\n\t\t\ttestImage = argv[i + 1];\n\t\t}\n\t\telse\n\t\t{\n\t\t\ti--;\n\t\t}\n\t\ti++;\n\t}\n\t\/\/test2DPoints();\n\t\/\/testMatData();\n\ttestAdaBoostEdgeDetection(horizontal,vertical,t,trainImg,testImage);\n\treturn 0;\n}<|endoftext|>"} {"text":"\/\/ FROM: http:\/\/playground.arduino.cc\/Code\/EEPROMLoadAndSaveSettings\n\n\/* LoadAndSaveSettings\n * footswitch 2012-03-05, original code by Joghurt (2010)\n * Demonstrates how to load and save settings to the EEPROM\n * Tested on Arduino Uno R2 with Arduino 0023\n *\/\n\/\/ Contains EEPROM.read() and EEPROM.write()\n#include \n#include \n#include \"Settings.h\"\n\n#define MAD_SETTINGS_LOGGING 1\n\nStoreStruct my_settings = {\n \/\/ The default values\n 0.2f,\n -0.25f,\n \/\/ 220, 1884,\n \/\/ 'c',\n \/\/ 10000,\n \/\/ {4.5, 5.5, 7, 8.5, 10, 12},\n CONFIG_VERSION\n};\n\nbool my_settings_loaded = false;\n\nvoid loadConfig() {\n \/\/ To make sure there are settings, and they are YOURS!\n \/\/ If nothing is found it will use the default settings.\n if (\/\/EEPROM.read(CONFIG_START + sizeof(settings) - 1) == settings.version_of_program[3] \/\/ this is '\\0'\n EEPROM.read(CONFIG_START + sizeof(my_settings) - 2) == my_settings.version_of_program[2] &&\n EEPROM.read(CONFIG_START + sizeof(my_settings) - 3) == my_settings.version_of_program[1] &&\n EEPROM.read(CONFIG_START + sizeof(my_settings) - 4) == my_settings.version_of_program[0])\n { \/\/ reads settings from EEPROM\n for (unsigned int t=0; tminor\/\/ FROM: http:\/\/playground.arduino.cc\/Code\/EEPROMLoadAndSaveSettings\n\n\/* LoadAndSaveSettings\n * footswitch 2012-03-05, original code by Joghurt (2010)\n * Demonstrates how to load and save settings to the EEPROM\n * Tested on Arduino Uno R2 with Arduino 0023\n *\/\n\/\/ Contains EEPROM.read() and EEPROM.write()\n#include \n#include \n#include \"Settings.h\"\n\n#define MAD_SETTINGS_LOGGING 1\n\nStoreStruct my_settings = {\n \/\/ The default values\n 0.2f,\n -0.25f,\n \/\/ 220, 1884,\n \/\/ 'c',\n \/\/ 10000,\n \/\/ {4.5, 5.5, 7, 8.5, 10, 12},\n CONFIG_VERSION\n};\n\nbool my_settings_loaded = false;\n\nvoid loadConfig() {\n \/\/ To make sure there are settings, and they are YOURS!\n \/\/ If nothing is found it will use the default settings.\n if (\/\/EEPROM.read(CONFIG_START + sizeof(settings) - 1) == settings.version_of_program[3] \/\/ this is '\\0'\n EEPROM.read(CONFIG_START + sizeof(my_settings) - 2) == my_settings.version_of_program[2] &&\n EEPROM.read(CONFIG_START + sizeof(my_settings) - 3) == my_settings.version_of_program[1] &&\n EEPROM.read(CONFIG_START + sizeof(my_settings) - 4) == my_settings.version_of_program[0])\n { \/\/ reads settings from EEPROM\n for (unsigned int t=0; t"} {"text":"Replace fedpeg template init check for pak one<|endoftext|>"} {"text":"#pragma once\n\n#include \n#include \n\n#include \n\nnamespace color_coded\n{\n namespace clang\n {\n namespace token\n {\n inline std::string map_type_kind(CXTypeKind const kind)\n {\n switch(kind)\n {\n case CXType_Unexposed:\n return \"Variable\";\n\n case CXType_Void:\n case CXType_Bool:\n case CXType_Char_U:\n case CXType_UChar:\n case CXType_Char16:\n case CXType_Char32:\n case CXType_UShort:\n case CXType_UInt:\n case CXType_ULong:\n case CXType_ULongLong:\n case CXType_UInt128:\n case CXType_Char_S:\n case CXType_SChar:\n case CXType_WChar:\n case CXType_Short:\n case CXType_Int:\n case CXType_Long:\n case CXType_LongLong:\n case CXType_Int128:\n case CXType_Float:\n case CXType_Double:\n case CXType_LongDouble:\n case CXType_NullPtr:\n case CXType_Overload:\n case CXType_Dependent:\n case CXType_ObjCId:\n case CXType_ObjCClass:\n case CXType_ObjCSel:\n return \"Variable\";\n\n case CXType_Complex:\n case CXType_Pointer:\n case CXType_BlockPointer:\n case CXType_LValueReference:\n case CXType_RValueReference:\n case CXType_Record:\n case CXType_Typedef:\n case CXType_ObjCInterface:\n case CXType_ObjCObjectPointer:\n case CXType_ConstantArray:\n case CXType_Vector:\n case CXType_IncompleteArray:\n case CXType_VariableArray:\n case CXType_DependentSizedArray:\n return \"Variable\";\n\n case CXType_MemberPointer:\n return \"Member\";\n\n case CXType_Enum:\n return \"EnumConstant\";\n\n case CXType_FunctionNoProto:\n case CXType_FunctionProto:\n return \"Function\";\n\n case CXType_Auto:\n return \"Variable\";\n\n default:\n return \"\";\n \/\/return \"Error1 \" + std::to_string(kind);\n }\n }\n\n inline std::string map_cursor_kind(CXCursorKind const kind,\n CXTypeKind const type)\n {\n switch(kind)\n {\n \/********* Declarations **********\/\n case CXCursor_UnexposedDecl: \/* Unknown declaration *\/\n return \"\";\n case CXCursor_StructDecl:\n return \"StructDecl\";\n case CXCursor_UnionDecl:\n return \"UnionDecl\";\n case CXCursor_ClassDecl:\n return \"ClassDecl\";\n case CXCursor_EnumDecl:\n return \"EnumDecl\";\n case CXCursor_FieldDecl:\n return \"FieldDecl\";\n case CXCursor_EnumConstantDecl:\n return \"EnumConstantDecl\";\n case CXCursor_FunctionDecl:\n return \"FunctionDecl\";\n case CXCursor_VarDecl:\n return \"VarDecl\";\n case CXCursor_ParmDecl:\n return \"ParmDecl\";\n case CXCursor_ObjCInterfaceDecl:\n return \"ObjCInterfaceDecl\";\n case CXCursor_ObjCCategoryDecl:\n return \"ObjCCategoryDecl\";\n case CXCursor_ObjCProtocolDecl:\n return \"ObjCProtocolDecl\";\n case CXCursor_ObjCPropertyDecl:\n return \"ObjCPropertyDecl\";\n case CXCursor_ObjCIvarDecl:\n return \"ObjCIvarDecl\";\n case CXCursor_ObjCInstanceMethodDecl:\n return \"ObjCInstanceMethodDecl\";\n case CXCursor_ObjCClassMethodDecl:\n return \"ObjCClassMethodDecl\";\n case CXCursor_ObjCImplementationDecl:\n return \"ObjCImplementationDecl\";\n case CXCursor_ObjCCategoryImplDecl:\n return \"ObjCCategoryImplDecl\";\n case CXCursor_TypedefDecl:\n return \"TypedefDecl\";\n case CXCursor_CXXMethod:\n return \"CXXMethod\";\n case CXCursor_Namespace:\n return \"Namespace\";\n case CXCursor_LinkageSpec:\n return \"LinkageSpec\";\n case CXCursor_Constructor:\n return \"Constructor\";\n case CXCursor_Destructor:\n return \"Destructor\";\n case CXCursor_ConversionFunction:\n return \"ConversionFunction\";\n case CXCursor_TemplateTypeParameter:\n return \"TemplateTypeParameter\";\n case CXCursor_NonTypeTemplateParameter:\n return \"NonTypeTemplateParameter\";\n case CXCursor_TemplateTemplateParameter:\n return \"TemplateTemplateParameter\";\n case CXCursor_FunctionTemplate:\n return \"FunctionTemplate\";\n case CXCursor_ClassTemplate:\n return \"ClassTemplate\";\n case CXCursor_ClassTemplatePartialSpecialization:\n return \"ClassTemplatePartialSpecialization\";\n case CXCursor_NamespaceAlias:\n return \"NamespaceAlias\";\n case CXCursor_UsingDirective:\n return \"UsingDirective\";\n case CXCursor_UsingDeclaration:\n return \"UsingDeclaration\";\n case CXCursor_TypeAliasDecl:\n return \"TypeAliasDecl\";\n case CXCursor_ObjCSynthesizeDecl:\n return \"ObjCSynthesizeDecl\";\n case CXCursor_ObjCDynamicDecl:\n return \"ObjCDynamicDecl\";\n case CXCursor_CXXAccessSpecifier:\n return \"CXXAccessSpecifier\";\n\n \/********* References **********\/\n case CXCursor_ObjCSuperClassRef:\n return \"ObjCSuperClassRef\";\n case CXCursor_ObjCProtocolRef:\n return \"ObjCProtocolRef\";\n case CXCursor_ObjCClassRef:\n return \"ObjCClassRef\";\n case CXCursor_TypeRef:\n return \"TypeRef\";\n case CXCursor_CXXBaseSpecifier:\n return \"CXXBaseSpecifier\";\n case CXCursor_TemplateRef:\n return \"TemplateRef\";\n case CXCursor_NamespaceRef:\n return \"NamespaceRef\";\n case CXCursor_MemberRef:\n return \"MemberRef\";\n case CXCursor_LabelRef:\n return \"LabelRef\";\n case CXCursor_OverloadedDeclRef:\n return \"OverloadedDeclRef\";\n case CXCursor_VariableRef:\n return \"VariableRef\";\n\n \/********* Errors **********\/\n case CXCursor_InvalidFile:\n return \"\";\n case CXCursor_NoDeclFound:\n return \"\";\n case CXCursor_NotImplemented:\n return \"\";\n case CXCursor_InvalidCode:\n return \"\";\n\n \/********* Expressions **********\/\n case CXCursor_UnexposedExpr:\n break;\n case CXCursor_DeclRefExpr:\n return map_type_kind(type);\n case CXCursor_MemberRefExpr:\n return \"MemberRefExpr\";\n case CXCursor_CallExpr:\n return \"CallExpr\";\n case CXCursor_ObjCMessageExpr:\n return \"ObjCMessageExpr\";\n case CXCursor_BlockExpr:\n return \"BlockExpr\";\n case CXCursor_MacroDefinition:\n return \"MacroDefinition\";\n case CXCursor_MacroInstantiation:\n return \"MacroInstantiation\";\n case CXCursor_PreprocessingDirective: \/* XXX: do not want *\/\n return \"\";\n case CXCursor_InclusionDirective: \/* XXX: do not want *\/\n return \"\";\n case CXCursor_CompoundStmt:\n return \"\";\n case CXCursor_ParenExpr:\n case CXCursor_LambdaExpr:\n case CXCursor_CXXForRangeStmt:\n case CXCursor_DeclStmt:\n return \"\";\n default:\n return \"\";\n \/\/return \"Error2 \" + std::to_string(kind);\n }\n return \"\";\n \/\/return \"Error3 \" + std::to_string(kind);\n }\n\n inline std::string map_literal_kind(CXCursorKind const kind)\n {\n switch(kind)\n {\n case CXCursor_IntegerLiteral:\n return \"Number\";\n case CXCursor_FloatingLiteral:\n return \"Float\";\n case CXCursor_ImaginaryLiteral:\n return \"Number\";\n case CXCursor_StringLiteral:\n return \"\"; \/* Allow vim to do this. *\/\n case CXCursor_CharacterLiteral:\n return \"Character\";\n case CXType_Unexposed:\n return \"\";\n default:\n return \"\";\n \/\/return \"Error4 \" + std::to_string(kind);\n }\n }\n\n \/* Clang token\/cursor -> Vim highlight group. *\/\n inline std::string map_token_kind(CXTokenKind const token_kind,\n CXCursorKind const cursor_kind,\n CXTypeKind const cursor_type)\n {\n switch (token_kind)\n {\n case CXToken_Punctuation:\n return \"\"; \/* Allow vim to do this. *\/\n case CXToken_Keyword:\n return \"\"; \/* Allow vim to do this. *\/\n case CXToken_Identifier:\n return map_cursor_kind(cursor_kind, cursor_type);\n case CXToken_Literal:\n return map_literal_kind(cursor_kind);\n case CXToken_Comment:\n return \"\"; \/* Allow vim to do this. *\/\n default:\n return \"\";\n \/\/return \"Error5 \" + std::to_string(token_kind);\n }\n }\n }\n }\n}\nPreserve compatibility with clang 3.6#pragma once\n\n#include \n#include \n\n#include \n\nnamespace color_coded\n{\n namespace clang\n {\n namespace token\n {\n inline std::string map_type_kind(CXTypeKind const kind)\n {\n switch(kind)\n {\n case CXType_Unexposed:\n return \"Variable\";\n\n case CXType_Void:\n case CXType_Bool:\n case CXType_Char_U:\n case CXType_UChar:\n case CXType_Char16:\n case CXType_Char32:\n case CXType_UShort:\n case CXType_UInt:\n case CXType_ULong:\n case CXType_ULongLong:\n case CXType_UInt128:\n case CXType_Char_S:\n case CXType_SChar:\n case CXType_WChar:\n case CXType_Short:\n case CXType_Int:\n case CXType_Long:\n case CXType_LongLong:\n case CXType_Int128:\n case CXType_Float:\n case CXType_Double:\n case CXType_LongDouble:\n case CXType_NullPtr:\n case CXType_Overload:\n case CXType_Dependent:\n case CXType_ObjCId:\n case CXType_ObjCClass:\n case CXType_ObjCSel:\n return \"Variable\";\n\n case CXType_Complex:\n case CXType_Pointer:\n case CXType_BlockPointer:\n case CXType_LValueReference:\n case CXType_RValueReference:\n case CXType_Record:\n case CXType_Typedef:\n case CXType_ObjCInterface:\n case CXType_ObjCObjectPointer:\n case CXType_ConstantArray:\n case CXType_Vector:\n case CXType_IncompleteArray:\n case CXType_VariableArray:\n case CXType_DependentSizedArray:\n return \"Variable\";\n\n case CXType_MemberPointer:\n return \"Member\";\n\n case CXType_Enum:\n return \"EnumConstant\";\n\n case CXType_FunctionNoProto:\n case CXType_FunctionProto:\n return \"Function\";\n#if CINDEX_VERSION_MINOR >= 32\n case CXType_Auto:\n return \"Variable\";\n#endif\n default:\n return \"\";\n \/\/return \"Error1 \" + std::to_string(kind);\n }\n }\n\n inline std::string map_cursor_kind(CXCursorKind const kind,\n CXTypeKind const type)\n {\n switch(kind)\n {\n \/********* Declarations **********\/\n case CXCursor_UnexposedDecl: \/* Unknown declaration *\/\n return \"\";\n case CXCursor_StructDecl:\n return \"StructDecl\";\n case CXCursor_UnionDecl:\n return \"UnionDecl\";\n case CXCursor_ClassDecl:\n return \"ClassDecl\";\n case CXCursor_EnumDecl:\n return \"EnumDecl\";\n case CXCursor_FieldDecl:\n return \"FieldDecl\";\n case CXCursor_EnumConstantDecl:\n return \"EnumConstantDecl\";\n case CXCursor_FunctionDecl:\n return \"FunctionDecl\";\n case CXCursor_VarDecl:\n return \"VarDecl\";\n case CXCursor_ParmDecl:\n return \"ParmDecl\";\n case CXCursor_ObjCInterfaceDecl:\n return \"ObjCInterfaceDecl\";\n case CXCursor_ObjCCategoryDecl:\n return \"ObjCCategoryDecl\";\n case CXCursor_ObjCProtocolDecl:\n return \"ObjCProtocolDecl\";\n case CXCursor_ObjCPropertyDecl:\n return \"ObjCPropertyDecl\";\n case CXCursor_ObjCIvarDecl:\n return \"ObjCIvarDecl\";\n case CXCursor_ObjCInstanceMethodDecl:\n return \"ObjCInstanceMethodDecl\";\n case CXCursor_ObjCClassMethodDecl:\n return \"ObjCClassMethodDecl\";\n case CXCursor_ObjCImplementationDecl:\n return \"ObjCImplementationDecl\";\n case CXCursor_ObjCCategoryImplDecl:\n return \"ObjCCategoryImplDecl\";\n case CXCursor_TypedefDecl:\n return \"TypedefDecl\";\n case CXCursor_CXXMethod:\n return \"CXXMethod\";\n case CXCursor_Namespace:\n return \"Namespace\";\n case CXCursor_LinkageSpec:\n return \"LinkageSpec\";\n case CXCursor_Constructor:\n return \"Constructor\";\n case CXCursor_Destructor:\n return \"Destructor\";\n case CXCursor_ConversionFunction:\n return \"ConversionFunction\";\n case CXCursor_TemplateTypeParameter:\n return \"TemplateTypeParameter\";\n case CXCursor_NonTypeTemplateParameter:\n return \"NonTypeTemplateParameter\";\n case CXCursor_TemplateTemplateParameter:\n return \"TemplateTemplateParameter\";\n case CXCursor_FunctionTemplate:\n return \"FunctionTemplate\";\n case CXCursor_ClassTemplate:\n return \"ClassTemplate\";\n case CXCursor_ClassTemplatePartialSpecialization:\n return \"ClassTemplatePartialSpecialization\";\n case CXCursor_NamespaceAlias:\n return \"NamespaceAlias\";\n case CXCursor_UsingDirective:\n return \"UsingDirective\";\n case CXCursor_UsingDeclaration:\n return \"UsingDeclaration\";\n case CXCursor_TypeAliasDecl:\n return \"TypeAliasDecl\";\n case CXCursor_ObjCSynthesizeDecl:\n return \"ObjCSynthesizeDecl\";\n case CXCursor_ObjCDynamicDecl:\n return \"ObjCDynamicDecl\";\n case CXCursor_CXXAccessSpecifier:\n return \"CXXAccessSpecifier\";\n\n \/********* References **********\/\n case CXCursor_ObjCSuperClassRef:\n return \"ObjCSuperClassRef\";\n case CXCursor_ObjCProtocolRef:\n return \"ObjCProtocolRef\";\n case CXCursor_ObjCClassRef:\n return \"ObjCClassRef\";\n case CXCursor_TypeRef:\n return \"TypeRef\";\n case CXCursor_CXXBaseSpecifier:\n return \"CXXBaseSpecifier\";\n case CXCursor_TemplateRef:\n return \"TemplateRef\";\n case CXCursor_NamespaceRef:\n return \"NamespaceRef\";\n case CXCursor_MemberRef:\n return \"MemberRef\";\n case CXCursor_LabelRef:\n return \"LabelRef\";\n case CXCursor_OverloadedDeclRef:\n return \"OverloadedDeclRef\";\n case CXCursor_VariableRef:\n return \"VariableRef\";\n\n \/********* Errors **********\/\n case CXCursor_InvalidFile:\n return \"\";\n case CXCursor_NoDeclFound:\n return \"\";\n case CXCursor_NotImplemented:\n return \"\";\n case CXCursor_InvalidCode:\n return \"\";\n\n \/********* Expressions **********\/\n case CXCursor_UnexposedExpr:\n break;\n case CXCursor_DeclRefExpr:\n return map_type_kind(type);\n case CXCursor_MemberRefExpr:\n return \"MemberRefExpr\";\n case CXCursor_CallExpr:\n return \"CallExpr\";\n case CXCursor_ObjCMessageExpr:\n return \"ObjCMessageExpr\";\n case CXCursor_BlockExpr:\n return \"BlockExpr\";\n case CXCursor_MacroDefinition:\n return \"MacroDefinition\";\n case CXCursor_MacroInstantiation:\n return \"MacroInstantiation\";\n case CXCursor_PreprocessingDirective: \/* XXX: do not want *\/\n return \"\";\n case CXCursor_InclusionDirective: \/* XXX: do not want *\/\n return \"\";\n case CXCursor_CompoundStmt:\n return \"\";\n case CXCursor_ParenExpr:\n case CXCursor_LambdaExpr:\n case CXCursor_CXXForRangeStmt:\n case CXCursor_DeclStmt:\n return \"\";\n default:\n return \"\";\n \/\/return \"Error2 \" + std::to_string(kind);\n }\n return \"\";\n \/\/return \"Error3 \" + std::to_string(kind);\n }\n\n inline std::string map_literal_kind(CXCursorKind const kind)\n {\n switch(kind)\n {\n case CXCursor_IntegerLiteral:\n return \"Number\";\n case CXCursor_FloatingLiteral:\n return \"Float\";\n case CXCursor_ImaginaryLiteral:\n return \"Number\";\n case CXCursor_StringLiteral:\n return \"\"; \/* Allow vim to do this. *\/\n case CXCursor_CharacterLiteral:\n return \"Character\";\n case CXType_Unexposed:\n return \"\";\n default:\n return \"\";\n \/\/return \"Error4 \" + std::to_string(kind);\n }\n }\n\n \/* Clang token\/cursor -> Vim highlight group. *\/\n inline std::string map_token_kind(CXTokenKind const token_kind,\n CXCursorKind const cursor_kind,\n CXTypeKind const cursor_type)\n {\n switch (token_kind)\n {\n case CXToken_Punctuation:\n return \"\"; \/* Allow vim to do this. *\/\n case CXToken_Keyword:\n return \"\"; \/* Allow vim to do this. *\/\n case CXToken_Identifier:\n return map_cursor_kind(cursor_kind, cursor_type);\n case CXToken_Literal:\n return map_literal_kind(cursor_kind);\n case CXToken_Comment:\n return \"\"; \/* Allow vim to do this. *\/\n default:\n return \"\";\n \/\/return \"Error5 \" + std::to_string(token_kind);\n }\n }\n }\n }\n}\n<|endoftext|>"} {"text":"\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \"SurgSim\/Blocks\/BasicSceneElement.h\"\n#include \"SurgSim\/Blocks\/TransferDeformableStateToVerticesBehavior.h\"\n#include \"SurgSim\/Framework\/BehaviorManager.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgCamera.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgPointCloudRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Graphics\/PointCloudRepresentation.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Physics\/Fem1DRepresentation.h\"\n#include \"SurgSim\/Physics\/FemElement1DBeam.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n\nusing SurgSim::Blocks::BasicSceneElement;\nusing SurgSim::Blocks::TransferDeformableStateToVerticesBehavior;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Graphics::OsgPointCloudRepresentation;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Physics::DeformableRepresentationState;\nusing SurgSim::Physics::Fem1DRepresentation;\nusing SurgSim::Physics::FemElement1DBeam;\nusing SurgSim::Physics::PhysicsManager;\n\n\/\/\/\\file Example of how to put together a very simple demo of Fem1D\n\nnamespace\n{\n\nvoid loadModelFem1D(std::shared_ptr physicsRepresentation, unsigned int numNodes)\n{\n\tstd::shared_ptr restState = std::make_shared();\n\trestState->setNumDof(physicsRepresentation->getNumDofPerNode(), numNodes);\n\n\t\/\/ Sets the initial state (node positions and boundary conditions)\n\tSurgSim::Math::Vector& x = restState->getPositions();\n\tfor (unsigned int nodeId = 0; nodeId < numNodes; nodeId++)\n\t{\n\t\tSurgSim::Math::getSubVector(x, nodeId, physicsRepresentation->getNumDofPerNode()).segment<3>(0)\n\t\t\t= Vector3d(static_cast(nodeId) \/ static_cast(numNodes), 0.0, 0.0);\n\t}\n\n\t\/\/ Fix the start and end nodes\n\trestState->addBoundaryCondition(0 + 0);\n\trestState->addBoundaryCondition(0 + 1);\n\trestState->addBoundaryCondition(0 + 2);\n\trestState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 0);\n\trestState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 1);\n\trestState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 2);\n\n\tphysicsRepresentation->setInitialState(restState);\n\n\t\/\/ Adds all the FemElements\n\tfor (unsigned int beamId = 0; beamId < numNodes - 1; beamId++)\n\t{\n\t\tstd::array beamNodeIds = {{beamId, beamId + 1}};\n\t\tstd::shared_ptr beam = std::make_shared(beamNodeIds);\n\t\tbeam->setRadius(0.10);\n\t\tbeam->setMassDensity(3000.0);\n\t\tbeam->setPoissonRatio(0.45);\n\t\tbeam->setYoungModulus(1e6);\n\t\tphysicsRepresentation->addFemElement(beam);\n\t}\n}\n\nstd::shared_ptr createView(const std::string& name, int x, int y, int width, int height)\n{\n\tusing SurgSim::Graphics::OsgViewElement;\n\n\tstd::shared_ptr viewElement = std::make_shared(name);\n\tviewElement->getView()->setPosition(x, y);\n\tviewElement->getView()->setDimensions(width, height);\n\n\treturn viewElement;\n}\n\n\/\/ Generates a 1d fem comprised of adjacent elements along a straight line. The number of fem elements is determined\n\/\/ by loadModelFem1D.\nstd::shared_ptr createFem1D(const std::string& name,\n\t\t\t\t\t\t\t\t\t\t const SurgSim::Math::RigidTransform3d& gfxPose,\n\t\t\t\t\t\t\t\t\t\t const SurgSim::Math::Vector4d& color,\n\t\t\t\t\t\t\t\t\t\t SurgSim::Math::IntegrationScheme integrationScheme)\n{\n\tstd::shared_ptr physicsRepresentation\n\t\t= std::make_shared(\"Physics Representation: \" + name);\n\n\t\/\/ In this example, the physics representations are not transformed, only the graphics will be transformed\n\tloadModelFem1D(physicsRepresentation, 10);\n\n\tphysicsRepresentation->setIntegrationScheme(integrationScheme);\n\tphysicsRepresentation->setRayleighDampingMass(5e-2);\n\tphysicsRepresentation->setRayleighDampingStiffness(5e-3);\n\n\tstd::shared_ptr femSceneElement = std::make_shared(name);\n\tfemSceneElement->addComponent(physicsRepresentation);\n\n\tstd::shared_ptr> graphicsRepresentation\n\t\t= std::make_shared>(\"Graphics Representation: \" + name);\n\tgraphicsRepresentation->setInitialPose(gfxPose);\n\tgraphicsRepresentation->setColor(color);\n\tgraphicsRepresentation->setPointSize(3.0f);\n\tgraphicsRepresentation->setVisible(true);\n\n\tfemSceneElement->addComponent(graphicsRepresentation);\n\n\tfemSceneElement->addComponent(\n\t\tstd::make_shared>(\"Transfer from Physics to Graphics: \" + name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t physicsRepresentation->getFinalState(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t graphicsRepresentation->getVertices()));\n\n\treturn femSceneElement;\n}\n\n} \/\/ anonymous namespace\n\n\nint main(int argc, char* argv[])\n{\n\tusing SurgSim::Math::makeRigidTransform;\n\tusing SurgSim::Math::Vector4d;\n\n\tstd::shared_ptr graphicsManager = std::make_shared();\n\tstd::shared_ptr physicsManager = std::make_shared();\n\tstd::shared_ptr behaviorManager\n\t\t= std::make_shared();\n\tstd::shared_ptr runtime = std::make_shared();\n\n\truntime->addManager(physicsManager);\n\truntime->addManager(graphicsManager);\n\truntime->addManager(behaviorManager);\n\n\tstd::shared_ptr camera = graphicsManager->getDefaultCamera();\n\tstd::shared_ptr scene = runtime->getScene();\n\n\tconst SurgSim::Math::Quaterniond quaternionIdentity = SurgSim::Math::Quaterniond::Identity();\n\n\tscene->addSceneElement(\n\t\tcreateFem1D(\"Euler Explicit\", \/\/ name\n\t\t\t\t\tmakeRigidTransform(quaternionIdentity, Vector3d(-3.5, 0.5, -3.0)), \/\/ graphics pose (rot., trans.)\n\t\t\t\t\tVector4d(1, 0, 0, 1), \/\/ color (r, g, b, a)\n\t\t\t\t\tSurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)); \/\/ technique to update object\n\n\tscene->addSceneElement(\n\t\tcreateFem1D(\"Modified Euler Explicit\",\n\t\t\t\t\tmakeRigidTransform(quaternionIdentity, Vector3d(-0.5, 0.5, -3.0)),\n\t\t\t\t\tVector4d(0, 1, 0, 1),\n\t\t\t\t\tSurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));\n\n\tscene->addSceneElement(\n\t\tcreateFem1D(\"Euler Implicit\",\n\t\t\t\t\tmakeRigidTransform(quaternionIdentity, Vector3d(2.5, 0.5, -3.0)),\n\t\t\t\t\tVector4d(0, 0, 1, 1),\n\t\t\t\t\tSurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));\n\n\tscene->addSceneElement(createView(\"view1\", 0, 0, 1023, 768));\n\n\tcamera->setInitialPose(SurgSim::Math::makeRigidTransform(quaternionIdentity, Vector3d(0.0, 0.5, 5.0)));\n\n\truntime->execute();\n\n\treturn 0;\n}\nMinor fix fem1d example, reduce visual spacing\/\/ This file is a part of the OpenSurgSim project.\n\/\/ Copyright 2013, SimQuest Solutions Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \"SurgSim\/Blocks\/BasicSceneElement.h\"\n#include \"SurgSim\/Blocks\/TransferDeformableStateToVerticesBehavior.h\"\n#include \"SurgSim\/Framework\/BehaviorManager.h\"\n#include \"SurgSim\/Framework\/Runtime.h\"\n#include \"SurgSim\/Framework\/Scene.h\"\n#include \"SurgSim\/Framework\/SceneElement.h\"\n#include \"SurgSim\/Graphics\/OsgCamera.h\"\n#include \"SurgSim\/Graphics\/OsgManager.h\"\n#include \"SurgSim\/Graphics\/OsgPointCloudRepresentation.h\"\n#include \"SurgSim\/Graphics\/OsgView.h\"\n#include \"SurgSim\/Graphics\/OsgViewElement.h\"\n#include \"SurgSim\/Graphics\/PointCloudRepresentation.h\"\n#include \"SurgSim\/Math\/Quaternion.h\"\n#include \"SurgSim\/Math\/RigidTransform.h\"\n#include \"SurgSim\/Math\/Vector.h\"\n#include \"SurgSim\/Physics\/Fem1DRepresentation.h\"\n#include \"SurgSim\/Physics\/FemElement1DBeam.h\"\n#include \"SurgSim\/Physics\/PhysicsManager.h\"\n\nusing SurgSim::Blocks::BasicSceneElement;\nusing SurgSim::Blocks::TransferDeformableStateToVerticesBehavior;\nusing SurgSim::Framework::SceneElement;\nusing SurgSim::Graphics::OsgPointCloudRepresentation;\nusing SurgSim::Math::Vector3d;\nusing SurgSim::Physics::DeformableRepresentationState;\nusing SurgSim::Physics::Fem1DRepresentation;\nusing SurgSim::Physics::FemElement1DBeam;\nusing SurgSim::Physics::PhysicsManager;\n\n\/\/\/\\file Example of how to put together a very simple demo of Fem1D\n\nnamespace\n{\n\nvoid loadModelFem1D(std::shared_ptr physicsRepresentation, unsigned int numNodes)\n{\n\tstd::shared_ptr restState = std::make_shared();\n\trestState->setNumDof(physicsRepresentation->getNumDofPerNode(), numNodes);\n\n\t\/\/ Sets the initial state (node positions and boundary conditions)\n\tSurgSim::Math::Vector& x = restState->getPositions();\n\tfor (unsigned int nodeId = 0; nodeId < numNodes; nodeId++)\n\t{\n\t\tSurgSim::Math::getSubVector(x, nodeId, physicsRepresentation->getNumDofPerNode()).segment<3>(0)\n\t\t\t= Vector3d(static_cast(nodeId) \/ static_cast(numNodes), 0.0, 0.0);\n\t}\n\n\t\/\/ Fix the start and end nodes\n\trestState->addBoundaryCondition(0 + 0);\n\trestState->addBoundaryCondition(0 + 1);\n\trestState->addBoundaryCondition(0 + 2);\n\trestState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 0);\n\trestState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 1);\n\trestState->addBoundaryCondition((numNodes - 1) * physicsRepresentation->getNumDofPerNode() + 2);\n\n\tphysicsRepresentation->setInitialState(restState);\n\n\t\/\/ Adds all the FemElements\n\tfor (unsigned int beamId = 0; beamId < numNodes - 1; beamId++)\n\t{\n\t\tstd::array beamNodeIds = {{beamId, beamId + 1}};\n\t\tstd::shared_ptr beam = std::make_shared(beamNodeIds);\n\t\tbeam->setRadius(0.10);\n\t\tbeam->setMassDensity(3000.0);\n\t\tbeam->setPoissonRatio(0.45);\n\t\tbeam->setYoungModulus(1e6);\n\t\tphysicsRepresentation->addFemElement(beam);\n\t}\n}\n\nstd::shared_ptr createView(const std::string& name, int x, int y, int width, int height)\n{\n\tusing SurgSim::Graphics::OsgViewElement;\n\n\tstd::shared_ptr viewElement = std::make_shared(name);\n\tviewElement->getView()->setPosition(x, y);\n\tviewElement->getView()->setDimensions(width, height);\n\n\treturn viewElement;\n}\n\n\/\/ Generates a 1d fem comprised of adjacent elements along a straight line. The number of fem elements is determined\n\/\/ by loadModelFem1D.\nstd::shared_ptr createFem1D(const std::string& name,\n\t\t\t\t\t\t\t\t\t\t const SurgSim::Math::RigidTransform3d& gfxPose,\n\t\t\t\t\t\t\t\t\t\t const SurgSim::Math::Vector4d& color,\n\t\t\t\t\t\t\t\t\t\t SurgSim::Math::IntegrationScheme integrationScheme)\n{\n\tstd::shared_ptr physicsRepresentation\n\t\t= std::make_shared(\"Physics Representation: \" + name);\n\n\t\/\/ In this example, the physics representations are not transformed, only the graphics will be transformed\n\tloadModelFem1D(physicsRepresentation, 10);\n\n\tphysicsRepresentation->setIntegrationScheme(integrationScheme);\n\tphysicsRepresentation->setRayleighDampingMass(5e-2);\n\tphysicsRepresentation->setRayleighDampingStiffness(5e-3);\n\n\tstd::shared_ptr femSceneElement = std::make_shared(name);\n\tfemSceneElement->addComponent(physicsRepresentation);\n\n\tstd::shared_ptr> graphicsRepresentation\n\t\t= std::make_shared>(\"Graphics Representation: \" + name);\n\tgraphicsRepresentation->setInitialPose(gfxPose);\n\tgraphicsRepresentation->setColor(color);\n\tgraphicsRepresentation->setPointSize(3.0f);\n\tgraphicsRepresentation->setVisible(true);\n\n\tfemSceneElement->addComponent(graphicsRepresentation);\n\n\tfemSceneElement->addComponent(\n\t\tstd::make_shared>(\"Transfer from Physics to Graphics: \" + name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t physicsRepresentation->getFinalState(),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t graphicsRepresentation->getVertices()));\n\n\treturn femSceneElement;\n}\n\n} \/\/ anonymous namespace\n\n\nint main(int argc, char* argv[])\n{\n\tusing SurgSim::Math::makeRigidTransform;\n\tusing SurgSim::Math::Vector4d;\n\n\tstd::shared_ptr graphicsManager = std::make_shared();\n\tstd::shared_ptr physicsManager = std::make_shared();\n\tstd::shared_ptr behaviorManager\n\t\t= std::make_shared();\n\tstd::shared_ptr runtime = std::make_shared();\n\n\truntime->addManager(physicsManager);\n\truntime->addManager(graphicsManager);\n\truntime->addManager(behaviorManager);\n\n\tstd::shared_ptr camera = graphicsManager->getDefaultCamera();\n\tstd::shared_ptr scene = runtime->getScene();\n\n\tconst SurgSim::Math::Quaterniond quaternionIdentity = SurgSim::Math::Quaterniond::Identity();\n\n\tscene->addSceneElement(\n\t\tcreateFem1D(\"Euler Explicit\", \/\/ name\n\t\t\t\t\tmakeRigidTransform(quaternionIdentity, Vector3d(-3.0, 0.5, -3.0)), \/\/ graphics pose (rot., trans.)\n\t\t\t\t\tVector4d(1, 0, 0, 1), \/\/ color (r, g, b, a)\n\t\t\t\t\tSurgSim::Math::INTEGRATIONSCHEME_EXPLICIT_EULER)); \/\/ technique to update object\n\n\tscene->addSceneElement(\n\t\tcreateFem1D(\"Modified Euler Explicit\",\n\t\t\t\t\tmakeRigidTransform(quaternionIdentity, Vector3d(-0.5, 0.5, -3.0)),\n\t\t\t\t\tVector4d(0, 1, 0, 1),\n\t\t\t\t\tSurgSim::Math::INTEGRATIONSCHEME_MODIFIED_EXPLICIT_EULER));\n\n\tscene->addSceneElement(\n\t\tcreateFem1D(\"Euler Implicit\",\n\t\t\t\t\tmakeRigidTransform(quaternionIdentity, Vector3d(2.0, 0.5, -3.0)),\n\t\t\t\t\tVector4d(0, 0, 1, 1),\n\t\t\t\t\tSurgSim::Math::INTEGRATIONSCHEME_IMPLICIT_EULER));\n\n\tscene->addSceneElement(createView(\"view1\", 0, 0, 1023, 768));\n\n\tcamera->setInitialPose(SurgSim::Math::makeRigidTransform(quaternionIdentity, Vector3d(0.0, 0.5, 5.0)));\n\n\truntime->execute();\n\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/\/ Halide tutorial lesson 16: RGB images and memory layouts part 1\n\n\/\/ This lesson demonstrates how to feed Halide RGB images in\n\/\/ interleaved or planar format, and how to write code optimized for\n\/\/ each case.\n\n\/\/ On linux or os x, you can compile and run it like so:\n\n\/\/ g++ lesson_16_rgb_generate.cpp ..\/tools\/GenGen.cpp -g -std=c++11 -fno-rtti -I ..\/include -L ..\/bin -lHalide -lpthread -ldl -o lesson_16_generate\n\/\/ export LD_LIBRARY_PATH=..\/bin # For linux\n\/\/ export DYLD_LIBRARY_PATH=..\/bin # For OS X\n\/\/ .\/lesson_16_generate -o . -f brighten_planar target=host layout=planar\n\/\/ .\/lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved\n\/\/ .\/lesson_16_generate -o . -f brighten_either target=host layout=either\n\/\/ .\/lesson_16_generate -o . -f brighten_specialized target=host layout=specialized\n\/\/ g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run\n\/\/ .\/lesson_16_run\n\n\/\/ If you have the entire Halide source tree, you can also build it by\n\/\/ running:\n\/\/ make tutorial_lesson_16_rgb_run\n\/\/ in a shell with the current directory at the top of the halide\n\/\/ source tree.\n\n#include \"Halide.h\"\n#include \n\nusing namespace Halide;\n\n\/\/ We will define a generator that brightens an RGB image.\nclass Brighten : public Halide::Generator {\npublic:\n \/\/ We declare a three-dimensional input image. The first two\n \/\/ dimensions will be x, and y, and the third dimension will be\n \/\/ the color channel.\n ImageParam input{UInt(8), 3, \"input\"};\n\n \/\/ We will compile this generator in several ways to accept\n \/\/ several different memory layouts for the input and output. This\n \/\/ is a good use of a GeneratorParam (see lesson 15).\n enum class Layout { Planar, Interleaved, Either, Specialized };\n GeneratorParam layout{\"layout\",\n \/\/ default value\n Layout::Planar,\n \/\/ map from names to values\n {{ \"planar\", Layout::Planar },\n { \"interleaved\", Layout::Interleaved },\n { \"either\", Layout::Either },\n { \"specialized\", Layout::Specialized }}};\n\n \/\/ We also declare a scalar parameter to control the amount of\n \/\/ brightening.\n Param offset{\"offset\"};\n\n \/\/ Declare our Vars\n Var x, y, c;\n\n Func build() {\n \/\/ Define the Func.\n Func brighter(\"brighter\");\n brighter(x, y, c) = input(x, y, c) + offset;\n\n \/\/ Schedule it.\n brighter.vectorize(x, 16);\n\n \/\/ We will compile this pipeline to handle memory layouts in\n \/\/ several different ways, depending on the 'layout' generator\n \/\/ param.\n if (layout == Layout::Planar) {\n \/\/ This pipeline as written will only work with images in\n \/\/ which each scanline is densely-packed single color\n \/\/ channel. In terms of the strides described in lesson\n \/\/ 10, Halide assumes and asserts that the stride in x is\n \/\/ one.\n\n \/\/ This constraint permits planar images, where the red,\n \/\/ green, and blue channels are laid out in memory like\n \/\/ this:\n\n \/\/ RRRRRRRR\n \/\/ RRRRRRRR\n \/\/ RRRRRRRR\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ GGGGGGGG\n \/\/ GGGGGGGG\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ BBBBBBBB\n \/\/ BBBBBBBB\n \/\/ BBBBBBBB\n\n \/\/ It also works with the less-commonly used line-by-line\n \/\/ layout, in which scanlines of red, green, and blue\n \/\/ alternate.\n\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n\n } else if (layout == Layout::Interleaved) {\n \/\/ Another common format is 'interleaved', in which the\n \/\/ red, green, and blue values for each pixel occur next\n \/\/ to each other in memory:\n\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n\n \/\/ In this case the stride in x is three, the stride in y\n \/\/ is three times the width of the image, and the stride\n \/\/ in c is one. We can tell Halide to assume (and assert)\n \/\/ that this is the case for the input and output like so:\n\n input\n .set_stride(0, 3) \/\/ stride in dimension 0 (x) is three\n .set_stride(2, 1); \/\/ stride in dimension 2 (c) is one\n\n brighter.output_buffer()\n .set_stride(0, 3)\n .set_stride(2, 1);\n\n \/\/ For interleaved layout, you may want to use a different\n \/\/ schedule. We'll tell Halide to additionally assume and\n \/\/ assert that there are three color channels, then\n \/\/ exploit this fact to make the loop over 'c' innermost\n \/\/ and unrolled.\n\n input.set_bounds(2, 0, 3); \/\/ Dimension 2 (c) starts at 0 and has extent 3.\n brighter.output_buffer().set_bounds(2, 0, 3);\n\n \/\/ Move the loop over color channels innermost and unroll\n \/\/ it.\n brighter.reorder(c, x, y).unroll(c);\n\n \/\/ Note that if we were dealing with an image with an\n \/\/ alpha channel (RGBA), then the stride in x and the\n \/\/ bounds of the channels dimension would both be four\n \/\/ instead of three.\n\n } else if (layout == Layout::Either) {\n \/\/ We can also remove all constraints and compile a\n \/\/ pipeline that will work with any memory layout. It will\n \/\/ probably be slow, because all vector loads become\n \/\/ gathers, and all vector stores become scatters.\n input.set_stride(0, Expr()); \/\/ Use a default-constructed\n \/\/ undefined Expr to mean\n \/\/ there is no constraint.\n\n brighter.output_buffer().set_stride(0, Expr());\n\n } else if (layout == Layout::Specialized) {\n \/\/ We can accept any memory layout with good performance\n \/\/ by telling Halide to inspect the memory layout at\n \/\/ runtime, and branch to different code depending on the\n \/\/ strides it find. First we relax the default constraint\n \/\/ that stride(0) == 1:\n\n input.set_stride(0, Expr()); \/\/ Use an undefined Expr to\n \/\/ mean there is no\n \/\/ constraint.\n\n brighter.output_buffer().set_stride(0, Expr());\n\n \/\/ The we construct boolean Exprs that detect at runtime\n \/\/ whether we're planar or interleaved. The conditions\n \/\/ should check for all the facts we want to exploit in\n \/\/ each case.\n Expr input_is_planar =\n (input.stride(0) == 1);\n Expr input_is_interleaved =\n (input.stride(0) == 3 &&\n input.stride(2) == 1 &&\n input.extent(2) == 3);\n\n Expr output_is_planar =\n (brighter.output_buffer().stride(0) == 1);\n Expr output_is_interleaved =\n (brighter.output_buffer().stride(0) == 3 &&\n brighter.output_buffer().stride(2) == 1 &&\n brighter.output_buffer().extent(2) == 3);\n\n \/\/ We can then use Func::specialize to write a schedule\n \/\/ that switches at runtime to specialized code based on a\n \/\/ boolean Expr. That code will exploit the fact that the\n \/\/ Expr is known to be true.\n brighter.specialize(input_is_planar && output_is_planar);\n\n \/\/ We've already vectorized and parallelized brighter, and\n \/\/ our two specializations will inherit those scheduling\n \/\/ directives. We can also add additional scheduling\n \/\/ directives that apply to a single specialization\n \/\/ only. We'll tell Halide to make a specialized version\n \/\/ of the code for interleaved layouts, and to reorder and\n \/\/ unroll that specialized code.\n brighter.specialize(input_is_interleaved && output_is_interleaved)\n .reorder(c, x, y).unroll(c);\n\n \/\/ We could also add specializations for if the input is\n \/\/ interleaved and the output is planar, and vice versa,\n \/\/ but two specializations is enough to demonstrate the\n \/\/ feature. A later tutorial will explore more creative\n \/\/ uses of Func::specialize.\n\n \/\/ Adding specializations can improve performance\n \/\/ substantially for the cases they apply to, but it also\n \/\/ increases the amount of code to compile and ship. If\n \/\/ binary sizes are a concern and the input and output\n \/\/ memory layouts are known, you probably want to use\n \/\/ set_stride and set_extent instead.\n }\n\n return brighter;\n }\n};\n\n\/\/ As in lesson 15, we register our generator and then compile this\n\/\/ file along with tools\/GenGen.cpp.\nRegisterGenerator my_first_generator{\"brighten\"};\n\n\/\/ After compiling this file, see how to use it in\n\/\/ lesson_16_rgb_run.cpp\nFix tutorial convention\/\/ Halide tutorial lesson 16: RGB images and memory layouts part 1\n\n\/\/ This lesson demonstrates how to feed Halide RGB images in\n\/\/ interleaved or planar format, and how to write code optimized for\n\/\/ each case.\n\n\/\/ On linux or os x, you can compile and run it like so:\n\n\/\/ g++ lesson_16_rgb_generate.cpp ..\/tools\/GenGen.cpp -g -std=c++11 -fno-rtti -I ..\/include -L ..\/bin -lHalide -lpthread -ldl -o lesson_16_generate\n\/\/ export LD_LIBRARY_PATH=..\/bin # For linux\n\/\/ export DYLD_LIBRARY_PATH=..\/bin # For OS X\n\/\/ .\/lesson_16_generate -o . -f brighten_planar target=host layout=planar\n\/\/ .\/lesson_16_generate -o . -f brighten_interleaved target=host layout=interleaved\n\/\/ .\/lesson_16_generate -o . -f brighten_either target=host layout=either\n\/\/ .\/lesson_16_generate -o . -f brighten_specialized target=host layout=specialized\n\/\/ g++ lesson_16_rgb_run.cpp brighten_*.o -ldl -lpthread -o lesson_16_run\n\/\/ .\/lesson_16_run\n\n\/\/ If you have the entire Halide source tree, you can also build it by\n\/\/ running:\n\/\/ make tutorial_lesson_16_rgb_run\n\/\/ in a shell with the current directory at the top of the halide\n\/\/ source tree.\n\n#include \"Halide.h\"\n#include \n\nusing namespace Halide;\n\n\/\/ We will define a generator that brightens an RGB image.\nclass Brighten : public Halide::Generator {\npublic:\n \/\/ We declare a three-dimensional input image. The first two\n \/\/ dimensions will be x, and y, and the third dimension will be\n \/\/ the color channel.\n ImageParam input{UInt(8), 3, \"input\"};\n\n \/\/ We will compile this generator in several ways to accept\n \/\/ several different memory layouts for the input and output. This\n \/\/ is a good use of a GeneratorParam (see lesson 15).\n enum class Layout { Planar, Interleaved, Either, Specialized };\n GeneratorParam layout{\"layout\",\n \/\/ default value\n Layout::Planar,\n \/\/ map from names to values\n {{ \"planar\", Layout::Planar },\n { \"interleaved\", Layout::Interleaved },\n { \"either\", Layout::Either },\n { \"specialized\", Layout::Specialized }}};\n\n \/\/ We also declare a scalar parameter to control the amount of\n \/\/ brightening.\n Param offset{\"offset\"};\n\n \/\/ Declare our Vars\n Var x, y, c;\n\n Func build() {\n \/\/ Define the Func.\n Func brighter(\"brighter\");\n brighter(x, y, c) = input(x, y, c) + offset;\n\n \/\/ Schedule it.\n brighter.vectorize(x, 16);\n\n \/\/ We will compile this pipeline to handle memory layouts in\n \/\/ several different ways, depending on the 'layout' generator\n \/\/ param.\n if (layout == Layout::Planar) {\n \/\/ This pipeline as written will only work with images in\n \/\/ which each scanline is densely-packed single color\n \/\/ channel. In terms of the strides described in lesson\n \/\/ 10, Halide assumes and asserts that the stride in x is\n \/\/ one.\n\n \/\/ This constraint permits planar images, where the red,\n \/\/ green, and blue channels are laid out in memory like\n \/\/ this:\n\n \/\/ RRRRRRRR\n \/\/ RRRRRRRR\n \/\/ RRRRRRRR\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ GGGGGGGG\n \/\/ GGGGGGGG\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ BBBBBBBB\n \/\/ BBBBBBBB\n \/\/ BBBBBBBB\n\n \/\/ It also works with the less-commonly used line-by-line\n \/\/ layout, in which scanlines of red, green, and blue\n \/\/ alternate.\n\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n \/\/ RRRRRRRR\n \/\/ GGGGGGGG\n \/\/ BBBBBBBB\n\n } else if (layout == Layout::Interleaved) {\n \/\/ Another common format is 'interleaved', in which the\n \/\/ red, green, and blue values for each pixel occur next\n \/\/ to each other in memory:\n\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n \/\/ RGBRGBRGBRGBRGBRGBRGBRGB\n\n \/\/ In this case the stride in x is three, the stride in y\n \/\/ is three times the width of the image, and the stride\n \/\/ in c is one. We can tell Halide to assume (and assert)\n \/\/ that this is the case for the input and output like so:\n\n input\n .dim(0).set_stride(3) \/\/ stride in dimension 0 (x) is three\n .dim(2).set_stride(1); \/\/ stride in dimension 2 (c) is one\n\n brighter.output_buffer()\n .dim(0).set_stride(3)\n .dim(2).set_stride(1);\n\n \/\/ For interleaved layout, you may want to use a different\n \/\/ schedule. We'll tell Halide to additionally assume and\n \/\/ assert that there are three color channels, then\n \/\/ exploit this fact to make the loop over 'c' innermost\n \/\/ and unrolled.\n\n input.dim(2).set_bounds(0, 3); \/\/ Dimension 2 (c) starts at 0 and has extent 3.\n brighter.output_buffer().dim(2).set_bounds(0, 3);\n\n \/\/ Move the loop over color channels innermost and unroll\n \/\/ it.\n brighter.reorder(c, x, y).unroll(c);\n\n \/\/ Note that if we were dealing with an image with an\n \/\/ alpha channel (RGBA), then the stride in x and the\n \/\/ bounds of the channels dimension would both be four\n \/\/ instead of three.\n\n } else if (layout == Layout::Either) {\n \/\/ We can also remove all constraints and compile a\n \/\/ pipeline that will work with any memory layout. It will\n \/\/ probably be slow, because all vector loads become\n \/\/ gathers, and all vector stores become scatters.\n input.dim(0).set_stride(Expr()); \/\/ Use a default-constructed\n \/\/ undefined Expr to mean\n \/\/ there is no constraint.\n\n brighter.output_buffer().dim(0).set_stride(Expr());\n\n } else if (layout == Layout::Specialized) {\n \/\/ We can accept any memory layout with good performance\n \/\/ by telling Halide to inspect the memory layout at\n \/\/ runtime, and branch to different code depending on the\n \/\/ strides it find. First we relax the default constraint\n \/\/ that dim(0).stride() == 1:\n\n input.dim(0).set_stride(Expr()); \/\/ Use an undefined Expr to\n \/\/ mean there is no\n \/\/ constraint.\n\n brighter.output_buffer().dim(0).set_stride(Expr());\n\n \/\/ The we construct boolean Exprs that detect at runtime\n \/\/ whether we're planar or interleaved. The conditions\n \/\/ should check for all the facts we want to exploit in\n \/\/ each case.\n Expr input_is_planar =\n (input.dim(0).stride() == 1);\n Expr input_is_interleaved =\n (input.dim(0).stride() == 3 &&\n input.dim(2).stride() == 1 &&\n input.dim(2).extent() == 3);\n\n Expr output_is_planar =\n (brighter.output_buffer().dim(0).stride() == 1);\n Expr output_is_interleaved =\n (brighter.output_buffer().dim(0).stride() == 3 &&\n brighter.output_buffer().dim(2).stride() == 1 &&\n brighter.output_buffer().dim(2).extent() == 3);\n\n \/\/ We can then use Func::specialize to write a schedule\n \/\/ that switches at runtime to specialized code based on a\n \/\/ boolean Expr. That code will exploit the fact that the\n \/\/ Expr is known to be true.\n brighter.specialize(input_is_planar && output_is_planar);\n\n \/\/ We've already vectorized and parallelized brighter, and\n \/\/ our two specializations will inherit those scheduling\n \/\/ directives. We can also add additional scheduling\n \/\/ directives that apply to a single specialization\n \/\/ only. We'll tell Halide to make a specialized version\n \/\/ of the code for interleaved layouts, and to reorder and\n \/\/ unroll that specialized code.\n brighter.specialize(input_is_interleaved && output_is_interleaved)\n .reorder(c, x, y).unroll(c);\n\n \/\/ We could also add specializations for if the input is\n \/\/ interleaved and the output is planar, and vice versa,\n \/\/ but two specializations is enough to demonstrate the\n \/\/ feature. A later tutorial will explore more creative\n \/\/ uses of Func::specialize.\n\n \/\/ Adding specializations can improve performance\n \/\/ substantially for the cases they apply to, but it also\n \/\/ increases the amount of code to compile and ship. If\n \/\/ binary sizes are a concern and the input and output\n \/\/ memory layouts are known, you probably want to use\n \/\/ set_stride and set_extent instead.\n }\n\n return brighter;\n }\n};\n\n\/\/ As in lesson 15, we register our generator and then compile this\n\/\/ file along with tools\/GenGen.cpp.\nRegisterGenerator my_first_generator{\"brighten\"};\n\n\/\/ After compiling this file, see how to use it in\n\/\/ lesson_16_rgb_run.cpp\n<|endoftext|>"} {"text":"\/\/ @(#)root\/net:$Name: $:$Id: TGrid.cxx,v 1.8 2005\/05\/13 08:49:54 rdm Exp $\n\/\/ Author: Fons Rademakers 3\/1\/2002\n\n\/*************************************************************************\n * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGrid \/\/\n\/\/ \/\/\n\/\/ Abstract base class defining interface to common GRID services. \/\/\n\/\/ \/\/\n\/\/ To open a connection to a GRID use the static method Connect(). \/\/\n\/\/ The argument of Connect() is of the form: \/\/\n\/\/ [:\/\/][:], e.g. \/\/\n\/\/ alien, alien:\/\/alice.cern.ch, globus:\/\/glsvr1.cern.ch, ... \/\/\n\/\/ Depending on the specified an appropriate plugin library \/\/\n\/\/ will be loaded which will provide the real interface. \/\/\n\/\/ \/\/\n\/\/ Related classes are TGridResult. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGrid.h\"\n#include \"TUrl.h\"\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n#include \"TFile.h\"\n#include \"TList.h\"\n#include \"TError.h\"\n#include \"TUUID.h\"\n#include \"TSystem.h\"\n#include \"TH1.h\"\n#include \"TChain.h\"\n#include \"TKey.h\"\n\nTGrid *gGrid = 0;\n\n\nClassImp(TGrid)\n\n\n\/\/______________________________________________________________________________\nTGrid::TGrid() : fPort(-1), fMergerOutputFile(0)\n{\n \/\/ Create grid interface object.\n\n fMergerFileList = new TList;\n fMergerFileList->SetOwner(kTRUE);\n}\n\n\/\/______________________________________________________________________________\nTGrid *TGrid::Connect(const char *grid, const char *uid, const char *pw,\n const char *options)\n{\n \/\/ The grid should be of the form: :\/\/[:],\n \/\/ e.g.: alien:\/\/alice.cern.ch, globus:\/\/glsrv1.cern.ch, ...\n \/\/ The uid is the username and pw the password that should be used for\n \/\/ the connection. Depending on the the shared library (plugin)\n \/\/ for the selected system will be loaded. When the connection could not\n \/\/ be opened 0 is returned. For AliEn the supported options are:\n \/\/ -domain=\n \/\/ -debug=\n \/\/ Example: \"-domain=cern.ch -debug=5\"\n\n TPluginHandler *h;\n TGrid *g = 0;\n\n if (!grid) {\n ::Error(\"TGrid::Connect\", \"no grid specified\");\n return 0;\n }\n if (!uid)\n uid = \"\";\n if (!pw)\n pw = \"\";\n if (!options)\n options = \"\";\n\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TGrid\", grid))) {\n if (h->LoadPlugin() == -1)\n return 0;\n g = (TGrid *) h->ExecPlugin(4, grid, uid, pw, options);\n }\n\n return g;\n}\n\n\/\/______________________________________________________________________________\nTGrid::~TGrid()\n{\n \/\/ Cleanup.\n\n if (fMergerFileList)\n delete fMergerFileList;\n\n if (fMergerOutputFile)\n delete fMergerOutputFile;\n}\n\n\/\/______________________________________________________________________________\nvoid TGrid::PrintProgress(Long64_t bytesread, Long64_t size)\n{\n \/\/ Print file copy progress.\n\n fprintf(stderr, \"[TGrid::Cp] Total %.02f MB\\t|\", (Double_t)size\/1048576);\n for (int l = 0; l < 20; l++) {\n if (l < 20*bytesread\/size)\n fprintf(stderr, \"=\");\n if (l == 20*bytesread\/size)\n fprintf(stderr, \">\");\n if (l > 20*bytesread\/size)\n fprintf(stderr, \".\");\n }\n\n fWatch.Stop();\n Double_t lCopy_time = fWatch.RealTime();\n fprintf(stderr, \"| %.02f %% [%.01f MB\/s]\\r\",\n 100.0*bytesread\/size, bytesread\/lCopy_time\/1048576.);\n fWatch.Continue();\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::Cp(const char *src, const char *dst, Bool_t progressbar,\n UInt_t buffersize)\n{\n \/\/ Allows to copy file from src to dst URL.\n\n Bool_t success = kFALSE;\n\n TUrl sURL(src, kTRUE);\n TUrl dURL(dst, kTRUE);\n\n char *copybuffer = 0;\n\n TFile *sfile = 0;\n TFile *dfile = 0;\n\n sfile = TFile::Open(src, \"-READ\");\n\n if (!sfile) {\n Error(\"Cp\", \"cannot open source file %s\", src);\n goto copyout;\n }\n\n dfile = TFile::Open(dst, \"-RECREATE\");\n\n if (!dfile) {\n Error(\"Cp\", \"cannot open destination file %s\", dst);\n goto copyout;\n }\n\n sfile->Seek(0);\n dfile->Seek(0);\n\n copybuffer = new char[buffersize];\n if (!copybuffer) {\n Error(\"Cp\", \"cannot allocate the copy buffer\");\n goto copyout;\n }\n\n Bool_t readop;\n Bool_t writeop;\n Long64_t read;\n Long64_t written;\n Long64_t totalread;\n Long64_t filesize;\n filesize = sfile->GetSize();\n totalread = 0;\n fWatch.Start();\n\n Long64_t b00 = sfile->GetBytesRead();\n\n do {\n if (progressbar) PrintProgress(totalread, filesize);\n\n Long64_t b1 = sfile->GetBytesRead() - b00;\n\n Long64_t readsize;\n if (filesize - b1 > (Long64_t)buffersize) {\n readsize = buffersize;\n } else {\n readsize = filesize - b1;\n }\n\n Long64_t b0 = sfile->GetBytesRead();\n readop = sfile->ReadBuffer(copybuffer, readsize);\n read = sfile->GetBytesRead() - b0;\n if (read < 0) {\n Error(\"Cp\", \"cannot read from source file %s\", src);\n goto copyout;\n }\n\n Long64_t w0 = dfile->GetBytesWritten();\n writeop = dfile->WriteBuffer(copybuffer, read);\n written = dfile->GetBytesWritten() - w0;\n if (written != read) {\n Error(\"Cp\", \"cannot write %d bytes to destination file %s\", read, dst);\n goto copyout;\n }\n totalread += read;\n } while (read == (Long64_t)buffersize);\n\n if (progressbar) {\n PrintProgress(totalread, filesize);\n fprintf(stderr, \"\\n\");\n }\n\n success = kTRUE;\n\ncopyout:\n if (sfile) sfile->Close();\n if (dfile) dfile->Close();\n\n if (sfile) delete sfile;\n if (dfile) delete dfile;\n if (copybuffer) delete copybuffer;\n\n fWatch.Stop();\n fWatch.Reset();\n\n return success;\n}\n\n\/\/______________________________________________________________________________\nvoid TGrid::MergerReset()\n{\n \/\/ Reset merger file list.\n\n fMergerFileList->Clear();\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerAddFile(const char *url)\n{\n \/\/ Add file to file merger.\n\n TUUID uuid;\n TString localcopy = \"file:\/tmp\/\";\n localcopy += \"ROOTMERGE-\";\n localcopy += uuid.AsString();\n localcopy += \".root\";\n\n if (!Cp(url, localcopy)) {\n Error(\"MergerAddFile\", \"cannot get a local copy of file %s\", url);\n return kFALSE;\n }\n\n TFile *newfile = TFile::Open(localcopy, \"READ\");\n if (!newfile) {\n Error(\"MergerAddFile\", \"cannot open local copy %s of URL %s\",\n localcopy.Data(), url);\n return kFALSE;\n } else {\n fMergerFileList->Add(newfile);\n return kTRUE;\n }\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerOutputFile(const char *outputfile)\n{\n \/\/ Open merger output file.\n\n if (fMergerOutputFile)\n delete fMergerOutputFile;\n\n fMergerOutputFilename = outputfile;\n\n TUUID uuid;\n TString localcopy = \"file:\/tmp\/\";\n localcopy += \"ROOTMERGED-\";\n localcopy += uuid.AsString();\n localcopy += \".root\";\n\n fMergerOutputFile = TFile::Open(localcopy, \"RECREATE\");\n fMergerOutputFilename1 = localcopy;\n\n if (!fMergerOutputFile) {\n Error(\"MergerOutputFile\", \"cannot open the MERGER outputfile %s\", localcopy.Data());\n return kFALSE;\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGrid::MergerPrintFiles(Option_t *options)\n{\n \/\/ Print list of files being merged.\n\n fMergerFileList->Print(options);\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerMerge()\n{\n \/\/ Merge the files.\n\n if (!fMergerOutputFile) {\n Info(\"MergerMerge\", \"will merge the results to the file \"\n \"GridMergerMerged.root in your working directory, \"\n \"since you didn't specify a merge filename\");\n if (!MergerOutputFile(\"GridMergerMerged.root\")) {\n return kFALSE;\n }\n }\n\n Bool_t result = MergerMergeRecursive(fMergerOutputFile, fMergerFileList);\n if (!result) {\n Error(\"MergerMerge\", \"error during merge of your ROOT files\");\n } else {\n fMergerOutputFile->Write();\n \/\/ copy the result file to the final destination\n Cp(fMergerOutputFilename1, fMergerOutputFilename);\n }\n\n \/\/ remove the temporary result file\n TString path(fMergerOutputFile->GetPath());\n path = path(0, path.Index(':',0));\n gSystem->Unlink(path);\n fMergerOutputFile = 0;\n\n TIter next(fMergerFileList);\n TFile *file;\n while ((file = (TFile*) next())) {\n \/\/ close the files\n file->Close();\n \/\/ remove the temporary files\n TString path(file->GetPath());\n path = path(0, path.Index(':',0));\n gSystem->Unlink(path);\n }\n return result;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerMergeRecursive(TDirectory *target, TList *sourcelist)\n{\n \/\/ Recursively merge objects in the ROOT files.\n\n TString path(strstr(target->GetPath(), \":\"));\n path.Remove(0, 2);\n\n TFile *first_source = (TFile*)sourcelist->First();\n first_source->cd(path);\n TDirectory *current_sourcedir = gDirectory;\n\n TChain *globChain = 0;\n TIter nextkey(current_sourcedir->GetListOfKeys());\n TKey *key;\n Bool_t success = kTRUE;\n\n \/\/ gain time, do not add the objects in the list in memory\n TH1::AddDirectory(kFALSE);\n\n while ((key = (TKey*) nextkey())) {\n first_source->cd(path);\n TObject *obj = key->ReadObj();\n\n if (obj->IsA()->InheritsFrom(\"TH1\")) {\n Info(\"MergerMergeRecursive\", \"merging histogram %s\", obj->GetName());\n TH1 *h1 = (TH1*)obj;\n\n TFile *nextsource = (TFile*)sourcelist->After(first_source);\n while (nextsource) {\n\n nextsource->cd(path);\n TH1 *h2 = (TH1*)gDirectory->Get(h1->GetName());\n if (h2) {\n h1->Add(h2);\n delete h2;\n }\n\n nextsource = (TFile*)sourcelist->After(nextsource);\n }\n } else if (obj->IsA()->InheritsFrom(\"TTree\")) {\n Info(\"MergerMergeRecursive\", \"merging tree %s\", obj->GetName());\n const char *obj_name= obj->GetName();\n\n globChain = new TChain(obj_name);\n globChain->Add(first_source->GetName());\n TFile *nextsource = (TFile*)sourcelist->After(first_source);\n while (nextsource) {\n globChain->Add(nextsource->GetName());\n nextsource = (TFile*)sourcelist->After(nextsource);\n }\n\n } else if (obj->IsA()->InheritsFrom(\"TDirectory\")) {\n target->cd();\n TDirectory *newdir = target->mkdir(obj->GetName(), obj->GetTitle());\n if (!MergerMergeRecursive(newdir, sourcelist)) {\n Error(\"MergerMergeRecursive\", \"error during merge of directory %s\",\n newdir->GetPath());\n success = kFALSE;\n }\n } else {\n Error(\"MergerMergeRecursive\", \"unknown object type, name: %s title: %s\",\n obj->GetName(), obj->GetTitle());\n success = kFALSE;\n }\n\n if (obj) {\n target->cd();\n\n if (obj->IsA()->InheritsFrom(\"TTree\")) {\n globChain->Merge(target->GetFile() ,0, \"keep\");\n delete globChain;\n } else\n obj->Write(key->GetName());\n }\n\n } \/\/ nextkey\n\n target->Write();\n\n TH1::AddDirectory(kTRUE);\n\n return success;\n}\nFix compile problem on MacOS X.\/\/ @(#)root\/net:$Name: $:$Id: TGrid.cxx,v 1.9 2005\/05\/20 09:59:35 rdm Exp $\n\/\/ Author: Fons Rademakers 3\/1\/2002\n\n\/*************************************************************************\n * Copyright (C) 1995-2002, Rene Brun and Fons Rademakers. *\n * All rights reserved. *\n * *\n * For the licensing terms see $ROOTSYS\/LICENSE. *\n * For the list of contributors see $ROOTSYS\/README\/CREDITS. *\n *************************************************************************\/\n\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\/\/ \/\/\n\/\/ TGrid \/\/\n\/\/ \/\/\n\/\/ Abstract base class defining interface to common GRID services. \/\/\n\/\/ \/\/\n\/\/ To open a connection to a GRID use the static method Connect(). \/\/\n\/\/ The argument of Connect() is of the form: \/\/\n\/\/ [:\/\/][:], e.g. \/\/\n\/\/ alien, alien:\/\/alice.cern.ch, globus:\/\/glsvr1.cern.ch, ... \/\/\n\/\/ Depending on the specified an appropriate plugin library \/\/\n\/\/ will be loaded which will provide the real interface. \/\/\n\/\/ \/\/\n\/\/ Related classes are TGridResult. \/\/\n\/\/ \/\/\n\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\n\n#include \"TGrid.h\"\n#include \"TUrl.h\"\n#include \"TROOT.h\"\n#include \"TPluginManager.h\"\n#include \"TFile.h\"\n#include \"TList.h\"\n#include \"TError.h\"\n#include \"TUUID.h\"\n#include \"TSystem.h\"\n#include \"TH1.h\"\n#include \"TChain.h\"\n#include \"TKey.h\"\n\nTGrid *gGrid = 0;\n\n\nClassImp(TGrid)\n\n\n\/\/______________________________________________________________________________\nTGrid::TGrid() : fPort(-1), fMergerOutputFile(0)\n{\n \/\/ Create grid interface object.\n\n fMergerFileList = new TList;\n fMergerFileList->SetOwner(kTRUE);\n}\n\n\/\/______________________________________________________________________________\nTGrid *TGrid::Connect(const char *grid, const char *uid, const char *pw,\n const char *options)\n{\n \/\/ The grid should be of the form: :\/\/[:],\n \/\/ e.g.: alien:\/\/alice.cern.ch, globus:\/\/glsrv1.cern.ch, ...\n \/\/ The uid is the username and pw the password that should be used for\n \/\/ the connection. Depending on the the shared library (plugin)\n \/\/ for the selected system will be loaded. When the connection could not\n \/\/ be opened 0 is returned. For AliEn the supported options are:\n \/\/ -domain=\n \/\/ -debug=\n \/\/ Example: \"-domain=cern.ch -debug=5\"\n\n TPluginHandler *h;\n TGrid *g = 0;\n\n if (!grid) {\n ::Error(\"TGrid::Connect\", \"no grid specified\");\n return 0;\n }\n if (!uid)\n uid = \"\";\n if (!pw)\n pw = \"\";\n if (!options)\n options = \"\";\n\n if ((h = gROOT->GetPluginManager()->FindHandler(\"TGrid\", grid))) {\n if (h->LoadPlugin() == -1)\n return 0;\n g = (TGrid *) h->ExecPlugin(4, grid, uid, pw, options);\n }\n\n return g;\n}\n\n\/\/______________________________________________________________________________\nTGrid::~TGrid()\n{\n \/\/ Cleanup.\n\n if (fMergerFileList)\n delete fMergerFileList;\n\n if (fMergerOutputFile)\n delete fMergerOutputFile;\n}\n\n\/\/______________________________________________________________________________\nvoid TGrid::PrintProgress(Long64_t bytesread, Long64_t size)\n{\n \/\/ Print file copy progress.\n\n fprintf(stderr, \"[TGrid::Cp] Total %.02f MB\\t|\", (Double_t)size\/1048576);\n for (int l = 0; l < 20; l++) {\n if (l < 20*bytesread\/size)\n fprintf(stderr, \"=\");\n if (l == 20*bytesread\/size)\n fprintf(stderr, \">\");\n if (l > 20*bytesread\/size)\n fprintf(stderr, \".\");\n }\n\n fWatch.Stop();\n Double_t lCopy_time = fWatch.RealTime();\n fprintf(stderr, \"| %.02f %% [%.01f MB\/s]\\r\",\n 100.0*bytesread\/size, bytesread\/lCopy_time\/1048576.);\n fWatch.Continue();\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::Cp(const char *src, const char *dst, Bool_t progressbar,\n UInt_t buffersize)\n{\n \/\/ Allows to copy file from src to dst URL.\n\n Bool_t success = kFALSE;\n\n TUrl sURL(src, kTRUE);\n TUrl dURL(dst, kTRUE);\n\n char *copybuffer = 0;\n\n TFile *sfile = 0;\n TFile *dfile = 0;\n\n sfile = TFile::Open(src, \"-READ\");\n\n if (!sfile) {\n Error(\"Cp\", \"cannot open source file %s\", src);\n goto copyout;\n }\n\n dfile = TFile::Open(dst, \"-RECREATE\");\n\n if (!dfile) {\n Error(\"Cp\", \"cannot open destination file %s\", dst);\n goto copyout;\n }\n\n sfile->Seek(0);\n dfile->Seek(0);\n\n copybuffer = new char[buffersize];\n if (!copybuffer) {\n Error(\"Cp\", \"cannot allocate the copy buffer\");\n goto copyout;\n }\n\n Bool_t readop;\n Bool_t writeop;\n Long64_t read;\n Long64_t written;\n Long64_t totalread;\n Long64_t filesize;\n Long64_t b00;\n filesize = sfile->GetSize();\n totalread = 0;\n fWatch.Start();\n\n b00 = (Long64_t)sfile->GetBytesRead();\n\n do {\n if (progressbar) PrintProgress(totalread, filesize);\n\n Long64_t b1 = (Long64_t)sfile->GetBytesRead() - b00;\n\n Long64_t readsize;\n if (filesize - b1 > (Long64_t)buffersize) {\n readsize = buffersize;\n } else {\n readsize = filesize - b1;\n }\n\n Long64_t b0 = (Long64_t)sfile->GetBytesRead();\n readop = sfile->ReadBuffer(copybuffer, readsize);\n read = (Long64_t)sfile->GetBytesRead() - b0;\n if (read < 0) {\n Error(\"Cp\", \"cannot read from source file %s\", src);\n goto copyout;\n }\n\n Long64_t w0 = (Long64_t)dfile->GetBytesWritten();\n writeop = dfile->WriteBuffer(copybuffer, read);\n written = (Long64_t)dfile->GetBytesWritten() - w0;\n if (written != read) {\n Error(\"Cp\", \"cannot write %d bytes to destination file %s\", read, dst);\n goto copyout;\n }\n totalread += read;\n } while (read == (Long64_t)buffersize);\n\n if (progressbar) {\n PrintProgress(totalread, filesize);\n fprintf(stderr, \"\\n\");\n }\n\n success = kTRUE;\n\ncopyout:\n if (sfile) sfile->Close();\n if (dfile) dfile->Close();\n\n if (sfile) delete sfile;\n if (dfile) delete dfile;\n if (copybuffer) delete copybuffer;\n\n fWatch.Stop();\n fWatch.Reset();\n\n return success;\n}\n\n\/\/______________________________________________________________________________\nvoid TGrid::MergerReset()\n{\n \/\/ Reset merger file list.\n\n fMergerFileList->Clear();\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerAddFile(const char *url)\n{\n \/\/ Add file to file merger.\n\n TUUID uuid;\n TString localcopy = \"file:\/tmp\/\";\n localcopy += \"ROOTMERGE-\";\n localcopy += uuid.AsString();\n localcopy += \".root\";\n\n if (!Cp(url, localcopy)) {\n Error(\"MergerAddFile\", \"cannot get a local copy of file %s\", url);\n return kFALSE;\n }\n\n TFile *newfile = TFile::Open(localcopy, \"READ\");\n if (!newfile) {\n Error(\"MergerAddFile\", \"cannot open local copy %s of URL %s\",\n localcopy.Data(), url);\n return kFALSE;\n } else {\n fMergerFileList->Add(newfile);\n return kTRUE;\n }\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerOutputFile(const char *outputfile)\n{\n \/\/ Open merger output file.\n\n if (fMergerOutputFile)\n delete fMergerOutputFile;\n\n fMergerOutputFilename = outputfile;\n\n TUUID uuid;\n TString localcopy = \"file:\/tmp\/\";\n localcopy += \"ROOTMERGED-\";\n localcopy += uuid.AsString();\n localcopy += \".root\";\n\n fMergerOutputFile = TFile::Open(localcopy, \"RECREATE\");\n fMergerOutputFilename1 = localcopy;\n\n if (!fMergerOutputFile) {\n Error(\"MergerOutputFile\", \"cannot open the MERGER outputfile %s\", localcopy.Data());\n return kFALSE;\n }\n return kTRUE;\n}\n\n\/\/______________________________________________________________________________\nvoid TGrid::MergerPrintFiles(Option_t *options)\n{\n \/\/ Print list of files being merged.\n\n fMergerFileList->Print(options);\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerMerge()\n{\n \/\/ Merge the files.\n\n if (!fMergerOutputFile) {\n Info(\"MergerMerge\", \"will merge the results to the file \"\n \"GridMergerMerged.root in your working directory, \"\n \"since you didn't specify a merge filename\");\n if (!MergerOutputFile(\"GridMergerMerged.root\")) {\n return kFALSE;\n }\n }\n\n Bool_t result = MergerMergeRecursive(fMergerOutputFile, fMergerFileList);\n if (!result) {\n Error(\"MergerMerge\", \"error during merge of your ROOT files\");\n } else {\n fMergerOutputFile->Write();\n \/\/ copy the result file to the final destination\n Cp(fMergerOutputFilename1, fMergerOutputFilename);\n }\n\n \/\/ remove the temporary result file\n TString path(fMergerOutputFile->GetPath());\n path = path(0, path.Index(':',0));\n gSystem->Unlink(path);\n fMergerOutputFile = 0;\n\n TIter next(fMergerFileList);\n TFile *file;\n while ((file = (TFile*) next())) {\n \/\/ close the files\n file->Close();\n \/\/ remove the temporary files\n TString path(file->GetPath());\n path = path(0, path.Index(':',0));\n gSystem->Unlink(path);\n }\n return result;\n}\n\n\/\/______________________________________________________________________________\nBool_t TGrid::MergerMergeRecursive(TDirectory *target, TList *sourcelist)\n{\n \/\/ Recursively merge objects in the ROOT files.\n\n TString path(strstr(target->GetPath(), \":\"));\n path.Remove(0, 2);\n\n TFile *first_source = (TFile*)sourcelist->First();\n first_source->cd(path);\n TDirectory *current_sourcedir = gDirectory;\n\n TChain *globChain = 0;\n TIter nextkey(current_sourcedir->GetListOfKeys());\n TKey *key;\n Bool_t success = kTRUE;\n\n \/\/ gain time, do not add the objects in the list in memory\n TH1::AddDirectory(kFALSE);\n\n while ((key = (TKey*) nextkey())) {\n first_source->cd(path);\n TObject *obj = key->ReadObj();\n\n if (obj->IsA()->InheritsFrom(\"TH1\")) {\n Info(\"MergerMergeRecursive\", \"merging histogram %s\", obj->GetName());\n TH1 *h1 = (TH1*)obj;\n\n TFile *nextsource = (TFile*)sourcelist->After(first_source);\n while (nextsource) {\n\n nextsource->cd(path);\n TH1 *h2 = (TH1*)gDirectory->Get(h1->GetName());\n if (h2) {\n h1->Add(h2);\n delete h2;\n }\n\n nextsource = (TFile*)sourcelist->After(nextsource);\n }\n } else if (obj->IsA()->InheritsFrom(\"TTree\")) {\n Info(\"MergerMergeRecursive\", \"merging tree %s\", obj->GetName());\n const char *obj_name= obj->GetName();\n\n globChain = new TChain(obj_name);\n globChain->Add(first_source->GetName());\n TFile *nextsource = (TFile*)sourcelist->After(first_source);\n while (nextsource) {\n globChain->Add(nextsource->GetName());\n nextsource = (TFile*)sourcelist->After(nextsource);\n }\n\n } else if (obj->IsA()->InheritsFrom(\"TDirectory\")) {\n target->cd();\n TDirectory *newdir = target->mkdir(obj->GetName(), obj->GetTitle());\n if (!MergerMergeRecursive(newdir, sourcelist)) {\n Error(\"MergerMergeRecursive\", \"error during merge of directory %s\",\n newdir->GetPath());\n success = kFALSE;\n }\n } else {\n Error(\"MergerMergeRecursive\", \"unknown object type, name: %s title: %s\",\n obj->GetName(), obj->GetTitle());\n success = kFALSE;\n }\n\n if (obj) {\n target->cd();\n\n if (obj->IsA()->InheritsFrom(\"TTree\")) {\n globChain->Merge(target->GetFile() ,0, \"keep\");\n delete globChain;\n } else\n obj->Write(key->GetName());\n }\n\n } \/\/ nextkey\n\n target->Write();\n\n TH1::AddDirectory(kTRUE);\n\n return success;\n}\n<|endoftext|>"} {"text":"improved VCOM Toggle<|endoftext|>"} {"text":"WaE: possible loss of data<|endoftext|>"} {"text":"#ifndef __RANK_FILTER__\n#define __RANK_FILTER__\n\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace rank_filter\n{\n\ntemplate\ninline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,\n I2& dest_begin, I2& dest_end,\n size_t half_length, double rank)\n{\n \/\/ Types in use.\n typedef typename std::iterator_traits::value_type T1;\n typedef typename std::iterator_traits::value_type T2;\n typedef typename std::iterator_traits::difference_type I1_diff_t;\n typedef typename std::iterator_traits::difference_type I2_diff_t;\n\n \/\/ Establish common types to work with source and destination values.\n BOOST_STATIC_ASSERT((boost::is_same::value));\n typedef T1 T;\n typedef typename boost::common_type::type I_diff_t;\n\n \/\/ Define container types that will be used.\n typedef boost::container::multiset< T,\n std::less,\n boost::container::node_allocator,\n boost::container::tree_assoc_options< boost::container::tree_type >::type> multiset;\n typedef std::deque< typename multiset::iterator > deque;\n\n \/\/ Lengths.\n const I_diff_t src_size = std::distance(src_begin, src_end);\n const I_diff_t dest_size = std::distance(dest_begin, dest_end);\n\n \/\/ Ensure the result will fit.\n assert(src_size <= dest_size);\n\n \/\/ Window length cannot exceed input data with reflection.\n assert((half_length + 1) <= src_size);\n\n \/\/ Rank must be in the range 0 to 1.\n assert((0 <= rank) && (rank <= 1));\n\n \/\/ The position of the window.\n I_diff_t window_begin = 0;\n\n \/\/ Find window offset corresponding to this rank.\n const I_diff_t rank_pos = static_cast(boost::math::round(rank * (2 * half_length)));\n\n multiset sorted_window;\n deque window_iters(2 * half_length + 1);\n\n \/\/ Get the initial sorted window.\n \/\/ Include the reflection.\n for (I_diff_t j = 0; j < half_length; j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]);\n }\n for (I_diff_t j = half_length; j < (2 * half_length + 1); j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]);\n }\n\n typename multiset::iterator rank_point = sorted_window.begin();\n\n for (I_diff_t i = 0; i < rank_pos; i++)\n {\n rank_point++;\n }\n\n typename multiset::iterator prev_iter;\n T prev_value;\n T next_value;\n while ( window_begin < src_size )\n {\n dest_begin[window_begin] = *rank_point;\n\n prev_iter = window_iters.front();\n prev_value = *prev_iter;\n window_iters.pop_front();\n\n window_begin++;\n\n if ( window_begin == src_size )\n {\n next_value = prev_value;\n }\n else if ( window_begin < (src_size - half_length) )\n {\n next_value = src_begin[window_begin + half_length];\n }\n else\n {\n next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]);\n }\n\n if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )\n {\n if ( rank_point == prev_iter )\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point--;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n }\n else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point--;\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )\n {\n if (rank_point == prev_iter)\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point++;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point++;\n }\n }\n }\n}\n\n}\n\n\nnamespace std\n{\n template \n ostream& operator<<(ostream& out, const boost::array& that)\n {\n out << \"{ \";\n for (unsigned int i = 0; i < (N - 1); i++)\n {\n out << that[i] << \", \";\n }\n out << that[N - 1] << \" }\";\n\n return(out);\n }\n}\n\n\n#endif \/\/__RANK_FILTER__\nExplain purpose of multiset and deque#ifndef __RANK_FILTER__\n#define __RANK_FILTER__\n\n\n#include \n#include \n#include \n#include \n#include \n\n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace rank_filter\n{\n\ntemplate\ninline void lineRankOrderFilter1D(const I1& src_begin, const I1& src_end,\n I2& dest_begin, I2& dest_end,\n size_t half_length, double rank)\n{\n \/\/ Types in use.\n typedef typename std::iterator_traits::value_type T1;\n typedef typename std::iterator_traits::value_type T2;\n typedef typename std::iterator_traits::difference_type I1_diff_t;\n typedef typename std::iterator_traits::difference_type I2_diff_t;\n\n \/\/ Establish common types to work with source and destination values.\n BOOST_STATIC_ASSERT((boost::is_same::value));\n typedef T1 T;\n typedef typename boost::common_type::type I_diff_t;\n\n \/\/ Define container types that will be used.\n typedef boost::container::multiset< T,\n std::less,\n boost::container::node_allocator,\n boost::container::tree_assoc_options< boost::container::tree_type >::type> multiset;\n typedef std::deque< typename multiset::iterator > deque;\n\n \/\/ Lengths.\n const I_diff_t src_size = std::distance(src_begin, src_end);\n const I_diff_t dest_size = std::distance(dest_begin, dest_end);\n\n \/\/ Ensure the result will fit.\n assert(src_size <= dest_size);\n\n \/\/ Window length cannot exceed input data with reflection.\n assert((half_length + 1) <= src_size);\n\n \/\/ Rank must be in the range 0 to 1.\n assert((0 <= rank) && (rank <= 1));\n\n \/\/ The position of the window.\n I_diff_t window_begin = 0;\n\n \/\/ Find window offset corresponding to this rank.\n const I_diff_t rank_pos = static_cast(boost::math::round(rank * (2 * half_length)));\n\n \/\/ Track values in window both in sorted and sequential order.\n multiset sorted_window;\n deque window_iters(2 * half_length + 1);\n\n \/\/ Get the initial sorted window.\n \/\/ Include the reflection.\n for (I_diff_t j = 0; j < half_length; j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + half_length - j]);\n }\n for (I_diff_t j = half_length; j < (2 * half_length + 1); j++)\n {\n window_iters[j] = sorted_window.insert(src_begin[window_begin + j - half_length]);\n }\n\n typename multiset::iterator rank_point = sorted_window.begin();\n\n for (I_diff_t i = 0; i < rank_pos; i++)\n {\n rank_point++;\n }\n\n typename multiset::iterator prev_iter;\n T prev_value;\n T next_value;\n while ( window_begin < src_size )\n {\n dest_begin[window_begin] = *rank_point;\n\n prev_iter = window_iters.front();\n prev_value = *prev_iter;\n window_iters.pop_front();\n\n window_begin++;\n\n if ( window_begin == src_size )\n {\n next_value = prev_value;\n }\n else if ( window_begin < (src_size - half_length) )\n {\n next_value = src_begin[window_begin + half_length];\n }\n else\n {\n next_value = *(window_iters[(2 * (src_size - (window_begin + 1)))]);\n }\n\n if ( ( *rank_point < prev_value ) && ( *rank_point <= next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point > next_value ) )\n {\n if ( rank_point == prev_iter )\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point--;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n }\n }\n else if ( ( *rank_point < prev_value ) && ( *rank_point > next_value ) )\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point--;\n }\n else if ( ( *rank_point >= prev_value ) && ( *rank_point <= next_value ) )\n {\n if (rank_point == prev_iter)\n {\n window_iters.push_back(sorted_window.insert(next_value));\n rank_point++;\n\n sorted_window.erase(prev_iter);\n }\n else\n {\n sorted_window.erase(prev_iter);\n window_iters.push_back(sorted_window.insert(next_value));\n\n rank_point++;\n }\n }\n }\n}\n\n}\n\n\nnamespace std\n{\n template \n ostream& operator<<(ostream& out, const boost::array& that)\n {\n out << \"{ \";\n for (unsigned int i = 0; i < (N - 1); i++)\n {\n out << that[i] << \", \";\n }\n out << that[N - 1] << \" }\";\n\n return(out);\n }\n}\n\n\n#endif \/\/__RANK_FILTER__\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 C. Brett Witherspoon\n *\n * This file is part of the signum library\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef SIGNUM_PIPE_HPP_\n#define SIGNUM_PIPE_HPP_\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace signum\n{\n\nclass pipe\n{\npublic:\n pipe(const std::string &name)\n {\n \/\/ Try to open pipe (blocks until other end appears) or create it\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n {\n if (mkfifo(name.c_str(), 0666) == -1)\n throw std::runtime_error(\"Unable to create named pipe: \" + name);\n\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n throw std::runtime_error(\"Unable to open named pipe: \" + name);\n }\n }\n\n pipe(const pipe&) = delete;\n\n ~pipe()\n {\n close(m_fd);\n }\n\n pipe &operator=(const pipe&) = delete;\n\n bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; }\n\n bool operator!=(const pipe &rhs) const { return !operator==(rhs); }\n\n operator int() const { return m_fd; }\n\n template\n size_t write(T *data, size_t size)\n {\n ssize_t n = ::write(m_fd, data, size * sizeof(T));\n if (n == -1)\n throw std::runtime_error(\"Unable to write to named pipe\");\n return n;\n }\n\nprivate:\n int m_fd;\n};\n\n} \/\/ end namespace signum\n\n#endif \/* SIGNUM_PIPE_HPP_ *\/\npipe: add unlink method\/*\n * Copyright 2016 C. Brett Witherspoon\n *\n * This file is part of the signum library\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef SIGNUM_PIPE_HPP_\n#define SIGNUM_PIPE_HPP_\n\n#include \n\n#include \n#include \n#include \n#include \n\nnamespace signum\n{\n\nclass pipe\n{\npublic:\n pipe(const std::string &name)\n : m_name(name)\n {\n \/\/ Try to open pipe (blocks until other end appears) or create it\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n {\n if (mkfifo(name.c_str(), 0666) == -1)\n throw std::runtime_error(\"Unable to create named pipe: \" + name);\n\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n throw std::runtime_error(\"Unable to open named pipe: \" + name);\n }\n }\n\n pipe(const pipe&) = delete;\n\n ~pipe()\n {\n unlink();\n close(m_fd);\n }\n\n pipe &operator=(const pipe&) = delete;\n\n bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; }\n\n bool operator!=(const pipe &rhs) const { return !operator==(rhs); }\n\n operator int() const { return m_fd; }\n\n std::string name() const { return m_name; }\n\n void unlink() { ::unlink(m_name.c_str()); }\n\n template\n size_t write(T *data, size_t size)\n {\n ssize_t n = ::write(m_fd, data, size * sizeof(T));\n if (n == -1)\n throw std::runtime_error(\"Unable to write to named pipe\");\n return n;\n }\n\nprivate:\n const std::string m_name;\n int m_fd;\n};\n\n} \/\/ end namespace signum\n\n#endif \/* SIGNUM_PIPE_HPP_ *\/\n<|endoftext|>"} {"text":"\/*\n * Copyright 2016 C. Brett Witherspoon\n *\n * This file is part of the signum library\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef SIGNUM_PIPE_HPP_\n#define SIGNUM_PIPE_HPP_\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace signum\n{\n\nclass pipe\n{\npublic:\n pipe()\n : m_name(), m_fd(-1)\n {\n }\n\n explicit pipe(const std::string &name, mode_t mode = 0660)\n : m_name(name)\n {\n \/\/ Try to open pipe (blocks until other end appears) or create it\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n {\n if (mkfifo(name.c_str(), mode) == -1)\n throw std::runtime_error(\"Unable to create named pipe: \" + name);\n\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n throw std::runtime_error(\"Unable to open named pipe: \" + name);\n }\n }\n\n pipe(const pipe&) = delete;\n\n pipe(pipe &&other)\n : m_name(other.m_name),\n m_fd(other.m_fd)\n {\n other.m_fd = -1;\n other.m_name = \"\";\n }\n\n ~pipe()\n {\n unlink();\n close(m_fd);\n }\n\n pipe &operator=(const pipe&) = delete;\n\n pipe &operator=(pipe &&other)\n {\n m_name = other.m_name;\n other.m_name = \"\";\n\n m_fd = other.m_fd;\n other.m_fd = -1;\n\n return *this;\n }\n\n bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; }\n\n bool operator!=(const pipe &rhs) const { return !operator==(rhs); }\n\n operator int() const { return m_fd; }\n\n std::string name() const { return m_name; }\n\n void unlink() { ::unlink(m_name.c_str()); }\n\n template\n size_t write(T *data, size_t size)\n {\n ssize_t n = ::write(m_fd, data, size * sizeof(T));\n if (n == -1)\n throw std::runtime_error(\"Unable to write to named pipe\");\n return n;\n }\n\nprivate:\n std::string m_name;\n int m_fd;\n};\n\n} \/\/ end namespace signum\n\n#endif \/* SIGNUM_PIPE_HPP_ *\/\npipe: use system error exception\/*\n * Copyright 2016 C. Brett Witherspoon\n *\n * This file is part of the signum library\n *\n * Permission to use, copy, modify, and\/or distribute this software for any\n * purpose with or without fee is hereby granted, provided that the above\n * copyright notice and this permission notice appear in all copies.\n *\n * THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES\n * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF\n * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR\n * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES\n * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN\n * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF\n * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.\n *\/\n\n#ifndef SIGNUM_PIPE_HPP_\n#define SIGNUM_PIPE_HPP_\n\n#include \n#include \n\n#include \n#include \n#include \n#include \n\nnamespace signum\n{\n\nclass pipe\n{\npublic:\n pipe()\n : m_name(), m_fd(-1)\n {\n }\n\n explicit pipe(const std::string &name, mode_t mode = 0660)\n : m_name(name)\n {\n \/\/ Try to open pipe (blocks until other end appears) or create it\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n {\n if (errno == EACCES)\n throw std::system_error(EACCES, std::system_category());\n\n if (mkfifo(name.c_str(), mode) == -1)\n throw std::system_error(errno, std::system_category());\n\n m_fd = open(name.c_str(), O_WRONLY);\n if (m_fd == -1)\n throw std::system_error(errno, std::system_category());\n }\n }\n\n pipe(const pipe&) = delete;\n\n pipe(pipe &&other)\n : m_name(other.m_name),\n m_fd(other.m_fd)\n {\n other.m_fd = -1;\n other.m_name = \"\";\n }\n\n ~pipe()\n {\n unlink();\n close(m_fd);\n }\n\n pipe &operator=(const pipe&) = delete;\n\n pipe &operator=(pipe &&other)\n {\n m_name = other.m_name;\n other.m_name = \"\";\n\n m_fd = other.m_fd;\n other.m_fd = -1;\n\n return *this;\n }\n\n bool operator==(const pipe &rhs) const { return m_fd == rhs.m_fd; }\n\n bool operator!=(const pipe &rhs) const { return !operator==(rhs); }\n\n operator int() const { return m_fd; }\n\n std::string name() const { return m_name; }\n\n void unlink() { ::unlink(m_name.c_str()); }\n\n template\n size_t write(T *data, size_t size)\n {\n ssize_t n = ::write(m_fd, data, size * sizeof(T));\n if (n == -1)\n throw std::system_error(errno, std::system_category());\n return n;\n }\n\nprivate:\n std::string m_name;\n int m_fd;\n};\n\n} \/\/ end namespace signum\n\n#endif \/* SIGNUM_PIPE_HPP_ *\/\n<|endoftext|>"} {"text":"\/\/\n\/\/ linked_list.hpp\n\/\/ DS\n\/\/\n\/\/ Created by Rahul Goel on 7\/26\/17.\n\/\/ Copyright © 2017 Rahul Goel. All rights reserved.\n\/\/\n\n#ifndef linked_list_hpp\n#define linked_list_hpp\n\n#include \n#include \n\n\/\/To create a test Single Linked List with four nodes in it\nstruct list_node* linkedlist_testcreate();\n\n\/\/To print all the elements in given single lineked list - O(n) Time\nvoid linkedlist_print(struct list_node *base);\n\n\/\/To count the number of nodes in given single linked list - O(n) Time\nint linkedlist_countnodes(struct list_node *base);\n\n\/\/To insert a node on given position pos\nint linkedlist_insert(struct list_node *base,int pos,int data);\n\n\/\/To delete a node from given position pos\nvoid linkedlist_delete(struct list_node *base, int pos);\n\n\/\/To check if given linked list has cycle or not\nint linkedlist_checkIfCycle(struct list_node *base);\n\n\/\/Reverse of given linked list\nstruct list_node* linkedlist_reverse(struct list_node *base);\n\n#endif \/* linked_list_hpp *\/\nlinkedlist\/\/\n\/\/ linked_list.hpp\n\/\/ DS\n\/\/\n\/\/ Created by Rahul Goel on 7\/26\/17.\n\/\/ Copyright © 2017 Rahul Goel. All rights reserved.\n\/\/\n\n#ifndef linked_list_hpp\n#define linked_list_hpp\n\n#include \n#include \n\n\/\/1. To create a test Single Linked List with four nodes in it\nstruct list_node* linkedlist_testcreate();\n\n\/\/2. To print all the elements in given single lineked list - O(n) Time\nvoid linkedlist_print(struct list_node *base);\n\n\/\/3. To count the number of nodes in given single linked list - O(n) Time\nint linkedlist_countnodes(struct list_node *base);\n\n\/\/4. To insert a node on given position pos\nint linkedlist_insert(struct list_node *base,int pos,int data);\n\n\/\/5. To delete a node from given position pos\nvoid linkedlist_delete(struct list_node *base, int pos);\n\n\/\/6. To check if given linked list has cycle or not\nint linkedlist_checkIfCycle(struct list_node *base);\n\n\/\/7. Reverse of given linked list\nstruct list_node* linkedlist_reverse(struct list_node *base);\n\n\/\/8. Search given element in Linked List\nbool linkedlist_searchElement(struct list_node *base, int number);\n\n\/\/9. Swap two nodes in linked list, without swapping data but with address as Swapping data of nodes may be expensive in many situations when data contains many fields\nvoid linkedlist_swapTwoNodes(struct list_node *base, int val1, int val2);\n\n\/\/10. Get data in nth node from given linked list\nint linkedlist_getNthNode(struct list_node *base,int n);\n\n\/\/11. Find middle of given linked list\nint linkedlist_middleIs(struct list_node *base);\n\n\n\n\n\n#endif \/* linked_list_hpp *\/\n<|endoftext|>"} {"text":"\/* Copyright 2016 Hewlett Packard Enterprise Development LP\n\n Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software distributed under the License is distributed\n on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for\n the specific language governing permissions and limitations under the License.*\/\n\n\/\/ #include \n#include \"dynamiclibop.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/device_base.h\"\n#include \"threadpool.h\"\n\n#if GOOGLE_CUDA\n\n\/\/ this must be defined for the include file below to actually include anything\n#define EIGEN_USE_GPU\n#include \n#include \"third_party\/eigen3\/unsupported\/Eigen\/CXX11\/Tensor\"\n#endif \/\/ GOOGLE_CUDA\n\nnamespace tensorflow {\n\n\/\/ Define the operator interface: inputs, outputs and parameters\n\/\/ inputs and outputs are a list of tensors that can be either floats or doubles\n\/\/ and all input tensors do not need to be the same type\nREGISTER_OP(\"DynamicLib\")\n .Attr(\"gpu_func_name: string\")\n .Attr(\"gpu_lib_path: string\")\n .Attr(\"cpu_func_name: string\")\n .Attr(\"cpu_lib_path: string\")\n .Attr(\"serialized_grad_dag: string\")\n .Attr(\"cuda_threads_per_block: int\")\n .Attr(\"out_shapes: list(shape)\")\n .Attr(\"in_types: list({float, double}) >= 0\")\n .Attr(\"out_types: list({float, double})\")\n .Input(\"inputs: in_types\")\n .Output(\"outputs: out_types\")\n .Doc(R\"doc(call a dynamically generated library operation)doc\");\n\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n\n\/\/ static std::string getDebugString(\n\/\/ const std::vector> parameters) {\n\/\/ std::string str;\n\/\/ int status;\n\/\/ char *paramType;\n\/\/ for (uint32_t i = 0; i < parameters.size(); i++) {\n\/\/ const std::type_info &ti = typeid(*(parameters[i]));\n\/\/ paramType = abi::__cxa_demangle(ti.name(), 0, 0, &status);\n\/\/ str.append(paramType + std::string(\": \") +\n\/\/ std::to_string(parameters[i]->length()) + \", \");\n\/\/ }\n\/\/ return str;\n\/\/ }\n\n\/\/ Class which will dynamically load and launch the generated operators\n\/\/ on either CPU or GPU\ntemplate \nclass DynamicLibLaunch;\n\n\/\/ Partial specialization for CPU\ntemplate <>\nclass DynamicLibLaunch {\n public:\n typedef uint16_t\n (*FUNPTR)(std::vector> inputs,\n std::vector> outputs,\n int num_threads, int thread_idx, uint16_t *err);\n DynamicLibLaunch(OpKernelConstruction* context,\n const string& cpu_func_name, const string& cpu_lib_path,\n const string&, const string&,\n const int ) {\n LOG(INFO) << \"*** Standalone DynamicLibLaunch on CPU *****\";\n\n \/\/ load the compiled op shared library\n static_assert(sizeof(void *) == sizeof(void (*)(void)),\n \"object pointer and function pointer sizes must equal\");\n void *handle = dlopen(cpu_lib_path.c_str(), RTLD_LAZY);\n OP_REQUIRES(context, handle != nullptr,\n errors::NotFound(\"Unable to find DynamicLib library \"\n + cpu_lib_path));\n\n \/\/ load the function and cast it from void* to a function pointer\n void *f = dlsym(handle, cpu_func_name.c_str());\n func_ = reinterpret_cast(f);\n OP_REQUIRES(context, func_ != nullptr,\n errors::NotFound(\"Unable to find DynamicLib function \"\n + cpu_func_name));\n }\n\n void Run(OpKernelContext* context, const CPUDevice&,\n std::vector> inputs,\n std::vector> outputs) {\n const int num_threads = context->device()->tensorflow_cpu_worker_threads()->workers->NumThreads();\n thread::ThreadPool thread_pool(Env::Default(), \"dynamiclibop\", num_threads);\n uint16_t err = 0;\n for (int thread = 0; thread < num_threads; thread++) {\n auto fn_work = std::bind(func_, inputs, outputs, num_threads, thread, &err);\n thread_pool.Schedule(fn_work);\n }\n OP_REQUIRES(context, err == 0,\n errors::InvalidArgument(\"External function execution error code: \",\n err));\n }\n\n private:\n FUNPTR func_;\n};\n\n#if GOOGLE_CUDA\n\/\/ Partial specialization for GPU\ntemplate <>\nclass DynamicLibLaunch {\n public:\n typedef uint16_t\n (*FUNPTR)(std::vector> inputs,\n std::vector> outputs,\n CUstream stream,\n int cuda_threads_per_block);\n DynamicLibLaunch(OpKernelConstruction* context,\n const string&, const string&,\n const string& gpu_func_name, const string& gpu_lib_path,\n const int cuda_threads_per_block) {\n LOG(INFO) << \"*** Standalone DynamicLibLaunch on GPU *****\";\n\n \/\/ load the compiled op shared library\n static_assert(sizeof(void *) == sizeof(void (*)(void)),\n \"object pointer and function pointer sizes must equal\");\n void *handle = dlopen(gpu_lib_path.c_str(), RTLD_LAZY);\n OP_REQUIRES(context, handle != nullptr,\n errors::NotFound(\"Unable to find DynamicLib library \"\n + gpu_lib_path));\n\n \/\/ load the function and cast it from void* to a function pointer\n void *f = dlsym(handle, gpu_func_name.c_str());\n func_ = reinterpret_cast(f);\n OP_REQUIRES(context, func_ != nullptr,\n errors::NotFound(\"Unable to find DynamicLib function \"\n + gpu_func_name));\n\n cuda_threads_per_block_ = cuda_threads_per_block;\n }\n\n void Run(OpKernelContext* context, const GPUDevice& d,\n std::vector> inputs,\n std::vector> outputs) {\n \/\/ call the DynamicLib library functions\n uint16_t err = func_(inputs, outputs, d.stream(),\n cuda_threads_per_block_);\n OP_REQUIRES(context, err == 0,\n errors::InvalidArgument(\"External function execution error code: \",\n err));\n }\n\n private:\n FUNPTR func_;\n int cuda_threads_per_block_;\n};\n#endif \/\/ GOOGLE_CUDA\n\n\/\/ General purpose tensorflow user operator class\n\/\/ that allows us to run operators generated and compiled independently\n\/\/ by the Operator Vectorization Library.\n\/\/ Parameters are a list of input tensors, list of output shapes, list of\n\/\/ output types, the location of the DynamicLib shared libraries and the name\n\/\/ of the DynamicLib operator.\n\/\/ See tensorflow\/python\/kernel_tests\/dynamic_lib_op_test.py for example usage\ntemplate \nclass DynamicLibOp : public OpKernel {\n public:\n explicit DynamicLibOp(OpKernelConstruction* context) : OpKernel(context) {\n \/\/ store the passed in parameters\n OP_REQUIRES_OK(context, context->GetAttr(\"cpu_func_name\", &cpu_func_name_));\n OP_REQUIRES_OK(context, context->GetAttr(\"cpu_lib_path\", &cpu_lib_path_));\n OP_REQUIRES_OK(context, context->GetAttr(\"gpu_func_name\", &gpu_func_name_));\n OP_REQUIRES_OK(context, context->GetAttr(\"gpu_lib_path\", &gpu_lib_path_));\n OP_REQUIRES_OK(context, context->GetAttr(\"cuda_threads_per_block\",\n &cuda_threads_per_block_));\n OP_REQUIRES_OK(context, context->GetAttr(\"out_types\", &out_types_));\n OP_REQUIRES_OK(context, context->GetAttr(\"out_shapes\", &out_shapes_));\n\n launcher_ = std::unique_ptr>(\n new DynamicLibLaunch(context, cpu_func_name_,\n cpu_lib_path_, gpu_func_name_,\n gpu_lib_path_,\n cuda_threads_per_block_));\n }\n\n \/\/ Function that is called when the output tensors of the operator\n \/\/ are evaluated\n void Compute(OpKernelContext* context) override {\n\/\/ LOG(INFO) << \"*** computing DynamicLibOp ***\";\n\n \/\/ Build the tensor input parameter list\n OpInputList input_list;\n context->input_list(\"inputs\", &input_list);\n std::vector> inputs;\n inputs.reserve(input_list.size());\n for (int32_t i = 0; i < input_list.size(); ++i) {\n const Tensor& cur_input = input_list[i];\n switch (cur_input.dtype()) {\n case (DT_FLOAT):\n inputs.emplace_back(\n new TypedInput(cur_input.flat().data(),\n cur_input.NumElements()));\n break;\n case (DT_DOUBLE):\n inputs.emplace_back(\n new TypedInput(cur_input.flat().data(),\n cur_input.NumElements()));\n break;\n default:\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Only float and double inputs are supported.\"));\n break;\n }\n }\n\n \/\/ Build the output tensor parameter list\n const uint32_t num_outputs = context->num_outputs();\n OP_REQUIRES(context, num_outputs == out_shapes_.size(),\n errors::InvalidArgument(\n \"Output shapes inconsistent with output types\"))\n OP_REQUIRES(context, num_outputs == out_types_.size(),\n errors::InvalidArgument(\n \"Output types inconsistent num_outputs\"))\n Tensor *output_tensor[num_outputs];\n std::vector> outputs;\n outputs.reserve(num_outputs);\n for (uint32_t i = 0; i < num_outputs; ++i) {\n DataType cur_output_type = out_types_[i];\n TensorShape cur_shape = TensorShape(out_shapes_[i]);\n OP_REQUIRES_OK(context,\n context->allocate_output(i,\n cur_shape, &output_tensor[i]));\n OP_REQUIRES(context, output_tensor[i]->dtype() == cur_output_type,\n errors::InvalidArgument(\"Types inconsistent\"))\n switch (cur_output_type) {\n case (DT_FLOAT):\n outputs.emplace_back(new TypedOutput(\n output_tensor[i]->template flat().data(),\n output_tensor[i]->NumElements()));\n break;\n case (DT_DOUBLE):\n outputs.emplace_back(new TypedOutput(\n output_tensor[i]->template flat().data(),\n output_tensor[i]->NumElements()));\n break;\n default:\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Only float and double outputs are supported.\"));\n break;\n }\n }\n\n \/\/ call the DynamicLib library function\n const Device& d = context->eigen_device();\n launcher_->Run(context, d, inputs, outputs);\n }\n\n private:\n string cpu_func_name_;\n string cpu_lib_path_;\n string gpu_func_name_;\n string gpu_lib_path_;\n int cuda_threads_per_block_;\n DataTypeVector out_types_;\n std::vector out_shapes_;\n std::unique_ptr> launcher_;\n};\n\n\/\/ register the operator for each template type with tensorflow\n\/\/ Note: this registration will cause the operator constructors to get called\n\/\/ regardless of whether or not they are used in a tensorflow application\nREGISTER_KERNEL_BUILDER(Name(\"DynamicLib\")\n .Device(DEVICE_CPU),\n DynamicLibOp);\n\n#if GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(Name(\"DynamicLib\")\n .Device(DEVICE_GPU),\n DynamicLibOp);\n#endif \/\/ GOOGLE_CUDA\n} \/\/ namespace tensorflow\n\nadded scoping of threadpool in dynamiclibop.cc\/* Copyright 2016 Hewlett Packard Enterprise Development LP\n\n Licensed under the Apache License, Version 2.0 (the \"License\"); you may not use this file except in compliance with\n the License. You may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n Unless required by applicable law or agreed to in writing, software distributed under the License is distributed\n on an \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for\n the specific language governing permissions and limitations under the License.*\/\n\n\/\/ #include \n#include \"dynamiclibop.h\"\n#include \n#include \n#include \n#include \n#include \n#include \"tensorflow\/core\/platform\/logging.h\"\n#include \"tensorflow\/core\/framework\/op.h\"\n#include \"tensorflow\/core\/framework\/op_kernel.h\"\n#include \"tensorflow\/core\/framework\/device_base.h\"\n#include \"threadpool.h\"\n\n#if GOOGLE_CUDA\n\n\/\/ this must be defined for the include file below to actually include anything\n#define EIGEN_USE_GPU\n#include \n#include \"third_party\/eigen3\/unsupported\/Eigen\/CXX11\/Tensor\"\n#endif \/\/ GOOGLE_CUDA\n\nnamespace tensorflow {\n\n\/\/ Define the operator interface: inputs, outputs and parameters\n\/\/ inputs and outputs are a list of tensors that can be either floats or doubles\n\/\/ and all input tensors do not need to be the same type\nREGISTER_OP(\"DynamicLib\")\n .Attr(\"gpu_func_name: string\")\n .Attr(\"gpu_lib_path: string\")\n .Attr(\"cpu_func_name: string\")\n .Attr(\"cpu_lib_path: string\")\n .Attr(\"serialized_grad_dag: string\")\n .Attr(\"cuda_threads_per_block: int\")\n .Attr(\"out_shapes: list(shape)\")\n .Attr(\"in_types: list({float, double}) >= 0\")\n .Attr(\"out_types: list({float, double})\")\n .Input(\"inputs: in_types\")\n .Output(\"outputs: out_types\")\n .Doc(R\"doc(call a dynamically generated library operation)doc\");\n\n\ntypedef Eigen::ThreadPoolDevice CPUDevice;\ntypedef Eigen::GpuDevice GPUDevice;\n\n\/\/ static std::string getDebugString(\n\/\/ const std::vector> parameters) {\n\/\/ std::string str;\n\/\/ int status;\n\/\/ char *paramType;\n\/\/ for (uint32_t i = 0; i < parameters.size(); i++) {\n\/\/ const std::type_info &ti = typeid(*(parameters[i]));\n\/\/ paramType = abi::__cxa_demangle(ti.name(), 0, 0, &status);\n\/\/ str.append(paramType + std::string(\": \") +\n\/\/ std::to_string(parameters[i]->length()) + \", \");\n\/\/ }\n\/\/ return str;\n\/\/ }\n\n\/\/ Class which will dynamically load and launch the generated operators\n\/\/ on either CPU or GPU\ntemplate \nclass DynamicLibLaunch;\n\n\/\/ Partial specialization for CPU\ntemplate <>\nclass DynamicLibLaunch {\n public:\n typedef uint16_t\n (*FUNPTR)(std::vector> inputs,\n std::vector> outputs,\n int num_threads, int thread_idx, uint16_t *err);\n DynamicLibLaunch(OpKernelConstruction* context,\n const string& cpu_func_name, const string& cpu_lib_path,\n const string&, const string&,\n const int ) {\n LOG(INFO) << \"*** Standalone DynamicLibLaunch on CPU *****\";\n\n \/\/ load the compiled op shared library\n static_assert(sizeof(void *) == sizeof(void (*)(void)),\n \"object pointer and function pointer sizes must equal\");\n void *handle = dlopen(cpu_lib_path.c_str(), RTLD_LAZY);\n OP_REQUIRES(context, handle != nullptr,\n errors::NotFound(\"Unable to find DynamicLib library \"\n + cpu_lib_path));\n\n \/\/ load the function and cast it from void* to a function pointer\n void *f = dlsym(handle, cpu_func_name.c_str());\n func_ = reinterpret_cast(f);\n OP_REQUIRES(context, func_ != nullptr,\n errors::NotFound(\"Unable to find DynamicLib function \"\n + cpu_func_name));\n }\n\n void Run(OpKernelContext* context, const CPUDevice&,\n std::vector> inputs,\n std::vector> outputs) {\n const int num_threads = context->device()->tensorflow_cpu_worker_threads()->workers->NumThreads();\n uint16_t err = 0;\n \/\/ ThreadPool destructor is what joins all the threads and waits for completion, so we\n \/\/ scope it as a local variable and when it goes out of scope, all the work is done and result\n \/\/ can be used\n {\n thread::ThreadPool thread_pool(Env::Default(), \"dynamiclibop\", num_threads);\n for (int thread = 0; thread < num_threads; thread++) {\n auto fn_work = std::bind(func_, inputs, outputs, num_threads, thread, &err);\n thread_pool.Schedule(fn_work);\n }\n }\n OP_REQUIRES(context, err == 0,\n errors::InvalidArgument(\"External function execution error code: \",\n err));\n }\n\n private:\n FUNPTR func_;\n};\n\n#if GOOGLE_CUDA\n\/\/ Partial specialization for GPU\ntemplate <>\nclass DynamicLibLaunch {\n public:\n typedef uint16_t\n (*FUNPTR)(std::vector> inputs,\n std::vector> outputs,\n CUstream stream,\n int cuda_threads_per_block);\n DynamicLibLaunch(OpKernelConstruction* context,\n const string&, const string&,\n const string& gpu_func_name, const string& gpu_lib_path,\n const int cuda_threads_per_block) {\n LOG(INFO) << \"*** Standalone DynamicLibLaunch on GPU *****\";\n\n \/\/ load the compiled op shared library\n static_assert(sizeof(void *) == sizeof(void (*)(void)),\n \"object pointer and function pointer sizes must equal\");\n void *handle = dlopen(gpu_lib_path.c_str(), RTLD_LAZY);\n OP_REQUIRES(context, handle != nullptr,\n errors::NotFound(\"Unable to find DynamicLib library \"\n + gpu_lib_path));\n\n \/\/ load the function and cast it from void* to a function pointer\n void *f = dlsym(handle, gpu_func_name.c_str());\n func_ = reinterpret_cast(f);\n OP_REQUIRES(context, func_ != nullptr,\n errors::NotFound(\"Unable to find DynamicLib function \"\n + gpu_func_name));\n\n cuda_threads_per_block_ = cuda_threads_per_block;\n }\n\n void Run(OpKernelContext* context, const GPUDevice& d,\n std::vector> inputs,\n std::vector> outputs) {\n \/\/ call the DynamicLib library functions\n uint16_t err = func_(inputs, outputs, d.stream(),\n cuda_threads_per_block_);\n OP_REQUIRES(context, err == 0,\n errors::InvalidArgument(\"External function execution error code: \",\n err));\n }\n\n private:\n FUNPTR func_;\n int cuda_threads_per_block_;\n};\n#endif \/\/ GOOGLE_CUDA\n\n\/\/ General purpose tensorflow user operator class\n\/\/ that allows us to run operators generated and compiled independently\n\/\/ by the Operator Vectorization Library.\n\/\/ Parameters are a list of input tensors, list of output shapes, list of\n\/\/ output types, the location of the DynamicLib shared libraries and the name\n\/\/ of the DynamicLib operator.\n\/\/ See tensorflow\/python\/kernel_tests\/dynamic_lib_op_test.py for example usage\ntemplate \nclass DynamicLibOp : public OpKernel {\n public:\n explicit DynamicLibOp(OpKernelConstruction* context) : OpKernel(context) {\n \/\/ store the passed in parameters\n OP_REQUIRES_OK(context, context->GetAttr(\"cpu_func_name\", &cpu_func_name_));\n OP_REQUIRES_OK(context, context->GetAttr(\"cpu_lib_path\", &cpu_lib_path_));\n OP_REQUIRES_OK(context, context->GetAttr(\"gpu_func_name\", &gpu_func_name_));\n OP_REQUIRES_OK(context, context->GetAttr(\"gpu_lib_path\", &gpu_lib_path_));\n OP_REQUIRES_OK(context, context->GetAttr(\"cuda_threads_per_block\",\n &cuda_threads_per_block_));\n OP_REQUIRES_OK(context, context->GetAttr(\"out_types\", &out_types_));\n OP_REQUIRES_OK(context, context->GetAttr(\"out_shapes\", &out_shapes_));\n\n launcher_ = std::unique_ptr>(\n new DynamicLibLaunch(context, cpu_func_name_,\n cpu_lib_path_, gpu_func_name_,\n gpu_lib_path_,\n cuda_threads_per_block_));\n }\n\n \/\/ Function that is called when the output tensors of the operator\n \/\/ are evaluated\n void Compute(OpKernelContext* context) override {\n\/\/ LOG(INFO) << \"*** computing DynamicLibOp ***\";\n\n \/\/ Build the tensor input parameter list\n OpInputList input_list;\n context->input_list(\"inputs\", &input_list);\n std::vector> inputs;\n inputs.reserve(input_list.size());\n for (int32_t i = 0; i < input_list.size(); ++i) {\n const Tensor& cur_input = input_list[i];\n switch (cur_input.dtype()) {\n case (DT_FLOAT):\n inputs.emplace_back(\n new TypedInput(cur_input.flat().data(),\n cur_input.NumElements()));\n break;\n case (DT_DOUBLE):\n inputs.emplace_back(\n new TypedInput(cur_input.flat().data(),\n cur_input.NumElements()));\n break;\n default:\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Only float and double inputs are supported.\"));\n break;\n }\n }\n\n \/\/ Build the output tensor parameter list\n const uint32_t num_outputs = context->num_outputs();\n OP_REQUIRES(context, num_outputs == out_shapes_.size(),\n errors::InvalidArgument(\n \"Output shapes inconsistent with output types\"))\n OP_REQUIRES(context, num_outputs == out_types_.size(),\n errors::InvalidArgument(\n \"Output types inconsistent num_outputs\"))\n Tensor *output_tensor[num_outputs];\n std::vector> outputs;\n outputs.reserve(num_outputs);\n for (uint32_t i = 0; i < num_outputs; ++i) {\n DataType cur_output_type = out_types_[i];\n TensorShape cur_shape = TensorShape(out_shapes_[i]);\n OP_REQUIRES_OK(context,\n context->allocate_output(i,\n cur_shape, &output_tensor[i]));\n OP_REQUIRES(context, output_tensor[i]->dtype() == cur_output_type,\n errors::InvalidArgument(\"Types inconsistent\"))\n switch (cur_output_type) {\n case (DT_FLOAT):\n outputs.emplace_back(new TypedOutput(\n output_tensor[i]->template flat().data(),\n output_tensor[i]->NumElements()));\n break;\n case (DT_DOUBLE):\n outputs.emplace_back(new TypedOutput(\n output_tensor[i]->template flat().data(),\n output_tensor[i]->NumElements()));\n break;\n default:\n OP_REQUIRES(context, false,\n errors::InvalidArgument(\n \"Only float and double outputs are supported.\"));\n break;\n }\n }\n\n \/\/ call the DynamicLib library function\n const Device& d = context->eigen_device();\n launcher_->Run(context, d, inputs, outputs);\n }\n\n private:\n string cpu_func_name_;\n string cpu_lib_path_;\n string gpu_func_name_;\n string gpu_lib_path_;\n int cuda_threads_per_block_;\n DataTypeVector out_types_;\n std::vector out_shapes_;\n std::unique_ptr> launcher_;\n};\n\n\/\/ register the operator for each template type with tensorflow\n\/\/ Note: this registration will cause the operator constructors to get called\n\/\/ regardless of whether or not they are used in a tensorflow application\nREGISTER_KERNEL_BUILDER(Name(\"DynamicLib\")\n .Device(DEVICE_CPU),\n DynamicLibOp);\n\n#if GOOGLE_CUDA\nREGISTER_KERNEL_BUILDER(Name(\"DynamicLib\")\n .Device(DEVICE_GPU),\n DynamicLibOp);\n#endif \/\/ GOOGLE_CUDA\n} \/\/ namespace tensorflow\n\n<|endoftext|>"} {"text":"\/*******************************************************************************\nProgram: Wake Forest University - Virginia Tech CTC Software\nId: $Id$\nLanguage: C++\n*******************************************************************************\/\n\n\/\/ command line app to subtract tagged stool from images\n \n#include \n#include \nusing namespace std;\n\n\/\/ ITK includes\n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ CTC includes\n#include \"ctcConfigure.h\"\n#include \"ctcCTCImage.h\"\n#include \"ctcCTCImageReader.h\"\n#include \"ctcSegmentColonWithContrastFilter.h\"\n#include \"vul_arg.h\"\n\nint main(int argc, char ** argv)\n{\n \/\/ parse args\n vul_arg infile(0, \"Input DICOM directory\");\n vul_arg outfile(0, \"Output DICOM directory\");\n vul_arg replaceval(\"-r\", \n\t\t\t \"Replacement HU value for tagged regions (default -900)\", \n\t\t\t -900);\n vul_arg_parse(argc, argv);\n\n \/\/ test if outfile exists, if so bail out\n if(itksys::SystemTools::FileExists(outfile()))\n {\n if(itksys::SystemTools::FileIsDirectory(outfile()))\n\t{\n\t cerr << \"Error: directory \" << outfile() << \" exists. Halting.\" << endl;\n\t}\n else\n\t{\n\t cerr << \"Error: file \" << outfile() << \" exists. Halting.\" << endl;\n\t}\n return EXIT_FAILURE;\n }\n\n \/\/ read in the DICOM series\n ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New();\n reader->SetDirectory(string(infile()));\n try\n {\n reader->Update();\n }\n catch (itk::ExceptionObject &ex)\n {\n std::cout << ex << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ segment air + constrast\n clog << \"Starting Segment\";\n ctc::SegmentColonWithContrastFilter::Pointer filter = ctc::SegmentColonWithContrastFilter::New();\n filter->SetInput( reader->GetOutput() );\n filter->Update();\n clog << \" Done Segmenting.\" << endl;\n\n \/\/ loop through the voxels, testing for threshold and lumen test\n \/\/ replace image values with air\n clog << \"Starting Mask\";\n int replace = replaceval();\n typedef itk::ImageRegionIterator InputIteratorType;\n typedef itk::ImageRegionConstIterator BinaryIteratorType;\n InputIteratorType it1(reader->GetOutput(), reader->GetOutput()->GetRequestedRegion());\n BinaryIteratorType it2(filter->GetOutput(), filter->GetOutput()->GetRequestedRegion());\n for( it1.GoToBegin(), it2.GoToBegin(); \n !it1.IsAtEnd() || !it2.IsAtEnd(); \n ++it1, ++it2)\n {\n if( (it2.Get() == 255) && (it1.Get() > -800) )\n\t{\n\t it1.Set(replace);\n\t}\n }\n clog << \" Done Masking\" << endl;\n\n\n \/\/ write out modified image\n typedef itk::Image< short, 2 > Image2DType; \n typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType; \n WriterType::Pointer writer = WriterType::New(); \n writer->SetInput( reader->GetOutput() );\n writer->SetMetaDataDictionaryArray( reader->GetMetaDataDictionaryArray() ); \n\n itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New();\n writer->SetImageIO( dicomIO );\n\n typedef itk::NumericSeriesFileNames NameGeneratorType; \n NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();\n if( !itksys::SystemTools::MakeDirectory(outfile()) )\n {\n cerr << \"Error: could not create output directory\" << endl;\n return EXIT_FAILURE;\n }\n\n std::string format = outfile(); \n format += \"\/%03d.dcm\"; \n nameGenerator->SetSeriesFormat( format.c_str() );\n\n ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput(); \n ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion(); \n ctc::CTCImageType::IndexType start = region.GetIndex(); \n ctc::CTCImageType::SizeType size = region.GetSize(); \n\n const unsigned int firstSlice = start[2]; \n const unsigned int lastSlice = start[2] + size[2] - 1; \n nameGenerator->SetStartIndex( firstSlice ); \n nameGenerator->SetEndIndex( lastSlice ); \n nameGenerator->SetIncrementIndex( 1 ); \n writer->SetFileNames( nameGenerator->GetFileNames() );\n\n try \n { \n writer->Update(); \n } \n catch( itk::ExceptionObject & err ) \n { \n cerr << \"ExceptionObject caught !\" << endl; \n cerr << err << endl; \n return EXIT_FAILURE; \n } \n \n return EXIT_SUCCESS;\n}\nCLW: added modifier for DICOM tags to facilitate placement in PACS\/*******************************************************************************\nProgram: Wake Forest University - Virginia Tech CTC Software\nId: $Id$\nLanguage: C++\n*******************************************************************************\/\n\n\/\/ command line app to subtract tagged stool from images\n \n#include \n#include \nusing namespace std;\n\n\/\/ ITK includes\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\/\/ CTC includes\n#include \"ctcConfigure.h\"\n#include \"ctcCTCImage.h\"\n#include \"ctcCTCImageReader.h\"\n#include \"ctcSegmentColonWithContrastFilter.h\"\n#include \"vul_arg.h\"\n\nint main(int argc, char ** argv)\n{\n \/\/ parse args\n vul_arg infile(0, \"Input DICOM directory\");\n vul_arg outfile(0, \"Output DICOM directory\");\n vul_arg replaceval(\"-r\", \n\t\t\t \"Replacement HU value for tagged regions (default -900)\", \n\t\t\t -900);\n vul_arg_parse(argc, argv);\n\n \/\/ test if outfile exists, if so bail out\n if(itksys::SystemTools::FileExists(outfile()))\n {\n if(itksys::SystemTools::FileIsDirectory(outfile()))\n\t{\n\t cerr << \"Error: directory \" << outfile() << \" exists. Halting.\" << endl;\n\t}\n else\n\t{\n\t cerr << \"Error: file \" << outfile() << \" exists. Halting.\" << endl;\n\t}\n return EXIT_FAILURE;\n }\n\n \/\/ read in the DICOM series\n ctc::CTCImageReader::Pointer reader = ctc::CTCImageReader::New();\n reader->SetDirectory(string(infile()));\n try\n {\n reader->Update();\n }\n catch (itk::ExceptionObject &ex)\n {\n std::cout << ex << std::endl;\n return EXIT_FAILURE;\n }\n\n \/\/ segment air + constrast\n clog << \"Starting Segment\";\n ctc::SegmentColonWithContrastFilter::Pointer filter = \n ctc::SegmentColonWithContrastFilter::New();\n filter->SetInput( reader->GetOutput() );\n filter->Update();\n clog << \" Done Segmenting.\" << endl;\n\n \/\/ loop through the voxels, testing for threshold and lumen test\n \/\/ replace image values with air\n clog << \"Starting Mask\";\n int replace = replaceval();\n typedef itk::ImageRegionIterator InputIteratorType;\n typedef itk::ImageRegionConstIterator BinaryIteratorType;\n InputIteratorType it1(reader->GetOutput(), \n\t\t\treader->GetOutput()->GetRequestedRegion());\n BinaryIteratorType it2(filter->GetOutput(), \n\t\t\t filter->GetOutput()->GetRequestedRegion());\n\n for( it1.GoToBegin(), it2.GoToBegin(); \n !it1.IsAtEnd() || !it2.IsAtEnd(); \n ++it1, ++it2)\n {\n if( (it2.Get() == 255) && (it1.Get() > -800) )\n\t{\n\t it1.Set(replace);\n\t}\n }\n clog << \" Done Masking\" << endl;\n\n \/\/ write out modified image\n typedef itk::Image< short, 2 > Image2DType; \n typedef itk::ImageSeriesWriter< ctc::CTCImageType, Image2DType > WriterType; \n WriterType::Pointer writer = WriterType::New(); \n writer->SetInput( reader->GetOutput() );\n\n \/\/ modify series number\n ctc::CTCImageReader::DictionaryArrayRawPointer dictarray = \n reader->GetMetaDataDictionaryArray();\n\n std::string SeriesNumberTag = \"0020|0011\";\n std::string SeriesNumberValue;\n for(int slice = 0; \n slice < dictarray->size(); \n slice++)\n {\n ctc::CTCImageReader::DictionaryRawPointer dict = \n\t(*(reader->GetMetaDataDictionaryArray()))[slice];\n\n itk::ExposeMetaData(*dict, \n\t\t\t\t\tSeriesNumberTag, \n\t\t\t\t\tSeriesNumberValue);\n SeriesNumberValue = \"90\";\n itk::EncapsulateMetaData(*dict, \n\t\t\t\t\t SeriesNumberTag, \n\t\t\t\t\t SeriesNumberValue);\n }\n\n writer->SetMetaDataDictionaryArray( dictarray ); \n\n itk::GDCMImageIO::Pointer dicomIO = itk::GDCMImageIO::New();\n\n writer->SetImageIO( dicomIO );\n\n typedef itk::NumericSeriesFileNames NameGeneratorType; \n NameGeneratorType::Pointer nameGenerator = NameGeneratorType::New();\n if( !itksys::SystemTools::MakeDirectory(outfile()) )\n {\n cerr << \"Error: could not create output directory\" << endl;\n return EXIT_FAILURE;\n }\n\n std::string format = outfile(); \n format += \"\/%03d.dcm\"; \n nameGenerator->SetSeriesFormat( format.c_str() );\n\n ctc::CTCImageType::ConstPointer inputImage = reader->GetOutput(); \n ctc::CTCImageType::RegionType region = inputImage->GetLargestPossibleRegion(); \n ctc::CTCImageType::IndexType start = region.GetIndex(); \n ctc::CTCImageType::SizeType size = region.GetSize(); \n\n const unsigned int firstSlice = start[2]; \n const unsigned int lastSlice = start[2] + size[2] - 1; \n nameGenerator->SetStartIndex( firstSlice ); \n nameGenerator->SetEndIndex( lastSlice ); \n nameGenerator->SetIncrementIndex( 1 ); \n writer->SetFileNames( nameGenerator->GetFileNames() );\n\n try \n { \n writer->Update(); \n } \n catch( itk::ExceptionObject & err ) \n { \n cerr << \"ExceptionObject caught !\" << endl; \n cerr << err << endl; \n return EXIT_FAILURE; \n } \n \n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"\/* \n * File: Sfuck.cpp\n * Author: Michael Hrcek \n *\n * Created on September 14, 2015, 6:25 PM\n *\/\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct store {\n int intBank[128][128];\n int index, vindex;\n bool printAsChar;\n bool notFlaged;\n\n store() {\n index = 0;\n vindex = 0;\n printAsChar = true;\n }\n\n void getCommand(char c);\n};\n\nvoid store::getCommand(char c) {\n switch (c) {\n case '+':\n intBank[vindex][index]++;\n break;\n case '-':\n intBank[vindex][index]--;\n break;\n case '>':\n if (index == 127) {\n index = 0;\n } else {\n index++;\n }\n break;\n case '<':\n if (index == 0) {\n index = 127;\n } else {\n index--;\n }\n break;\n case '^':\n if (vindex == 127) {\n vindex = 0;\n } else {\n vindex++;\n }\n break;\n case '\\\\':\n if (vindex == 0) {\n vindex = 127;\n } else {\n vindex--;\n }\n break;\n case '#':\n index = vindex = 0;\n break;\n case ',':\n intBank[vindex][index] = (int) cin.get();\n break;\n case '.':\n if (printAsChar) {\n cout << (char) intBank[vindex][index];\n } else {\n cout << intBank[vindex][index];\n }\n break;\n case '=':\n if (intBank[vindex][index] == (int) 'x') {\n intBank[vindex][index] = 1;\n } else {\n intBank[vindex][index] = 0;\n }\n break;\n case '?':\n intBank[vindex][index] = rand();\n break;\n case '@':\n printAsChar = !printAsChar;\n break;\n case '~':\n notFlaged = false;\n break;\n case '|':\n if (vindex > 0) {\n intBank[vindex][index] = intBank[vindex - 1][index];\n } else {\n intBank[vindex][index] = intBank[127][index];\n }\n break;\n case '}':\n if (index > 0) {\n intBank[vindex][index] = intBank[vindex][index - 1];\n } else {\n intBank[vindex][index] = intBank[vindex][127];\n }\n break;\n\n }\n}\n\n\/*\n * \n *\/\nint main(int argc, char** argv) {\n\n srand(time(NULL));\n\n store s;\n string choice;\n\n while (true) {\n cout << \"SGFY interpreter v0.1.1\\n\\n------------------------------------------\\n\"\n << \"Enter filename (cin if live interpret): \";\n cin >> choice;\n cin.clear();\n\n s.notFlaged = true;\n\n if (choice == \"cin\") {\n while (s.notFlaged) {\n s.getCommand(cin.get());\n }\n } else {\n ifstream stream(choice.c_str());\n while (!stream.eof()) {\n s.getCommand(stream.get());\n }\n }\n\n cout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n }\n\n \/\/ if (argc <= 1) {\n \/\/ while (true) {\n \/\/ s.getCommand(cin.get());\n \/\/ }\n \/\/ } else{\n \/\/ \/\/Get args\n \/\/ }\n\n\n return 0;\n}\n\nUpdated | logic\/* \n * File: Sfuck.cpp\n * Author: Michael Hrcek \n *\n * Created on September 14, 2015, 6:25 PM\n *\/\n\n#include \n#include \n#include \n#include \n\nusing namespace std;\n\nstruct store {\n int intBank[128][128];\n int index, vindex;\n bool printAsChar;\n bool notFlaged;\n\n store() {\n index = 0;\n vindex = 0;\n printAsChar = true;\n }\n\n void getCommand(char c);\n};\n\nvoid store::getCommand(char c) {\n switch (c) {\n case '+':\n intBank[vindex][index]++;\n break;\n case '-':\n intBank[vindex][index]--;\n break;\n case '>':\n if (index == 127) {\n index = 0;\n } else {\n index++;\n }\n break;\n case '<':\n if (index == 0) {\n index = 127;\n } else {\n index--;\n }\n break;\n case '^':\n if (vindex == 127) {\n vindex = 0;\n } else {\n vindex++;\n }\n break;\n case '\\\\':\n if (vindex == 0) {\n vindex = 127;\n } else {\n vindex--;\n }\n break;\n case '#':\n index = vindex = 0;\n break;\n case ',':\n intBank[vindex][index] = (int) cin.get();\n break;\n case '.':\n if (printAsChar) {\n cout << (char) intBank[vindex][index];\n } else {\n cout << intBank[vindex][index];\n }\n break;\n case '=':\n if (intBank[vindex][index] == (int) 'x') {\n intBank[vindex][index] = 1;\n } else {\n intBank[vindex][index] = 0;\n }\n break;\n case '?':\n intBank[vindex][index] = rand();\n break;\n case '@':\n printAsChar = !printAsChar;\n break;\n case '~':\n notFlaged = false;\n break;\n case '|':\n if (vindex < 127) {\n intBank[vindex][index] = intBank[vindex + 1][index];\n } else {\n intBank[vindex][index] = intBank[0][index];\n }\n break;\n case '}':\n if (index > 0) {\n intBank[vindex][index] = intBank[vindex][index - 1];\n } else {\n intBank[vindex][index] = intBank[vindex][127];\n }\n break;\n\n }\n}\n\n\/*\n * \n *\/\nint main(int argc, char** argv) {\n\n srand(time(NULL));\n\n store s;\n string choice;\n\n while (true) {\n cout << \"SGFY interpreter v0.1.1\\n\\n------------------------------------------\\n\"\n << \"Enter filename (cin if live interpret): \";\n cin >> choice;\n cin.clear();\n\n s.notFlaged = true;\n\n if (choice == \"cin\") {\n while (s.notFlaged) {\n s.getCommand(cin.get());\n }\n } else {\n ifstream stream(choice.c_str());\n while (!stream.eof()) {\n s.getCommand(stream.get());\n }\n }\n\n cout << \"\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\\n\";\n }\n\n \/\/ if (argc <= 1) {\n \/\/ while (true) {\n \/\/ s.getCommand(cin.get());\n \/\/ }\n \/\/ } else{\n \/\/ \/\/Get args\n \/\/ }\n\n\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ vimshell.cpp : Defines the entry point for the application.\r\n\/\/\r\n\r\n#include \"vimshell.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nbool cvtLPW2stdstring(std::string& s, const LPWSTR pw,\r\n UINT codepage = CP_ACP)\r\n{\r\n bool res = false;\r\n char* p = 0;\r\n int bsz;\r\n\r\n bsz = WideCharToMultiByte(codepage,\r\n 0,\r\n pw,-1,\r\n 0,0,\r\n 0,0);\r\n if (bsz > 0) {\r\n p = new char[bsz];\r\n int rc = WideCharToMultiByte(codepage,\r\n 0,\r\n pw,-1,\r\n p,bsz,\r\n 0,0);\r\n if (rc != 0) {\r\n p[bsz-1] = 0;\r\n s = p;\r\n res = true;\r\n }\r\n }\r\n delete [] p;\r\n return res;\r\n}\r\n\r\nstd::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace ) \r\n{ \r\n\tsize_t uPos = 0; \r\n\tsize_t uFindLen = tFind.length(); \r\n\tsize_t uReplaceLen = tReplace.length();\r\n\r\n\tif( uFindLen == 0 )\r\n\t{\r\n\t\treturn tInput;\r\n\t}\r\n\r\n\twhile((uPos = tInput.find( tFind, uPos )) != std::string::npos)\r\n\t{\r\n\t\ttInput.replace( uPos, uFindLen, tReplace );\r\n\t\tuPos += uReplaceLen;\r\n\t}\r\n\r\n\treturn tInput;\r\n}\r\n\r\nint APIENTRY WinMain(HINSTANCE hInstance,\r\n HINSTANCE hPrevInstance,\r\n LPTSTR lpCmdLine,\r\n int nCmdShow)\r\n{\r\n\tint count;\r\n\t\/\/MessageBox(0, lpCmdLine, 0, 0);\r\n\tLPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count);\r\n\tstd::string currentDir;\r\n\r\n\tcvtLPW2stdstring(currentDir, strings[0]);\r\n\r\n\t\/\/ Cut off the filename\r\n\twhile((currentDir.length() > 0) &&\r\n\t\t(currentDir[currentDir.length()-1] != '\/') && \r\n\t\t(currentDir[currentDir.length()-1] != '\\\\'))\r\n\t{\r\n\t\tcurrentDir = currentDir.substr(0, currentDir.length()-1);\r\n\t}\r\n\tif(currentDir.length() > 0 && currentDir[0] == '\"')\r\n\t\tcurrentDir = currentDir.substr(1);\r\n\t\r\n\tstd::string filename = currentDir + std::string(\"shell.txt\");\r\n\t\r\n\tstd::ifstream fileIn(filename.c_str());\r\n\tif(!fileIn)\r\n\t{\r\n\t\tMessageBox(0, \"Please create a file called shell.txt in the same folder you put this new vimrun.exe\", 0,0);\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tstd::string argumentshellcommand;\r\n\tstd::string silentshellcommand;\r\n\tstd::string interactiveshellcommand;\r\n\r\n\tstd::getline(fileIn, argumentshellcommand);\r\n\tstd::getline(fileIn, silentshellcommand);\r\n\tstd::getline(fileIn, interactiveshellcommand);\r\n\r\n\tstd::string args = lpCmdLine;\r\n\r\n\t\r\n\twhile(args.length() > 0 && args[0] == ' ')\r\n\t\targs = args.substr(1);\r\n\r\n\tbool execSilently = false;\r\n\r\n\tif(args.length() > 3 && \r\n\t\t\targs[0] == '-' &&\r\n\t\t\targs[1] == 's' &&\r\n\t\t\targs[2] == ' ')\r\n\t{\r\n\t\targs = args.substr(3);\r\n\t\texecSilently = true;\r\n\t}\r\n\r\n\tsize_t spacepos = args.find_first_of(\" \");\r\n\targs = args.substr(spacepos+1);\r\n\tspacepos = args.find_first_of(\" \");\r\n\targs = args.substr(spacepos+1);\r\n\r\n\tstd::string cmd;\r\n\r\n\tif(spacepos == std::string::npos)\r\n\t\targs = \"\";\r\n\r\n\tstd::string argcmd = execSilently ? silentshellcommand : argumentshellcommand;\r\n\r\n\tif(args.length() == 0)\r\n\t{\r\n\t\tcmd = interactiveshellcommand;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tstd::string quotedPH = \"#QQQQ#\";\r\n\t\tif(argcmd.find(quotedPH) != std::string::npos)\r\n\t\t{\r\n\t\t\tbool indoubles = false;\r\n\t\t\tbool insingles = false;\r\n\t\t\tfor(size_t i = 0; i < args.length(); i++)\r\n\t\t\t{\r\n\t\t\t\tif(args[i] == '\"')\r\n\t\t\t\t\tindoubles = !indoubles;\r\n\t\t\t\tif(args[i] == '\\'')\r\n\t\t\t\t\tinsingles = !insingles;\r\n\r\n\t\t\t\tif(!indoubles && !insingles && args[i] == '\\\\')\r\n\t\t\t\t{\r\n\t\t\t\t\targs.insert(i, \"\\\\\");\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t\tif(!indoubles && args[i] == '\\'')\r\n\t\t\t\t{\r\n\t\t\t\t\targs.insert(i, \"\\\\\");\r\n\t\t\t\t\ti++;\r\n\t\t\t\t\tcontinue;\r\n\t\t\t\t}\r\n\r\n\t\t\t}\r\n\t\t\t\/\/args = FindAndReplace(args,\"'\", \"\\\\'\");\r\n\r\n\t\t\/\/\targs = FindAndReplace(args, \"\\\\\", \"\\\\\\\\\");\r\n\t\t\tcmd = FindAndReplace(argcmd, quotedPH, args);\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tcmd = argcmd + \" \" + args;\r\n\t\t}\r\n\t}\r\n\t\/*MessageBox(0,cmd.c_str(), 0,0);\r\n\tstd::ofstream f(\"C:\/output.txt\");\r\n\tf << cmd.c_str();\r\n\tf.close();*\/\r\n\r\n\r\n\r\n\tSTARTUPINFO si = { sizeof(STARTUPINFO) };\r\n\tsi.dwFlags = STARTF_USESHOWWINDOW;\r\n\tif(execSilently)\r\n\t\tsi.wShowWindow = SW_HIDE;\r\n\telse\r\n\t\tsi.wShowWindow = SW_SHOW;\r\n\tPROCESS_INFORMATION pi;\r\n\tchar arr[1024];\r\n\tstrcpy_s(arr, 1024, cmd.c_str());\r\n\tCreateProcess(NULL, arr, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);\r\n\tWaitForSingleObject(pi.hProcess, INFINITE);\r\n\tDWORD exit_code;\r\n\tGetExitCodeProcess(pi.hProcess, &exit_code);\r\n\t\r\n\treturn exit_code;\r\n}\r\nVimshell now works with files instead of inline strings. This assures everything works 100% of the time. Instead of the old #QQQQ# you now enter #F# in your shell.txt to reference the file your shell should read from. If you wish to append (prepending isn't possible at the moment (and would be impossible with this syntax)) something at the end of this file, do so like this: #Fxxx# to append xxx. For example, something useful to append would be #F;read;# on the first line of your shell.txt, so your shell will pauze after running\/\/ vimshell.cpp : Defines the entry point for the application.\r\n\/\/\r\n\r\n#include \"vimshell.h\"\r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n\r\nbool cvtLPW2stdstring(std::string& s, const LPWSTR pw,\r\n UINT codepage = CP_ACP)\r\n{\r\n bool res = false;\r\n char* p = 0;\r\n int bsz;\r\n\r\n bsz = WideCharToMultiByte(codepage,\r\n 0,\r\n pw,-1,\r\n 0,0,\r\n 0,0);\r\n if (bsz > 0) {\r\n p = new char[bsz];\r\n int rc = WideCharToMultiByte(codepage,\r\n 0,\r\n pw,-1,\r\n p,bsz,\r\n 0,0);\r\n if (rc != 0) {\r\n p[bsz-1] = 0;\r\n s = p;\r\n res = true;\r\n }\r\n }\r\n delete [] p;\r\n return res;\r\n}\r\n\r\nstd::string FindAndReplace(std::string tInput, std::string tFind, std::string tReplace ) \r\n{ \r\n\tsize_t uPos = 0; \r\n\tsize_t uFindLen = tFind.length(); \r\n\tsize_t uReplaceLen = tReplace.length();\r\n\r\n\tif( uFindLen == 0 )\r\n\t{\r\n\t\treturn tInput;\r\n\t}\r\n\r\n\twhile((uPos = tInput.find( tFind, uPos )) != std::string::npos)\r\n\t{\r\n\t\ttInput.replace( uPos, uFindLen, tReplace );\r\n\t\tuPos += uReplaceLen;\r\n\t}\r\n\r\n\treturn tInput;\r\n}\r\n\r\nint APIENTRY WinMain(HINSTANCE hInstance,\r\n HINSTANCE hPrevInstance,\r\n LPTSTR lpCmdLine,\r\n int nCmdShow)\r\n{\r\n\tint count;\r\n\t\/\/MessageBox(0, lpCmdLine, 0, 0);\r\n\tLPWSTR* strings = CommandLineToArgvW(GetCommandLineW(), &count);\r\n\tstd::string currentDir;\r\n\r\n\tcvtLPW2stdstring(currentDir, strings[0]);\r\n\r\n\t\/\/ Cut off the filename\r\n\twhile((currentDir.length() > 0) &&\r\n\t\t(currentDir[currentDir.length()-1] != '\/') && \r\n\t\t(currentDir[currentDir.length()-1] != '\\\\'))\r\n\t{\r\n\t\tcurrentDir = currentDir.substr(0, currentDir.length()-1);\r\n\t}\r\n\tif(currentDir.length() > 0 && currentDir[0] == '\"')\r\n\t\tcurrentDir = currentDir.substr(1);\r\n\t\r\n\tstd::string filename = currentDir + std::string(\"shell.txt\");\r\n\t\r\n\tstd::ifstream fileIn(filename.c_str());\r\n\tif(!fileIn)\r\n\t{\r\n\t\tMessageBox(0, \"Please create a file called shell.txt in the same folder you put this new vimrun.exe\", 0,0);\r\n\t\treturn 1;\r\n\t}\r\n\r\n\tstd::string argumentshellcommand;\r\n\tstd::string silentshellcommand;\r\n\tstd::string interactiveshellcommand;\r\n\r\n\tstd::getline(fileIn, argumentshellcommand);\r\n\tstd::getline(fileIn, silentshellcommand);\r\n\tstd::getline(fileIn, interactiveshellcommand);\r\n\r\n\tstd::string args = lpCmdLine;\r\n\r\n\t\r\n\twhile(args.length() > 0 && args[0] == ' ')\r\n\t\targs = args.substr(1);\r\n\r\n\tbool execSilently = false;\r\n\r\n\tif(args.length() > 3 && \r\n\t\t\targs[0] == '-' &&\r\n\t\t\targs[1] == 's' &&\r\n\t\t\targs[2] == ' ')\r\n\t{\r\n\t\targs = args.substr(3);\r\n\t\texecSilently = true;\r\n\t}\r\n\r\n\tsize_t spacepos = args.find_first_of(\" \");\r\n\targs = args.substr(spacepos+1);\r\n\tspacepos = args.find_first_of(\" \");\r\n\targs = args.substr(spacepos+1);\r\n\r\n\tstd::string cmd;\r\n\r\n\tif(spacepos == std::string::npos)\r\n\t\targs = \"\";\r\n\r\n\tstd::string argcmd = execSilently ? silentshellcommand : argumentshellcommand;\r\n\r\n\tif(args.length() == 0)\r\n\t{\r\n\t\tcmd = interactiveshellcommand;\r\n\t}\r\n\telse\r\n\t{\r\n\t\tint start = argcmd.find('#F');\r\n\t\tint end = argcmd.find('#', start+1);\r\n\r\n\t\t\/\/MessageBox(0, argcmd.c_str(), 0,0);\r\n\t\tif(start == std::string::npos || end == std::string::npos)\r\n\t\t\tMessageBox(0, \"Check your shell.txt\", 0,0);\r\n\r\n\t\tstd::string appendage = argcmd.substr(start+1, end-start-1);\r\n\r\n\t\tstd::string filename = \"C:\/vimshelltmp.txt\";\r\n\r\n\t\tcmd = argcmd.replace(start-1, end-start+2, filename);\r\n\t\tstd::ofstream f(filename.c_str());\r\n\t\tf << args.c_str() << appendage;\r\n\t\tf.close();\r\n\t}\r\n\r\n\t\/\/MessageBox(0,cmd.c_str(), 0,0);\r\n\tstd::ofstream f(\"C:\/output.txt\");\r\n\tf << cmd.c_str();\r\n\tf.close();\r\n\r\n\r\n\r\n\tSTARTUPINFO si = { sizeof(STARTUPINFO) };\r\n\tsi.dwFlags = STARTF_USESHOWWINDOW;\r\n\tif(execSilently)\r\n\t\tsi.wShowWindow = SW_HIDE;\r\n\telse\r\n\t\tsi.wShowWindow = SW_SHOW;\r\n\tPROCESS_INFORMATION pi;\r\n\tchar arr[1024];\r\n\tstrcpy_s(arr, 1024, cmd.c_str());\r\n\tCreateProcess(NULL, arr, NULL, NULL, FALSE, 0, NULL, NULL, &si, &pi);\r\n\tWaitForSingleObject(pi.hProcess, INFINITE);\r\n\tDWORD exit_code;\r\n\tGetExitCodeProcess(pi.hProcess, &exit_code);\r\n\t\r\n\treturn exit_code;\r\n}\r\n<|endoftext|>"} {"text":"\/\/ ========================================================================== \/\/\n\/\/ This file is part of Sara, a basic set of libraries in C++ for computer\n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2018 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n\n#define BOOST_TEST_MODULE \"MultiViewGeometry\/Essential Matrix\"\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n\nusing namespace std;\nusing namespace DO::Sara;\n\n\nvoid load(Image& image1, Image& image2,\n Set& keys1,\n Set& keys2, \/\/\n vector& matches)\n{\n cout << \"Loading images\" << endl;\n\n auto data_dir = std::string{\"\/home\/david\/Desktop\/Datasets\/sfm\/castle_int\"};\n auto file1 = \"0000.png\";\n auto file2 = \"0001.png\";\n\n image1 = imread(data_dir + \"\/\" + file1);\n image2 = imread(data_dir + \"\/\" + file2);\n\n#ifdef COMPUTE_KEYPOINTS\n cout << \"Computing\/Reading keypoints\" << endl;\n auto sifts1 = compute_sift_keypoints(image1.convert());\n auto sifts2 = compute_sift_keypoints(image2.convert());\n keys1.append(sifts1);\n keys2.append(sifts2);\n cout << \"Image 1: \" << keys1.size() << \" keypoints\" << endl;\n cout << \"Image 2: \" << keys2.size() << \" keypoints\" << endl;\n\n write_keypoints(sifts1.features, sifts1.descriptors,\n data_dir + \"\/\" + \"0000.key\");\n write_keypoints(sifts2.features, sifts2.descriptors,\n data_dir + \"\/\" + \"0001.key\");\n\n#else\n read_keypoints(keys1.features, keys1.descriptors,\n data_dir + \"\/\" + \"0000.key\");\n read_keypoints(keys2.features, keys2.descriptors,\n data_dir + \"\/\" + \"0001.key\");\n#endif\n\n \/\/ Compute\/read matches\n cout << \"Computing Matches\" << endl;\n AnnMatcher matcher{keys1, keys2, 1.0f};\n matches = matcher.compute_matches();\n cout << matches.size() << \" matches\" << endl;\n\n \/\/ Debug this.\n \/\/write_matches(matches, data_dir + \"\/\" + \"0000_0001.match\");\n}\n\n\n\/\/ NumPy-like interface for Tensors\nauto range(int n) -> Tensor_\n{\n auto indices = Tensor_{n};\n std::iota(indices.begin(), indices.end(), 0);\n return indices;\n}\n\nauto random_shuffle(const Tensor_& x) -> Tensor_\n{\n Tensor_ x_shuffled = x;\n std::random_shuffle(x_shuffled.begin(), x_shuffled.end());\n return x_shuffled;\n}\n\nauto random_samples(int num_samples, int sample_size, int num_data_points)\n -> Tensor_\n{\n auto indices = range(num_data_points);\n\n auto samples = Tensor_{sample_size, num_samples};\n for (int i = 0; i < sample_size; ++i)\n samples[i].flat_array() =\n random_shuffle(indices).flat_array().head(num_samples);\n\n samples = samples.transpose({1, 0});\n\n return samples;\n}\n\n\n\/\/ Data transformations.\nauto extract_centers(const std::vector& features) -> Tensor_\n{\n auto centers = Tensor_(features.size(), 3);\n auto mat = centers.matrix();\n\n for (auto i = 0; i < centers.size(0); ++i)\n mat.row(i) << features[i].x(), features[i].y(), 1.f;\n\n return centers;\n}\n\nauto to_point_indices(const Tensor_& samples, const Tensor_& matches)\n -> Tensor_\n{\n const auto num_samples = samples.size(0);\n const auto sample_size = samples.size(1);\n\n auto point_indices = Tensor_{num_samples, sample_size, 2};\n for (auto s = 0; s < num_samples; ++s)\n for (auto m = 0; m < sample_size; ++m)\n point_indices[s][m].flat_array() = matches[samples(s, m)].flat_array();\n\n return point_indices;\n}\n\nauto to_coordinates(const Tensor_& point_indices,\n const Tensor_& p1,\n const Tensor_& p2)\n -> Tensor_\n{\n auto num_samples = point_indices.size(0);\n auto sample_size = point_indices.size(1);\n auto num_points = 2;\n auto coords_dim = 2;\n\n auto p =\n Tensor_{{num_samples, sample_size, num_points, coords_dim}};\n\n for (auto s = 0; s < num_samples; ++s)\n for (auto m = 0; m < sample_size; ++m)\n {\n auto p1_idx = point_indices(s, m, 0);\n auto p2_idx = point_indices(s, m, 1);\n\n p[s][m][0].flat_array() = p1[p1_idx].flat_array();\n p[s][m][1].flat_array() = p2[p2_idx].flat_array();\n }\n\n return p;\n}\n\n\n\/\/ Point transformations.\nauto compute_normalizer(const Tensor_& X) -> Matrix3f\n{\n const RowVector3f min = X.matrix().colwise().minCoeff();\n const RowVector3f max = X.matrix().colwise().maxCoeff();\n\n const Matrix2f scale = (max - min).cwiseInverse().head(2).asDiagonal();\n\n Matrix3f T = Matrix3f::Zero();\n T.topLeftCorner<2, 2>() = scale;\n T.col(2) << -min.cwiseQuotient(max - min).transpose().head(2), 1.f;\n\n return T;\n}\n\nauto apply_transform(const Matrix3f& T, const Tensor_& X)\n -> Tensor_\n{\n auto TX = Tensor_{X.sizes()};\n auto TX_ = TX.colmajor_view().matrix();\n TX_ = T * X.colmajor_view().matrix();\n TX_.array().rowwise() \/= TX_.array().row(2);\n return TX;\n}\n\n\nBOOST_AUTO_TEST_SUITE(TestMultiViewGeometry)\n\nBOOST_AUTO_TEST_CASE(test_range)\n{\n auto a = range(3);\n BOOST_CHECK(vec(a) == Vector3i(0, 1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(test_random_shuffle)\n{\n auto a = range(4);\n a = random_shuffle(a);\n BOOST_CHECK(vec(a) != Vector4i(0, 1, 2, 3));\n}\n\nBOOST_AUTO_TEST_CASE(test_random_samples)\n{\n constexpr auto num_samples = 2;\n constexpr auto sample_size = 5;\n constexpr auto num_data_points = 10;\n auto samples = random_samples(num_samples, sample_size, num_data_points);\n\n BOOST_CHECK_EQUAL(samples.size(0), num_samples);\n BOOST_CHECK_EQUAL(samples.size(1), sample_size);\n BOOST_CHECK(samples.matrix().minCoeff() >= 0);\n BOOST_CHECK(samples.matrix().maxCoeff() < 10);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_extract_centers)\n{\n auto features = std::vector{{Point2f::Ones() * 0, 1.f},\n {Point2f::Ones() * 1, 1.f},\n {Point2f::Ones() * 2, 1.f}};\n\n auto centers = extract_centers(features);\n auto expected_centers = Tensor_{centers.sizes()};\n expected_centers.matrix() <<\n 0, 0, 1,\n 1, 1, 1,\n 2, 2, 1;\n\n BOOST_CHECK(centers.matrix() == expected_centers.matrix());\n}\n\nBOOST_AUTO_TEST_CASE(test_to_point_indices)\n{\n constexpr auto num_matches = 5;\n constexpr auto num_samples = 2;\n constexpr auto sample_size = 4;\n\n auto matches = Tensor_{num_matches, 2};\n matches.matrix() <<\n 0, 0,\n 1, 1,\n 2, 2,\n 3, 3,\n 4, 0;\n\n auto samples = Tensor_{num_samples, sample_size};\n samples.matrix() <<\n 0, 1, 2, 3,\n 4, 2, 3, 1;\n\n auto point_indices = to_point_indices(samples, matches);\n\n auto expected_point_indices = Tensor_{num_samples, sample_size, 2};\n expected_point_indices[0].matrix() <<\n 0, 0,\n 1, 1,\n 2, 2,\n 3, 3;\n expected_point_indices[1].matrix() <<\n 4, 0,\n 2, 2,\n 3, 3,\n 1, 1;\n\n BOOST_CHECK(vec(point_indices) == vec(expected_point_indices));\n}\n\ntemplate \nvoid print_3d_array(const TensorView_& x)\n{\n const auto max = x.flat_array().abs().maxCoeff();\n std::stringstream ss;\n ss << max;\n const auto pad_size = ss.str().size();\n\n\n cout << \"[\";\n for (auto i = 0; i < x.size(0); ++i)\n {\n cout << \"[\";\n for (auto j = 0; j < x.size(1); ++j)\n {\n cout << \"[\";\n for (auto k = 0; k < x.size(2); ++k)\n {\n cout << std::setw(pad_size) << x(i,j,k);\n if (k != x.size(2) - 1)\n cout << \", \";\n }\n cout << \"]\";\n\n if (j != x.size(1) - 1)\n cout << \", \";\n else\n cout << \"]\";\n }\n\n if (i != x.size(0) - 1)\n cout << \",\\n \";\n }\n cout << \"]\" << endl;\n}\n\nBOOST_AUTO_TEST_CASE(test_to_coordinates)\n{\n constexpr auto num_matches = 5;\n constexpr auto num_samples = 2;\n constexpr auto sample_size = 4;\n\n const auto features1 = std::vector{{Point2f::Ones() * 0, 1.f},\n {Point2f::Ones() * 1, 1.f},\n {Point2f::Ones() * 2, 1.f}};\n const auto features2 = std::vector{{Point2f::Ones() * 1, 1.f},\n {Point2f::Ones() * 2, 1.f},\n {Point2f::Ones() * 3, 1.f}};\n\n const auto points1 = extract_centers(features1);\n const auto points2 = extract_centers(features2);\n\n auto matches = Tensor_{num_matches, 2};\n matches.matrix() <<\n 0, 0,\n 1, 1,\n 2, 2,\n 0, 1,\n 1, 2;\n\n auto samples = Tensor_{num_samples, sample_size};\n samples.matrix() <<\n 0, 1, 2, 3,\n 1, 2, 3, 4;\n\n const auto point_indices = to_point_indices(samples, matches);\n const auto coords = to_coordinates(point_indices, points1, points2);\n\n \/\/ N K P C\n auto expected_coords = Tensor_{{num_samples, sample_size, 2, 2}};\n expected_coords[0].flat_array() <<\n 0.f, 0.f, 1.f, 1.f,\n 1.f, 1.f, 2.f, 2.f,\n 2.f, 2.f, 3.f, 3.f,\n 0.f, 0.f, 2.f, 2.f;\n\n expected_coords[1].flat_array() <<\n 1.f, 1.f, 2.f, 2.f,\n 2.f, 2.f, 3.f, 3.f,\n 0.f, 0.f, 2.f, 2.f,\n 1.f, 1.f, 3.f, 3.f;\n\n BOOST_CHECK(vec(expected_coords) == vec(coords));\n BOOST_CHECK(expected_coords.sizes() == coords.sizes());\n\n\n const auto coords_t = coords.transpose({0, 2, 1, 3});\n const auto sample1 = coords_t[0];\n\n auto expected_sample1 = Tensor_{sample1.sizes()};\n expected_sample1.flat_array() <<\n \/\/ P1\n 0.f, 0.f,\n 1.f, 1.f,\n 2.f, 2.f,\n 0.f, 0.f,\n \/\/ P2\n 1.f, 1.f,\n 2.f, 2.f,\n 3.f, 3.f,\n 2.f, 2.f;\n\n \/\/print_3d_array(expected_sample1);\n \/\/print_3d_array(sample1);\n BOOST_CHECK(vec(expected_sample1) == vec(sample1));\n}\n\nBOOST_AUTO_TEST_CASE(test_compute_normalizer)\n{\n auto X = Tensor_{3, 3};\n X.matrix() <<\n 1, 1, 1,\n 2, 2, 1,\n 3, 3, 1;\n\n auto T = compute_normalizer(X);\n\n Matrix3f expected_T;\n expected_T <<\n 0.5, 0.0, -0.5,\n 0.0, 0.5, -0.5,\n 0.0, 0.0, 1.0;\n\n BOOST_CHECK((T - expected_T).norm() < 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE(test_apply_transform)\n{\n auto X = Tensor_{3, 3};\n X.matrix() <<\n 1, 1, 1,\n 2, 2, 1,\n 3, 3, 1;\n\n auto T = compute_normalizer(X);\n\n auto TX = apply_transform(T, X);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\nWIP: fix tests.\/\/ ========================================================================== \/\/\n\/\/ This file is part of Sara, a basic set of libraries in C++ for computer\n\/\/ vision.\n\/\/\n\/\/ Copyright (C) 2018 David Ok \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla Public\n\/\/ License v. 2.0. If a copy of the MPL was not distributed with this file,\n\/\/ you can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\/\/ ========================================================================== \/\/\n\n\n#define BOOST_TEST_MODULE \"MultiViewGeometry\/Essential Matrix\"\n\n#include \n#include \n#include \n\n#include \n\n#include \n#include \n\n\nusing namespace std;\nusing namespace DO::Sara;\n\n\ntemplate \nvoid print_3d_array(const TensorView_& x)\n{\n const auto max = x.flat_array().abs().maxCoeff();\n std::stringstream ss;\n ss << max;\n const auto pad_size = ss.str().size();\n\n\n cout << \"[\";\n for (auto i = 0; i < x.size(0); ++i)\n {\n cout << \"[\";\n for (auto j = 0; j < x.size(1); ++j)\n {\n cout << \"[\";\n for (auto k = 0; k < x.size(2); ++k)\n {\n cout << std::setw(pad_size) << x(i,j,k);\n if (k != x.size(2) - 1)\n cout << \", \";\n }\n cout << \"]\";\n\n if (j != x.size(1) - 1)\n cout << \", \";\n else\n cout << \"]\";\n }\n\n if (i != x.size(0) - 1)\n cout << \",\\n \";\n }\n cout << \"]\" << endl;\n}\n\nvoid print_3d_array(const TensorView_& x)\n{\n cout << \"[\";\n for (auto i = 0; i < x.size(0); ++i)\n {\n cout << \"[\";\n for (auto j = 0; j < x.size(1); ++j)\n {\n cout << \"[\";\n for (auto k = 0; k < x.size(2); ++k)\n {\n cout << fixed << x(i,j,k);\n if (k != x.size(2) - 1)\n cout << \", \";\n }\n cout << \"]\";\n\n if (j != x.size(1) - 1)\n cout << \", \";\n else\n cout << \"]\";\n }\n\n if (i != x.size(0) - 1)\n cout << \",\\n \";\n }\n cout << \"]\" << endl;\n}\n\n\nvoid load(Image& image1, Image& image2,\n Set& keys1,\n Set& keys2, \/\/\n vector& matches)\n{\n cout << \"Loading images\" << endl;\n\n auto data_dir = std::string{\"\/home\/david\/Desktop\/Datasets\/sfm\/castle_int\"};\n auto file1 = \"0000.png\";\n auto file2 = \"0001.png\";\n\n image1 = imread(data_dir + \"\/\" + file1);\n image2 = imread(data_dir + \"\/\" + file2);\n\n#ifdef COMPUTE_KEYPOINTS\n cout << \"Computing\/Reading keypoints\" << endl;\n auto sifts1 = compute_sift_keypoints(image1.convert());\n auto sifts2 = compute_sift_keypoints(image2.convert());\n keys1.append(sifts1);\n keys2.append(sifts2);\n cout << \"Image 1: \" << keys1.size() << \" keypoints\" << endl;\n cout << \"Image 2: \" << keys2.size() << \" keypoints\" << endl;\n\n write_keypoints(sifts1.features, sifts1.descriptors,\n data_dir + \"\/\" + \"0000.key\");\n write_keypoints(sifts2.features, sifts2.descriptors,\n data_dir + \"\/\" + \"0001.key\");\n\n#else\n read_keypoints(keys1.features, keys1.descriptors,\n data_dir + \"\/\" + \"0000.key\");\n read_keypoints(keys2.features, keys2.descriptors,\n data_dir + \"\/\" + \"0001.key\");\n#endif\n\n \/\/ Compute\/read matches\n cout << \"Computing Matches\" << endl;\n AnnMatcher matcher{keys1, keys2, 1.0f};\n matches = matcher.compute_matches();\n cout << matches.size() << \" matches\" << endl;\n\n \/\/ Debug this.\n \/\/write_matches(matches, data_dir + \"\/\" + \"0000_0001.match\");\n}\n\n\n\/\/ NumPy-like interface for Tensors\nauto range(int n) -> Tensor_\n{\n auto indices = Tensor_{n};\n std::iota(indices.begin(), indices.end(), 0);\n return indices;\n}\n\nauto random_shuffle(const Tensor_& x) -> Tensor_\n{\n Tensor_ x_shuffled = x;\n std::random_shuffle(x_shuffled.begin(), x_shuffled.end());\n return x_shuffled;\n}\n\nauto random_samples(int num_samples, int sample_size, int num_data_points)\n -> Tensor_\n{\n auto indices = range(num_data_points);\n\n auto samples = Tensor_{sample_size, num_samples};\n for (int i = 0; i < sample_size; ++i)\n samples[i].flat_array() =\n random_shuffle(indices).flat_array().head(num_samples);\n\n samples = samples.transpose({1, 0});\n\n return samples;\n}\n\n\n\/\/ Data transformations.\nauto extract_centers(const std::vector& features) -> Tensor_\n{\n auto centers = Tensor_{int(features.size()), 2};\n auto mat = centers.matrix();\n\n for (auto i = 0; i < centers.size(0); ++i)\n mat.row(i) = features[i].center().transpose();\n\n return centers;\n}\n\nauto homogeneous(const TensorView_& x)\n -> Tensor_\n{\n auto X = Tensor_(x.size(0), x.size(1) + 1);\n X.matrix().leftCols(x.size(1)) = x.matrix();\n X.matrix().col(x.size(1)).setOnes();\n return X;\n}\n\nauto to_point_indices(const TensorView_& samples, const TensorView_& matches)\n -> Tensor_\n{\n const auto num_samples = samples.size(0);\n const auto sample_size = samples.size(1);\n\n auto point_indices = Tensor_{num_samples, sample_size, 2};\n for (auto s = 0; s < num_samples; ++s)\n for (auto m = 0; m < sample_size; ++m)\n point_indices[s][m].flat_array() = matches[samples(s, m)].flat_array();\n\n return point_indices;\n}\n\nauto to_coordinates(const Tensor_& point_indices,\n const Tensor_& p1,\n const Tensor_& p2)\n -> Tensor_\n{\n const auto num_samples = point_indices.size(0);\n const auto sample_size = point_indices.size(1);\n const auto num_points = 2;\n const auto coords_dim = p1.size(1);\n\n auto p =\n Tensor_{{num_samples, sample_size, num_points, coords_dim}};\n\n for (auto s = 0; s < num_samples; ++s)\n for (auto m = 0; m < sample_size; ++m)\n {\n auto p1_idx = point_indices(s, m, 0);\n auto p2_idx = point_indices(s, m, 1);\n\n p[s][m][0].flat_array() = p1[p1_idx].flat_array();\n p[s][m][1].flat_array() = p2[p2_idx].flat_array();\n }\n\n return p;\n}\n\n\n\/\/ Point transformations.\nauto compute_normalizer(const Tensor_& X) -> Matrix3f\n{\n const RowVector3f min = X.matrix().colwise().minCoeff();\n const RowVector3f max = X.matrix().colwise().maxCoeff();\n\n const Matrix2f scale = (max - min).cwiseInverse().head(2).asDiagonal();\n\n Matrix3f T = Matrix3f::Zero();\n T.topLeftCorner<2, 2>() = scale;\n T.col(2) << -min.cwiseQuotient(max - min).transpose().head(2), 1.f;\n\n return T;\n}\n\nauto apply_transform(const Matrix3f& T, const Tensor_& X)\n -> Tensor_\n{\n auto TX = Tensor_{X.sizes()};\n auto TX_ = TX.colmajor_view().matrix();\n TX_ = T * X.colmajor_view().matrix();\n TX_.array().rowwise() \/= TX_.array().row(2);\n return TX;\n}\n\n\nBOOST_AUTO_TEST_SUITE(TestMultiViewGeometry)\n\nBOOST_AUTO_TEST_CASE(test_range)\n{\n auto a = range(3);\n BOOST_CHECK(vec(a) == Vector3i(0, 1, 2));\n}\n\nBOOST_AUTO_TEST_CASE(test_random_shuffle)\n{\n auto a = range(4);\n a = random_shuffle(a);\n BOOST_CHECK(vec(a) != Vector4i(0, 1, 2, 3));\n}\n\nBOOST_AUTO_TEST_CASE(test_random_samples)\n{\n constexpr auto num_samples = 2;\n constexpr auto sample_size = 5;\n constexpr auto num_data_points = 10;\n auto samples = random_samples(num_samples, sample_size, num_data_points);\n\n BOOST_CHECK_EQUAL(samples.size(0), num_samples);\n BOOST_CHECK_EQUAL(samples.size(1), sample_size);\n BOOST_CHECK(samples.matrix().minCoeff() >= 0);\n BOOST_CHECK(samples.matrix().maxCoeff() < 10);\n}\n\n\nBOOST_AUTO_TEST_CASE(test_extract_centers)\n{\n auto features = std::vector{{Point2f::Ones() * 0, 1.f},\n {Point2f::Ones() * 1, 1.f},\n {Point2f::Ones() * 2, 1.f}};\n\n const auto x = extract_centers(features);\n auto expected_x = Tensor_{x.sizes()};\n expected_x.matrix() <<\n 0, 0,\n 1, 1,\n 2, 2;\n\n BOOST_CHECK(x.matrix() == expected_x.matrix());\n\n const auto X = homogeneous(x);\n auto expected_X = Tensor_{X.sizes()};\n expected_X.matrix() <<\n 0, 0, 1,\n 1, 1, 1,\n 2, 2, 1;\n BOOST_CHECK(X.matrix() == expected_X.matrix());\n}\n\nBOOST_AUTO_TEST_CASE(test_to_point_indices)\n{\n constexpr auto num_matches = 5;\n constexpr auto num_samples = 2;\n constexpr auto sample_size = 4;\n\n auto matches = Tensor_{num_matches, 2};\n matches.matrix() <<\n 0, 0,\n 1, 1,\n 2, 2,\n 3, 3,\n 4, 0;\n\n auto samples = Tensor_{num_samples, sample_size};\n samples.matrix() <<\n 0, 1, 2, 3,\n 4, 2, 3, 1;\n\n auto point_indices = to_point_indices(samples, matches);\n\n auto expected_point_indices = Tensor_{num_samples, sample_size, 2};\n expected_point_indices[0].matrix() <<\n 0, 0,\n 1, 1,\n 2, 2,\n 3, 3;\n expected_point_indices[1].matrix() <<\n 4, 0,\n 2, 2,\n 3, 3,\n 1, 1;\n\n BOOST_CHECK(vec(point_indices) == vec(expected_point_indices));\n}\n\nBOOST_AUTO_TEST_CASE(test_to_coordinates)\n{\n constexpr auto num_matches = 5;\n constexpr auto num_samples = 2;\n constexpr auto sample_size = 4;\n\n const auto features1 = std::vector{{Point2f::Ones() * 0, 1.f},\n {Point2f::Ones() * 1, 1.f},\n {Point2f::Ones() * 2, 1.f}};\n const auto features2 = std::vector{{Point2f::Ones() * 1, 1.f},\n {Point2f::Ones() * 2, 1.f},\n {Point2f::Ones() * 3, 1.f}};\n\n const auto points1 = extract_centers(features1);\n const auto points2 = extract_centers(features2);\n\n auto matches = Tensor_{num_matches, 2};\n matches.matrix() <<\n 0, 0,\n 1, 1,\n 2, 2,\n 0, 1,\n 1, 2;\n\n auto samples = Tensor_{num_samples, sample_size};\n samples.matrix() <<\n 0, 1, 2, 3,\n 1, 2, 3, 4;\n\n const auto point_indices = to_point_indices(samples, matches);\n const auto coords = to_coordinates(point_indices, points1, points2);\n\n \/\/ N K P C\n auto expected_coords = Tensor_{{num_samples, sample_size, 2, 2}};\n expected_coords[0].flat_array() <<\n 0.f, 0.f, 1.f, 1.f,\n 1.f, 1.f, 2.f, 2.f,\n 2.f, 2.f, 3.f, 3.f,\n 0.f, 0.f, 2.f, 2.f;\n\n expected_coords[1].flat_array() <<\n 1.f, 1.f, 2.f, 2.f,\n 2.f, 2.f, 3.f, 3.f,\n 0.f, 0.f, 2.f, 2.f,\n 1.f, 1.f, 3.f, 3.f;\n\n BOOST_CHECK(vec(expected_coords) == vec(coords));\n BOOST_CHECK(expected_coords.sizes() == coords.sizes());\n\n\n const auto coords_t = coords.transpose({0, 2, 1, 3});\n const auto sample1 = coords_t[0];\n\n auto expected_sample1 = Tensor_{sample1.sizes()};\n expected_sample1.flat_array() <<\n \/\/ P1\n 0.f, 0.f,\n 1.f, 1.f,\n 2.f, 2.f,\n 0.f, 0.f,\n \/\/ P2\n 1.f, 1.f,\n 2.f, 2.f,\n 3.f, 3.f,\n 2.f, 2.f;\n\n \/\/print_3d_array(expected_sample1);\n \/\/print_3d_array(sample1);\n BOOST_CHECK(vec(expected_sample1) == vec(sample1));\n}\n\nBOOST_AUTO_TEST_CASE(test_compute_normalizer)\n{\n auto X = Tensor_{3, 3};\n X.matrix() <<\n 1, 1, 1,\n 2, 2, 1,\n 3, 3, 1;\n\n auto T = compute_normalizer(X);\n\n Matrix3f expected_T;\n expected_T <<\n 0.5, 0.0, -0.5,\n 0.0, 0.5, -0.5,\n 0.0, 0.0, 1.0;\n\n BOOST_CHECK((T - expected_T).norm() < 1e-12);\n}\n\nBOOST_AUTO_TEST_CASE(test_apply_transform)\n{\n auto X = Tensor_{3, 3};\n X.matrix() <<\n 1, 1, 1,\n 2, 2, 1,\n 3, 3, 1;\n\n auto T = compute_normalizer(X);\n\n auto TX = apply_transform(T, X);\n}\n\nBOOST_AUTO_TEST_SUITE_END()\n<|endoftext|>"} {"text":"\/********************************************************************************\n $Header$\n\n purpose:\n\n notes:\n\n to do:\n\n author(s):\n - Dirk Farin, farin@ti.uni-mannheim.de\n University Mannheim, Dept. Circuitry and Simulation\n L 15,16 room 410 \/ D-68131 Mannheim \/ Germany\n\n modifications:\n 24\/Jan\/2002 - Dirk Farin - Complete reimplementation based on old Image type.\n 02\/Jun\/1999 - Dirk Farin - first implementation\n ********************************************************************************\n Copyright (C) 2002 Dirk Farin\n\n This program is distributed under GNU Public License (GPL) as\n outlined in the COPYING file that comes with the source distribution.\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n ********************************************************************************\/\n\n\n#ifndef LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH\n#define LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH\n\n#include \n\n#include \n#include \n#include \n\n\nenum Colorspace\n {\n Colorspace_RGB, Colorspace_YUV, Colorspace_Greyscale, Colorspace_HSV,\n Colorspace_Invalid\n };\n\nenum ChromaFormat {\n \/** Subsampling h:2 v:2 *\/ Chroma_420,\n \/** Subsampling h:2 v:1 *\/ Chroma_422,\n \/** No subsampling *\/ Chroma_444,\n Chroma_Invalid\n};\n\nenum BitmapChannel { Bitmap_Red = 0, Bitmap_Green = 1, Bitmap_Blue = 2,\n\t\t Bitmap_Y = 0, Bitmap_Cb = 1, Bitmap_Cr = 2,\n \t\t Bitmap_U = 1, Bitmap_V = 2,\n\t\t Bitmap_Hue = 0, Bitmap_Saturation = 1, Bitmap_Value = 2,\n\t\t Bitmap_Alpha=3\n};\n\n\n\/** Check if chroma is horizontally subsampled. Usage of the more general #ChromaSubH()# is recommended. *\/\ninline bool IsSubH(ChromaFormat cf) { return cf != Chroma_444; }\n\/** Check if chroma is vertically subsampled. Usage of the more general #ChromaSubV()# is recommended. *\/\ninline bool IsSubV(ChromaFormat cf) { return cf == Chroma_420; }\n\/** Get horizontal subsampling factor. *\/\ninline int ChromaSubH(ChromaFormat cf) { return (cf != Chroma_444) ? 2 : 1; }\n\/** Get vertical subsampling factor. *\/\ninline int ChromaSubV(ChromaFormat cf) { return (cf == Chroma_420) ? 2 : 1; }\n\n\nstruct ImageParam\n{\n ImageParam() : width(0), height(0), halign(1), valign(1), border(0),\n\t\t colorspace(Colorspace_Invalid), has_alpha(false),\n\t\t chroma(Chroma_420), reduced_chroma_resolution(true),\n\t\t chroma_border(-1), chroma_halign(-1), chroma_valign(-1)\n { }\n\n int width,height;\n int halign,valign;\n int border;\n\n Colorspace colorspace;\n bool has_alpha;\n\n ChromaFormat chroma;\n bool reduced_chroma_resolution;\n int chroma_border;\n int chroma_halign;\n int chroma_valign;\n\n#if 0\n \/** If set to #true#: don't allow the alignment or the border to be greater than specified.\n {\\bf Explanation}: As it is more efficient to keep and older bitmap if the new one\n is smaller than the old one, the old one is sometimes used instead of creating\n a new one. This does not work if you are depending on the exact memory layout of\n the image. So you can disable it by setting exact\\_size to true. *\/\n bool exact_size;\n#endif\n\n int AskChromaWidth() const { return (width +ChromaSubH(chroma)-1)\/ChromaSubH(chroma); }\n int AskChromaHeight() const { return (height+ChromaSubV(chroma)-1)\/ChromaSubV(chroma); }\n void AskChromaSizes(int& w,int &h) const;\n int AskChromaBorder() const;\n int AskChromaHAlign() const;\n int AskChromaVAlign() const;\n};\n\n\n\n\ntemplate class Image\n{\npublic:\n virtual ~Image() { }\n\n void Create(const ImageParam&);\n void Release();\n\n \/\/\/ Get colorspace independent image parameters.\n ImageParam AskParam() const { return d_param; }\n int AskWidth() const { return d_param.width; }\n int AskHeight() const { return d_param.height; }\n int AskBorder() const { return d_param.border; }\n void GetSize(int& w,int& h) const { w=d_param.width; h=d_param.height; }\n\n\n Bitmap& AskBitmap(BitmapChannel pm_id) { return d_pm[pm_id]; }\n const Bitmap& AskBitmap(BitmapChannel pm_id) const { return d_pm[pm_id]; }\n\n Pel*const* AskFrame(BitmapChannel pm_id) { return d_pm[pm_id].AskFrame(); }\n const Pel*const* AskFrame(BitmapChannel pm_id) const { return d_pm[pm_id].AskFrame(); }\n\n\n \/** Replace a complete bitmap. Note that the new bitmap either has to be empty or has to\n be exactly the same size as the old one.\n Furthermore you are responsible that all alignments and the border size is sufficient\n for your application. This is not checked!\n \n If you insert or remove (by replacing a bitmap by an empty one) an alpha bitmap,\n the alphamask-flag in ImageParam will be set accordingly.\n *\/\n void ReplaceBitmap(BitmapChannel id,const Bitmap&);\n \/\/\/ Set new image parameters.\n void SetParam(const ImageParam& param) { d_param=param; }\n\n Image Clone() const;\n\n Image CreateSubView (int x0,int y0,int w,int h) const;\n Image CreateFieldView(bool top) const;\n\n bool IsEmpty() const { return d_pm[0].IsEmpty(); }\n\n Pel*const* AskFrameR() { return d_pm[Bitmap_Red].AskFrame(); }\n const Pel*const* AskFrameR() const { return d_pm[Bitmap_Red].AskFrame(); }\n Pel*const* AskFrameG() { return d_pm[Bitmap_Green].AskFrame(); }\n const Pel*const* AskFrameG() const { return d_pm[Bitmap_Green].AskFrame(); }\n Pel*const* AskFrameB() { return d_pm[Bitmap_Blue].AskFrame(); }\n const Pel*const* AskFrameB() const { return d_pm[Bitmap_Blue].AskFrame(); }\n Pel*const* AskFrameY() { return d_pm[Bitmap_Y].AskFrame(); }\n const Pel*const* AskFrameY() const { return d_pm[Bitmap_Y].AskFrame(); }\n Pel*const* AskFrameU() { return d_pm[Bitmap_U].AskFrame(); }\n const Pel*const* AskFrameU() const { return d_pm[Bitmap_U].AskFrame(); }\n Pel*const* AskFrameV() { return d_pm[Bitmap_V].AskFrame(); }\n const Pel*const* AskFrameV() const { return d_pm[Bitmap_V].AskFrame(); }\n Pel*const* AskFrameCb() { return d_pm[Bitmap_Cb].AskFrame(); }\n const Pel*const* AskFrameCb() const { return d_pm[Bitmap_Cb].AskFrame(); }\n Pel*const* AskFrameCr() { return d_pm[Bitmap_Cr].AskFrame(); }\n const Pel*const* AskFrameCr() const { return d_pm[Bitmap_Cr].AskFrame(); }\n Pel*const* AskFrameA() { return d_pm[Bitmap_Alpha].AskFrame(); }\n const Pel*const* AskFrameA() const { return d_pm[Bitmap_Alpha].AskFrame(); }\n\n Bitmap& AskBitmapR() { return d_pm[Bitmap_Red]; }\n const Bitmap& AskBitmapR() const { return d_pm[Bitmap_Red]; }\n Bitmap& AskBitmapG() { return d_pm[Bitmap_Green]; }\n const Bitmap& AskBitmapG() const { return d_pm[Bitmap_Green]; }\n Bitmap& AskBitmapB() { return d_pm[Bitmap_Blue]; }\n const Bitmap& AskBitmapB() const { return d_pm[Bitmap_Blue]; }\n Bitmap& AskBitmapY() { return d_pm[Bitmap_Y]; }\n const Bitmap& AskBitmapY() const { return d_pm[Bitmap_Y]; }\n Bitmap& AskBitmapU() { return d_pm[Bitmap_U]; }\n const Bitmap& AskBitmapU() const { return d_pm[Bitmap_U]; }\n Bitmap& AskBitmapV() { return d_pm[Bitmap_V]; }\n const Bitmap& AskBitmapV() const { return d_pm[Bitmap_V]; }\n Bitmap& AskBitmapCb() { return d_pm[Bitmap_Cb]; }\n const Bitmap& AskBitmapCb() const { return d_pm[Bitmap_Cb]; }\n Bitmap& AskBitmapCr() { return d_pm[Bitmap_Cr]; }\n const Bitmap& AskBitmapCr() const { return d_pm[Bitmap_Cr]; }\n Bitmap& AskBitmapA() { return d_pm[Bitmap_Alpha]; }\n const Bitmap& AskBitmapA() const { return d_pm[Bitmap_Alpha]; }\n\n bool IsShared() const\n {\n for (int i=0;i<4;i++)\n if (d_pm[i].IsShared())\n\treturn true;\n\n return false;\n }\n\nprivate:\n Bitmap d_pm[4];\n ImageParam d_param;\n};\n\n\n\ntemplate void Image::Create(const ImageParam& param)\n{\n d_pm[0].Create(param.width, param.height, param.border,param.halign,param.valign);\n\n switch (param.colorspace)\n {\n case Colorspace_RGB:\n case Colorspace_HSV:\n d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);\n d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);\n break;\n\n case Colorspace_YUV:\n if (param.reduced_chroma_resolution)\n\t{\n\t d_pm[1].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),\n\t\t\t param.AskChromaHAlign(),param.AskChromaVAlign());\n\t d_pm[2].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),\n\t\t\t param.AskChromaHAlign(),param.AskChromaVAlign());\n\t}\n else\n\t{\n\t d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);\n\t d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);\n\t}\n break;\n\n case Colorspace_Greyscale:\n d_pm[1].Release();\n d_pm[2].Release();\n break;\n }\n\n if (param.has_alpha)\n d_pm[Bitmap_Alpha].Create(param.width, param.height, param.border,param.halign,param.valign);\n else\n d_pm[Bitmap_Alpha].Release();\n\n d_param = param;\n}\n\n\ntemplate void Image::Release()\n{\n for (int i=0;i<4;i++)\n d_pm[i].Release();\n\n d_param = ImageParam();\n}\n\n\ntemplate Image Image::Clone() const\n{\n Image img;\n for (int i=0;i<4;i++)\n img.d_pm[i] = d_pm[i].Clone();\n\n img.d_param = d_param;\n\n return img;\n}\n\ntemplate Image Image::CreateSubView(int x0,int y0,int w,int h) const\n{\n Image newimg;\n newimg.d_param = d_param;\n\n newimg.d_param.width = w;\n newimg.d_param.height = h;\n newimg.d_param.halign = 1;\n newimg.d_param.valign = 1;\n newimg.d_param.border = 0;\n newimg.d_param.chroma_border = -1;\n newimg.d_param.chroma_halign = -1;\n newimg.d_param.chroma_valign = -1;\n\n if (d_param.colorspace == Colorspace_YUV)\n {\n newimg.d_pm[0] = d_pm[0].CreateSubView(x0,y0,w,h);\n newimg.d_pm[3] = d_pm[3].CreateSubView(x0,y0,w,h);\n\n int subh = ChromaSubH(d_param.chroma);\n int subv = ChromaSubV(d_param.chroma);\n\n newimg.d_pm[1] = d_pm[1].CreateSubView(x0\/subh,y0\/subv,(w+subh-1)\/subh,(h+subv-1)\/subv);\n newimg.d_pm[2] = d_pm[2].CreateSubView(x0\/subh,y0\/subv,(w+subh-1)\/subh,(h+subv-1)\/subv);\n }\n else\n {\n for (int i=0;i<4;i++)\n\tnewimg.d_pm[i] = d_pm[i].CreateSubView(x0,y0,w,h);\n }\n\n return newimg;\n}\n\ntemplate Image Image::CreateFieldView(bool top) const\n{\n if (!top && d_param.colorspace==Colorspace_YUV && d_param.chroma==Chroma_420 &&\n (d_pm[0].AskHeight()%2)==0 && (d_pm[1].AskHeight()%2)==1)\n {\n AssertDescr(false,\"not enough chroma information for bottom field\");\n }\n\n Image newimg;\n newimg.d_param = d_param;\n\n for (int i=0;i<4;i++)\n newimg.d_pm[i] = d_pm[i].CreateFieldView(top);\n\n newimg.d_param.width = newimg.d_pm[0].AskWidth();\n newimg.d_param.height = newimg.d_pm[0].AskHeight();\n newimg.d_param.halign = 1;\n newimg.d_param.valign = 1;\n newimg.d_param.border = 0;\n newimg.d_param.chroma_border = -1;\n newimg.d_param.chroma_halign = -1;\n newimg.d_param.chroma_valign = -1;\n\n return newimg;\n}\n\n#endif\nutility methods in ImageParam: scale pixel coordinates according to chroma type\/********************************************************************************\n $Header$\n\n purpose:\n\n notes:\n\n to do:\n\n author(s):\n - Dirk Farin, farin@ti.uni-mannheim.de\n University Mannheim, Dept. Circuitry and Simulation\n L 15,16 room 410 \/ D-68131 Mannheim \/ Germany\n\n modifications:\n 24\/Jan\/2002 - Dirk Farin - Complete reimplementation based on old Image type.\n 02\/Jun\/1999 - Dirk Farin - first implementation\n ********************************************************************************\n Copyright (C) 2002 Dirk Farin\n\n This program is distributed under GNU Public License (GPL) as\n outlined in the COPYING file that comes with the source distribution.\n\n This program is free software; you can redistribute it and\/or modify\n it under the terms of the GNU General Public License as published by\n the Free Software Foundation; either version 2 of the License, or\n (at your option) any later version.\n\n This program is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n GNU General Public License for more details.\n\n You should have received a copy of the GNU General Public License\n along with this program; if not, write to the Free Software\n Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n ********************************************************************************\/\n\n\n#ifndef LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH\n#define LIBVIDEOGFX_GRAPHICS_BASIC_IMAGE_HH\n\n#include \n\n#include \n#include \n#include \n\n\nenum Colorspace\n {\n Colorspace_RGB, Colorspace_YUV, Colorspace_Greyscale, Colorspace_HSV,\n Colorspace_Invalid\n };\n\nenum ChromaFormat {\n \/** Subsampling h:2 v:2 *\/ Chroma_420,\n \/** Subsampling h:2 v:1 *\/ Chroma_422,\n \/** No subsampling *\/ Chroma_444,\n Chroma_Invalid\n};\n\nenum BitmapChannel { Bitmap_Red = 0, Bitmap_Green = 1, Bitmap_Blue = 2,\n\t\t Bitmap_Y = 0, Bitmap_Cb = 1, Bitmap_Cr = 2,\n \t\t Bitmap_U = 1, Bitmap_V = 2,\n\t\t Bitmap_Hue = 0, Bitmap_Saturation = 1, Bitmap_Value = 2,\n\t\t Bitmap_Alpha=3\n};\n\n\n\/** Check if chroma is horizontally subsampled. Usage of the more general #ChromaSubH()# is recommended. *\/\ninline bool IsSubH(ChromaFormat cf) { return cf != Chroma_444; }\n\/** Check if chroma is vertically subsampled. Usage of the more general #ChromaSubV()# is recommended. *\/\ninline bool IsSubV(ChromaFormat cf) { return cf == Chroma_420; }\n\/** Get horizontal subsampling factor. *\/\ninline int ChromaSubH(ChromaFormat cf) { return (cf != Chroma_444) ? 2 : 1; }\n\/** Get vertical subsampling factor. *\/\ninline int ChromaSubV(ChromaFormat cf) { return (cf == Chroma_420) ? 2 : 1; }\n\n\nstruct ImageParam\n{\n ImageParam() : width(0), height(0), halign(1), valign(1), border(0),\n\t\t colorspace(Colorspace_Invalid), has_alpha(false),\n\t\t chroma(Chroma_444), reduced_chroma_resolution(true),\n\t\t chroma_border(-1), chroma_halign(-1), chroma_valign(-1)\n { }\n\n int width,height;\n int halign,valign;\n int border;\n\n Colorspace colorspace;\n bool has_alpha;\n\n ChromaFormat chroma;\n bool reduced_chroma_resolution;\n int chroma_border;\n int chroma_halign;\n int chroma_valign;\n\n#if 0\n \/** If set to #true#: don't allow the alignment or the border to be greater than specified.\n {\\bf Explanation}: As it is more efficient to keep and older bitmap if the new one\n is smaller than the old one, the old one is sometimes used instead of creating\n a new one. This does not work if you are depending on the exact memory layout of\n the image. So you can disable it by setting exact\\_size to true. *\/\n bool exact_size;\n#endif\n\n int AskChromaWidth() const\n {\n if (colorspace==Colorspace_YUV)\n return (width +ChromaSubH(chroma)-1)\/ChromaSubH(chroma);\n else\n return width;\n }\n int AskChromaHeight() const\n {\n if (colorspace==Colorspace_YUV)\n return (height+ChromaSubV(chroma)-1)\/ChromaSubV(chroma);\n else\n return height;\n }\n void AskChromaSizes(int& w,int &h) const;\n int AskChromaBorder() const;\n int AskChromaHAlign() const;\n int AskChromaVAlign() const;\n\n int BitmapWidth (BitmapChannel b) const { if (b==1||b==2) return AskChromaWidth(); else return width; }\n int BitmapHeight(BitmapChannel b) const { if (b==1||b==2) return AskChromaHeight(); else return height; }\n int ChromaScaleH(BitmapChannel b,int x) const\n { if ((b==1||b==2) && colorspace==Colorspace_YUV) return x\/ChromaSubH(chroma); else return x; }\n int ChromaScaleV(BitmapChannel b,int y) const\n { if ((b==1||b==2) && colorspace==Colorspace_YUV) return y\/ChromaSubV(chroma); else return y; }\n};\n\n\n\n\ntemplate class Image\n{\npublic:\n virtual ~Image() { }\n\n void Create(const ImageParam&);\n void Release();\n\n \/\/\/ Get colorspace independent image parameters.\n ImageParam AskParam() const { return d_param; }\n int AskWidth() const { return d_param.width; }\n int AskHeight() const { return d_param.height; }\n int AskBorder() const { return d_param.border; }\n void GetSize(int& w,int& h) const { w=d_param.width; h=d_param.height; }\n\n\n Bitmap& AskBitmap(BitmapChannel pm_id) { return d_pm[pm_id]; }\n const Bitmap& AskBitmap(BitmapChannel pm_id) const { return d_pm[pm_id]; }\n\n Pel*const* AskFrame(BitmapChannel pm_id) { return d_pm[pm_id].AskFrame(); }\n const Pel*const* AskFrame(BitmapChannel pm_id) const { return d_pm[pm_id].AskFrame(); }\n\n\n \/** Replace a complete bitmap. Note that the new bitmap either has to be empty or has to\n be exactly the same size as the old one.\n Furthermore you are responsible that all alignments and the border size is sufficient\n for your application. This is not checked!\n \n If you insert or remove (by replacing a bitmap by an empty one) an alpha bitmap,\n the alphamask-flag in ImageParam will be set accordingly.\n *\/\n void ReplaceBitmap(BitmapChannel id,const Bitmap&);\n \/\/\/ Set new image parameters.\n void SetParam(const ImageParam& param) { d_param=param; }\n\n Image Clone() const;\n\n Image CreateSubView (int x0,int y0,int w,int h) const;\n Image CreateFieldView(bool top) const;\n\n bool IsEmpty() const { return d_pm[0].IsEmpty(); }\n\n Pel*const* AskFrameR() { return d_pm[Bitmap_Red].AskFrame(); }\n const Pel*const* AskFrameR() const { return d_pm[Bitmap_Red].AskFrame(); }\n Pel*const* AskFrameG() { return d_pm[Bitmap_Green].AskFrame(); }\n const Pel*const* AskFrameG() const { return d_pm[Bitmap_Green].AskFrame(); }\n Pel*const* AskFrameB() { return d_pm[Bitmap_Blue].AskFrame(); }\n const Pel*const* AskFrameB() const { return d_pm[Bitmap_Blue].AskFrame(); }\n Pel*const* AskFrameY() { return d_pm[Bitmap_Y].AskFrame(); }\n const Pel*const* AskFrameY() const { return d_pm[Bitmap_Y].AskFrame(); }\n Pel*const* AskFrameU() { return d_pm[Bitmap_U].AskFrame(); }\n const Pel*const* AskFrameU() const { return d_pm[Bitmap_U].AskFrame(); }\n Pel*const* AskFrameV() { return d_pm[Bitmap_V].AskFrame(); }\n const Pel*const* AskFrameV() const { return d_pm[Bitmap_V].AskFrame(); }\n Pel*const* AskFrameCb() { return d_pm[Bitmap_Cb].AskFrame(); }\n const Pel*const* AskFrameCb() const { return d_pm[Bitmap_Cb].AskFrame(); }\n Pel*const* AskFrameCr() { return d_pm[Bitmap_Cr].AskFrame(); }\n const Pel*const* AskFrameCr() const { return d_pm[Bitmap_Cr].AskFrame(); }\n Pel*const* AskFrameA() { return d_pm[Bitmap_Alpha].AskFrame(); }\n const Pel*const* AskFrameA() const { return d_pm[Bitmap_Alpha].AskFrame(); }\n\n Bitmap& AskBitmapR() { return d_pm[Bitmap_Red]; }\n const Bitmap& AskBitmapR() const { return d_pm[Bitmap_Red]; }\n Bitmap& AskBitmapG() { return d_pm[Bitmap_Green]; }\n const Bitmap& AskBitmapG() const { return d_pm[Bitmap_Green]; }\n Bitmap& AskBitmapB() { return d_pm[Bitmap_Blue]; }\n const Bitmap& AskBitmapB() const { return d_pm[Bitmap_Blue]; }\n Bitmap& AskBitmapY() { return d_pm[Bitmap_Y]; }\n const Bitmap& AskBitmapY() const { return d_pm[Bitmap_Y]; }\n Bitmap& AskBitmapU() { return d_pm[Bitmap_U]; }\n const Bitmap& AskBitmapU() const { return d_pm[Bitmap_U]; }\n Bitmap& AskBitmapV() { return d_pm[Bitmap_V]; }\n const Bitmap& AskBitmapV() const { return d_pm[Bitmap_V]; }\n Bitmap& AskBitmapCb() { return d_pm[Bitmap_Cb]; }\n const Bitmap& AskBitmapCb() const { return d_pm[Bitmap_Cb]; }\n Bitmap& AskBitmapCr() { return d_pm[Bitmap_Cr]; }\n const Bitmap& AskBitmapCr() const { return d_pm[Bitmap_Cr]; }\n Bitmap& AskBitmapA() { return d_pm[Bitmap_Alpha]; }\n const Bitmap& AskBitmapA() const { return d_pm[Bitmap_Alpha]; }\n\n bool IsShared() const\n {\n for (int i=0;i<4;i++)\n if (d_pm[i].IsShared())\n\treturn true;\n\n return false;\n }\n\nprivate:\n Bitmap d_pm[4];\n ImageParam d_param;\n};\n\n\n\ntemplate void Image::Create(const ImageParam& param)\n{\n d_pm[0].Create(param.width, param.height, param.border,param.halign,param.valign);\n\n switch (param.colorspace)\n {\n case Colorspace_RGB:\n case Colorspace_HSV:\n d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);\n d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);\n break;\n\n case Colorspace_YUV:\n if (param.reduced_chroma_resolution)\n\t{\n\t d_pm[1].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),\n\t\t\t param.AskChromaHAlign(),param.AskChromaVAlign());\n\t d_pm[2].Create(param.AskChromaWidth(), param.AskChromaHeight(), param.AskChromaBorder(),\n\t\t\t param.AskChromaHAlign(),param.AskChromaVAlign());\n\t}\n else\n\t{\n\t d_pm[1].Create(param.width, param.height, param.border,param.halign,param.valign);\n\t d_pm[2].Create(param.width, param.height, param.border,param.halign,param.valign);\n\t}\n break;\n\n case Colorspace_Greyscale:\n d_pm[1].Release();\n d_pm[2].Release();\n break;\n }\n\n if (param.has_alpha)\n d_pm[Bitmap_Alpha].Create(param.width, param.height, param.border,param.halign,param.valign);\n else\n d_pm[Bitmap_Alpha].Release();\n\n d_param = param;\n}\n\n\ntemplate void Image::Release()\n{\n for (int i=0;i<4;i++)\n d_pm[i].Release();\n\n d_param = ImageParam();\n}\n\n\ntemplate Image Image::Clone() const\n{\n Image img;\n for (int i=0;i<4;i++)\n img.d_pm[i] = d_pm[i].Clone();\n\n img.d_param = d_param;\n\n return img;\n}\n\ntemplate Image Image::CreateSubView(int x0,int y0,int w,int h) const\n{\n Image newimg;\n newimg.d_param = d_param;\n\n newimg.d_param.width = w;\n newimg.d_param.height = h;\n newimg.d_param.halign = 1;\n newimg.d_param.valign = 1;\n newimg.d_param.border = 0;\n newimg.d_param.chroma_border = -1;\n newimg.d_param.chroma_halign = -1;\n newimg.d_param.chroma_valign = -1;\n\n if (d_param.colorspace == Colorspace_YUV)\n {\n newimg.d_pm[0] = d_pm[0].CreateSubView(x0,y0,w,h);\n newimg.d_pm[3] = d_pm[3].CreateSubView(x0,y0,w,h);\n\n int subh = ChromaSubH(d_param.chroma);\n int subv = ChromaSubV(d_param.chroma);\n\n newimg.d_pm[1] = d_pm[1].CreateSubView(x0\/subh,y0\/subv,(w+subh-1)\/subh,(h+subv-1)\/subv);\n newimg.d_pm[2] = d_pm[2].CreateSubView(x0\/subh,y0\/subv,(w+subh-1)\/subh,(h+subv-1)\/subv);\n }\n else\n {\n for (int i=0;i<4;i++)\n\tnewimg.d_pm[i] = d_pm[i].CreateSubView(x0,y0,w,h);\n }\n\n return newimg;\n}\n\ntemplate Image Image::CreateFieldView(bool top) const\n{\n if (!top && d_param.colorspace==Colorspace_YUV && d_param.chroma==Chroma_420 &&\n (d_pm[0].AskHeight()%2)==0 && (d_pm[1].AskHeight()%2)==1)\n {\n AssertDescr(false,\"not enough chroma information for bottom field\");\n }\n\n Image newimg;\n newimg.d_param = d_param;\n\n for (int i=0;i<4;i++)\n newimg.d_pm[i] = d_pm[i].CreateFieldView(top);\n\n newimg.d_param.width = newimg.d_pm[0].AskWidth();\n newimg.d_param.height = newimg.d_pm[0].AskHeight();\n newimg.d_param.halign = 1;\n newimg.d_param.valign = 1;\n newimg.d_param.border = 0;\n newimg.d_param.chroma_border = -1;\n newimg.d_param.chroma_halign = -1;\n newimg.d_param.chroma_valign = -1;\n\n return newimg;\n}\n\n#endif\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n\n#include \"test\/opt\/pass_fixture.h\"\n#include \"test\/opt\/pass_utils.h\"\n\nnamespace spvtools {\nnamespace opt {\nnamespace {\n\nusing StripLineReflectInfoTest = PassTest<::testing::Test>;\n\nTEST_F(StripLineReflectInfoTest, StripHlslSemantic) {\n \/\/ This is a non-sensical example, but exercises the instructions.\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_decorate_string\"\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpDecorateStringGOOGLE %float HlslSemanticGOOGLE \"foobar\"\nOpDecorateStringGOOGLE %void HlslSemanticGOOGLE \"my goodness\"\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n\n SinglePassRunAndCheck(before, after, false);\n}\n\nTEST_F(StripLineReflectInfoTest, StripHlslCounterBuffer) {\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpDecorateId %void HlslCounterBufferGOOGLE %float\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n\n SinglePassRunAndCheck(before, after, false);\n}\n\nTEST_F(StripLineReflectInfoTest, StripHlslSemanticOnMember) {\n \/\/ This is a non-sensical example, but exercises the instructions.\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_decorate_string\"\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpMemberDecorateStringGOOGLE %struct 0 HlslSemanticGOOGLE \"foobar\"\n%float = OpTypeFloat 32\n%_struct_3 = OpTypeStruct %float\n)\";\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%float = OpTypeFloat 32\n%_struct_3 = OpTypeStruct %float\n)\";\n\n SinglePassRunAndCheck(before, after, false);\n}\n\n} \/\/ namespace\n} \/\/ namespace opt\n} \/\/ namespace spvtools\nAdd test with explicit example of stripping reflection info (#3064)\/\/ Copyright (c) 2018 Google LLC\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \"gmock\/gmock.h\"\n\n#include \"spirv-tools\/optimizer.hpp\"\n\n#include \"test\/opt\/pass_fixture.h\"\n#include \"test\/opt\/pass_utils.h\"\n\nnamespace spvtools {\nnamespace opt {\nnamespace {\n\nusing StripLineReflectInfoTest = PassTest<::testing::Test>;\n\n\/\/ This test acts as an end-to-end code example on how to strip\n\/\/ reflection info from a SPIR-V module. Use this code pattern\n\/\/ when you have compiled HLSL code with Glslang or DXC using\n\/\/ option -fhlsl_functionality1 to insert reflection information,\n\/\/ but then want to filter out the extra instructions before sending\n\/\/ it to a driver that does not implement VK_GOOGLE_hlsl_functionality1.\nTEST_F(StripLineReflectInfoTest, StripReflectEnd2EndExample) {\n \/\/ This is a non-sensical example, but exercises the instructions.\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_decorate_string\"\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpDecorateStringGOOGLE %float HlslSemanticGOOGLE \"foobar\"\nOpDecorateStringGOOGLE %void HlslSemanticGOOGLE \"my goodness\"\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n SpirvTools tools(SPV_ENV_UNIVERSAL_1_1);\n std::vector binary_in;\n tools.Assemble(before, &binary_in);\n\n \/\/ Instantiate the optimizer, and run the strip-reflection-info\n \/\/ pass over the |binary_in| module, and place the modified module\n \/\/ into |binary_out|.\n spvtools::Optimizer optimizer(SPV_ENV_UNIVERSAL_1_1);\n optimizer.RegisterPass(spvtools::CreateStripReflectInfoPass());\n std::vector binary_out;\n optimizer.Run(binary_in.data(), binary_in.size(), &binary_out);\n\n \/\/ Check results\n std::string disassembly;\n tools.Disassemble(binary_out.data(), binary_out.size(), &disassembly);\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n EXPECT_THAT(disassembly, testing::Eq(after));\n}\n\n\/\/ This test is functionally the same as the end-to-end test above,\n\/\/ but uses the test SinglePassRunAndCheck test fixture instead.\nTEST_F(StripLineReflectInfoTest, StripHlslSemantic) {\n \/\/ This is a non-sensical example, but exercises the instructions.\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_decorate_string\"\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpDecorateStringGOOGLE %float HlslSemanticGOOGLE \"foobar\"\nOpDecorateStringGOOGLE %void HlslSemanticGOOGLE \"my goodness\"\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n\n SinglePassRunAndCheck(before, after, false);\n}\n\nTEST_F(StripLineReflectInfoTest, StripHlslCounterBuffer) {\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpDecorateId %void HlslCounterBufferGOOGLE %float\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%void = OpTypeVoid\n%float = OpTypeFloat 32\n)\";\n\n SinglePassRunAndCheck(before, after, false);\n}\n\nTEST_F(StripLineReflectInfoTest, StripHlslSemanticOnMember) {\n \/\/ This is a non-sensical example, but exercises the instructions.\n std::string before = R\"(OpCapability Shader\nOpCapability Linkage\nOpExtension \"SPV_GOOGLE_decorate_string\"\nOpExtension \"SPV_GOOGLE_hlsl_functionality1\"\nOpMemoryModel Logical Simple\nOpMemberDecorateStringGOOGLE %struct 0 HlslSemanticGOOGLE \"foobar\"\n%float = OpTypeFloat 32\n%_struct_3 = OpTypeStruct %float\n)\";\n std::string after = R\"(OpCapability Shader\nOpCapability Linkage\nOpMemoryModel Logical Simple\n%float = OpTypeFloat 32\n%_struct_3 = OpTypeStruct %float\n)\";\n\n SinglePassRunAndCheck(before, after, false);\n}\n\n} \/\/ namespace\n} \/\/ namespace opt\n} \/\/ namespace spvtools\n<|endoftext|>"} {"text":"#include \n#include \n#include \"clock.h\"\n#include \n\nusing namespace Halide;\n\nenum {\n scalar_trans,\n vec_y_trans,\n vec_x_trans\n};\n\nvoid test_transpose(int mode) {\n Func input, block, block_transpose, output;\n Var x, y;\n\n input(x, y) = cast(x + y);\n input.compute_root();\n\n block(x, y) = input(x, y);\n block_transpose(x, y) = block(y, x);\n output(x, y) = block_transpose(x, y);\n\n Var xi, yi;\n output.tile(x, y, xi, yi, 8, 8).vectorize(xi).unroll(yi);\n\n \/\/ Do 8 vectorized loads from the input.\n block.compute_at(output, x).vectorize(x).unroll(y);\n\n std::string algorithm;\n switch(mode) {\n case scalar_trans:\n block_transpose.compute_at(output, x).unroll(x).unroll(y);\n algorithm = \"Scalar transpose\";\n break;\n case vec_y_trans:\n block_transpose.compute_at(output, x).vectorize(y).unroll(x);\n algorithm = \"Transpose vectorized in y\";\n break;\n case vec_x_trans:\n block_transpose.compute_at(output, x).vectorize(x).unroll(y);\n algorithm = \"Transpose vectorized in x\";\n break;\n }\n\n output.compile_to_lowered_stmt(\"fast_transpose.stmt\");\n output.compile_to_assembly(\"fast_transpose.s\", std::vector());\n\n Image result(1024, 1024);\n output.compile_jit();\n\n output.realize(result);\n\n double t1 = current_time();\n for (int i = 0; i < 10; i++) {\n output.realize(result);\n }\n double t2 = current_time();\n\n std::cout << algorithm << \" bandwidth \" << ((1024*1024 \/ (t2 - t1)) * 1000 * 10) << \" byte\/s.\\n\";\n}\n\nint main(int argc, char **argv) {\n test_transpose(scalar_trans);\n test_transpose(vec_y_trans);\n test_transpose(vec_x_trans);\n printf(\"Success!\\n\");\n return 0;\n}\nModified block_transpose performance test to ouput assembly code for each different algorithm.#include \n#include \n#include \"clock.h\"\n#include \n\nusing namespace Halide;\n\nenum {\n scalar_trans,\n vec_y_trans,\n vec_x_trans\n};\n\nvoid test_transpose(int mode) {\n Func input, block, block_transpose, output;\n Var x, y;\n\n input(x, y) = cast(x + y);\n input.compute_root();\n\n block(x, y) = input(x, y);\n block_transpose(x, y) = block(y, x);\n output(x, y) = block_transpose(x, y);\n\n Var xi, yi;\n output.tile(x, y, xi, yi, 8, 8).vectorize(xi).unroll(yi);\n\n \/\/ Do 8 vectorized loads from the input.\n block.compute_at(output, x).vectorize(x).unroll(y);\n\n std::string algorithm;\n switch(mode) {\n case scalar_trans:\n block_transpose.compute_at(output, x).unroll(x).unroll(y);\n algorithm = \"Scalar transpose\";\n output.compile_to_assembly(\"scalar_transpose.s\", std::vector());\n break;\n case vec_y_trans:\n block_transpose.compute_at(output, x).vectorize(y).unroll(x);\n algorithm = \"Transpose vectorized in y\";\n output.compile_to_assembly(\"fast_transpose_y.s\", std::vector());\n break;\n case vec_x_trans:\n block_transpose.compute_at(output, x).vectorize(x).unroll(y);\n algorithm = \"Transpose vectorized in x\";\n output.compile_to_assembly(\"fast_transpose_x.s\", std::vector());\n break;\n }\n\n\n Image result(1024, 1024);\n output.compile_jit();\n\n output.realize(result);\n\n double t1 = current_time();\n for (int i = 0; i < 10; i++) {\n output.realize(result);\n }\n double t2 = current_time();\n\n std::cout << algorithm << \" bandwidth \" << ((1024*1024 \/ (t2 - t1)) * 1000 * 10) << \" byte\/s.\\n\";\n}\n\nint main(int argc, char **argv) {\n test_transpose(scalar_trans);\n test_transpose(vec_y_trans);\n test_transpose(vec_x_trans);\n printf(\"Success!\\n\");\n return 0;\n}\n<|endoftext|>"} {"text":"#include \n#include \n\n#include \"wrapper.h\"\n\nextern \"C\"\n{\n\n\/* bitmap\/image helpers *\/\nEWXWEXPORT(wxBitmap*,wxBitmap_CreateFromImage)(wxImage* image,int depth)\n{\n return new wxBitmap(*image,depth);\n}\n\n\nEWXWEXPORT(wxImage*,wxImage_CreateFromDataEx)(int width,int height,wxUint8* data,bool isStaticData)\n{\n return new wxImage(width, height, data, isStaticData);\n}\n\n\nEWXWEXPORT(void,wxImage_Delete)(wxImage* image)\n{\n delete image;\n}\n\n\n\/* colours *\/\nEWXWEXPORT(wxColour*,wxColour_CreateFromInt)(int rgb)\n{\n return new wxColour((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);\n}\n\nEWXWEXPORT(int,wxColour_GetInt)(wxColour* colour)\n{\n int r = colour->Red();\n int g = colour->Green();\n int b = colour->Blue();\n return ((r << 16) | (g << 8) | b);\n}\n\n\/* basic pixel manipulation *\/\nEWXWEXPORT(void,wxcSetPixelRGB)(wxUint8* buffer,int width,int x,int y,int rgb)\n{\n int indexR = 3*(width*y + x);\n buffer[indexR] = rgb >> 16;\n buffer[indexR+1] = rgb >> 8;\n buffer[indexR+2] = rgb;\n}\n\nEWXWEXPORT(int,wxcGetPixelRGB)(wxUint8* buffer,int width,int x,int y)\n{\n int indexR = 3*(width*y + x);\n int r,g,b;\n r = buffer[indexR];\n g = buffer[indexR+1];\n b = buffer[indexR+2];\n return ((r << 16) | (g << 8) | b);\n}\n\nEWXWEXPORT(void,wxcSetPixelRowRGB)(wxUint8* buffer,int width,int x,int y,int rgb0,int rgb1,int count)\n{\n int r0 = ((rgb0 >> 16) && 0xFF);\n int g0 = ((rgb0 >> 8) && 0xFF);\n int b0 = (rgb0 && 0xFF);\n int start = 3*(width*y+x);\n int i;\n\n if (rgb0 == rgb1) {\n \/* same color *\/\n for( i=0; i < count*3; i +=3) {\n buffer[start+i] = r0;\n buffer[start+i+1] = g0;\n buffer[start+i+2] = b0;\n }\n }\n else {\n \/* do linear interpolation of the color *\/\n int r1 = ((rgb1 >> 16) && 0xFF);\n int g1 = ((rgb1 >> 8) && 0xFF);\n int b1 = (rgb1 && 0xFF);\n\n int rd = ((r1 - r0) << 16) \/ (count-1);\n int gd = ((g1 - g0) << 16) \/ (count-1);\n int bd = ((b1 - b0) << 16) \/ (count-1);\n\n int r = r0 << 16;\n int g = g0 << 16;\n int b = b0 << 16;\n\n for( i = 0; i < count*3; i += 3 ) {\n buffer[start+i] = (r >> 16);\n buffer[start+i+1] = (g >> 16);\n buffer[start+i+2] = (b >> 16);\n r += rd;\n g += gd;\n b += bd;\n }\n }\n}\n\nEWXWEXPORT(void,wxcInitPixelsRGB)(wxUint8* buffer,int width,int height,int rgb)\n{\n int count = width*height*3;\n wxUint8 r = ((rgb >> 16) && 0xFF);\n wxUint8 g = ((rgb >> 8) && 0xFF);\n wxUint8 b = rgb && 0xFF;\n int i;\n\n if (r==g && g==b) {\n for( i=0; i < count; i++ ) {\n buffer[i] = r;\n }\n }\n else {\n for( i=0; i < count; i += 3) {\n buffer[i] = r;\n buffer[i+1] = g;\n buffer[i+2] = b;\n }\n }\n}\n\nEWXWEXPORT(wxColour*,wxColour_CreateFromUnsignedInt)(unsigned int rgba)\n{\n return new wxColour((rgba >> 24) & 0xFF, (rgba >> 16) & 0xFF, (rgba >> 8) & 0xFF, rgba & 0xFF);\n}\n\nEWXWEXPORT(unsigned int,wxColour_GetUnsignedInt)(wxColour* colour)\n{\n int r = colour->Red();\n int g = colour->Green();\n int b = colour->Blue();\n int a = colour->Alpha();\n return ((r << 24) | (g << 16) | (b << 8) | a);\n}\n\n\/* basic pixel manipulation *\/\nEWXWEXPORT(void,wxcSetPixelRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba)\n{\n unsigned int indexR = 4*(width*y + x);\n buffer[indexR] = rgba >> 24;\n buffer[indexR+1] = rgba >> 16;\n buffer[indexR+2] = rgba >> 8;\n buffer[indexR+3] = rgba;\n}\n\nEWXWEXPORT(int,wxcGetPixelRGBA)(wxUint8* buffer,int width,int x,int y)\n{\n unsigned int indexR = 4*(width*y + x);\n int r,g,b,a;\n r = buffer[indexR];\n g = buffer[indexR+1];\n b = buffer[indexR+2];\n a = buffer[indexR+3];\n return ((r << 24) | (g << 16) | (b << 8) | a);\n}\n\nEWXWEXPORT(void,wxcSetPixelRowRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba0,unsigned int rgba1,unsigned int count)\n{\n int r0 = ((rgba0 >> 24) && 0xFF);\n int g0 = ((rgba0 >> 16) && 0xFF);\n int b0 = ((rgba0 >> 8) && 0xFF);\n int a0 = (rgba0 && 0xFF);\n unsigned int start = 4*(width*y+x);\n unsigned int i;\n\n if (rgba0 == rgba1) {\n \/* same color *\/\n for( i=0; i < count*4; i +=4) {\n buffer[start+i] = r0;\n buffer[start+i+1] = g0;\n buffer[start+i+2] = b0;\n buffer[start+i+3] = a0;\n }\n }\n else {\n \/* do linear interpolation of the color *\/\n int r1 = ((rgba1 >> 24) && 0xFF);\n int g1 = ((rgba1 >> 16) && 0xFF);\n int b1 = ((rgba1 >> 8) && 0xFF);\n int a1 = (rgba1 && 0xFF);\n\n int rd = ((r1 - r0) << 24) \/ (count-1);\n int gd = ((g1 - g0) << 24) \/ (count-1);\n int bd = ((b1 - b0) << 24) \/ (count-1);\n int ad = ((a1 - a0) << 24) \/ (count-1);\n\n int r = r0 << 24;\n int g = g0 << 24;\n int b = b0 << 24;\n int a = b0 << 24;\n\n for( i = 0; i < count*4; i += 4 ) {\n buffer[start+i] = (r >> 24);\n buffer[start+i+1] = (g >> 24);\n buffer[start+i+2] = (b >> 24);\n buffer[start+i+3] = (a >> 24);\n r += rd;\n g += gd;\n b += bd;\n a += ad;\n }\n }\n}\n\nEWXWEXPORT(void,wxcInitPixelsRGBA)(wxUint8* buffer,int width,int height,int rgba)\n{\n unsigned int count = width*height*4;\n wxUint8 r = ((rgba >> 24) && 0xFF);\n wxUint8 g = ((rgba >> 16) && 0xFF);\n wxUint8 b = ((rgba >> 8) && 0xFF);\n wxUint8 a = rgba && 0xFF;\n unsigned int i;\n\n if (r==g && g==b && b==a) {\n for( i=0; i < count; i++ ) {\n buffer[i] = r;\n }\n }\n else {\n for( i=0; i < count; i += 4) {\n buffer[i] = r;\n buffer[i+1] = g;\n buffer[i+2] = b;\n buffer[i+3] = a;\n }\n }\n}\n\n}\nReplaced '&&' with '&' several times in wxc\/src\/cpp\/image.cpp#include \n#include \n\n#include \"wrapper.h\"\n\nextern \"C\"\n{\n\n\/* bitmap\/image helpers *\/\nEWXWEXPORT(wxBitmap*,wxBitmap_CreateFromImage)(wxImage* image,int depth)\n{\n return new wxBitmap(*image,depth);\n}\n\n\nEWXWEXPORT(wxImage*,wxImage_CreateFromDataEx)(int width,int height,wxUint8* data,bool isStaticData)\n{\n return new wxImage(width, height, data, isStaticData);\n}\n\n\nEWXWEXPORT(void,wxImage_Delete)(wxImage* image)\n{\n delete image;\n}\n\n\n\/* colours *\/\nEWXWEXPORT(wxColour*,wxColour_CreateFromInt)(int rgb)\n{\n return new wxColour((rgb >> 16) & 0xFF, (rgb >> 8) & 0xFF, rgb & 0xFF);\n}\n\nEWXWEXPORT(int,wxColour_GetInt)(wxColour* colour)\n{\n int r = colour->Red();\n int g = colour->Green();\n int b = colour->Blue();\n return ((r << 16) | (g << 8) | b);\n}\n\n\/* basic pixel manipulation *\/\nEWXWEXPORT(void,wxcSetPixelRGB)(wxUint8* buffer,int width,int x,int y,int rgb)\n{\n int indexR = 3*(width*y + x);\n buffer[indexR] = rgb >> 16;\n buffer[indexR+1] = rgb >> 8;\n buffer[indexR+2] = rgb;\n}\n\nEWXWEXPORT(int,wxcGetPixelRGB)(wxUint8* buffer,int width,int x,int y)\n{\n int indexR = 3*(width*y + x);\n int r,g,b;\n r = buffer[indexR];\n g = buffer[indexR+1];\n b = buffer[indexR+2];\n return ((r << 16) | (g << 8) | b);\n}\n\nEWXWEXPORT(void,wxcSetPixelRowRGB)(wxUint8* buffer,int width,int x,int y,int rgb0,int rgb1,int count)\n{\n int r0 = ((rgb0 >> 16) & 0xFF);\n int g0 = ((rgb0 >> 8) & 0xFF);\n int b0 = (rgb0 & 0xFF);\n int start = 3*(width*y+x);\n int i;\n\n if (rgb0 == rgb1) {\n \/* same color *\/\n for( i=0; i < count*3; i +=3) {\n buffer[start+i] = r0;\n buffer[start+i+1] = g0;\n buffer[start+i+2] = b0;\n }\n }\n else {\n \/* do linear interpolation of the color *\/\n int r1 = ((rgb1 >> 16) & 0xFF);\n int g1 = ((rgb1 >> 8) & 0xFF);\n int b1 = (rgb1 & 0xFF);\n\n int rd = ((r1 - r0) << 16) \/ (count-1);\n int gd = ((g1 - g0) << 16) \/ (count-1);\n int bd = ((b1 - b0) << 16) \/ (count-1);\n\n int r = r0 << 16;\n int g = g0 << 16;\n int b = b0 << 16;\n\n for( i = 0; i < count*3; i += 3 ) {\n buffer[start+i] = (r >> 16);\n buffer[start+i+1] = (g >> 16);\n buffer[start+i+2] = (b >> 16);\n r += rd;\n g += gd;\n b += bd;\n }\n }\n}\n\nEWXWEXPORT(void,wxcInitPixelsRGB)(wxUint8* buffer,int width,int height,int rgb)\n{\n int count = width*height*3;\n wxUint8 r = ((rgb >> 16) & 0xFF);\n wxUint8 g = ((rgb >> 8) & 0xFF);\n wxUint8 b = rgb & 0xFF;\n int i;\n\n if (r==g && g==b) {\n for( i=0; i < count; i++ ) {\n buffer[i] = r;\n }\n }\n else {\n for( i=0; i < count; i += 3) {\n buffer[i] = r;\n buffer[i+1] = g;\n buffer[i+2] = b;\n }\n }\n}\n\nEWXWEXPORT(wxColour*,wxColour_CreateFromUnsignedInt)(unsigned int rgba)\n{\n return new wxColour((rgba >> 24) & 0xFF, (rgba >> 16) & 0xFF, (rgba >> 8) & 0xFF, rgba & 0xFF);\n}\n\nEWXWEXPORT(unsigned int,wxColour_GetUnsignedInt)(wxColour* colour)\n{\n int r = colour->Red();\n int g = colour->Green();\n int b = colour->Blue();\n int a = colour->Alpha();\n return ((r << 24) | (g << 16) | (b << 8) | a);\n}\n\n\/* basic pixel manipulation *\/\nEWXWEXPORT(void,wxcSetPixelRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba)\n{\n unsigned int indexR = 4*(width*y + x);\n buffer[indexR] = rgba >> 24;\n buffer[indexR+1] = rgba >> 16;\n buffer[indexR+2] = rgba >> 8;\n buffer[indexR+3] = rgba;\n}\n\nEWXWEXPORT(int,wxcGetPixelRGBA)(wxUint8* buffer,int width,int x,int y)\n{\n unsigned int indexR = 4*(width*y + x);\n int r,g,b,a;\n r = buffer[indexR];\n g = buffer[indexR+1];\n b = buffer[indexR+2];\n a = buffer[indexR+3];\n return ((r << 24) | (g << 16) | (b << 8) | a);\n}\n\nEWXWEXPORT(void,wxcSetPixelRowRGBA)(wxUint8* buffer,int width,int x,int y,unsigned int rgba0,unsigned int rgba1,unsigned int count)\n{\n int r0 = ((rgba0 >> 24) & 0xFF);\n int g0 = ((rgba0 >> 16) & 0xFF);\n int b0 = ((rgba0 >> 8) & 0xFF);\n int a0 = (rgba0 & 0xFF);\n unsigned int start = 4*(width*y+x);\n unsigned int i;\n\n if (rgba0 == rgba1) {\n \/* same color *\/\n for( i=0; i < count*4; i +=4) {\n buffer[start+i] = r0;\n buffer[start+i+1] = g0;\n buffer[start+i+2] = b0;\n buffer[start+i+3] = a0;\n }\n }\n else {\n \/* do linear interpolation of the color *\/\n int r1 = ((rgba1 >> 24) & 0xFF);\n int g1 = ((rgba1 >> 16) & 0xFF);\n int b1 = ((rgba1 >> 8) & 0xFF);\n int a1 = (rgba1 & 0xFF);\n\n int rd = ((r1 - r0) << 24) \/ (count-1);\n int gd = ((g1 - g0) << 24) \/ (count-1);\n int bd = ((b1 - b0) << 24) \/ (count-1);\n int ad = ((a1 - a0) << 24) \/ (count-1);\n\n int r = r0 << 24;\n int g = g0 << 24;\n int b = b0 << 24;\n int a = b0 << 24;\n\n for( i = 0; i < count*4; i += 4 ) {\n buffer[start+i] = (r >> 24);\n buffer[start+i+1] = (g >> 24);\n buffer[start+i+2] = (b >> 24);\n buffer[start+i+3] = (a >> 24);\n r += rd;\n g += gd;\n b += bd;\n a += ad;\n }\n }\n}\n\nEWXWEXPORT(void,wxcInitPixelsRGBA)(wxUint8* buffer,int width,int height,int rgba)\n{\n unsigned int count = width*height*4;\n wxUint8 r = ((rgba >> 24) & 0xFF);\n wxUint8 g = ((rgba >> 16) & 0xFF);\n wxUint8 b = ((rgba >> 8) & 0xFF);\n wxUint8 a = rgba & 0xFF;\n unsigned int i;\n\n if (r==g && g==b && b==a) {\n for( i=0; i < count; i++ ) {\n buffer[i] = r;\n }\n }\n else {\n for( i=0; i < count; i += 4) {\n buffer[i] = r;\n buffer[i+1] = g;\n buffer[i+2] = b;\n buffer[i+3] = a;\n }\n }\n}\n\n}\n<|endoftext|>"} {"text":"#ifndef __ENVIRE_MAPS_LOCAL_MAP_HPP__\n#define __ENVIRE_MAPS_LOCAL_MAP_HPP__\n\n#include \n\n#include \n\n#include \n\nnamespace envire { namespace maps\n{\n \/**@brief LocalMapType\n * The type of the LocalMap\n *\/\n\n \/\/ TODO: do we need unknown type?\n enum LocalMapType\n {\n GRID_MAP = 0,\n GEOMETRIC_MAP = 1,\n MLS_MAP = 2,\n TOPOLOGICAL_MAP = 3\n };\n\n struct LocalMapData\n {\n \/\/ TODO: which map_type should be set by default\n LocalMapData()\n : offset(base::Transform3d::Identity()) {};\n\n \/** string id of this local map **\/\n std::string id;\n\n \/** Offset within the grid. The description of the local map frame.\n * It will be the offset with respect\n * to the bottom left corner (origin) of the map.\n * For the time being we use 3D transformation.\n * \n * \n **\/\n base::Transform3d offset;\n\n \/** map_type of this local map **\/\n LocalMapType map_type;\n\n \/** EPSG_code that provides the geo-localized coordinate system **\/\n std::string EPSG_code;\n\n \/** The EPSG code depends in the coordinate system used for the\n * local map \"NONE\" in case of not geo-referenced map.\n * Example: \"EPSG::4978\" for the World Geodetic System 1984 (WGS-84)\n * Example: \"EPSG::3199\" Spain - Canary Islands onshore and offshore.\n * with bounds are [-21.93W, -11.75E] and [24.6S, 11.75N] using the\n * World Geodetic System 1984 (WGS-84) coordinate reference system\n * (CRS).\n * Example: \"EPSG::5243\" ETRS89 \/ LCC Germany (E-N) Bremen area with\n * WGS084 CRS\n * Reference: https:\/\/www.epsg-registry.org **\/\n };\n\n \/**@brief LocalMap\n * Local map with respect to a given reference frame\n * A local map is the basic element to form a global\n * map (set of local maps structured in a tree).\n *\/\n class LocalMap\n {\n public:\n typedef boost::shared_ptr Ptr;\n\n LocalMap()\n : data_ptr(new LocalMapData())\n { \n }\n\n \/**\n * @brief [brief description]\n * @details to share same content (LocalMapData) between various instance of LocalMap\n * \n * @param data [description]\n *\/\n LocalMap(const boost::shared_ptr &data)\n : data_ptr(data)\n {\n }\n\n \/**\n * @brief make copy without sharing the content\n * @details the copy instance owns a new content (LocalMapData)\n * \n * @param other [description]\n *\/\n LocalMap(const LocalMap& other)\n : data_ptr(new LocalMapData(*(other.data_ptr.get())))\n {\n }\n\n virtual ~LocalMap() {};\n\n const std::string& getId() const\n {\n return data_ptr->id;\n }\n\n std::string& getId() \n {\n return data_ptr->id;\n } \n\n const base::Transform3d& getOffset() const\n {\n return data_ptr->offset;\n }\n\n base::Transform3d& getOffset()\n {\n return data_ptr->offset;\n }\n\n const boost::shared_ptr& getLocalMap() const\n {\n return data_ptr;\n }\n\n protected:\n boost::shared_ptr data_ptr;\n };\n}}\n#endif \/\/ __ENVIRE_MAPS_LOCAL_MAP_HPP__\nsrc: default LocalMap information and constructor#ifndef __ENVIRE_MAPS_LOCAL_MAP_HPP__\n#define __ENVIRE_MAPS_LOCAL_MAP_HPP__\n\n#include \n\n#include \n\n#include \n\nnamespace envire { namespace maps\n{\n \/**@brief LocalMapType\n * The type of the LocalMap\n *\/\n\n enum LocalMapType\n {\n GRID_MAP = 0,\n GEOMETRIC_MAP = 1,\n MLS_MAP = 2,\n TOPOLOGICAL_MAP = 3\n };\n\n const std::string DEFAULT_GRID_MAP_ID = \"DEFAULT_GRID_MAP\";\n const std::string DEFAULT_EPSG_CODE = \"NONE\";\n\n struct LocalMapData\n {\n \/** Grid map is the map by default **\/\n LocalMapData()\n :id(DEFAULT_GRID_MAP_ID),\n offset(base::Transform3d::Identity()),\n map_type(GRID_MAP),\n EPSG_code(DEFAULT_EPSG_CODE){};\n\n LocalMapData(const std::string _id, const base::Transform3d &_offset,\n const LocalMapType _map_type, const std::string _EPSG_code)\n :id(_id), offset(_offset), map_type(_map_type), EPSG_code(_EPSG_code) {};\n\n \/** string id of this local map **\/\n std::string id;\n\n \/** Offset within the grid. The description of the local map frame.\n * It will be the offset with respect\n * to the bottom left corner (origin) of the map.\n * For the time being we use 3D transformation.\n * \n * \n **\/\n base::Transform3d offset;\n\n \/** map_type of this local map **\/\n LocalMapType map_type;\n\n \/** EPSG_code that provides the geo-localized coordinate system **\/\n std::string EPSG_code;\n\n \/** The EPSG code depends in the coordinate system used for the\n * local map \"NONE\" in case of not geo-referenced map.\n * Example: \"EPSG::4978\" for the World Geodetic System 1984 (WGS-84)\n * Example: \"EPSG::3199\" Spain - Canary Islands onshore and offshore.\n * with bounds are [-21.93W, -11.75E] and [24.6S, 11.75N] using the\n * World Geodetic System 1984 (WGS-84) coordinate reference system\n * (CRS).\n * Example: \"EPSG::5243\" ETRS89 \/ LCC Germany (E-N) Bremen area with\n * WGS084 CRS\n * Reference: https:\/\/www.epsg-registry.org **\/\n };\n\n \/**@brief LocalMap\n * Local map with respect to a given reference frame\n * A local map is the basic element to form a global\n * map (set of local maps structured in a tree).\n *\/\n class LocalMap\n {\n public:\n typedef boost::shared_ptr Ptr;\n\n LocalMap()\n : data_ptr(new LocalMapData())\n { \n }\n\n \/**\n * @brief [brief description]\n * @details to share same content (LocalMapData) between various instance of LocalMap\n * \n * @param data [description]\n *\/\n LocalMap(const boost::shared_ptr &data)\n : data_ptr(data)\n {\n }\n\n \/**\n * @brief make copy without sharing the content\n * @details the copy instance owns a new content (LocalMapData)\n * \n * @param other [description]\n *\/\n LocalMap(const LocalMap& other)\n : data_ptr(new LocalMapData(*(other.data_ptr.get())))\n {\n }\n\n virtual ~LocalMap() {};\n\n const std::string& getId() const\n {\n return data_ptr->id;\n }\n\n std::string& getId() \n {\n return data_ptr->id;\n } \n\n const base::Transform3d& getOffset() const\n {\n return data_ptr->offset;\n }\n\n base::Transform3d& getOffset()\n {\n return data_ptr->offset;\n }\n\n const boost::shared_ptr& getLocalMap() const\n {\n return data_ptr;\n }\n\n protected:\n boost::shared_ptr data_ptr;\n };\n}}\n#endif \/\/ __ENVIRE_MAPS_LOCAL_MAP_HPP__\n<|endoftext|>"} {"text":"#include \"LuaTable.h\"\n#include \"LuaObjectImpl.h\"\n\n\nLuaTable::LuaTable(LuaState* L)\n\t:LuaObject(L)\n{\n\t\n}\n\nLuaTable::LuaTable(LuaObjectImpl* impl)\n\t:LuaObject(impl)\n{\n\t\n}\n\nLuaTable::LuaTable(const LuaObject& rfs)\n\t:LuaObject(rfs)\n{\n}\n\nLuaTable::LuaTable(const LuaTable& rfs)\n\t:LuaObject(rfs)\n{\n}\n\n\nbool LuaTable::isValid()\n{\n\treturn getType()==LUA_TTABLE;\n}\n\nLuaObject LuaTable::getTable(const char* key)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key);\n}\n\nLuaObject LuaTable::getTable(lua_Integer key)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key);\n}\n\nLuaObject LuaTable::operator[](const char* key)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key);\n}\n\nLuaObject LuaTable::operator[](lua_Integer idx)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,idx);\n}\n\nbool LuaTable::setTable(const char* key,LuaObject val)\n{\n\tif(isValid())\n\t{\n\t\tlua_State* L=m_ptr->getLuaState();\n\t\tlua_pushstring(L,key);\/\/key\n\t\tlua_pushvalue(L,val.getIndex());\/\/value\n\t\tlua_settable(L,getIndex());\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool LuaTable::setTable(lua_Integer key,LuaObject val)\n{\n\tif(isValid())\n\t{\n\t\tlua_State* L=m_ptr->getLuaState();\n\t\tlua_pushinteger(L,key);\/\/key\n\t\tlua_pushvalue(L,val.getIndex());\/\/value\n\t\tlua_settable(L,getIndex());\n\t\treturn true;\n\t}\n\treturn false;\n}fixbug#include \"LuaTable.h\"\n#include \"LuaObjectImpl.h\"\n\n\nLuaTable::LuaTable(LuaState* L)\n\t:LuaObject(L)\n{\n\t\n}\n\nLuaTable::LuaTable(LuaObjectImpl* impl)\n\t:LuaObject(impl)\n{\n\t\n}\n\nLuaTable::LuaTable(const LuaObject& rfs)\n\t:LuaObject(rfs)\n{\n}\n\nLuaTable::LuaTable(const LuaTable& rfs)\n\t:LuaObject(rfs)\n{\n}\n\n\nbool LuaTable::isValid()\n{\n\treturn getType()==LUA_TTABLE;\n}\n\nLuaObject LuaTable::getTable(const char* key)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key);\n}\n\nLuaObject LuaTable::getTable(lua_Integer key)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key);\n}\n\nLuaObject LuaTable::operator[](const char* key)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,key);\n}\n\nLuaObject LuaTable::operator[](lua_Integer idx)\n{\n\tassert(isValid());\n\treturn LuaObjectImpl::createGetTable(m_ptr->getCppLuaState(),m_ptr,idx);\n}\n\nbool LuaTable::setTable(const char* key,LuaObject val)\n{\n\tif(isValid())\n\t{\n\t\tlua_State* L=m_ptr->getLuaState();\n\t\tlua_pushstring(L,key);\/\/key\n\t\tif(val.isNone())\n\t\t\tlua_pushnil(L);\n\t\telse\n\t\t\tlua_pushvalue(L,val.getIndex());\/\/value\n\t\tlua_settable(L,getIndex());\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nbool LuaTable::setTable(lua_Integer key,LuaObject val)\n{\n\tif(isValid())\n\t{\n\t\tlua_State* L=m_ptr->getLuaState();\n\t\tlua_pushinteger(L,key);\/\/key\n\t\tif(val.isNone())\n\t\t\tlua_pushnil(L);\n\t\telse\n\t\t\tlua_pushvalue(L,val.getIndex());\/\/value\n\t\tlua_settable(L,getIndex());\n\t\treturn true;\n\t}\n\treturn false;\n}<|endoftext|>"} {"text":"\/\/ 'operator delete' redeclared without throw()\n\n\/\/ originally found in package drscheme_1:208-1\n\n\/\/ %%% progress: 0ms: done type checking (1 ms)\n\/\/ a.ii:3:6: error: prior declaration of `operator delete' at :1:1 had type `void ()(void *p) throw()', but this one uses `void ()(void *\/*anon*\/)'\n\/\/ typechecking results:\n\/\/ errors: 1\n\/\/ warnings: 0\n\nvoid operator delete(void *) {\n}\n(Comment)\/\/ 'operator delete' redeclared without throw()\n\n\/\/ originally found in package drscheme_1:208-1\n\n\/\/ a.ii:3:6: error: prior declaration of `operator delete' at :1:1 had\n\/\/ type `void ()(void *p) throw()', but this one uses `void ()(void\n\/\/ *\/*anon*\/)'\n\nvoid operator delete(void *) {\n}\n<|endoftext|>"} {"text":"\/*! \\file MatTools.cpp\n \\brief Implements the MatTools class used by the Generic Repository \n \\author Kathryn D. Huff\n *\/\n#include \n#include \n#include \n#include \n#include \n\n\n#include \"CycException.h\"\n#include \"CycLimits.h\"\n#include \"MatTools.h\"\n#include \"Material.h\"\n#include \"Logger.h\"\n#include \"Timer.h\"\n\nusing namespace std;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair MatTools::sum_mats(deque mats){\n IsoVector vec;\n CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));\n double tot = 0;\n double kg = 0;\n\n if( !mats.empty() ){ \n CompMapPtr comp_to_add;\n deque::iterator mat;\n int iso;\n CompMap::const_iterator comp;\n\n for(mat = mats.begin(); mat != mats.end(); ++mat){ \n kg = (*mat)->mass(MassUnit(KG));\n tot += kg;\n comp_to_add = (*mat)->isoVector().comp();\n comp_to_add->massify();\n for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {\n iso = comp->first;\n if(sum_comp->count(iso)!=0) {\n (*sum_comp)[iso] += (comp->second)*kg;\n } else { \n (*sum_comp)[iso] = (comp->second)*kg;\n }\n }\n }\n } else {\n (*sum_comp)[92235] = 0;\n }\n vec = IsoVector(sum_comp);\n return make_pair(vec, tot);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nmat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque& mat_list){\n comp_to_rem->normalize();\n mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));\n left_over->setQuantity(0);\n while(!mat_list.empty()) { \n left_over->absorb(mat_list.back());\n mat_list.pop_back();\n }\n mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem);\n if(left_over->mass(KG) > cyclus::eps_rsrc()){ \n mat_list.push_back(left_over);\n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){\n MatTools::validate_finite_pos(vol);\n MatTools::validate_finite_pos(mass);\n\n IsoConcMap to_ret;\n if( vol==0 ) {\n to_ret = zeroConcMap();\n } else {\n int iso;\n double m_iso;\n CompMap::const_iterator it;\n it=(*comp).begin();\n while(it!= (*comp).end() ){\n iso = (*it).first;\n m_iso=((*it).second)*mass;\n to_ret.insert(make_pair(iso, m_iso\/vol));\n ++it;\n } \n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::zeroConcMap(){\n IsoConcMap to_ret;\n to_ret[92235] = 0;\n return to_ret;\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair MatTools::conc_to_comp_map(IsoConcMap conc, double vol){\n MatTools::validate_finite_pos(vol);\n\n CompMapPtr comp = CompMapPtr(new CompMap(MASS));\n double mass(0);\n int iso;\n double c_iso;\n double m_iso;\n CompMap::const_iterator it;\n it=conc.begin();\n while(it!= conc.end() ){\n iso = (*it).first;\n c_iso=((*it).second);\n m_iso = c_iso*vol;\n (*comp)[iso] = m_iso;\n mass+=m_iso;\n ++it;\n } \n (*comp).normalize();\n pair to_ret = make_pair(CompMapPtr(comp), mass);\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_f(double V_T, double theta){\n validate_percent(theta);\n validate_finite_pos(V_T);\n return theta*V_T;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ff(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_f(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_mf(double V_T, double theta, double d){\n return (V_f(V_T,theta) - V_ff(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_s(double V_T, double theta){\n return (V_T - V_f(V_T, theta));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ds(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_s(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ms(double V_T, double theta, double d){\n return (V_s(V_T, theta) - V_ds(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_percent(double per){\n if( per <= 1 && per >= 0 ){\n return;\n } else if ( per < 0) {\n throw CycRangeException(\"The value is not a valid percent. It is less than zero.\");\n } else if ( per > 1) {\n throw CycRangeException(\"The value is not a valid percent. It is greater than one.\");\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_finite_pos(double pos){\n if ( pos >= numeric_limits::infinity() ) {\n throw CycRangeException(\"The value is not positive and finite. It is infinite.\");\n } \n validate_pos(pos);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_pos(double pos){\n if ( pos < 0) {\n throw CycRangeException(\"The value is not positive and finite. It is less than zero.\");\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_nonzero(double nonzero){\n if ( nonzero == 0 )\n throw CycRangeException(\"The value is zero.\");\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){\n MatTools::validate_finite_pos(scalar);\n double orig;\n IsoConcMap::iterator it;\n for(it = C_0.begin(); it != C_0.end(); ++it) { \n orig = C_0[(*it).first];\n C_0[(*it).first] = orig*scalar;\n }\n return C_0;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::addConcMaps(IsoConcMap orig, IsoConcMap to_add){\n IsoConcMap to_ret;\n IsoConcMap::iterator it;\n for(it = orig.begin(); it != orig.end(); ++it) {\n Iso iso=(*it).first;\n if(to_add.find(iso) != to_add.end()) {\n to_ret[iso] = (*it).second + to_add[iso];\n } else {\n to_ret[iso] = (*it).second;\n }\n }\n for(it = to_add.begin(); it != to_add.end(); ++it) {\n Iso iso=(*it).first;\n if(orig.find(iso) == orig.end()) {\n to_ret[iso] = (*it).second;\n }\n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nint MatTools::isoToElem(int iso) { \n int N = iso % 1000;\n return (iso-N)\/1000;\n}\nextraction in grams\/*! \\file MatTools.cpp\n \\brief Implements the MatTools class used by the Generic Repository \n \\author Kathryn D. Huff\n *\/\n#include \n#include \n#include \n#include \n#include \n\n\n#include \"CycException.h\"\n#include \"CycLimits.h\"\n#include \"MatTools.h\"\n#include \"Material.h\"\n#include \"Logger.h\"\n#include \"Timer.h\"\n\nusing namespace std;\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair MatTools::sum_mats(deque mats){\n IsoVector vec;\n CompMapPtr sum_comp = CompMapPtr(new CompMap(MASS));\n double tot = 0;\n double kg = 0;\n\n if( !mats.empty() ){ \n CompMapPtr comp_to_add;\n deque::iterator mat;\n int iso;\n CompMap::const_iterator comp;\n\n for(mat = mats.begin(); mat != mats.end(); ++mat){ \n kg = (*mat)->mass(MassUnit(KG));\n tot += kg;\n comp_to_add = (*mat)->isoVector().comp();\n comp_to_add->massify();\n for(comp = (*comp_to_add).begin(); comp != (*comp_to_add).end(); ++comp) {\n iso = comp->first;\n if(sum_comp->count(iso)!=0) {\n (*sum_comp)[iso] += (comp->second)*kg;\n } else { \n (*sum_comp)[iso] = (comp->second)*kg;\n }\n }\n }\n } else {\n (*sum_comp)[92235] = 0;\n }\n vec = IsoVector(sum_comp);\n return make_pair(vec, tot);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nmat_rsrc_ptr MatTools::extract(const CompMapPtr comp_to_rem, double kg_to_rem, deque& mat_list){\n comp_to_rem->normalize();\n mat_rsrc_ptr left_over = mat_rsrc_ptr(new Material(comp_to_rem));\n left_over->setQuantity(0);\n while(!mat_list.empty()) { \n left_over->absorb(mat_list.back());\n mat_list.pop_back();\n }\n mat_rsrc_ptr to_ret = left_over->extract(comp_to_rem, kg_to_rem*1000, G);\n if(left_over->mass(KG) > cyclus::eps_rsrc()){ \n mat_list.push_back(left_over);\n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::comp_to_conc_map(CompMapPtr comp, double mass, double vol){\n MatTools::validate_finite_pos(vol);\n MatTools::validate_finite_pos(mass);\n\n IsoConcMap to_ret;\n if( vol==0 ) {\n to_ret = zeroConcMap();\n } else {\n int iso;\n double m_iso;\n CompMap::const_iterator it;\n it=(*comp).begin();\n while(it!= (*comp).end() ){\n iso = (*it).first;\n m_iso=((*it).second)*mass;\n to_ret.insert(make_pair(iso, m_iso\/vol));\n ++it;\n } \n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::zeroConcMap(){\n IsoConcMap to_ret;\n to_ret[92235] = 0;\n return to_ret;\n}\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \npair MatTools::conc_to_comp_map(IsoConcMap conc, double vol){\n MatTools::validate_finite_pos(vol);\n\n CompMapPtr comp = CompMapPtr(new CompMap(MASS));\n double mass(0);\n int iso;\n double c_iso;\n double m_iso;\n CompMap::const_iterator it;\n it=conc.begin();\n while(it!= conc.end() ){\n iso = (*it).first;\n c_iso=((*it).second);\n m_iso = c_iso*vol;\n (*comp)[iso] = m_iso;\n mass+=m_iso;\n ++it;\n } \n (*comp).normalize();\n pair to_ret = make_pair(CompMapPtr(comp), mass);\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_f(double V_T, double theta){\n validate_percent(theta);\n validate_finite_pos(V_T);\n return theta*V_T;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ff(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_f(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_mf(double V_T, double theta, double d){\n return (V_f(V_T,theta) - V_ff(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_s(double V_T, double theta){\n return (V_T - V_f(V_T, theta));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ds(double V_T, double theta, double d){\n validate_percent(d);\n return d*V_s(V_T, theta);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \ndouble MatTools::V_ms(double V_T, double theta, double d){\n return (V_s(V_T, theta) - V_ds(V_T, theta, d));\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_percent(double per){\n if( per <= 1 && per >= 0 ){\n return;\n } else if ( per < 0) {\n throw CycRangeException(\"The value is not a valid percent. It is less than zero.\");\n } else if ( per > 1) {\n throw CycRangeException(\"The value is not a valid percent. It is greater than one.\");\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_finite_pos(double pos){\n if ( pos >= numeric_limits::infinity() ) {\n throw CycRangeException(\"The value is not positive and finite. It is infinite.\");\n } \n validate_pos(pos);\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_pos(double pos){\n if ( pos < 0) {\n throw CycRangeException(\"The value is not positive and finite. It is less than zero.\");\n }\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nvoid MatTools::validate_nonzero(double nonzero){\n if ( nonzero == 0 )\n throw CycRangeException(\"The value is zero.\");\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::scaleConcMap(IsoConcMap C_0, double scalar){\n MatTools::validate_finite_pos(scalar);\n double orig;\n IsoConcMap::iterator it;\n for(it = C_0.begin(); it != C_0.end(); ++it) { \n orig = C_0[(*it).first];\n C_0[(*it).first] = orig*scalar;\n }\n return C_0;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nIsoConcMap MatTools::addConcMaps(IsoConcMap orig, IsoConcMap to_add){\n IsoConcMap to_ret;\n IsoConcMap::iterator it;\n for(it = orig.begin(); it != orig.end(); ++it) {\n Iso iso=(*it).first;\n if(to_add.find(iso) != to_add.end()) {\n to_ret[iso] = (*it).second + to_add[iso];\n } else {\n to_ret[iso] = (*it).second;\n }\n }\n for(it = to_add.begin(); it != to_add.end(); ++it) {\n Iso iso=(*it).first;\n if(orig.find(iso) == orig.end()) {\n to_ret[iso] = (*it).second;\n }\n }\n return to_ret;\n}\n\n\/\/- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - \nint MatTools::isoToElem(int iso) { \n int N = iso % 1000;\n return (iso-N)\/1000;\n}\n<|endoftext|>"} {"text":"Spiral1 Soltuion from interviewbit<|endoftext|>"} {"text":"\/** @file main.cpp\n * @brief\n *\n * @author Viacheslav Kroilov (metopa) \n *\/\n\n#include \n#include \"murmurhash2functor.h\"\n\nint main() {\n\tmmh2::MurmurHash2 h;\n\tstd::cout << h(700) << std::endl;\n\treturn 0;\n}\nUpdate example\/** @file main.cpp\n * @brief\n *\n * @author Viacheslav Kroilov (metopa) \n *\/\n\n#include \n#include \"murmurhash2functor.h\"\n#include \"murmurhash2_stl_specializations.h\"\n\nint main() {\n\tstd::cout << mmh2::getMurmurHash2(std::string(\"\")) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::string(\"AB\")) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::string(\"BA\")) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_pair(0.f, 0.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(0., 0.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(-0., 0.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(0.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(0., 0., 0.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(1., 0.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(0., 1.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(1., 1.)) << std::endl;\n\tstd::cout << mmh2::getMurmurHash2(std::make_tuple(-1., 1.)) << std::endl;\n\treturn 0;\n}\n<|endoftext|>"} {"text":"\/* COPYRIGHT (c) 2015 Sam Westrick, Laxman Dhulipala, Umut Acar,\n * Arthur Chargueraud, and Michael Rainey.\n * All rights reserved.\n *\n * \\file pwsa.cpp\n *\n *\/\n\n#include \"benchmark.hpp\"\n#include \"treap-frontier.hpp\"\n#include \"weighted-graph.hpp\"\n#include \"native.hpp\"\n#include \"defaults.hpp\"\n#include \n\nstatic inline void pmemset(char * ptr, int value, size_t num) {\n const size_t cutoff = 100000;\n if (num <= cutoff) {\n std::memset(ptr, value, num);\n } else {\n long m = num\/2;\n pasl::sched::native::fork2([&] {\n pmemset(ptr, value, m);\n }, [&] {\n pmemset(ptr+m, value, num-m);\n });\n }\n}\n\ntemplate \nvoid fill_array_par(std::atomic* array, Size sz, Number val) {\n pmemset((char*)array, val, sz*sizeof(Number));\n}\n\ntemplate \nvoid print(const Body& b) {\n pasl::util::atomic::msg(b);\n}\n\ntemplate \nstd::atomic* pwsa(graph& graph, const HEURISTIC& heuristic,\n const intT& source, const intT& destination,\n int split_cutoff, int poll_cutoff) {\n intT N = graph.number_vertices();\n std::atomic* finalized = pasl::data::mynew_array>(N);\n fill_array_par(finalized, N, -1l);\n\n FRONTIER initF = FRONTIER();\n int heur = heuristic(source);\n VertexPackage vtxPackage = graph.make_vertex_package(source, false, 0);\n initF.insert(heur, vtxPackage);\n\n pasl::data::perworker::array work_since_split;\n work_since_split.init(0);\n\n auto size = [&] (FRONTIER& frontier) {\n auto sz = frontier.total_weight();\n if (sz == 0) {\n work_since_split.mine() = 0;\n return 0; \/\/ no work left\n }\n if (sz > split_cutoff || (work_since_split.mine() > split_cutoff && sz > 1)) {\n return 2; \/\/ split\n }\n else {\n return 1; \/\/ don't split\n }\n };\n\n auto fork = [&] (FRONTIER& src, FRONTIER& dst) {\n print([&] { std::cout << \"splitting \"; src.display(); std::cout << std::endl; });\n src.split_at(src.total_weight() \/ 2, dst);\n print([&] { std::cout << \"produced \"; src.display(); std::cout << \"; \"; dst.display(); std::cout << std::endl; });\n work_since_split.mine() = 0;\n };\n\n auto set_in_env = [&] (FRONTIER& f) {\n ; \/\/ nothing to do\n };\n\n auto do_work = [&] (FRONTIER& frontier) {\n print([&] { std::cout << \"Frontier dump: \"; frontier.display(); std::cout << std::endl; });\n\n int work_this_round = 0;\n while (work_this_round < poll_cutoff && frontier.total_weight() > 0) {\n auto pair = frontier.delete_min();\n VertexPackage vpack = pair.second;\n long orig = -1l;\n if (vpack.mustProcess || (finalized[vpack.vertexId].load() == -1 && finalized[vpack.vertexId].compare_exchange_strong(orig, vpack.distance))) {\n if (vpack.vertexId == destination) {\n print([&] { std::cout << \"FOUND DESTINATION: distance \" << finalized[destination].load() << std::endl; });\n return true;\n }\n if (work_this_round + vpack.weight() > poll_cutoff) {\n \/\/ need to split vpack\n VertexPackage other = VertexPackage();\n vpack.split_at(poll_cutoff - work_this_round, other);\n other.mustProcess = true;\n if (other.weight() != 0) frontier.insert(pair.first, other);\n }\n \/\/ Have to process our vpack\n graph.apply_to_each_in_range(vpack, [&] (intT ngh, intT weight) {\n VertexPackage nghpack = graph.make_vertex_package(ngh, false, vpack.distance + weight);\n int heur = heuristic(ngh) + vpack.distance + weight;\n frontier.insert(heur, nghpack);\n\n print([&] { std::cout << \"inserted pack \"; nghpack.display(); std::cout << \": \"; frontier.display(); std::cout << std::endl; });\n });\n work_this_round += vpack.weight();\n } else {\n \/\/ Account 1 for popping.\n work_this_round += 1;\n }\n }\n work_since_split.mine() += work_this_round;\n return false;\n };\n\n pasl::sched::native::parallel_while_pwsa(initF, size, fork, set_in_env, do_work);\n return finalized;\n}\n\nint main(int argc, char** argv) {\n long n;\n int split_cutoff;\n int poll_cutoff;\n std::string fname;\n int src;\n int dst;\n\n auto init = [&] {\n n = (long)pasl::util::cmdline::parse_or_default_long(\"n\", 24);\n split_cutoff = (int)pasl::util::cmdline::parse_or_default_int(\"K\", 100);\n poll_cutoff = (int)pasl::util::cmdline::parse_or_default_int(\"D\", 100);\n fname = pasl::util::cmdline::parse_or_default_string(\"graph\", \"simple_weighted.txt\");\n src = (int)pasl::util::cmdline::parse_or_default_int(\"src\", 0);\n dst = (int)pasl::util::cmdline::parse_or_default_int(\"dst\", 0);\n };\n\n auto run = [&] (bool sequential) {\n std::cout << n << std::endl;\n\n \/\/char const* fname = \"simple_weighted.txt\";\n \/\/char const* fname = \"simple_weighted_2.txt\";\n bool isSym = false;\n graph g = readGraphFromFile(fname.c_str(), isSym);\n\n g.printGraph();\n auto heuristic = [] (intT vtx) { return 0; };\n std::atomic* res = pwsa, decltype(heuristic), asymmetricVertex>(g, heuristic, src, dst, split_cutoff, poll_cutoff);\n for (int i = 0; i < g.n; i++) {\n std::cout << \"res[\" << i << \"] = \" << res[i].load() << std::endl;\n }\n };\n\n auto output = [&] {\n ;\n };\n\n auto destroy = [&] {\n ;\n };\n\n pasl::sched::launch(argc, argv, init, run, output, destroy);\n return 0;\n}\ncleanup\/* COPYRIGHT (c) 2015 Sam Westrick, Laxman Dhulipala, Umut Acar,\n * Arthur Chargueraud, and Michael Rainey.\n * All rights reserved.\n *\n * \\file pwsa.cpp\n *\n *\/\n\n#include \"benchmark.hpp\"\n#include \"treap-frontier.hpp\"\n#include \"weighted-graph.hpp\"\n#include \"native.hpp\"\n#include \"defaults.hpp\"\n#include \n\nstatic inline void pmemset(char * ptr, int value, size_t num) {\n const size_t cutoff = 100000;\n if (num <= cutoff) {\n std::memset(ptr, value, num);\n } else {\n long m = num\/2;\n pasl::sched::native::fork2([&] {\n pmemset(ptr, value, m);\n }, [&] {\n pmemset(ptr+m, value, num-m);\n });\n }\n}\n\ntemplate \nvoid fill_array_par(std::atomic* array, Size sz, Number val) {\n pmemset((char*)array, val, sz*sizeof(Number));\n}\n\nbool shouldPrint = false;\ntemplate \nvoid print(const Body& b) {\n if (shouldPrint) {\n pasl::util::atomic::msg(b);\n }\n}\n\ntemplate \nstd::atomic* pwsa(graph& graph, const HEURISTIC& heuristic,\n const intT& source, const intT& destination,\n int split_cutoff, int poll_cutoff) {\n intT N = graph.number_vertices();\n std::atomic* finalized = pasl::data::mynew_array>(N);\n fill_array_par(finalized, N, -1l);\n\n FRONTIER initF = FRONTIER();\n int heur = heuristic(source);\n VertexPackage vtxPackage = graph.make_vertex_package(source, false, 0);\n initF.insert(heur, vtxPackage);\n\n pasl::data::perworker::array work_since_split;\n work_since_split.init(0);\n\n auto size = [&] (FRONTIER& frontier) {\n auto sz = frontier.total_weight();\n if (sz == 0) {\n work_since_split.mine() = 0;\n return 0; \/\/ no work left\n }\n if (sz > split_cutoff || (work_since_split.mine() > split_cutoff && sz > 1)) {\n return 2; \/\/ split\n }\n else {\n return 1; \/\/ don't split\n }\n };\n\n auto fork = [&] (FRONTIER& src, FRONTIER& dst) {\n print([&] { \n std::cout << \"splitting \"; src.display(); \n std::cout << std::endl; \n });\n src.split_at(src.total_weight() \/ 2, dst);\n print([&] { \n std::cout << \"produced \"; src.display(); std::cout << \"; \"; \n dst.display(); std::cout << std::endl; \n });\n work_since_split.mine() = 0;\n };\n\n auto set_in_env = [&] (FRONTIER& f) {;};\n\n auto do_work = [&] (FRONTIER& frontier) {\n print([&] {\n std::cout << \"Frontier dump: \"; frontier.display(); \n std::cout << std::endl;\n });\n\n int work_this_round = 0;\n while (work_this_round < poll_cutoff && frontier.total_weight() > 0) {\n auto pair = frontier.delete_min();\n VertexPackage vpack = pair.second;\n long orig = -1l;\n if (vpack.mustProcess || \n (finalized[vpack.vertexId].load() == -1 && \n finalized[vpack.vertexId].compare_exchange_strong(orig, vpack.distance))) {\n if (vpack.vertexId == destination) {\n print([&] { \n std::cout << \"Found destination: distance = \" << \n finalized[destination].load() << std::endl; \n });\n return true;\n }\n if (work_this_round + vpack.weight() > poll_cutoff) {\n \/\/ need to split vpack\n VertexPackage other = VertexPackage();\n vpack.split_at(poll_cutoff - work_this_round, other);\n other.mustProcess = true;\n if (other.weight() != 0) {\n frontier.insert(pair.first, other);\n }\n }\n \/\/ Have to process our vpack\n graph.apply_to_each_in_range(vpack, [&] (intT ngh, intT weight) {\n VertexPackage nghpack = graph.make_vertex_package(ngh, false, vpack.distance + weight);\n int heur = heuristic(ngh) + vpack.distance + weight;\n frontier.insert(heur, nghpack);\n\n print([&] { \n std::cout << \"inserted pack \"; nghpack.display(); \n std::cout << \": \"; frontier.display(); std::cout << std::endl; \n });\n });\n work_this_round += vpack.weight();\n } else {\n \/\/ Account 1 for popping.\n work_this_round += 1;\n }\n }\n work_since_split.mine() += work_this_round;\n return false;\n };\n\n pasl::sched::native::parallel_while_pwsa(initF, size, fork, set_in_env, do_work);\n return finalized;\n}\n\nint main(int argc, char** argv) {\n int split_cutoff; \/\/ (K)\n int poll_cutoff; \/\/ (D)\n std::string fname;\n int src;\n int dst;\n\n auto init = [&] {\n split_cutoff = (int)pasl::util::cmdline::parse_or_default_int(\"K\", 100);\n poll_cutoff = (int)pasl::util::cmdline::parse_or_default_int(\"D\", 100);\n fname = pasl::util::cmdline::parse_or_default_string(\"graph\", \"graphs\/simple_weighted.txt\");\n src = (int)pasl::util::cmdline::parse_or_default_int(\"src\", 0);\n dst = (int)pasl::util::cmdline::parse_or_default_int(\"dst\", 0);\n };\n\n auto run = [&] (bool sequential) {\n\n bool isSym = false;\n graph g = readGraphFromFile(fname.c_str(), isSym);\n\n \/\/ g.printGraph();\n auto heuristic = [] (intT vtx) { return 0; };\n std::atomic* res = pwsa, \n decltype(heuristic), \n asymmetricVertex>(g, heuristic, src, dst, \n split_cutoff, poll_cutoff);\n\n\n int numExpanded = 0;\n for (int i = 0; i < g.n; i++) {\n if (res[i].load() != -1) {\n numExpanded++;\n }\n }\n std::cout << \"expanded : \" << numExpanded << \" many nodes out of \" << g.n;\n std::cout << \"path lengh is : \" << res[dst].load(); \n\n\/\/ for (int i = 0; i < g.n; i++) {\n\/\/ std::cout << \"res[\" << i << \"] = \" << res[i].load() << std::endl;\n\/\/ }\n };\n\n auto output = [&] {;};\n\n auto destroy = [&] {;};\n\n pasl::sched::launch(argc, argv, init, run, output, destroy);\n return 0;\n}\n<|endoftext|>"} {"text":"\/*\n * Priority.cpp\n *\n * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2000, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"PortabilityImpl.hh\"\n#include \n#include \n\nnamespace log4cpp {\n\n namespace {\n const std::string names[10] = {\n \"FATAL\",\n\t\t\t\"ALERT\",\n\t\t\t\"CRIT\",\n\t\t\t\"ERROR\",\n\t\t\t\"WARN\",\n \"NOTICE\",\n\t\t\t\"INFO\",\n\t\t\t\"DEBUG\",\n\t\t\t\"NOTSET\",\n\t\t\t\"UNKNOWN\" \n };\n } \n\n const int log4cpp::Priority::MESSAGE_SIZE = 8;\n \n\n const std::string& Priority::getPriorityName(int priority) throw() {\n \n priority++;\n priority \/= 100;\n return names[((priority < 0) || (priority > 8)) ? 8 : priority];\n }\n\n Priority::Value Priority::getPriorityValue(const std::string& priorityName) \n throw(std::invalid_argument) {\n\tPriority::Value value = -1;\n\n\tfor (unsigned int i = 0; i < 10; i++) {\n\t if (priorityName == names[i]) {\n\t\tvalue = i * 100;\n\t\tbreak;\n\t }\n\t}\n\n\tif (value == -1) {\n\t if (priorityName == \"EMERG\") {\n\t\t value = 0;\n\t } else {\n\t\t char* endPointer;\n\t\t value = std::strtoul(priorityName.c_str(), &endPointer, 10);\n\t\t if (*endPointer != 0) {\n\t\t throw std::invalid_argument(\n\t\t\t\t\tstd::string(\"unknown priority name: '\") + priorityName + \"'\"\n\t\t\t\t);\n\t\t }\n\t }\n\t}\n\t\n\treturn value;\n }\n}\nFix for bug#3198140\/*\n * Priority.cpp\n *\n * Copyright 2000, LifeLine Networks BV (www.lifeline.nl). All rights reserved.\n * Copyright 2000, Bastiaan Bakker. All rights reserved.\n *\n * See the COPYING file for the terms of usage and distribution.\n *\/\n\n#include \"PortabilityImpl.hh\"\n#include \n#include \n\nnamespace log4cpp {\n\n namespace {\n\tconst std::string *names() {\n\t static const std::string priority_names[10] = {\n\t\t\t\"FATAL\",\n\t\t\t\"ALERT\",\n\t\t\t\"CRIT\",\n\t\t\t\"ERROR\",\n\t\t\t\"WARN\",\n\t\t\t\"NOTICE\",\n\t\t\t\"INFO\",\n\t\t\t\"DEBUG\",\n\t\t\t\"NOTSET\",\n\t\t\t\"UNKNOWN\" \n\t };\n\t return priority_names;\n\t}\n } \n\n const int log4cpp::Priority::MESSAGE_SIZE = 8;\n \n\n const std::string& Priority::getPriorityName(int priority) throw() {\n \n priority++;\n priority \/= 100;\n return names()[((priority < 0) || (priority > 8)) ? 8 : priority];\n }\n\n Priority::Value Priority::getPriorityValue(const std::string& priorityName) \n throw(std::invalid_argument) {\n\tPriority::Value value = -1;\n\n\tfor (unsigned int i = 0; i < 10; i++) {\n\t if (priorityName == names()[i]) {\n\t\tvalue = i * 100;\n\t\tbreak;\n\t }\n\t}\n\n\tif (value == -1) {\n\t if (priorityName == \"EMERG\") {\n\t\t value = 0;\n\t } else {\n\t\t char* endPointer;\n\t\t value = std::strtoul(priorityName.c_str(), &endPointer, 10);\n\t\t if (*endPointer != 0) {\n\t\t throw std::invalid_argument(\n\t\t\t\t\tstd::string(\"unknown priority name: '\") + priorityName + \"'\"\n\t\t\t\t);\n\t\t }\n\t }\n\t}\n\t\n\treturn value;\n }\n}\n<|endoftext|>"} {"text":"\/*\n\nCopyright (c) 2015, Project OSRM contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n\/\/ based on\n\/\/ https:\/\/svn.apache.org\/repos\/asf\/mesos\/tags\/release-0.9.0-incubating-RC0\/src\/common\/json.hpp\n\n#ifndef JSON_V8_RENDERER_HPP\n#define JSON_V8_RENDERER_HPP\n\n#include \n\n\/\/ v8\n#include \n\n#include \n\nnamespace node_osrm\n{\n\nstruct V8Renderer : mapbox::util::static_visitor<>\n{\n explicit V8Renderer(v8::Local &_out) : out(_out) {}\n\n void operator()(const osrm::json::String &string) const\n {\n out = Nan::New(std::cref(string.value)).ToLocalChecked();\n }\n\n void operator()(const osrm::json::Number &number) const { out = Nan::New(number.value); }\n\n void operator()(const osrm::json::Object &object) const\n {\n v8::Local obj = Nan::New();\n for (const auto &keyValue : object.values)\n {\n v8::Local child;\n mapbox::util::apply_visitor(v8_renderer(child), keyValue.second);\n obj->Set(Nan::New(keyValue.first).ToLocalChecked(), child);\n }\n out = obj;\n }\n\n void operator()(const osrm::json::Array &array) const\n {\n v8::Local a = Nan::New(array.values.size());\n for (auto i = 0u; i < array.values.size(); ++i)\n {\n v8::Local child;\n mapbox::util::apply_visitor(v8_renderer(child), array.values[i]);\n a->Set(i, child);\n }\n out = a;\n }\n\n void operator()(const osrm::json::True &) const { out = Nan::New(true); }\n\n void operator()(const osrm::json::False &) const { out = Nan::New(false); }\n\n void operator()(const osrm::json::Null &) const { out = Nan::Null(); }\n\n private:\n v8::Local &out;\n};\n\ninline void renderToV8(v8::Local &out, const osrm::json::Object &object)\n{\n \/\/ FIXME this should be a cast?\n osrm::json::Value value = object;\n mapbox::util::apply_visitor(V8Renderer(out), value);\n}\n\n}\n\n#endif \/\/ JSON_V8_RENDERER_HPP\nFix v8 renderer\/*\n\nCopyright (c) 2015, Project OSRM contributors\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification,\nare permitted provided that the following conditions are met:\n\nRedistributions of source code must retain the above copyright notice, this list\nof conditions and the following disclaimer.\nRedistributions in binary form must reproduce the above copyright notice, this\nlist of conditions and the following disclaimer in the documentation and\/or\nother materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON\nANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n*\/\n\n\/\/ based on\n\/\/ https:\/\/svn.apache.org\/repos\/asf\/mesos\/tags\/release-0.9.0-incubating-RC0\/src\/common\/json.hpp\n\n#ifndef JSON_V8_RENDERER_HPP\n#define JSON_V8_RENDERER_HPP\n\n#include \n\n\/\/ v8\n#include \n\n#include \n\nnamespace node_osrm\n{\n\nstruct V8Renderer : mapbox::util::static_visitor<>\n{\n explicit V8Renderer(v8::Local &_out) : out(_out) {}\n\n void operator()(const osrm::json::String &string) const\n {\n out = Nan::New(std::cref(string.value)).ToLocalChecked();\n }\n\n void operator()(const osrm::json::Number &number) const { out = Nan::New(number.value); }\n\n void operator()(const osrm::json::Object &object) const\n {\n v8::Local obj = Nan::New();\n for (const auto &keyValue : object.values)\n {\n v8::Local child;\n mapbox::util::apply_visitor(V8Renderer(child), keyValue.second);\n obj->Set(Nan::New(keyValue.first).ToLocalChecked(), child);\n }\n out = obj;\n }\n\n void operator()(const osrm::json::Array &array) const\n {\n v8::Local a = Nan::New(array.values.size());\n for (auto i = 0u; i < array.values.size(); ++i)\n {\n v8::Local child;\n mapbox::util::apply_visitor(V8Renderer(child), array.values[i]);\n a->Set(i, child);\n }\n out = a;\n }\n\n void operator()(const osrm::json::True &) const { out = Nan::New(true); }\n\n void operator()(const osrm::json::False &) const { out = Nan::New(false); }\n\n void operator()(const osrm::json::Null &) const { out = Nan::Null(); }\n\n private:\n v8::Local &out;\n};\n\ninline void renderToV8(v8::Local &out, const osrm::json::Object &object)\n{\n \/\/ FIXME this should be a cast?\n osrm::json::Value value = object;\n mapbox::util::apply_visitor(V8Renderer(out), value);\n}\n\n}\n\n#endif \/\/ JSON_V8_RENDERER_HPP\n<|endoftext|>"} {"text":"\/******************************************************************************\n * Copyright (c) 2015 Jamis Hoo\n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: k_means_iteration.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Jul 19, 2015\n * Time: 20:55:38\n * Description: \n *****************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n\n#include \"hadoop\/Pipes.hh\"\n#include \"hadoop\/TemplateFactory.hh\"\n#include \"hadoop\/StringUtils.hh\"\n\n#include \"netflix_movie.h\"\n\nconstexpr size_t canopy_threshold = 2;\nconst std::string canopy_centers_path = \"canopy_centers\";\nconst std::string k_means_center_path = \"k_means_centers\";\n\ninline std::string to_hex_string(const size_t x) {\n char buff[32] = { 0 };\n sprintf(buff, \"%zx\", x);\n \n return buff;\n}\n\ninline std::vector string_split(const std::string& str) {\n std::vector numbers;\n\n char* offset;\n\n const char* end = str.data() + str.length();\n const char* tmp = str.data();\n while (tmp < end) {\n uint32_t movie_id = strtoul(tmp, &offset, 16);\n numbers.emplace_back(movie_id);\n tmp = offset + 1;\n }\n\n return numbers;\n}\n\nclass kMeansMapper: public HadoopPipes::Mapper {\npublic:\n kMeansMapper(HadoopPipes::TaskContext& \/* context *\/) {\n load_canopy_centers();\n load_kmeans_centers();\n\n \/\/ no use anymore\n canopy_centers.clear();\n }\n\n void map(HadoopPipes::MapContext& context) {\n std::string input_value = context.getInputValue(); \n\n std::string movie_string = \n input_value.substr(0, input_value.find_first_of('\\t')) + ':' +\n input_value.substr(input_value.find_first_of(';') + 1);\n\n Movie movie = movie_string;\n\n size_t start_pos = input_value.find_first_of('\\t');\n size_t end_pos = input_value.find_first_of(';', start_pos);\n std::vector canopy_ids = string_split(input_value.substr(start_pos + 1, end_pos - start_pos - 1));\n\n float max_distance = -1;\n const Movie* max_distance_movie = nullptr;\n for (const auto canopy_id: canopy_ids) {\n if (canopy_id == movie.movie_id()) continue;\n for (const auto& k_means_center: centers[canopy_id]) {\n float distance = movie.cos_distance(k_means_center);\n if (distance > max_distance) {\n max_distance = distance;\n max_distance_movie = &k_means_center;\n }\n }\n }\n\n std::string emit_key = max_distance_movie->to_string();\n std::string emit_value = movie_string;\n\n context.emit(emit_key, emit_value);\n }\n\nprivate: \n void load_canopy_centers() {\n std::ifstream fin(canopy_centers_path);\n\n std::string line;\n while (std::getline(fin, line)) \n canopy_centers.emplace_back(line);\n\n }\n\n void load_kmeans_centers() {\n std::ifstream fin(k_means_center_path);\n\n std::string line;\n while (std::getline(fin, line)) {\n Movie k_means_center(line);\n\n for (const auto& canopy_center: canopy_centers) \n if (k_means_center.user_match_count(canopy_center) > canopy_threshold) {\n auto ite = centers.emplace(canopy_center.movie_id(), std::vector()).first;\n ite->second.push_back(k_means_center);\n }\n }\n }\n \n std::vector canopy_centers;\n \/\/ canopy movie_id, vector of k-means centers\n std::unordered_map< uint32_t, std::vector > centers;\n};\n\nclass kMeansReducer: public HadoopPipes::Reducer {\npublic:\n kMeansReducer(const HadoopPipes::TaskContext& \/* context *\/) { }\n\n void reduce(HadoopPipes::ReduceContext& context) {\n Movie k_means_center(context.getInputKey());\n\n \/\/ >\n std::unordered_map > new_features;\n\n while (context.nextValue()) {\n Movie movie(context.getInputValue());\n\n for (size_t i = 0; i < movie.num_users(); ++i) {\n auto ite = new_features.emplace(movie.user_id(i), std::make_pair(0, 0)).first;\n\n ite->second.first += 1;\n ite->second.second += movie.rating(i);\n }\n }\n\n std::vector< std::pair > new_features_vec;\n for (const auto i: new_features)\n new_features_vec.push_back({ i.first, i.second.second \/ i.second.first });\n\n sort(new_features_vec.begin(), new_features_vec.end());\n\n std::string emit_key = to_hex_string(k_means_center.movie_id());\n\n std::string emit_value;\n for (const auto i: new_features_vec)\n emit_value += to_hex_string(i.first) + ',' + to_hex_string(i.second) + ',';\n\n if (emit_value.size()) {\n emit_value.pop_back();\n context.emit(emit_key, emit_value);\n }\n }\n};\n\nint main(int, char**) {\n return HadoopPipes::runTask(HadoopPipes::TemplateFactory());\n}\n\n\nfix bug\/******************************************************************************\n * Copyright (c) 2015 Jamis Hoo\n * Distributed under the MIT license \n * (See accompanying file LICENSE or copy at http:\/\/opensource.org\/licenses\/MIT)\n * \n * Project: \n * Filename: k_means_iteration.cc \n * Version: 1.0\n * Author: Jamis Hoo\n * E-mail: hjm211324@gmail.com\n * Date: Jul 19, 2015\n * Time: 20:55:38\n * Description: \n *****************************************************************************\/\n#include \n#include \n#include \n#include \n#include \n\n#include \"hadoop\/Pipes.hh\"\n#include \"hadoop\/TemplateFactory.hh\"\n#include \"hadoop\/StringUtils.hh\"\n\n#include \"netflix_movie.h\"\n\nconstexpr size_t canopy_threshold = 2;\nconst std::string canopy_centers_path = \"canopy_centers\";\nconst std::string k_means_center_path = \"k_means_centers\";\n\ninline std::string to_hex_string(const size_t x) {\n char buff[32] = { 0 };\n sprintf(buff, \"%zx\", x);\n \n return buff;\n}\n\ninline std::vector string_split(const std::string& str) {\n std::vector numbers;\n\n char* offset;\n\n const char* end = str.data() + str.length();\n const char* tmp = str.data();\n while (tmp < end) {\n uint32_t movie_id = strtoul(tmp, &offset, 16);\n numbers.emplace_back(movie_id);\n tmp = offset + 1;\n }\n\n return numbers;\n}\n\nclass kMeansMapper: public HadoopPipes::Mapper {\npublic:\n kMeansMapper(HadoopPipes::TaskContext& \/* context *\/) {\n load_canopy_centers();\n load_kmeans_centers();\n\n \/\/ no use anymore\n canopy_centers.clear();\n }\n\n void map(HadoopPipes::MapContext& context) {\n std::string input_value = context.getInputValue(); \n\n std::string movie_string = \n input_value.substr(0, input_value.find_first_of('\\t')) + ':' +\n input_value.substr(input_value.find_first_of(';') + 1);\n\n Movie movie = movie_string;\n\n std::cout << \"Load input movie: \" << movie.to_string() << std::endl;\n\n size_t start_pos = input_value.find_first_of('\\t');\n size_t end_pos = input_value.find_first_of(';', start_pos);\n std::vector canopy_ids = string_split(input_value.substr(start_pos + 1, end_pos - start_pos - 1));\n \n std::cout << \"canopy_ids: \"; for (const auto i: canopy_ids) std::cout << i << ' '; std::cout << std::endl;\n\n float max_distance = -1;\n const Movie* max_distance_movie = nullptr;\n for (const auto canopy_id: canopy_ids) {\n if (canopy_id == movie.movie_id()) continue;\n for (const auto& k_means_center: centers[canopy_id]) {\n float distance = movie.cos_distance(k_means_center);\n std::cout << \"Distance with \" << k_means_center.to_string() << \" is \" << distance;\n if (distance > max_distance) {\n std::cout << \" is max. \";\n max_distance = distance;\n max_distance_movie = &k_means_center;\n }\n std::cout << std::endl;\n }\n }\n\n if (max_distance_movie == nullptr) return;\n\n std::string emit_key = max_distance_movie->to_string();\n std::string emit_value = movie_string;\n\n std::cout << \"emit_key = \" << emit_key << std::endl;\n std::cout << \"emit_value = \" << emit_value << std::endl;\n\n context.emit(emit_key, emit_value);\n }\n\nprivate: \n void load_canopy_centers() {\n std::ifstream fin(canopy_centers_path);\n\n std::string line;\n while (std::getline(fin, line)) {\n canopy_centers.emplace_back(line); \n std::cout << \"Load cannopy center: \" << canopy_centers.back().to_string() << std::endl;\n }\n\n }\n\n void load_kmeans_centers() {\n std::ifstream fin(k_means_center_path);\n\n std::string line;\n while (std::getline(fin, line)) {\n Movie k_means_center(line);\n\n std::cout << \"k-means center: \" << k_means_center.to_string() << \" \";\n for (const auto& canopy_center: canopy_centers) \n if (k_means_center.user_match_count(canopy_center) > canopy_threshold) {\n std::cout << \"applied to canopy \" << canopy_center.to_string() << \" \";\n auto ite = centers.emplace(canopy_center.movie_id(), std::vector()).first;\n ite->second.push_back(k_means_center);\n }\n std::cout << std::endl;\n }\n }\n \n std::vector canopy_centers;\n \/\/ canopy movie_id, vector of k-means centers\n std::unordered_map< uint32_t, std::vector > centers;\n};\n\nclass kMeansReducer: public HadoopPipes::Reducer {\npublic:\n kMeansReducer(const HadoopPipes::TaskContext& \/* context *\/) { }\n\n void reduce(HadoopPipes::ReduceContext& context) {\n Movie k_means_center(context.getInputKey());\n\n \/\/ >\n std::unordered_map > new_features;\n\n while (context.nextValue()) {\n Movie movie(context.getInputValue());\n\n for (size_t i = 0; i < movie.num_users(); ++i) {\n auto ite = new_features.emplace(movie.user_id(i), std::make_pair(0, 0)).first;\n\n ite->second.first += 1;\n ite->second.second += movie.rating(i);\n }\n }\n\n std::vector< std::pair > new_features_vec;\n for (const auto i: new_features)\n new_features_vec.push_back({ i.first, i.second.second \/ i.second.first });\n\n sort(new_features_vec.begin(), new_features_vec.end());\n\n std::string emit_key = to_hex_string(k_means_center.movie_id());\n\n std::string emit_value;\n for (const auto i: new_features_vec)\n emit_value += to_hex_string(i.first) + ',' + to_hex_string(i.second) + ',';\n\n if (emit_value.size()) {\n emit_value.pop_back();\n context.emit(emit_key, emit_value);\n }\n }\n};\n\nint main(int, char**) {\n return HadoopPipes::runTask(HadoopPipes::TemplateFactory());\n}\n\n\n<|endoftext|>"} {"text":"\/* GG is a GUI for SDL and OpenGL.\n Copyright (C) 2003 T. Zachary Laine\n\n This library is free software; you can redistribute it and\/or\n modify it under the terms of the GNU Lesser General Public License\n as published by the Free Software Foundation; either version 2.1\n of the License, or (at your option) any later version.\n \n This library is distributed in the hope that it will be useful,\n but WITHOUT ANY WARRANTY; without even the implied warranty of\n MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n Lesser General Public License for more details.\n \n You should have received a copy of the GNU Lesser General Public\n License along with this library; if not, write to the Free\n Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA\n 02111-1307 USA\n\n If you do not wish to comply with the terms of the LGPL please\n contact the author as other terms are available for a fee.\n \n Zach Laine\n whatwasthataddress@hotmail.com *\/\n\n\/* $Header$ *\/\n\n#include \"SDLGGApp.h\"\n\nusing std::string;\n\n\/\/ member functions\nSDLGGApp::SDLGGApp(int w\/* = 1024*\/, int h\/* = 768*\/, bool calc_FPS\/* = false*\/, const std::string& app_name\/* = \"GG\"*\/) :\n GG::App(this, app_name),\n m_app_width(w),\n m_app_height(h),\n m_delta_t(1),\n m_FPS(-1.0),\n m_calc_FPS(calc_FPS)\n{\n}\n\nSDLGGApp::~SDLGGApp()\n{\n SDLQuit();\n}\n\nSDLGGApp* SDLGGApp::GetApp()\n{\n return dynamic_cast(GG::App::GetApp());\n}\n\nvoid SDLGGApp::Exit(int code)\n{\n Logger().fatalStream() << \"Initiating Exit (code \" << code << \" - \" << (code ? \"error\" : \"normal\") << \" termination)\";\n SDLQuit();\n exit(code);\n}\n\nvoid SDLGGApp::CalcuateFPS(bool b\/* = true*\/)\n{\n m_calc_FPS = b;\n if (!b) m_FPS = -1.0f;\n}\n\nconst string& SDLGGApp::FPSString() const\n{\n static string retval;\n char buf[64];\n sprintf(buf, \"%.2f frames per second\", m_FPS);\n retval = buf;\n return retval;\n}\n\nGG::Key SDLGGApp::GGKeyFromSDLKey(const SDL_keysym& key)\n{\n GG::Key retval = GG::Key(key.sym);\n bool shift = key.mod & KMOD_SHIFT;\n bool caps_lock = key.mod & KMOD_CAPS;\n\n \/\/ this code works because both SDLKey and GG::Key map (at least\n \/\/ partially) to the printable ASCII characters\n if (shift || caps_lock) {\n if (shift != caps_lock && (retval >= 'a' && retval <= 'z')) {\n retval = GG::Key(toupper(retval));\n } else if (shift) { \/\/ the caps lock key should not affect these\n \/\/ this assumes a US keyboard layout\n switch (retval) {\n case '`': retval = GG::Key('~'); break;\n case '1': retval = GG::Key('!'); break;\n case '2': retval = GG::Key('@'); break;\n case '3': retval = GG::Key('#'); break;\n case '4': retval = GG::Key('$'); break;\n case '5': retval = GG::Key('%'); break;\n case '6': retval = GG::Key('^'); break;\n case '7': retval = GG::Key('&'); break;\n case '8': retval = GG::Key('*'); break;\n case '9': retval = GG::Key('('); break;\n case '0': retval = GG::Key(')'); break;\n case '-': retval = GG::Key('_'); break;\n case '=': retval = GG::Key('+'); break;\n case '[': retval = GG::Key('{'); break;\n case ']': retval = GG::Key('}'); break;\n case '\\\\': retval = GG::Key('|'); break;\n case ';': retval = GG::Key(':'); break;\n case '\\'': retval = GG::Key('\"'); break;\n case ',': retval = GG::Key('<'); break;\n case '.': retval = GG::Key('>'); break;\n case '\/': retval = GG::Key('?'); break;\n default: break;\n }\n }\n }\n return retval;\n}\n\nvoid SDLGGApp::SDLInit()\n{\n const SDL_VideoInfo* vid_info = 0;\n\n if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_NOPARACHUTE) < 0) {\n Logger().errorStream() << \"SDL initialization failed: \" << SDL_GetError();\n Exit(1);\n }\n\n if (SDLNet_Init() < 0) {\n Logger().errorStream() << \"SDL Net initialization failed: \" << SDLNet_GetError();\n Exit(1);\n }\n\n if (TTF_Init() < 0) {\n Logger().errorStream() << \"TTF initialization failed: \" << TTF_GetError();\n Exit(1);\n }\n\n if (FE_Init() < 0) {\n Logger().errorStream() << \"FastEvents initialization failed: \" << FE_GetError();\n Exit(1);\n }\n\n vid_info = SDL_GetVideoInfo();\n\n if (!vid_info) {\n Logger().errorStream() << \"Video info query failed: \" << SDL_GetError();\n Exit(1);\n }\n\n SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);\n\n if (SDL_SetVideoMode(m_app_width, m_app_height, 16, SDL_OPENGL) == 0) {\n Logger().errorStream() << \"Video mode set failed: \" << SDL_GetError();\n Exit(1);\n }\n\n if (NET2_Init() < 0) {\n Logger().errorStream() << \"SDL Net2 initialization failed: \" << NET2_GetError();\n Exit(1);\n }\n\n SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);\n EnableMouseDragRepeat(SDL_DEFAULT_REPEAT_DELAY \/ 2, SDL_DEFAULT_REPEAT_INTERVAL \/ 2);\n\n Logger().debugStream() << \"SDLInit() complete.\";\n GLInit();\n}\n\nvoid SDLGGApp::GLInit()\n{\n double ratio = m_app_width \/ (float)(m_app_height);\n\n glEnable(GL_LIGHTING);\n glEnable(GL_LIGHT0);\n glEnable(GL_DEPTH_TEST);\n glEnable(GL_CULL_FACE);\n glEnable(GL_BLEND);\n glShadeModel(GL_SMOOTH);\n glClearColor(0, 0, 0, 0);\n glViewport(0, 0, m_app_width - 1, m_app_height - 1);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluPerspective(50.0, ratio, 1.0, 10.0);\n\n Logger().debugStream() << \"GLInit() complete.\";\n}\n\nvoid SDLGGApp::HandleSDLEvent(const SDL_Event& event)\n{\n bool send_to_gg = false;\n GG::App::EventType gg_event;\n GG::Key key = GGKeyFromSDLKey(event.key.keysym);\n Uint32 key_mods = SDL_GetModState();\n GG::Pt mouse_pos(event.motion.x, event.motion.y);\n GG::Pt mouse_rel(event.motion.xrel, event.motion.yrel);\n\n switch(event.type) {\n case SDL_KEYDOWN:\n if (key < GG::GGK_NUMLOCK)\n send_to_gg = true;\n gg_event = GG::App::KEYPRESS;\n break;\n case SDL_MOUSEMOTION:\n send_to_gg = true;\n gg_event = GG::App::MOUSEMOVE;\n break;\n case SDL_MOUSEBUTTONDOWN:\n send_to_gg = true;\n switch (event.button.button) {\n case SDL_BUTTON_LEFT: gg_event = GG::App::LPRESS; break;\n case SDL_BUTTON_MIDDLE: gg_event = GG::App::MPRESS; break;\n case SDL_BUTTON_RIGHT: gg_event = GG::App::RPRESS; break;\n case SDL_BUTTON_WHEELUP: gg_event = GG::App::MOUSEWHEEL; mouse_rel = GG::Pt(0, 1); break;\n case SDL_BUTTON_WHEELDOWN: gg_event = GG::App::MOUSEWHEEL; mouse_rel = GG::Pt(0, -1); break;\n }\n key_mods = SDL_GetModState();\n break;\n case SDL_MOUSEBUTTONUP:\n send_to_gg = true;\n switch (event.button.button) {\n case SDL_BUTTON_LEFT: gg_event = GG::App::LRELEASE; break;\n case SDL_BUTTON_MIDDLE: gg_event = GG::App::MRELEASE; break;\n case SDL_BUTTON_RIGHT: gg_event = GG::App::RRELEASE; break;\n }\n key_mods = SDL_GetModState();\n break;\n case SDL_QUIT:\n Exit(0);\n break;\n }\n if (send_to_gg)\n GG::App::HandleEvent(gg_event, key, key_mods, mouse_pos, mouse_rel);\n}\n\nvoid SDLGGApp::RenderBegin()\n{\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n}\n\nvoid SDLGGApp::RenderEnd()\n{\n SDL_GL_SwapBuffers();\n}\n\nvoid SDLGGApp::SDLQuit()\n{\n FinalCleanup();\n NET2_Quit();\n FE_Quit();\n TTF_Quit();\n SDLNet_Quit();\n SDL_Quit();\n Logger().debugStream() << \"SDLQuit() complete.\";\n}\n\nvoid SDLGGApp::PollAndRender()\n{\n static int last_FPS_time = 0;\n static int most_recent_time = 0;\n static int time = 0;\n static int frames = 0;\n\n static int last_mouse_event_time = 0;\n static int mouse_drag_repeat_start_time = 0;\n static int last_mouse_drag_repeat_time = 0;\n static int old_mouse_repeat_delay = MouseRepeatDelay();\n static int old_mouse_repeat_interval = MouseRepeatInterval();\n\n \/\/ handle events\n SDL_Event event;\n while (0 < FE_PollEvent(&event)) {\n if (event.type == SDL_MOUSEBUTTONDOWN || event.type == SDL_MOUSEBUTTONUP || event.type == SDL_MOUSEMOTION)\n last_mouse_event_time = time;\n HandleSDLEvent(event);\n }\n\n \/\/ update time and track FPS if needed\n time = SDL_GetTicks();\n m_delta_t = time - most_recent_time;\n if (m_calc_FPS) {\n ++frames;\n if (time - last_FPS_time > 1000) { \/\/ calculate FPS at most once a second\n m_FPS = frames \/ ((time - last_FPS_time) \/ 1000.0f);\n last_FPS_time = time;\n frames = 0;\n }\n }\n most_recent_time = time;\n\n \/\/ handle mouse drag repeats\n if (old_mouse_repeat_delay != MouseRepeatDelay() || old_mouse_repeat_interval != MouseRepeatInterval()) { \/\/ if there's a change in the values, zero everything out and start the counting over\n old_mouse_repeat_delay = MouseRepeatDelay();\n old_mouse_repeat_interval = MouseRepeatInterval();\n mouse_drag_repeat_start_time = 0;\n last_mouse_drag_repeat_time = 0;\n }\n int x, y;\n \/\/ if drag repeat is enabled, the left mouse button is depressed (a drag is ocurring), and the last event processed wasn't too recent\n if (MouseRepeatDelay() && SDL_GetMouseState(&x, &y) & SDL_BUTTON_LEFT && time - last_mouse_event_time > old_mouse_repeat_interval) {\n if (!mouse_drag_repeat_start_time) { \/\/ if we're just starting the drag, mark the time we started\n mouse_drag_repeat_start_time = time;\n } else if (mouse_drag_repeat_start_time == MouseRepeatDelay()) { \/\/ if we're counting repeat intervals\n if (time - last_mouse_drag_repeat_time > MouseRepeatInterval()) {\n last_mouse_drag_repeat_time = time;\n event.type = SDL_MOUSEMOTION;\n event.motion.x = x;\n event.motion.y = y;\n event.motion.xrel = event.motion.yrel = 0; \/\/ this is just an update, so set the motion to 0\n HandleSDLEvent(event);\n }\n } else if (time - mouse_drag_repeat_start_time > MouseRepeatDelay()) { \/\/ if we're done waiting for the initial delay period\n mouse_drag_repeat_start_time = MouseRepeatDelay(); \/\/ set this as equal so we know later that we've passed the delay interval\n last_mouse_drag_repeat_time = time;\n event.type = SDL_MOUSEMOTION;\n event.motion.x = x;\n event.motion.y = y;\n event.motion.xrel = event.motion.yrel = 0;\n HandleSDLEvent(event);\n }\n } else { \/\/ otherwise, reset the mouse drag repeat start time to zero\n mouse_drag_repeat_start_time = 0;\n }\n\n \/\/ do one iteration of the render loop\n Update();\n RenderBegin();\n Render();\n RenderEnd();\n}\n\nvoid SDLGGApp::Run()\n{\n try {\n SDLInit();\n Initialize();\n while (1)\n PollAndRender();\n } catch (const std::invalid_argument& exception) {\n Logger().fatal(\"std::invalid_argument Exception caught in App::Run(): \" + string(exception.what()));\n Exit(1);\n } catch (const std::runtime_error& exception) {\n Logger().fatal(\"std::runtime_error Exception caught in App::Run(): \" + string(exception.what()));\n Exit(1);\n } catch (const GG::GGException& exception) {\n Logger().fatal(\"GG::GGException (subclass \" + string(exception.what()) + \") caught in App::Run(): \" + exception.Message());\n Exit(1);\n }\n}\n\nMoved to its own directory.<|endoftext|>"} {"text":"\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#define ARGS_MAX 64\n\n__attribute__((weak))\nextern \"C\" int main(int, const char*[]);\n\n__attribute__((weak))\nvoid Service::start(const std::string& cmd)\n{\n std::string st(cmd); \/\/ mangled copy\n int argc = 0;\n const char* argv[ARGS_MAX];\n \n \/\/ Populate argv\n char* begin = (char*) st.data();\n char* end = begin + st.size();\n \n for (char* ptr = begin; ptr < end; ptr++)\n if (std::isspace(*ptr)) {\n argv[argc++] = begin;\n *ptr = 0; \/\/ zero terminate\n begin = ptr+1; \/\/ next arg\n if (argc >= ARGS_MAX) break;\n }\n\n int exit_status = main(argc, argv);\n INFO(\"main\",\"returned with status %d\", exit_status);\n \/\/exit(exit_status);\n}\nmain: new argparser now finds last arg and handles n spaces\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n#define ARGS_MAX 64\n\n__attribute__((weak))\nextern \"C\" int main(int, const char*[]);\n\n__attribute__((weak))\nvoid Service::start(const std::string& cmd)\n{\n std::string st(cmd); \/\/ mangled copy\n int argc = 0;\n const char* argv[ARGS_MAX];\n\n \/\/ Get pointers to null-terminated string\n char* word = (char*) st.c_str();\n char* end = word + st.size() + 1;\n bool new_word = false;\n\n for (char* ptr = word; ptr < end; ptr++) {\n\n \/\/ Replace all spaces with 0\n if(std::isspace(*ptr)) {\n *ptr = 0;\n new_word = true;\n continue;\n }\n\n \/\/ At the start of each word, or last byte, add previous pointer to array\n if (new_word or ptr == end - 1) {\n argv[argc++] = word;\n word = ptr; \/\/ next arg\n if (argc >= ARGS_MAX) break;\n new_word = false;\n }\n }\n\n int exit_status = main(argc, argv);\n INFO(\"main\",\"returned with status %d\", exit_status);\n\n}\n<|endoftext|>"} {"text":"\/*************************************************************************\n\t> Author: Wayne Ho\n\t> Purpose: TODO\n\t> Created Time: Wed 03 Jun 2015 11:01:35 AM CST\n\t> Mail: hewr2010@gmail.com \n ************************************************************************\/\n#include \"storage\/graph_builder.h\"\n#include \n#include \n#include \nusing namespace std;\nusing namespace sae::io;\n\nint main(int argc, char **argv) {\n GraphBuilder graph;\n ifstream fin(\".\/resource\/amazon0312.txt\");\n string buf;\n for (int i = 0; i < 4; ++i) getline(fin, buf);\n int v_cnt(-1);\n while (1) {\n int x, y;\n if (!(fin >> x >> y)) break;\n int z = max(max(v_cnt, x), y);\n while (v_cnt < z) graph.AddVertex(++v_cnt, 0);\n graph.AddEdge(x, y, 0);\n }\n cout << graph.VertexCount() << \" \" << graph.EdgeCount() << endl;\n graph.Save(\".\/data\/graph\");\n return 0;\n}\n\nupdate\/*************************************************************************\n\t> Author: Wayne Ho\n\t> Purpose: TODO\n\t> Created Time: Wed 03 Jun 2015 11:01:35 AM CST\n\t> Mail: hewr2010@gmail.com \n ************************************************************************\/\n#include \"storage\/graph_builder.h\"\n#include \n#include \n#include \n#include \nusing namespace std;\nusing namespace sae::io;\n \nmap nodeMap;\n\nint GetOrInsert(const string& key)\n{\n map::iterator it = nodeMap.find(key);\n if (it != nodeMap.end())\n return it -> second;\n int id = (int) nodeMap.size();\n nodeMap.insert(make_pair(key, id));\n return id;\n}\n\nint main(int argc, char **argv) {\n GraphBuilder graph;\n \/\/ifstream fin(\".\/resource\/amazon0312.txt\");\n ifstream fin(\".\/resource\/twitter_combined.txt\");\n string buf;\n \/\/for (int i = 0; i < 4; ++i) getline(fin, buf);\n int v_cnt(-1);\n map nodeMap;\n while (1) {\n string x, y;\n if (!(fin >> x >> y)) break;\n int a = GetOrInsert(x);\n int b = GetOrInsert(y);\n int c = max(max(v_cnt, a), b);\n while (v_cnt < c) graph.AddVertex(++v_cnt, 0);\n graph.AddEdge(a, b, 0);\n }\n cout << graph.VertexCount() << \" \" << graph.EdgeCount() << endl;\n graph.Save(\".\/data\/twitter\");\n return 0;\n}\n\n<|endoftext|>"} {"text":"\/\/ illarionserver - server for the game Illarion\n\/\/ Copyright 2011 Illarion e.V.\n\/\/\n\/\/ This file is part of illarionserver.\n\/\/\n\/\/ illarionserver is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ illarionserver is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with illarionserver. If not, see .\n\n\n#ifndef _WORLDMAP_HPP_\n#define _WORLDMAP_HPP_\n\n#include \n#include \n#include \n#include \"globals.hpp\"\n\nclass Field;\nclass Map;\n\nclass WorldMap {\n using map_t = std::shared_ptr;\n using map_vector_t = std::vector;\n\n map_vector_t maps;\n std::unordered_map world_map;\n size_t ageIndex = 0;\n\npublic:\n void clear();\n\n Field &at(const position &pos) const;\n Field &walkableNear(position &pos) const;\n bool intersects(const Map &map) const;\n\n bool insert(map_t newMap);\n\n bool allMapsAged();\n\n bool import(const std::string &importDir, const std::string &mapName);\n bool exportTo(const std::string &exportDir) const;\n bool loadFromDisk(const std::string &prefix);\n void saveToDisk(const std::string &prefix) const;\n bool createMap(const std::string &name, const position &origin,\n uint16_t width, uint16_t height, uint16_t tile);\n\nprivate:\n static map_t createMapFromHeaderFile(const std::string &importDir,\n const std::string &mapName);\n static int16_t readHeaderLine(const std::string &mapName, char header,\n std::ifstream &headerFile, int &lineNumber);\n static bool isCommentOrEmpty(const std::string &line);\n};\n#endif\nMake inserting maps private to WorldMap\/\/ illarionserver - server for the game Illarion\n\/\/ Copyright 2011 Illarion e.V.\n\/\/\n\/\/ This file is part of illarionserver.\n\/\/\n\/\/ illarionserver is free software: you can redistribute it and\/or modify\n\/\/ it under the terms of the GNU Affero General Public License as published by\n\/\/ the Free Software Foundation, either version 3 of the License, or\n\/\/ (at your option) any later version.\n\/\/\n\/\/ illarionserver is distributed in the hope that it will be useful,\n\/\/ but WITHOUT ANY WARRANTY; without even the implied warranty of\n\/\/ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n\/\/ GNU Affero General Public License for more details.\n\/\/\n\/\/ You should have received a copy of the GNU Affero General Public License\n\/\/ along with illarionserver. If not, see .\n\n\n#ifndef _WORLDMAP_HPP_\n#define _WORLDMAP_HPP_\n\n#include \n#include \n#include \n#include \"globals.hpp\"\n\nclass Field;\nclass Map;\n\nclass WorldMap {\n using map_t = std::shared_ptr;\n using map_vector_t = std::vector;\n\n map_vector_t maps;\n std::unordered_map world_map;\n size_t ageIndex = 0;\n\npublic:\n void clear();\n\n Field &at(const position &pos) const;\n Field &walkableNear(position &pos) const;\n bool intersects(const Map &map) const;\n\n bool allMapsAged();\n\n bool import(const std::string &importDir, const std::string &mapName);\n bool exportTo(const std::string &exportDir) const;\n bool loadFromDisk(const std::string &prefix);\n void saveToDisk(const std::string &prefix) const;\n bool createMap(const std::string &name, const position &origin,\n uint16_t width, uint16_t height, uint16_t tile);\n\nprivate:\n bool insert(map_t newMap);\n static map_t createMapFromHeaderFile(const std::string &importDir,\n const std::string &mapName);\n static int16_t readHeaderLine(const std::string &mapName, char header,\n std::ifstream &headerFile, int &lineNumber);\n static bool isCommentOrEmpty(const std::string &line);\n};\n#endif\n<|endoftext|>"} {"text":"Grabber class now receives objects names when collision<|endoftext|>"} {"text":"\/\/\r\n\/\/#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 100;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\t\tPulse(out1, sin((PI\/2) * time_to_complete));\r\n\t\t\t\tWait(sin((PI\/2) * time_to_complete));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1 * resolution);\r\n\t\t\tWait(0.5);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\nUpdate pwm.cpp\/\/\r\n\/\/#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \r\n#include \"GPIOClass.h\"\r\n\r\nusing namespace std;\r\n\r\nvoid Pulse(GPIOClass* pin, double cycles);\r\nvoid Wait(double seconds);\r\nclock_t timer;\r\ndouble time_to_complete;\r\ndouble resolution = 100;\r\n\r\n#define PI 4*atan(1)\r\n\r\nint main (int argc, char *argv[]) {\r\n\tstring type = argv[1];\r\n\ttransform(type.begin(), type.end(), type.begin(), :: tolower);\r\n\t\/\/ lets assume that the way to run this is\r\n\t\/\/ pwm.exe [rising\/falling\/sine\/constant]\r\n\tif (argc != 2) {\r\n\t\tcout << \"Usage: pwm [rising\/falling\/sine\/constant\/blink]\" << endl;\r\n\t\treturn -1;\r\n\t}\r\n\r\n\twhile (time_to_complete <= 0) {\r\n\t\tcout << \"Input How Long To Run (in seconds)\" << endl;\r\n\t\tcin >> time_to_complete;\r\n\t}\r\n\r\n\tGPIOClass* out1 = new GPIOClass(\"4\");\r\n\tGPIOClass* in2 = new GPIOClass(\"17\");\r\n\r\n\tout1->export_gpio();\r\n\tin2->export_gpio();\r\n\r\n\tout1->setdir_gpio(\"out\");\r\n\tin2->setdir_gpio(\"in\");\r\n\r\n\tcout << \"Pins are setup.\" << endl;\r\n\t\/\/ avoiding flickering will be at 100hz\r\n\t\/\/ aka turn on and off 100 times a sec\r\n\t\/\/ a cycle of 0 is off\r\n\t\/\/ a cycle of 100 is on\r\n\r\n\tif (type == \"rising\") {\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\t\tPulse(out1, sin((PI\/2) * (1\/time_to_complete)));\r\n\t\t\t\tWait(sin((PI\/2) * (1\/time_to_complete)));\r\n\t\t}\r\n\t}\r\n\tif (type == \"falling\") {\r\n\r\n\t}\r\n\tif (type == \"sine\") {\r\n\r\n\t}\r\n\tif (type == \"constant\") {\r\n\t\tout1->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(time_to_complete); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tout1->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t}\r\n\tif (type == \"blink\") { \/\/ aka. TESTR\r\n\t\tclock_t finish = clock() + time_to_complete * CLOCKS_PER_SEC;\r\n\t\twhile (clock() < finish) {\r\n\t\t\t\/\/ pulse for however long we need to to achieve brightness.\r\n\t\t\tPulse(out1, 1 * resolution);\r\n\t\t\tWait(0.5);\r\n\t\t}\r\n\t}\r\n\tcout << \"Done.\" << endl;\r\n}\r\n\r\n\/\/1 cycle is 1\/100th of a second\r\n\/\/100 cycles is 1 sec\r\nvoid Pulse(GPIOClass* pin, double cycles) {\r\n\tbool running = true;\r\n\twhile (running) {\r\n\t\tpin->setval_gpio(\"1\"); \/\/ turn the pin on\r\n\t\tWait(cycles \/ resolution); \/\/ sleep for number of cycles \/ 1\/100 sec\r\n\t\t\/\/cout << \"Waiting during pulse\" << endl;\r\n\t\tpin->setval_gpio(\"0\"); \/\/ turn the pin off\r\n\t\trunning = false; \/\/ this is unnessesary but could be useful if modified a bit.\r\n\t}\r\n}\r\n\r\nvoid Wait ( double seconds )\r\n{\r\n\tclock_t endwait;\r\n\tendwait = clock () + seconds * CLOCKS_PER_SEC ;\r\n\twhile (clock() < endwait) {}\r\n}\r\n<|endoftext|>"} {"text":"Fix voxel grid<|endoftext|>"} {"text":"\n#include \"pin.H\"\n#include \"Triton.h\"\n\n\nstatic std::string replaceEq(std::string str, const std::string from, const std::string to)\n{\n size_t start_pos = str.find(from);\n if(start_pos == std::string::npos)\n return NULL;\n str.replace(start_pos, from.length(), to);\n return str;\n}\n\n\nstatic std::string formulaReconstruction(UINT64 id)\n{\n int value;\n std::size_t found;\n std::stringstream formula;\n\n std::stringstream from;\n std::stringstream to;\n\n formula.str(symbolicEngine->getElementFromId(id)->getSource());\n while (formula.str().find(\"#\") != std::string::npos){\n\n from.str(\"\");\n to.str(\"\");\n\n found = formula.str().find(\"#\") + 1;\n std::string subs = formula.str().substr(found, std::string::npos);\n value = atoi(subs.c_str());\n from << \"#\" << value;\n to.str(symbolicEngine->getElementFromId(value)->getSource());\n\n formula.str(replaceEq(formula.str(), from.str(), to.str()));\n }\n \n return formula.str();\n}\n\n\nSolverEngine::SolverEngine(SymbolicEngine *symEngine)\n{\n this->symEngine = symEngine;\n}\n\n\nSolverEngine::~SolverEngine()\n{\n}\n\n\nVOID SolverEngine::solveFromID(UINT64 id)\n{\n std::stringstream formula;\n\n std::cout << 1 << std::endl;\n\n formula.str(formulaReconstruction(symEngine->symbolicReg[ID_ZF]));\n\n this->formula << this->symEngine->getSmt2LibVarsDecl();\n this->formula << formula.str();\n\n this->ctx = new z3::context();\n\n Z3_ast ast = Z3_parse_smtlib2_string(*this->ctx, this->formula.str().c_str(), 0, 0, 0, 0, 0, 0);\n z3::expr eq(*this->ctx, ast);\n this->solver = new z3::solver(*this->ctx);\n this->solver->add(eq);\n this->solver->check();\n}\n\n\nVOID SolverEngine::displayModel()\n{\n z3::model m = this->solver->get_model();\n std::cout << \"----- Model -----\" << std::endl << m << std::endl << \"-----------------\" << std::endl;\n}\n\n\nz3::model SolverEngine::getModel()\n{\n return this->solver->get_model();\n}\n\n\nstd::string SolverEngine::getFormula()\n{\n return this->formula.str();\n}\n\nFeature #10: Use QF_AUFBV\n#include \"pin.H\"\n#include \"Triton.h\"\n\n\nstatic std::string replaceEq(std::string str, const std::string from, const std::string to)\n{\n size_t start_pos = str.find(from);\n if(start_pos == std::string::npos)\n return NULL;\n str.replace(start_pos, from.length(), to);\n return str;\n}\n\n\nstatic std::string formulaReconstruction(UINT64 id)\n{\n int value;\n std::size_t found;\n std::stringstream formula;\n\n std::stringstream from;\n std::stringstream to;\n\n formula.str(symbolicEngine->getElementFromId(id)->getSource());\n while (formula.str().find(\"#\") != std::string::npos){\n\n from.str(\"\");\n to.str(\"\");\n\n found = formula.str().find(\"#\") + 1;\n std::string subs = formula.str().substr(found, std::string::npos);\n value = atoi(subs.c_str());\n from << \"#\" << value;\n to.str(symbolicEngine->getElementFromId(value)->getSource());\n\n formula.str(replaceEq(formula.str(), from.str(), to.str()));\n }\n \n return formula.str();\n}\n\n\nSolverEngine::SolverEngine(SymbolicEngine *symEngine)\n{\n this->symEngine = symEngine;\n}\n\n\nSolverEngine::~SolverEngine()\n{\n}\n\n\nVOID SolverEngine::solveFromID(UINT64 id)\n{\n std::stringstream formula;\n\n formula.str(formulaReconstruction(symEngine->symbolicReg[ID_ZF]));\n\n this->formula << \"(set-logic QF_AUFBV)\";\n this->formula << this->symEngine->getSmt2LibVarsDecl();\n this->formula << formula.str();\n\n this->ctx = new z3::context();\n\n Z3_ast ast = Z3_parse_smtlib2_string(*this->ctx, this->formula.str().c_str(), 0, 0, 0, 0, 0, 0);\n z3::expr eq(*this->ctx, ast);\n this->solver = new z3::solver(*this->ctx);\n this->solver->add(eq);\n this->solver->check();\n}\n\n\nVOID SolverEngine::displayModel()\n{\n z3::model m = this->solver->get_model();\n std::cout << \"----- Model -----\" << std::endl << m << std::endl << \"-----------------\" << std::endl;\n}\n\n\nz3::model SolverEngine::getModel()\n{\n return this->solver->get_model();\n}\n\n\nstd::string SolverEngine::getFormula()\n{\n return this->formula.str();\n}\n\n<|endoftext|>"} {"text":"#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP\n#define STAN_IO_ARRAY_VAR_CONTEXT_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n\nnamespace io {\n\n\/**\n * An array_var_context object represents a named arrays\n * with dimensions constructed from an array, a vector\n * of names, and a vector of all dimensions for each element.\n *\/\nclass array_var_context : public var_context {\n private:\n \/\/ Pairs\n template \n using pair_ = std::pair,\n std::vector>>;\n\n \/\/ Map holding reals\n using map_r_ = std::vector>;\n map_r_ vars_r_;\n using map_i_ = std::vector>;\n map_i_ vars_i_;\n \/\/ When search for variable name fails, return one these\n std::vector const empty_vec_r_;\n std::vector const empty_vec_i_;\n std::vector const empty_vec_ui_;\n\n template \n auto find_var_r(Str&& name) const {\n return std::find_if(vars_r_.begin(), vars_r_.end(),\n [&](auto&& element){ return element.first == name;});\n }\n\n template \n auto find_var_i(Str&& name) const {\n return std::find_if(vars_i_.begin(), vars_i_.end(),\n [&](auto&& element){ return element.first == name;});\n }\n\n \/\/ Find method\n bool contains_r_only(const std::string& name) const {\n return find_var_r(name) != vars_r_.end();\n }\n\n \/**\n * Check (1) if the vector size of dimensions is no smaller\n * than the name vector size; (2) if the size of the input\n * array is large enough for what is needed.\n *\n * @param names The names for each variable\n * @param array_size The total size of the vector holding the values we want\n * to access.\n * @param dims Vector holding the dimensions for each variable.\n * @return If the array size is equal to the number of dimensions,\n * a vector of the cumulative sum of the dimensions of each inner element of\n * dims. The return of this function is used in the add_* methods to get the\n * sequence of values For each variable.\n *\/\n\n template \n std::vector validate_dims(\n const std::vector& names, const T array_size,\n const std::vector>& dims) {\n const size_t num_par = names.size();\n if (num_par > dims.size()) {\n std::stringstream msg;\n msg << \"size of vector of dimensions (found \" << dims.size() << \") \"\n << \"should be no smaller than number of parameters (found \" << num_par\n << \").\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n std::vector elem_dims_total(dims.size() + 1);\n elem_dims_total[0] = 0;\n int i = 0;\n for (i = 0; i < dims.size(); i++) {\n elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(),\n 1, std::multiplies());\n elem_dims_total[i + 1] += elem_dims_total[i];\n }\n if (elem_dims_total[i] > array_size) {\n std::stringstream msg;\n msg << \"array is not long enough for all elements: \" << array_size\n << \" is found, but \" << elem_dims_total[i] << \" is needed.\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n return elem_dims_total;\n }\n\n \/**\n * Adds a set of floating point variables to the floating point map.\n * @param names Names of each variable.\n * @param values The real values of variable in a contiguous\n * column major order container.\n * @param dims the dimensions for each variable.\n *\/\n void add_r(const std::vector& names,\n const std::vector& values,\n const std::vector>& dims) {\n std::vector dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_[i] =\n {names[i], {{values.data() + dim_vec[i],\n values.data() + dim_vec[i + 1]}, dims[i]}};\n }\n }\n\n void add_r(const std::vector& names,\n const Eigen::VectorXd& values,\n const std::vector>& dims) {\n std::vector dim_vec = validate_dims(names, values.size(), dims);\n using val_d_t = decltype(values.data());\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_[i] =\n {names[i], {{values.data() + dim_vec[i],\n values.data() + dim_vec[i + 1]}, dims[i]}};\n }\n }\n\n \/**\n * Adds a set of integer variables to the integer map.\n * @param names Names of each variable.\n * @param values The integer values of variable in a vector.\n * @param dims the dimensions for each variable.\n *\/\n void add_i(const std::vector& names,\n const std::vector& values,\n const std::vector>& dims) {\n std::vector dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_i_[i] =\n {names[i], {{values.data() + dim_vec[i],\n values.data() + dim_vec[i + 1]}, dims[i]}};\n }\n }\n\n public:\n \/**\n * Construct an array_var_context from only real value arrays.\n *\n * @param names_r names for each element\n * @param values_r a vector of double values for all elements\n * @param dim_r a vector of dimensions\n *\/\n array_var_context(const std::vector& names_r,\n const std::vector& values_r,\n const std::vector>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Construct an array_var_context from only integer value arrays.\n *\n * @param names_i names for each element\n * @param values_i a vector of integer values for all elements\n * @param dim_i a vector of dimensions\n *\/\n array_var_context(const std::vector& names_i,\n const std::vector& values_i,\n const std::vector>& dim_i)\n : vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n }\n\n \/**\n * Construct an array_var_context from arrays of both double\n * and integer separately\n *\n *\/\n array_var_context(const std::vector& names_r,\n const std::vector& values_r,\n const std::vector>& dim_r,\n const std::vector& names_i,\n const std::vector& values_i,\n const std::vector>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector>& dim_r,\n const std::vector& names_i,\n const std::vector& values_i,\n const std::vector>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Return true<\/code> if this dump contains the specified\n * variable name is defined. This method returns true<\/code>\n * even if the values are all integers.\n *\n * @param name Variable name to test.\n * @return true<\/code> if the variable exists.\n *\/\n bool contains_r(const std::string& name) const {\n return contains_r_only(name) || contains_i(name);\n }\n\n \/**\n * Return true<\/code> if this dump contains an integer\n * valued array with the specified name.\n *\n * @param name Variable name to test.\n * @return true<\/code> if the variable name has an integer\n * array value.\n *\/\n bool contains_i(const std::string& name) const {\n return find_var_i(name) != vars_i_.end();\n }\n\n \/**\n * Return the double values for the variable with the specified\n * name or null.\n *\n * @param name Name of variable.\n * @return Values of variable.\n *\n *\/\n std::vector vals_r(const std::string& name) const {\n auto ret_val_r = find_var_r(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.first;\n } else {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return {ret_val_i->second.first.begin(), ret_val_i->second.first.end()};\n }\n }\n return empty_vec_r_;\n }\n\n \/**\n * Return the dimensions for the double variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector dims_r(const std::string& name) const {\n auto ret_val_r = find_var_r(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.second;\n } else {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return the integer values for the variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Values.\n *\/\n std::vector vals_i(const std::string& name) const {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.first;\n }\n return empty_vec_i_;\n }\n\n \/**\n * Return the dimensions for the integer variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector dims_i(const std::string& name) const {\n auto ret_val_i = find_var_i(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return a list of the names of the floating point variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_r(std::vector& names) const {\n names.clear();\n for (const auto& vars_r_iter : vars_r_) {\n names.push_back(vars_r_iter.first);\n }\n }\n\n \/**\n * Return a list of the names of the integer variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_i(std::vector& names) const {\n names.clear();\n for (const auto& vars_i_iter : vars_r_) {\n names.push_back(vars_i_iter.first);\n }\n }\n\n \/**\n * Remove variable from the object.\n *\n * @param name Name of the variable to remove.\n * @return If variable is removed returns true<\/code>, else\n * returns false<\/code>.\n *\/\n bool remove(const std::string& name) {\n vars_i_.erase(find_var_i(name));\n vars_r_.erase(find_var_r(name));\n return true;\n }\n};\n} \/\/ namespace io\n} \/\/ namespace stan\n#endif\ntesting with an unordered map and emplace#ifndef STAN_IO_ARRAY_VAR_CONTEXT_HPP\n#define STAN_IO_ARRAY_VAR_CONTEXT_HPP\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace stan {\n\nnamespace io {\n\n\/**\n * An array_var_context object represents a named arrays\n * with dimensions constructed from an array, a vector\n * of names, and a vector of all dimensions for each element.\n *\/\nclass array_var_context : public var_context {\n private:\n \/\/ Pairs\n template \n using pair_ = std::pair, std::vector>;\n\n \/\/ Map holding reals\n using map_r_ = std::unordered_map>;\n map_r_ vars_r_;\n using map_i_ = std::unordered_map>;\n map_i_ vars_i_;\n \/\/ When search for variable name fails, return one these\n std::vector const empty_vec_r_{0};\n std::vector const empty_vec_i_{0};\n std::vector const empty_vec_ui_{0};\n\n\n \/\/ Find method\n bool contains_r_only(const std::string& name) const {\n return vars_r_.find(name) != vars_r_.end();\n }\n\n \/**\n * Check (1) if the vector size of dimensions is no smaller\n * than the name vector size; (2) if the size of the input\n * array is large enough for what is needed.\n *\n * @param names The names for each variable\n * @param array_size The total size of the vector holding the values we want\n * to access.\n * @param dims Vector holding the dimensions for each variable.\n * @return If the array size is equal to the number of dimensions,\n * a vector of the cumulative sum of the dimensions of each inner element of\n * dims. The return of this function is used in the add_* methods to get the\n * sequence of values For each variable.\n *\/\n\n template \n std::vector validate_dims(\n const std::vector& names, const T array_size,\n const std::vector>& dims) {\n const size_t num_par = names.size();\n if (num_par > dims.size()) {\n std::stringstream msg;\n msg << \"size of vector of dimensions (found \" << dims.size() << \") \"\n << \"should be no smaller than number of parameters (found \" << num_par\n << \").\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n std::vector elem_dims_total(dims.size() + 1);\n elem_dims_total[0] = 0;\n int i = 0;\n for (i = 0; i < dims.size(); i++) {\n elem_dims_total[i + 1] = std::accumulate(dims[i].begin(), dims[i].end(),\n 1, std::multiplies())\n + elem_dims_total[i];;\n }\n if (elem_dims_total[i] > array_size) {\n std::stringstream msg;\n msg << \"array is not long enough for all elements: \" << array_size\n << \" is found, but \" << elem_dims_total[i] << \" is needed.\";\n BOOST_THROW_EXCEPTION(std::invalid_argument(msg.str()));\n }\n return elem_dims_total;\n }\n\n \/**\n * Adds a set of floating point variables to the floating point map.\n * @param names Names of each variable.\n * @param values The real values of variable in a contiguous\n * column major order container.\n * @param dims the dimensions for each variable.\n *\/\n void add_r(const std::vector& names,\n const std::vector& values,\n const std::vector>& dims) {\n std::vector dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_r_.emplace(names[i], pair_{{values.data() + dim_vec[i],\n values.data() + dim_vec[i + 1]}, dims[i]});\n }\n }\n\n void add_r(const std::vector& names,\n const Eigen::VectorXd& values,\n const std::vector>& dims) {\n std::vector dim_vec = validate_dims(names, values.size(), dims);\n const auto name_size = names.size();\n for (size_t i = 0; i < name_size; i++) {\n vars_r_.emplace(names[i], pair_{{values.data() + dim_vec[i],\n values.data() + dim_vec[i + 1]}, dims[i]});\n }\n }\n\n \/**\n * Adds a set of integer variables to the integer map.\n * @param names Names of each variable.\n * @param values The integer values of variable in a vector.\n * @param dims the dimensions for each variable.\n *\/\n void add_i(const std::vector& names,\n const std::vector& values,\n const std::vector>& dims) {\n std::vector dim_vec = validate_dims(names, values.size(), dims);\n for (size_t i = 0; i < names.size(); i++) {\n vars_i_.emplace(names[i], pair_{{values.data() + dim_vec[i],\n values.data() + dim_vec[i + 1]}, dims[i]});\n }\n }\n\n public:\n \/**\n * Construct an array_var_context from only real value arrays.\n *\n * @param names_r names for each element\n * @param values_r a vector of double values for all elements\n * @param dim_r a vector of dimensions\n *\/\n array_var_context(const std::vector& names_r,\n const std::vector& values_r,\n const std::vector>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector>& dim_r)\n : vars_r_(names_r.size()) {\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Construct an array_var_context from only integer value arrays.\n *\n * @param names_i names for each element\n * @param values_i a vector of integer values for all elements\n * @param dim_i a vector of dimensions\n *\/\n array_var_context(const std::vector& names_i,\n const std::vector& values_i,\n const std::vector>& dim_i)\n : vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n }\n\n \/**\n * Construct an array_var_context from arrays of both double\n * and integer separately\n *\n *\/\n array_var_context(const std::vector& names_r,\n const std::vector& values_r,\n const std::vector>& dim_r,\n const std::vector& names_i,\n const std::vector& values_i,\n const std::vector>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n array_var_context(const std::vector& names_r,\n const Eigen::VectorXd& values_r,\n const std::vector>& dim_r,\n const std::vector& names_i,\n const std::vector& values_i,\n const std::vector>& dim_i)\n : vars_r_(names_r.size()), vars_i_(names_i.size()) {\n add_i(names_i, values_i, dim_i);\n add_r(names_r, values_r, dim_r);\n }\n\n \/**\n * Return true<\/code> if this dump contains the specified\n * variable name is defined. This method returns true<\/code>\n * even if the values are all integers.\n *\n * @param name Variable name to test.\n * @return true<\/code> if the variable exists.\n *\/\n bool contains_r(const std::string& name) const {\n return contains_r_only(name) || contains_i(name);\n }\n\n \/**\n * Return true<\/code> if this dump contains an integer\n * valued array with the specified name.\n *\n * @param name Variable name to test.\n * @return true<\/code> if the variable name has an integer\n * array value.\n *\/\n bool contains_i(const std::string& name) const {\n return vars_i_.find(name) != vars_i_.end();\n }\n\n \/**\n * Return the double values for the variable with the specified\n * name or null.\n *\n * @param name Name of variable.\n * @return Values of variable.\n *\n *\/\n std::vector vals_r(const std::string& name) const {\n const auto ret_val_r = vars_r_.find(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.first;\n } else {\n const auto ret_val_i = vars_i_.find(name);\n if (ret_val_i != vars_i_.end()) {\n return {ret_val_i->second.first.begin(), ret_val_i->second.first.end()};\n }\n }\n return empty_vec_r_;\n }\n\n \/**\n * Return the dimensions for the double variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector dims_r(const std::string& name) const {\n const auto ret_val_r = vars_r_.find(name);\n if (ret_val_r != vars_r_.end()) {\n return ret_val_r->second.second;\n } else {\n const auto ret_val_i = vars_i_.find(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return the integer values for the variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Values.\n *\/\n std::vector vals_i(const std::string& name) const {\n auto ret_val_i = vars_i_.find(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.first;\n }\n return empty_vec_i_;\n }\n\n \/**\n * Return the dimensions for the integer variable with the specified\n * name.\n *\n * @param name Name of variable.\n * @return Dimensions of variable.\n *\/\n std::vector dims_i(const std::string& name) const {\n auto ret_val_i = vars_i_.find(name);\n if (ret_val_i != vars_i_.end()) {\n return ret_val_i->second.second;\n }\n return empty_vec_ui_;\n }\n\n \/**\n * Return a list of the names of the floating point variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_r(std::vector& names) const {\n names.clear();\n names.reserve(vars_r_.size());\n for (const auto& vars_r_iter : vars_r_) {\n names.push_back(vars_r_iter.first);\n }\n }\n\n \/**\n * Return a list of the names of the integer variables in\n * the dump.\n *\n * @param names Vector to store the list of names in.\n *\/\n virtual void names_i(std::vector& names) const {\n names.clear();\n names.reserve(vars_i_.size());\n for (const auto& vars_i_iter : vars_r_) {\n names.push_back(vars_i_iter.first);\n }\n }\n\n \/**\n * Remove variable from the object.\n *\n * @param name Name of the variable to remove.\n * @return If variable is removed returns true<\/code>, else\n * returns false<\/code>.\n *\/\n bool remove(const std::string& name) {\n vars_i_.erase(name);\n vars_r_.erase(name);\n return true;\n }\n};\n} \/\/ namespace io\n} \/\/ namespace stan\n#endif\n<|endoftext|>"} {"text":"\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n\n#define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \\\n SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \\\n \"Timer \" #NAME \" still running in amrreset\"); \\\n sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \\\n (ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \\\n} while (0)\n\n\nstatic\nvoid delete_ghost_patches(fclaw2d_domain_t* domain)\n{\n for(int i = 0; i < domain->num_ghost_patches; i++)\n {\n fclaw2d_patch_t* ghost_patch = &domain->ghost_patches[i];\n\n fclaw2d_patch_delete_cp(ghost_patch);\n fclaw2d_patch_delete_data(ghost_patch);\n }\n}\n\n\nvoid amrreset(fclaw2d_domain_t **domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (*domain);\n\n for(int i = 0; i < (*domain)->num_blocks; i++)\n {\n fclaw2d_block_t *block = (*domain)->blocks + i;\n fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user;\n\n for(int j = 0; j < block->num_patches; j++)\n {\n fclaw2d_patch_t *patch = block->patches + j;\n fclaw2d_patch_delete_cp(patch);\n fclaw2d_patch_delete_data(patch);\n#if 0\n fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;\n delete pdata->cp;\n pdata->cp = NULL;\n FCLAW2D_FREE (pdata);\n patch->user = NULL;\n#endif\n ++ddata->count_delete_clawpatch;\n }\n\n FCLAW2D_FREE (bd);\n block->user = NULL;\n }\n\n \/\/ Free old parallel ghost patch data structure, must exist by construction.\n delete_ghost_patches(*domain);\n fclaw2d_domain_exchange_t *e_old = fclaw2d_partition_get_exchange_data(*domain);\n fclaw2d_domain_free_after_exchange (*domain, e_old);\n\n \/\/ Output memory discrepancy for the ClawPatch\n if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) {\n printf (\"[%d] This domain had Clawpatch set %d and deleted %d times\\n\",\n (*domain)->mpirank,\n ddata->count_set_clawpatch, ddata->count_delete_clawpatch);\n }\n\n \/\/ Evaluate timers if this domain has not been superseded yet.\n if (ddata->is_latest_domain) {\n sc_statinfo_t stats[FCLAW2D_TIMER_COUNT];\n\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);\n\n FCLAW2D_STATS_SET (stats, ddata, INIT);\n FCLAW2D_STATS_SET (stats, ddata, REGRID);\n FCLAW2D_STATS_SET (stats, ddata, OUTPUT);\n FCLAW2D_STATS_SET (stats, ddata, CHECK);\n FCLAW2D_STATS_SET (stats, ddata, ADVANCE);\n FCLAW2D_STATS_SET (stats, ddata, EXCHANGE);\n FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);\n FCLAW2D_STATS_SET (stats, ddata, WALLTIME);\n sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED],\n ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative -\n (ddata->timers[FCLAW2D_TIMER_INIT].cumulative +\n ddata->timers[FCLAW2D_TIMER_REGRID].cumulative +\n ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative +\n ddata->timers[FCLAW2D_TIMER_CHECK].cumulative +\n ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative +\n ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative),\n \"UNACCOUNTED\");\n sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats);\n sc_stats_print (sc_package_id, SC_LP_PRODUCTION, FCLAW2D_TIMER_COUNT,\n stats, 1, 0);\n SC_GLOBAL_PRODUCTIONF (\"Procs %d advance %d %g exchange %d %g \"\n \"regrid %d %g\\n\", (*domain)->mpisize,\n ddata->count_amr_advance,\n stats[FCLAW2D_TIMER_ADVANCE].average,\n ddata->count_ghost_exchange,\n stats[FCLAW2D_TIMER_EXCHANGE].average,\n ddata->count_amr_regrid,\n stats[FCLAW2D_TIMER_REGRID].average);\n SC_GLOBAL_PRODUCTIONF (\"Max\/P %d advance %d %g exchange %d %g \"\n \"regrid %d %g\\n\", (*domain)->mpisize,\n ddata->count_amr_advance,\n stats[FCLAW2D_TIMER_ADVANCE].max,\n ddata->count_ghost_exchange,\n stats[FCLAW2D_TIMER_EXCHANGE].max,\n ddata->count_amr_regrid,\n stats[FCLAW2D_TIMER_REGRID].max);\n }\n\n\n delete_domain_data(*domain); \/\/ Delete allocated pointers to set of functions.\n\n fclaw2d_domain_destroy(*domain);\n *domain = NULL;\n}\nLowered log level for timing stats output at end of run\/*\nCopyright (c) 2012 Carsten Burstedde, Donna Calhoun\nAll rights reserved.\n\nRedistribution and use in source and binary forms, with or without\nmodification, are permitted provided that the following conditions are met:\n\n * Redistributions of source code must retain the above copyright notice, this\nlist of conditions and the following disclaimer.\n * Redistributions in binary form must reproduce the above copyright notice,\nthis list of conditions and the following disclaimer in the documentation\nand\/or other materials provided with the distribution.\n\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE\nFOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\nDAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\nSERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\nCAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,\nOR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\nOF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n*\/\n\n#include \n#include \n#include \n\n#include \n\n#define FCLAW2D_STATS_SET(stats,ddata,NAME) do { \\\n SC_CHECK_ABORT (!(ddata)->timers[FCLAW2D_TIMER_ ## NAME].running, \\\n \"Timer \" #NAME \" still running in amrreset\"); \\\n sc_stats_set1 ((stats) + FCLAW2D_TIMER_ ## NAME, \\\n (ddata)->timers[FCLAW2D_TIMER_ ## NAME].cumulative, #NAME); \\\n} while (0)\n\n\nstatic\nvoid delete_ghost_patches(fclaw2d_domain_t* domain)\n{\n for(int i = 0; i < domain->num_ghost_patches; i++)\n {\n fclaw2d_patch_t* ghost_patch = &domain->ghost_patches[i];\n\n fclaw2d_patch_delete_cp(ghost_patch);\n fclaw2d_patch_delete_data(ghost_patch);\n }\n}\n\n\nvoid amrreset(fclaw2d_domain_t **domain)\n{\n fclaw2d_domain_data_t *ddata = get_domain_data (*domain);\n\n for(int i = 0; i < (*domain)->num_blocks; i++)\n {\n fclaw2d_block_t *block = (*domain)->blocks + i;\n fclaw2d_block_data_t *bd = (fclaw2d_block_data_t *) block->user;\n\n for(int j = 0; j < block->num_patches; j++)\n {\n fclaw2d_patch_t *patch = block->patches + j;\n fclaw2d_patch_delete_cp(patch);\n fclaw2d_patch_delete_data(patch);\n#if 0\n fclaw2d_patch_data_t *pdata = (fclaw2d_patch_data_t *) patch->user;\n delete pdata->cp;\n pdata->cp = NULL;\n FCLAW2D_FREE (pdata);\n patch->user = NULL;\n#endif\n ++ddata->count_delete_clawpatch;\n }\n\n FCLAW2D_FREE (bd);\n block->user = NULL;\n }\n\n \/\/ Free old parallel ghost patch data structure, must exist by construction.\n delete_ghost_patches(*domain);\n fclaw2d_domain_exchange_t *e_old = fclaw2d_partition_get_exchange_data(*domain);\n fclaw2d_domain_free_after_exchange (*domain, e_old);\n\n \/\/ Output memory discrepancy for the ClawPatch\n if (ddata->count_set_clawpatch != ddata->count_delete_clawpatch) {\n printf (\"[%d] This domain had Clawpatch set %d and deleted %d times\\n\",\n (*domain)->mpirank,\n ddata->count_set_clawpatch, ddata->count_delete_clawpatch);\n }\n\n \/\/ Evaluate timers if this domain has not been superseded yet.\n if (ddata->is_latest_domain) {\n sc_statinfo_t stats[FCLAW2D_TIMER_COUNT];\n\n fclaw2d_timer_stop (&ddata->timers[FCLAW2D_TIMER_WALLTIME]);\n\n FCLAW2D_STATS_SET (stats, ddata, INIT);\n FCLAW2D_STATS_SET (stats, ddata, REGRID);\n FCLAW2D_STATS_SET (stats, ddata, OUTPUT);\n FCLAW2D_STATS_SET (stats, ddata, CHECK);\n FCLAW2D_STATS_SET (stats, ddata, ADVANCE);\n FCLAW2D_STATS_SET (stats, ddata, EXCHANGE);\n FCLAW2D_STATS_SET (stats, ddata, BUILDPATCHES);\n FCLAW2D_STATS_SET (stats, ddata, WALLTIME);\n sc_stats_set1 (&stats[FCLAW2D_TIMER_UNACCOUNTED],\n ddata->timers[FCLAW2D_TIMER_WALLTIME].cumulative -\n (ddata->timers[FCLAW2D_TIMER_INIT].cumulative +\n ddata->timers[FCLAW2D_TIMER_REGRID].cumulative +\n ddata->timers[FCLAW2D_TIMER_OUTPUT].cumulative +\n ddata->timers[FCLAW2D_TIMER_CHECK].cumulative +\n ddata->timers[FCLAW2D_TIMER_ADVANCE].cumulative +\n ddata->timers[FCLAW2D_TIMER_EXCHANGE].cumulative),\n \"UNACCOUNTED\");\n sc_stats_compute ((*domain)->mpicomm, FCLAW2D_TIMER_COUNT, stats);\n sc_stats_print (sc_package_id, SC_LP_ESSENTIAL, FCLAW2D_TIMER_COUNT,\n stats, 1, 0);\n SC_GLOBAL_ESSENTIALF (\"Procs %d advance %d %g exchange %d %g \"\n \"regrid %d %g\\n\", (*domain)->mpisize,\n ddata->count_amr_advance,\n stats[FCLAW2D_TIMER_ADVANCE].average,\n ddata->count_ghost_exchange,\n stats[FCLAW2D_TIMER_EXCHANGE].average,\n ddata->count_amr_regrid,\n stats[FCLAW2D_TIMER_REGRID].average);\n SC_GLOBAL_ESSENTIALF (\"Max\/P %d advance %d %g exchange %d %g \"\n \"regrid %d %g\\n\", (*domain)->mpisize,\n ddata->count_amr_advance,\n stats[FCLAW2D_TIMER_ADVANCE].max,\n ddata->count_ghost_exchange,\n stats[FCLAW2D_TIMER_EXCHANGE].max,\n ddata->count_amr_regrid,\n stats[FCLAW2D_TIMER_REGRID].max);\n }\n\n\n delete_domain_data(*domain); \/\/ Delete allocated pointers to set of functions.\n\n fclaw2d_domain_destroy(*domain);\n *domain = NULL;\n}\n<|endoftext|>"} {"text":"#include \"Text.h\"\n\nnamespace hm\n{\n\tText::Text()\n\t{\n\t\t\/\/ Initialize.\n\t\tfont = NULL;\n\t\tsdltext = NULL;\n\t\ttext = \"Hume Library\";\n\t}\n\n\tText::Text(Font *font)\n\t{\n\t\t\/\/ Initialize and set default text.\n\t\tthis->font = font;\n\t\tsdltext = NULL;\n\t\ttext = \"Hume Library\";\n\t\tstd::cout << \"constructor invoked and calling updateSurface()\" << std::endl;\n\t\tupdateSurface();\n\t}\n\n\tText::Text(std::string text, Font *font)\n\t{\n\t\t\/\/ Initialize and set custom text.\n\t\tthis->font = font;\n\t\tsdltext = NULL;\n\t\tthis->text = text;\n\t\tupdateSurface();\n\t}\n\n\tSDL_Surface* Text::getSurface()\n\t{\n\t\treturn sdltext;\n\t}\n\n\tvoid Text::setText(std::string text)\n\t{\n\t\tthis->text = text;\n\t\tupdateSurface();\n\t}\n\n\tstd::string Text::getText()\n\t{\n\t\treturn text;\n\t}\n\n\tvoid Text::setPosition(int x, int y)\n\t{\n\t\tposition.x = x;\n\t\tposition.y = y;\n\n\t\treturn;\n\t}\n\n\tSDL_Rect* Text::getPosition()\n\t{\n\t\treturn &position;\n\t}\n\n\tvoid Text::updateSurface()\n\t{\n\t\t\/\/ See if TTF_WasInit().\n\t\tif(TTF_WasInit() == 0)\n\t\t{\n\t\t\tstd::cout << \"SDL_ttf was not initialized. Cannot update surface.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t\tstd::cout << \"SDL_ttf was initialized. Continuing...\" << std::endl;\n\n\t\t\/\/ Check if the font is null.\n\t\tif(font == NULL)\n\t\t{\n\t\t\tstd::cout << \"Cannot update surface. Font is nulled.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Output.\n\t\tstd::cout << \"Font: \" << font << std::endl;\n\t\tstd::cout << \"Text: \" << text.c_str() << std::endl;\n\t\tstd::cout << \"FGColor: \" << font->getFgColor().r << \", \" << font->getFgColor().g << \", \" << font->getFgColor().b << std::endl;\n\t\tstd::cout << \"BGColor: \" << font->getBgColor().r << \", \" << font->getBgColor().g << \", \" << font->getBgColor().b << std::endl;\n\n\t\tif(font->getRenderMode() == SOLID)\n\t\t{\n\t\t\tstd::cout << \"Rendering text solid...\" << std::endl;\n\t\t\tsdltext = TTF_RenderText_Solid(font->getFont(), text.c_str(), font->getFgColor());\n\t\t}\n\t\tif(font->getRenderMode() == SHADED)\n\t\t{\n\t\t\tstd::cout << \"Rendering text shaded...\" << std::endl;\n\t\t\tsdltext = TTF_RenderText_Shaded(font->getFont(), text.c_str(), font->getFgColor(), font->getBgColor());\n\t\t}\n\t\tif(font->getRenderMode() == BLENDED)\n\t\t{\n\t\t\tstd::cout << \"Rendering text blended...\" << std::endl;\n\t\t\tsdltext = TTF_RenderText_Blended(font->getFont(), text.c_str(), font->getFgColor());\n\t\t}\n\n\t\tstd::cout << \"Surface is located at \" << sdltext << \".\" << std::endl;\n\n\t\treturn;\n\t}\n}\nGot rid of output of TTF_RenderText_*() parameters.#include \"Text.h\"\n\nnamespace hm\n{\n\tText::Text()\n\t{\n\t\t\/\/ Initialize.\n\t\tfont = NULL;\n\t\tsdltext = NULL;\n\t\ttext = \"Hume Library\";\n\t}\n\n\tText::Text(Font *font)\n\t{\n\t\t\/\/ Initialize and set default text.\n\t\tthis->font = font;\n\t\tsdltext = NULL;\n\t\ttext = \"Hume Library\";\n\t\tstd::cout << \"constructor invoked and calling updateSurface()\" << std::endl;\n\t\tupdateSurface();\n\t}\n\n\tText::Text(std::string text, Font *font)\n\t{\n\t\t\/\/ Initialize and set custom text.\n\t\tthis->font = font;\n\t\tsdltext = NULL;\n\t\tthis->text = text;\n\t\tupdateSurface();\n\t}\n\n\tSDL_Surface* Text::getSurface()\n\t{\n\t\treturn sdltext;\n\t}\n\n\tvoid Text::setText(std::string text)\n\t{\n\t\tthis->text = text;\n\t\tupdateSurface();\n\t}\n\n\tstd::string Text::getText()\n\t{\n\t\treturn text;\n\t}\n\n\tvoid Text::setPosition(int x, int y)\n\t{\n\t\tposition.x = x;\n\t\tposition.y = y;\n\n\t\treturn;\n\t}\n\n\tSDL_Rect* Text::getPosition()\n\t{\n\t\treturn &position;\n\t}\n\n\tvoid Text::updateSurface()\n\t{\n\t\t\/\/ See if TTF_WasInit().\n\t\tif(TTF_WasInit() == 0)\n\t\t{\n\t\t\tstd::cout << \"SDL_ttf was not initialized. Cannot update surface.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\t\telse\n\t\t\tstd::cout << \"SDL_ttf was initialized. Continuing...\" << std::endl;\n\n\t\t\/\/ Check if the font is null.\n\t\tif(font == NULL)\n\t\t{\n\t\t\tstd::cout << \"Cannot update surface. Font is nulled.\" << std::endl;\n\t\t\treturn;\n\t\t}\n\n\t\t\/\/ Output.\n\t\tstd::cout << \"Font: \" << font << std::endl;\n std::cout << \"Text: \" << text.c_str() << std::endl;\n\n\t\tif(font->getRenderMode() == SOLID)\n\t\t{\n\t\t\tstd::cout << \"Rendering text solid...\" << std::endl;\n\t\t\tsdltext = TTF_RenderText_Solid(font->getFont(), text.c_str(), font->getFgColor());\n\t\t}\n\t\tif(font->getRenderMode() == SHADED)\n\t\t{\n\t\t\tstd::cout << \"Rendering text shaded...\" << std::endl;\n\t\t\tsdltext = TTF_RenderText_Shaded(font->getFont(), text.c_str(), font->getFgColor(), font->getBgColor());\n\t\t}\n\t\tif(font->getRenderMode() == BLENDED)\n\t\t{\n\t\t\tstd::cout << \"Rendering text blended...\" << std::endl;\n\t\t\tsdltext = TTF_RenderText_Blended(font->getFont(), text.c_str(), font->getFgColor());\n\t\t}\n\n\t\tstd::cout << \"Surface is located at \" << sdltext << \".\" << std::endl;\n\n\t\treturn;\n\t}\n}\n<|endoftext|>"} {"text":"\/* \n * File: Zone.cpp\n * Author: Aztyu\n * \n * Created on 22 décembre 2014, 15:50\n *\/\n\n#include \"Zone.h\"\n\nusing namespace std;\n\nZone::Zone(char* name){\n zone_name = name;\n tableau.reserve(10);\n \n for(int i=0; i < 8; i++){\n type_number[i] = 0;\n }\n \n cout << \"Creation de la zone \" << zone_name << endl;\n}\n\nZone::Zone(const Zone& orig) {\n}\n\nZone::~Zone() {\n}\n\nvoid Zone::addObjet(Objet* objet){\n tableau.push_back(objet);\n}\n\nvoid Zone::removeObjet(int index){\n tableau[index]->getSceneNode()->remove();\n delete tableau[index]->getPointer();\n tableau.erase(tableau.begin()+index);\n}\n\nvoid Zone::createObjet(object form){\n char name[50];\n string type = \"ressources\/\";\n switch((int)form){\n case 0:\n if(type_number[0] > 0){\n sprintf (name, \"Rectangle%d\", type_number[0]);\n }else{\n sprintf (name, \"Rectangle\");\n }\n type += \"rectangle\";\n type_number[0]++;\n break;\n case 1:\n if(type_number[1] > 0){\n sprintf (name, \"Line%d\", type_number[1]);\n }else{\n sprintf (name, \"Line\");\n }\n type += \"line\";\n type_number[1]++;\n break;\n case 2:\n if(type_number[2] > 0){\n sprintf (name, \"Circle%d\", type_number[2]);\n }else{\n sprintf (name, \"Circle\");\n }\n type += \"circle\";\n type_number[2]++;\n break;\n case 3:\n if(type_number[3] > 0){\n sprintf (name, \"Trapeze%d\", type_number[3]);\n }else{\n sprintf (name, \"Trapeze\");\n }\n type += \"trapeze\";\n type_number[3]++;\n break;\n case 4:\n if(type_number[4] > 0){\n sprintf (name, \"Cube%d\", type_number[4]);\n }else{\n sprintf (name, \"Cube\");\n }\n type += \"cube\";\n type_number[4]++;\n break;\n case 5:\n if(type_number[5] > 0){\n sprintf (name, \"Pyramid%d\", type_number[5]);\n }else{\n sprintf (name, \"Pyramid\");\n }\n type += \"pyramide\";\n type_number[5]++;\n break;\n case 6:\n if(type_number[6] > 0){\n sprintf (name, \"Sphere%d\", type_number[6]);\n }else{\n sprintf (name, \"Sphere\");\n }\n type += \"sphere\";\n type_number[6]++;\n break;\n case 7:\n if(type_number[7] > 0){\n sprintf (name, \"Cylinder%d\", type_number[7]);\n }else{\n sprintf (name, \"Cylinder\");\n }\n type += \"cylinder\";\n type_number[7]++;\n break;\n }\n type += \".obj\";\n tableau.push_back(new Objet(current_scene->addMeshSceneNode(current_scene->getMesh(type.c_str())), name));\n wchar_t buffer [100];\n swprintf( buffer, 100, L\"%s\", name);\n \/\/box_global->addItem(buffer);\n}\n\nint Zone::getObjectCount(){\n return tableau.size();\n}\n\nvoid Zone::printZone(){\n cout << \"La zone s'appelle \" << zone_name << endl;\n for(int i=0; i < tableau.size(); i++){\n tableau[i]->printObjet();\n }\n}\n\nObjet* Zone::getObjetPointer(int index){\n if(index >= 0 && index < tableau.size()){\n return tableau[index];\n }else{\n return 0;\n }\n}\n\nZone* Zone::getPointer(){\n return this;\n}\n\nforgot one file\/* \n * File: Zone.cpp\n * Author: Aztyu\n * \n * Created on 22 décembre 2014, 15:50\n *\/\n\n#include \"Zone.h\"\n\nusing namespace std;\n\nZone::Zone(char* name, irr::scene::ISceneManager* scene){\n zone_name = name;\n tableau.reserve(10);\n \n for(int i=0; i < 8; i++){\n type_number[i] = 0;\n }\n current_scene = scene;\n \n cout << \"Creation de la zone \" << zone_name << endl;\n}\n\nZone::Zone(const Zone& orig) {\n}\n\nZone::~Zone() {\n}\n\nvoid Zone::addObjet(Objet* objet){\n tableau.push_back(objet);\n}\n\nvoid Zone::removeObjet(int index){\n tableau[index]->getSceneNode()->remove();\n delete tableau[index]->getPointer();\n tableau.erase(tableau.begin()+index);\n}\n\nvoid Zone::createObjet(object form){\n char name[50];\n string type = \"ressources\/\";\n switch((int)form){\n case 0:\n if(type_number[0] > 0){\n sprintf (name, \"Rectangle%d\", type_number[0]);\n }else{\n sprintf (name, \"Rectangle\");\n }\n type += \"rectangle\";\n type_number[0]++;\n break;\n case 1:\n if(type_number[1] > 0){\n sprintf (name, \"Line%d\", type_number[1]);\n }else{\n sprintf (name, \"Line\");\n }\n type += \"line\";\n type_number[1]++;\n break;\n case 2:\n if(type_number[2] > 0){\n sprintf (name, \"Circle%d\", type_number[2]);\n }else{\n sprintf (name, \"Circle\");\n }\n type += \"circle\";\n type_number[2]++;\n break;\n case 3:\n if(type_number[3] > 0){\n sprintf (name, \"Trapeze%d\", type_number[3]);\n }else{\n sprintf (name, \"Trapeze\");\n }\n type += \"trapeze\";\n type_number[3]++;\n break;\n case 4:\n if(type_number[4] > 0){\n sprintf (name, \"Cube%d\", type_number[4]);\n }else{\n sprintf (name, \"Cube\");\n }\n type += \"cube\";\n type_number[4]++;\n break;\n case 5:\n if(type_number[5] > 0){\n sprintf (name, \"Pyramid%d\", type_number[5]);\n }else{\n sprintf (name, \"Pyramid\");\n }\n type += \"pyramide\";\n type_number[5]++;\n break;\n case 6:\n if(type_number[6] > 0){\n sprintf (name, \"Sphere%d\", type_number[6]);\n }else{\n sprintf (name, \"Sphere\");\n }\n type += \"sphere\";\n type_number[6]++;\n break;\n case 7:\n if(type_number[7] > 0){\n sprintf (name, \"Cylinder%d\", type_number[7]);\n }else{\n sprintf (name, \"Cylinder\");\n }\n type += \"cylinder\";\n type_number[7]++;\n break;\n }\n type += \".obj\";\n tableau.push_back(new Objet(current_scene->addMeshSceneNode(current_scene->getMesh(type.c_str())), name));\n \/\/wchar_t buffer [100];\n \/\/swprintf( buffer, 100, L\"%s\", name);\n \/\/box_global->addItem(buffer);\n}\n\nint Zone::getObjectCount(){\n return tableau.size();\n}\n\nvoid Zone::printZone(){\n cout << \"La zone s'appelle \" << zone_name << endl;\n for(int i=0; i < tableau.size(); i++){\n tableau[i]->printObjet();\n }\n}\n\nObjet* Zone::getObjetPointer(int index){\n if(index >= 0 && index < tableau.size()){\n return tableau[index];\n }else{\n return 0;\n }\n}\n\nZone* Zone::getPointer(){\n return this;\n}\n\n<|endoftext|>"} {"text":"\/*\nCopyright 2014-2015 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL.hpp\"\n\n#include \n\nnamespace ReQL {\n\nResult::Result() : type(REQL_R_JSON) {}\n\nResult::Result(const Result &other) {\n value.copy(other.value, type);\n}\n\nResult::Result(Result &&other) {\n value.move(std::move(other.value), type);\n}\n\nResult::~Result() {\n value.release(type);\n}\n\nResult &\nResult::operator=(const Result &other) {\n if (this != &other) {\n type = other.type;\n value.copy(other.value, type);\n }\n return *this;\n}\n\nResult &\nResult::operator=(Result &&other) {\n if (this != &other) {\n type = std::move(other.type);\n value.move(std::move(other.value), type);\n }\n return *this;\n}\n\nResult::JSON_Value::JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n\nvoid\nResult::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t a_type) {\n release(a_type);\n switch (a_type) {\n case REQL_R_ARRAY: {\n array = new std::vector(*other.array);\n break;\n }\n case REQL_R_BOOL: {\n boolean = new bool(*other.boolean);\n break;\n }\n case REQL_R_NUM: {\n num = new double(*other.num);\n break;\n }\n case REQL_R_OBJECT: {\n object = new std::map(*other.object);\n break;\n }\n case REQL_R_STR: {\n string = new std::string(*other.string);\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t a_type) {\n release(a_type);\n switch (a_type) {\n case REQL_R_ARRAY: {\n array = std::move(other.array);\n break;\n }\n case REQL_R_BOOL: {\n boolean = std::move(other.boolean);\n break;\n }\n case REQL_R_NUM: {\n num = std::move(other.num);\n break;\n }\n case REQL_R_OBJECT: {\n object = std::move(other.object);\n break;\n }\n case REQL_R_STR: {\n string = std::move(other.string);\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::release(ReQL_Datum_t a_type) {\n switch (a_type) {\n case REQL_R_ARRAY: {\n if (array != nullptr) {\n delete array;\n }\n break;\n }\n case REQL_R_OBJECT: {\n if (object != nullptr) {\n delete object;\n }\n break;\n }\n case REQL_R_STR: {\n if (string != nullptr) {\n delete string;\n }\n break;\n }\n case REQL_R_BOOL: {\n if (boolean != nullptr) {\n delete boolean;\n }\n break;\n }\n case REQL_R_NUM: {\n if (num != nullptr) {\n delete num;\n }\n break;\n }\n case REQL_R_JSON:\n case REQL_R_NULL:\n case REQL_R_REQL: break;\n }\n}\n\nResult::JSON_Value::~JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n\nvoid\nParser::parse(ReQL_Obj_t *val) {\n switch (reql_datum_type(val)) {\n case REQL_R_ARRAY: {\n startArray();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *elem = NULL;\n\n while ((elem = reql_iter_next(&it)) != NULL) {\n parse(elem);\n }\n\n endArray();\n break;\n }\n case REQL_R_BOOL: {\n addElement(static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_NULL: {\n addElement();\n break;\n }\n case REQL_R_NUM: {\n addElement(reql_to_number(val));\n break;\n }\n case REQL_R_OBJECT: {\n startObject();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *key = NULL;\n ReQL_Obj_t *value = NULL;\n\n while ((key = reql_iter_next(&it)) != NULL) {\n value = reql_object_get(val, key);\n std::string key_string((char *)reql_string_buf(key), reql_size(key));\n\n switch (reql_datum_type(value)) {\n case REQL_R_BOOL: {\n addKeyValue(key_string, static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_ARRAY:\n case REQL_R_OBJECT: {\n addKey(key_string);\n parse(value);\n break;\n }\n case REQL_R_NULL: {\n addKeyValue(key_string);\n break;\n }\n case REQL_R_NUM: {\n addKeyValue(key_string, reql_to_number(value));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_STR: {\n addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value)));\n break;\n }\n }\n }\n\n endObject();\n break;\n }\n case REQL_R_STR: {\n addElement(std::string((char *)reql_string_buf(val), reql_size(val)));\n break;\n }\n }\n}\n\nclass ResultBuilder : public Parser {\npublic:\n Result result() { return p_result; }\n\nprivate:\n void startObject() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_OBJECT;\n }\n\n void addKey(std::string key) {\n p_keys.push_back(key);\n }\n\n void addKeyValue(std::string key) {\n Result res;\n res.type = REQL_R_NULL;\n p_stack.end()->value.object->insert({key, res});\n }\n\n void addKeyValue(std::string key, bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = new bool(value);\n p_stack.end()->value.object->insert({key, res});\n }\n\n void addKeyValue(std::string key, double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = new double(value);\n p_stack.end()->value.object->insert({key, res});\n }\n\n void addKeyValue(std::string key, std::string value) {\n Result res;\n res.type = REQL_R_STR;\n res.value.string = new std::string(value);\n p_stack.end()->value.object->insert({key, res});\n }\n\n void endObject() {\n end();\n }\n\n void startArray() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_ARRAY;\n p_stack.end()->value.array = new std::vector;\n }\n\n void addElement() {\n Result res;\n res.type = REQL_R_NULL;\n addElement(std::move(res));\n }\n\n void addElement(bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = new bool(value);\n addElement(std::move(res));\n }\n\n void addElement(double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = new double(value);\n addElement(std::move(res));\n }\n\n void addElement(std::string value) {\n Result res;\n res.type = REQL_R_STR;\n res.value.string = new std::string(value);\n addElement(std::move(res));\n }\n\n void endArray() {\n end();\n }\n\n void addElement(Result &&val) {\n if (p_stack.empty()) {\n p_result = std::move(val);\n } else if (p_stack.end()->type == REQL_R_ARRAY) {\n std::vector *array = p_stack.end()->value.array;\n array->insert(array->end(), std::move(val));\n } else {\n }\n }\n\n void end() {\n Result last = *p_stack.end().base();\n p_stack.pop_back();\n if (p_stack.empty()) {\n p_result = last;\n } else if (p_stack.end()->type == REQL_R_OBJECT) {\n std::string key = *p_keys.end();\n p_keys.pop_back();\n p_stack.end()->value.object->insert({key, last});\n } else if (p_stack.end()->type == REQL_R_ARRAY) {\n addElement(std::move(last));\n } else {\n }\n }\n\n std::vector p_stack;\n std::vector p_keys;\n Result p_result;\n};\n\nCursor::Cursor() : cur(new ReQL_Cur_t) {\n reql_cursor_init(data());\n}\n\nCursor::~Cursor() {\n}\n\nbool Cursor::isOpen() const {\n return reql_cur_open(data());\n}\n\nResult\nCursor::next() {\n ResultBuilder builder;\n next(builder);\n return builder.result();\n}\n\nvoid\nCursor::next(Parser &p) {\n p.parse(reql_cursor_next(data()));\n}\n\nReQL_Cur_t *\nCursor::data() const {\n return cur.get();\n}\n\nvoid\nCursor::close() {\n}\n\nConnection::Connection() : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n if (key.size() > UINT32_MAX) {\n }\n\n std::uint32_t key_len = (std::uint32_t)key.size();\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n reql_conn_set_auth(data(), key_len, (char *)key.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const Connection &other) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n ReQL_Conn_t *o_conn = other.data();\n\n reql_conn_set_addr(data(), o_conn->addr);\n reql_conn_set_port(data(), o_conn->port);\n reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(Connection &&other) {\n conn = std::move(other.conn);\n}\n\nConnection::~Connection() {\n reql_ensure_conn_close(data());\n}\n\nConnection &Connection::operator=(const Connection &other) {\n if (this != &other) {\n reql_ensure_conn_close(data());\n reql_connection_init(data());\n\n ReQL_Conn_t *o_conn = other.data();\n\n reql_conn_set_addr(data(), o_conn->addr);\n reql_conn_set_port(data(), o_conn->port);\n reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n }\n return *this;\n}\n\nConnection &Connection::operator=(Connection &&other) {\n reql_ensure_conn_close(data());\n conn = std::move(other.conn);\n return *this;\n}\n\nvoid\nConnection::close() {\n reql_close_conn(data());\n}\n\nbool\nConnection::isOpen() const {\n return reql_conn_open(data());\n}\n\nReQL_Conn_t *\nConnection::data() const {\n return conn.get();\n}\n\nCursor Query::run(const Connection &conn) const {\n if (!conn.isOpen()) {\n }\n\n Cursor cur;\n\n reql_run(cur.data(), p_query.data(), conn.data(), nullptr);\n\n return cur;\n}\n\nQuery &Query::operator=(const Query &other) {\n Expr::operator=(other);\n return *this;\n}\n\nQuery &Query::operator=(Query &&other) {\n Expr::operator=(std::move(other));\n return *this;\n}\n\nbool Query::operator<(const Query &other) const {\n return Expr::operator<(other);\n}\n\n}\nCompare type limits from c++.\/*\nCopyright 2014-2015 Adam Grandquist\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n *\/\n\/**\n * @author Adam Grandquist\n * @copyright Apache\n *\/\n\n#include \"ReQL.hpp\"\n\n#include \n\nnamespace ReQL {\n\nResult::Result() : type(REQL_R_JSON) {}\n\nResult::Result(const Result &other) {\n value.copy(other.value, type);\n}\n\nResult::Result(Result &&other) {\n value.move(std::move(other.value), type);\n}\n\nResult::~Result() {\n value.release(type);\n}\n\nResult &\nResult::operator=(const Result &other) {\n if (this != &other) {\n type = other.type;\n value.copy(other.value, type);\n }\n return *this;\n}\n\nResult &\nResult::operator=(Result &&other) {\n if (this != &other) {\n type = std::move(other.type);\n value.move(std::move(other.value), type);\n }\n return *this;\n}\n\nResult::JSON_Value::JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n\nvoid\nResult::JSON_Value::copy(const Result::JSON_Value &other, ReQL_Datum_t a_type) {\n release(a_type);\n switch (a_type) {\n case REQL_R_ARRAY: {\n array = new std::vector(*other.array);\n break;\n }\n case REQL_R_BOOL: {\n boolean = new bool(*other.boolean);\n break;\n }\n case REQL_R_NUM: {\n num = new double(*other.num);\n break;\n }\n case REQL_R_OBJECT: {\n object = new std::map(*other.object);\n break;\n }\n case REQL_R_STR: {\n string = new std::string(*other.string);\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::move(Result::JSON_Value &&other, ReQL_Datum_t a_type) {\n release(a_type);\n switch (a_type) {\n case REQL_R_ARRAY: {\n array = std::move(other.array);\n break;\n }\n case REQL_R_BOOL: {\n boolean = std::move(other.boolean);\n break;\n }\n case REQL_R_NUM: {\n num = std::move(other.num);\n break;\n }\n case REQL_R_OBJECT: {\n object = std::move(other.object);\n break;\n }\n case REQL_R_STR: {\n string = std::move(other.string);\n break;\n }\n case REQL_R_NULL:\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n }\n}\n\nvoid\nResult::JSON_Value::release(ReQL_Datum_t a_type) {\n switch (a_type) {\n case REQL_R_ARRAY: {\n if (array != nullptr) {\n delete array;\n }\n break;\n }\n case REQL_R_OBJECT: {\n if (object != nullptr) {\n delete object;\n }\n break;\n }\n case REQL_R_STR: {\n if (string != nullptr) {\n delete string;\n }\n break;\n }\n case REQL_R_BOOL: {\n if (boolean != nullptr) {\n delete boolean;\n }\n break;\n }\n case REQL_R_NUM: {\n if (num != nullptr) {\n delete num;\n }\n break;\n }\n case REQL_R_JSON:\n case REQL_R_NULL:\n case REQL_R_REQL: break;\n }\n}\n\nResult::JSON_Value::~JSON_Value() {\n std::memset(this, 0, sizeof(Result::JSON_Value));\n}\n\nvoid\nParser::parse(ReQL_Obj_t *val) {\n switch (reql_datum_type(val)) {\n case REQL_R_ARRAY: {\n startArray();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *elem = NULL;\n\n while ((elem = reql_iter_next(&it)) != NULL) {\n parse(elem);\n }\n\n endArray();\n break;\n }\n case REQL_R_BOOL: {\n addElement(static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_NULL: {\n addElement();\n break;\n }\n case REQL_R_NUM: {\n addElement(reql_to_number(val));\n break;\n }\n case REQL_R_OBJECT: {\n startObject();\n\n ReQL_Iter_t it = reql_new_iter(val);\n ReQL_Obj_t *key = NULL;\n ReQL_Obj_t *value = NULL;\n\n while ((key = reql_iter_next(&it)) != NULL) {\n value = reql_object_get(val, key);\n std::string key_string((char *)reql_string_buf(key), reql_size(key));\n\n switch (reql_datum_type(value)) {\n case REQL_R_BOOL: {\n addKeyValue(key_string, static_cast(reql_to_bool(val)));\n break;\n }\n case REQL_R_ARRAY:\n case REQL_R_OBJECT: {\n addKey(key_string);\n parse(value);\n break;\n }\n case REQL_R_NULL: {\n addKeyValue(key_string);\n break;\n }\n case REQL_R_NUM: {\n addKeyValue(key_string, reql_to_number(value));\n break;\n }\n case REQL_R_JSON:\n case REQL_R_REQL: break;\n case REQL_R_STR: {\n addKeyValue(key_string, std::string((char *)reql_string_buf(value), reql_size(value)));\n break;\n }\n }\n }\n\n endObject();\n break;\n }\n case REQL_R_STR: {\n addElement(std::string((char *)reql_string_buf(val), reql_size(val)));\n break;\n }\n }\n}\n\nclass ResultBuilder : public Parser {\npublic:\n Result result() { return p_result; }\n\nprivate:\n void startObject() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_OBJECT;\n }\n\n void addKey(std::string key) {\n p_keys.push_back(key);\n }\n\n void addKeyValue(std::string key) {\n Result res;\n res.type = REQL_R_NULL;\n p_stack.end()->value.object->insert({key, res});\n }\n\n void addKeyValue(std::string key, bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = new bool(value);\n p_stack.end()->value.object->insert({key, res});\n }\n\n void addKeyValue(std::string key, double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = new double(value);\n p_stack.end()->value.object->insert({key, res});\n }\n\n void addKeyValue(std::string key, std::string value) {\n Result res;\n res.type = REQL_R_STR;\n res.value.string = new std::string(value);\n p_stack.end()->value.object->insert({key, res});\n }\n\n void endObject() {\n end();\n }\n\n void startArray() {\n p_stack.push_back(Result());\n p_stack.end()->type = REQL_R_ARRAY;\n p_stack.end()->value.array = new std::vector;\n }\n\n void addElement() {\n Result res;\n res.type = REQL_R_NULL;\n addElement(std::move(res));\n }\n\n void addElement(bool value) {\n Result res;\n res.type = REQL_R_BOOL;\n res.value.boolean = new bool(value);\n addElement(std::move(res));\n }\n\n void addElement(double value) {\n Result res;\n res.type = REQL_R_NUM;\n res.value.num = new double(value);\n addElement(std::move(res));\n }\n\n void addElement(std::string value) {\n Result res;\n res.type = REQL_R_STR;\n res.value.string = new std::string(value);\n addElement(std::move(res));\n }\n\n void endArray() {\n end();\n }\n\n void addElement(Result &&val) {\n if (p_stack.empty()) {\n p_result = std::move(val);\n } else if (p_stack.end()->type == REQL_R_ARRAY) {\n std::vector *array = p_stack.end()->value.array;\n array->insert(array->end(), std::move(val));\n } else {\n }\n }\n\n void end() {\n Result last = *p_stack.end().base();\n p_stack.pop_back();\n if (p_stack.empty()) {\n p_result = last;\n } else if (p_stack.end()->type == REQL_R_OBJECT) {\n std::string key = *p_keys.end();\n p_keys.pop_back();\n p_stack.end()->value.object->insert({key, last});\n } else if (p_stack.end()->type == REQL_R_ARRAY) {\n addElement(std::move(last));\n } else {\n }\n }\n\n std::vector p_stack;\n std::vector p_keys;\n Result p_result;\n};\n\nCursor::Cursor() : cur(new ReQL_Cur_t) {\n reql_cursor_init(data());\n}\n\nCursor::~Cursor() {\n}\n\nbool Cursor::isOpen() const {\n return reql_cur_open(data());\n}\n\nResult\nCursor::next() {\n ResultBuilder builder;\n next(builder);\n return builder.result();\n}\n\nvoid\nCursor::next(Parser &p) {\n p.parse(reql_cursor_next(data()));\n}\n\nReQL_Cur_t *\nCursor::data() const {\n return cur.get();\n}\n\nvoid\nCursor::close() {\n}\n\nConnection::Connection() : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const std::string &host, const std::uint16_t &port, const std::string &key) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n std::size_t auth_size = key.size();\n\n if (auth_size > std::numeric_limits::max()) {\n return;\n }\n\n reql_conn_set_addr(data(), (char *)host.c_str());\n reql_conn_set_port(data(), (char *)std::to_string(port).c_str());\n reql_conn_set_auth(data(), key_len, (char *)key.c_str());\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(const Connection &other) : conn(new ReQL_Conn_t) {\n reql_connection_init(data());\n\n ReQL_Conn_t *o_conn = other.data();\n\n reql_conn_set_addr(data(), o_conn->addr);\n reql_conn_set_port(data(), o_conn->port);\n reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n}\n\nConnection::Connection(Connection &&other) {\n conn = std::move(other.conn);\n}\n\nConnection::~Connection() {\n reql_ensure_conn_close(data());\n}\n\nConnection &Connection::operator=(const Connection &other) {\n if (this != &other) {\n reql_ensure_conn_close(data());\n reql_connection_init(data());\n\n ReQL_Conn_t *o_conn = other.data();\n\n reql_conn_set_addr(data(), o_conn->addr);\n reql_conn_set_port(data(), o_conn->port);\n reql_conn_set_auth(data(), o_conn->auth_size, o_conn->auth);\n\n std::uint8_t buf[500];\n\n if (reql_connect(data(), buf, 500)) {\n }\n }\n return *this;\n}\n\nConnection &Connection::operator=(Connection &&other) {\n reql_ensure_conn_close(data());\n conn = std::move(other.conn);\n return *this;\n}\n\nvoid\nConnection::close() {\n reql_close_conn(data());\n}\n\nbool\nConnection::isOpen() const {\n return reql_conn_open(data());\n}\n\nReQL_Conn_t *\nConnection::data() const {\n return conn.get();\n}\n\nCursor Query::run(const Connection &conn) const {\n if (!conn.isOpen()) {\n }\n\n Cursor cur;\n\n reql_run(cur.data(), p_query.data(), conn.data(), nullptr);\n\n return cur;\n}\n\nQuery &Query::operator=(const Query &other) {\n Expr::operator=(other);\n return *this;\n}\n\nQuery &Query::operator=(Query &&other) {\n Expr::operator=(std::move(other));\n return *this;\n}\n\nbool Query::operator<(const Query &other) const {\n return Expr::operator<(other);\n}\n\n}\n<|endoftext|>"} {"text":"\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef MIDDLEWARE_COOKIE_PARSER_HPP\n#define MIDDLEWARE_COOKIE_PARSER_HPP\n\n#include \"..\/cookie\/cookie.hpp\"\n#include \"middleware.hpp\"\n\nnamespace middleware {\n\n\/**\n * @brief A way to parse cookies: Reading cookies that the browser is sending to the server\n * @details\n *\n *\/\n\n\/\/ hpp-declarations first and implement methods further down? Or in own cpp-file?\n\nclass CookieParser : public server::Middleware {\n\npublic:\n virtual void process(server::Request_ptr req, server::Response_ptr res, server::Next next) override {\n\n using namespace cookie;\n\n if(!has_cookie(req)) {\n \/\/No Cookie in header field: We want to create a cookie then??:\n \/\/\n \/\/create cookie:\n\n (*next)();\n return;\n }\n\n \/\/ Found Cookie in header\n\n\n\n }\n\n \/\/ Just name this method cookie?\n \/\/ Return bool or void?\n bool create_cookie(std::string& key, std::string& value); \/\/ new Cookie(...) and add_header: Set-Cookie ?\n\n \/\/ Just name this method cookie?\n \/\/ Return bool or void?\n bool create_cookie(std::string& key, std::string& value, std::string& options); \/\/ new Cookie(...) and add_header: Set-Cookie ?\n\/\/ options: map eller enum\n\n \/\/ Return bool or void?\n bool clear_cookie(std::string& key); \/\/ remove Cookie from client\n\nprivate:\n bool has_cookie(server::Request_ptr req) const {\n auto c_type = http::header_fields::Request::Cookie;\n\n return req->has_header(c_type);\n }\n\n};\n\n} \/\/< namespace middleware\n\n#endif\nRefactored CookieParser::has_cookie\/\/ This file is a part of the IncludeOS unikernel - www.includeos.org\n\/\/\n\/\/ Copyright 2015-2016 Oslo and Akershus University College of Applied Sciences\n\/\/ and Alfred Bratterud\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#ifndef MIDDLEWARE_COOKIE_PARSER_HPP\n#define MIDDLEWARE_COOKIE_PARSER_HPP\n\n#include \"..\/cookie\/cookie.hpp\"\n#include \"middleware.hpp\"\n\nnamespace middleware {\n\n\/**\n * @brief A way to parse cookies: Reading cookies that the browser is sending to the server\n * @details\n *\n *\/\n\n\/\/ hpp-declarations first and implement methods further down? Or in own cpp-file?\n\nclass CookieParser : public server::Middleware {\n\npublic:\n virtual void process(server::Request_ptr req, server::Response_ptr res, server::Next next) override {\n\n using namespace cookie;\n\n if(!has_cookie(req)) {\n \/\/No Cookie in header field: We want to create a cookie then??:\n \/\/\n \/\/create cookie:\n\n (*next)();\n return;\n }\n\n \/\/ Found Cookie in header\n\n\n\n }\n\n \/\/ Just name this method cookie?\n \/\/ Return bool or void?\n bool create_cookie(std::string& key, std::string& value); \/\/ new Cookie(...) and add_header: Set-Cookie ?\n\n \/\/ Just name this method cookie?\n \/\/ Return bool or void?\n bool create_cookie(std::string& key, std::string& value, std::string& options); \/\/ new Cookie(...) and add_header: Set-Cookie ?\n\/\/ options: map eller enum\n\n \/\/ Return bool or void?\n bool clear_cookie(std::string& key); \/\/ remove Cookie from client\n\nprivate:\n bool has_cookie(server::Request_ptr req) const noexcept;\n};\n\ninline bool CookieParser::has_cookie(server::Request_ptr req) const noexcept {\n return req->has_header(http::header_fields::Request::Cookie);\n}\n\n} \/\/< namespace middleware\n\n#endif\n<|endoftext|>"} {"text":"#include \n\n#include \"html-escape.hh\"\n\nnamespace mimosa\n{\n namespace stream\n {\n HtmlEscape::HtmlEscape(Stream::Ptr stream)\n : Filter(stream)\n {\n }\n\n int64_t\n HtmlEscape::write(const char * data, uint64_t nbytes, runtime::Time timeout)\n {\n const char * const start = data;\n const char * const end = data + nbytes;\n const char * p = data;\n\n while (data < end)\n {\n while (p < end && *p != '<' && *p != '>' &&\n *p != '&' && *p != '\"' && *p != '\\'')\n ++p;\n\n if (data < p)\n {\n auto bytes = stream_->write(data, p - data, timeout);\n if (bytes < 0)\n return data == start ? bytes : data - start;\n if (bytes < p - data)\n return data - start + bytes;\n data = p;\n }\n\n if (p < end)\n {\n const char * replace = nullptr;\n int size = 0;\n\n switch (*p)\n {\n case '<': replace = \"<\"; size = 4; break;\n case '>': replace = \">\"; size = 4; break;\n case '&': replace = \"&\"; size = 5; break;\n case '\\'': replace = \"'\"; size = 6; break;\n case '\"': replace = \""\"; size = 6; break;\n default: assert(false); break;\n }\n\n auto wrote = stream_->loopWrite(replace, size, timeout);\n if (wrote < 0)\n return data - start;\n if (wrote < size)\n return -1;\n ++data;\n ++p;\n }\n }\n return nbytes;\n }\n\n int64_t\n HtmlEscape::read(char * data, uint64_t nbytes, runtime::Time timeout)\n {\n assert(false && \"TODO\");\n }\n }\n}\nfix a return value error#include \n\n#include \"html-escape.hh\"\n\nnamespace mimosa\n{\n namespace stream\n {\n HtmlEscape::HtmlEscape(Stream::Ptr stream)\n : Filter(stream)\n {\n }\n\n int64_t\n HtmlEscape::write(const char * data, uint64_t nbytes, runtime::Time timeout)\n {\n const char * const start = data;\n const char * const end = data + nbytes;\n const char * p = data;\n\n while (data < end)\n {\n while (p < end && *p != '<' && *p != '>' &&\n *p != '&' && *p != '\"' && *p != '\\'')\n ++p;\n\n if (data < p)\n {\n auto bytes = stream_->write(data, p - data, timeout);\n if (bytes < 0)\n return data == start ? bytes : data - start;\n if (bytes < p - data)\n return data - start + bytes;\n data = p;\n }\n\n if (p < end)\n {\n const char * replace = nullptr;\n int size = 0;\n\n switch (*p)\n {\n case '<': replace = \"<\"; size = 4; break;\n case '>': replace = \">\"; size = 4; break;\n case '&': replace = \"&\"; size = 5; break;\n case '\\'': replace = \"'\"; size = 6; break;\n case '\"': replace = \""\"; size = 6; break;\n default: assert(false); break;\n }\n\n auto wrote = stream_->loopWrite(replace, size, timeout);\n if (wrote < 0)\n return data - start;\n if (wrote < size)\n return -1;\n ++data;\n ++p;\n }\n }\n return nbytes;\n }\n\n int64_t\n HtmlEscape::read(char * data, uint64_t nbytes, runtime::Time timeout)\n {\n assert(false && \"TODO\");\n return -1;\n }\n }\n}\n<|endoftext|>"} {"text":"#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH\n# define MIMOSA_TPL_ABSTRACT_VALUE_HH\n\n# include \"..\/ref-countable.hh\"\n# include \"..\/stream\/stream.hh\"\n# include \"..\/string\/string-ref.hh\"\n\nnamespace mimosa\n{\n namespace tpl\n {\n class AbstractValue\n {\n public:\n virtual const AbstractValue * lookup(const string::StringRef & var) const = 0;\n virtual void write(stream::Stream::Ptr stream) const = 0;\n\n AbstractValue * parent_;\n };\n }\n}\n\n#endif \/* !MIMOSA_TPL_ABSTRACT_VALUE_HH *\/\ntemplate: added some mechanism to iterate on \"repeated\" values#ifndef MIMOSA_TPL_ABSTRACT_VALUE_HH\n# define MIMOSA_TPL_ABSTRACT_VALUE_HH\n\n# include \"..\/ref-countable.hh\"\n# include \"..\/stream\/stream.hh\"\n# include \"..\/string\/string-ref.hh\"\n\nnamespace mimosa\n{\n namespace tpl\n {\n class AbstractValue\n {\n public:\n virtual const AbstractValue * lookup(const string::StringRef & var) const = 0;\n virtual void write(stream::Stream::Ptr stream) const = 0;\n\n class Iterator\n {\n virtual const AbstractValue & operator*() const = 0;\n virtual const AbstractValue * operator->() const = 0;\n virtual Iterator & operator++() = 0;\n virtual bool operator==(const Iterator &) const = 0;\n };\n\n virtual Iterator begin() const = 0;\n virtual Iterator end() const = 0;\n virtual bool empty() const = 0;\n\n AbstractValue * parent_;\n };\n }\n}\n\n#endif \/* !MIMOSA_TPL_ABSTRACT_VALUE_HH *\/\n<|endoftext|>"} {"text":"\/*************************************************************************\n * *\n * OU library interface file for Open Dynamics Engine, *\n * Copyright (C) 2008 Oleh Derevenko. All rights reserved. *\n * Email: odar@eleks.com (change all \"a\" to \"e\") *\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/*\n\nODE interface to OU library implementation.\n\n*\/\n\n\n#include \n#include \n#include \"config.h\"\n#include \"odeou.h\"\n\n\n\n#if dOU_ENABLED\n\ntemplate<>\nconst char *const CEnumUnsortedElementArray::m_aetElementArray[] =\n{\n \"assert\", \/\/ AFS_ASSERT,\n \"check\", \/\/ AFS_CHECK,\n};\nstatic const CEnumUnsortedElementArray g_aszAssertionFailureSeverityNames;\n\n\nstatic void _OU_CONVENTION_CALLBACK ForwardOUAssertionFailure(EASSERTIONFAILURESEVERITY fsFailureSeverity, \n const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine)\n{\n dDebug(d_ERR_IASSERT, \"Assertion failure in OU Library. Kind: %s, expression: \\\"%s\\\", file: \\\"%s\\\", line: %u\",\n g_aszAssertionFailureSeverityNames.Encode(fsFailureSeverity), \n szAssertionExpression, szAssertionFileName, uiAssertionSourceLine);\n}\n\n\nstatic void *_OU_CONVENTION_CALLBACK ForwardOUMemoryAlloc(size_t nBlockSize)\n{\n return dAlloc(nBlockSize);\n}\n\nstatic void *_OU_CONVENTION_CALLBACK ForwardOUMemoryRealloc(void *pv_ExistingBlock, size_t nBlockNewSize)\n{\n return dRealloc(pv_ExistingBlock, 0, nBlockNewSize);\n}\n\nstatic void _OU_CONVENTION_CALLBACK ForwardOUMemoryFree(void *pv_ExistingBlock)\n{\n return dFree(pv_ExistingBlock, 0);\n}\n\n\nbool COdeOu::DoOUCustomizations()\n{\n CMemoryManagerCustomization::CustomizeMemoryManager(&ForwardOUMemoryAlloc, \n &ForwardOUMemoryRealloc, &ForwardOUMemoryFree);\n\n CAssertionCheckCustomization::CustomizeAssertionChecks(&ForwardOUAssertionFailure);\n\n return true;\n}\n\nvoid COdeOu::UndoOUCustomizations()\n{\n CAssertionCheckCustomization::CustomizeAssertionChecks(NULL);\n\n CMemoryManagerCustomization::CustomizeMemoryManager(NULL, NULL, NULL);\n}\n\n\n#endif \/\/ dOU_ENABLED\n\nCosmetic: A warning fixed in LLVM compiler\/*************************************************************************\n * *\n * OU library interface file for Open Dynamics Engine, *\n * Copyright (C) 2008 Oleh Derevenko. All rights reserved. *\n * Email: odar@eleks.com (change all \"a\" to \"e\") *\n * *\n * Open Dynamics Engine, Copyright (C) 2001,2002 Russell L. Smith. *\n * All rights reserved. Email: russ@q12.org Web: www.q12.org *\n * *\n * *\n * This library is free software; you can redistribute it and\/or *\n * modify it under the terms of EITHER: *\n * (1) The GNU Lesser General Public License as published by the Free *\n * Software Foundation; either version 2.1 of the License, or (at *\n * your option) any later version. The text of the GNU Lesser *\n * General Public License is included with this library in the *\n * file LICENSE.TXT. *\n * (2) The BSD-style license that is included with this library in *\n * the file LICENSE-BSD.TXT. *\n * *\n * This library is distributed in the hope that it will be useful, *\n * but WITHOUT ANY WARRANTY; without even the implied warranty of *\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the files *\n * LICENSE.TXT and LICENSE-BSD.TXT for more details. *\n * *\n *************************************************************************\/\n\n\/*\n\nODE interface to OU library implementation.\n\n*\/\n\n\n#include \n#include \n#include \"config.h\"\n#include \"odeou.h\"\n\n\n\n#if dOU_ENABLED\n\nBEGIN_NAMESPACE_OU();\ntemplate<>\nconst char *const CEnumUnsortedElementArray::m_aetElementArray[] =\n{\n \"assert\", \/\/ AFS_ASSERT,\n \"check\", \/\/ AFS_CHECK,\n};\nEND_NAMESPACE_OU();\n\nstatic const CEnumUnsortedElementArray g_aszAssertionFailureSeverityNames;\n\n\nstatic void _OU_CONVENTION_CALLBACK ForwardOUAssertionFailure(EASSERTIONFAILURESEVERITY fsFailureSeverity, \n const char *szAssertionExpression, const char *szAssertionFileName, unsigned int uiAssertionSourceLine)\n{\n dDebug(d_ERR_IASSERT, \"Assertion failure in OU Library. Kind: %s, expression: \\\"%s\\\", file: \\\"%s\\\", line: %u\",\n g_aszAssertionFailureSeverityNames.Encode(fsFailureSeverity), \n szAssertionExpression, szAssertionFileName, uiAssertionSourceLine);\n}\n\n\nstatic void *_OU_CONVENTION_CALLBACK ForwardOUMemoryAlloc(size_t nBlockSize)\n{\n return dAlloc(nBlockSize);\n}\n\nstatic void *_OU_CONVENTION_CALLBACK ForwardOUMemoryRealloc(void *pv_ExistingBlock, size_t nBlockNewSize)\n{\n return dRealloc(pv_ExistingBlock, 0, nBlockNewSize);\n}\n\nstatic void _OU_CONVENTION_CALLBACK ForwardOUMemoryFree(void *pv_ExistingBlock)\n{\n return dFree(pv_ExistingBlock, 0);\n}\n\n\nbool COdeOu::DoOUCustomizations()\n{\n CMemoryManagerCustomization::CustomizeMemoryManager(&ForwardOUMemoryAlloc, \n &ForwardOUMemoryRealloc, &ForwardOUMemoryFree);\n\n CAssertionCheckCustomization::CustomizeAssertionChecks(&ForwardOUAssertionFailure);\n\n return true;\n}\n\nvoid COdeOu::UndoOUCustomizations()\n{\n CAssertionCheckCustomization::CustomizeAssertionChecks(NULL);\n\n CMemoryManagerCustomization::CustomizeMemoryManager(NULL, NULL, NULL);\n}\n\n\n#endif \/\/ dOU_ENABLED\n\n<|endoftext|>"} {"text":"\/* Sirikata Transfer\n * DiskManager.hpp\n *\n * Copyright (c) 2010, Jeff Terrace\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef SIRIKATA_DiskManager_HPP__\n#define SIRIKATA_DiskManager_HPP__\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Sirikata {\nnamespace Transfer {\n\nnamespace fs = boost::filesystem;\n\nnamespace Filesystem {\n typedef boost::filesystem::path Path;\n typedef boost::filesystem::file_status FileStatus;\n typedef boost::filesystem::file_type FileType;\n namespace boost_fs = boost::filesystem;\n class PathInfo {\n public:\n Path mPath;\n FileStatus mFileStatus;\n PathInfo(Path p, FileStatus f) : mPath(p), mFileStatus(f) {}\n };\n}\n\nclass SIRIKATA_EXPORT DiskManager\n : public AutoSingleton {\n\npublic:\n\n class DiskRequest {\n protected:\n virtual void execute() = 0;\n\n virtual ~DiskRequest() {}\n friend class DiskManager;\n };\n\n class ScanRequest : public DiskRequest {\n public:\n typedef std::vector DirectoryListing;\n typedef std::tr1::function dirListing\n )> ScanRequestCallback;\n\n ScanRequest(Filesystem::Path path, ScanRequestCallback cb);\n private:\n ScanRequestCallback mCb;\n Filesystem::Path mPath;\n protected:\n void execute();\n };\n\n class ReadRequest : public DiskRequest {\n public:\n typedef std::tr1::function fileContents\n )> ReadRequestCallback;\n\n ReadRequest(Filesystem::Path path, ReadRequestCallback cb);\n private:\n ReadRequestCallback mCb;\n Filesystem::Path mPath;\n protected:\n void execute();\n };\n\n class WriteRequest : public DiskRequest {\n public:\n typedef std::tr1::function WriteRequestCallback;\n\n WriteRequest(Filesystem::Path path, std::tr1::shared_ptr fileContents, WriteRequestCallback cb);\n private:\n WriteRequestCallback mCb;\n Filesystem::Path mPath;\n std::tr1::shared_ptr mFileContents;\n protected:\n void execute();\n };\n\n DiskManager();\n ~DiskManager();\n\n void addRequest(std::tr1::shared_ptr req);\n\n static DiskManager& getSingleton();\n static void destroy();\n\nprivate:\n ThreadSafeQueue > mRequestQueue;\n Thread *mWorkerThread;\n boost::mutex destroyLock;\n boost::condition_variable destroyCV;\n\n void workerThread();\n\n};\n\n}\n}\n\n#endif \/* SIRIKATA_DiskManager_HPP__ *\/\nAdd missing SIRIKATA_EXPORT to public nested classes, which some platforms require even when the parent class has SIRIKATA_EXPORT.\/* Sirikata Transfer\n * DiskManager.hpp\n *\n * Copyright (c) 2010, Jeff Terrace\n * All rights reserved.\n *\n * Redistribution and use in source and binary forms, with or without\n * modification, are permitted provided that the following conditions are\n * met:\n * * Redistributions of source code must retain the above copyright\n * notice, this list of conditions and the following disclaimer.\n * * Redistributions in binary form must reproduce the above copyright\n * notice, this list of conditions and the following disclaimer in\n * the documentation and\/or other materials provided with the\n * distribution.\n * * Neither the name of Sirikata nor the names of its contributors may\n * be used to endorse or promote products derived from this software\n * without specific prior written permission.\n *\n * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS\n * IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED\n * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\n * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER\n * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,\n * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,\n * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR\n * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF\n * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING\n * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\n * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n *\/\n\n#ifndef SIRIKATA_DiskManager_HPP__\n#define SIRIKATA_DiskManager_HPP__\n\n#include \n#include \n#include \n#include \n#include \n\nnamespace Sirikata {\nnamespace Transfer {\n\nnamespace fs = boost::filesystem;\n\nnamespace Filesystem {\n typedef boost::filesystem::path Path;\n typedef boost::filesystem::file_status FileStatus;\n typedef boost::filesystem::file_type FileType;\n namespace boost_fs = boost::filesystem;\n class PathInfo {\n public:\n Path mPath;\n FileStatus mFileStatus;\n PathInfo(Path p, FileStatus f) : mPath(p), mFileStatus(f) {}\n };\n}\n\nclass SIRIKATA_EXPORT DiskManager\n : public AutoSingleton {\n\npublic:\n\n class DiskRequest {\n protected:\n virtual void execute() = 0;\n\n virtual ~DiskRequest() {}\n friend class DiskManager;\n };\n\n class SIRIKATA_EXPORT ScanRequest : public DiskRequest {\n public:\n typedef std::vector DirectoryListing;\n typedef std::tr1::function dirListing\n )> ScanRequestCallback;\n\n ScanRequest(Filesystem::Path path, ScanRequestCallback cb);\n private:\n ScanRequestCallback mCb;\n Filesystem::Path mPath;\n protected:\n void execute();\n };\n\n class SIRIKATA_EXPORT ReadRequest : public DiskRequest {\n public:\n typedef std::tr1::function fileContents\n )> ReadRequestCallback;\n\n ReadRequest(Filesystem::Path path, ReadRequestCallback cb);\n private:\n ReadRequestCallback mCb;\n Filesystem::Path mPath;\n protected:\n void execute();\n };\n\n class SIRIKATA_EXPORT WriteRequest : public DiskRequest {\n public:\n typedef std::tr1::function WriteRequestCallback;\n\n WriteRequest(Filesystem::Path path, std::tr1::shared_ptr fileContents, WriteRequestCallback cb);\n private:\n WriteRequestCallback mCb;\n Filesystem::Path mPath;\n std::tr1::shared_ptr mFileContents;\n protected:\n void execute();\n };\n\n DiskManager();\n ~DiskManager();\n\n void addRequest(std::tr1::shared_ptr req);\n\n static DiskManager& getSingleton();\n static void destroy();\n\nprivate:\n ThreadSafeQueue > mRequestQueue;\n Thread *mWorkerThread;\n boost::mutex destroyLock;\n boost::condition_variable destroyCV;\n\n void workerThread();\n\n};\n\n}\n}\n\n#endif \/* SIRIKATA_DiskManager_HPP__ *\/\n<|endoftext|>"} {"text":"\/\/ --*- Mode: C++; c-basic-offset: 8 -*--\n#include \n#include \"EigenLab.h\"\n\nint main(int argc, const char * argv[])\n{\n EigenLab::ParserXd parserXd;\n auto failXd = parserXd.test();\n \n EigenLab::ParserXf parserXf;\n auto failXf = parserXf.test();\n \n EigenLab::ParserXi parserXi;\n auto failXi = parserXi.test();\n\n EigenLab::Parser,Eigen::Dynamic,Eigen::Dynamic > > parserXcd;\n auto failXcd = parserXcd.test();\n\n std::cout << \"Test summary, number of failures: Xd=\" << failXd << \" Xf=\" << failXf << \" Xi=\" << failXi << \" Xcd=\" << failXcd << std::endl;\n return 0;\n}\nmake test return -1 if fail\/\/ --*- Mode: C++; c-basic-offset: 8 -*--\n#include \n#include \"EigenLab.h\"\n\nint main(int argc, const char * argv[])\n{\n EigenLab::ParserXd parserXd;\n auto failXd = parserXd.test();\n \n EigenLab::ParserXf parserXf;\n auto failXf = parserXf.test();\n \n EigenLab::ParserXi parserXi;\n auto failXi = parserXi.test();\n\n EigenLab::Parser,Eigen::Dynamic,Eigen::Dynamic > > parserXcd;\n auto failXcd = parserXcd.test();\n\n std::cout << \"Test summary, number of failures: Xd=\" << failXd << \" Xf=\" << failXf << \" Xi=\" << failXi << \" Xcd=\" << failXcd << std::endl;\n\n return (failXd || failXf || failXi || failXcd) ? -1 : 0;\n}\n<|endoftext|>"} {"text":"#include <..\/recurse.hpp>\n#include \n\nint main(int argc, char *argv[])\n{\n Recurse app(argc, argv);\n\n \/\/ http options\n QHash http_options;\n http_options[\"port\"] = 3000;\n\n \/\/ https options\n QHash https_options;\n https_options[\"port\"] = 3020;\n https_options[\"private_key\"] = \".\/priv.pem\";\n https_options[\"certificate\"] = \".\/cert.pem\";\n\n app.http_server(http_options);\n app.https_server(https_options);\n\n qDebug() << \"start listening...\";\n\n auto ret = app.listen();\n if (ret.error()) {\n qDebug() << \"error upon listening:\" << ret.lastError();\n }\n};\nexample: update for middleware changes#include <..\/recurse.hpp>\n#include \n\nint main(int argc, char *argv[])\n{\n Recurse app(argc, argv);\n\n \/\/ http options\n QHash http_options;\n http_options[\"port\"] = 3000;\n\n \/\/ https options\n QHash https_options;\n https_options[\"port\"] = 3020;\n https_options[\"private_key\"] = \".\/priv.pem\";\n https_options[\"certificate\"] = \".\/cert.pem\";\n\n app.http_server(http_options);\n app.https_server(https_options);\n\n app.use([](auto &ctx, auto next) {\n qDebug() << \"got a new request from\" << ctx.request.ip;\n next();\n });\n\n app.use([](auto &ctx) {\n ctx.response.send(\"Hello, world\");\n });\n\n qDebug() << \"start listening...\";\n\n auto ret = app.listen();\n if (ret.error()) {\n qDebug() << \"error upon listening:\" << ret.lastError();\n }\n};\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n\nint main(int argn, char** argv)\n{\n if(argn != 2)\n {\n std::cout << \"USAGE: \" << argv[0] << \" \\n\";\n return -1;\n }\n\n const std::string dataPath = \"\/opt\/visionlabs\/data\/\";\n\n vlf::Image image;\n if( !image.loadFromPPM(argv[1]) )\n {\n std::cout << \"Cant load image: \" << argv[1] << '\\n';\n return -1;\n }\n\n \/\/ Need only R-channel image for feature extraction\n vlf::Image imageR;\n image.convert(imageR, vlf::Format::R8);\n\n \/\/ Create FaceEngine main object\n fsdk::Ref faceEngine = fsdk::acquire(fsdk::createFaceEngine());\n\n \/\/ Creating detector\n fsdk::Ref detectorFactory = fsdk::acquire(faceEngine->createDetectorFactory());\n detectorFactory->setDataDirectory(dataPath.c_str());\n fsdk::Ref detector = fsdk::acquire(detectorFactory->createDetector(fsdk::ODT_DPM));\n\n \/\/ Creating feature extractor\n fsdk::Ref featureFactory = fsdk::acquire(faceEngine->createFeatureFactory());\n featureFactory->setDataDirectory(dataPath.c_str());\n fsdk::Ref featureDetector = fsdk::acquire(featureFactory->createDetector(fsdk::FT_VGG));\n fsdk::Ref featureSet = fsdk::acquire(featureFactory->createFeatureSet());\n\n \/\/ Create warper\n fsdk::Ref descriptorFactory = fsdk::acquire(faceEngine->createDescriptorFactory());\n fsdk::Ref descriptor =\n fsdk::acquire(static_cast(descriptorFactory->createDescriptor(fsdk::DT_CNN)));\n fsdk::Ref warper = \n fsdk::acquire(static_cast(descriptorFactory->createWarper(fsdk::DT_CNN)));\n\n \/\/ Creating estimator\n fsdk::Ref estimatorFactory = fsdk::acquire(faceEngine->createEstimatorFactory());\n estimatorFactory->setDataDirectory(dataPath.c_str());\n fsdk::Ref complexEstimator =\n fsdk::acquire(static_cast(estimatorFactory->createEstimator(fsdk::ET_COMPLEX)));\n fsdk::Ref qualityEstimator =\n fsdk::acquire(static_cast(estimatorFactory->createEstimator(fsdk::ET_QUALITY)));\n\n \/\/ Detecting faces on the photo\n fsdk::Detection detections[10];\n int count = 10;\n fsdk::Result res = detector->detect(image, image.getRect(), detections, &count);\n if(res.isError())\n {\n std::cout << \"Face detection error\\n\";\n return -1;\n }\n std::cout << \"Detections found: \" << count << \"\\n\\n\";\n for(int i = 0; i < count; i++)\n {\n\t fsdk::Detection& detection = detections[i];\n\n\t std::cout << \"Detection \" << i << \"\\n\";\n\t std::cout << \"Rect: x=\" << detection.rect.x << \" y=\" << detection.rect.y\n << \" w=\" << detection.rect.width << \" h=\" << detection.rect.height << '\\n';\n\n \/\/ Extracting face features\n fsdk::Result res = featureDetector->detect(imageR, detection, featureSet);\n if(res.isError())\n {\n std::cout << \"Feature extraction error\\n\";\n continue;\n }\n\n \/\/ Get warped face from detection\n fsdk::Image warp;\n warper->warp(image, detection, featureSet, warp);\n\n warp.saveAsPPM((\"warp_\" + std::to_string(i) + \".ppm\").c_str());\n \n \/\/ Quality estimating\n float qualityOut;\n res = qualityEstimator->estimate(warp, &qualityOut);\n if(res.isError())\n {\n std::cout << \"Quality estimating error\\n\";\n return -1;\n }\n std::cout << \"Quality estimated\\n\";\n std::cout << \"Quality: \" << qualityOut << \"\\n\";\n\n \/\/ Complex attributes estimating\n fsdk::ComplexEstimation complexEstimationOut;\n res = complexEstimator->estimate(warp, complexEstimationOut);\n\n if(res.isError())\n {\n std::cout << \"Complex attributes estimating error\\n\";\n return -1;\n }\n std::cout << \"Complex attributes estimated\\n\";\n std::cout << \"Gender: \" << complexEstimationOut.gender << \" (1 - man, 0 - woman)\\n\";\n std::cout << \"Natural skin color: \" << complexEstimationOut.naturSkinColor << \" (1 - natural color of skin, 0 - not natural color of skin color)\\n\";\n std::cout << \"Over exposed: \" << complexEstimationOut.overExposed << \" (1 - image is overexposed, 0 - image isn't overexposed)\\n\";\n std::cout << \"Wear glasses: \" << complexEstimationOut.wearGlasses << \" (1 - person wears glasses, 0 - person doesn't wear glasses)\\n\";\n std::cout << \"Age: \" << complexEstimationOut.age << \" (in years)\\n\";\n std::cout << '\\n';\n }\n\n return 0;\n}\nremove dataPath in the example2#include \n#include \n#include \n#include \n\nint main(int argn, char** argv)\n{\n if(argn != 2)\n {\n std::cout << \"USAGE: \" << argv[0] << \" \\n\";\n return -1;\n }\n\n vlf::Image image;\n if( !image.loadFromPPM(argv[1]) )\n {\n std::cout << \"Cant load image: \" << argv[1] << '\\n';\n return -1;\n }\n\n \/\/ Need only R-channel image for feature extraction\n vlf::Image imageR;\n image.convert(imageR, vlf::Format::R8);\n\n \/\/ Create FaceEngine main object\n fsdk::Ref faceEngine = fsdk::acquire(fsdk::createFaceEngine());\n\n \/\/ Creating detector\n fsdk::Ref detectorFactory = fsdk::acquire(faceEngine->createDetectorFactory());\n fsdk::Ref detector = fsdk::acquire(detectorFactory->createDetector(fsdk::ODT_DPM));\n\n \/\/ Creating feature extractor\n fsdk::Ref featureFactory = fsdk::acquire(faceEngine->createFeatureFactory());\n fsdk::Ref featureDetector = fsdk::acquire(featureFactory->createDetector(fsdk::FT_VGG));\n fsdk::Ref featureSet = fsdk::acquire(featureFactory->createFeatureSet());\n\n \/\/ Create warper\n fsdk::Ref descriptorFactory = fsdk::acquire(faceEngine->createDescriptorFactory());\n fsdk::Ref descriptor =\n fsdk::acquire(static_cast(descriptorFactory->createDescriptor(fsdk::DT_CNN)));\n fsdk::Ref warper = \n fsdk::acquire(static_cast(descriptorFactory->createWarper(fsdk::DT_CNN)));\n\n \/\/ Creating estimator\n fsdk::Ref estimatorFactory = fsdk::acquire(faceEngine->createEstimatorFactory());\n fsdk::Ref complexEstimator =\n fsdk::acquire(static_cast(estimatorFactory->createEstimator(fsdk::ET_COMPLEX)));\n fsdk::Ref qualityEstimator =\n fsdk::acquire(static_cast(estimatorFactory->createEstimator(fsdk::ET_QUALITY)));\n\n \/\/ Detecting faces on the photo\n fsdk::Detection detections[10];\n int count = 10;\n fsdk::Result res = detector->detect(image, image.getRect(), detections, &count);\n if(res.isError())\n {\n std::cout << \"Face detection error\\n\";\n return -1;\n }\n std::cout << \"Detections found: \" << count << \"\\n\\n\";\n for(int i = 0; i < count; i++)\n {\n\t fsdk::Detection& detection = detections[i];\n\n\t std::cout << \"Detection \" << i << \"\\n\";\n\t std::cout << \"Rect: x=\" << detection.rect.x << \" y=\" << detection.rect.y\n << \" w=\" << detection.rect.width << \" h=\" << detection.rect.height << '\\n';\n\n \/\/ Extracting face features\n fsdk::Result res = featureDetector->detect(imageR, detection, featureSet);\n if(res.isError())\n {\n std::cout << \"Feature extraction error\\n\";\n continue;\n }\n\n \/\/ Get warped face from detection\n fsdk::Image warp;\n warper->warp(image, detection, featureSet, warp);\n\n warp.saveAsPPM((\"warp_\" + std::to_string(i) + \".ppm\").c_str());\n \n \/\/ Quality estimating\n float qualityOut;\n res = qualityEstimator->estimate(warp, &qualityOut);\n if(res.isError())\n {\n std::cout << \"Quality estimating error\\n\";\n return -1;\n }\n std::cout << \"Quality estimated\\n\";\n std::cout << \"Quality: \" << qualityOut << \"\\n\";\n\n \/\/ Complex attributes estimating\n fsdk::ComplexEstimation complexEstimationOut;\n res = complexEstimator->estimate(warp, complexEstimationOut);\n\n if(res.isError())\n {\n std::cout << \"Complex attributes estimating error\\n\";\n return -1;\n }\n std::cout << \"Complex attributes estimated\\n\";\n std::cout << \"Gender: \" << complexEstimationOut.gender << \" (1 - man, 0 - woman)\\n\";\n std::cout << \"Natural skin color: \" << complexEstimationOut.naturSkinColor << \" (1 - natural color of skin, 0 - not natural color of skin color)\\n\";\n std::cout << \"Over exposed: \" << complexEstimationOut.overExposed << \" (1 - image is overexposed, 0 - image isn't overexposed)\\n\";\n std::cout << \"Wear glasses: \" << complexEstimationOut.wearGlasses << \" (1 - person wears glasses, 0 - person doesn't wear glasses)\\n\";\n std::cout << \"Age: \" << complexEstimationOut.age << \" (in years)\\n\";\n std::cout << '\\n';\n }\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/ $Id$\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\nint main ( int argc , char** argv)\n{ \n if (argc != 2)\n {\n std::cout << \"usage: .\/rundemo \\n\";\n return EXIT_SUCCESS;\n }\n \n using namespace mapnik;\n try {\n std::cout << \" running demo ... \\n\";\n datasource_cache::instance()->register_datasources(argv[1]); \n freetype_engine::register_font(\"\/usr\/local\/lib\/mapnik\/fonts\/DejaVuSans.ttf\");\n \n Map m(800,600);\n m.set_background(color_factory::from_string(\"white\"));\n \n \/\/ create styles\n\n \/\/ Provinces (polygon)\n feature_type_style provpoly_style;\n \n rule_type provpoly_rule_on;\n provpoly_rule_on.set_filter(create_filter(\"[NAME_EN] = 'Ontario'\"));\n provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183)));\n provpoly_style.add_rule(provpoly_rule_on);\n \n rule_type provpoly_rule_qc;\n provpoly_rule_qc.set_filter(create_filter(\"[NAME_EN] = 'Quebec'\"));\n provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203)));\n provpoly_style.add_rule(provpoly_rule_qc);\n \n m.insert_style(\"provinces\",provpoly_style);\n\n \/\/ Provinces (polyline)\n feature_type_style provlines_style;\n \n stroke provlines_stk (Color(0,0,0),1.0);\n provlines_stk.add_dash(8, 4);\n provlines_stk.add_dash(2, 2);\n provlines_stk.add_dash(2, 2);\n \n rule_type provlines_rule;\n provlines_rule.append(line_symbolizer(provlines_stk));\n provlines_style.add_rule(provlines_rule);\n \n m.insert_style(\"provlines\",provlines_style);\n \n \/\/ Drainage \n feature_type_style qcdrain_style;\n \n rule_type qcdrain_rule;\n qcdrain_rule.set_filter(create_filter(\"[HYC] = 8\"));\n qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255)));\n qcdrain_style.add_rule(qcdrain_rule);\n \n m.insert_style(\"drainage\",qcdrain_style);\n \n \/\/ Roads 3 and 4 (The \"grey\" roads)\n feature_type_style roads34_style; \n rule_type roads34_rule;\n roads34_rule.set_filter(create_filter(\"[CLASS] = 3 or [CLASS] = 4\"));\n stroke roads34_rule_stk(Color(171,158,137),2.0);\n roads34_rule_stk.set_line_cap(ROUND_CAP);\n roads34_rule_stk.set_line_join(ROUND_JOIN);\n roads34_rule.append(line_symbolizer(roads34_rule_stk));\n roads34_style.add_rule(roads34_rule);\n \n m.insert_style(\"smallroads\",roads34_style);\n \n\n \/\/ Roads 2 (The thin yellow ones)\n feature_type_style roads2_style_1;\n rule_type roads2_rule_1;\n roads2_rule_1.set_filter(create_filter(\"[CLASS] = 2\"));\n stroke roads2_rule_stk_1(Color(171,158,137),4.0);\n roads2_rule_stk_1.set_line_cap(ROUND_CAP);\n roads2_rule_stk_1.set_line_join(ROUND_JOIN);\n roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));\n roads2_style_1.add_rule(roads2_rule_1);\n \n m.insert_style(\"road-border\", roads2_style_1);\n \n feature_type_style roads2_style_2;\n rule_type roads2_rule_2;\n roads2_rule_2.set_filter(create_filter(\"[CLASS] = 2\"));\n stroke roads2_rule_stk_2(Color(255,250,115),2.0);\n roads2_rule_stk_2.set_line_cap(ROUND_CAP);\n roads2_rule_stk_2.set_line_join(ROUND_JOIN);\n roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));\n roads2_style_2.add_rule(roads2_rule_2);\n \n m.insert_style(\"road-fill\", roads2_style_2);\n \n \/\/ Roads 1 (The big orange ones, the highways)\n feature_type_style roads1_style_1;\n rule_type roads1_rule_1;\n roads1_rule_1.set_filter(create_filter(\"[CLASS] = 1\"));\n stroke roads1_rule_stk_1(Color(188,149,28),7.0);\n roads1_rule_stk_1.set_line_cap(ROUND_CAP);\n roads1_rule_stk_1.set_line_join(ROUND_JOIN);\n roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));\n roads1_style_1.add_rule(roads1_rule_1);\n m.insert_style(\"highway-border\", roads1_style_1);\n \n feature_type_style roads1_style_2;\n rule_type roads1_rule_2;\n roads1_rule_2.set_filter(create_filter(\"[CLASS] = 1\"));\n stroke roads1_rule_stk_2(Color(242,191,36),5.0);\n roads1_rule_stk_2.set_line_cap(ROUND_CAP);\n roads1_rule_stk_2.set_line_join(ROUND_JOIN);\n roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));\n roads1_style_2.add_rule(roads1_rule_2);\n m.insert_style(\"highway-fill\", roads1_style_2);\n \n \/\/ Populated Places\n \n feature_type_style popplaces_style;\n rule_type popplaces_rule;\n text_symbolizer popplaces_text_symbolizer(\"GEONAME\",\"DejaVu Sans Book\",10,Color(0,0,0));\n popplaces_text_symbolizer.set_halo_fill(Color(255,255,200));\n popplaces_text_symbolizer.set_halo_radius(1);\n popplaces_rule.append(popplaces_text_symbolizer);\n popplaces_style.add_rule(popplaces_rule);\n \n m.insert_style(\"popplaces\",popplaces_style );\n \n \/\/ Layers\n \/\/ Provincial polygons\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/boundaries\";\n \n Layer lyr(\"Provinces\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"provinces\"); \n m.addLayer(lyr);\n }\n \n \/\/ Drainage\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/qcdrainage\";\n Layer lyr(\"Quebec Hydrography\");\n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"drainage\"); \n m.addLayer(lyr);\n }\n \n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/ontdrainage\";\n \n Layer lyr(\"Ontario Hydrography\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"drainage\"); \n m.addLayer(lyr);\n }\n \n \/\/ Provincial boundaries\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/boundaries_l\";\n Layer lyr(\"Provincial borders\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"provlines\"); \n m.addLayer(lyr);\n }\n \n \/\/ Roads\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/roads\"; \n Layer lyr(\"Roads\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"smallroads\");\n lyr.add_style(\"road-border\");\n lyr.add_style(\"road-fill\");\n lyr.add_style(\"highway-border\");\n lyr.add_style(\"highway-fill\");\n\n m.addLayer(lyr); \n }\n \/\/ popplaces\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/popplaces\";\n p[\"encoding\"] = \"latin1\";\n Layer lyr(\"Populated Places\");\n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"popplaces\"); \n m.addLayer(lyr);\n }\n \n m.zoomToBox(Envelope(1405120.04127408,-247003.813399447,\n 1706357.31328276,-25098.593149577));\n \n Image32 buf(m.getWidth(),m.getHeight());\n agg_renderer ren(m,buf);\n ren.apply();\n \n save_to_file(\"demo.jpg\",\"jpeg\",buf.data());\n save_to_file(\"demo.png\",\"png\",buf.data());\n \n std::cout << \"Two maps have been rendered in the current directory:\\n\"\n \"- demo.jpg\\n\"\n \"- demo.png\\n\"\n \"Have a look!\\n\";\n \n }\n catch ( const mapnik::config_error & ex )\n {\n std::cerr << \"### Configuration error: \" << ex.what();\n return EXIT_FAILURE;\n }\n catch ( const std::exception & ex )\n {\n std::cerr << \"### std::exception: \" << ex.what();\n return EXIT_FAILURE;\n }\n catch ( ... )\n {\n std::cerr << \"### Unknown exception.\" << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n1. define BOOST_SPIRIT_THREADSAFE (should be defined in config.hpp??) to be compatible with the core library. 2. use mapnik install_dir as input argument. 3. Generate three images as in rundemo.py\/*****************************************************************************\n * \n * This file is part of Mapnik (c++ mapping toolkit)\n *\n * Copyright (C) 2006 Artem Pavlenko\n *\n * This library is free software; you can redistribute it and\/or\n * modify it under the terms of the GNU Lesser General Public\n * License as published by the Free Software Foundation; either\n * version 2.1 of the License, or (at your option) any later version.\n *\n * This library is distributed in the hope that it will be useful,\n * but WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n * Lesser General Public License for more details.\n *\n * You should have received a copy of the GNU Lesser General Public\n * License along with this library; if not, write to the Free Software\n * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA\n *\n *****************************************************************************\/\n\/\/ $Id$\n\n\/\/ define before any includes\n#define BOOST_SPIRIT_THREADSAFE\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n#include \n\n\nint main ( int argc , char** argv)\n{ \n if (argc != 2)\n {\n std::cout << \"usage: .\/rundemo \\n\";\n return EXIT_SUCCESS;\n }\n \n using namespace mapnik;\n try {\n std::cout << \" running demo ... \\n\";\n std::string mapnik_dir(argv[1]);\n datasource_cache::instance()->register_datasources(mapnik_dir + \"\/lib\/mapnik\/input\/\"); \n freetype_engine::register_font(mapnik_dir + \"\/lib\/mapnik\/fonts\/DejaVuSans.ttf\");\n \n Map m(800,600);\n m.set_background(color_factory::from_string(\"white\"));\n \n \/\/ create styles\n\n \/\/ Provinces (polygon)\n feature_type_style provpoly_style;\n \n rule_type provpoly_rule_on;\n provpoly_rule_on.set_filter(create_filter(\"[NAME_EN] = 'Ontario'\"));\n provpoly_rule_on.append(polygon_symbolizer(Color(250, 190, 183)));\n provpoly_style.add_rule(provpoly_rule_on);\n \n rule_type provpoly_rule_qc;\n provpoly_rule_qc.set_filter(create_filter(\"[NAME_EN] = 'Quebec'\"));\n provpoly_rule_qc.append(polygon_symbolizer(Color(217, 235, 203)));\n provpoly_style.add_rule(provpoly_rule_qc);\n \n m.insert_style(\"provinces\",provpoly_style);\n\n \/\/ Provinces (polyline)\n feature_type_style provlines_style;\n \n stroke provlines_stk (Color(0,0,0),1.0);\n provlines_stk.add_dash(8, 4);\n provlines_stk.add_dash(2, 2);\n provlines_stk.add_dash(2, 2);\n \n rule_type provlines_rule;\n provlines_rule.append(line_symbolizer(provlines_stk));\n provlines_style.add_rule(provlines_rule);\n \n m.insert_style(\"provlines\",provlines_style);\n \n \/\/ Drainage \n feature_type_style qcdrain_style;\n \n rule_type qcdrain_rule;\n qcdrain_rule.set_filter(create_filter(\"[HYC] = 8\"));\n qcdrain_rule.append(polygon_symbolizer(Color(153, 204, 255)));\n qcdrain_style.add_rule(qcdrain_rule);\n \n m.insert_style(\"drainage\",qcdrain_style);\n \n \/\/ Roads 3 and 4 (The \"grey\" roads)\n feature_type_style roads34_style; \n rule_type roads34_rule;\n roads34_rule.set_filter(create_filter(\"[CLASS] = 3 or [CLASS] = 4\"));\n stroke roads34_rule_stk(Color(171,158,137),2.0);\n roads34_rule_stk.set_line_cap(ROUND_CAP);\n roads34_rule_stk.set_line_join(ROUND_JOIN);\n roads34_rule.append(line_symbolizer(roads34_rule_stk));\n roads34_style.add_rule(roads34_rule);\n \n m.insert_style(\"smallroads\",roads34_style);\n \n\n \/\/ Roads 2 (The thin yellow ones)\n feature_type_style roads2_style_1;\n rule_type roads2_rule_1;\n roads2_rule_1.set_filter(create_filter(\"[CLASS] = 2\"));\n stroke roads2_rule_stk_1(Color(171,158,137),4.0);\n roads2_rule_stk_1.set_line_cap(ROUND_CAP);\n roads2_rule_stk_1.set_line_join(ROUND_JOIN);\n roads2_rule_1.append(line_symbolizer(roads2_rule_stk_1));\n roads2_style_1.add_rule(roads2_rule_1);\n \n m.insert_style(\"road-border\", roads2_style_1);\n \n feature_type_style roads2_style_2;\n rule_type roads2_rule_2;\n roads2_rule_2.set_filter(create_filter(\"[CLASS] = 2\"));\n stroke roads2_rule_stk_2(Color(255,250,115),2.0);\n roads2_rule_stk_2.set_line_cap(ROUND_CAP);\n roads2_rule_stk_2.set_line_join(ROUND_JOIN);\n roads2_rule_2.append(line_symbolizer(roads2_rule_stk_2));\n roads2_style_2.add_rule(roads2_rule_2);\n \n m.insert_style(\"road-fill\", roads2_style_2);\n \n \/\/ Roads 1 (The big orange ones, the highways)\n feature_type_style roads1_style_1;\n rule_type roads1_rule_1;\n roads1_rule_1.set_filter(create_filter(\"[CLASS] = 1\"));\n stroke roads1_rule_stk_1(Color(188,149,28),7.0);\n roads1_rule_stk_1.set_line_cap(ROUND_CAP);\n roads1_rule_stk_1.set_line_join(ROUND_JOIN);\n roads1_rule_1.append(line_symbolizer(roads1_rule_stk_1));\n roads1_style_1.add_rule(roads1_rule_1);\n m.insert_style(\"highway-border\", roads1_style_1);\n \n feature_type_style roads1_style_2;\n rule_type roads1_rule_2;\n roads1_rule_2.set_filter(create_filter(\"[CLASS] = 1\"));\n stroke roads1_rule_stk_2(Color(242,191,36),5.0);\n roads1_rule_stk_2.set_line_cap(ROUND_CAP);\n roads1_rule_stk_2.set_line_join(ROUND_JOIN);\n roads1_rule_2.append(line_symbolizer(roads1_rule_stk_2));\n roads1_style_2.add_rule(roads1_rule_2);\n m.insert_style(\"highway-fill\", roads1_style_2);\n \n \/\/ Populated Places\n \n feature_type_style popplaces_style;\n rule_type popplaces_rule;\n text_symbolizer popplaces_text_symbolizer(\"GEONAME\",\"DejaVu Sans Book\",10,Color(0,0,0));\n popplaces_text_symbolizer.set_halo_fill(Color(255,255,200));\n popplaces_text_symbolizer.set_halo_radius(1);\n popplaces_rule.append(popplaces_text_symbolizer);\n popplaces_style.add_rule(popplaces_rule);\n \n m.insert_style(\"popplaces\",popplaces_style );\n \n \/\/ Layers\n \/\/ Provincial polygons\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/boundaries\";\n \n Layer lyr(\"Provinces\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"provinces\"); \n m.addLayer(lyr);\n }\n \n \/\/ Drainage\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/qcdrainage\";\n Layer lyr(\"Quebec Hydrography\");\n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"drainage\"); \n m.addLayer(lyr);\n }\n \n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/ontdrainage\";\n \n Layer lyr(\"Ontario Hydrography\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"drainage\"); \n m.addLayer(lyr);\n }\n \n \/\/ Provincial boundaries\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/boundaries_l\";\n Layer lyr(\"Provincial borders\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"provlines\"); \n m.addLayer(lyr);\n }\n \n \/\/ Roads\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/roads\"; \n Layer lyr(\"Roads\"); \n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"smallroads\");\n lyr.add_style(\"road-border\");\n lyr.add_style(\"road-fill\");\n lyr.add_style(\"highway-border\");\n lyr.add_style(\"highway-fill\");\n\n m.addLayer(lyr); \n }\n \/\/ popplaces\n {\n parameters p;\n p[\"type\"]=\"shape\";\n p[\"file\"]=\"..\/data\/popplaces\";\n p[\"encoding\"] = \"latin1\";\n Layer lyr(\"Populated Places\");\n lyr.set_datasource(datasource_cache::instance()->create(p));\n lyr.add_style(\"popplaces\"); \n m.addLayer(lyr);\n }\n \n m.zoomToBox(Envelope(1405120.04127408,-247003.813399447,\n 1706357.31328276,-25098.593149577));\n \n Image32 buf(m.getWidth(),m.getHeight());\n agg_renderer ren(m,buf);\n ren.apply();\n \n save_to_file(\"demo.jpg\",\"jpeg\",buf.data());\n save_to_file(\"demo.png\",\"png\",buf.data());\n save_to_file(\"demo256.png\",\"png256\",buf.data());\n std::cout << \"Three maps have been rendered in the current directory:\\n\"\n \"- demo.jpg\\n\"\n \"- demo.png\\n\"\n \"- demo256.png\\n\"\n \"Have a look!\\n\";\n }\n catch ( const mapnik::config_error & ex )\n {\n std::cerr << \"### Configuration error: \" << ex.what();\n return EXIT_FAILURE;\n }\n catch ( const std::exception & ex )\n {\n std::cerr << \"### std::exception: \" << ex.what();\n return EXIT_FAILURE;\n }\n catch ( ... )\n {\n std::cerr << \"### Unknown exception.\" << std::endl;\n return EXIT_FAILURE;\n }\n return EXIT_SUCCESS;\n}\n<|endoftext|>"} {"text":"#include \n#include \n#include \n\n\/* These are input settings that make this demo actually work -- you need to get\n * these, e.g. by referring to the Twitter documentation and by registering an\n * application with them. Here we have examples from Twitter. If you\n * don't enter any, you'll be prompted to enter them at runtime.\n *\/\nstd::string consumer_key = \"\"; \/\/ Key from Twitter\nstd::string consumer_secret = \"\"; \/\/ Secret from Twitter\nstd::string request_token_url = \"http:\/\/twitter.com\/oauth\/request_token\";\nstd::string authorize_url = \"http:\/\/twitter.com\/oauth\/authorize\";\nstd::string access_token_url = \"http:\/\/twitter.com\/oauth\/access_token\";\n\n\nstd::string getUserString(std::string prompt) {\n std::cout << prompt << \" \";\n\n std::string res;\n std::cin >> res;\n std::cout << std::endl;\n return res;\n}\n\nint main(int argc, char** argv) {\n\n \/\/ Initialization\n if (consumer_key.empty()) consumer_key = getUserString(\"Enter consumer key:\");\n if (consumer_secret.empty()) consumer_secret = getUserString(\"Enter consumer secret:\");\n OAuth::Consumer consumer(consumer_key, consumer_secret);\n OAuth::Client oauth(&consumer);\n\n \/\/ Step 1: Get a request token. This is a temporary token that is used for\n \/\/ having the user authorize an access token and to sign the request to\n \/\/ obtain said access token.\n std::string oAuthQueryString =\n oauth.getURLQueryString( OAuth::Http::Get, request_token_url);\n std::cout << \"Enter the following in your browser to get the request token: \" << std::endl;\n std::cout << request_token_url << \"?\" << oAuthQueryString << std::endl;\n std::cout << std::endl;\n\n \/\/ Extract the token and token_secret from the response\n std::string request_token_resp = getUserString(\"Enter the response:\");\n \/\/ This time we pass the response directly and have the library do the\n \/\/ parsing (see next extractToken call for alternative)\n OAuth::Token request_token = OAuth::Token::extract( request_token_resp );\n\n \/\/ Get access token and secret from OAuth object\n std::cout << \"Request Token:\" << std::endl;\n std::cout << \" - oauth_token = \" << request_token.key() << std::endl;\n std::cout << \" - oauth_token_secret = \" << request_token.secret() << std::endl;\n std::cout << std::endl;\n\n \/\/ Step 2: Redirect to the provider. Since this is a CLI script we\n \/\/ do not redirect. In a web application you would redirect the\n \/\/ user to the URL below.\n std::cout << \"Go to the following link in your browser to authorize this application on a user's account:\" << std::endl;\n std::cout << authorize_url << \"?oauth_token=\" << request_token.key() << std::endl;\n\n \/\/ After the user has granted access to you, the consumer, the\n \/\/ provider will redirect you to whatever URL you have told them\n \/\/ to redirect to. You can usually define this in the\n \/\/ oauth_callback argument as well.\n std::string pin = getUserString(\"What is the PIN?\");\n request_token.setPin(pin);\n\n \/\/ Step 3: Once the consumer has redirected the user back to the\n \/\/ oauth_callback URL you can request the access token the user\n \/\/ has approved. You use the request token to sign this\n \/\/ request. After this is done you throw away the request token\n \/\/ and use the access token returned. You should store the oauth\n \/\/ token and token secret somewhere safe, like a database, for\n \/\/ future use.\n oauth = OAuth::Client(&consumer, &request_token);\n \/\/ Note that we explicitly specify an empty body here (it's a GET) so we can\n \/\/ also specify to include the oauth_verifier parameter\n oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( \"\" ), true );\n std::cout << \"Enter the following in your browser to get the final access token & secret: \" << std::endl;\n std::cout << access_token_url << \"?\" << oAuthQueryString;\n std::cout << std::endl;\n\n \/\/ Once they've come back from the browser, extract the token and token_secret from the response\n std::string access_token_resp = getUserString(\"Enter the response:\");\n \/\/ On this extractToken, we do the parsing ourselves (via the library) so we\n \/\/ can extract additional keys that are sent back, in the case of twitter,\n \/\/ the screen_name\n OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp);\n OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data );\n\n std::cout << \"Access token:\" << std::endl;\n std::cout << \" - oauth_token = \" << access_token.key() << std::endl;\n std::cout << \" - oauth_token_secret = \" << access_token.secret() << std::endl;\n std::cout << std::endl;\n std::cout << \"You may now access protected resources using the access tokens above.\" << std::endl;\n std::cout << std::endl;\n\n if (access_token_resp_data.find(\"screen_name\") != access_token_resp_data.end())\n std::cout << \"Also extracted screen name from access token response: \" << access_token_resp_data[\"screen_name\"] << std::endl;\n\n \/\/ E.g., to use the access token, you'd create a new OAuth using\n \/\/ it, discarding the request_token:\n \/\/ oauth = OAuth::Client(&consumer, &access_token);\n\n return 0;\n}\nUpdate Twitter demo URLs in simple_auth.#include \n#include \n#include \n\n\/* These are input settings that make this demo actually work -- you need to get\n * these, e.g. by referring to the Twitter documentation and by registering an\n * application with them. Here we have examples from Twitter. If you\n * don't enter any, you'll be prompted to enter them at runtime.\n *\/\nstd::string consumer_key = \"\"; \/\/ Key from Twitter\nstd::string consumer_secret = \"\"; \/\/ Secret from Twitter\nstd::string request_token_url = \"https:\/\/api.twitter.com\/oauth\/request_token\";\nstd::string authorize_url = \"https:\/\/api.twitter.com\/oauth\/authorize\";\nstd::string access_token_url = \"https:\/\/api.twitter.com\/oauth\/access_token\";\n\n\nstd::string getUserString(std::string prompt) {\n std::cout << prompt << \" \";\n\n std::string res;\n std::cin >> res;\n std::cout << std::endl;\n return res;\n}\n\nint main(int argc, char** argv) {\n\n \/\/ Initialization\n if (consumer_key.empty()) consumer_key = getUserString(\"Enter consumer key:\");\n if (consumer_secret.empty()) consumer_secret = getUserString(\"Enter consumer secret:\");\n OAuth::Consumer consumer(consumer_key, consumer_secret);\n OAuth::Client oauth(&consumer);\n\n \/\/ Step 1: Get a request token. This is a temporary token that is used for\n \/\/ having the user authorize an access token and to sign the request to\n \/\/ obtain said access token.\n std::string oAuthQueryString =\n oauth.getURLQueryString( OAuth::Http::Get, request_token_url);\n std::cout << \"Enter the following in your browser to get the request token: \" << std::endl;\n std::cout << request_token_url << \"?\" << oAuthQueryString << std::endl;\n std::cout << std::endl;\n\n \/\/ Extract the token and token_secret from the response\n std::string request_token_resp = getUserString(\"Enter the response:\");\n \/\/ This time we pass the response directly and have the library do the\n \/\/ parsing (see next extractToken call for alternative)\n OAuth::Token request_token = OAuth::Token::extract( request_token_resp );\n\n \/\/ Get access token and secret from OAuth object\n std::cout << \"Request Token:\" << std::endl;\n std::cout << \" - oauth_token = \" << request_token.key() << std::endl;\n std::cout << \" - oauth_token_secret = \" << request_token.secret() << std::endl;\n std::cout << std::endl;\n\n \/\/ Step 2: Redirect to the provider. Since this is a CLI script we\n \/\/ do not redirect. In a web application you would redirect the\n \/\/ user to the URL below.\n std::cout << \"Go to the following link in your browser to authorize this application on a user's account:\" << std::endl;\n std::cout << authorize_url << \"?oauth_token=\" << request_token.key() << std::endl;\n\n \/\/ After the user has granted access to you, the consumer, the\n \/\/ provider will redirect you to whatever URL you have told them\n \/\/ to redirect to. You can usually define this in the\n \/\/ oauth_callback argument as well.\n std::string pin = getUserString(\"What is the PIN?\");\n request_token.setPin(pin);\n\n \/\/ Step 3: Once the consumer has redirected the user back to the\n \/\/ oauth_callback URL you can request the access token the user\n \/\/ has approved. You use the request token to sign this\n \/\/ request. After this is done you throw away the request token\n \/\/ and use the access token returned. You should store the oauth\n \/\/ token and token secret somewhere safe, like a database, for\n \/\/ future use.\n oauth = OAuth::Client(&consumer, &request_token);\n \/\/ Note that we explicitly specify an empty body here (it's a GET) so we can\n \/\/ also specify to include the oauth_verifier parameter\n oAuthQueryString = oauth.getURLQueryString( OAuth::Http::Get, access_token_url, std::string( \"\" ), true );\n std::cout << \"Enter the following in your browser to get the final access token & secret: \" << std::endl;\n std::cout << access_token_url << \"?\" << oAuthQueryString;\n std::cout << std::endl;\n\n \/\/ Once they've come back from the browser, extract the token and token_secret from the response\n std::string access_token_resp = getUserString(\"Enter the response:\");\n \/\/ On this extractToken, we do the parsing ourselves (via the library) so we\n \/\/ can extract additional keys that are sent back, in the case of twitter,\n \/\/ the screen_name\n OAuth::KeyValuePairs access_token_resp_data = OAuth::ParseKeyValuePairs(access_token_resp);\n OAuth::Token access_token = OAuth::Token::extract( access_token_resp_data );\n\n std::cout << \"Access token:\" << std::endl;\n std::cout << \" - oauth_token = \" << access_token.key() << std::endl;\n std::cout << \" - oauth_token_secret = \" << access_token.secret() << std::endl;\n std::cout << std::endl;\n std::cout << \"You may now access protected resources using the access tokens above.\" << std::endl;\n std::cout << std::endl;\n\n if (access_token_resp_data.find(\"screen_name\") != access_token_resp_data.end())\n std::cout << \"Also extracted screen name from access token response: \" << access_token_resp_data[\"screen_name\"] << std::endl;\n\n \/\/ E.g., to use the access token, you'd create a new OAuth using\n \/\/ it, discarding the request_token:\n \/\/ oauth = OAuth::Client(&consumer, &access_token);\n\n return 0;\n}\n<|endoftext|>"} {"text":"\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Gael Guennebaud \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n#include \n\nnamespace Eigen {\n\ntemplate\nT test_relative_error(const AlignedVector3 &a, const MatrixBase &b)\n{\n return test_relative_error(a.coeffs().template head<3>(), b);\n}\n\n}\n\ntemplate\nvoid alignedvector3()\n{\n Scalar s1 = internal::random();\n Scalar s2 = internal::random();\n typedef Matrix RefType;\n typedef Matrix Mat33;\n typedef AlignedVector3 FastType;\n RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),\n r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());\n FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);\n Mat33 m1(Mat33::Random());\n \n VERIFY_IS_APPROX(f1,r1);\n VERIFY_IS_APPROX(f4,r4);\n\n VERIFY_IS_APPROX(f4+f1,r4+r1);\n VERIFY_IS_APPROX(f4-f1,r4-r1);\n VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);\n VERIFY_IS_APPROX(f4+=f3,r4+=r3);\n VERIFY_IS_APPROX(f4-=f5,r4-=r5);\n VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);\n VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);\n VERIFY_IS_APPROX(f5+f1\/s2-s1*f2,r5+r1\/s2-s1*r2);\n \n VERIFY_IS_APPROX(m1*f4,m1*r4);\n VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);\n \n VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));\n VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));\n VERIFY_IS_APPROX(f2.norm(),r2.norm());\n\n VERIFY_IS_APPROX(f2.normalized(),r2.normalized());\n\n VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());\n \n f2.normalize();\n r2.normalize();\n VERIFY_IS_APPROX(f2,r2);\n \n std::stringstream ss1, ss2;\n ss1 << f1;\n ss2 << r1;\n VERIFY(ss1.str()==ss2.str());\n}\n\nvoid test_alignedvector3()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( alignedvector3() );\n }\n}\nadd regression unit test for previous changeset\/\/ This file is part of Eigen, a lightweight C++ template library\n\/\/ for linear algebra.\n\/\/\n\/\/ Copyright (C) 2009 Gael Guennebaud \n\/\/\n\/\/ This Source Code Form is subject to the terms of the Mozilla\n\/\/ Public License v. 2.0. If a copy of the MPL was not distributed\n\/\/ with this file, You can obtain one at http:\/\/mozilla.org\/MPL\/2.0\/.\n\n#include \"main.h\"\n#include \n\nnamespace Eigen {\n\ntemplate\nT test_relative_error(const AlignedVector3 &a, const MatrixBase &b)\n{\n return test_relative_error(a.coeffs().template head<3>(), b);\n}\n\n}\n\ntemplate\nvoid alignedvector3()\n{\n Scalar s1 = internal::random();\n Scalar s2 = internal::random();\n typedef Matrix RefType;\n typedef Matrix Mat33;\n typedef AlignedVector3 FastType;\n RefType r1(RefType::Random()), r2(RefType::Random()), r3(RefType::Random()),\n r4(RefType::Random()), r5(RefType::Random()), r6(RefType::Random());\n FastType f1(r1), f2(r2), f3(r3), f4(r4), f5(r5), f6(r6);\n Mat33 m1(Mat33::Random());\n \n VERIFY_IS_APPROX(f1,r1);\n VERIFY_IS_APPROX(f4,r4);\n\n VERIFY_IS_APPROX(f4+f1,r4+r1);\n VERIFY_IS_APPROX(f4-f1,r4-r1);\n VERIFY_IS_APPROX(f4+f1-f2,r4+r1-r2);\n VERIFY_IS_APPROX(f4+=f3,r4+=r3);\n VERIFY_IS_APPROX(f4-=f5,r4-=r5);\n VERIFY_IS_APPROX(f4-=f5+f1,r4-=r5+r1);\n VERIFY_IS_APPROX(f5+f1-s1*f2,r5+r1-s1*r2);\n VERIFY_IS_APPROX(f5+f1\/s2-s1*f2,r5+r1\/s2-s1*r2);\n \n VERIFY_IS_APPROX(m1*f4,m1*r4);\n VERIFY_IS_APPROX(f4.transpose()*m1,r4.transpose()*m1);\n \n VERIFY_IS_APPROX(f2.dot(f3),r2.dot(r3));\n VERIFY_IS_APPROX(f2.cross(f3),r2.cross(r3));\n VERIFY_IS_APPROX(f2.norm(),r2.norm());\n\n VERIFY_IS_APPROX(f2.normalized(),r2.normalized());\n\n VERIFY_IS_APPROX((f2+f1).normalized(),(r2+r1).normalized());\n \n f2.normalize();\n r2.normalize();\n VERIFY_IS_APPROX(f2,r2);\n \n {\n FastType f6 = RefType::Zero();\n FastType f7 = FastType::Zero();\n VERIFY_IS_APPROX(f6,f7);\n f6 = r4+r1;\n VERIFY_IS_APPROX(f6,r4+r1);\n f6 -= Scalar(2)*r4;\n VERIFY_IS_APPROX(f6,r1-r4);\n }\n \n std::stringstream ss1, ss2;\n ss1 << f1;\n ss2 << r1;\n VERIFY(ss1.str()==ss2.str());\n}\n\nvoid test_alignedvector3()\n{\n for(int i = 0; i < g_repeat; i++) {\n CALL_SUBTEST( alignedvector3() );\n }\n}\n<|endoftext|>"} {"text":"#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__\n#define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace aleph\n{\n\nnamespace containers\n{\n\n\/*\n Wrapper class for representing a sequence of correlation dimension\n integral values. I want the interface to be as clear as possible.\n*\/\n\nstruct CorrelationDimensionSequence\n{\n std::vector x;\n std::vector y;\n};\n\n\/**\n Calculates samples of the correlation dimension integral for a given\n point cloud. This does *not* yet result in a dimension estimate, but\n only produces a set of points.\n*\/\n\ntemplate <\n class Distance,\n class Container\n> CorrelationDimensionSequence correlationDimensionIntegral(\n const Container& container,\n Distance dist = Distance() )\n{\n auto n = container.size();\n auto d = container.dimension();\n\n std::map distances;\n\n aleph::geometry::distances::Traits traits;\n\n for( decltype(n) i = 0; i < n; i++ )\n {\n auto&& p = container[i];\n\n for( decltype(n) j = i+1; j < n; j++ )\n {\n auto&& q = container[j];\n auto distance = dist( p.begin(),\n q.begin(),\n d );\n\n distances[ traits.from( distance ) ] += 1;\n }\n }\n\n CorrelationDimensionSequence cds;\n cds.x.reserve( distances.size() );\n cds.y.reserve( distances.size() );\n\n \/\/ Determine the correlation dimension integral for all potential\n \/\/ values. This only requires counting how many *pairs* have been\n \/\/ seen by the algorithm.\n\n unsigned seen = 0;\n for( auto&& pair : distances )\n {\n auto&& distance = pair.first;\n auto&& count = pair.second;\n\n seen += count;\n\n if( distance > 0 )\n {\n cds.x.push_back( distance );\n cds.y.push_back( seen \/ static_cast( 0.5 * n * (n-1) ) );\n }\n }\n\n return cds;\n}\n\n\/**\n Estimates the correlation dimension from a correlation dimension\n sequence, which involves calculating a log-log plot of the data,\n and determining the best coefficient for a linear fit.\n*\/\n\ndouble correlationDimension( const CorrelationDimensionSequence& cds )\n{\n if( cds.x.size() != cds.y.size() )\n throw std::runtime_error( \"Inconsistent correlation dimension sequence\" );\n\n std::vector X;\n std::vector Y;\n\n X.reserve( cds.x.size() );\n Y.reserve( cds.y.size() );\n\n auto log = [] ( double x )\n {\n return std::log( x );\n };\n\n std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log );\n std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log );\n\n \/\/ This is a simple linear regression model. We are only interested in\n \/\/ the slope of the regression line, so this is sufficient.\n\n auto cov\n = aleph::math::sampleCovariance( X.begin(), X.end(),\n Y.begin(), Y.end() );\n\n auto var\n = aleph::math::sampleVariance( X.begin(), X.end() );\n\n return cov \/ var;\n}\n\n} \/\/ namespace containers\n\n} \/\/ namespace aleph\n\n#endif\nFixed conversion error#ifndef ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__\n#define ALEPH_CONTAINERS_FRACTAL_DIMENSION_HH__\n\n#include \n\n#include \n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace aleph\n{\n\nnamespace containers\n{\n\n\/*\n Wrapper class for representing a sequence of correlation dimension\n integral values. I want the interface to be as clear as possible.\n*\/\n\nstruct CorrelationDimensionSequence\n{\n std::vector x;\n std::vector y;\n};\n\n\/**\n Calculates samples of the correlation dimension integral for a given\n point cloud. This does *not* yet result in a dimension estimate, but\n only produces a set of points.\n*\/\n\ntemplate <\n class Distance,\n class Container\n> CorrelationDimensionSequence correlationDimensionIntegral(\n const Container& container,\n Distance dist = Distance() )\n{\n auto n = container.size();\n auto d = container.dimension();\n\n std::map distances;\n\n aleph::geometry::distances::Traits traits;\n\n for( decltype(n) i = 0; i < n; i++ )\n {\n auto&& p = container[i];\n\n for( decltype(n) j = i+1; j < n; j++ )\n {\n auto&& q = container[j];\n auto distance = dist( p.begin(),\n q.begin(),\n d );\n\n distances[ traits.from( distance ) ] += 1;\n }\n }\n\n CorrelationDimensionSequence cds;\n cds.x.reserve( distances.size() );\n cds.y.reserve( distances.size() );\n\n \/\/ Determine the correlation dimension integral for all potential\n \/\/ values. This only requires counting how many *pairs* have been\n \/\/ seen by the algorithm.\n\n unsigned seen = 0;\n for( auto&& pair : distances )\n {\n auto&& distance = pair.first;\n auto&& count = pair.second;\n\n seen += count;\n\n if( distance > 0 )\n {\n cds.x.push_back( distance );\n cds.y.push_back( seen \/ ( static_cast( n * (n-1) ) * 0.5 ) );\n }\n }\n\n return cds;\n}\n\n\/**\n Estimates the correlation dimension from a correlation dimension\n sequence, which involves calculating a log-log plot of the data,\n and determining the best coefficient for a linear fit.\n*\/\n\ndouble correlationDimension( const CorrelationDimensionSequence& cds )\n{\n if( cds.x.size() != cds.y.size() )\n throw std::runtime_error( \"Inconsistent correlation dimension sequence\" );\n\n std::vector X;\n std::vector Y;\n\n X.reserve( cds.x.size() );\n Y.reserve( cds.y.size() );\n\n auto log = [] ( double x )\n {\n return std::log( x );\n };\n\n std::transform( cds.x.begin(), cds.x.end(), std::back_inserter( X ), log );\n std::transform( cds.y.begin(), cds.y.end(), std::back_inserter( Y ), log );\n\n \/\/ This is a simple linear regression model. We are only interested in\n \/\/ the slope of the regression line, so this is sufficient.\n\n auto cov\n = aleph::math::sampleCovariance( X.begin(), X.end(),\n Y.begin(), Y.end() );\n\n auto var\n = aleph::math::sampleVariance( X.begin(), X.end() );\n\n return cov \/ var;\n}\n\n} \/\/ namespace containers\n\n} \/\/ namespace aleph\n\n#endif\n<|endoftext|>"} {"text":"#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_\n#define CLOTHO_BIT_BLOCK_FITNESS_HPP_\n\n#include \n#include \"clotho\/fitness\/bit_block_genotyper.hpp\"\n#include \"clotho\/utility\/bit_block_iterator.hpp\"\n\nnamespace clotho {\nnamespace fitness {\n\nstruct no_fit {};\n\ntemplate < class HetFit, class AltHomFit, class RefHomFit, class Result = double >\nclass bit_block_fitness {\npublic:\n typedef Result result_type;\n\n bit_block_fitness() {}\n\n bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) :\n m_hets( hets )\n , m_ahoms(ahoms)\n , m_rhoms(rhoms) {\n }\n\n template < class Block, class ElementIterator >\n result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {\n result_type res = f;\n\n typedef bit_block_genotyper< Block > genotyper;\n\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms);\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms);\n\n return res;\n }\n\n virtual ~bit_block_fitness() {}\nprotected:\n\n template < class Block, class ElementIterator, class FitOp >\n void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {\n typedef clotho::utility::bit_block_iterator< Block > iterator;\n\n iterator it( b ), end;\n while( it != end ) {\n (*op)( res, *(first + *it++));\n }\n }\n\n template < class Block, class ElementIterator, class SetOp, class FitOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {\n Block bits = ( (*sop)(b0, b1) & keep );\n computeFitness( res, bits, first, op );\n }\n\n template < class Block, class ElementIterator, class SetOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }\n\n HetFit m_hets;\n AltHomFit m_ahoms;\n RefHomFit m_rhoms;\n};\n\ntemplate < class HetFit, class HomFit, class Result >\nclass bit_block_fitness< HetFit, HomFit, HomFit, Result > {\npublic:\n typedef Result result_type;\n\n bit_block_fitness( ) {}\n\n bit_block_fitness( const HetFit & hets, const HomFit & homs ) :\n m_hets( hets )\n , m_homs(homs) {\n }\n\n template < class Block, class ElementIterator >\n result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {\n result_type res = f;\n\n typedef bit_block_genotyper< Block > genotyper;\n\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs);\n\n return res;\n }\n\n virtual ~bit_block_fitness() {}\nprotected:\n template < class Block, class ElementIterator, class FitOp >\n inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {\n typedef clotho::utility::bit_block_iterator< Block > iterator;\n\n iterator it( b ), end;\n while( it != end ) {\n (*op)( res, *(first + *it++));\n }\n }\n\n template < class Block, class ElementIterator, class SetOp, class FitOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {\n Block bits = ( (*sop)(b0, b1) & keep );\n computeFitness( res, bits, first, op );\n }\n\n template < class Block, class ElementIterator, class SetOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }\n\n HetFit m_hets;\n HomFit m_homs;\n};\n\ntemplate < class Result >\nclass bit_block_fitness< no_fit, no_fit, no_fit, Result > {\npublic:\n typedef Result result_type;\n\n bit_block_fitness( ) {}\n\n template < class Block, class ElementIterator >\n result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {\n return f;\n }\n\n virtual ~bit_block_fitness() {}\n};\n\n} \/\/ namespace fitness {\n} \/\/ namespace clotho {\n\n#endif \/\/ CLOTHO_BIT_BLOCK_FITNESS_HPP_\nutilizing new bit walking based iterator#ifndef CLOTHO_BIT_BLOCK_FITNESS_HPP_\n#define CLOTHO_BIT_BLOCK_FITNESS_HPP_\n\n#include \n#include \"clotho\/fitness\/bit_block_genotyper.hpp\"\n#include \"clotho\/utility\/bit_block_iterator.hpp\"\n\nnamespace clotho {\nnamespace fitness {\n\nstruct no_fit {};\n\ntemplate < class HetFit, class AltHomFit, class RefHomFit, class Result = double >\nclass bit_block_fitness {\npublic:\n typedef Result result_type;\n\n bit_block_fitness() {}\n\n bit_block_fitness( const HetFit & hets, const AltHomFit & ahoms, const RefHomFit & rhoms ) :\n m_hets( hets )\n , m_ahoms(ahoms)\n , m_rhoms(rhoms) {\n }\n\n template < class Block, class ElementIterator >\n result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {\n result_type res = f;\n\n typedef bit_block_genotyper< Block > genotyper;\n\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_ahoms);\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_ref_homozygous, &m_rhoms);\n\n return res;\n }\n\n virtual ~bit_block_fitness() {}\nprotected:\n\n template < class Block, class ElementIterator, class FitOp >\n void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {\n typedef clotho::utility::bit_block_iterator< Block, clotho::utility::walk_iterator_tag > iterator;\n\n iterator it( b ), end;\n while( it != end ) {\n (*op)( res, *(first + *it++));\n }\n }\n\n template < class Block, class ElementIterator, class SetOp, class FitOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {\n Block bits = ( (*sop)(b0, b1) & keep );\n computeFitness( res, bits, first, op );\n }\n\n template < class Block, class ElementIterator, class SetOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }\n\n HetFit m_hets;\n AltHomFit m_ahoms;\n RefHomFit m_rhoms;\n};\n\ntemplate < class HetFit, class HomFit, class Result >\nclass bit_block_fitness< HetFit, HomFit, HomFit, Result > {\npublic:\n typedef Result result_type;\n\n bit_block_fitness( ) {}\n\n bit_block_fitness( const HetFit & hets, const HomFit & homs ) :\n m_hets( hets )\n , m_homs(homs) {\n }\n\n template < class Block, class ElementIterator >\n result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {\n result_type res = f;\n\n typedef bit_block_genotyper< Block > genotyper;\n\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_all_heterozygous, &m_hets);\n computeFitness( res, b0, b1, keep_mask, first, &genotyper::get_alt_homozygous, &m_homs);\n\n return res;\n }\n\n virtual ~bit_block_fitness() {}\nprotected:\n template < class Block, class ElementIterator, class FitOp >\n inline void computeFitness(result_type & res, Block b, ElementIterator first, FitOp * op ) {\n typedef clotho::utility::bit_block_iterator< Block > iterator;\n\n iterator it( b ), end;\n while( it != end ) {\n (*op)( res, *(first + *it++));\n }\n }\n\n template < class Block, class ElementIterator, class SetOp, class FitOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, FitOp * op ) {\n Block bits = ( (*sop)(b0, b1) & keep );\n computeFitness( res, bits, first, op );\n }\n\n template < class Block, class ElementIterator, class SetOp >\n inline void computeFitness( result_type & res, Block b0, Block b1, Block keep, ElementIterator first, SetOp * sop, no_fit * op ) { }\n\n HetFit m_hets;\n HomFit m_homs;\n};\n\ntemplate < class Result >\nclass bit_block_fitness< no_fit, no_fit, no_fit, Result > {\npublic:\n typedef Result result_type;\n\n bit_block_fitness( ) {}\n\n template < class Block, class ElementIterator >\n result_type operator()( result_type f, Block b0, Block b1, Block keep_mask, ElementIterator first ) {\n return f;\n }\n\n virtual ~bit_block_fitness() {}\n};\n\n} \/\/ namespace fitness {\n} \/\/ namespace clotho {\n\n#endif \/\/ CLOTHO_BIT_BLOCK_FITNESS_HPP_\n<|endoftext|>"} {"text":"#include \n#include \n#include \n#include \n#include \n#include \n#include \n\ndouble goal_tolerance, frontier_tolerance;\nbool random_frontier;\nstd::string map_frame, base_frame, goal_topic;\nsensor_msgs::PointCloud global_frontiers;\ngeometry_msgs::Point32 frontier, old_frontier;\ntf::TransformListener* listener;\nactionlib_msgs::GoalStatusArray global_status;\nstd::vector reached_frontiers;\ntemplate \ndouble distance(T1 from, T2 to)\n{\n return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2));\n}\n\nbool my_pose(geometry_msgs::Pose *pose)\n{\n tf::StampedTransform transform;\n try {\n listener->lookupTransform(map_frame, base_frame, ros::Time(0), transform);\n } catch(tf::TransformException ex) {\n \/\/ROS_ERROR(\"TF %s - %s: %s\", map_frame.c_str(), base_frame.c_str(), ex.what());\n return false;\n }\n pose->position.x = transform.getOrigin().getX();\n pose->position.y = transform.getOrigin().getY();\n pose->position.z = transform.getOrigin().getZ();\n pose->orientation.x = transform.getRotation().getX();\n pose->orientation.y = transform.getRotation().getY();\n pose->orientation.z = transform.getRotation().getZ();\n return true;\n}\n\nvoid frontier_callback(const sensor_msgs::PointCloud::ConstPtr &msg)\n{\n global_frontiers = *msg;\n}\n\nvoid status_callback(const actionlib_msgs::GoalStatusArray::ConstPtr &msg){\n global_status = *msg;\n}\n\nbool frontier_blacklisting( geometry_msgs::Point32 p)\n{\n std::vector::iterator it;\n\n for(it = reached_frontiers.begin(); it != reached_frontiers.end(); it++)\n {\n double dist = distance(*it, p);\n if(dist < goal_tolerance) return false;\n }\n return true;\n}\n\nbool find_next_frontier()\n{\n \n geometry_msgs::Pose pose;\n if(!my_pose(&pose))\n {\n \/\/ROS_WARN(\"Cannot find my pose\");\n return false;\n }\n\n double dist = distance(pose.position, frontier);\n if(dist > goal_tolerance)\n { \n for (int i = 0; i < global_status.status_list.size(); i++)\n {\n int stat = global_status.status_list[i].status;\n if (stat == 1) return false;\n }\n\n } else {\n reached_frontiers.push_back(frontier);\n }\n\n \n if(global_frontiers.points.size() == 0)\n {\n ROS_WARN(\"No frontier to allocate at this time\");\n return false;\n }\n\n if(random_frontier )\n {\n old_frontier = frontier;\n frontier = global_frontiers.points[ rand() % global_frontiers.points.size()];\n return true;\n }\n\n \/\/ nearest frontier allocation\n double mindist = 0, fr_dist;\n bool allocated = false;\n old_frontier = frontier;\n for (int i = 0; i < global_frontiers.points.size(); i++)\n {\n if(!frontier_blacklisting(global_frontiers.points[i])) continue;\n dist = distance(pose.position, global_frontiers.points[i]);\n fr_dist = distance(old_frontier, global_frontiers.points[i]);\n if ( ( old_frontier.x == 0 && old_frontier.y == 0 ) ||( (mindist == 0 || dist < mindist) && dist > goal_tolerance && fr_dist > frontier_tolerance))\n {\n frontier = global_frontiers.points[i];\n mindist = dist;\n allocated = true;\n }\n }\n\n return allocated;\n}\n\n\nint main(int argc, char**argv)\n{\n ros::init(argc, argv, \"frontier_allocator\");\n ros::NodeHandle private_nh(\"~\");\n listener = new tf::TransformListener();\n private_nh.param(\"goal_tolerance\", goal_tolerance, 0.3);\n private_nh.param(\"frontier_tolerance\", frontier_tolerance, 0.3);\n private_nh.param(\"random_frontier\", random_frontier, false);\n private_nh.param(\"map_frame\", map_frame, \"map\");\n private_nh.param(\"base_frame\", base_frame, \"base_link\");\n private_nh.param(\"goal_topic\", goal_topic, \"\/move_base_simple\/goal\");\n\n ros::Subscriber sub_ph = private_nh.subscribe(\"\/phrontier_global\", 100, &frontier_callback);\n ros::Publisher pub_goal = private_nh.advertise(goal_topic, 10);\n ros::Subscriber sub_status = private_nh.subscribe(\"\/move_base\/status\", 10, &status_callback);\n\n srand(time(NULL));\n\n ros::Rate loop_rate(3.0);\n while (ros::ok())\n {\n ros::spinOnce();\n if (find_next_frontier())\n {\n geometry_msgs::PoseStamped goal;\n goal.header.frame_id = map_frame;\n goal.pose.position.x = frontier.x;\n goal.pose.position.y = frontier.y;\n \n goal.pose.orientation.x = 0;\n goal.pose.orientation.y = 0;\n goal.pose.orientation.z = 0;\n goal.pose.orientation.w = 1;\n \n pub_goal.publish(goal);\n \n }\n loop_rate.sleep();\n }\n}fix frontier allocation#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\ntypedef struct {\n geometry_msgs::Point32 position;\n int weight;\n} frontier_t;\n\ndouble goal_tolerance, frontier_tolerance;\nbool random_frontier;\nstd::string map_frame, base_frame, goal_topic;\nsensor_msgs::PointCloud global_frontiers;\nfrontier_t frontier, old_frontier;\ntf::TransformListener* listener;\nactionlib_msgs::GoalStatusArray global_status;\nstd::vector reached_frontiers;\ntemplate \n\ndouble distance(T1 from, T2 to)\n{\n return sqrt(pow(to.x - from.x, 2) + pow(to.y - from.y, 2));\n}\n\nbool my_pose(geometry_msgs::Pose *pose)\n{\n tf::StampedTransform transform;\n try {\n listener->lookupTransform(map_frame, base_frame, ros::Time(0), transform);\n } catch(tf::TransformException ex) {\n \/\/ROS_ERROR(\"TF %s - %s: %s\", map_frame.c_str(), base_frame.c_str(), ex.what());\n return false;\n }\n pose->position.x = transform.getOrigin().getX();\n pose->position.y = transform.getOrigin().getY();\n pose->position.z = transform.getOrigin().getZ();\n pose->orientation.x = transform.getRotation().getX();\n pose->orientation.y = transform.getRotation().getY();\n pose->orientation.z = transform.getRotation().getZ();\n return true;\n}\n\nvoid frontier_callback(const sensor_msgs::PointCloud::ConstPtr &msg)\n{\n global_frontiers = *msg;\n}\n\nvoid status_callback(const actionlib_msgs::GoalStatusArray::ConstPtr &msg){\n global_status = *msg;\n}\n\nfrontier_t frontier_blacklisting( geometry_msgs::Point32 p)\n{\n frontier_t fr;\n fr.weight = 0;\n fr.position = p;\n std::vector::iterator it;\n\n for(it = reached_frontiers.begin(); it != reached_frontiers.end(); it++)\n {\n double dist = distance(it->position, p);\n if(dist < goal_tolerance)\n {\n fr.weight++;\n return fr;\n }\n }\n return fr;\n}\n\nbool find_next_frontier()\n{\n \n geometry_msgs::Pose pose;\n if(!my_pose(&pose))\n {\n \/\/ROS_WARN(\"Cannot find my pose\");\n return false;\n }\n\n double dist = distance(pose.position, frontier.position);\n if(dist > goal_tolerance)\n { \n for (int i = 0; i < global_status.status_list.size(); i++)\n {\n int stat = global_status.status_list[i].status;\n if (stat == 1) return false;\n }\n\n } else {\n frontier.weight++;\n reached_frontiers.push_back(frontier);\n }\n\n \n if(global_frontiers.points.size() == 0)\n {\n ROS_WARN(\"No frontier to allocate at this time\");\n return false;\n }\n\n if(random_frontier )\n {\n old_frontier = frontier;\n frontier.weight=0;\n frontier.position = global_frontiers.points[ rand() % global_frontiers.points.size()];\n return true;\n }\n\n \/\/ nearest frontier allocation\n double mindist = 0, fr_dist;\n bool allocated = false;\n old_frontier = frontier;\n frontier_t fr;\n for (int i = 0; i < global_frontiers.points.size(); i++)\n {\n dist = distance(pose.position, global_frontiers.points[i]);\n fr_dist = distance(old_frontier.position, global_frontiers.points[i]);\n if ( ( old_frontier.position.x == 0 && old_frontier.position.y == 0 ) ||( (mindist == 0 || dist < mindist) && dist > goal_tolerance && fr_dist > frontier_tolerance))\n {\n fr = frontier_blacklisting(global_frontiers.points[i]);\n if(fr.weight <= frontier.weight)\n {\n frontier = fr;\n mindist = dist;\n allocated = true;\n }\n \n }\n }\n\n return allocated;\n}\n\n\nint main(int argc, char**argv)\n{\n ros::init(argc, argv, \"frontier_allocator\");\n ros::NodeHandle private_nh(\"~\");\n listener = new tf::TransformListener();\n private_nh.param(\"goal_tolerance\", goal_tolerance, 0.3);\n private_nh.param(\"frontier_tolerance\", frontier_tolerance, 0.3);\n private_nh.param(\"random_frontier\", random_frontier, false);\n private_nh.param(\"map_frame\", map_frame, \"map\");\n private_nh.param(\"base_frame\", base_frame, \"base_link\");\n private_nh.param(\"goal_topic\", goal_topic, \"\/move_base_simple\/goal\");\n\n ros::Subscriber sub_ph = private_nh.subscribe(\"\/phrontier_global\", 100, &frontier_callback);\n ros::Publisher pub_goal = private_nh.advertise(goal_topic, 10);\n ros::Subscriber sub_status = private_nh.subscribe(\"\/move_base\/status\", 10, &status_callback);\n\n srand(time(NULL));\n\n ros::Rate loop_rate(3.0);\n while (ros::ok())\n {\n ros::spinOnce();\n if (find_next_frontier())\n {\n geometry_msgs::PoseStamped goal;\n goal.header.frame_id = map_frame;\n goal.pose.position.x = frontier.position.x;\n goal.pose.position.y = frontier.position.y;\n \n goal.pose.orientation.x = 0;\n goal.pose.orientation.y = 0;\n goal.pose.orientation.z = 0;\n goal.pose.orientation.w = 1;\n \n pub_goal.publish(goal);\n \n }\n loop_rate.sleep();\n }\n}<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n\n#include \"depthai-shared\/common\/CameraBoardSocket.hpp\"\n#include \"depthai-shared\/common\/CameraInfo.hpp\"\n#include \"depthai-shared\/common\/Extrinsics.hpp\"\n#include \"depthai-shared\/common\/Point3f.hpp\"\n#include \"depthai-shared\/common\/StereoRectification.hpp\"\n\n\/\/ libraries\n#include \"nlohmann\/json.hpp\"\n\nnamespace dai {\n\/**\n * EepromData structure\n *\n * Contains the Calibration and Board data stored on device\n *\/\nstruct EepromData {\n uint32_t version = 6;\n bool swapLeftRightCam = false;\n std::string boardName, boardRev;\n std::unordered_map cameraData;\n StereoRectification stereoRectificationData;\n Extrinsics imuExtrinsics;\n std::vector miscellaneousData;\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData);\n};\n\n} \/\/ namespace dai\nremvoed swap#pragma once\n#include \n#include \n#include \n\n#include \"depthai-shared\/common\/CameraBoardSocket.hpp\"\n#include \"depthai-shared\/common\/CameraInfo.hpp\"\n#include \"depthai-shared\/common\/Extrinsics.hpp\"\n#include \"depthai-shared\/common\/Point3f.hpp\"\n#include \"depthai-shared\/common\/StereoRectification.hpp\"\n\n\/\/ libraries\n#include \"nlohmann\/json.hpp\"\n\nnamespace dai {\n\/**\n * EepromData structure\n *\n * Contains the Calibration and Board data stored on device\n *\/\nstruct EepromData {\n uint32_t version = 6;\n std::string boardName, boardRev;\n std::unordered_map cameraData;\n StereoRectification stereoRectificationData;\n Extrinsics imuExtrinsics;\n std::vector miscellaneousData;\n NLOHMANN_DEFINE_TYPE_INTRUSIVE(EepromData, version, swapLeftRightCam, boardName, boardRev, cameraData, stereoRectificationData, imuExtrinsics, miscellaneousData);\n};\n\n} \/\/ namespace dai\n<|endoftext|>"} {"text":"\/\/ Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ - Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ - Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ - Neither the name of Salesforce.com nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n\/\/ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n\/\/ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace distributions\n{\nnamespace protobuf\n{\n\ninline bool startswith (const char * filename, const char * prefix)\n{\n return strlen(filename) >= strlen(prefix) and\n strncmp(filename, prefix, strlen(prefix)) == 0;\n}\n\ninline bool endswith (const char * filename, const char * suffix)\n{\n return strlen(filename) >= strlen(suffix) and\n strcmp(filename + strlen(filename) - strlen(suffix), suffix) == 0;\n}\n\nclass InFile\n{\npublic:\n\n InFile (const char * filename) : filename_(filename)\n {\n if (startswith(filename, \"-\")) {\n fid_ = -1;\n raw_ = new google::protobuf::io::IstreamInputStream(& std::cin);\n } else {\n fid_ = open(filename, O_RDONLY | O_NOATIME);\n DIST_ASSERT(fid_ != -1, \"failed to open input file \" << filename);\n raw_ = new google::protobuf::io::FileInputStream(fid_);\n }\n\n if (endswith(filename, \".gz\")) {\n gzip_ = new google::protobuf::io::GzipInputStream(raw_);\n coded_ = new google::protobuf::io::CodedInputStream(gzip_);\n } else {\n gzip_ = nullptr;\n coded_ = new google::protobuf::io::CodedInputStream(raw_);\n }\n }\n\n ~InFile ()\n {\n delete coded_;\n delete gzip_;\n delete raw_;\n if (fid_ != -1) {\n close(fid_);\n }\n }\n\n template\n void read (Message & message)\n {\n bool success = message.ParseFromCodedStream(coded_);\n DIST_ASSERT(success, \"failed to parse message from \" << filename_);\n }\n\n template\n bool try_read_stream (Message & message)\n {\n uint32_t message_size = 0;\n if (DIST_LIKELY(coded_->ReadLittleEndian32(& message_size))) {\n auto old_limit = coded_->PushLimit(message_size);\n bool success = message.ParseFromCodedStream(coded_);\n DIST_ASSERT(success, \"failed to parse message from \" << filename_);\n coded_->PopLimit(old_limit);\n return true;\n } else {\n return false;\n }\n }\n\nprivate:\n\n const std::string filename_;\n int fid_;\n google::protobuf::io::ZeroCopyInputStream * raw_;\n google::protobuf::io::GzipInputStream * gzip_;\n google::protobuf::io::CodedInputStream * coded_;\n};\n\n\nclass OutFile\n{\npublic:\n\n OutFile (const char * filename) : filename_(filename)\n {\n if (startswith(filename, \"-\")) {\n fid_ = -1;\n raw_ = new google::protobuf::io::OstreamOutputStream(& std::cout);\n } else {\n fid_ = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664);\n DIST_ASSERT(fid_ != -1, \"failed to open output file \" << filename);\n raw_ = new google::protobuf::io::FileOutputStream(fid_);\n }\n\n if (endswith(filename, \".gz\")) {\n gzip_ = new google::protobuf::io::GzipOutputStream(raw_);\n coded_ = new google::protobuf::io::CodedOutputStream(gzip_);\n } else {\n gzip_ = nullptr;\n coded_ = new google::protobuf::io::CodedOutputStream(raw_);\n }\n }\n\n ~OutFile ()\n {\n delete coded_;\n delete gzip_;\n delete raw_;\n if (fid_ != -1) {\n close(fid_);\n }\n }\n\n template\n void write (Message & message)\n {\n DIST_ASSERT1(message.IsInitialized(), \"message not initialized\");\n message.ByteSize();\n message.SerializeWithCachedSizes(coded_);\n }\n\n template\n void write_stream (Message & message)\n {\n DIST_ASSERT1(message.IsInitialized(), \"message not initialized\");\n uint32_t message_size = message.ByteSize();\n DIST_ASSERT1(message_size > 0, \"zero sized message\");\n coded_->WriteLittleEndian32(message_size);\n message.SerializeWithCachedSizes(coded_);\n }\n\nprivate:\n\n const std::string filename_;\n int fid_;\n google::protobuf::io::ZeroCopyOutputStream * raw_;\n google::protobuf::io::GzipOutputStream * gzip_;\n google::protobuf::io::CodedOutputStream * coded_;\n};\n\n} \/\/ namespace protobuf\n} \/\/ namespace distributions\nAdd assertion to protobuf::OutFile::write\/\/ Copyright (c) 2014, Salesforce.com, Inc. All rights reserved.\n\/\/\n\/\/ Redistribution and use in source and binary forms, with or without\n\/\/ modification, are permitted provided that the following conditions\n\/\/ are met:\n\/\/\n\/\/ - Redistributions of source code must retain the above copyright\n\/\/ notice, this list of conditions and the following disclaimer.\n\/\/ - Redistributions in binary form must reproduce the above copyright\n\/\/ notice, this list of conditions and the following disclaimer in the\n\/\/ documentation and\/or other materials provided with the distribution.\n\/\/ - Neither the name of Salesforce.com nor the names of its contributors\n\/\/ may be used to endorse or promote products derived from this\n\/\/ software without specific prior written permission.\n\/\/\n\/\/ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n\/\/ \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n\/\/ LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS\n\/\/ FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE\n\/\/ COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,\n\/\/ INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,\n\/\/ BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS\n\/\/ OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\n\/\/ ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR\n\/\/ TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE\n\/\/ USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n\n#pragma once\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace distributions\n{\nnamespace protobuf\n{\n\ninline bool startswith (const char * filename, const char * prefix)\n{\n return strlen(filename) >= strlen(prefix) and\n strncmp(filename, prefix, strlen(prefix)) == 0;\n}\n\ninline bool endswith (const char * filename, const char * suffix)\n{\n return strlen(filename) >= strlen(suffix) and\n strcmp(filename + strlen(filename) - strlen(suffix), suffix) == 0;\n}\n\nclass InFile\n{\npublic:\n\n InFile (const char * filename) : filename_(filename)\n {\n if (startswith(filename, \"-\")) {\n fid_ = -1;\n raw_ = new google::protobuf::io::IstreamInputStream(& std::cin);\n } else {\n fid_ = open(filename, O_RDONLY | O_NOATIME);\n DIST_ASSERT(fid_ != -1, \"failed to open input file \" << filename);\n raw_ = new google::protobuf::io::FileInputStream(fid_);\n }\n\n if (endswith(filename, \".gz\")) {\n gzip_ = new google::protobuf::io::GzipInputStream(raw_);\n coded_ = new google::protobuf::io::CodedInputStream(gzip_);\n } else {\n gzip_ = nullptr;\n coded_ = new google::protobuf::io::CodedInputStream(raw_);\n }\n }\n\n ~InFile ()\n {\n delete coded_;\n delete gzip_;\n delete raw_;\n if (fid_ != -1) {\n close(fid_);\n }\n }\n\n template\n void read (Message & message)\n {\n bool success = message.ParseFromCodedStream(coded_);\n DIST_ASSERT(success, \"failed to parse message from \" << filename_);\n }\n\n template\n bool try_read_stream (Message & message)\n {\n uint32_t message_size = 0;\n if (DIST_LIKELY(coded_->ReadLittleEndian32(& message_size))) {\n auto old_limit = coded_->PushLimit(message_size);\n bool success = message.ParseFromCodedStream(coded_);\n DIST_ASSERT(success, \"failed to parse message from \" << filename_);\n coded_->PopLimit(old_limit);\n return true;\n } else {\n return false;\n }\n }\n\nprivate:\n\n const std::string filename_;\n int fid_;\n google::protobuf::io::ZeroCopyInputStream * raw_;\n google::protobuf::io::GzipInputStream * gzip_;\n google::protobuf::io::CodedInputStream * coded_;\n};\n\n\nclass OutFile\n{\npublic:\n\n OutFile (const char * filename) : filename_(filename)\n {\n if (startswith(filename, \"-\")) {\n fid_ = -1;\n raw_ = new google::protobuf::io::OstreamOutputStream(& std::cout);\n } else {\n fid_ = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0664);\n DIST_ASSERT(fid_ != -1, \"failed to open output file \" << filename);\n raw_ = new google::protobuf::io::FileOutputStream(fid_);\n }\n\n if (endswith(filename, \".gz\")) {\n gzip_ = new google::protobuf::io::GzipOutputStream(raw_);\n coded_ = new google::protobuf::io::CodedOutputStream(gzip_);\n } else {\n gzip_ = nullptr;\n coded_ = new google::protobuf::io::CodedOutputStream(raw_);\n }\n }\n\n ~OutFile ()\n {\n delete coded_;\n delete gzip_;\n delete raw_;\n if (fid_ != -1) {\n close(fid_);\n }\n }\n\n template\n void write (Message & message)\n {\n DIST_ASSERT1(message.IsInitialized(), \"message not initialized\");\n bool success = message.SerializeToCodedStream(coded_);\n DIST_ASSERT(success, \"failed to serialize message to \" << filename_);\n }\n\n template\n void write_stream (Message & message)\n {\n DIST_ASSERT1(message.IsInitialized(), \"message not initialized\");\n uint32_t message_size = message.ByteSize();\n DIST_ASSERT1(message_size > 0, \"zero sized message\");\n coded_->WriteLittleEndian32(message_size);\n message.SerializeWithCachedSizes(coded_);\n }\n\nprivate:\n\n const std::string filename_;\n int fid_;\n google::protobuf::io::ZeroCopyOutputStream * raw_;\n google::protobuf::io::GzipOutputStream * gzip_;\n google::protobuf::io::CodedOutputStream * coded_;\n};\n\n} \/\/ namespace protobuf\n} \/\/ namespace distributions\n<|endoftext|>"} {"text":"#include \n#include \"..\/..\/include\/SQLiteDatabase.h\"\n\n#include \n#include \n#include \n\nbool fexists(const std::string& filename) {\n std::ifstream ifile(filename.c_str());\n return ifile;\n};\n\nclass SQLiteDatabaseTestFixture : public ::testing::Test {\npublic:\n SQLiteDatabaseTestFixture( ) {\n test_database_filename_ = \"test.db\";\n }\n\n void SetUp( ) {\n \/\/ code here will execute just before the test ensues\n }\n\n void TearDown( ) {\n \/\/ code here will be called just after the test completes\n \/\/ ok to through exceptions from here if need be\n }\n\n ~SQLiteDatabaseTestFixture( ) {\n remove(\"test.db\");\n }\n\n \/\/ Test Member Variables\n std::string test_database_filename_;\n};\n\nTEST_F(SQLiteDatabaseTestFixture, create_database_test) {\n \n sqlite::SQLiteDatabase db;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n db.close();\n }\n catch (const std::exception & e) {\n std::cout << e.what() << std::endl;\n }\n\n ASSERT_TRUE(fexists(test_database_filename_));\n}\n\nTEST_F(SQLiteDatabaseTestFixture, database_version_test) {\n\n sqlite::SQLiteDatabase db;\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n\n int expected_version = 1;\n db.setVersion(expected_version);\n auto version = db.getVersion();\n\n db.close();\n\n EXPECT_EQ(expected_version, version);\n}\n\nTEST_F(SQLiteDatabaseTestFixture, get_readonly_database_test) {\n\n sqlite::SQLiteDatabase db;\n\n int expected_version = 1;\n int version = 0;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READONLY);\n\n EXPECT_ANY_THROW(db.setVersion(expected_version));\n\n db.close();\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n}\n\nTEST_F(SQLiteDatabaseTestFixture, query_test) {\n\n sqlite::SQLiteDatabase db;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n\n\n \/\/ Create Cars table test data\n const std::string kCreateTable =\n \"CREATE TABLE IF NOT EXISTS cars \"\n \"(mpg text, \"\n \"weight text)\";\n\n db.execQuery(kCreateTable);\n\n db.execQuery(\"INSERT INTO cars \"\n \"VALUES('34', '2000')\");\n\n db.execQuery(\"INSERT INTO cars \"\n \"VALUES('27', '25000')\");\n\n db.execQuery(\"INSERT INTO cars \"\n \"VALUES('16', '5000')\");\n\n std::vector columns;\n columns.push_back(\"mpg\");\n columns.push_back(\"weight\");\n\n std::string selection;\n\n std::vector selectionArgs;\n\n auto c = db.query(true, \"cars\", columns, selection, selectionArgs, \"\", \"\", \"\");\n\n c.next();\n EXPECT_STREQ(c.getString(1).c_str(), \"34\");\n EXPECT_STREQ(c.getString(2).c_str(), \"2000\");\n c.next();\n EXPECT_STREQ(c.getString(1).c_str(), \"27\");\n EXPECT_STREQ(c.getString(2).c_str(), \"25000\");\n c.next();\n EXPECT_STREQ(c.getString(1).c_str(), \"16\");\n EXPECT_STREQ(c.getString(2).c_str(), \"5000\");\n\n db.close();\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n}\n\nadded insert unit test#include \n#include \"..\/..\/include\/SQLiteDatabase.h\"\n\n#include \n#include \n#include \n\nbool fexists(const std::string& filename) {\n std::ifstream ifile(filename.c_str());\n return ifile;\n};\n\nclass SQLiteDatabaseTestFixture : public ::testing::Test {\npublic:\n SQLiteDatabaseTestFixture( ) {\n test_database_filename_ = \"test.db\";\n }\n\n void SetUp( ) {\n \/\/ code here will execute just before the test ensues\n }\n\n void TearDown( ) {\n \/\/ code here will be called just after the test completes\n \/\/ ok to through exceptions from here if need be\n }\n\n ~SQLiteDatabaseTestFixture( ) {\n remove(\"test.db\");\n }\n\n \/\/ Test Member Variables\n std::string test_database_filename_;\n};\n\nTEST_F(SQLiteDatabaseTestFixture, create_database_test) {\n \n sqlite::SQLiteDatabase db;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n db.close();\n }\n catch (const std::exception & e) {\n std::cout << e.what() << std::endl;\n }\n\n ASSERT_TRUE(fexists(test_database_filename_));\n}\n\nTEST_F(SQLiteDatabaseTestFixture, database_version_test) {\n\n sqlite::SQLiteDatabase db;\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n\n int expected_version = 1;\n db.setVersion(expected_version);\n auto version = db.getVersion();\n\n db.close();\n\n EXPECT_EQ(expected_version, version);\n}\n\nTEST_F(SQLiteDatabaseTestFixture, get_readonly_database_test) {\n\n sqlite::SQLiteDatabase db;\n\n int expected_version = 1;\n int version = 0;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READONLY);\n\n EXPECT_ANY_THROW(db.setVersion(expected_version));\n\n db.close();\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n}\n\nTEST_F(SQLiteDatabaseTestFixture, query_test) {\n\n sqlite::SQLiteDatabase db;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n\n\n \/\/ Create Cars table test data\n const std::string kCreateTable =\n \"CREATE TABLE IF NOT EXISTS cars \"\n \"(mpg text, \"\n \"weight text)\";\n\n db.execQuery(kCreateTable);\n\n db.execQuery(\"INSERT INTO cars \"\n \"VALUES('34', '2000')\");\n\n db.execQuery(\"INSERT INTO cars \"\n \"VALUES('27', '25000')\");\n\n db.execQuery(\"INSERT INTO cars \"\n \"VALUES('16', '5000')\");\n\n std::vector columns;\n columns.push_back(\"mpg\");\n columns.push_back(\"weight\");\n\n std::string selection;\n\n std::vector selectionArgs;\n\n auto c = db.query(true, \"cars\", columns, selection, selectionArgs, \"\", \"\", \"\");\n\n c.next();\n EXPECT_STREQ(c.getString(1).c_str(), \"34\");\n EXPECT_STREQ(c.getString(2).c_str(), \"2000\");\n c.next();\n EXPECT_STREQ(c.getString(1).c_str(), \"27\");\n EXPECT_STREQ(c.getString(2).c_str(), \"25000\");\n c.next();\n EXPECT_STREQ(c.getString(1).c_str(), \"16\");\n EXPECT_STREQ(c.getString(2).c_str(), \"5000\");\n\n db.close();\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n}\n\nTEST_F(SQLiteDatabaseTestFixture, insert_test) {\n\n sqlite::SQLiteDatabase db;\n\n try{\n db.open(test_database_filename_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE);\n\n\n \/\/ Create Cars table test data\n const std::string kCreateTable =\n \"CREATE TABLE IF NOT EXISTS cars \"\n \"(mpg text, \"\n \"weight text)\";\n\n db.execQuery(kCreateTable);\n\n const std::string table = \"cars\";\n long id = db.insert(table, std::vector{\"mpg\", \"weight\"}, std::vector{\"34\", \"2000\"}, \"\", std::vector{});\n long id2 = db.insert(table, std::vector{\"mpg\", \"weight\"}, std::vector{\"20\", \"1500\"}, \"\", std::vector{});\n\n EXPECT_EQ(id, 1);\n EXPECT_EQ(id2, 2);\n\n db.close();\n }\n catch (const std::exception & e){\n std::cout << e.what() << std::endl;\n }\n}\n\n<|endoftext|>"} {"text":"\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"rclcpp\/rclcpp.hpp\"\n\n#ifdef RMW_IMPLEMENTATION\n# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX\n# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)\n#else\n# define CLASSNAME(NAME, SUFFIX) NAME\n#endif\n\nTEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete) {\n auto node = rclcpp::Node::make_shared(\"test_spin\");\n\n \/\/ Construct a fake future to wait on\n std::promise promise;\n std::shared_future future(promise.get_future());\n\n \/\/ Make a timer to complete the promise in the future\n int i = 0;\n auto callback = [&promise, &i]() {\n if (i > 0) {\n promise.set_value(true);\n }\n ++i;\n };\n auto timer = node->create_wall_timer(std::chrono::milliseconds(25), callback);\n\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future),\n rclcpp::executors::FutureReturnCode::SUCCESS);\n EXPECT_EQ(future.get(), true);\n}\n\nTEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_timeout) {\n auto node = rclcpp::Node::make_shared(\"test_spin\");\n\n \/\/ Construct a fake future to wait on\n std::promise promise;\n std::shared_future future(promise.get_future());\n\n \/\/ Make a timer to complete the promise in the future\n int i = 0;\n auto callback = [&promise, &i]() {\n if (i > 0) {\n promise.set_value(true);\n }\n ++i;\n };\n auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);\n\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(25)),\n rclcpp::executors::FutureReturnCode::TIMEOUT);\n\n \/\/ If we wait a little longer, we should complete the future\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),\n rclcpp::executors::FutureReturnCode::SUCCESS);\n\n EXPECT_EQ(future.get(), true);\n}\n\nTEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_interrupted) {\n auto node = rclcpp::Node::make_shared(\"test_spin\");\n\n \/\/ Construct a fake future to wait on\n std::promise promise;\n std::shared_future future(promise.get_future());\n\n \/\/ Make a timer to complete the promise in the future\n int i = 0;\n auto callback = [&promise, &i]() {\n if (i > 0) {\n promise.set_value(true);\n }\n ++i;\n };\n auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);\n\n \/\/ Create a timer that will shut down rclcpp before\n auto shutdown_callback = []() {\n rclcpp::utilities::shutdown();\n };\n auto shutdown_timer = node->create_wall_timer(std::chrono::milliseconds(25), shutdown_callback);\n\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),\n rclcpp::executors::FutureReturnCode::INTERRUPTED);\n}\n\nint main(int argc, char ** argv)\n{\n \/\/ NOTE: use custom main to ensure that rclcpp::init is called only once\n rclcpp::init(0, nullptr);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\nfix timer behavior in test_spin\/\/ Copyright 2015 Open Source Robotics Foundation, Inc.\n\/\/\n\/\/ Licensed under the Apache License, Version 2.0 (the \"License\");\n\/\/ you may not use this file except in compliance with the License.\n\/\/ You may obtain a copy of the License at\n\/\/\n\/\/ http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n\/\/\n\/\/ Unless required by applicable law or agreed to in writing, software\n\/\/ distributed under the License is distributed on an \"AS IS\" BASIS,\n\/\/ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n\/\/ See the License for the specific language governing permissions and\n\/\/ limitations under the License.\n\n#include \n#include \n\n#include \"gtest\/gtest.h\"\n\n#include \"rclcpp\/rclcpp.hpp\"\n\n#ifdef RMW_IMPLEMENTATION\n# define CLASSNAME_(NAME, SUFFIX) NAME ## __ ## SUFFIX\n# define CLASSNAME(NAME, SUFFIX) CLASSNAME_(NAME, SUFFIX)\n#else\n# define CLASSNAME(NAME, SUFFIX) NAME\n#endif\n\nTEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete) {\n auto node = rclcpp::Node::make_shared(\"test_spin\");\n\n \/\/ Construct a fake future to wait on\n std::promise promise;\n std::shared_future future(promise.get_future());\n\n \/\/ Make a timer to complete the promise in the future\n auto callback = [&promise]() {\n promise.set_value(true);\n };\n auto timer = node->create_wall_timer(std::chrono::milliseconds(25), callback);\n\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future),\n rclcpp::executors::FutureReturnCode::SUCCESS);\n EXPECT_EQ(future.get(), true);\n}\n\nTEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_timeout) {\n auto node = rclcpp::Node::make_shared(\"test_spin\");\n\n \/\/ Construct a fake future to wait on\n std::promise promise;\n std::shared_future future(promise.get_future());\n\n \/\/ Make a timer to complete the promise in the future\n auto callback = [&promise]() {\n promise.set_value(true);\n };\n auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);\n\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(25)),\n rclcpp::executors::FutureReturnCode::TIMEOUT);\n\n \/\/ If we wait a little longer, we should complete the future\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),\n rclcpp::executors::FutureReturnCode::SUCCESS);\n\n EXPECT_EQ(future.get(), true);\n}\n\nTEST(CLASSNAME(test_spin, RMW_IMPLEMENTATION), spin_until_future_complete_interrupted) {\n auto node = rclcpp::Node::make_shared(\"test_spin\");\n\n \/\/ Construct a fake future to wait on\n std::promise promise;\n std::shared_future future(promise.get_future());\n\n \/\/ Make a timer to complete the promise in the future\n auto callback = [&promise]() {\n promise.set_value(true);\n };\n auto timer = node->create_wall_timer(std::chrono::milliseconds(50), callback);\n\n \/\/ Create a timer that will shut down rclcpp before\n auto shutdown_callback = []() {\n rclcpp::utilities::shutdown();\n };\n auto shutdown_timer = node->create_wall_timer(std::chrono::milliseconds(25), shutdown_callback);\n\n ASSERT_EQ(rclcpp::spin_until_future_complete(node, future, std::chrono::milliseconds(50)),\n rclcpp::executors::FutureReturnCode::INTERRUPTED);\n}\n\nint main(int argc, char ** argv)\n{\n \/\/ NOTE: use custom main to ensure that rclcpp::init is called only once\n rclcpp::init(0, nullptr);\n ::testing::InitGoogleTest(&argc, argv);\n return RUN_ALL_TESTS();\n}\n<|endoftext|>"} {"text":"#include \"mocca\/base\/ByteArray.h\"\n\n#include \n#include \n\nstatic_assert(std::numeric_limits::is_iec559 == true, \"Unsupported floating point type\");\nstatic_assert(std::numeric_limits::is_iec559 == true, \"Unsupported floating point type\");\n\nnamespace mocca {\n\nconst unsigned char ByteArray::trueConst;\nconst unsigned char ByteArray::falseConst;\n\nByteArray::ByteArray(uint32_t capacity)\n : data_(new unsigned char[capacity])\n , capacity_(capacity)\n , size_(0)\n , readPos_(0) {}\n\nByteArray::ByteArray(const ByteArray& other)\n : data_(new unsigned char[other.capacity_])\n , capacity_(other.capacity_)\n , size_(other.size_)\n , readPos_(other.readPos_) {\n memcpy(data_.get(), other.data_.get(), other.size_);\n}\n\nByteArray::ByteArray(ByteArray&& other)\n : data_(std::move(other.data_))\n , capacity_(other.capacity_)\n , size_(other.size_)\n , readPos_(other.readPos_) {\n other.capacity_ = 0;\n other.size_ = 0;\n other.readPos_ = 0;\n}\n\nByteArray& ByteArray::operator=(ByteArray other) {\n swap(other, *this);\n return *this;\n}\n\nvoid swap(ByteArray& lhs, ByteArray& rhs) {\n using std::swap;\n swap(lhs.data_, rhs.data_);\n swap(lhs.capacity_, rhs.capacity_);\n swap(lhs.size_, rhs.size_);\n swap(lhs.readPos_, rhs.readPos_);\n}\n\nunsigned char* ByteArray::data() {\n return data_.get();\n}\n\nconst unsigned char* ByteArray::data() const {\n return data_.get();\n}\n\nuint32_t ByteArray::size() const {\n return size_;\n}\n\nvoid ByteArray::setSize(uint32_t size) {\n if (size > capacity_) {\n throw Error(\"Size exceeds capacity of the byte array\", __FILE__, __LINE__);\n }\n size_ = size;\n}\n\nbool ByteArray::isEmpty() const {\n return size_ == 0;\n}\n\nuint32_t ByteArray::capacity() const {\n return capacity_;\n}\n\nvoid ByteArray::resize(uint32_t newCapacity) {\n auto newData = std::unique_ptr(new unsigned char[newCapacity]);\n memcpy(newData.get(), data_.get(), size_);\n data_ = std::move(newData);\n capacity_ = newCapacity;\n}\n\nvoid ByteArray::append(const void* data, uint32_t size) {\n if (capacity_ < size_ + size) {\n resize(size_ + std::max(2 * size, 256u));\n }\n memcpy(data_.get() + size_, data, size);\n size_ += size;\n}\n\nvoid mocca::ByteArray::append(const ByteArray& byteArray) {\n append(byteArray.data(), byteArray.size());\n}\n\nByteArray ByteArray::createFromRaw(const void* raw, uint32_t size) {\n auto byteArray = ByteArray(size);\n memcpy(byteArray.data_.get(), raw, size);\n byteArray.size_ = size;\n return byteArray;\n}\n\nByteArray& ByteArray::operator<<(int32_t val) {\n append(&val, sizeof(int32_t));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(int32_t& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(int32_t) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(int32_t));\n readPos_ += sizeof(int32_t);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(uint32_t val) {\n return (*this << (int32_t)val);\n}\n\nByteArray& ByteArray::operator>>(uint32_t& val) {\n return (*this >> (int32_t&)val);\n}\n\nByteArray& ByteArray::operator<<(int64_t val) {\n append(&val, sizeof(int64_t));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(int64_t& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(int64_t) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(int64_t));\n readPos_ += sizeof(int64_t);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(uint64_t val) {\n return (*this << (int64_t)val);\n}\n\nByteArray& ByteArray::operator>>(uint64_t& val) {\n return (*this >> (int64_t&)val);\n}\n\nByteArray& ByteArray::operator<<(bool val) {\n if (val) {\n append(&trueConst, sizeof(unsigned char));\n } else {\n append(&falseConst, sizeof(unsigned char));\n }\n return *this;\n}\n\nByteArray& ByteArray::operator>>(bool& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(unsigned char) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n unsigned char code;\n memcpy(&code, data_.get() + readPos_, sizeof(unsigned char));\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (code != trueConst && code != falseConst) {\n throw Error(\"Package corrupted\", __FILE__, __LINE__);\n }\n#endif\n val = (code & trueConst) != 0;\n readPos_ += sizeof(unsigned char);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(float val) {\n append(&val, sizeof(float));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(float& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(float) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(float));\n readPos_ += sizeof(float);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(double val) {\n append(&val, sizeof(double));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(double& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(double) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(double));\n readPos_ += sizeof(double);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(const std::string& val) {\n *this << (uint32_t)val.size();\n append(val.c_str(), (uint32_t)val.size());\n return *this;\n}\n\nByteArray& ByteArray::operator>>(std::string& val) {\n uint32_t strSize;\n *this >> strSize;\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + strSize > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n val.reserve(strSize);\n val = std::string((char*)data_.get() + readPos_, strSize);\n readPos_ += strSize;\n return *this;\n}\n\nByteArray& ByteArray::operator<<(const char* val) {\n return (*this << std::string(val));\n}\n\nByteArray& ByteArray::operator<<(const ByteArray& val) {\n *this << (int32_t)val.size();\n append(val.data(), val.size());\n return *this;\n}\n\nByteArray& ByteArray::operator>>(ByteArray& val) {\n int32_t innerSize;\n *this >> innerSize;\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + innerSize > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n val.append(data_.get() + readPos_, innerSize);\n readPos_ += innerSize;\n return *this;\n}\n\nunsigned char& mocca::ByteArray::operator[](uint32_t index) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (index < 0 || index >= size_) {\n throw Error(\"Index out of bounds\", __FILE__, __LINE__);\n }\n#endif\n return data_[index];\n}\n\nconst unsigned char& mocca::ByteArray::operator[](uint32_t index) const {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (index < 0 || index >= size_) {\n throw Error(\"Index out of bounds\", __FILE__, __LINE__);\n }\n#endif\n return data_[index];\n}\n\nvoid ByteArray::resetReadPos() {\n readPos_ = 0;\n}\n}fixed clang warning #include \"mocca\/base\/ByteArray.h\"\n\n#include \n#include \n\nstatic_assert(std::numeric_limits::is_iec559 == true, \"Unsupported floating point type\");\nstatic_assert(std::numeric_limits::is_iec559 == true, \"Unsupported floating point type\");\n\nnamespace mocca {\n\nconst unsigned char ByteArray::trueConst;\nconst unsigned char ByteArray::falseConst;\n\nByteArray::ByteArray(uint32_t capacity)\n : data_(new unsigned char[capacity])\n , capacity_(capacity)\n , size_(0)\n , readPos_(0) {}\n\nByteArray::ByteArray(const ByteArray& other)\n : data_(new unsigned char[other.capacity_])\n , capacity_(other.capacity_)\n , size_(other.size_)\n , readPos_(other.readPos_) {\n memcpy(data_.get(), other.data_.get(), other.size_);\n}\n\nByteArray::ByteArray(ByteArray&& other)\n : data_(std::move(other.data_))\n , capacity_(other.capacity_)\n , size_(other.size_)\n , readPos_(other.readPos_) {\n other.capacity_ = 0;\n other.size_ = 0;\n other.readPos_ = 0;\n}\n\nByteArray& ByteArray::operator=(ByteArray other) {\n swap(other, *this);\n return *this;\n}\n\nvoid swap(ByteArray& lhs, ByteArray& rhs) {\n using std::swap;\n swap(lhs.data_, rhs.data_);\n swap(lhs.capacity_, rhs.capacity_);\n swap(lhs.size_, rhs.size_);\n swap(lhs.readPos_, rhs.readPos_);\n}\n\nunsigned char* ByteArray::data() {\n return data_.get();\n}\n\nconst unsigned char* ByteArray::data() const {\n return data_.get();\n}\n\nuint32_t ByteArray::size() const {\n return size_;\n}\n\nvoid ByteArray::setSize(uint32_t size) {\n if (size > capacity_) {\n throw Error(\"Size exceeds capacity of the byte array\", __FILE__, __LINE__);\n }\n size_ = size;\n}\n\nbool ByteArray::isEmpty() const {\n return size_ == 0;\n}\n\nuint32_t ByteArray::capacity() const {\n return capacity_;\n}\n\nvoid ByteArray::resize(uint32_t newCapacity) {\n auto newData = std::unique_ptr(new unsigned char[newCapacity]);\n memcpy(newData.get(), data_.get(), size_);\n data_ = std::move(newData);\n capacity_ = newCapacity;\n}\n\nvoid ByteArray::append(const void* data, uint32_t size) {\n if (capacity_ < size_ + size) {\n resize(size_ + std::max(2 * size, 256u));\n }\n memcpy(data_.get() + size_, data, size);\n size_ += size;\n}\n\nvoid mocca::ByteArray::append(const ByteArray& byteArray) {\n append(byteArray.data(), byteArray.size());\n}\n\nByteArray ByteArray::createFromRaw(const void* raw, uint32_t size) {\n auto byteArray = ByteArray(size);\n memcpy(byteArray.data_.get(), raw, size);\n byteArray.size_ = size;\n return byteArray;\n}\n\nByteArray& ByteArray::operator<<(int32_t val) {\n append(&val, sizeof(int32_t));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(int32_t& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(int32_t) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(int32_t));\n readPos_ += sizeof(int32_t);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(uint32_t val) {\n return (*this << (int32_t)val);\n}\n\nByteArray& ByteArray::operator>>(uint32_t& val) {\n return (*this >> (int32_t&)val);\n}\n\nByteArray& ByteArray::operator<<(int64_t val) {\n append(&val, sizeof(int64_t));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(int64_t& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(int64_t) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(int64_t));\n readPos_ += sizeof(int64_t);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(uint64_t val) {\n return (*this << (int64_t)val);\n}\n\nByteArray& ByteArray::operator>>(uint64_t& val) {\n return (*this >> (int64_t&)val);\n}\n\nByteArray& ByteArray::operator<<(bool val) {\n if (val) {\n append(&trueConst, sizeof(unsigned char));\n } else {\n append(&falseConst, sizeof(unsigned char));\n }\n return *this;\n}\n\nByteArray& ByteArray::operator>>(bool& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(unsigned char) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n unsigned char code;\n memcpy(&code, data_.get() + readPos_, sizeof(unsigned char));\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (code != trueConst && code != falseConst) {\n throw Error(\"Package corrupted\", __FILE__, __LINE__);\n }\n#endif\n val = (code & trueConst) != 0;\n readPos_ += sizeof(unsigned char);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(float val) {\n append(&val, sizeof(float));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(float& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(float) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(float));\n readPos_ += sizeof(float);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(double val) {\n append(&val, sizeof(double));\n return *this;\n}\n\nByteArray& ByteArray::operator>>(double& val) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + sizeof(double) > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n memcpy(&val, data_.get() + readPos_, sizeof(double));\n readPos_ += sizeof(double);\n return *this;\n}\n\nByteArray& ByteArray::operator<<(const std::string& val) {\n *this << (uint32_t)val.size();\n append(val.c_str(), (uint32_t)val.size());\n return *this;\n}\n\nByteArray& ByteArray::operator>>(std::string& val) {\n uint32_t strSize;\n *this >> strSize;\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + strSize > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n val.reserve(strSize);\n val = std::string((char*)data_.get() + readPos_, strSize);\n readPos_ += strSize;\n return *this;\n}\n\nByteArray& ByteArray::operator<<(const char* val) {\n return (*this << std::string(val));\n}\n\nByteArray& ByteArray::operator<<(const ByteArray& val) {\n *this << (int32_t)val.size();\n append(val.data(), val.size());\n return *this;\n}\n\nByteArray& ByteArray::operator>>(ByteArray& val) {\n int32_t innerSize;\n *this >> innerSize;\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (readPos_ + innerSize > size_) {\n throw Error(\"Reading beyond end of packet\", __FILE__, __LINE__);\n }\n#endif\n val.append(data_.get() + readPos_, innerSize);\n readPos_ += innerSize;\n return *this;\n}\n\nunsigned char& mocca::ByteArray::operator[](uint32_t index) {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (index >= size_) {\n throw Error(\"Index out of bounds\", __FILE__, __LINE__);\n }\n#endif\n return data_[index];\n}\n\nconst unsigned char& mocca::ByteArray::operator[](uint32_t index) const {\n#ifdef MOCCA_BYTEARRAY_CHECKS\n if (index >= size_) {\n throw Error(\"Index out of bounds\", __FILE__, __LINE__);\n }\n#endif\n return data_[index];\n}\n\nvoid ByteArray::resetReadPos() {\n readPos_ = 0;\n}\n}<|endoftext|>"} {"text":"#include \"stdafx.hpp\"\n\n#include \n\n#include \"CppUnitTest.h\"\n#include \"..\\TestUtilities\\TestUtilities.hpp\"\n#include \"..\\TestUtilities\\QuantityComparisons.hpp\"\n#include \"..\\TestUtilities\\GeometryComparisons.hpp\"\n#include \"..\\TestUtilities\\Algebra.hpp\"\n\n#include \"..\\Quantities\\Dimensionless.hpp\"\n#include \"..\\Quantities\\Quantities.hpp\"\n#include \"..\\Quantities\\SI.hpp\"\n#include \"..\\Quantities\\Constants.hpp\"\n#include \"..\\Quantities\\UK.hpp\"\n#include \"..\\Quantities\\BIPM.hpp\"\n#include \"..\\Quantities\\Astronomy.hpp\"\n#include \"..\\Geometry\\R3Element.hpp\"\n#include \"..\\Geometry\\Grassmann.hpp\"\n#include \"..\\Quantities\\ElementaryFunctions.hpp\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace Principia {\nnamespace GeometryTests\n{\nusing namespace Geometry;\nusing namespace Quantities;\nusing namespace SI;\nusing namespace UK;\nusing namespace BIPM;\nusing namespace Astronomy;\nusing namespace Constants;\nusing namespace TestUtilities;\n\nTEST_CLASS(GeometryTests)\n{\n public:\n struct World;\n TEST_METHOD(Dumb3Vector) {\n R3Element nullVector(0 * Metre \/ Second,\n 0 * Metre \/ Second,\n 0 * Metre \/ Second);\n R3Element u(1 * Metre \/ Second,\n 120 * Kilo(Metre) \/ Hour,\n -SpeedOfLight);\n R3Element v(-20 * Knot,\n 2 * π * AstronomicalUnit \/ JulianYear,\n 1 * Admiralty::NauticalMile \/ Hour);\n R3Element w(-1 * Mile \/ Hour, -2 * Foot \/ Second, -3 * Knot);\n R3Element a(88 * Mile \/ Hour, 300 * Metre \/ Second, 46 * Knot);\n AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));\n TestVectorSpace,\n Dimensionless>(nullVector, u, v, w, Dimensionless(0),\n Dimensionless(1), e, Dimensionless(42));\n TestAlternatingBilinearMap(Cross, u,\n v, w, a, Dimensionless(42));\n TestSymmetricPositiveDefiniteBilinearMap(Dot,\n u, v, w, a, Dimensionless(42));\n }\n\n TEST_METHOD(SpecialOrthogonalLieAlgebra) {\n R3Element u(3, -42, 0);\n R3Element v(-π, -e, -1);\n R3Element w(2, 2, 2);\n R3Element a(1.2, 2.3, 3.4);\n TestLieBracket(Commutator,\n Bivector(u),\n Bivector(v),\n Bivector(w),\n Bivector(a), Dimensionless(0.42));\n }\n\n TEST_METHOD(VectorSpaces) {\n R3Element nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);\n R3Element u(3 * Metre, -42 * Metre, 0 * Metre);\n R3Element v(-π * Metre, -e * Metre, -1 * Metre);\n R3Element w(2 * Metre, 2 * Metre, 2 * Metre);\n R3Element a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);\n {\n std::function,\n Vector)> vectorInnerProduct =\n [](Vector a, Vector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Bivector)> bivectorInnerProduct =\n [](Bivector a, Bivector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Trivector)> trivectorInnerProduct =\n [](Trivector a, Trivector b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector(nullDisplacement),\n Vector(u), Vector(v),\n Vector(w), Vector(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector(nullDisplacement),\n Bivector(u),\n Bivector(v),\n Bivector(w),\n Bivector(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector(nullDisplacement.x),\n Trivector(u.y),\n Trivector(v.z),\n Trivector(w.x),\n Trivector(a.y),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n {\n std::function,\n Vector)>\n vectorInnerProduct = [](Vector a,\n Vector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Bivector)>\n bivectorInnerProduct = [](Bivector a,\n Bivector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Trivector)>\n trivectorInnerProduct = [](Trivector a,\n Trivector b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector(nullDisplacement \/ Metre),\n Vector(u \/ Metre),\n Vector(v \/ Metre),\n Vector(w \/ Metre),\n Vector(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector(nullDisplacement \/ Metre),\n Bivector(u \/ Metre),\n Bivector(v \/ Metre),\n Bivector(w \/ Metre),\n Bivector(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector(nullDisplacement.x \/ Metre),\n Trivector(u.y \/ Metre),\n Trivector(v.z \/ Metre),\n Trivector(w.x \/ Metre),\n Trivector(a.y \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n }\n TEST_METHOD(GrassmannAlgebra) {\n R3Element u(3, -42, 0);\n R3Element v(-π, -e, -1);\n R3Element w(2, 2, 2);\n R3Element a(1.2, 2.3, 3.4);\n std::function(Vector,\n Vector)> vectorWedge =\n [](Vector a, Vector b) {\n return Wedge(a, b);\n };\n TestAlternatingBilinearMap(vectorWedge, Vector(u),\n Vector(u),\n Vector(u),\n Vector(u),\n Dimensionless(6 * 9));\n }\n};\n} \/\/ namespace GeometryTests\n} \/\/ namespace Principia\nNot sure that's a good idea, but then it's easy to get confused between all these '}'s.#include \"stdafx.hpp\"\n\n#include \n\n#include \"CppUnitTest.h\"\n#include \"..\\TestUtilities\\TestUtilities.hpp\"\n#include \"..\\TestUtilities\\QuantityComparisons.hpp\"\n#include \"..\\TestUtilities\\GeometryComparisons.hpp\"\n#include \"..\\TestUtilities\\Algebra.hpp\"\n\n#include \"..\\Quantities\\Dimensionless.hpp\"\n#include \"..\\Quantities\\Quantities.hpp\"\n#include \"..\\Quantities\\SI.hpp\"\n#include \"..\\Quantities\\Constants.hpp\"\n#include \"..\\Quantities\\UK.hpp\"\n#include \"..\\Quantities\\BIPM.hpp\"\n#include \"..\\Quantities\\Astronomy.hpp\"\n#include \"..\\Geometry\\R3Element.hpp\"\n#include \"..\\Geometry\\Grassmann.hpp\"\n#include \"..\\Quantities\\ElementaryFunctions.hpp\"\n\nusing namespace Microsoft::VisualStudio::CppUnitTestFramework;\n\nnamespace Principia {\nnamespace GeometryTests\n{\nusing namespace Geometry;\nusing namespace Quantities;\nusing namespace SI;\nusing namespace UK;\nusing namespace BIPM;\nusing namespace Astronomy;\nusing namespace Constants;\nusing namespace TestUtilities;\n\nTEST_CLASS(GeometryTests)\n{\n public:\n struct World;\n TEST_METHOD(Dumb3Vector) {\n R3Element nullVector(0 * Metre \/ Second,\n 0 * Metre \/ Second,\n 0 * Metre \/ Second);\n R3Element u(1 * Metre \/ Second,\n 120 * Kilo(Metre) \/ Hour,\n -SpeedOfLight);\n R3Element v(-20 * Knot,\n 2 * π * AstronomicalUnit \/ JulianYear,\n 1 * Admiralty::NauticalMile \/ Hour);\n R3Element w(-1 * Mile \/ Hour, -2 * Foot \/ Second, -3 * Knot);\n R3Element a(88 * Mile \/ Hour, 300 * Metre \/ Second, 46 * Knot);\n AssertEqual((e * Dimensionless(42)) * v, e * (Dimensionless(42) * v));\n TestVectorSpace,\n Dimensionless>(nullVector, u, v, w, Dimensionless(0),\n Dimensionless(1), e, Dimensionless(42));\n TestAlternatingBilinearMap(Cross, u,\n v, w, a, Dimensionless(42));\n TestSymmetricPositiveDefiniteBilinearMap(Dot,\n u, v, w, a, Dimensionless(42));\n } \/\/ TEST_METHOD Dumb3Vector\n\n TEST_METHOD(SpecialOrthogonalLieAlgebra) {\n R3Element u(3, -42, 0);\n R3Element v(-π, -e, -1);\n R3Element w(2, 2, 2);\n R3Element a(1.2, 2.3, 3.4);\n TestLieBracket(Commutator,\n Bivector(u),\n Bivector(v),\n Bivector(w),\n Bivector(a), Dimensionless(0.42));\n } \/\/ TEST_METHOD SpecialOrthogonalLieAlgebra\n\n TEST_METHOD(VectorSpaces) {\n R3Element nullDisplacement(0 * Metre, 0 * Metre, 0 * Metre);\n R3Element u(3 * Metre, -42 * Metre, 0 * Metre);\n R3Element v(-π * Metre, -e * Metre, -1 * Metre);\n R3Element w(2 * Metre, 2 * Metre, 2 * Metre);\n R3Element a(1 * Inch, 2 * Foot, 3 * Admiralty::Fathom);\n {\n std::function,\n Vector)> vectorInnerProduct =\n [](Vector a, Vector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Bivector)> bivectorInnerProduct =\n [](Bivector a, Bivector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Trivector)> trivectorInnerProduct =\n [](Trivector a, Trivector b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector(nullDisplacement),\n Vector(u), Vector(v),\n Vector(w), Vector(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector(nullDisplacement),\n Bivector(u),\n Bivector(v),\n Bivector(w),\n Bivector(a),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector(nullDisplacement.x),\n Trivector(u.y),\n Trivector(v.z),\n Trivector(w.x),\n Trivector(a.y),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n {\n std::function,\n Vector)>\n vectorInnerProduct = [](Vector a,\n Vector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Bivector)>\n bivectorInnerProduct = [](Bivector a,\n Bivector b) {\n return InnerProduct(a, b);\n };\n std::function,\n Trivector)>\n trivectorInnerProduct = [](Trivector a,\n Trivector b) {\n return InnerProduct(a, b);\n };\n TestInnerProductSpace(vectorInnerProduct,\n Vector(nullDisplacement \/ Metre),\n Vector(u \/ Metre),\n Vector(v \/ Metre),\n Vector(w \/ Metre),\n Vector(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(bivectorInnerProduct,\n Bivector(nullDisplacement \/ Metre),\n Bivector(u \/ Metre),\n Bivector(v \/ Metre),\n Bivector(w \/ Metre),\n Bivector(a \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n TestInnerProductSpace(trivectorInnerProduct,\n Trivector(nullDisplacement.x \/ Metre),\n Trivector(u.y \/ Metre),\n Trivector(v.z \/ Metre),\n Trivector(w.x \/ Metre),\n Trivector(a.y \/ Metre),\n Dimensionless(0), Dimensionless(1), Sqrt(163),\n -Sqrt(2));\n }\n } \/\/ TEST_METHOD VectorSpaces\n\n TEST_METHOD(GrassmannAlgebra) {\n R3Element u(3, -42, 0);\n R3Element v(-π, -e, -1);\n R3Element w(2, 2, 2);\n R3Element a(1.2, 2.3, 3.4);\n std::function(Vector,\n Vector)> vectorWedge =\n [](Vector a, Vector b) {\n return Wedge(a, b);\n };\n TestAlternatingBilinearMap(vectorWedge, Vector(u),\n Vector(u),\n Vector(u),\n Vector(u),\n Dimensionless(6 * 9));\n } \/\/ TEST_METHOD GrassmannAlgebra\n\n}; \/\/ TEST_CLASS GeometryTests\n} \/\/ namespace GeometryTests\n} \/\/ namespace Principia\n<|endoftext|>"} {"text":"\/**\n * \\file dcs\/testbed\/application.hpp\n *\n * \\brief Generic application.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * \n *\n * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef DCS_TESTBED_APPLICATION_HPP\n#define DCS_TESTBED_APPLICATION_HPP\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace dcs { namespace testbed {\n\ntemplate \nclass application: public base_application\n{\n\tprivate: typedef base_application base_type;\n\tpublic: typedef typename base_type::traits_type traits_type;\n\tpublic: typedef typename base_type::vm_pointer vm_pointer;\n\tpublic: typedef typename base_type::sensor_pointer sensor_pointer;\n\tpublic: typedef typename base_type::slo_checker_type slo_checker_type;\n\tpublic: typedef typename base_type::real_type real_type;\n\/\/\tprivate: typedef typename base_type::vm_type::identifier_type vm _identifier_type;\n\/\/\tprivate: typedef ::std::map vm_container;\n\tprivate: typedef ::std::vector vm_container;\n\tprivate: typedef ::std::map sensor_map;\n\tprivate: typedef ::std::map slo_checker_map;\n\n\n\tpublic: application()\n\t{\n\t}\n\n\tpublic: template \n\t\t\tapplication(IterT vm_first, IterT vm_last)\n\t: vms_(vm_first,vm_last)\n\t{\n\/\/\t\twhile (vm_first != vm_last)\n\/\/\t\t{\n\/\/\t\t\tvms_[*(vm_first)->id()] = *vm_first;\n\/\/\t\t\t++vm_first;\n\/\/\t\t}\n\t}\n\n\tprivate: ::std::size_t do_num_vms() const\n\t{\n\t\treturn vms_.size();\n\t}\n\n\tprivate: ::std::vector do_vms() const\n\t{\n\/\/\t\t::std::vector vms(vms_.size());\n\/\/\n\/\/\t\t::std::size_t i(0);\n\/\/\t\ttypename vm_container::const_iterator end_it(vms_.end());\n\/\/\t\tfor (typename vm_container::const_iterator it = vms_.begin();\n\/\/\t\t\t it != end_it;\n\/\/\t\t\t ++it)\n\/\/\t\t{\n\/\/\t\t\tvms[i] = *it;\n\/\/\t\t\t++i;\n\/\/\t\t}\n\/\/\n\/\/\t\treturn vms;\n\t\treturn vms_;\n\t}\n\n\/\/\tprivate: vm_pointer do_vm(vm_identifier_type id) const\n\/\/\t{\n\/\/\t\tDCS_ASSERT(vms_.count(id) > 0,\n\/\/\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\/\/\t\t\t\t\t\t\t\t\t \"Invalid VM identifier\"));\n\/\/\n\/\/\t\treturn vms_.at(id);\n\/\/\t}\n\n\tprivate: void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens)\n\t{\n\t\tDCS_ASSERT(p_sens,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid sensor\"));\n\n\t\tsensors_[cat] = p_sens;\n\t}\n\n\tprivate: void do_deregister_sensor(application_performance_category cat)\n\t{\n\t\tDCS_ASSERT(sensors_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: sensor not found\"));\n\n\t\tsensors_.erase(cat);\n\t}\n\n\tprivate: sensor_pointer do_sensor(application_performance_category cat)\n\t{\n\t\tDCS_ASSERT(sensors_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: sensor not found\"));\n\n\t\treturn sensors_.at(cat);\n\t}\n\n\tprivate: sensor_pointer do_sensor(application_performance_category cat) const\n\t{\n\t\tDCS_ASSERT(sensors_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: sensor not found\"));\n\n\t\treturn sensors_.at(cat);\n\t}\n\n\tprivate: void do_slo(application_performance_category cat, slo_checker_type const& checker)\n\t{\n\t\tslo_map_[cat] = checker;\n\t}\n\n\tprivate: bool do_slo(application_performance_category cat, real_type val) const\n\t{\n\t\tDCS_ASSERT(slo_map_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: SLO checker not found\"));\n\n\t\treturn slo_map_.at(cat)(val);\n\t}\n\n\n\tprivate: vm_container vms_;\n\tprivate: sensor_map sensors_;\n\tprivate: slo_checker_map slo_map_;\n}; \/\/ application\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_APPLICATION_HPP\nImproved inline doc\/**\n * \\file dcs\/testbed\/application.hpp\n *\n * \\brief Generic application.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\n * \n *\n * Copyright 2012 Marco Guazzone (marco.guazzone@gmail.com)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http:\/\/www.apache.org\/licenses\/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\/\n\n#ifndef DCS_TESTBED_APPLICATION_HPP\n#define DCS_TESTBED_APPLICATION_HPP\n\n\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\n\nnamespace dcs { namespace testbed {\n\n\/**\n * \\brief Generic application.\n *\n * \\tparam TraitsT Traits type.\n *\n * \\author Marco Guazzone (marco.guazzone@gmail.com)\n *\/\ntemplate \nclass application: public base_application\n{\n\tprivate: typedef base_application base_type;\n\tpublic: typedef typename base_type::traits_type traits_type;\n\tpublic: typedef typename base_type::vm_pointer vm_pointer;\n\tpublic: typedef typename base_type::sensor_pointer sensor_pointer;\n\tpublic: typedef typename base_type::slo_checker_type slo_checker_type;\n\tpublic: typedef typename base_type::real_type real_type;\n\/\/\tprivate: typedef typename base_type::vm_type::identifier_type vm _identifier_type;\n\/\/\tprivate: typedef ::std::map vm_container;\n\tprivate: typedef ::std::vector vm_container;\n\tprivate: typedef ::std::map sensor_map;\n\tprivate: typedef ::std::map slo_checker_map;\n\n\n\tpublic: application()\n\t{\n\t\t\/\/ Empty\n\t}\n\n\tpublic: template \n\t\t\tapplication(IterT vm_first, IterT vm_last)\n\t: vms_(vm_first,vm_last)\n\t{\n\/\/\t\twhile (vm_first != vm_last)\n\/\/\t\t{\n\/\/\t\t\tvms_[*(vm_first)->id()] = *vm_first;\n\/\/\t\t\t++vm_first;\n\/\/\t\t}\n\t}\n\n\tprivate: ::std::size_t do_num_vms() const\n\t{\n\t\treturn vms_.size();\n\t}\n\n\tprivate: ::std::vector do_vms() const\n\t{\n\/\/\t\t::std::vector vms(vms_.size());\n\/\/\n\/\/\t\t::std::size_t i(0);\n\/\/\t\ttypename vm_container::const_iterator end_it(vms_.end());\n\/\/\t\tfor (typename vm_container::const_iterator it = vms_.begin();\n\/\/\t\t\t it != end_it;\n\/\/\t\t\t ++it)\n\/\/\t\t{\n\/\/\t\t\tvms[i] = *it;\n\/\/\t\t\t++i;\n\/\/\t\t}\n\/\/\n\/\/\t\treturn vms;\n\t\treturn vms_;\n\t}\n\n\/\/\tprivate: vm_pointer do_vm(vm_identifier_type id) const\n\/\/\t{\n\/\/\t\tDCS_ASSERT(vms_.count(id) > 0,\n\/\/\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\/\/\t\t\t\t\t\t\t\t\t \"Invalid VM identifier\"));\n\/\/\n\/\/\t\treturn vms_.at(id);\n\/\/\t}\n\n\tprivate: void do_register_sensor(application_performance_category cat, sensor_pointer const& p_sens)\n\t{\n\t\tDCS_ASSERT(p_sens,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid sensor\"));\n\n\t\tsensors_[cat] = p_sens;\n\t}\n\n\tprivate: void do_deregister_sensor(application_performance_category cat)\n\t{\n\t\tDCS_ASSERT(sensors_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: sensor not found\"));\n\n\t\tsensors_.erase(cat);\n\t}\n\n\tprivate: sensor_pointer do_sensor(application_performance_category cat)\n\t{\n\t\tDCS_ASSERT(sensors_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: sensor not found\"));\n\n\t\treturn sensors_.at(cat);\n\t}\n\n\tprivate: sensor_pointer do_sensor(application_performance_category cat) const\n\t{\n\t\tDCS_ASSERT(sensors_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: sensor not found\"));\n\n\t\treturn sensors_.at(cat);\n\t}\n\n\tprivate: void do_slo(application_performance_category cat, slo_checker_type const& checker)\n\t{\n\t\tslo_map_[cat] = checker;\n\t}\n\n\tprivate: bool do_slo(application_performance_category cat, real_type val) const\n\t{\n\t\tDCS_ASSERT(slo_map_.count(cat) > 0,\n\t\t\t\t DCS_EXCEPTION_THROW(::std::invalid_argument,\n\t\t\t\t\t\t\t\t\t \"Invalid category: SLO checker not found\"));\n\n\t\treturn slo_map_.at(cat)(val);\n\t}\n\n\n\tprivate: vm_container vms_;\n\tprivate: sensor_map sensors_;\n\tprivate: slo_checker_map slo_map_;\n}; \/\/ application\n\n}} \/\/ Namespace dcs::testbed\n\n#endif \/\/ DCS_TESTBED_APPLICATION_HPP\n<|endoftext|>"} {"text":"#include \"stdafx.h\"\n#include \n\ntypedef LONG KPRIORITY;\ntypedef struct _CLIENT_ID {\n\tDWORD UniqueProcess;\n\tDWORD UniqueThread;\n} CLIENT_ID;\n\ntypedef struct _UNICODE_STRING {\n\tUSHORT Length;\n\tUSHORT MaximumLength;\n\tPWSTR Buffer;\n} UNICODE_STRING;\n\n\n\/\/from http:\/\/boinc.berkeley.edu\/android-boinc\/boinc\/lib\/diagnostics_win.h\ntypedef struct _VM_COUNTERS {\n#ifdef _WIN64\n\t\/\/ the following was inferred by painful reverse engineering\n\tSIZE_T\t\t PeakVirtualSize;\t\/\/ not actually\n\tSIZE_T PageFaultCount;\n\tSIZE_T PeakWorkingSetSize;\n\tSIZE_T WorkingSetSize;\n\tSIZE_T QuotaPeakPagedPoolUsage;\n\tSIZE_T QuotaPagedPoolUsage;\n\tSIZE_T QuotaPeakNonPagedPoolUsage;\n\tSIZE_T QuotaNonPagedPoolUsage;\n\tSIZE_T PagefileUsage;\n\tSIZE_T PeakPagefileUsage;\n\tSIZE_T VirtualSize;\t\t\/\/ not actually\n#else\n\tSIZE_T PeakVirtualSize;\n\tSIZE_T VirtualSize;\n\tULONG PageFaultCount;\n\tSIZE_T PeakWorkingSetSize;\n\tSIZE_T WorkingSetSize;\n\tSIZE_T QuotaPeakPagedPoolUsage;\n\tSIZE_T QuotaPagedPoolUsage;\n\tSIZE_T QuotaPeakNonPagedPoolUsage;\n\tSIZE_T QuotaNonPagedPoolUsage;\n\tSIZE_T PagefileUsage;\n\tSIZE_T PeakPagefileUsage;\n#endif\n} VM_COUNTERS;\n\ntypedef enum _KWAIT_REASON\n{\n\tExecutive = 0,\n\tFreePage = 1,\n\tPageIn = 2,\n\tPoolAllocation = 3,\n\tDelayExecution = 4,\n\tSuspended = 5,\n\tUserRequest = 6,\n\tWrExecutive = 7,\n\tWrFreePage = 8,\n\tWrPageIn = 9,\n\tWrPoolAllocation = 10,\n\tWrDelayExecution = 11,\n\tWrSuspended = 12,\n\tWrUserRequest = 13,\n\tWrEventPair = 14,\n\tWrQueue = 15,\n\tWrLpcReceive = 16,\n\tWrLpcReply = 17,\n\tWrVirtualMemory = 18,\n\tWrPageOut = 19,\n\tWrRendezvous = 20,\n\tSpare2 = 21,\n\tSpare3 = 22,\n\tSpare4 = 23,\n\tSpare5 = 24,\n\tWrCalloutStack = 25,\n\tWrKernel = 26,\n\tWrResource = 27,\n\tWrPushLock = 28,\n\tWrMutex = 29,\n\tWrQuantumEnd = 30,\n\tWrDispatchInt = 31,\n\tWrPreempted = 32,\n\tWrYieldExecution = 33,\n\tWrFastMutex = 34,\n\tWrGuardedMutex = 35,\n\tWrRundown = 36,\n\tMaximumWaitReason = 37\n} KWAIT_REASON;\n\ntypedef struct _SYSTEM_THREAD_INFORMATION {\n\tLARGE_INTEGER KernelTime;\n\tLARGE_INTEGER UserTime;\n\tLARGE_INTEGER CreateTime;\n\tULONG WaitTime;\n\tPVOID StartAddress;\n\tCLIENT_ID ClientId;\n\tKPRIORITY Priority;\n\tLONG BasePriority;\n\tULONG ContextSwitchCount;\n\tULONG ThreadState;\n\tKWAIT_REASON WaitReason;\n#ifdef _WIN64\n\tULONG Reserved[4];\n#endif\n}SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;\n\ntypedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION\n{\n\tSYSTEM_THREAD_INFORMATION ThreadInfo;\n\tPVOID StackBase;\n\tPVOID StackLimit;\n\tPVOID Win32StartAddress;\n\tPVOID TebAddress; \/* This is only filled in on Vista and above *\/\n\tULONG Reserved1;\n\tULONG Reserved2;\n\tULONG Reserved3;\n} SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION;\ntypedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION\n{\n\tULONG NextEntryOffset;\n\tULONG NumberOfThreads;\n\tLARGE_INTEGER SpareLi1;\n\tLARGE_INTEGER SpareLi2;\n\tLARGE_INTEGER SpareLi3;\n\tLARGE_INTEGER CreateTime;\n\tLARGE_INTEGER UserTime;\n\tLARGE_INTEGER KernelTime;\n\tUNICODE_STRING ImageName;\n\tKPRIORITY BasePriority;\n\tULONG ProcessId;\n\tULONG InheritedFromUniqueProcessId;\n\tULONG HandleCount;\n\tULONG SessionId;\n\tPVOID PageDirectoryBase;\n\tVM_COUNTERS VirtualMemoryCounters;\n\tSIZE_T PrivatePageCount;\n\tIO_COUNTERS IoCounters;\n\tSYSTEM_EXTENDED_THREAD_INFORMATION Threads[1];\n} SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION;\n\ntypedef enum _SYSTEM_INFORMATION_CLASS {\n\tSystemExtendedProcessInformation = 57\n} SYSTEM_INFORMATION_CLASS;\n\ntypedef NTSTATUS(WINAPI *PNtQuerySystemInformation)(\n\t__in SYSTEM_INFORMATION_CLASS SystemInformationClass,\n\t__inout PVOID SystemInformation,\n\t__in ULONG SystemInformationLength,\n\t__out_opt PULONG ReturnLength\n\t);\n\nint main()\n{\n\tHMODULE ntdll = GetModuleHandle(TEXT(\"ntdll\"));\n\tPNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, \"NtQuerySystemInformation\");\n\tif (query == NULL) {\n\t\tprintf(\"GetProcAddress() failed.\\n\");\n\t\treturn 1;\n\t}\n\tULONG len = 2000;\n\tNTSTATUS status = NULL;\n\tPSYSTEM_EXTENDED_PROCESS_INFORMATION pProcessInfo = NULL;\n\tdo {\n\t\tlen *= 2;\n\t\tpProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len);\n\t\tstatus = query(SystemExtendedProcessInformation, pProcessInfo, len, &len);\n\t} while (status == (NTSTATUS)0xc0000004);\n\tif (status != (NTSTATUS)0x0) {\n\t\tprintf(\"NtQuerySystemInformation failed with error code 0x%X\\n\", status);\n\t\treturn 1;\n\t}\n\n\twhile (pProcessInfo->NextEntryOffset != NULL) {\n\t\tfor (unsigned int i = 0; i < pProcessInfo->NumberOfThreads; i++) {\n\t\t\tPVOID stackBase = pProcessInfo->Threads[i].StackBase;\n\t\t\tPVOID stackLimit = pProcessInfo->Threads[i].StackLimit;\n#ifdef _WIN64\n\t\t\tprintf(\"Stack base 0x%llx\\t\", stackBase);\n\t\t\tprintf(\"Stack limit 0x%llx\\r\\n\", stackLimit);\n#else\n\t\t\tprintf(\"Stack base 0x%X\\t\", stackBase);\n\t\t\tprintf(\"Stack limit 0x%X\\r\\n\", stackLimit);\n#endif\n\t\t}\n\t\tpProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)((ULONG_PTR)pProcessInfo + pProcessInfo->NextEntryOffset);\n\t}\n\treturn 0;\n}\n\n\nremove unneeded ifdef struct change#include \"stdafx.h\"\n#include \n\ntypedef LONG KPRIORITY;\ntypedef struct _CLIENT_ID {\n\tDWORD UniqueProcess;\n\tDWORD UniqueThread;\n} CLIENT_ID;\n\ntypedef struct _UNICODE_STRING {\n\tUSHORT Length;\n\tUSHORT MaximumLength;\n\tPWSTR Buffer;\n} UNICODE_STRING;\n\n\n\/\/from http:\/\/boinc.berkeley.edu\/android-boinc\/boinc\/lib\/diagnostics_win.h\ntypedef struct _VM_COUNTERS {\n\t\/\/ the following was inferred by painful reverse engineering\n\tSIZE_T\t\t PeakVirtualSize;\t\/\/ not actually\n\tSIZE_T PageFaultCount;\n\tSIZE_T PeakWorkingSetSize;\n\tSIZE_T WorkingSetSize;\n\tSIZE_T QuotaPeakPagedPoolUsage;\n\tSIZE_T QuotaPagedPoolUsage;\n\tSIZE_T QuotaPeakNonPagedPoolUsage;\n\tSIZE_T QuotaNonPagedPoolUsage;\n\tSIZE_T PagefileUsage;\n\tSIZE_T PeakPagefileUsage;\n\tSIZE_T VirtualSize;\t\t\/\/ not actually\n} VM_COUNTERS;\n\ntypedef enum _KWAIT_REASON\n{\n\tExecutive = 0,\n\tFreePage = 1,\n\tPageIn = 2,\n\tPoolAllocation = 3,\n\tDelayExecution = 4,\n\tSuspended = 5,\n\tUserRequest = 6,\n\tWrExecutive = 7,\n\tWrFreePage = 8,\n\tWrPageIn = 9,\n\tWrPoolAllocation = 10,\n\tWrDelayExecution = 11,\n\tWrSuspended = 12,\n\tWrUserRequest = 13,\n\tWrEventPair = 14,\n\tWrQueue = 15,\n\tWrLpcReceive = 16,\n\tWrLpcReply = 17,\n\tWrVirtualMemory = 18,\n\tWrPageOut = 19,\n\tWrRendezvous = 20,\n\tSpare2 = 21,\n\tSpare3 = 22,\n\tSpare4 = 23,\n\tSpare5 = 24,\n\tWrCalloutStack = 25,\n\tWrKernel = 26,\n\tWrResource = 27,\n\tWrPushLock = 28,\n\tWrMutex = 29,\n\tWrQuantumEnd = 30,\n\tWrDispatchInt = 31,\n\tWrPreempted = 32,\n\tWrYieldExecution = 33,\n\tWrFastMutex = 34,\n\tWrGuardedMutex = 35,\n\tWrRundown = 36,\n\tMaximumWaitReason = 37\n} KWAIT_REASON;\n\ntypedef struct _SYSTEM_THREAD_INFORMATION {\n\tLARGE_INTEGER KernelTime;\n\tLARGE_INTEGER UserTime;\n\tLARGE_INTEGER CreateTime;\n\tULONG WaitTime;\n\tPVOID StartAddress;\n\tCLIENT_ID ClientId;\n\tKPRIORITY Priority;\n\tLONG BasePriority;\n\tULONG ContextSwitchCount;\n\tULONG ThreadState;\n\tKWAIT_REASON WaitReason;\n#ifdef _WIN64\n\tULONG Reserved[4];\n#endif\n}SYSTEM_THREAD_INFORMATION, *PSYSTEM_THREAD_INFORMATION;\n\ntypedef struct _SYSTEM_EXTENDED_THREAD_INFORMATION\n{\n\tSYSTEM_THREAD_INFORMATION ThreadInfo;\n\tPVOID StackBase;\n\tPVOID StackLimit;\n\tPVOID Win32StartAddress;\n\tPVOID TebAddress; \/* This is only filled in on Vista and above *\/\n\tULONG Reserved1;\n\tULONG Reserved2;\n\tULONG Reserved3;\n} SYSTEM_EXTENDED_THREAD_INFORMATION, *PSYSTEM_EXTENDED_THREAD_INFORMATION;\ntypedef struct _SYSTEM_EXTENDED_PROCESS_INFORMATION\n{\n\tULONG NextEntryOffset;\n\tULONG NumberOfThreads;\n\tLARGE_INTEGER SpareLi1;\n\tLARGE_INTEGER SpareLi2;\n\tLARGE_INTEGER SpareLi3;\n\tLARGE_INTEGER CreateTime;\n\tLARGE_INTEGER UserTime;\n\tLARGE_INTEGER KernelTime;\n\tUNICODE_STRING ImageName;\n\tKPRIORITY BasePriority;\n\tULONG ProcessId;\n\tULONG InheritedFromUniqueProcessId;\n\tULONG HandleCount;\n\tULONG SessionId;\n\tPVOID PageDirectoryBase;\n\tVM_COUNTERS VirtualMemoryCounters;\n\tSIZE_T PrivatePageCount;\n\tIO_COUNTERS IoCounters;\n\tSYSTEM_EXTENDED_THREAD_INFORMATION Threads[1];\n} SYSTEM_EXTENDED_PROCESS_INFORMATION, *PSYSTEM_EXTENDED_PROCESS_INFORMATION;\n\ntypedef enum _SYSTEM_INFORMATION_CLASS {\n\tSystemExtendedProcessInformation = 57\n} SYSTEM_INFORMATION_CLASS;\n\ntypedef NTSTATUS(WINAPI *PNtQuerySystemInformation)(\n\t__in SYSTEM_INFORMATION_CLASS SystemInformationClass,\n\t__inout PVOID SystemInformation,\n\t__in ULONG SystemInformationLength,\n\t__out_opt PULONG ReturnLength\n\t);\n\nint main()\n{\n\tHMODULE ntdll = GetModuleHandle(TEXT(\"ntdll\"));\n\tPNtQuerySystemInformation query = (PNtQuerySystemInformation)GetProcAddress(ntdll, \"NtQuerySystemInformation\");\n\tif (query == NULL) {\n\t\tprintf(\"GetProcAddress() failed.\\n\");\n\t\treturn 1;\n\t}\n\tULONG len = 2000;\n\tNTSTATUS status = NULL;\n\tPSYSTEM_EXTENDED_PROCESS_INFORMATION pProcessInfo = NULL;\n\tdo {\n\t\tlen *= 2;\n\t\tpProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len);\n\t\tstatus = query(SystemExtendedProcessInformation, pProcessInfo, len, &len);\n\t} while (status == (NTSTATUS)0xc0000004);\n\tif (status != (NTSTATUS)0x0) {\n\t\tprintf(\"NtQuerySystemInformation failed with error code 0x%X\\n\", status);\n\t\treturn 1;\n\t}\n\n\twhile (pProcessInfo->NextEntryOffset != NULL) {\n\t\tfor (unsigned int i = 0; i < pProcessInfo->NumberOfThreads; i++) {\n\t\t\tPVOID stackBase = pProcessInfo->Threads[i].StackBase;\n\t\t\tPVOID stackLimit = pProcessInfo->Threads[i].StackLimit;\n#ifdef _WIN64\n\t\t\tprintf(\"Stack base 0x%llx\\t\", stackBase);\n\t\t\tprintf(\"Stack limit 0x%llx\\r\\n\", stackLimit);\n#else\n\t\t\tprintf(\"Stack base 0x%X\\t\", stackBase);\n\t\t\tprintf(\"Stack limit 0x%X\\r\\n\", stackLimit);\n#endif\n\t\t}\n\t\tpProcessInfo = (PSYSTEM_EXTENDED_PROCESS_INFORMATION)((ULONG_PTR)pProcessInfo + pProcessInfo->NextEntryOffset);\n\t}\n\treturn 0;\n}\n\n\n<|endoftext|>"} {"text":"\/**************************************************************************\r\n** This file is part of LiteIDE\r\n**\r\n** Copyright (c) 2011-2017 LiteIDE Team. All rights reserved.\r\n**\r\n** This library is free software; you can redistribute it and\/or\r\n** modify it under the terms of the GNU Lesser General Public\r\n** License as published by the Free Software Foundation; either\r\n** version 2.1 of the License, or (at your option) any later version.\r\n**\r\n** This library is distributed in the hope that it will be useful,\r\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n** Lesser General Public License for more details.\r\n**\r\n** In addition, as a special exception, that plugins developed for LiteIDE,\r\n** are allowed to remain closed sourced and can be distributed under any license .\r\n** These rights are included in the file LGPL_EXCEPTION.txt in this package.\r\n**\r\n**************************************************************************\/\r\n\/\/ Module: goremovetagsdialog.cpp\r\n\/\/ Creator: visualfc \r\n\r\n#include \"goremovetagsdialog.h\"\r\n#include \"ui_goremovetagsdialog.h\"\r\n\/\/lite_memory_check_begin\r\n#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)\r\n #define _CRTDBG_MAP_ALLOC\r\n #include \r\n #include \r\n #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )\r\n #define new DEBUG_NEW\r\n#endif\r\n\/\/lite_memory_check_end\r\n\r\nGoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) :\r\n QDialog(parent),\r\n ui(new Ui::GoRemoveTagsDialog)\r\n{\r\n ui->setupUi(this);\r\n connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n\r\n connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n\r\n connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n\r\n connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n}\r\n\r\nGoRemoveTagsDialog::~GoRemoveTagsDialog()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid GoRemoveTagsDialog::setInfo(const QString &info)\r\n{\r\n ui->infoLabel->setText(info);\r\n}\r\n\r\nQString GoRemoveTagsDialog::arguments() const\r\n{\r\n return ui->argumentsEdit->toPlainText().trimmed();\r\n}\r\n\r\nstatic QString removeHead(const QString &text, const QString &head)\r\n{\r\n if (text.startsWith(head)) {\r\n return text.mid(head.length());\r\n }\r\n return text;\r\n}\r\n\r\nvoid GoRemoveTagsDialog::updateArguments()\r\n{\r\n QString args;\r\n if (ui->clearAllTagsRadioButton->isChecked()) {\r\n args = \"-clear-tags\";\r\n } else if (ui->clearAllOptionsRadioButton->isChecked()) {\r\n args = \"-clear-options\";\r\n } else if (ui->removeJsonTagRadioButton->isChecked()) {\r\n args = \"-remove-tags json\";\r\n } else if (ui->removeXmlTagRadioButton->isChecked()) {\r\n args = \"-remove-tags xml\";\r\n } else if (ui->removeCustomTagRadioButton->isChecked()) {\r\n QString tag = ui->customTaglineEdit->text().trimmed();\r\n if (!tag.isEmpty()) {\r\n args = \"-remove-tags \"+tag;\r\n }\r\n } else if (ui->removeJsonOptionRadioButton->isChecked()) {\r\n QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(\",\",QString::SkipEmptyParts);\r\n QStringList options;\r\n foreach (QString opt, optList) {\r\n options << \"json=\"+opt;\r\n }\r\n if (!options.isEmpty()) {\r\n args = \"-remove-options \"+options.join(\",\");\r\n }\r\n } else if (ui->removeXmlOptionRadioButton->isChecked()) {\r\n QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(\",\",QString::SkipEmptyParts);\r\n QStringList options;\r\n foreach (QString opt, optList) {\r\n options << \"json=\"+opt;\r\n }\r\n if (!options.isEmpty()) {\r\n args = \"-remove-options \"+options.join(\",\");\r\n }\r\n } else if(ui->removeCustomOptionRadioButton->isChecked()) {\r\n QString opt = ui->customOptionLineEdit->text().trimmed();\r\n if (opt == ui->customOptionLineEdit->placeholderText()) {\r\n if (ui->customOptionLineEdit->cursorPosition() == 0) {\r\n opt.clear();\r\n }\r\n }\r\n if (opt.contains(\"=\")) {\r\n args = \"-remove-options \"+opt;\r\n }\r\n }\r\n\r\n ui->argumentsEdit->setPlainText(args);\r\n}\r\ngolangedit: fix removetags xml option\/**************************************************************************\r\n** This file is part of LiteIDE\r\n**\r\n** Copyright (c) 2011-2017 LiteIDE Team. All rights reserved.\r\n**\r\n** This library is free software; you can redistribute it and\/or\r\n** modify it under the terms of the GNU Lesser General Public\r\n** License as published by the Free Software Foundation; either\r\n** version 2.1 of the License, or (at your option) any later version.\r\n**\r\n** This library is distributed in the hope that it will be useful,\r\n** but WITHOUT ANY WARRANTY; without even the implied warranty of\r\n** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\r\n** Lesser General Public License for more details.\r\n**\r\n** In addition, as a special exception, that plugins developed for LiteIDE,\r\n** are allowed to remain closed sourced and can be distributed under any license .\r\n** These rights are included in the file LGPL_EXCEPTION.txt in this package.\r\n**\r\n**************************************************************************\/\r\n\/\/ Module: goremovetagsdialog.cpp\r\n\/\/ Creator: visualfc \r\n\r\n#include \"goremovetagsdialog.h\"\r\n#include \"ui_goremovetagsdialog.h\"\r\n\/\/lite_memory_check_begin\r\n#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)\r\n #define _CRTDBG_MAP_ALLOC\r\n #include \r\n #include \r\n #define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )\r\n #define new DEBUG_NEW\r\n#endif\r\n\/\/lite_memory_check_end\r\n\r\nGoRemoveTagsDialog::GoRemoveTagsDialog(QWidget *parent) :\r\n QDialog(parent),\r\n ui(new Ui::GoRemoveTagsDialog)\r\n{\r\n ui->setupUi(this);\r\n connect(ui->clearAllTagsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->clearAllOptionsRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n\r\n connect(ui->removeJsonTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeCustomTagRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n\r\n connect(ui->removeJsonOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeXmlOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n connect(ui->removeCustomOptionRadioButton,SIGNAL(toggled(bool)),this,SLOT(updateArguments()));\r\n\r\n connect(ui->customTaglineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n connect(ui->jsonOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n connect(ui->xmlOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n connect(ui->customOptionLineEdit,SIGNAL(textChanged(QString)),this,SLOT(updateArguments()));\r\n}\r\n\r\nGoRemoveTagsDialog::~GoRemoveTagsDialog()\r\n{\r\n delete ui;\r\n}\r\n\r\nvoid GoRemoveTagsDialog::setInfo(const QString &info)\r\n{\r\n ui->infoLabel->setText(info);\r\n}\r\n\r\nQString GoRemoveTagsDialog::arguments() const\r\n{\r\n return ui->argumentsEdit->toPlainText().trimmed();\r\n}\r\n\r\nstatic QString removeHead(const QString &text, const QString &head)\r\n{\r\n if (text.startsWith(head)) {\r\n return text.mid(head.length());\r\n }\r\n return text;\r\n}\r\n\r\nvoid GoRemoveTagsDialog::updateArguments()\r\n{\r\n QString args;\r\n if (ui->clearAllTagsRadioButton->isChecked()) {\r\n args = \"-clear-tags\";\r\n } else if (ui->clearAllOptionsRadioButton->isChecked()) {\r\n args = \"-clear-options\";\r\n } else if (ui->removeJsonTagRadioButton->isChecked()) {\r\n args = \"-remove-tags json\";\r\n } else if (ui->removeXmlTagRadioButton->isChecked()) {\r\n args = \"-remove-tags xml\";\r\n } else if (ui->removeCustomTagRadioButton->isChecked()) {\r\n QString tag = ui->customTaglineEdit->text().trimmed();\r\n if (!tag.isEmpty()) {\r\n args = \"-remove-tags \"+tag;\r\n }\r\n } else if (ui->removeJsonOptionRadioButton->isChecked()) {\r\n QStringList optList = ui->jsonOptionLineEdit->text().trimmed().split(\",\",QString::SkipEmptyParts);\r\n QStringList options;\r\n foreach (QString opt, optList) {\r\n options << \"json=\"+opt;\r\n }\r\n if (!options.isEmpty()) {\r\n args = \"-remove-options \"+options.join(\",\");\r\n }\r\n } else if (ui->removeXmlOptionRadioButton->isChecked()) {\r\n QStringList optList = ui->xmlOptionLineEdit->text().trimmed().split(\",\",QString::SkipEmptyParts);\r\n QStringList options;\r\n foreach (QString opt, optList) {\r\n options << \"xml=\"+opt;\r\n }\r\n if (!options.isEmpty()) {\r\n args = \"-remove-options \"+options.join(\",\");\r\n }\r\n } else if(ui->removeCustomOptionRadioButton->isChecked()) {\r\n QString opt = ui->customOptionLineEdit->text().trimmed();\r\n if (opt == ui->customOptionLineEdit->placeholderText()) {\r\n if (ui->customOptionLineEdit->cursorPosition() == 0) {\r\n opt.clear();\r\n }\r\n }\r\n if (opt.contains(\"=\")) {\r\n args = \"-remove-options \"+opt;\r\n }\r\n }\r\n\r\n ui->argumentsEdit->setPlainText(args);\r\n}\r\n<|endoftext|>"} {"text":"\/*\n * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#include \n#include \n#include \n#include \n\n#include \n\n#ifndef ATOM_PRINT_FUNCTIONS_HPP\n#define ATOM_PRINT_FUNCTIONS_HPP\n\nnamespace atom\n{\n\n\/\/! Print Cartesian-state-to-TLE converter solver summary table header.\n\/*!\n * Prints header to string for table containing summary of status of non-linear solver used to\n * convert a Cartesian state to a TLE.\n *\n * @sa convertCartesianStateToTwoLineElements\n * @return String containing table header for non-linear solver status.\n *\/\ninline std::string printCartesianToTleSolverStateTableHeader( );\n\n\/\/! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.\n\/*!\n * Prints current state of non-linear solver used to convert a Cartesian state to a TLE, as row\n * for a summary table.\n *\n * @sa convertCartesianStateToTwoLineElements\n * @param iteration Current iteration of solver\n * @param solver Pointer to GSL solver\n * @return String containing row-data for non-linear solver status summary table\n *\/\ninline std::string printCartesianToTleSolverState(\n const int iteration, gsl_multiroot_fsolver* solver );\n\n\/\/! Print Atom solver summary table header.\n\/*!\n * Prints header to string for table containing summary of status of non-linear solver used to\n * execute Atom solver.\n *\n * @sa executeAtomSolver\n * @return String containing table header for non-linear solver status.\n *\/\ninline std::string printAtomSolverStateTableHeader( );\n\n\/\/! Print summary of current state of non-linear solver for Atom solver.\n\/*!\n * Prints current state of non-linear solver used to execute Atom solver, as row for a summary\n * table.\n *\n * @sa executeAtomSolver\n * @param iteration Current iteration of solver\n * @param solver Pointer to GSL solver\n * @return String containing row-data for non-linear solver status summary table\n *\/\ninline std::string printAtomSolverState(\n const int iteration, gsl_multiroot_fsolver* solver );\n\n\/\/! Print data element to console.\n\/*!\n * Prints a specified data element to string, given a specified width and a filler character.\n * This function is auxilliary to the print-functions used to the print the state of the non-linear\n * solver.\n *\n * @sa printSolverStateTableHeader, printSolverState\n * @tparam DataType Type for specified data element\n * @param datum Specified data element to print\n * @param width Width of datum printed to console, in terms of number of characters\n * @param filler Character used to fill fixed-width, [default: ' ']\n * @return String containing printed data element\n *\/\ntemplate< typename DataType >\ninline std::string printElement( const DataType datum, const int width, const char filler = ' ' );\n\n\/\/! Print Cartesian-state-to-TLE converter solver summary table header.\ninline std::string printCartesianToTleSolverStateTableHeader( )\n{\n std::ostringstream headerBuffer;\n headerBuffer << printElement( \"#\", 3, ' ' )\n << printElement( \"a\", 15, ' ' )\n << printElement( \"e\", 15, ' ' )\n << printElement( \"i\", 15, ' ' )\n << printElement( \"AoP\", 15, ' ' )\n << printElement( \"RAAN\", 15, ' ' )\n << printElement( \"TA\", 15, ' ' )\n << printElement( \"f1\", 15, ' ' )\n << printElement( \"f2\", 15, ' ' )\n << printElement( \"f3\", 15, ' ' )\n << printElement( \"f4\", 15, ' ' )\n << printElement( \"f5\", 15, ' ' )\n << printElement( \"f6\", 15, ' ' )\n << std::endl;\n return headerBuffer.str( );\n}\n\n\/\/! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.\ninline std::string printCartesianToTleSolverState(\n const int iteration, gsl_multiroot_fsolver* solver )\n{\n std::ostringstream buffer;\n buffer << printElement( iteration, 3, ' ' )\n << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 3 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 4 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 5 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 3 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 4 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 5 ), 15, ' ' )\n << std::endl;\n return buffer.str( );\n}\n\n\/\/! Print Atom solver summary table header.\ninline std::string printAtomSolverStateTableHeader( )\n{\n std::ostringstream headerBuffer;\n headerBuffer << printElement( \"#\", 3, ' ' )\n << printElement( \"v1_x\", 15, ' ' )\n << printElement( \"v1_y\", 15, ' ' )\n << printElement( \"v1_z\", 15, ' ' )\n << printElement( \"f1\", 15, ' ' )\n << printElement( \"f2\", 15, ' ' )\n << printElement( \"f3\", 15, ' ' )\n << std::endl;\n return headerBuffer.str( );\n}\n\n\/\/! Print summary of current state of non-linear solver for Atom solver.\ninline std::string printAtomSolverState(\n const int iteration, gsl_multiroot_fsolver* solver )\n{\n std::ostringstream buffer;\n buffer << printElement( iteration, 3, ' ' )\n << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )\n << std::endl;\n return buffer.str( );\n}\n\n\/\/! Print data element to console.\ntemplate< typename DataType >\ninline std::string printElement( const DataType datum, const int width, const char filler )\n{\n std::ostringstream buffer;\n buffer << std::left << std::setw( width ) << std::setfill( filler ) << datum;\n return buffer.str( );\n}\n\n} \/\/ namespace atom\n\n#endif \/\/ ATOM_PRINT_FUNCTIONS_HPP\nMove header include guard above include statements in print functions header.\/*\n * Copyright (c) 2014-2016 Kartik Kumar, Dinamica Srl (me@kartikkumar.com)\n * Distributed under the MIT License.\n * See accompanying file LICENSE.md or copy at http:\/\/opensource.org\/licenses\/MIT\n *\/\n\n#ifndef ATOM_PRINT_FUNCTIONS_HPP\n#define ATOM_PRINT_FUNCTIONS_HPP\n\n#include \n#include \n#include \n#include \n\n#include \n\nnamespace atom\n{\n\n\/\/! Print Cartesian-state-to-TLE converter solver summary table header.\n\/*!\n * Prints header to string for table containing summary of status of non-linear solver used to\n * convert a Cartesian state to a TLE.\n *\n * @sa convertCartesianStateToTwoLineElements\n * @return String containing table header for non-linear solver status.\n *\/\ninline std::string printCartesianToTleSolverStateTableHeader( );\n\n\/\/! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.\n\/*!\n * Prints current state of non-linear solver used to convert a Cartesian state to a TLE, as row\n * for a summary table.\n *\n * @sa convertCartesianStateToTwoLineElements\n * @param iteration Current iteration of solver\n * @param solver Pointer to GSL solver\n * @return String containing row-data for non-linear solver status summary table\n *\/\ninline std::string printCartesianToTleSolverState(\n const int iteration, gsl_multiroot_fsolver* solver );\n\n\/\/! Print Atom solver summary table header.\n\/*!\n * Prints header to string for table containing summary of status of non-linear solver used to\n * execute Atom solver.\n *\n * @sa executeAtomSolver\n * @return String containing table header for non-linear solver status.\n *\/\ninline std::string printAtomSolverStateTableHeader( );\n\n\/\/! Print summary of current state of non-linear solver for Atom solver.\n\/*!\n * Prints current state of non-linear solver used to execute Atom solver, as row for a summary\n * table.\n *\n * @sa executeAtomSolver\n * @param iteration Current iteration of solver\n * @param solver Pointer to GSL solver\n * @return String containing row-data for non-linear solver status summary table\n *\/\ninline std::string printAtomSolverState(\n const int iteration, gsl_multiroot_fsolver* solver );\n\n\/\/! Print data element to console.\n\/*!\n * Prints a specified data element to string, given a specified width and a filler character.\n * This function is auxilliary to the print-functions used to the print the state of the non-linear\n * solver.\n *\n * @sa printSolverStateTableHeader, printSolverState\n * @tparam DataType Type for specified data element\n * @param datum Specified data element to print\n * @param width Width of datum printed to console, in terms of number of characters\n * @param filler Character used to fill fixed-width, [default: ' ']\n * @return String containing printed data element\n *\/\ntemplate< typename DataType >\ninline std::string printElement( const DataType datum, const int width, const char filler = ' ' );\n\n\/\/! Print Cartesian-state-to-TLE converter solver summary table header.\ninline std::string printCartesianToTleSolverStateTableHeader( )\n{\n std::ostringstream headerBuffer;\n headerBuffer << printElement( \"#\", 3, ' ' )\n << printElement( \"a\", 15, ' ' )\n << printElement( \"e\", 15, ' ' )\n << printElement( \"i\", 15, ' ' )\n << printElement( \"AoP\", 15, ' ' )\n << printElement( \"RAAN\", 15, ' ' )\n << printElement( \"TA\", 15, ' ' )\n << printElement( \"f1\", 15, ' ' )\n << printElement( \"f2\", 15, ' ' )\n << printElement( \"f3\", 15, ' ' )\n << printElement( \"f4\", 15, ' ' )\n << printElement( \"f5\", 15, ' ' )\n << printElement( \"f6\", 15, ' ' )\n << std::endl;\n return headerBuffer.str( );\n}\n\n\/\/! Print summary of current state of non-linear solver for Cartesian-state-to-TLE converter.\ninline std::string printCartesianToTleSolverState(\n const int iteration, gsl_multiroot_fsolver* solver )\n{\n std::ostringstream buffer;\n buffer << printElement( iteration, 3, ' ' )\n << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 3 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 4 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 5 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 3 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 4 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 5 ), 15, ' ' )\n << std::endl;\n return buffer.str( );\n}\n\n\/\/! Print Atom solver summary table header.\ninline std::string printAtomSolverStateTableHeader( )\n{\n std::ostringstream headerBuffer;\n headerBuffer << printElement( \"#\", 3, ' ' )\n << printElement( \"v1_x\", 15, ' ' )\n << printElement( \"v1_y\", 15, ' ' )\n << printElement( \"v1_z\", 15, ' ' )\n << printElement( \"f1\", 15, ' ' )\n << printElement( \"f2\", 15, ' ' )\n << printElement( \"f3\", 15, ' ' )\n << std::endl;\n return headerBuffer.str( );\n}\n\n\/\/! Print summary of current state of non-linear solver for Atom solver.\ninline std::string printAtomSolverState(\n const int iteration, gsl_multiroot_fsolver* solver )\n{\n std::ostringstream buffer;\n buffer << printElement( iteration, 3, ' ' )\n << printElement( gsl_vector_get( solver->x, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->x, 2 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 0 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 1 ), 15, ' ' )\n << printElement( gsl_vector_get( solver->f, 2 ), 15, ' ' )\n << std::endl;\n return buffer.str( );\n}\n\n\/\/! Print data element to console.\ntemplate< typename DataType >\ninline std::string printElement( const DataType datum, const int width, const char filler )\n{\n std::ostringstream buffer;\n buffer << std::left << std::setw( width ) << std::setfill( filler ) << datum;\n return buffer.str( );\n}\n\n} \/\/ namespace atom\n\n#endif \/\/ ATOM_PRINT_FUNCTIONS_HPP\n<|endoftext|>"} {"text":"#pragma once\n\n#ifndef RAZ_MATERIAL_HPP\n#define RAZ_MATERIAL_HPP\n\n#include \n\n#include \"RaZ\/Math\/Vector.hpp\"\n#include \"RaZ\/Render\/Shader.hpp\"\n#include \"RaZ\/Render\/ShaderProgram.hpp\"\n#include \"RaZ\/Render\/Texture.hpp\"\n\nnamespace Raz {\n\nenum class MaterialType {\n MATERIAL_TYPE_STANDARD = 0,\n MATERIAL_TYPE_COOK_TORRANCE\n};\n\nenum class MaterialPreset {\n CHARCOAL, GRASS, SAND, ICE, SNOW, \/\/ Dielectric presets\n IRON, SILVER, ALUMINIUM, GOLD, COPPER, CHROMIUM, NICKEL, TITANIUM, COBALT, PLATINUM \/\/ Metallic presets\n};\n\nclass MaterialCookTorrance;\n\nclass Material {\npublic:\n Material(const Material&) = default;\n\n virtual MaterialType getType() const = 0;\n\n static std::unique_ptr recoverMaterial(MaterialPreset preset, float roughnessFactor);\n virtual std::unique_ptr clone() const = 0;\n virtual void initTextures(const ShaderProgram& program) const = 0;\n virtual void bindAttributes(const ShaderProgram& program) const = 0;\n\n virtual ~Material() = default;\n\nprotected:\n Material() = default;\n};\n\nusing MaterialPtr = std::unique_ptr;\n\nclass MaterialStandard : public Material {\npublic:\n MaterialStandard() = default;\n explicit MaterialStandard(TexturePtr diffuseMap) : m_diffuseMap{ std::move(diffuseMap) } {}\n explicit MaterialStandard(const std::string& fileName) { m_diffuseMap = std::make_shared(fileName); }\n\n MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_STANDARD; }\n const Vec3f& getAmbient() const { return m_ambient; }\n const Vec3f& getDiffuse() const { return m_diffuse; }\n const Vec3f& getSpecular() const { return m_specular; }\n const Vec3f& getEmissive() const { return m_emissive; }\n float getTransparency() const { return m_transparency; }\n\n const TexturePtr& getAmbientMap() const { return m_ambientMap; }\n const TexturePtr& getDiffuseMap() const { return m_diffuseMap; }\n const TexturePtr& getSpecularMap() const { return m_specularMap; }\n const TexturePtr& getEmissiveMap() const { return m_emissiveMap; }\n const TexturePtr& getTransparencyMap() const { return m_transparencyMap; }\n const TexturePtr& getBumpMap() const { return m_bumpMap; }\n\n void setDiffuse(float red, float green, float blue) { setDiffuse(Vec3f({ red, green, blue })); }\n void setDiffuse(const Vec3f& val) { m_diffuse = val; }\n void setAmbient(float red, float green, float blue) { setAmbient(Vec3f({ red, green, blue })); }\n void setAmbient(const Vec3f& val) { m_ambient = val; }\n void setSpecular(float red, float green, float blue) { setSpecular(Vec3f({ red, green, blue })); }\n void setSpecular(const Vec3f& val) { m_specular = val; }\n void setEmissive(float red, float green, float blue) { setEmissive(Vec3f({ red, green, blue })); }\n void setEmissive(const Vec3f& val) { m_emissive = val; }\n void setTransparency(float transparency) { m_transparency = transparency; }\n\n void setAmbientMap(const TexturePtr& ambientMap) { m_ambientMap = ambientMap; }\n void setDiffuseMap(const TexturePtr& diffuseMap) { m_diffuseMap = diffuseMap; }\n void setSpecularMap(const TexturePtr& specularMap) { m_specularMap = specularMap; }\n void setEmissiveMap(const TexturePtr& emissiveMap) { m_emissiveMap = emissiveMap; }\n void setTransparencyMap(const TexturePtr& transparencyMap) { m_transparencyMap = transparencyMap; }\n void setBumpMap(const TexturePtr& bumpMap) { m_bumpMap = bumpMap; }\n\n void loadAmbientMap(const std::string& fileName) { m_ambientMap = std::make_shared(fileName); }\n void loadDiffuseMap(const std::string& fileName) { m_diffuseMap = std::make_shared(fileName); }\n void loadSpecularMap(const std::string& fileName) { m_specularMap = std::make_shared(fileName); }\n void loadEmissiveMap(const std::string& fileName) { m_emissiveMap = std::make_shared(fileName); }\n void loadTransparencyMap(const std::string& fileName) { m_transparencyMap = std::make_shared(fileName); }\n void loadBumpMap(const std::string& fileName) { m_bumpMap = std::make_shared(fileName); }\n\n std::unique_ptr clone() const override { return std::make_unique(*this); }\n void initTextures(const ShaderProgram& program) const override;\n void bindAttributes(const ShaderProgram& program) const override;\n\nprivate:\n Vec3f m_ambient = Vec3f(1.f);\n Vec3f m_diffuse = Vec3f(1.f);\n Vec3f m_specular = Vec3f(1.f);\n Vec3f m_emissive = Vec3f(1.f);\n float m_transparency = 1.f;\n\n TexturePtr m_ambientMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_diffuseMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_specularMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_emissiveMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_transparencyMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_bumpMap = Texture::recoverTexture(TexturePreset::WHITE);\n};\n\nclass MaterialCookTorrance : public Material {\npublic:\n MaterialCookTorrance() = default;\n explicit MaterialCookTorrance(TexturePtr albedoMap) : m_albedoMap{ std::move(albedoMap) } {}\n explicit MaterialCookTorrance(const std::string& fileName) { m_albedoMap = std::make_shared(fileName); }\n MaterialCookTorrance(const Vec3f& baseColor, float metallicFactor, float roughnessFactor)\n : m_baseColor{ baseColor }, m_metallicFactor{ metallicFactor }, m_roughnessFactor{ roughnessFactor } {}\n\n MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_COOK_TORRANCE; }\n const Vec3f& getBaseColor() const { return m_baseColor; }\n float getMetallicFactor() const { return m_metallicFactor; }\n float getRoughnessFactor() const { return m_roughnessFactor; }\n\n const TexturePtr& getAlbedoMap() const { return m_albedoMap; }\n const TexturePtr& getMetallicMap() const { return m_metallicMap; }\n const TexturePtr& getNormalMap() const { return m_normalMap; }\n const TexturePtr& getRoughnessMap() const { return m_roughnessMap; }\n const TexturePtr& getAmbientOcclusionMap() const { return m_ambientOcclusionMap; }\n\n void setBaseColor(float red, float green, float blue) { setBaseColor(Vec3f({ red, green, blue })); }\n void setBaseColor(const Vec3f& color) { m_baseColor = color; }\n void setMetallicFactor(float metallicFactor) { m_metallicFactor = metallicFactor; }\n void setRoughnessFactor(float roughnessFactor) { m_roughnessFactor = roughnessFactor; }\n\n void setAlbedoMap(const TexturePtr& albedoMap) { m_albedoMap = albedoMap; }\n void setNormalMap(const TexturePtr& normalMap) { m_normalMap = normalMap; }\n void setMetallicMap(const TexturePtr& metallicMap) { m_metallicMap = metallicMap; }\n void setRoughnessMap(const TexturePtr& roughnessMap) { m_roughnessMap = roughnessMap; }\n void setAmbientOcclusionMap(const TexturePtr& ambientOcclusionMap) { m_ambientOcclusionMap = ambientOcclusionMap; }\n\n void loadAlbedoMap(const std::string& fileName) { m_albedoMap = std::make_shared(fileName); }\n void loadNormalMap(const std::string& fileName) { m_normalMap = std::make_shared(fileName); }\n void loadMetallicMap(const std::string& fileName) { m_metallicMap = std::make_shared(fileName); }\n void loadRoughnessMap(const std::string& fileName) { m_roughnessMap = std::make_shared(fileName); }\n void loadAmbientOcclusionMap(const std::string& fileName) { m_ambientOcclusionMap = std::make_shared(fileName); }\n\n std::unique_ptr clone() const override { return std::make_unique(*this); }\n void initTextures(const ShaderProgram& program) const override;\n void bindAttributes(const ShaderProgram& program) const override;\n\nprivate:\n Vec3f m_baseColor = Vec3f(1.f);\n float m_metallicFactor = 1.f;\n float m_roughnessFactor = 1.f;\n\n TexturePtr m_albedoMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_normalMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_metallicMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_roughnessMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_ambientOcclusionMap = Texture::recoverTexture(TexturePreset::WHITE);\n};\n\n} \/\/ namespace Raz\n\n#endif \/\/ RAZ_MATERIAL_HPP\n[Update] Standard material's emissive factor is now defaulted to 0#pragma once\n\n#ifndef RAZ_MATERIAL_HPP\n#define RAZ_MATERIAL_HPP\n\n#include \n\n#include \"RaZ\/Math\/Vector.hpp\"\n#include \"RaZ\/Render\/Shader.hpp\"\n#include \"RaZ\/Render\/ShaderProgram.hpp\"\n#include \"RaZ\/Render\/Texture.hpp\"\n\nnamespace Raz {\n\nenum class MaterialType {\n MATERIAL_TYPE_STANDARD = 0,\n MATERIAL_TYPE_COOK_TORRANCE\n};\n\nenum class MaterialPreset {\n CHARCOAL, GRASS, SAND, ICE, SNOW, \/\/ Dielectric presets\n IRON, SILVER, ALUMINIUM, GOLD, COPPER, CHROMIUM, NICKEL, TITANIUM, COBALT, PLATINUM \/\/ Metallic presets\n};\n\nclass MaterialCookTorrance;\n\nclass Material {\npublic:\n Material(const Material&) = default;\n\n virtual MaterialType getType() const = 0;\n\n static std::unique_ptr recoverMaterial(MaterialPreset preset, float roughnessFactor);\n virtual std::unique_ptr clone() const = 0;\n virtual void initTextures(const ShaderProgram& program) const = 0;\n virtual void bindAttributes(const ShaderProgram& program) const = 0;\n\n virtual ~Material() = default;\n\nprotected:\n Material() = default;\n};\n\nusing MaterialPtr = std::unique_ptr;\n\nclass MaterialStandard : public Material {\npublic:\n MaterialStandard() = default;\n explicit MaterialStandard(TexturePtr diffuseMap) : m_diffuseMap{ std::move(diffuseMap) } {}\n explicit MaterialStandard(const std::string& fileName) { m_diffuseMap = std::make_shared(fileName); }\n\n MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_STANDARD; }\n const Vec3f& getAmbient() const { return m_ambient; }\n const Vec3f& getDiffuse() const { return m_diffuse; }\n const Vec3f& getSpecular() const { return m_specular; }\n const Vec3f& getEmissive() const { return m_emissive; }\n float getTransparency() const { return m_transparency; }\n\n const TexturePtr& getAmbientMap() const { return m_ambientMap; }\n const TexturePtr& getDiffuseMap() const { return m_diffuseMap; }\n const TexturePtr& getSpecularMap() const { return m_specularMap; }\n const TexturePtr& getEmissiveMap() const { return m_emissiveMap; }\n const TexturePtr& getTransparencyMap() const { return m_transparencyMap; }\n const TexturePtr& getBumpMap() const { return m_bumpMap; }\n\n void setDiffuse(float red, float green, float blue) { setDiffuse(Vec3f({ red, green, blue })); }\n void setDiffuse(const Vec3f& val) { m_diffuse = val; }\n void setAmbient(float red, float green, float blue) { setAmbient(Vec3f({ red, green, blue })); }\n void setAmbient(const Vec3f& val) { m_ambient = val; }\n void setSpecular(float red, float green, float blue) { setSpecular(Vec3f({ red, green, blue })); }\n void setSpecular(const Vec3f& val) { m_specular = val; }\n void setEmissive(float red, float green, float blue) { setEmissive(Vec3f({ red, green, blue })); }\n void setEmissive(const Vec3f& val) { m_emissive = val; }\n void setTransparency(float transparency) { m_transparency = transparency; }\n\n void setAmbientMap(const TexturePtr& ambientMap) { m_ambientMap = ambientMap; }\n void setDiffuseMap(const TexturePtr& diffuseMap) { m_diffuseMap = diffuseMap; }\n void setSpecularMap(const TexturePtr& specularMap) { m_specularMap = specularMap; }\n void setEmissiveMap(const TexturePtr& emissiveMap) { m_emissiveMap = emissiveMap; }\n void setTransparencyMap(const TexturePtr& transparencyMap) { m_transparencyMap = transparencyMap; }\n void setBumpMap(const TexturePtr& bumpMap) { m_bumpMap = bumpMap; }\n\n void loadAmbientMap(const std::string& fileName) { m_ambientMap = std::make_shared(fileName); }\n void loadDiffuseMap(const std::string& fileName) { m_diffuseMap = std::make_shared(fileName); }\n void loadSpecularMap(const std::string& fileName) { m_specularMap = std::make_shared(fileName); }\n void loadEmissiveMap(const std::string& fileName) { m_emissiveMap = std::make_shared(fileName); }\n void loadTransparencyMap(const std::string& fileName) { m_transparencyMap = std::make_shared(fileName); }\n void loadBumpMap(const std::string& fileName) { m_bumpMap = std::make_shared(fileName); }\n\n std::unique_ptr clone() const override { return std::make_unique(*this); }\n void initTextures(const ShaderProgram& program) const override;\n void bindAttributes(const ShaderProgram& program) const override;\n\nprivate:\n Vec3f m_ambient = Vec3f(1.f);\n Vec3f m_diffuse = Vec3f(1.f);\n Vec3f m_specular = Vec3f(1.f);\n Vec3f m_emissive = Vec3f(0.f);\n float m_transparency = 1.f;\n\n TexturePtr m_ambientMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_diffuseMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_specularMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_emissiveMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_transparencyMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_bumpMap = Texture::recoverTexture(TexturePreset::WHITE);\n};\n\nclass MaterialCookTorrance : public Material {\npublic:\n MaterialCookTorrance() = default;\n explicit MaterialCookTorrance(TexturePtr albedoMap) : m_albedoMap{ std::move(albedoMap) } {}\n explicit MaterialCookTorrance(const std::string& fileName) { m_albedoMap = std::make_shared(fileName); }\n MaterialCookTorrance(const Vec3f& baseColor, float metallicFactor, float roughnessFactor)\n : m_baseColor{ baseColor }, m_metallicFactor{ metallicFactor }, m_roughnessFactor{ roughnessFactor } {}\n\n MaterialType getType() const override { return MaterialType::MATERIAL_TYPE_COOK_TORRANCE; }\n const Vec3f& getBaseColor() const { return m_baseColor; }\n float getMetallicFactor() const { return m_metallicFactor; }\n float getRoughnessFactor() const { return m_roughnessFactor; }\n\n const TexturePtr& getAlbedoMap() const { return m_albedoMap; }\n const TexturePtr& getMetallicMap() const { return m_metallicMap; }\n const TexturePtr& getNormalMap() const { return m_normalMap; }\n const TexturePtr& getRoughnessMap() const { return m_roughnessMap; }\n const TexturePtr& getAmbientOcclusionMap() const { return m_ambientOcclusionMap; }\n\n void setBaseColor(float red, float green, float blue) { setBaseColor(Vec3f({ red, green, blue })); }\n void setBaseColor(const Vec3f& color) { m_baseColor = color; }\n void setMetallicFactor(float metallicFactor) { m_metallicFactor = metallicFactor; }\n void setRoughnessFactor(float roughnessFactor) { m_roughnessFactor = roughnessFactor; }\n\n void setAlbedoMap(const TexturePtr& albedoMap) { m_albedoMap = albedoMap; }\n void setNormalMap(const TexturePtr& normalMap) { m_normalMap = normalMap; }\n void setMetallicMap(const TexturePtr& metallicMap) { m_metallicMap = metallicMap; }\n void setRoughnessMap(const TexturePtr& roughnessMap) { m_roughnessMap = roughnessMap; }\n void setAmbientOcclusionMap(const TexturePtr& ambientOcclusionMap) { m_ambientOcclusionMap = ambientOcclusionMap; }\n\n void loadAlbedoMap(const std::string& fileName) { m_albedoMap = std::make_shared(fileName); }\n void loadNormalMap(const std::string& fileName) { m_normalMap = std::make_shared(fileName); }\n void loadMetallicMap(const std::string& fileName) { m_metallicMap = std::make_shared(fileName); }\n void loadRoughnessMap(const std::string& fileName) { m_roughnessMap = std::make_shared(fileName); }\n void loadAmbientOcclusionMap(const std::string& fileName) { m_ambientOcclusionMap = std::make_shared(fileName); }\n\n std::unique_ptr clone() const override { return std::make_unique(*this); }\n void initTextures(const ShaderProgram& program) const override;\n void bindAttributes(const ShaderProgram& program) const override;\n\nprivate:\n Vec3f m_baseColor = Vec3f(1.f);\n float m_metallicFactor = 1.f;\n float m_roughnessFactor = 1.f;\n\n TexturePtr m_albedoMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_normalMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_metallicMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_roughnessMap = Texture::recoverTexture(TexturePreset::WHITE);\n TexturePtr m_ambientOcclusionMap = Texture::recoverTexture(TexturePreset::WHITE);\n};\n\n} \/\/ namespace Raz\n\n#endif \/\/ RAZ_MATERIAL_HPP\n<|endoftext|>"} {"text":"\/\/\n\/\/ embed.hpp\n\/\/ *********\n\/\/\n\/\/ Copyright (c) 2018 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/\n\n#pragma once\n\n#include \"aegis\/config.hpp\"\n#include \"aegis\/snowflake.hpp\"\n#include \"field.hpp\"\n#include \"footer.hpp\"\n#include \"image.hpp\"\n#include \"thumbnail.hpp\"\n#include \"video.hpp\"\n#include \"provider.hpp\"\n#include \n#include \n#include \n\nnamespace aegis\n{\n\nnamespace gateway\n{\n\nnamespace objects\n{\n\n\/**\\todo Needs documentation\n *\/\nclass embed\n{\npublic:\n \/\/\/ Adds a new embed field\n \/**\n * @param name Name of the field\n * @param value Text to be shown within field\n * @param is_inline Sets whether the field is inline\n *\/\n void add_field(const std::string & name, const std::string & value, bool is_inline = false)\n {\n fields.emplace_back(name, value, is_inline);\n }\n \/\/\/ Sets the title of the embed\n \/**\n * @param str Title to set\n *\/\n void set_title(const std::string & str)\n {\n title = str;\n }\n \/\/\/ Sets the footer of the embed\n \/**\n * @param str Footer to set\n *\/\n void set_footer(const footer ftr)\n {\n footer_ = ftr;\n }\n \/\/\/ Sets the description of the embed\n \/**\n * @param str Description to set\n *\/\n void set_description(const std::string & str)\n {\n description = str;\n }\n \/\/\/ Sets the url of the embed\n \/**\n * @param str Url to set\n *\/\n void set_url(const std::string & str)\n {\n url = str;\n }\n \/\/\/ Sets the timestamp of the embed\n \/**\n * @param str Timestamp to set\n *\/\n void set_timestamp(const std::string & str)\n {\n timestamp = str;\n }\n \/\/\/ Sets the color of the embed\n \/**\n * @param clr Color to set\n *\/\n void set_color(const int32_t clr)\n {\n color = clr;\n }\n \/\/ Combined Limit: 6000\n std::string title; \/**<\\todo Needs documentation *\/ \/\/ Limit: 256\n std::string type; \/**<\\todo Needs documentation *\/\n std::string description; \/**<\\todo Needs documentation *\/ \/\/ Limit: 2048\n std::string url; \/**<\\todo Needs documentation *\/\n std::string timestamp; \/**<\\todo Needs documentation *\/\n int32_t color = 0; \/**<\\todo Needs documentation *\/\n footer footer_; \/**<\\todo Needs documentation *\/ \/\/ Limit: 2048\n image image_; \/**<\\todo Needs documentation *\/\n thumbnail thumbnail_; \/**<\\todo Needs documentation *\/\n video video_; \/**<\\todo Needs documentation *\/\n provider provider_; \/**<\\todo Needs documentation *\/\n std::vector fields; \/**<\\todo Needs documentation *\/ \/\/ Limit: 25 name:256 value:1024\n};\n\n\/\/\/ \\cond TEMPLATES\ninline void from_json(const nlohmann::json& j, embed& m)\n{\n if (j.count(\"title\") && !j[\"title\"].is_null())\n m.title = j[\"title\"];\n if (j.count(\"type\"))\n m.type = j[\"type\"];\n if (j.count(\"description\") && !j[\"description\"].is_null())\n m.description = j[\"description\"];\n if (j.count(\"url\") && !j[\"url\"].is_null())\n m.url = j[\"url\"];\n if (j.count(\"timestamp\") && !j[\"timestamp\"].is_null())\n m.timestamp = j[\"timestamp\"];\n if (j.count(\"color\") && !j[\"color\"].is_null())\n m.color = j[\"color\"];\n if (j.count(\"footer\") && !j[\"footer\"].is_null())\n m.footer_ = j[\"footer\"];\n if (j.count(\"image\") && !j[\"image\"].is_null())\n m.image_ = j[\"image\"];\n if (j.count(\"thumbnail\") && !j[\"thumbnail\"].is_null())\n m.thumbnail_ = j[\"thumbnail\"];\n if (j.count(\"video\") && !j[\"video\"].is_null())\n m.video_ = j[\"video\"];\n if (j.count(\"provider\") && !j[\"provider\"].is_null())\n m.provider_ = j[\"provider\"];\n if (j.count(\"fields\") && !j[\"fields\"].is_null())\n for (const auto & _field : j[\"fields\"])\n m.fields.push_back(_field);\n}\n\/\/\/ \\endcond\n\n\/\/\/ \\cond TEMPLATES\ninline void to_json(nlohmann::json& j, const embed& m)\n{\n j[\"title\"] = m.title;\n j[\"type\"] = m.type;\n j[\"description\"] = m.description;\n j[\"url\"] = m.url;\n j[\"timestamp\"] = m.timestamp;\n j[\"color\"] = m.color;\n j[\"footer\"] = m.footer_;\n j[\"image\"] = m.image_;\n j[\"thumbnail\"] = m.thumbnail_;\n j[\"video\"] = m.video_;\n j[\"provider\"] = m.provider_;\n for (const auto & _field : m.fields)\n j[\"fields\"].push_back(_field);\n}\n\/\/\/ \\endcond\n\n}\n\n}\n\n}\nChanged embed to fluent-style interface\/\/\n\/\/ embed.hpp\n\/\/ *********\n\/\/\n\/\/ Copyright (c) 2018 Sharon W (sharon at aegis dot gg)\n\/\/\n\/\/ Distributed under the MIT License. (See accompanying file LICENSE)\n\/\/\n\n#pragma once\n\n#include \"aegis\/config.hpp\"\n#include \"aegis\/snowflake.hpp\"\n#include \"field.hpp\"\n#include \"footer.hpp\"\n#include \"image.hpp\"\n#include \"thumbnail.hpp\"\n#include \"video.hpp\"\n#include \"provider.hpp\"\n#include \n#include \n#include \n\nnamespace aegis\n{\n\nnamespace gateway\n{\n\nnamespace objects\n{\n\n\/**\\todo Needs documentation\n *\/\nclass embed\n{\npublic:\n \/\/\/ Adds a new embed field\n \/**\n * @param name Name of the field\n * @param value Text to be shown within field\n * @param is_inline Sets whether the field is inline\n *\/\n embed & fields(std::vector flds)\n {\n _fields = flds;\n return *this;\n }\n \/\/\/ Sets the title of the embed\n \/**\n * @param str Title to set\n *\/\n embed & title(const std::string & str)\n {\n _title = str;\n return *this;\n }\n \/\/\/ Sets the footer of the embed\n \/**\n * @param str Footer to set\n *\/\n embed & footer(const footer ftr)\n {\n _footer = ftr;\n return *this;\n }\n \/\/\/ Sets the description of the embed\n \/**\n * @param str Description to set\n *\/\n embed & description(const std::string & str)\n {\n _description = str;\n return *this;\n }\n \/\/\/ Sets the url of the embed\n \/**\n * @param str Url to set\n *\/\n embed & url(std::string & str)\n {\n _url = str;\n return *this;\n }\n \/\/\/ Sets the timestamp of the embed\n \/**\n * @param str Timestamp to set\n *\/\n embed & timestamp(const std::string & str)\n {\n _timestamp = str;\n return *this;\n }\n \/\/\/ Sets the color of the embed\n \/**\n * @param clr Color to set\n *\/\n embed & color(const int32_t clr)\n {\n _color = clr;\n return *this;\n }\n \/\/ Combined Limit: 6000\n std::string _title; \/**<\\todo Needs documentation *\/ \/\/ Limit: 256\n std::string _type; \/**<\\todo Needs documentation *\/\n std::string _description; \/**<\\todo Needs documentation *\/ \/\/ Limit: 2048\n std::string _url; \/**<\\todo Needs documentation *\/\n std::string _timestamp; \/**<\\todo Needs documentation *\/\n int32_t _color = 0; \/**<\\todo Needs documentation *\/\n objects::footer _footer; \/**<\\todo Needs documentation *\/ \/\/ Limit: 2048\n objects::image _image; \/**<\\todo Needs documentation *\/\n objects::thumbnail _thumbnail; \/**<\\todo Needs documentation *\/\n objects::video _video; \/**<\\todo Needs documentation *\/\n objects::provider _provider; \/**<\\todo Needs documentation *\/\n std::vector _fields; \/**<\\todo Needs documentation *\/ \/\/ Limit: 25 name:256 value:1024\n friend void from_json(const nlohmann::json& j, embed& m);\n friend void to_json(nlohmann::json& j, const embed& m);\n};\n\n\/\/\/ \\cond TEMPLATES\ninline void from_json(const nlohmann::json& j, embed& m)\n{\n if (j.count(\"title\") && !j[\"title\"].is_null())\n m._title = j[\"title\"].get();\n if (j.count(\"type\"))\n m._type = j[\"type\"].get();\n if (j.count(\"description\") && !j[\"description\"].is_null())\n m._description = j[\"description\"].get();\n if (j.count(\"url\") && !j[\"url\"].is_null())\n m._url = j[\"url\"].get();\n if (j.count(\"timestamp\") && !j[\"timestamp\"].is_null())\n m._timestamp = j[\"timestamp\"].get();\n if (j.count(\"color\") && !j[\"color\"].is_null())\n m._color = j[\"color\"];\n if (j.count(\"footer\") && !j[\"footer\"].is_null())\n m._footer = j[\"footer\"];\n if (j.count(\"image\") && !j[\"image\"].is_null())\n m._image = j[\"image\"];\n if (j.count(\"thumbnail\") && !j[\"thumbnail\"].is_null())\n m._thumbnail = j[\"thumbnail\"];\n if (j.count(\"video\") && !j[\"video\"].is_null())\n m._video = j[\"video\"];\n if (j.count(\"provider\") && !j[\"provider\"].is_null())\n m._provider = j[\"provider\"];\n if (j.count(\"fields\") && !j[\"fields\"].is_null())\n for (const auto & _field : j[\"fields\"])\n m._fields.push_back(_field);\n}\n\/\/\/ \\endcond\n\n\/\/\/ \\cond TEMPLATES\ninline void to_json(nlohmann::json& j, const embed& m)\n{\n j[\"title\"] = m._title;\n j[\"type\"] = m._type;\n j[\"description\"] = m._description;\n j[\"url\"] = m._url;\n j[\"timestamp\"] = m._timestamp;\n j[\"color\"] = m._color;\n j[\"footer\"] = m._footer;\n j[\"image\"] = m._image;\n j[\"thumbnail\"] = m._thumbnail;\n j[\"video\"] = m._video;\n j[\"provider\"] = m._provider;\n for (const auto & _field : m._fields)\n j[\"fields\"].push_back(_field);\n}\n\/\/\/ \\endcond\n\n}\n\n}\n\n}\n<|endoftext|>"} {"text":"#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace baka {\n namespace detail {\n template\n ffi_type* type();\n\n template<>\n ffi_type* type() {\n return &ffi_type_sint;\n }\n }\n\n template\n class bound_function;\n\n template\n class bound_function {\n using fptr_t = Ret(*)(Args...);\n\n public:\n template\n explicit bound_function(F&& function_)\n : function(std::forward(function_)) {\n return_type = detail::type();\n argument_types = { detail::type()... };\n ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argument_types.size(), return_type, argument_types.data());\n\n closure = ffi_closure_alloc(sizeof(ffi_closure), &thunk);\n ffi_prep_closure_loc(static_cast(closure), &cif, &call, this, reinterpret_cast(thunk));\n }\n\n operator fptr_t() const {\n return reinterpret_cast(thunk);\n }\n\n private:\n static void call(ffi_cif*, void* ret, void** args, void* self_void) {\n auto self = static_cast(self_void);\n self->template call_<0>(static_cast(ret), args);\n }\n\n template\n typename std::enable_if::type\n call_(Ret* ret, void** args, CallArgs&&... call_args) {\n call_(ret, args, std::forward(call_args)..., *static_cast*>(args[N]));\n }\n\n template\n typename std::enable_if::type\n call_(Ret* ret, void**, CallArgs&&... call_args) {\n *ret = function(std::forward(call_args)...);\n }\n\n std::function function;\n ffi_cif cif;\n ffi_type* return_type;\n std::vector argument_types;\n void* closure;\n void* thunk;\n };\n}\nFree closure when bound_function is destroyed#pragma once\n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n#include \n\nnamespace baka {\n namespace detail {\n template\n ffi_type* type();\n\n template<>\n ffi_type* type() {\n return &::ffi_type_sint;\n }\n }\n\n template\n class bound_function;\n\n template\n class bound_function {\n using fptr_t = Ret(*)(Args...);\n\n public:\n template\n explicit bound_function(F&& function_)\n : function(std::forward(function_))\n , closure(nullptr, &::ffi_closure_free) {\n return_type = detail::type();\n argument_types = { detail::type()... };\n ::ffi_prep_cif(&cif, FFI_DEFAULT_ABI, argument_types.size(), return_type, argument_types.data());\n\n closure.reset(static_cast<::ffi_closure*>(::ffi_closure_alloc(sizeof(::ffi_closure), &thunk)));\n ::ffi_prep_closure_loc(closure.get(), &cif, &call, this, reinterpret_cast(thunk));\n }\n\n operator fptr_t() const {\n return reinterpret_cast(thunk);\n }\n\n private:\n static void call(ffi_cif*, void* ret, void** args, void* self_void) {\n auto self = static_cast(self_void);\n self->template call_<0>(static_cast(ret), args);\n }\n\n template\n typename std::enable_if::type\n call_(Ret* ret, void** args, CallArgs&&... call_args) {\n call_(ret, args, std::forward(call_args)..., *static_cast*>(args[N]));\n }\n\n template\n typename std::enable_if::type\n call_(Ret* ret, void**, CallArgs&&... call_args) {\n *ret = function(std::forward(call_args)...);\n }\n\n std::function function;\n ::ffi_cif cif;\n ::ffi_type* return_type;\n std::vector<::ffi_type*> argument_types;\n std::unique_ptr<::ffi_closure, decltype(&::ffi_closure_free)> closure;\n void* thunk; \/\/ freed by ::ffi_closure_free\n };\n}\n<|endoftext|>"} {"text":"the variable is only available on linux<|endoftext|>"} {"text":"\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager.h\"\n\n#include \"base\/logging.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility.h\"\n#include \"content\/common\/accessibility_messages.h\"\n\nnamespace content {\n\nBrowserAccessibility* BrowserAccessibilityFactory::Create() {\n return BrowserAccessibility::Create();\n}\n\n#if !defined(OS_MACOSX) && \\\n !defined(OS_WIN) && \\\n !defined(TOOLKIT_GTK) && \\\n !defined(OS_ANDROID) \\\n\/\/ We have subclassess of BrowserAccessibilityManager on Mac, Linux\/GTK,\n\/\/ and Win. For any other platform, instantiate the base class.\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManager(src, delegate, factory);\n}\n#endif\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : delegate_(delegate),\n factory_(factory),\n root_(NULL),\n focus_(NULL),\n osk_state_(OSK_ALLOWED) {\n}\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : delegate_(delegate),\n factory_(factory),\n root_(NULL),\n focus_(NULL),\n osk_state_(OSK_ALLOWED) {\n Initialize(src);\n}\n\nBrowserAccessibilityManager::~BrowserAccessibilityManager() {\n if (root_)\n root_->Destroy();\n}\n\nvoid BrowserAccessibilityManager::Initialize(const AccessibilityNodeData src) {\n std::vector nodes;\n nodes.push_back(src);\n if (!UpdateNodes(nodes))\n return;\n if (!focus_)\n SetFocus(root_, false);\n}\n\n\/\/ static\nAccessibilityNodeData BrowserAccessibilityManager::GetEmptyDocument() {\n AccessibilityNodeData empty_document;\n empty_document.id = 0;\n empty_document.role = blink::WebAXRoleRootWebArea;\n return empty_document;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetRoot() {\n return root_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(\n int32 renderer_id) {\n base::hash_map::iterator iter =\n renderer_id_map_.find(renderer_id);\n if (iter != renderer_id_map_.end())\n return iter->second;\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::GotFocus(bool touch_event_context) {\n if (!touch_event_context)\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED;\n\n if (!focus_)\n return;\n\n NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_);\n}\n\nvoid BrowserAccessibilityManager::WasHidden() {\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_HIDDEN;\n}\n\nvoid BrowserAccessibilityManager::GotMouseDown() {\n osk_state_ = OSK_ALLOWED_WITHIN_FOCUSED_OBJECT;\n NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_);\n}\n\nbool BrowserAccessibilityManager::IsOSKAllowed(const gfx::Rect& bounds) {\n if (!delegate_ || !delegate_->HasFocus())\n return false;\n\n gfx::Point touch_point = delegate_->GetLastTouchEventLocation();\n return bounds.Contains(touch_point);\n}\n\nbool BrowserAccessibilityManager::UseRootScrollOffsetsWhenComputingBounds() {\n return true;\n}\n\nvoid BrowserAccessibilityManager::RemoveNode(BrowserAccessibility* node) {\n if (node == focus_)\n SetFocus(root_, false);\n int renderer_id = node->renderer_id();\n renderer_id_map_.erase(renderer_id);\n}\n\nvoid BrowserAccessibilityManager::OnAccessibilityEvents(\n const std::vector& params) {\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_EventParams& param = params[index];\n\n \/\/ Update nodes that changed.\n if (!UpdateNodes(param.nodes))\n return;\n\n \/\/ Find the node corresponding to the id that's the target of the\n \/\/ event (which may not be the root of the update tree).\n BrowserAccessibility* node = GetFromRendererID(param.id);\n if (!node)\n continue;\n\n blink::WebAXEvent event_type = param.event_type;\n if (event_type == blink::WebAXEventFocus ||\n event_type == blink::WebAXEventBlur) {\n SetFocus(node, false);\n\n if (osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_HIDDEN &&\n osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED)\n osk_state_ = OSK_ALLOWED;\n\n \/\/ Don't send a native focus event if the window itself doesn't\n \/\/ have focus.\n if (delegate_ && !delegate_->HasFocus())\n continue;\n }\n\n \/\/ Send the event event to the operating system.\n NotifyAccessibilityEvent(event_type, node);\n\n \/\/ Set initial focus when a page is loaded.\n if (event_type == blink::WebAXEventLoadComplete) {\n if (!focus_)\n SetFocus(root_, false);\n if (!delegate_ || delegate_->HasFocus())\n NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_);\n }\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFocus(\n BrowserAccessibility* root) {\n if (focus_ && (!root || focus_->IsDescendantOf(root)))\n return focus_;\n\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::SetFocus(\n BrowserAccessibility* node, bool notify) {\n if (focus_ != node)\n focus_ = node;\n\n if (notify && node && delegate_)\n delegate_->SetAccessibilityFocus(node->renderer_id());\n}\n\nvoid BrowserAccessibilityManager::SetRoot(BrowserAccessibility* node) {\n root_ = node;\n NotifyRootChanged();\n}\n\nvoid BrowserAccessibilityManager::DoDefaultAction(\n const BrowserAccessibility& node) {\n if (delegate_)\n delegate_->AccessibilityDoDefaultAction(node.renderer_id());\n}\n\nvoid BrowserAccessibilityManager::ScrollToMakeVisible(\n const BrowserAccessibility& node, gfx::Rect subfocus) {\n if (delegate_) {\n delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);\n }\n}\n\nvoid BrowserAccessibilityManager::ScrollToPoint(\n const BrowserAccessibility& node, gfx::Point point) {\n if (delegate_) {\n delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);\n }\n}\n\nvoid BrowserAccessibilityManager::SetTextSelection(\n const BrowserAccessibility& node, int start_offset, int end_offset) {\n if (delegate_) {\n delegate_->AccessibilitySetTextSelection(\n node.renderer_id(), start_offset, end_offset);\n }\n}\n\ngfx::Rect BrowserAccessibilityManager::GetViewBounds() {\n if (delegate_)\n return delegate_->GetViewBounds();\n return gfx::Rect();\n}\n\nvoid BrowserAccessibilityManager::UpdateNodesForTesting(\n const AccessibilityNodeData& node1,\n const AccessibilityNodeData& node2 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node3 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node4 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node5 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node6 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node7 \/* = AccessibilityNodeData() *\/) {\n std::vector nodes;\n nodes.push_back(node1);\n if (node2.id != AccessibilityNodeData().id)\n nodes.push_back(node2);\n if (node3.id != AccessibilityNodeData().id)\n nodes.push_back(node3);\n if (node4.id != AccessibilityNodeData().id)\n nodes.push_back(node4);\n if (node5.id != AccessibilityNodeData().id)\n nodes.push_back(node5);\n if (node6.id != AccessibilityNodeData().id)\n nodes.push_back(node6);\n if (node7.id != AccessibilityNodeData().id)\n nodes.push_back(node7);\n UpdateNodes(nodes);\n}\n\nbool BrowserAccessibilityManager::UpdateNodes(\n const std::vector& nodes) {\n bool success = true;\n\n \/\/ First, update all of the nodes in the tree.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n if (!UpdateNode(nodes[i]))\n success = false;\n }\n\n \/\/ In a second pass, call PostInitialize on each one - this must\n \/\/ be called after all of each node's children are initialized too.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n \/\/ Note: it's not a bug for nodes[i].id to not be found in the tree.\n \/\/ Consider this example:\n \/\/ Before:\n \/\/ A\n \/\/ B\n \/\/ C\n \/\/ D\n \/\/ E\n \/\/ F\n \/\/ After:\n \/\/ A\n \/\/ B\n \/\/ C\n \/\/ F\n \/\/ D\n \/\/ In this example, F is being reparented. The renderer scans the tree\n \/\/ in order. If can't update \"C\" to add \"F\" as a child, when \"F\" is still\n \/\/ a child of \"E\". So it first updates \"E\", to remove \"F\" as a child.\n \/\/ Later, it ends up deleting \"E\". So when we get here, \"E\" was updated as\n \/\/ part of this sequence but it no longer exists in the final tree, so\n \/\/ there's nothing to postinitialize.\n BrowserAccessibility* instance = GetFromRendererID(nodes[i].id);\n if (instance)\n instance->PostInitialize();\n }\n\n if (!success) {\n \/\/ A bad accessibility tree could lead to memory corruption.\n \/\/ Ask the delegate to crash the renderer, or if not available,\n \/\/ crash the browser.\n if (delegate_)\n delegate_->FatalAccessibilityTreeError();\n else\n CHECK(false);\n }\n\n return success;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::CreateNode(\n BrowserAccessibility* parent,\n int32 renderer_id,\n int32 index_in_parent) {\n BrowserAccessibility* node = factory_->Create();\n node->InitializeTreeStructure(\n this, parent, renderer_id, index_in_parent);\n AddNodeToMap(node);\n return node;\n}\n\nvoid BrowserAccessibilityManager::AddNodeToMap(BrowserAccessibility* node) {\n renderer_id_map_[node->renderer_id()] = node;\n}\n\nbool BrowserAccessibilityManager::UpdateNode(const AccessibilityNodeData& src) {\n \/\/ This method updates one node in the tree based on serialized data\n \/\/ received from the renderer.\n\n \/\/ Create a set of child ids in |src| for fast lookup. If a duplicate id is\n \/\/ found, exit now with a fatal error before changing anything else.\n std::set new_child_ids;\n for (size_t i = 0; i < src.child_ids.size(); ++i) {\n if (new_child_ids.find(src.child_ids[i]) != new_child_ids.end())\n return false;\n new_child_ids.insert(src.child_ids[i]);\n }\n\n \/\/ Look up the node by id. If it's not found, then either the root\n \/\/ of the tree is being swapped, or we're out of sync with the renderer\n \/\/ and this is a serious error.\n BrowserAccessibility* instance = GetFromRendererID(src.id);\n if (!instance) {\n if (src.role != blink::WebAXRoleRootWebArea)\n return false;\n instance = CreateNode(NULL, src.id, 0);\n }\n\n \/\/ TODO(dmazzoni): avoid a linear scan here.\n for (size_t i = 0; i < src.bool_attributes.size(); i++) {\n if (src.bool_attributes[i].first ==\n AccessibilityNodeData::ATTR_UPDATE_LOCATION_ONLY) {\n instance->SetLocation(src.location);\n return true;\n }\n }\n\n \/\/ Update all of the node-specific data, like its role, state, name, etc.\n instance->InitializeData(src);\n\n \/\/\n \/\/ Update the children in three steps:\n \/\/\n \/\/ 1. Iterate over the old children and delete nodes that are no longer\n \/\/ in the tree.\n \/\/ 2. Build up a vector of new children, reusing children that haven't\n \/\/ changed (but may have been reordered) and adding new empty\n \/\/ objects for new children.\n \/\/ 3. Swap in the new children vector for the old one.\n\n \/\/ Delete any previous children of this instance that are no longer\n \/\/ children first. We make a deletion-only pass first to prevent a\n \/\/ node that's being reparented from being the child of both its old\n \/\/ parent and new parent, which could lead to a double-free.\n \/\/ If a node is reparented, the renderer will always send us a fresh\n \/\/ copy of the node.\n const std::vector& old_children = instance->children();\n for (size_t i = 0; i < old_children.size(); ++i) {\n int old_id = old_children[i]->renderer_id();\n if (new_child_ids.find(old_id) == new_child_ids.end())\n old_children[i]->Destroy();\n }\n\n \/\/ Now build a vector of new children, reusing objects that were already\n \/\/ children of this node before.\n std::vector new_children;\n bool success = true;\n for (size_t i = 0; i < src.child_ids.size(); i++) {\n int32 child_renderer_id = src.child_ids[i];\n int32 index_in_parent = static_cast(i);\n BrowserAccessibility* child = GetFromRendererID(child_renderer_id);\n if (child) {\n if (child->parent() != instance) {\n \/\/ This is a serious error - nodes should never be reparented.\n \/\/ If this case occurs, continue so this node isn't left in an\n \/\/ inconsistent state, but return failure at the end.\n success = false;\n continue;\n }\n child->UpdateParent(instance, index_in_parent);\n } else {\n child = CreateNode(instance, child_renderer_id, index_in_parent);\n }\n new_children.push_back(child);\n }\n\n \/\/ Finally, swap in the new children vector for the old.\n instance->SwapChildren(new_children);\n\n \/\/ Handle the case where this node is the new root of the tree.\n if (src.role == blink::WebAXRoleRootWebArea &&\n (!root_ || root_->renderer_id() != src.id)) {\n if (root_)\n root_->Destroy();\n if (focus_ == root_)\n SetFocus(instance, false);\n SetRoot(instance);\n }\n\n \/\/ Keep track of what node is focused.\n if (src.role != blink::WebAXRoleRootWebArea &&\n src.role != blink::WebAXRoleWebArea &&\n (src.state >> blink::WebAXStateFocused & 1)) {\n SetFocus(instance, false);\n }\n return success;\n}\n\n} \/\/ namespace content\nUpdate accessibility tree before sending events.\/\/ Copyright (c) 2012 The Chromium Authors. All rights reserved.\n\/\/ Use of this source code is governed by a BSD-style license that can be\n\/\/ found in the LICENSE file.\n\n#include \"content\/browser\/accessibility\/browser_accessibility_manager.h\"\n\n#include \"base\/logging.h\"\n#include \"content\/browser\/accessibility\/browser_accessibility.h\"\n#include \"content\/common\/accessibility_messages.h\"\n\nnamespace content {\n\nBrowserAccessibility* BrowserAccessibilityFactory::Create() {\n return BrowserAccessibility::Create();\n}\n\n#if !defined(OS_MACOSX) && \\\n !defined(OS_WIN) && \\\n !defined(TOOLKIT_GTK) && \\\n !defined(OS_ANDROID) \\\n\/\/ We have subclassess of BrowserAccessibilityManager on Mac, Linux\/GTK,\n\/\/ and Win. For any other platform, instantiate the base class.\n\/\/ static\nBrowserAccessibilityManager* BrowserAccessibilityManager::Create(\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory) {\n return new BrowserAccessibilityManager(src, delegate, factory);\n}\n#endif\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : delegate_(delegate),\n factory_(factory),\n root_(NULL),\n focus_(NULL),\n osk_state_(OSK_ALLOWED) {\n}\n\nBrowserAccessibilityManager::BrowserAccessibilityManager(\n const AccessibilityNodeData& src,\n BrowserAccessibilityDelegate* delegate,\n BrowserAccessibilityFactory* factory)\n : delegate_(delegate),\n factory_(factory),\n root_(NULL),\n focus_(NULL),\n osk_state_(OSK_ALLOWED) {\n Initialize(src);\n}\n\nBrowserAccessibilityManager::~BrowserAccessibilityManager() {\n if (root_)\n root_->Destroy();\n}\n\nvoid BrowserAccessibilityManager::Initialize(const AccessibilityNodeData src) {\n std::vector nodes;\n nodes.push_back(src);\n if (!UpdateNodes(nodes))\n return;\n if (!focus_)\n SetFocus(root_, false);\n}\n\n\/\/ static\nAccessibilityNodeData BrowserAccessibilityManager::GetEmptyDocument() {\n AccessibilityNodeData empty_document;\n empty_document.id = 0;\n empty_document.role = blink::WebAXRoleRootWebArea;\n return empty_document;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetRoot() {\n return root_;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFromRendererID(\n int32 renderer_id) {\n base::hash_map::iterator iter =\n renderer_id_map_.find(renderer_id);\n if (iter != renderer_id_map_.end())\n return iter->second;\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::GotFocus(bool touch_event_context) {\n if (!touch_event_context)\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED;\n\n if (!focus_)\n return;\n\n NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_);\n}\n\nvoid BrowserAccessibilityManager::WasHidden() {\n osk_state_ = OSK_DISALLOWED_BECAUSE_TAB_HIDDEN;\n}\n\nvoid BrowserAccessibilityManager::GotMouseDown() {\n osk_state_ = OSK_ALLOWED_WITHIN_FOCUSED_OBJECT;\n NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_);\n}\n\nbool BrowserAccessibilityManager::IsOSKAllowed(const gfx::Rect& bounds) {\n if (!delegate_ || !delegate_->HasFocus())\n return false;\n\n gfx::Point touch_point = delegate_->GetLastTouchEventLocation();\n return bounds.Contains(touch_point);\n}\n\nbool BrowserAccessibilityManager::UseRootScrollOffsetsWhenComputingBounds() {\n return true;\n}\n\nvoid BrowserAccessibilityManager::RemoveNode(BrowserAccessibility* node) {\n if (node == focus_)\n SetFocus(root_, false);\n int renderer_id = node->renderer_id();\n renderer_id_map_.erase(renderer_id);\n}\n\nvoid BrowserAccessibilityManager::OnAccessibilityEvents(\n const std::vector& params) {\n bool should_send_initial_focus = false;\n\n \/\/ Process all changes to the accessibility tree first.\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_EventParams& param = params[index];\n if (!UpdateNodes(param.nodes))\n return;\n\n \/\/ Set initial focus when a page is loaded.\n blink::WebAXEvent event_type = param.event_type;\n if (event_type == blink::WebAXEventLoadComplete) {\n if (!focus_) {\n SetFocus(root_, false);\n should_send_initial_focus = true;\n }\n }\n }\n\n if (should_send_initial_focus &&\n (!delegate_ || delegate_->HasFocus())) {\n NotifyAccessibilityEvent(blink::WebAXEventFocus, focus_);\n }\n\n \/\/ Now iterate over the events again and fire the events.\n for (uint32 index = 0; index < params.size(); index++) {\n const AccessibilityHostMsg_EventParams& param = params[index];\n\n \/\/ Find the node corresponding to the id that's the target of the\n \/\/ event (which may not be the root of the update tree).\n BrowserAccessibility* node = GetFromRendererID(param.id);\n if (!node)\n continue;\n\n blink::WebAXEvent event_type = param.event_type;\n if (event_type == blink::WebAXEventFocus ||\n event_type == blink::WebAXEventBlur) {\n SetFocus(node, false);\n\n if (osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_HIDDEN &&\n osk_state_ != OSK_DISALLOWED_BECAUSE_TAB_JUST_APPEARED)\n osk_state_ = OSK_ALLOWED;\n\n \/\/ Don't send a native focus event if the window itself doesn't\n \/\/ have focus.\n if (delegate_ && !delegate_->HasFocus())\n continue;\n }\n\n \/\/ Send the event event to the operating system.\n NotifyAccessibilityEvent(event_type, node);\n }\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::GetFocus(\n BrowserAccessibility* root) {\n if (focus_ && (!root || focus_->IsDescendantOf(root)))\n return focus_;\n\n return NULL;\n}\n\nvoid BrowserAccessibilityManager::SetFocus(\n BrowserAccessibility* node, bool notify) {\n if (focus_ != node)\n focus_ = node;\n\n if (notify && node && delegate_)\n delegate_->SetAccessibilityFocus(node->renderer_id());\n}\n\nvoid BrowserAccessibilityManager::SetRoot(BrowserAccessibility* node) {\n root_ = node;\n NotifyRootChanged();\n}\n\nvoid BrowserAccessibilityManager::DoDefaultAction(\n const BrowserAccessibility& node) {\n if (delegate_)\n delegate_->AccessibilityDoDefaultAction(node.renderer_id());\n}\n\nvoid BrowserAccessibilityManager::ScrollToMakeVisible(\n const BrowserAccessibility& node, gfx::Rect subfocus) {\n if (delegate_) {\n delegate_->AccessibilityScrollToMakeVisible(node.renderer_id(), subfocus);\n }\n}\n\nvoid BrowserAccessibilityManager::ScrollToPoint(\n const BrowserAccessibility& node, gfx::Point point) {\n if (delegate_) {\n delegate_->AccessibilityScrollToPoint(node.renderer_id(), point);\n }\n}\n\nvoid BrowserAccessibilityManager::SetTextSelection(\n const BrowserAccessibility& node, int start_offset, int end_offset) {\n if (delegate_) {\n delegate_->AccessibilitySetTextSelection(\n node.renderer_id(), start_offset, end_offset);\n }\n}\n\ngfx::Rect BrowserAccessibilityManager::GetViewBounds() {\n if (delegate_)\n return delegate_->GetViewBounds();\n return gfx::Rect();\n}\n\nvoid BrowserAccessibilityManager::UpdateNodesForTesting(\n const AccessibilityNodeData& node1,\n const AccessibilityNodeData& node2 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node3 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node4 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node5 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node6 \/* = AccessibilityNodeData() *\/,\n const AccessibilityNodeData& node7 \/* = AccessibilityNodeData() *\/) {\n std::vector nodes;\n nodes.push_back(node1);\n if (node2.id != AccessibilityNodeData().id)\n nodes.push_back(node2);\n if (node3.id != AccessibilityNodeData().id)\n nodes.push_back(node3);\n if (node4.id != AccessibilityNodeData().id)\n nodes.push_back(node4);\n if (node5.id != AccessibilityNodeData().id)\n nodes.push_back(node5);\n if (node6.id != AccessibilityNodeData().id)\n nodes.push_back(node6);\n if (node7.id != AccessibilityNodeData().id)\n nodes.push_back(node7);\n UpdateNodes(nodes);\n}\n\nbool BrowserAccessibilityManager::UpdateNodes(\n const std::vector& nodes) {\n bool success = true;\n\n \/\/ First, update all of the nodes in the tree.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n if (!UpdateNode(nodes[i]))\n success = false;\n }\n\n \/\/ In a second pass, call PostInitialize on each one - this must\n \/\/ be called after all of each node's children are initialized too.\n for (size_t i = 0; i < nodes.size() && success; i++) {\n \/\/ Note: it's not a bug for nodes[i].id to not be found in the tree.\n \/\/ Consider this example:\n \/\/ Before:\n \/\/ A\n \/\/ B\n \/\/ C\n \/\/ D\n \/\/ E\n \/\/ F\n \/\/ After:\n \/\/ A\n \/\/ B\n \/\/ C\n \/\/ F\n \/\/ D\n \/\/ In this example, F is being reparented. The renderer scans the tree\n \/\/ in order. If can't update \"C\" to add \"F\" as a child, when \"F\" is still\n \/\/ a child of \"E\". So it first updates \"E\", to remove \"F\" as a child.\n \/\/ Later, it ends up deleting \"E\". So when we get here, \"E\" was updated as\n \/\/ part of this sequence but it no longer exists in the final tree, so\n \/\/ there's nothing to postinitialize.\n BrowserAccessibility* instance = GetFromRendererID(nodes[i].id);\n if (instance)\n instance->PostInitialize();\n }\n\n if (!success) {\n \/\/ A bad accessibility tree could lead to memory corruption.\n \/\/ Ask the delegate to crash the renderer, or if not available,\n \/\/ crash the browser.\n if (delegate_)\n delegate_->FatalAccessibilityTreeError();\n else\n CHECK(false);\n }\n\n return success;\n}\n\nBrowserAccessibility* BrowserAccessibilityManager::CreateNode(\n BrowserAccessibility* parent,\n int32 renderer_id,\n int32 index_in_parent) {\n BrowserAccessibility* node = factory_->Create();\n node->InitializeTreeStructure(\n this, parent, renderer_id, index_in_parent);\n AddNodeToMap(node);\n return node;\n}\n\nvoid BrowserAccessibilityManager::AddNodeToMap(BrowserAccessibility* node) {\n renderer_id_map_[node->renderer_id()] = node;\n}\n\nbool BrowserAccessibilityManager::UpdateNode(const AccessibilityNodeData& src) {\n \/\/ This method updates one node in the tree based on serialized data\n \/\/ received from the renderer.\n\n \/\/ Create a set of child ids in |src| for fast lookup. If a duplicate id is\n \/\/ found, exit now with a fatal error before changing anything else.\n std::set new_child_ids;\n for (size_t i = 0; i < src.child_ids.size(); ++i) {\n if (new_child_ids.find(src.child_ids[i]) != new_child_ids.end())\n return false;\n new_child_ids.insert(src.child_ids[i]);\n }\n\n \/\/ Look up the node by id. If it's not found, then either the root\n \/\/ of the tree is being swapped, or we're out of sync with the renderer\n \/\/ and this is a serious error.\n BrowserAccessibility* instance = GetFromRendererID(src.id);\n if (!instance) {\n if (src.role != blink::WebAXRoleRootWebArea)\n return false;\n instance = CreateNode(NULL, src.id, 0);\n }\n\n \/\/ TODO(dmazzoni): avoid a linear scan here.\n for (size_t i = 0; i < src.bool_attributes.size(); i++) {\n if (src.bool_attributes[i].first ==\n AccessibilityNodeData::ATTR_UPDATE_LOCATION_ONLY) {\n instance->SetLocation(src.location);\n return true;\n }\n }\n\n \/\/ Update all of the node-specific data, like its role, state, name, etc.\n instance->InitializeData(src);\n\n \/\/\n \/\/ Update the children in three steps:\n \/\/\n \/\/ 1. Iterate over the old children and delete nodes that are no longer\n \/\/ in the tree.\n \/\/ 2. Build up a vector of new children, reusing children that haven't\n \/\/ changed (but may have been reordered) and adding new empty\n \/\/ objects for new children.\n \/\/ 3. Swap in the new children vector for the old one.\n\n \/\/ Delete any previous children of this instance that are no longer\n \/\/ children first. We make a deletion-only pass first to prevent a\n \/\/ node that's being reparented from being the child of both its old\n \/\/ parent and new parent, which could lead to a double-free.\n \/\/ If a node is reparented, the renderer will always send us a fresh\n \/\/ copy of the node.\n const std::vector& old_children = instance->children();\n for (size_t i = 0; i < old_children.size(); ++i) {\n int old_id = old_children[i]->renderer_id();\n if (new_child_ids.find(old_id) == new_child_ids.end())\n old_children[i]->Destroy();\n }\n\n \/\/ Now build a vector of new children, reusing objects that were already\n \/\/ children of this node before.\n std::vector new_children;\n bool success = true;\n for (size_t i = 0; i < src.child_ids.size(); i++) {\n int32 child_renderer_id = src.child_ids[i];\n int32 index_in_parent = static_cast(i);\n BrowserAccessibility* child = GetFromRendererID(child_renderer_id);\n if (child) {\n if (child->parent() != instance) {\n \/\/ This is a serious error - nodes should never be reparented.\n \/\/ If this case occurs, continue so this node isn't left in an\n \/\/ inconsistent state, but return failure at the end.\n success = false;\n continue;\n }\n child->UpdateParent(instance, index_in_parent);\n } else {\n child = CreateNode(instance, child_renderer_id, index_in_parent);\n }\n new_children.push_back(child);\n }\n\n \/\/ Finally, swap in the new children vector for the old.\n instance->SwapChildren(new_children);\n\n \/\/ Handle the case where this node is the new root of the tree.\n if (src.role == blink::WebAXRoleRootWebArea &&\n (!root_ || root_->renderer_id() != src.id)) {\n if (root_)\n root_->Destroy();\n if (focus_ == root_)\n SetFocus(instance, false);\n SetRoot(instance);\n }\n\n \/\/ Keep track of what node is focused.\n if (src.role != blink::WebAXRoleRootWebArea &&\n src.role != blink::WebAXRoleWebArea &&\n (src.state >> blink::WebAXStateFocused & 1)) {\n SetFocus(instance, false);\n }\n return success;\n}\n\n} \/\/ namespace content\n<|endoftext|>"} {"text":"\/\/=======================================================================\n\/\/ Copyright (c) 2015 Baptiste Wicht\n\/\/ Distributed under the terms of the MIT License.\n\/\/ (See accompanying file LICENSE or copy at\n\/\/ http:\/\/opensource.org\/licenses\/MIT)\n\/\/=======================================================================\n\n#ifndef CPM_BOOTSTRAP_THEME_HPP\n#define CPM_BOOTSTRAP_THEME_HPP\n\n#include \"cpm\/io.hpp\"\n#include \"cpm\/data.hpp\"\n\nnamespace cpm {\n\nstruct bootstrap_theme {\n const reports_data& data;\n cxxopts::Options& options;\n std::ostream& stream;\n std::string current_compiler;\n std::string current_configuration;\n\n bootstrap_theme(const reports_data& data, cxxopts::Options& options, std::ostream& stream, std::string compiler, std::string configuration) \n : data(data), options(options), stream(stream), current_compiler(std::move(compiler)), current_configuration(std::move(configuration)) {}\n\n void include(){\n stream << \"